text
stringlengths
2
1.04M
meta
dict
.class Landroid/mtp/MtpDatabase$MtpDatabaseThread; .super Ljava/lang/Thread; .source "MtpDatabase.java" # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Landroid/mtp/MtpDatabase; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x2 name = "MtpDatabaseThread" .end annotation # static fields .field private static final UPDATE_DB:I = 0x1 # instance fields .field private mContext:Landroid/content/Context; .field public mHandler:Landroid/os/Handler; .field final synthetic this$0:Landroid/mtp/MtpDatabase; # direct methods .method public constructor <init>(Landroid/mtp/MtpDatabase;Landroid/content/Context;)V .locals 1 .parameter .parameter "context" .prologue const/4 v0, 0x0 .line 1335 iput-object p1, p0, Landroid/mtp/MtpDatabase$MtpDatabaseThread;->this$0:Landroid/mtp/MtpDatabase; .line 1336 invoke-direct {p0}, Ljava/lang/Thread;-><init>()V .line 1332 iput-object v0, p0, Landroid/mtp/MtpDatabase$MtpDatabaseThread;->mContext:Landroid/content/Context; .line 1333 iput-object v0, p0, Landroid/mtp/MtpDatabase$MtpDatabaseThread;->mHandler:Landroid/os/Handler; .line 1337 iput-object p2, p0, Landroid/mtp/MtpDatabase$MtpDatabaseThread;->mContext:Landroid/content/Context; .line 1338 return-void .end method .method static synthetic access$000(Landroid/mtp/MtpDatabase$MtpDatabaseThread;)Landroid/content/Context; .locals 1 .parameter "x0" .prologue .line 1330 iget-object v0, p0, Landroid/mtp/MtpDatabase$MtpDatabaseThread;->mContext:Landroid/content/Context; return-object v0 .end method # virtual methods .method public run()V .locals 1 .prologue .line 1341 invoke-static {}, Landroid/os/Looper;->prepare()V .line 1342 new-instance v0, Landroid/mtp/MtpDatabase$MtpDatabaseThread$1; invoke-direct {v0, p0}, Landroid/mtp/MtpDatabase$MtpDatabaseThread$1;-><init>(Landroid/mtp/MtpDatabase$MtpDatabaseThread;)V iput-object v0, p0, Landroid/mtp/MtpDatabase$MtpDatabaseThread;->mHandler:Landroid/os/Handler; .line 1359 invoke-static {}, Landroid/os/Looper;->loop()V .line 1360 return-void .end method
{ "content_hash": "81569c6426e6860b5f84cd21e1896783", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 127, "avg_line_length": 25.146067415730336, "alnum_prop": 0.7359249329758714, "repo_name": "baidurom/devices-g520", "id": "e2ca690ce06e061978899fdffa99e9df539148f7", "size": "2238", "binary": false, "copies": "2", "ref": "refs/heads/coron-4.1", "path": "framework.jar.out/smali/android/mtp/MtpDatabase$MtpDatabaseThread.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "12575" }, { "name": "Python", "bytes": "1261" }, { "name": "Shell", "bytes": "2159" } ], "symlink_target": "" }
package org.apache.hadoop.mapreduce.v2.app.job.impl; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.JobContext; import org.apache.hadoop.mapred.MapReduceChildJVM; import org.apache.hadoop.mapred.ShuffleHandler; import org.apache.hadoop.mapred.Task; import org.apache.hadoop.mapred.TaskAttemptContextImpl; import org.apache.hadoop.mapred.WrappedJvmID; import org.apache.hadoop.mapred.WrappedProgressSplitsBlock; import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.Counters; import org.apache.hadoop.mapreduce.JobCounter; import org.apache.hadoop.mapreduce.MRJobConfig; import org.apache.hadoop.mapreduce.OutputCommitter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.TaskCounter; import org.apache.hadoop.mapreduce.TypeConverter; import org.apache.hadoop.mapreduce.jobhistory.JobHistoryEvent; import org.apache.hadoop.mapreduce.jobhistory.JobHistoryParser.TaskAttemptInfo; import org.apache.hadoop.mapreduce.jobhistory.MapAttemptFinishedEvent; import org.apache.hadoop.mapreduce.jobhistory.ReduceAttemptFinishedEvent; import org.apache.hadoop.mapreduce.jobhistory.TaskAttemptStartedEvent; import org.apache.hadoop.mapreduce.jobhistory.TaskAttemptUnsuccessfulCompletionEvent; import org.apache.hadoop.mapreduce.security.TokenCache; import org.apache.hadoop.mapreduce.security.token.JobTokenIdentifier; import org.apache.hadoop.mapreduce.v2.api.records.Avataar; import org.apache.hadoop.mapreduce.v2.api.records.Locality; import org.apache.hadoop.mapreduce.v2.api.records.Phase; import org.apache.hadoop.mapreduce.v2.api.records.TaskAttemptId; import org.apache.hadoop.mapreduce.v2.api.records.TaskAttemptReport; import org.apache.hadoop.mapreduce.v2.api.records.TaskAttemptState; import org.apache.hadoop.mapreduce.v2.api.records.TaskId; import org.apache.hadoop.mapreduce.v2.api.records.TaskType; import org.apache.hadoop.mapreduce.v2.app.AppContext; import org.apache.hadoop.mapreduce.v2.app.TaskAttemptListener; import org.apache.hadoop.mapreduce.v2.app.commit.CommitterTaskAbortEvent; import org.apache.hadoop.mapreduce.v2.app.job.TaskAttemptStateInternal; import org.apache.hadoop.mapreduce.v2.app.job.event.JobCounterUpdateEvent; import org.apache.hadoop.mapreduce.v2.app.job.event.JobDiagnosticsUpdateEvent; import org.apache.hadoop.mapreduce.v2.app.job.event.JobEvent; import org.apache.hadoop.mapreduce.v2.app.job.event.JobEventType; import org.apache.hadoop.mapreduce.v2.app.job.event.JobTaskAttemptFetchFailureEvent; import org.apache.hadoop.mapreduce.v2.app.job.event.TaskAttemptContainerAssignedEvent; import org.apache.hadoop.mapreduce.v2.app.job.event.TaskAttemptContainerLaunchedEvent; import org.apache.hadoop.mapreduce.v2.app.job.event.TaskAttemptDiagnosticsUpdateEvent; import org.apache.hadoop.mapreduce.v2.app.job.event.TaskAttemptEvent; import org.apache.hadoop.mapreduce.v2.app.job.event.TaskAttemptEventType; import org.apache.hadoop.mapreduce.v2.app.job.event.TaskAttemptKillEvent; import org.apache.hadoop.mapreduce.v2.app.job.event.TaskAttemptRecoverEvent; import org.apache.hadoop.mapreduce.v2.app.job.event.TaskAttemptStatusUpdateEvent; import org.apache.hadoop.mapreduce.v2.app.job.event.TaskAttemptStatusUpdateEvent.TaskAttemptStatus; import org.apache.hadoop.mapreduce.v2.app.job.event.TaskEventType; import org.apache.hadoop.mapreduce.v2.app.job.event.TaskTAttemptEvent; import org.apache.hadoop.mapreduce.v2.app.launcher.ContainerLauncher; import org.apache.hadoop.mapreduce.v2.app.launcher.ContainerLauncherEvent; import org.apache.hadoop.mapreduce.v2.app.launcher.ContainerRemoteLaunchEvent; import org.apache.hadoop.mapreduce.v2.app.rm.ContainerAllocator; import org.apache.hadoop.mapreduce.v2.app.rm.ContainerAllocatorEvent; import org.apache.hadoop.mapreduce.v2.app.rm.ContainerRequestEvent; import org.apache.hadoop.mapreduce.v2.app.speculate.SpeculatorEvent; import org.apache.hadoop.mapreduce.v2.util.MRApps; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.util.StringInterner; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.yarn.api.ApplicationConstants.Environment; import org.apache.hadoop.yarn.api.records.ApplicationAccessType; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; import org.apache.hadoop.yarn.api.records.LocalResource; import org.apache.hadoop.yarn.api.records.LocalResourceType; import org.apache.hadoop.yarn.api.records.LocalResourceVisibility; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.URL; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.state.InvalidStateTransitonException; import org.apache.hadoop.yarn.state.MultipleArcTransition; import org.apache.hadoop.yarn.state.SingleArcTransition; import org.apache.hadoop.yarn.state.StateMachine; import org.apache.hadoop.yarn.state.StateMachineFactory; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.ConverterUtils; import org.apache.hadoop.yarn.util.RackResolver; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; /** * Implementation of TaskAttempt interface. */ @SuppressWarnings({ "rawtypes" }) public abstract class TaskAttemptImpl implements org.apache.hadoop.mapreduce.v2.app.job.TaskAttempt, EventHandler<TaskAttemptEvent> { static final Counters EMPTY_COUNTERS = new Counters(); private static final Log LOG = LogFactory.getLog(TaskAttemptImpl.class); private static final long MEMORY_SPLITS_RESOLUTION = 1024; //TODO Make configurable? private final static RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); protected final JobConf conf; protected final Path jobFile; protected final int partition; protected EventHandler eventHandler; private final TaskAttemptId attemptId; private final Clock clock; private final org.apache.hadoop.mapred.JobID oldJobId; private final TaskAttemptListener taskAttemptListener; private final Resource resourceCapability; protected Set<String> dataLocalHosts; protected Set<String> dataLocalRacks; private final List<String> diagnostics = new ArrayList<String>(); private final Lock readLock; private final Lock writeLock; private final AppContext appContext; private Credentials credentials; private Token<JobTokenIdentifier> jobToken; private static AtomicBoolean initialClasspathFlag = new AtomicBoolean(); private static String initialClasspath = null; private static String initialAppClasspath = null; private static Object commonContainerSpecLock = new Object(); private static ContainerLaunchContext commonContainerSpec = null; private static final Object classpathLock = new Object(); private long launchTime; private long finishTime; private WrappedProgressSplitsBlock progressSplitBlock; private int shufflePort = -1; private String trackerName; private int httpPort; private Locality locality; private Avataar avataar; private static final CleanupContainerTransition CLEANUP_CONTAINER_TRANSITION = new CleanupContainerTransition(); private static final MoveContainerToSucceededFinishingTransition SUCCEEDED_FINISHING_TRANSITION = new MoveContainerToSucceededFinishingTransition(); private static final MoveContainerToFailedFinishingTransition FAILED_FINISHING_TRANSITION = new MoveContainerToFailedFinishingTransition(); private static final ExitFinishingOnTimeoutTransition FINISHING_ON_TIMEOUT_TRANSITION = new ExitFinishingOnTimeoutTransition(); private static final FinalizeFailedTransition FINALIZE_FAILED_TRANSITION = new FinalizeFailedTransition(); private static final DiagnosticInformationUpdater DIAGNOSTIC_INFORMATION_UPDATE_TRANSITION = new DiagnosticInformationUpdater(); private static final EnumSet<TaskAttemptEventType> FAILED_KILLED_STATE_IGNORED_EVENTS = EnumSet.of( TaskAttemptEventType.TA_KILL, TaskAttemptEventType.TA_ASSIGNED, TaskAttemptEventType.TA_CONTAINER_COMPLETED, TaskAttemptEventType.TA_UPDATE, // Container launch events can arrive late TaskAttemptEventType.TA_CONTAINER_LAUNCHED, TaskAttemptEventType.TA_CONTAINER_LAUNCH_FAILED, TaskAttemptEventType.TA_CONTAINER_CLEANED, TaskAttemptEventType.TA_COMMIT_PENDING, TaskAttemptEventType.TA_DONE, TaskAttemptEventType.TA_FAILMSG, TaskAttemptEventType.TA_FAILMSG_BY_CLIENT, TaskAttemptEventType.TA_TIMED_OUT, TaskAttemptEventType.TA_TOO_MANY_FETCH_FAILURE); private static final StateMachineFactory <TaskAttemptImpl, TaskAttemptStateInternal, TaskAttemptEventType, TaskAttemptEvent> stateMachineFactory = new StateMachineFactory <TaskAttemptImpl, TaskAttemptStateInternal, TaskAttemptEventType, TaskAttemptEvent> (TaskAttemptStateInternal.NEW) // Transitions from the NEW state. .addTransition(TaskAttemptStateInternal.NEW, TaskAttemptStateInternal.UNASSIGNED, TaskAttemptEventType.TA_SCHEDULE, new RequestContainerTransition(false)) .addTransition(TaskAttemptStateInternal.NEW, TaskAttemptStateInternal.UNASSIGNED, TaskAttemptEventType.TA_RESCHEDULE, new RequestContainerTransition(true)) .addTransition(TaskAttemptStateInternal.NEW, TaskAttemptStateInternal.KILLED, TaskAttemptEventType.TA_KILL, new KilledTransition()) .addTransition(TaskAttemptStateInternal.NEW, TaskAttemptStateInternal.FAILED, TaskAttemptEventType.TA_FAILMSG_BY_CLIENT, new FailedTransition()) .addTransition(TaskAttemptStateInternal.NEW, EnumSet.of(TaskAttemptStateInternal.FAILED, TaskAttemptStateInternal.KILLED, TaskAttemptStateInternal.SUCCEEDED), TaskAttemptEventType.TA_RECOVER, new RecoverTransition()) .addTransition(TaskAttemptStateInternal.NEW, TaskAttemptStateInternal.NEW, TaskAttemptEventType.TA_DIAGNOSTICS_UPDATE, DIAGNOSTIC_INFORMATION_UPDATE_TRANSITION) // Transitions from the UNASSIGNED state. .addTransition(TaskAttemptStateInternal.UNASSIGNED, TaskAttemptStateInternal.ASSIGNED, TaskAttemptEventType.TA_ASSIGNED, new ContainerAssignedTransition()) .addTransition(TaskAttemptStateInternal.UNASSIGNED, TaskAttemptStateInternal.KILLED, TaskAttemptEventType.TA_KILL, new DeallocateContainerTransition( TaskAttemptStateInternal.KILLED, true)) .addTransition(TaskAttemptStateInternal.UNASSIGNED, TaskAttemptStateInternal.FAILED, TaskAttemptEventType.TA_FAILMSG_BY_CLIENT, new DeallocateContainerTransition( TaskAttemptStateInternal.FAILED, true)) .addTransition(TaskAttemptStateInternal.UNASSIGNED, TaskAttemptStateInternal.UNASSIGNED, TaskAttemptEventType.TA_DIAGNOSTICS_UPDATE, DIAGNOSTIC_INFORMATION_UPDATE_TRANSITION) // Transitions from the ASSIGNED state. .addTransition(TaskAttemptStateInternal.ASSIGNED, TaskAttemptStateInternal.RUNNING, TaskAttemptEventType.TA_CONTAINER_LAUNCHED, new LaunchedContainerTransition()) .addTransition(TaskAttemptStateInternal.ASSIGNED, TaskAttemptStateInternal.ASSIGNED, TaskAttemptEventType.TA_DIAGNOSTICS_UPDATE, DIAGNOSTIC_INFORMATION_UPDATE_TRANSITION) .addTransition(TaskAttemptStateInternal.ASSIGNED, TaskAttemptStateInternal.FAILED, TaskAttemptEventType.TA_CONTAINER_LAUNCH_FAILED, new DeallocateContainerTransition(TaskAttemptStateInternal.FAILED, false)) .addTransition(TaskAttemptStateInternal.ASSIGNED, TaskAttemptStateInternal.FAILED, TaskAttemptEventType.TA_CONTAINER_COMPLETED, FINALIZE_FAILED_TRANSITION) .addTransition(TaskAttemptStateInternal.ASSIGNED, TaskAttemptStateInternal.KILL_CONTAINER_CLEANUP, TaskAttemptEventType.TA_KILL, CLEANUP_CONTAINER_TRANSITION) .addTransition(TaskAttemptStateInternal.ASSIGNED, TaskAttemptStateInternal.FAIL_FINISHING_CONTAINER, TaskAttemptEventType.TA_FAILMSG, FAILED_FINISHING_TRANSITION) .addTransition(TaskAttemptStateInternal.ASSIGNED, TaskAttemptStateInternal.FAIL_CONTAINER_CLEANUP, TaskAttemptEventType.TA_FAILMSG_BY_CLIENT, CLEANUP_CONTAINER_TRANSITION) // Transitions from RUNNING state. .addTransition(TaskAttemptStateInternal.RUNNING, TaskAttemptStateInternal.RUNNING, TaskAttemptEventType.TA_UPDATE, new StatusUpdater()) .addTransition(TaskAttemptStateInternal.RUNNING, TaskAttemptStateInternal.RUNNING, TaskAttemptEventType.TA_DIAGNOSTICS_UPDATE, DIAGNOSTIC_INFORMATION_UPDATE_TRANSITION) // If no commit is required, task goes to finishing state // This will give a chance for the container to exit by itself .addTransition(TaskAttemptStateInternal.RUNNING, TaskAttemptStateInternal.SUCCESS_FINISHING_CONTAINER, TaskAttemptEventType.TA_DONE, SUCCEEDED_FINISHING_TRANSITION) // If commit is required, task goes through commit pending state. .addTransition(TaskAttemptStateInternal.RUNNING, TaskAttemptStateInternal.COMMIT_PENDING, TaskAttemptEventType.TA_COMMIT_PENDING, new CommitPendingTransition()) // Failure handling while RUNNING .addTransition(TaskAttemptStateInternal.RUNNING, TaskAttemptStateInternal.FAIL_FINISHING_CONTAINER, TaskAttemptEventType.TA_FAILMSG, FAILED_FINISHING_TRANSITION) .addTransition(TaskAttemptStateInternal.RUNNING, TaskAttemptStateInternal.FAIL_CONTAINER_CLEANUP, TaskAttemptEventType.TA_FAILMSG_BY_CLIENT, CLEANUP_CONTAINER_TRANSITION) //for handling container exit without sending the done or fail msg .addTransition(TaskAttemptStateInternal.RUNNING, TaskAttemptStateInternal.FAILED, TaskAttemptEventType.TA_CONTAINER_COMPLETED, FINALIZE_FAILED_TRANSITION) // Timeout handling while RUNNING .addTransition(TaskAttemptStateInternal.RUNNING, TaskAttemptStateInternal.FAIL_CONTAINER_CLEANUP, TaskAttemptEventType.TA_TIMED_OUT, CLEANUP_CONTAINER_TRANSITION) // if container killed by AM shutting down .addTransition(TaskAttemptStateInternal.RUNNING, TaskAttemptStateInternal.KILLED, TaskAttemptEventType.TA_CONTAINER_CLEANED, new KilledTransition()) // Kill handling .addTransition(TaskAttemptStateInternal.RUNNING, TaskAttemptStateInternal.KILL_CONTAINER_CLEANUP, TaskAttemptEventType.TA_KILL, CLEANUP_CONTAINER_TRANSITION) // Transitions from SUCCESS_FINISHING_CONTAINER state // When the container exits by itself, the notification of container // completed event will be routed via NM -> RM -> AM. // After MRAppMaster gets notification from RM, it will generate // TA_CONTAINER_COMPLETED event. .addTransition(TaskAttemptStateInternal.SUCCESS_FINISHING_CONTAINER, TaskAttemptStateInternal.SUCCEEDED, TaskAttemptEventType.TA_CONTAINER_COMPLETED, new ExitFinishingOnContainerCompletedTransition()) // Given TA notifies task T_ATTEMPT_SUCCEEDED when it transitions to // SUCCESS_FINISHING_CONTAINER, it is possible to receive the event // TA_CONTAINER_CLEANED in the following scenario. // 1. It is the last task for the job. // 2. After the task receives T_ATTEMPT_SUCCEEDED, it will notify job. // 3. Job will be marked completed. // 4. As part of MRAppMaster's shutdown, all containers will be killed. .addTransition(TaskAttemptStateInternal.SUCCESS_FINISHING_CONTAINER, TaskAttemptStateInternal.SUCCEEDED, TaskAttemptEventType.TA_CONTAINER_CLEANED, new ExitFinishingOnContainerCleanedupTransition()) // The client wants to kill the task. Given the task is in finishing // state, it could go to succeeded state or killed state. If it is a // reducer, it will go to succeeded state; // otherwise, it goes to killed state. .addTransition(TaskAttemptStateInternal.SUCCESS_FINISHING_CONTAINER, EnumSet.of(TaskAttemptStateInternal.SUCCESS_CONTAINER_CLEANUP, TaskAttemptStateInternal.KILL_CONTAINER_CLEANUP), TaskAttemptEventType.TA_KILL, new KilledAfterSucceededFinishingTransition()) // The attempt stays in finishing state for too long // Let us clean up the container .addTransition(TaskAttemptStateInternal.SUCCESS_FINISHING_CONTAINER, TaskAttemptStateInternal.SUCCESS_CONTAINER_CLEANUP, TaskAttemptEventType.TA_TIMED_OUT, FINISHING_ON_TIMEOUT_TRANSITION) .addTransition(TaskAttemptStateInternal.SUCCESS_FINISHING_CONTAINER, TaskAttemptStateInternal.SUCCESS_FINISHING_CONTAINER, TaskAttemptEventType.TA_DIAGNOSTICS_UPDATE, DIAGNOSTIC_INFORMATION_UPDATE_TRANSITION) // ignore-able events .addTransition(TaskAttemptStateInternal.SUCCESS_FINISHING_CONTAINER, TaskAttemptStateInternal.SUCCESS_FINISHING_CONTAINER, EnumSet.of(TaskAttemptEventType.TA_UPDATE, TaskAttemptEventType.TA_DONE, TaskAttemptEventType.TA_COMMIT_PENDING, TaskAttemptEventType.TA_FAILMSG, TaskAttemptEventType.TA_FAILMSG_BY_CLIENT)) // Transitions from FAIL_FINISHING_CONTAINER state // When the container exits by itself, the notification of container // completed event will be routed via NM -> RM -> AM. // After MRAppMaster gets notification from RM, it will generate // TA_CONTAINER_COMPLETED event. .addTransition(TaskAttemptStateInternal.FAIL_FINISHING_CONTAINER, TaskAttemptStateInternal.FAILED, TaskAttemptEventType.TA_CONTAINER_COMPLETED, new ExitFinishingOnContainerCompletedTransition()) // Given TA notifies task T_ATTEMPT_FAILED when it transitions to // FAIL_FINISHING_CONTAINER, it is possible to receive the event // TA_CONTAINER_CLEANED in the following scenario. // 1. It is the last task attempt for the task. // 2. After the task receives T_ATTEMPT_FAILED, it will notify job. // 3. Job will be marked failed. // 4. As part of MRAppMaster's shutdown, all containers will be killed. .addTransition(TaskAttemptStateInternal.FAIL_FINISHING_CONTAINER, TaskAttemptStateInternal.FAILED, TaskAttemptEventType.TA_CONTAINER_CLEANED, new ExitFinishingOnContainerCleanedupTransition()) .addTransition(TaskAttemptStateInternal.FAIL_FINISHING_CONTAINER, TaskAttemptStateInternal.FAIL_CONTAINER_CLEANUP, TaskAttemptEventType.TA_TIMED_OUT, FINISHING_ON_TIMEOUT_TRANSITION) .addTransition(TaskAttemptStateInternal.FAIL_FINISHING_CONTAINER, TaskAttemptStateInternal.FAIL_FINISHING_CONTAINER, TaskAttemptEventType.TA_DIAGNOSTICS_UPDATE, DIAGNOSTIC_INFORMATION_UPDATE_TRANSITION) // ignore-able events .addTransition(TaskAttemptStateInternal.FAIL_FINISHING_CONTAINER, TaskAttemptStateInternal.FAIL_FINISHING_CONTAINER, EnumSet.of(TaskAttemptEventType.TA_KILL, TaskAttemptEventType.TA_UPDATE, TaskAttemptEventType.TA_DONE, TaskAttemptEventType.TA_COMMIT_PENDING, TaskAttemptEventType.TA_FAILMSG, TaskAttemptEventType.TA_FAILMSG_BY_CLIENT)) // Transitions from COMMIT_PENDING state .addTransition(TaskAttemptStateInternal.COMMIT_PENDING, TaskAttemptStateInternal.COMMIT_PENDING, TaskAttemptEventType.TA_UPDATE, new StatusUpdater()) .addTransition(TaskAttemptStateInternal.COMMIT_PENDING, TaskAttemptStateInternal.COMMIT_PENDING, TaskAttemptEventType.TA_DIAGNOSTICS_UPDATE, DIAGNOSTIC_INFORMATION_UPDATE_TRANSITION) .addTransition(TaskAttemptStateInternal.COMMIT_PENDING, TaskAttemptStateInternal.SUCCESS_FINISHING_CONTAINER, TaskAttemptEventType.TA_DONE, SUCCEEDED_FINISHING_TRANSITION) .addTransition(TaskAttemptStateInternal.COMMIT_PENDING, TaskAttemptStateInternal.KILL_CONTAINER_CLEANUP, TaskAttemptEventType.TA_KILL, CLEANUP_CONTAINER_TRANSITION) // if container killed by AM shutting down .addTransition(TaskAttemptStateInternal.COMMIT_PENDING, TaskAttemptStateInternal.KILLED, TaskAttemptEventType.TA_CONTAINER_CLEANED, new KilledTransition()) .addTransition(TaskAttemptStateInternal.COMMIT_PENDING, TaskAttemptStateInternal.FAIL_FINISHING_CONTAINER, TaskAttemptEventType.TA_FAILMSG, FAILED_FINISHING_TRANSITION) .addTransition(TaskAttemptStateInternal.COMMIT_PENDING, TaskAttemptStateInternal.FAIL_CONTAINER_CLEANUP, TaskAttemptEventType.TA_FAILMSG_BY_CLIENT, CLEANUP_CONTAINER_TRANSITION) .addTransition(TaskAttemptStateInternal.COMMIT_PENDING, TaskAttemptStateInternal.FAILED, TaskAttemptEventType.TA_CONTAINER_COMPLETED, FINALIZE_FAILED_TRANSITION) .addTransition(TaskAttemptStateInternal.COMMIT_PENDING, TaskAttemptStateInternal.FAIL_CONTAINER_CLEANUP, TaskAttemptEventType.TA_TIMED_OUT, CLEANUP_CONTAINER_TRANSITION) // AM is likely to receive duplicate TA_COMMIT_PENDINGs as the task attempt // will re-send the commit message until it doesn't encounter any // IOException and succeeds in delivering the commit message. // Ignoring the duplicate commit message is a short-term fix. In long term, // we need to make use of retry cache to help this and other MR protocol // APIs that can be considered as @AtMostOnce. .addTransition(TaskAttemptStateInternal.COMMIT_PENDING, TaskAttemptStateInternal.COMMIT_PENDING, TaskAttemptEventType.TA_COMMIT_PENDING) // Transitions from SUCCESS_CONTAINER_CLEANUP state // kill and cleanup the container .addTransition(TaskAttemptStateInternal.SUCCESS_CONTAINER_CLEANUP, TaskAttemptStateInternal.SUCCEEDED, TaskAttemptEventType.TA_CONTAINER_CLEANED) .addTransition( TaskAttemptStateInternal.SUCCESS_CONTAINER_CLEANUP, TaskAttemptStateInternal.SUCCESS_CONTAINER_CLEANUP, TaskAttemptEventType.TA_DIAGNOSTICS_UPDATE, DIAGNOSTIC_INFORMATION_UPDATE_TRANSITION) // Ignore-able events .addTransition(TaskAttemptStateInternal.SUCCESS_CONTAINER_CLEANUP, TaskAttemptStateInternal.SUCCESS_CONTAINER_CLEANUP, EnumSet.of(TaskAttemptEventType.TA_KILL, TaskAttemptEventType.TA_FAILMSG, TaskAttemptEventType.TA_FAILMSG_BY_CLIENT, TaskAttemptEventType.TA_TIMED_OUT, TaskAttemptEventType.TA_CONTAINER_COMPLETED)) // Transitions from FAIL_CONTAINER_CLEANUP state. .addTransition(TaskAttemptStateInternal.FAIL_CONTAINER_CLEANUP, TaskAttemptStateInternal.FAIL_TASK_CLEANUP, TaskAttemptEventType.TA_CONTAINER_CLEANED, new TaskCleanupTransition()) .addTransition(TaskAttemptStateInternal.FAIL_CONTAINER_CLEANUP, TaskAttemptStateInternal.FAIL_CONTAINER_CLEANUP, TaskAttemptEventType.TA_DIAGNOSTICS_UPDATE, DIAGNOSTIC_INFORMATION_UPDATE_TRANSITION) // Ignore-able events .addTransition(TaskAttemptStateInternal.FAIL_CONTAINER_CLEANUP, TaskAttemptStateInternal.FAIL_CONTAINER_CLEANUP, EnumSet.of(TaskAttemptEventType.TA_KILL, TaskAttemptEventType.TA_CONTAINER_COMPLETED, TaskAttemptEventType.TA_UPDATE, TaskAttemptEventType.TA_COMMIT_PENDING, // Container launch events can arrive late TaskAttemptEventType.TA_CONTAINER_LAUNCHED, TaskAttemptEventType.TA_CONTAINER_LAUNCH_FAILED, TaskAttemptEventType.TA_DONE, TaskAttemptEventType.TA_FAILMSG, TaskAttemptEventType.TA_FAILMSG_BY_CLIENT, TaskAttemptEventType.TA_TIMED_OUT)) // Transitions from KILL_CONTAINER_CLEANUP .addTransition(TaskAttemptStateInternal.KILL_CONTAINER_CLEANUP, TaskAttemptStateInternal.KILL_TASK_CLEANUP, TaskAttemptEventType.TA_CONTAINER_CLEANED, new TaskCleanupTransition()) .addTransition(TaskAttemptStateInternal.KILL_CONTAINER_CLEANUP, TaskAttemptStateInternal.KILL_CONTAINER_CLEANUP, TaskAttemptEventType.TA_DIAGNOSTICS_UPDATE, DIAGNOSTIC_INFORMATION_UPDATE_TRANSITION) // Ignore-able events .addTransition( TaskAttemptStateInternal.KILL_CONTAINER_CLEANUP, TaskAttemptStateInternal.KILL_CONTAINER_CLEANUP, EnumSet.of(TaskAttemptEventType.TA_KILL, TaskAttemptEventType.TA_CONTAINER_COMPLETED, TaskAttemptEventType.TA_UPDATE, TaskAttemptEventType.TA_COMMIT_PENDING, TaskAttemptEventType.TA_CONTAINER_LAUNCHED, TaskAttemptEventType.TA_CONTAINER_LAUNCH_FAILED, TaskAttemptEventType.TA_DONE, TaskAttemptEventType.TA_FAILMSG, TaskAttemptEventType.TA_FAILMSG_BY_CLIENT, TaskAttemptEventType.TA_TIMED_OUT)) // Transitions from FAIL_TASK_CLEANUP // run the task cleanup .addTransition(TaskAttemptStateInternal.FAIL_TASK_CLEANUP, TaskAttemptStateInternal.FAILED, TaskAttemptEventType.TA_CLEANUP_DONE, new FailedTransition()) .addTransition(TaskAttemptStateInternal.FAIL_TASK_CLEANUP, TaskAttemptStateInternal.FAIL_TASK_CLEANUP, TaskAttemptEventType.TA_DIAGNOSTICS_UPDATE, DIAGNOSTIC_INFORMATION_UPDATE_TRANSITION) // Ignore-able events .addTransition(TaskAttemptStateInternal.FAIL_TASK_CLEANUP, TaskAttemptStateInternal.FAIL_TASK_CLEANUP, EnumSet.of(TaskAttemptEventType.TA_KILL, TaskAttemptEventType.TA_CONTAINER_COMPLETED, TaskAttemptEventType.TA_UPDATE, TaskAttemptEventType.TA_COMMIT_PENDING, TaskAttemptEventType.TA_DONE, TaskAttemptEventType.TA_FAILMSG, TaskAttemptEventType.TA_FAILMSG_BY_CLIENT, TaskAttemptEventType.TA_CONTAINER_CLEANED, // Container launch events can arrive late TaskAttemptEventType.TA_CONTAINER_LAUNCHED, TaskAttemptEventType.TA_CONTAINER_LAUNCH_FAILED)) // Transitions from KILL_TASK_CLEANUP .addTransition(TaskAttemptStateInternal.KILL_TASK_CLEANUP, TaskAttemptStateInternal.KILLED, TaskAttemptEventType.TA_CLEANUP_DONE, new KilledTransition()) .addTransition(TaskAttemptStateInternal.KILL_TASK_CLEANUP, TaskAttemptStateInternal.KILL_TASK_CLEANUP, TaskAttemptEventType.TA_DIAGNOSTICS_UPDATE, DIAGNOSTIC_INFORMATION_UPDATE_TRANSITION) // Ignore-able events .addTransition(TaskAttemptStateInternal.KILL_TASK_CLEANUP, TaskAttemptStateInternal.KILL_TASK_CLEANUP, EnumSet.of(TaskAttemptEventType.TA_KILL, TaskAttemptEventType.TA_CONTAINER_COMPLETED, TaskAttemptEventType.TA_UPDATE, TaskAttemptEventType.TA_COMMIT_PENDING, TaskAttemptEventType.TA_DONE, TaskAttemptEventType.TA_FAILMSG, TaskAttemptEventType.TA_FAILMSG_BY_CLIENT, TaskAttemptEventType.TA_CONTAINER_CLEANED, // Container launch events can arrive late TaskAttemptEventType.TA_CONTAINER_LAUNCHED, TaskAttemptEventType.TA_CONTAINER_LAUNCH_FAILED)) // Transitions from SUCCEEDED .addTransition(TaskAttemptStateInternal.SUCCEEDED, //only possible for map attempts TaskAttemptStateInternal.FAILED, TaskAttemptEventType.TA_TOO_MANY_FETCH_FAILURE, new TooManyFetchFailureTransition()) .addTransition(TaskAttemptStateInternal.SUCCEEDED, EnumSet.of(TaskAttemptStateInternal.SUCCEEDED, TaskAttemptStateInternal.KILLED), TaskAttemptEventType.TA_KILL, new KilledAfterSuccessTransition()) .addTransition( TaskAttemptStateInternal.SUCCEEDED, TaskAttemptStateInternal.SUCCEEDED, TaskAttemptEventType.TA_DIAGNOSTICS_UPDATE, DIAGNOSTIC_INFORMATION_UPDATE_TRANSITION) // Ignore-able events for SUCCEEDED state .addTransition(TaskAttemptStateInternal.SUCCEEDED, TaskAttemptStateInternal.SUCCEEDED, EnumSet.of(TaskAttemptEventType.TA_FAILMSG, TaskAttemptEventType.TA_FAILMSG_BY_CLIENT, // TaskAttemptFinishingMonitor might time out the attempt right // after the attempt receives TA_CONTAINER_COMPLETED. TaskAttemptEventType.TA_TIMED_OUT, TaskAttemptEventType.TA_CONTAINER_CLEANED, TaskAttemptEventType.TA_CONTAINER_COMPLETED)) // Transitions from FAILED state .addTransition(TaskAttemptStateInternal.FAILED, TaskAttemptStateInternal.FAILED, TaskAttemptEventType.TA_DIAGNOSTICS_UPDATE, DIAGNOSTIC_INFORMATION_UPDATE_TRANSITION) // Ignore-able events for FAILED state .addTransition(TaskAttemptStateInternal.FAILED, TaskAttemptStateInternal.FAILED, FAILED_KILLED_STATE_IGNORED_EVENTS) // Transitions from KILLED state .addTransition(TaskAttemptStateInternal.KILLED, TaskAttemptStateInternal.KILLED, TaskAttemptEventType.TA_DIAGNOSTICS_UPDATE, DIAGNOSTIC_INFORMATION_UPDATE_TRANSITION) // Ignore-able events for KILLED state .addTransition(TaskAttemptStateInternal.KILLED, TaskAttemptStateInternal.KILLED, FAILED_KILLED_STATE_IGNORED_EVENTS) // create the topology tables .installTopology(); private final StateMachine <TaskAttemptStateInternal, TaskAttemptEventType, TaskAttemptEvent> stateMachine; @VisibleForTesting public Container container; private String nodeRackName; private WrappedJvmID jvmID; //this takes good amount of memory ~ 30KB. Instantiate it lazily //and make it null once task is launched. private org.apache.hadoop.mapred.Task remoteTask; //this is the last status reported by the REMOTE running attempt private TaskAttemptStatus reportedStatus; private static final String LINE_SEPARATOR = System .getProperty("line.separator"); public TaskAttemptImpl(TaskId taskId, int i, EventHandler eventHandler, TaskAttemptListener taskAttemptListener, Path jobFile, int partition, JobConf conf, String[] dataLocalHosts, Token<JobTokenIdentifier> jobToken, Credentials credentials, Clock clock, AppContext appContext) { oldJobId = TypeConverter.fromYarn(taskId.getJobId()); this.conf = conf; this.clock = clock; attemptId = recordFactory.newRecordInstance(TaskAttemptId.class); attemptId.setTaskId(taskId); attemptId.setId(i); this.taskAttemptListener = taskAttemptListener; this.appContext = appContext; // Initialize reportedStatus reportedStatus = new TaskAttemptStatus(); initTaskAttemptStatus(reportedStatus); ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); readLock = readWriteLock.readLock(); writeLock = readWriteLock.writeLock(); this.credentials = credentials; this.jobToken = jobToken; this.eventHandler = eventHandler; this.jobFile = jobFile; this.partition = partition; //TODO:create the resource reqt for this Task attempt this.resourceCapability = recordFactory.newRecordInstance(Resource.class); this.resourceCapability.setMemory( getMemoryRequired(conf, taskId.getTaskType())); this.resourceCapability.setVirtualCores( getCpuRequired(conf, taskId.getTaskType())); this.dataLocalHosts = resolveHosts(dataLocalHosts); RackResolver.init(conf); this.dataLocalRacks = new HashSet<String>(); for (String host : this.dataLocalHosts) { this.dataLocalRacks.add(RackResolver.resolve(host).getNetworkLocation()); } locality = Locality.OFF_SWITCH; avataar = Avataar.VIRGIN; // This "this leak" is okay because the retained pointer is in an // instance variable. stateMachine = stateMachineFactory.make(this); } private int getMemoryRequired(JobConf conf, TaskType taskType) { return conf.getMemoryRequired(TypeConverter.fromYarn(taskType)); } private int getCpuRequired(Configuration conf, TaskType taskType) { int vcores = 1; if (taskType == TaskType.MAP) { vcores = conf.getInt(MRJobConfig.MAP_CPU_VCORES, MRJobConfig.DEFAULT_MAP_CPU_VCORES); } else if (taskType == TaskType.REDUCE) { vcores = conf.getInt(MRJobConfig.REDUCE_CPU_VCORES, MRJobConfig.DEFAULT_REDUCE_CPU_VCORES); } return vcores; } /** * Create a {@link LocalResource} record with all the given parameters. */ private static LocalResource createLocalResource(FileSystem fc, Path file, LocalResourceType type, LocalResourceVisibility visibility) throws IOException { FileStatus fstat = fc.getFileStatus(file); URL resourceURL = ConverterUtils.getYarnUrlFromPath(fc.resolvePath(fstat .getPath())); long resourceSize = fstat.getLen(); long resourceModificationTime = fstat.getModificationTime(); return LocalResource.newInstance(resourceURL, type, visibility, resourceSize, resourceModificationTime); } /** * Lock this on initialClasspath so that there is only one fork in the AM for * getting the initial class-path. TODO: We already construct * a parent CLC and use it for all the containers, so this should go away * once the mr-generated-classpath stuff is gone. */ private static String getInitialClasspath(Configuration conf) throws IOException { synchronized (classpathLock) { if (initialClasspathFlag.get()) { return initialClasspath; } Map<String, String> env = new HashMap<String, String>(); MRApps.setClasspath(env, conf); initialClasspath = env.get(Environment.CLASSPATH.name()); initialAppClasspath = env.get(Environment.APP_CLASSPATH.name()); initialClasspathFlag.set(true); return initialClasspath; } } /** * Create the common {@link ContainerLaunchContext} for all attempts. * @param applicationACLs */ private static ContainerLaunchContext createCommonContainerLaunchContext( Map<ApplicationAccessType, String> applicationACLs, Configuration conf, Token<JobTokenIdentifier> jobToken, final org.apache.hadoop.mapred.JobID oldJobId, Credentials credentials) { // Application resources Map<String, LocalResource> localResources = new HashMap<String, LocalResource>(); // Application environment Map<String, String> environment = new HashMap<String, String>(); // Service data Map<String, ByteBuffer> serviceData = new HashMap<String, ByteBuffer>(); // Tokens ByteBuffer taskCredentialsBuffer = ByteBuffer.wrap(new byte[]{}); try { FileSystem remoteFS = FileSystem.get(conf); // //////////// Set up JobJar to be localized properly on the remote NM. String jobJar = conf.get(MRJobConfig.JAR); if (jobJar != null) { final Path jobJarPath = new Path(jobJar); final FileSystem jobJarFs = FileSystem.get(jobJarPath.toUri(), conf); Path remoteJobJar = jobJarPath.makeQualified(jobJarFs.getUri(), jobJarFs.getWorkingDirectory()); LocalResource rc = createLocalResource(jobJarFs, remoteJobJar, LocalResourceType.PATTERN, LocalResourceVisibility.APPLICATION); String pattern = conf.getPattern(JobContext.JAR_UNPACK_PATTERN, JobConf.UNPACK_JAR_PATTERN_DEFAULT).pattern(); rc.setPattern(pattern); localResources.put(MRJobConfig.JOB_JAR, rc); LOG.info("The job-jar file on the remote FS is " + remoteJobJar.toUri().toASCIIString()); } else { // Job jar may be null. For e.g, for pipes, the job jar is the hadoop // mapreduce jar itself which is already on the classpath. LOG.info("Job jar is not present. " + "Not adding any jar to the list of resources."); } // //////////// End of JobJar setup // //////////// Set up JobConf to be localized properly on the remote NM. Path path = MRApps.getStagingAreaDir(conf, UserGroupInformation .getCurrentUser().getShortUserName()); Path remoteJobSubmitDir = new Path(path, oldJobId.toString()); Path remoteJobConfPath = new Path(remoteJobSubmitDir, MRJobConfig.JOB_CONF_FILE); localResources.put( MRJobConfig.JOB_CONF_FILE, createLocalResource(remoteFS, remoteJobConfPath, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION)); LOG.info("The job-conf file on the remote FS is " + remoteJobConfPath.toUri().toASCIIString()); // //////////// End of JobConf setup // Setup DistributedCache MRApps.setupDistributedCache(conf, localResources); // Setup up task credentials buffer LOG.info("Adding #" + credentials.numberOfTokens() + " tokens and #" + credentials.numberOfSecretKeys() + " secret keys for NM use for launching container"); Credentials taskCredentials = new Credentials(credentials); // LocalStorageToken is needed irrespective of whether security is enabled // or not. TokenCache.setJobToken(jobToken, taskCredentials); DataOutputBuffer containerTokens_dob = new DataOutputBuffer(); LOG.info("Size of containertokens_dob is " + taskCredentials.numberOfTokens()); taskCredentials.writeTokenStorageToStream(containerTokens_dob); taskCredentialsBuffer = ByteBuffer.wrap(containerTokens_dob.getData(), 0, containerTokens_dob.getLength()); // Add shuffle secret key // The secret key is converted to a JobToken to preserve backwards // compatibility with an older ShuffleHandler running on an NM. LOG.info("Putting shuffle token in serviceData"); byte[] shuffleSecret = TokenCache.getShuffleSecretKey(credentials); if (shuffleSecret == null) { LOG.warn("Cannot locate shuffle secret in credentials." + " Using job token as shuffle secret."); shuffleSecret = jobToken.getPassword(); } Token<JobTokenIdentifier> shuffleToken = new Token<JobTokenIdentifier>( jobToken.getIdentifier(), shuffleSecret, jobToken.getKind(), jobToken.getService()); serviceData.put(ShuffleHandler.MAPREDUCE_SHUFFLE_SERVICEID, ShuffleHandler.serializeServiceData(shuffleToken)); // add external shuffle-providers - if any Collection<String> shuffleProviders = conf.getStringCollection( MRJobConfig.MAPREDUCE_JOB_SHUFFLE_PROVIDER_SERVICES); if (! shuffleProviders.isEmpty()) { Collection<String> auxNames = conf.getStringCollection( YarnConfiguration.NM_AUX_SERVICES); for (final String shuffleProvider : shuffleProviders) { if (shuffleProvider.equals(ShuffleHandler.MAPREDUCE_SHUFFLE_SERVICEID)) { continue; // skip built-in shuffle-provider that was already inserted with shuffle secret key } if (auxNames.contains(shuffleProvider)) { LOG.info("Adding ShuffleProvider Service: " + shuffleProvider + " to serviceData"); // This only serves for INIT_APP notifications // The shuffle service needs to be able to work with the host:port information provided by the AM // (i.e. shuffle services which require custom location / other configuration are not supported) serviceData.put(shuffleProvider, ByteBuffer.allocate(0)); } else { throw new YarnRuntimeException("ShuffleProvider Service: " + shuffleProvider + " was NOT found in the list of aux-services that are available in this NM." + " You may need to specify this ShuffleProvider as an aux-service in your yarn-site.xml"); } } } MRApps.addToEnvironment( environment, Environment.CLASSPATH.name(), getInitialClasspath(conf), conf); if (initialAppClasspath != null) { MRApps.addToEnvironment( environment, Environment.APP_CLASSPATH.name(), initialAppClasspath, conf); } } catch (IOException e) { throw new YarnRuntimeException(e); } // Shell environment.put( Environment.SHELL.name(), conf.get( MRJobConfig.MAPRED_ADMIN_USER_SHELL, MRJobConfig.DEFAULT_SHELL) ); // Add pwd to LD_LIBRARY_PATH, add this before adding anything else MRApps.addToEnvironment( environment, Environment.LD_LIBRARY_PATH.name(), MRApps.crossPlatformifyMREnv(conf, Environment.PWD), conf); // Add the env variables passed by the admin MRApps.setEnvFromInputString( environment, conf.get( MRJobConfig.MAPRED_ADMIN_USER_ENV, MRJobConfig.DEFAULT_MAPRED_ADMIN_USER_ENV), conf ); // Construct the actual Container // The null fields are per-container and will be constructed for each // container separately. ContainerLaunchContext container = ContainerLaunchContext.newInstance(localResources, environment, null, serviceData, taskCredentialsBuffer, applicationACLs); return container; } static ContainerLaunchContext createContainerLaunchContext( Map<ApplicationAccessType, String> applicationACLs, Configuration conf, Token<JobTokenIdentifier> jobToken, Task remoteTask, final org.apache.hadoop.mapred.JobID oldJobId, WrappedJvmID jvmID, TaskAttemptListener taskAttemptListener, Credentials credentials) { synchronized (commonContainerSpecLock) { if (commonContainerSpec == null) { commonContainerSpec = createCommonContainerLaunchContext( applicationACLs, conf, jobToken, oldJobId, credentials); } } // Fill in the fields needed per-container that are missing in the common // spec. // Setup environment by cloning from common env. Map<String, String> env = commonContainerSpec.getEnvironment(); Map<String, String> myEnv = new HashMap<String, String>(env.size()); myEnv.putAll(env); MapReduceChildJVM.setVMEnv(myEnv, remoteTask); // Set up the launch command List<String> commands = MapReduceChildJVM.getVMCommand( taskAttemptListener.getAddress(), remoteTask, jvmID); // Duplicate the ByteBuffers for access by multiple containers. Map<String, ByteBuffer> myServiceData = new HashMap<String, ByteBuffer>(); for (Entry<String, ByteBuffer> entry : commonContainerSpec .getServiceData().entrySet()) { myServiceData.put(entry.getKey(), entry.getValue().duplicate()); } // Construct the actual Container ContainerLaunchContext container = ContainerLaunchContext.newInstance( commonContainerSpec.getLocalResources(), myEnv, commands, myServiceData, commonContainerSpec.getTokens().duplicate(), applicationACLs); return container; } @Override public ContainerId getAssignedContainerID() { readLock.lock(); try { return container == null ? null : container.getId(); } finally { readLock.unlock(); } } @Override public String getAssignedContainerMgrAddress() { readLock.lock(); try { return container == null ? null : StringInterner.weakIntern(container .getNodeId().toString()); } finally { readLock.unlock(); } } @Override public long getLaunchTime() { readLock.lock(); try { return launchTime; } finally { readLock.unlock(); } } @Override public long getFinishTime() { readLock.lock(); try { return finishTime; } finally { readLock.unlock(); } } @Override public long getShuffleFinishTime() { readLock.lock(); try { return this.reportedStatus.shuffleFinishTime; } finally { readLock.unlock(); } } @Override public long getSortFinishTime() { readLock.lock(); try { return this.reportedStatus.sortFinishTime; } finally { readLock.unlock(); } } @Override public int getShufflePort() { readLock.lock(); try { return shufflePort; } finally { readLock.unlock(); } } @Override public NodeId getNodeId() { readLock.lock(); try { return container == null ? null : container.getNodeId(); } finally { readLock.unlock(); } } /**If container Assigned then return the node's address, otherwise null. */ @Override public String getNodeHttpAddress() { readLock.lock(); try { return container == null ? null : container.getNodeHttpAddress(); } finally { readLock.unlock(); } } /** * If container Assigned then return the node's rackname, otherwise null. */ @Override public String getNodeRackName() { this.readLock.lock(); try { return this.nodeRackName; } finally { this.readLock.unlock(); } } protected abstract org.apache.hadoop.mapred.Task createRemoteTask(); @Override public TaskAttemptId getID() { return attemptId; } @Override public boolean isFinished() { readLock.lock(); try { // TODO: Use stateMachine level method? return (getInternalState() == TaskAttemptStateInternal.SUCCEEDED || getInternalState() == TaskAttemptStateInternal.FAILED || getInternalState() == TaskAttemptStateInternal.KILLED); } finally { readLock.unlock(); } } @Override public TaskAttemptReport getReport() { TaskAttemptReport result = recordFactory.newRecordInstance(TaskAttemptReport.class); readLock.lock(); try { result.setTaskAttemptId(attemptId); //take the LOCAL state of attempt //DO NOT take from reportedStatus result.setTaskAttemptState(getState()); result.setProgress(reportedStatus.progress); result.setStartTime(launchTime); result.setFinishTime(finishTime); result.setShuffleFinishTime(this.reportedStatus.shuffleFinishTime); result.setDiagnosticInfo(StringUtils.join(LINE_SEPARATOR, getDiagnostics())); result.setPhase(reportedStatus.phase); result.setStateString(reportedStatus.stateString); result.setCounters(TypeConverter.toYarn(getCounters())); result.setContainerId(this.getAssignedContainerID()); result.setNodeManagerHost(trackerName); result.setNodeManagerHttpPort(httpPort); if (this.container != null) { result.setNodeManagerPort(this.container.getNodeId().getPort()); } return result; } finally { readLock.unlock(); } } @Override public List<String> getDiagnostics() { List<String> result = new ArrayList<String>(); readLock.lock(); try { result.addAll(diagnostics); return result; } finally { readLock.unlock(); } } @Override public Counters getCounters() { readLock.lock(); try { Counters counters = reportedStatus.counters; if (counters == null) { counters = EMPTY_COUNTERS; } return counters; } finally { readLock.unlock(); } } @Override public float getProgress() { readLock.lock(); try { return reportedStatus.progress; } finally { readLock.unlock(); } } @Override public Phase getPhase() { readLock.lock(); try { return reportedStatus.phase; } finally { readLock.unlock(); } } @Override public TaskAttemptState getState() { readLock.lock(); try { return getExternalState(stateMachine.getCurrentState()); } finally { readLock.unlock(); } } @SuppressWarnings("unchecked") @Override public void handle(TaskAttemptEvent event) { if (LOG.isDebugEnabled()) { LOG.debug("Processing " + event.getTaskAttemptID() + " of type " + event.getType()); } writeLock.lock(); try { final TaskAttemptStateInternal oldState = getInternalState() ; try { stateMachine.doTransition(event.getType(), event); } catch (InvalidStateTransitonException e) { LOG.error("Can't handle this event at current state for " + this.attemptId, e); eventHandler.handle(new JobDiagnosticsUpdateEvent( this.attemptId.getTaskId().getJobId(), "Invalid event " + event.getType() + " on TaskAttempt " + this.attemptId)); eventHandler.handle(new JobEvent(this.attemptId.getTaskId().getJobId(), JobEventType.INTERNAL_ERROR)); } if (oldState != getInternalState()) { LOG.info(attemptId + " TaskAttempt Transitioned from " + oldState + " to " + getInternalState()); } } finally { writeLock.unlock(); } } @VisibleForTesting public TaskAttemptStateInternal getInternalState() { readLock.lock(); try { return stateMachine.getCurrentState(); } finally { readLock.unlock(); } } public Locality getLocality() { return locality; } public void setLocality(Locality locality) { this.locality = locality; } public Avataar getAvataar() { return avataar; } public void setAvataar(Avataar avataar) { this.avataar = avataar; } @SuppressWarnings("unchecked") public TaskAttemptStateInternal recover(TaskAttemptInfo taInfo, OutputCommitter committer, boolean recoverOutput) { ContainerId containerId = taInfo.getContainerId(); NodeId containerNodeId = ConverterUtils.toNodeId(taInfo.getHostname() + ":" + taInfo.getPort()); String nodeHttpAddress = StringInterner.weakIntern(taInfo.getHostname() + ":" + taInfo.getHttpPort()); // Resource/Priority/Tokens are only needed while launching the container on // an NM, these are already completed tasks, so setting them to null container = Container.newInstance(containerId, containerNodeId, nodeHttpAddress, null, null, null); computeRackAndLocality(); launchTime = taInfo.getStartTime(); finishTime = (taInfo.getFinishTime() != -1) ? taInfo.getFinishTime() : clock.getTime(); shufflePort = taInfo.getShufflePort(); trackerName = taInfo.getHostname(); httpPort = taInfo.getHttpPort(); sendLaunchedEvents(); reportedStatus.id = attemptId; reportedStatus.progress = 1.0f; reportedStatus.counters = taInfo.getCounters(); reportedStatus.stateString = taInfo.getState(); reportedStatus.phase = Phase.CLEANUP; reportedStatus.mapFinishTime = taInfo.getMapFinishTime(); reportedStatus.shuffleFinishTime = taInfo.getShuffleFinishTime(); reportedStatus.sortFinishTime = taInfo.getSortFinishTime(); addDiagnosticInfo(taInfo.getError()); boolean needToClean = false; String recoveredState = taInfo.getTaskStatus(); if (recoverOutput && TaskAttemptState.SUCCEEDED.toString().equals(recoveredState)) { TaskAttemptContext tac = new TaskAttemptContextImpl(conf, TypeConverter.fromYarn(attemptId)); try { committer.recoverTask(tac); LOG.info("Recovered output from task attempt " + attemptId); } catch (Exception e) { LOG.error("Unable to recover task attempt " + attemptId, e); LOG.info("Task attempt " + attemptId + " will be recovered as KILLED"); recoveredState = TaskAttemptState.KILLED.toString(); needToClean = true; } } TaskAttemptStateInternal attemptState; if (TaskAttemptState.SUCCEEDED.toString().equals(recoveredState)) { attemptState = TaskAttemptStateInternal.SUCCEEDED; reportedStatus.taskState = TaskAttemptState.SUCCEEDED; eventHandler.handle(createJobCounterUpdateEventTASucceeded(this)); logAttemptFinishedEvent(attemptState); } else if (TaskAttemptState.FAILED.toString().equals(recoveredState)) { attemptState = TaskAttemptStateInternal.FAILED; reportedStatus.taskState = TaskAttemptState.FAILED; eventHandler.handle(createJobCounterUpdateEventTAFailed(this, false)); TaskAttemptUnsuccessfulCompletionEvent tauce = createTaskAttemptUnsuccessfulCompletionEvent(this, TaskAttemptStateInternal.FAILED); eventHandler.handle( new JobHistoryEvent(attemptId.getTaskId().getJobId(), tauce)); } else { if (!TaskAttemptState.KILLED.toString().equals(recoveredState)) { if (String.valueOf(recoveredState).isEmpty()) { LOG.info("TaskAttempt" + attemptId + " had not completed, recovering as KILLED"); } else { LOG.warn("TaskAttempt " + attemptId + " found in unexpected state " + recoveredState + ", recovering as KILLED"); } addDiagnosticInfo("Killed during application recovery"); needToClean = true; } attemptState = TaskAttemptStateInternal.KILLED; reportedStatus.taskState = TaskAttemptState.KILLED; eventHandler.handle(createJobCounterUpdateEventTAKilled(this, false)); TaskAttemptUnsuccessfulCompletionEvent tauce = createTaskAttemptUnsuccessfulCompletionEvent(this, TaskAttemptStateInternal.KILLED); eventHandler.handle( new JobHistoryEvent(attemptId.getTaskId().getJobId(), tauce)); } if (needToClean) { TaskAttemptContext tac = new TaskAttemptContextImpl(conf, TypeConverter.fromYarn(attemptId)); try { committer.abortTask(tac); } catch (Exception e) { LOG.warn("Task cleanup failed for attempt " + attemptId, e); } } return attemptState; } private static TaskAttemptState getExternalState( TaskAttemptStateInternal smState) { switch (smState) { case ASSIGNED: case UNASSIGNED: return TaskAttemptState.STARTING; case COMMIT_PENDING: return TaskAttemptState.COMMIT_PENDING; case FAIL_CONTAINER_CLEANUP: case FAIL_TASK_CLEANUP: case FAIL_FINISHING_CONTAINER: case FAILED: return TaskAttemptState.FAILED; case KILL_CONTAINER_CLEANUP: case KILL_TASK_CLEANUP: case KILLED: return TaskAttemptState.KILLED; case RUNNING: return TaskAttemptState.RUNNING; case NEW: return TaskAttemptState.NEW; case SUCCESS_CONTAINER_CLEANUP: case SUCCESS_FINISHING_CONTAINER: case SUCCEEDED: return TaskAttemptState.SUCCEEDED; default: throw new YarnRuntimeException("Attempt to convert invalid " + "stateMachineTaskAttemptState to externalTaskAttemptState: " + smState); } } //always called in write lock private void setFinishTime() { //set the finish time only if launch time is set if (launchTime != 0) { finishTime = clock.getTime(); } } private void computeRackAndLocality() { NodeId containerNodeId = container.getNodeId(); nodeRackName = RackResolver.resolve( containerNodeId.getHost()).getNetworkLocation(); locality = Locality.OFF_SWITCH; if (dataLocalHosts.size() > 0) { String cHost = resolveHost(containerNodeId.getHost()); if (dataLocalHosts.contains(cHost)) { locality = Locality.NODE_LOCAL; } } if (locality == Locality.OFF_SWITCH) { if (dataLocalRacks.contains(nodeRackName)) { locality = Locality.RACK_LOCAL; } } } private static void updateMillisCounters(JobCounterUpdateEvent jce, TaskAttemptImpl taskAttempt) { TaskType taskType = taskAttempt.getID().getTaskId().getTaskType(); long duration = (taskAttempt.getFinishTime() - taskAttempt.getLaunchTime()); int mbRequired = taskAttempt.getMemoryRequired(taskAttempt.conf, taskType); int vcoresRequired = taskAttempt.getCpuRequired(taskAttempt.conf, taskType); int minSlotMemSize = taskAttempt.conf.getInt( YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB); int simSlotsRequired = minSlotMemSize == 0 ? 0 : (int) Math.ceil((float) mbRequired / minSlotMemSize); if (taskType == TaskType.MAP) { jce.addCounterUpdate(JobCounter.SLOTS_MILLIS_MAPS, simSlotsRequired * duration); jce.addCounterUpdate(JobCounter.MB_MILLIS_MAPS, duration * mbRequired); jce.addCounterUpdate(JobCounter.VCORES_MILLIS_MAPS, duration * vcoresRequired); jce.addCounterUpdate(JobCounter.MILLIS_MAPS, duration); } else { jce.addCounterUpdate(JobCounter.SLOTS_MILLIS_REDUCES, simSlotsRequired * duration); jce.addCounterUpdate(JobCounter.MB_MILLIS_REDUCES, duration * mbRequired); jce.addCounterUpdate(JobCounter.VCORES_MILLIS_REDUCES, duration * vcoresRequired); jce.addCounterUpdate(JobCounter.MILLIS_REDUCES, duration); } } private static JobCounterUpdateEvent createJobCounterUpdateEventTASucceeded( TaskAttemptImpl taskAttempt) { TaskId taskId = taskAttempt.attemptId.getTaskId(); JobCounterUpdateEvent jce = new JobCounterUpdateEvent(taskId.getJobId()); updateMillisCounters(jce, taskAttempt); return jce; } private static JobCounterUpdateEvent createJobCounterUpdateEventTAFailed( TaskAttemptImpl taskAttempt, boolean taskAlreadyCompleted) { TaskType taskType = taskAttempt.getID().getTaskId().getTaskType(); JobCounterUpdateEvent jce = new JobCounterUpdateEvent(taskAttempt.getID().getTaskId().getJobId()); if (taskType == TaskType.MAP) { jce.addCounterUpdate(JobCounter.NUM_FAILED_MAPS, 1); } else { jce.addCounterUpdate(JobCounter.NUM_FAILED_REDUCES, 1); } if (!taskAlreadyCompleted) { updateMillisCounters(jce, taskAttempt); } return jce; } private static JobCounterUpdateEvent createJobCounterUpdateEventTAKilled( TaskAttemptImpl taskAttempt, boolean taskAlreadyCompleted) { TaskType taskType = taskAttempt.getID().getTaskId().getTaskType(); JobCounterUpdateEvent jce = new JobCounterUpdateEvent(taskAttempt.getID().getTaskId().getJobId()); if (taskType == TaskType.MAP) { jce.addCounterUpdate(JobCounter.NUM_KILLED_MAPS, 1); } else { jce.addCounterUpdate(JobCounter.NUM_KILLED_REDUCES, 1); } if (!taskAlreadyCompleted) { updateMillisCounters(jce, taskAttempt); } return jce; } private static TaskAttemptUnsuccessfulCompletionEvent createTaskAttemptUnsuccessfulCompletionEvent(TaskAttemptImpl taskAttempt, TaskAttemptStateInternal attemptState) { TaskAttemptUnsuccessfulCompletionEvent tauce = new TaskAttemptUnsuccessfulCompletionEvent( TypeConverter.fromYarn(taskAttempt.attemptId), TypeConverter.fromYarn(taskAttempt.attemptId.getTaskId() .getTaskType()), attemptState.toString(), taskAttempt.finishTime, taskAttempt.container == null ? "UNKNOWN" : taskAttempt.container.getNodeId().getHost(), taskAttempt.container == null ? -1 : taskAttempt.container.getNodeId().getPort(), taskAttempt.nodeRackName == null ? "UNKNOWN" : taskAttempt.nodeRackName, StringUtils.join( LINE_SEPARATOR, taskAttempt.getDiagnostics()), taskAttempt.getCounters(), taskAttempt .getProgressSplitBlock().burst()); return tauce; } @SuppressWarnings("unchecked") private void sendLaunchedEvents() { JobCounterUpdateEvent jce = new JobCounterUpdateEvent(attemptId.getTaskId() .getJobId()); jce.addCounterUpdate(attemptId.getTaskId().getTaskType() == TaskType.MAP ? JobCounter.TOTAL_LAUNCHED_MAPS : JobCounter.TOTAL_LAUNCHED_REDUCES, 1); eventHandler.handle(jce); LOG.info("TaskAttempt: [" + attemptId + "] using containerId: [" + container.getId() + " on NM: [" + StringInterner.weakIntern(container.getNodeId().toString()) + "]"); TaskAttemptStartedEvent tase = new TaskAttemptStartedEvent(TypeConverter.fromYarn(attemptId), TypeConverter.fromYarn(attemptId.getTaskId().getTaskType()), launchTime, trackerName, httpPort, shufflePort, container.getId(), locality.toString(), avataar.toString()); eventHandler.handle( new JobHistoryEvent(attemptId.getTaskId().getJobId(), tase)); } private WrappedProgressSplitsBlock getProgressSplitBlock() { readLock.lock(); try { if (progressSplitBlock == null) { progressSplitBlock = new WrappedProgressSplitsBlock(conf.getInt( MRJobConfig.MR_AM_NUM_PROGRESS_SPLITS, MRJobConfig.DEFAULT_MR_AM_NUM_PROGRESS_SPLITS)); } return progressSplitBlock; } finally { readLock.unlock(); } } private void updateProgressSplits() { double newProgress = reportedStatus.progress; newProgress = Math.max(Math.min(newProgress, 1.0D), 0.0D); Counters counters = reportedStatus.counters; if (counters == null) return; WrappedProgressSplitsBlock splitsBlock = getProgressSplitBlock(); if (splitsBlock != null) { long now = clock.getTime(); long start = getLaunchTime(); // TODO Ensure not 0 if (start != 0 && now - start <= Integer.MAX_VALUE) { splitsBlock.getProgressWallclockTime().extend(newProgress, (int) (now - start)); } Counter cpuCounter = counters.findCounter(TaskCounter.CPU_MILLISECONDS); if (cpuCounter != null && cpuCounter.getValue() <= Integer.MAX_VALUE) { splitsBlock.getProgressCPUTime().extend(newProgress, (int) cpuCounter.getValue()); // long to int? TODO: FIX. Same below } Counter virtualBytes = counters .findCounter(TaskCounter.VIRTUAL_MEMORY_BYTES); if (virtualBytes != null) { splitsBlock.getProgressVirtualMemoryKbytes().extend(newProgress, (int) (virtualBytes.getValue() / (MEMORY_SPLITS_RESOLUTION))); } Counter physicalBytes = counters .findCounter(TaskCounter.PHYSICAL_MEMORY_BYTES); if (physicalBytes != null) { splitsBlock.getProgressPhysicalMemoryKbytes().extend(newProgress, (int) (physicalBytes.getValue() / (MEMORY_SPLITS_RESOLUTION))); } } } private static void finalizeProgress(TaskAttemptImpl taskAttempt) { // unregister it to TaskAttemptListener so that it stops listening taskAttempt.taskAttemptListener.unregister( taskAttempt.attemptId, taskAttempt.jvmID); taskAttempt.reportedStatus.progress = 1.0f; taskAttempt.updateProgressSplits(); } static class RequestContainerTransition implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { private final boolean rescheduled; public RequestContainerTransition(boolean rescheduled) { this.rescheduled = rescheduled; } @SuppressWarnings("unchecked") @Override public void transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { // Tell any speculator that we're requesting a container taskAttempt.eventHandler.handle (new SpeculatorEvent(taskAttempt.getID().getTaskId(), +1)); //request for container if (rescheduled) { taskAttempt.eventHandler.handle( ContainerRequestEvent.createContainerRequestEventForFailedContainer( taskAttempt.attemptId, taskAttempt.resourceCapability)); } else { taskAttempt.eventHandler.handle(new ContainerRequestEvent( taskAttempt.attemptId, taskAttempt.resourceCapability, taskAttempt.dataLocalHosts.toArray( new String[taskAttempt.dataLocalHosts.size()]), taskAttempt.dataLocalRacks.toArray( new String[taskAttempt.dataLocalRacks.size()]))); } } } protected Set<String> resolveHosts(String[] src) { Set<String> result = new HashSet<String>(); if (src != null) { for (int i = 0; i < src.length; i++) { if (src[i] == null) { continue; } else if (isIP(src[i])) { result.add(resolveHost(src[i])); } else { result.add(src[i]); } } } return result; } protected String resolveHost(String src) { String result = src; // Fallback in case of failure. try { InetAddress addr = InetAddress.getByName(src); result = addr.getHostName(); } catch (UnknownHostException e) { LOG.warn("Failed to resolve address: " + src + ". Continuing to use the same."); } return result; } private static final Pattern ipPattern = // Pattern for matching ip Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); protected boolean isIP(String src) { return ipPattern.matcher(src).matches(); } private static class ContainerAssignedTransition implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { @SuppressWarnings({ "unchecked" }) @Override public void transition(final TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { final TaskAttemptContainerAssignedEvent cEvent = (TaskAttemptContainerAssignedEvent) event; Container container = cEvent.getContainer(); taskAttempt.container = container; // this is a _real_ Task (classic Hadoop mapred flavor): taskAttempt.remoteTask = taskAttempt.createRemoteTask(); taskAttempt.jvmID = new WrappedJvmID(taskAttempt.remoteTask.getTaskID().getJobID(), taskAttempt.remoteTask.isMapTask(), taskAttempt.container.getId().getContainerId()); taskAttempt.taskAttemptListener.registerPendingTask( taskAttempt.remoteTask, taskAttempt.jvmID); taskAttempt.computeRackAndLocality(); //launch the container //create the container object to be launched for a given Task attempt ContainerLaunchContext launchContext = createContainerLaunchContext( cEvent.getApplicationACLs(), taskAttempt.conf, taskAttempt.jobToken, taskAttempt.remoteTask, taskAttempt.oldJobId, taskAttempt.jvmID, taskAttempt.taskAttemptListener, taskAttempt.credentials); taskAttempt.eventHandler .handle(new ContainerRemoteLaunchEvent(taskAttempt.attemptId, launchContext, container, taskAttempt.remoteTask)); // send event to speculator that our container needs are satisfied taskAttempt.eventHandler.handle (new SpeculatorEvent(taskAttempt.getID().getTaskId(), -1)); } } private static class DeallocateContainerTransition implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { private final TaskAttemptStateInternal finalState; private final boolean withdrawsContainerRequest; DeallocateContainerTransition (TaskAttemptStateInternal finalState, boolean withdrawsContainerRequest) { this.finalState = finalState; this.withdrawsContainerRequest = withdrawsContainerRequest; } @SuppressWarnings("unchecked") @Override public void transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { //set the finish time taskAttempt.setFinishTime(); if (event instanceof TaskAttemptKillEvent) { taskAttempt.addDiagnosticInfo( ((TaskAttemptKillEvent) event).getMessage()); } //send the deallocate event to ContainerAllocator taskAttempt.eventHandler.handle( new ContainerAllocatorEvent(taskAttempt.attemptId, ContainerAllocator.EventType.CONTAINER_DEALLOCATE)); // send event to speculator that we withdraw our container needs, if // we're transitioning out of UNASSIGNED if (withdrawsContainerRequest) { taskAttempt.eventHandler.handle (new SpeculatorEvent(taskAttempt.getID().getTaskId(), -1)); } switch(finalState) { case FAILED: taskAttempt.eventHandler.handle(new TaskTAttemptEvent( taskAttempt.attemptId, TaskEventType.T_ATTEMPT_FAILED)); break; case KILLED: taskAttempt.eventHandler.handle(new TaskTAttemptEvent( taskAttempt.attemptId, TaskEventType.T_ATTEMPT_KILLED)); break; default: LOG.error("Task final state is not FAILED or KILLED: " + finalState); } if (taskAttempt.getLaunchTime() != 0) { TaskAttemptUnsuccessfulCompletionEvent tauce = createTaskAttemptUnsuccessfulCompletionEvent(taskAttempt, finalState); if(finalState == TaskAttemptStateInternal.FAILED) { taskAttempt.eventHandler .handle(createJobCounterUpdateEventTAFailed(taskAttempt, false)); } else if(finalState == TaskAttemptStateInternal.KILLED) { taskAttempt.eventHandler .handle(createJobCounterUpdateEventTAKilled(taskAttempt, false)); } taskAttempt.eventHandler.handle(new JobHistoryEvent( taskAttempt.attemptId.getTaskId().getJobId(), tauce)); } else { LOG.debug("Not generating HistoryFinish event since start event not " + "generated for taskAttempt: " + taskAttempt.getID()); } } } private static class LaunchedContainerTransition implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { @SuppressWarnings("unchecked") @Override public void transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent evnt) { TaskAttemptContainerLaunchedEvent event = (TaskAttemptContainerLaunchedEvent) evnt; //set the launch time taskAttempt.launchTime = taskAttempt.clock.getTime(); taskAttempt.shufflePort = event.getShufflePort(); // register it to TaskAttemptListener so that it can start monitoring it. taskAttempt.taskAttemptListener .registerLaunchedTask(taskAttempt.attemptId, taskAttempt.jvmID); //TODO Resolve to host / IP in case of a local address. InetSocketAddress nodeHttpInetAddr = // TODO: Costly to create sock-addr? NetUtils.createSocketAddr(taskAttempt.container.getNodeHttpAddress()); taskAttempt.trackerName = nodeHttpInetAddr.getHostName(); taskAttempt.httpPort = nodeHttpInetAddr.getPort(); taskAttempt.sendLaunchedEvents(); taskAttempt.eventHandler.handle (new SpeculatorEvent (taskAttempt.attemptId, true, taskAttempt.clock.getTime())); //make remoteTask reference as null as it is no more needed //and free up the memory taskAttempt.remoteTask = null; //tell the Task that attempt has started taskAttempt.eventHandler.handle(new TaskTAttemptEvent( taskAttempt.attemptId, TaskEventType.T_ATTEMPT_LAUNCHED)); } } private static class CommitPendingTransition implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { @SuppressWarnings("unchecked") @Override public void transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { taskAttempt.eventHandler.handle(new TaskTAttemptEvent( taskAttempt.attemptId, TaskEventType.T_ATTEMPT_COMMIT_PENDING)); } } private static class TaskCleanupTransition implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { @SuppressWarnings("unchecked") @Override public void transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { TaskAttemptContext taskContext = new TaskAttemptContextImpl(taskAttempt.conf, TypeConverter.fromYarn(taskAttempt.attemptId)); taskAttempt.eventHandler.handle(new CommitterTaskAbortEvent( taskAttempt.attemptId, taskContext)); } } /** * Transition from SUCCESS_FINISHING_CONTAINER or FAIL_FINISHING_CONTAINER * state upon receiving TA_CONTAINER_COMPLETED event */ private static class ExitFinishingOnContainerCompletedTransition implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { @SuppressWarnings("unchecked") @Override public void transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { taskAttempt.appContext.getTaskAttemptFinishingMonitor().unregister( taskAttempt.attemptId); sendContainerCompleted(taskAttempt); } } private static class ExitFinishingOnContainerCleanedupTransition implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { @SuppressWarnings("unchecked") @Override public void transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { taskAttempt.appContext.getTaskAttemptFinishingMonitor().unregister( taskAttempt.attemptId); } } private static class FailedTransition implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { @SuppressWarnings("unchecked") @Override public void transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { // set the finish time taskAttempt.setFinishTime(); notifyTaskAttemptFailed(taskAttempt); } } private static class FinalizeFailedTransition extends FailedTransition { @SuppressWarnings("unchecked") @Override public void transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { finalizeProgress(taskAttempt); sendContainerCompleted(taskAttempt); super.transition(taskAttempt, event); } } @SuppressWarnings("unchecked") private static void sendContainerCompleted(TaskAttemptImpl taskAttempt) { taskAttempt.eventHandler.handle(new ContainerLauncherEvent( taskAttempt.attemptId, taskAttempt.container.getId(), StringInterner .weakIntern(taskAttempt.container.getNodeId().toString()), taskAttempt.container.getContainerToken(), ContainerLauncher.EventType.CONTAINER_COMPLETED)); } private static class RecoverTransition implements MultipleArcTransition<TaskAttemptImpl, TaskAttemptEvent, TaskAttemptStateInternal> { @Override public TaskAttemptStateInternal transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { TaskAttemptRecoverEvent tare = (TaskAttemptRecoverEvent) event; return taskAttempt.recover(tare.getTaskAttemptInfo(), tare.getCommitter(), tare.getRecoverOutput()); } } @SuppressWarnings({ "unchecked" }) private void logAttemptFinishedEvent(TaskAttemptStateInternal state) { //Log finished events only if an attempt started. if (getLaunchTime() == 0) return; String containerHostName = this.container == null ? "UNKNOWN" : this.container.getNodeId().getHost(); int containerNodePort = this.container == null ? -1 : this.container.getNodeId().getPort(); if (attemptId.getTaskId().getTaskType() == TaskType.MAP) { MapAttemptFinishedEvent mfe = new MapAttemptFinishedEvent(TypeConverter.fromYarn(attemptId), TypeConverter.fromYarn(attemptId.getTaskId().getTaskType()), state.toString(), this.reportedStatus.mapFinishTime, finishTime, containerHostName, containerNodePort, this.nodeRackName == null ? "UNKNOWN" : this.nodeRackName, this.reportedStatus.stateString, getCounters(), getProgressSplitBlock().burst()); eventHandler.handle( new JobHistoryEvent(attemptId.getTaskId().getJobId(), mfe)); } else { ReduceAttemptFinishedEvent rfe = new ReduceAttemptFinishedEvent(TypeConverter.fromYarn(attemptId), TypeConverter.fromYarn(attemptId.getTaskId().getTaskType()), state.toString(), this.reportedStatus.shuffleFinishTime, this.reportedStatus.sortFinishTime, finishTime, containerHostName, containerNodePort, this.nodeRackName == null ? "UNKNOWN" : this.nodeRackName, this.reportedStatus.stateString, getCounters(), getProgressSplitBlock().burst()); eventHandler.handle( new JobHistoryEvent(attemptId.getTaskId().getJobId(), rfe)); } } private static class TooManyFetchFailureTransition implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { @SuppressWarnings("unchecked") @Override public void transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { // too many fetch failure can only happen for map tasks Preconditions .checkArgument(taskAttempt.getID().getTaskId().getTaskType() == TaskType.MAP); //add to diagnostic taskAttempt.addDiagnosticInfo("Too Many fetch failures.Failing the attempt"); if (taskAttempt.getLaunchTime() != 0) { taskAttempt.eventHandler .handle(createJobCounterUpdateEventTAFailed(taskAttempt, true)); TaskAttemptUnsuccessfulCompletionEvent tauce = createTaskAttemptUnsuccessfulCompletionEvent(taskAttempt, TaskAttemptStateInternal.FAILED); taskAttempt.eventHandler.handle(new JobHistoryEvent( taskAttempt.attemptId.getTaskId().getJobId(), tauce)); }else { LOG.debug("Not generating HistoryFinish event since start event not " + "generated for taskAttempt: " + taskAttempt.getID()); } taskAttempt.eventHandler.handle(new TaskTAttemptEvent( taskAttempt.attemptId, TaskEventType.T_ATTEMPT_FAILED)); } } private static class KilledAfterSuccessTransition implements MultipleArcTransition<TaskAttemptImpl, TaskAttemptEvent, TaskAttemptStateInternal> { @SuppressWarnings("unchecked") @Override public TaskAttemptStateInternal transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { if(taskAttempt.getID().getTaskId().getTaskType() == TaskType.REDUCE) { // after a reduce task has succeeded, its outputs are in safe in HDFS. // logically such a task should not be killed. we only come here when // there is a race condition in the event queue. E.g. some logic sends // a kill request to this attempt when the successful completion event // for this task is already in the event queue. so the kill event will // get executed immediately after the attempt is marked successful and // result in this transition being exercised. // ignore this for reduce tasks LOG.info("Ignoring killed event for successful reduce task attempt" + taskAttempt.getID().toString()); return TaskAttemptStateInternal.SUCCEEDED; } if(event instanceof TaskAttemptKillEvent) { TaskAttemptKillEvent msgEvent = (TaskAttemptKillEvent) event; //add to diagnostic taskAttempt.addDiagnosticInfo(msgEvent.getMessage()); } // not setting a finish time since it was set on success assert (taskAttempt.getFinishTime() != 0); assert (taskAttempt.getLaunchTime() != 0); taskAttempt.eventHandler .handle(createJobCounterUpdateEventTAKilled(taskAttempt, true)); TaskAttemptUnsuccessfulCompletionEvent tauce = createTaskAttemptUnsuccessfulCompletionEvent( taskAttempt, TaskAttemptStateInternal.KILLED); taskAttempt.eventHandler.handle(new JobHistoryEvent(taskAttempt.attemptId .getTaskId().getJobId(), tauce)); taskAttempt.eventHandler.handle(new TaskTAttemptEvent( taskAttempt.attemptId, TaskEventType.T_ATTEMPT_KILLED)); return TaskAttemptStateInternal.KILLED; } } private static class KilledAfterSucceededFinishingTransition implements MultipleArcTransition<TaskAttemptImpl, TaskAttemptEvent, TaskAttemptStateInternal> { @SuppressWarnings("unchecked") @Override public TaskAttemptStateInternal transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { taskAttempt.appContext.getTaskAttemptFinishingMonitor().unregister( taskAttempt.attemptId); sendContainerCleanup(taskAttempt, event); if(taskAttempt.getID().getTaskId().getTaskType() == TaskType.REDUCE) { // after a reduce task has succeeded, its outputs are in safe in HDFS. // logically such a task should not be killed. we only come here when // there is a race condition in the event queue. E.g. some logic sends // a kill request to this attempt when the successful completion event // for this task is already in the event queue. so the kill event will // get executed immediately after the attempt is marked successful and // result in this transition being exercised. // ignore this for reduce tasks LOG.info("Ignoring killed event for successful reduce task attempt" + taskAttempt.getID().toString()); return TaskAttemptStateInternal.SUCCESS_CONTAINER_CLEANUP; } else { return TaskAttemptStateInternal.KILL_CONTAINER_CLEANUP; } } } private static class KilledTransition implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { @SuppressWarnings("unchecked") @Override public void transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { //set the finish time taskAttempt.setFinishTime(); if (taskAttempt.getLaunchTime() != 0) { taskAttempt.eventHandler .handle(createJobCounterUpdateEventTAKilled(taskAttempt, false)); TaskAttemptUnsuccessfulCompletionEvent tauce = createTaskAttemptUnsuccessfulCompletionEvent(taskAttempt, TaskAttemptStateInternal.KILLED); taskAttempt.eventHandler.handle(new JobHistoryEvent( taskAttempt.attemptId.getTaskId().getJobId(), tauce)); }else { LOG.debug("Not generating HistoryFinish event since start event not " + "generated for taskAttempt: " + taskAttempt.getID()); } if (event instanceof TaskAttemptKillEvent) { taskAttempt.addDiagnosticInfo( ((TaskAttemptKillEvent) event).getMessage()); } // taskAttempt.logAttemptFinishedEvent(TaskAttemptStateInternal.KILLED); Not logging Map/Reduce attempts in case of failure. taskAttempt.eventHandler.handle(new TaskTAttemptEvent( taskAttempt.attemptId, TaskEventType.T_ATTEMPT_KILLED)); } } private static class PreemptedTransition implements SingleArcTransition<TaskAttemptImpl,TaskAttemptEvent> { @SuppressWarnings("unchecked") @Override public void transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { taskAttempt.setFinishTime(); taskAttempt.taskAttemptListener.unregister( taskAttempt.attemptId, taskAttempt.jvmID); taskAttempt.eventHandler.handle(new ContainerLauncherEvent( taskAttempt.attemptId, taskAttempt.getAssignedContainerID(), taskAttempt.getAssignedContainerMgrAddress(), taskAttempt.container.getContainerToken(), ContainerLauncher.EventType.CONTAINER_REMOTE_CLEANUP)); taskAttempt.eventHandler.handle(new TaskTAttemptEvent( taskAttempt.attemptId, TaskEventType.T_ATTEMPT_KILLED)); } } /** * Transition from SUCCESS_FINISHING_CONTAINER or FAIL_FINISHING_CONTAINER * state upon receiving TA_TIMED_OUT event */ private static class ExitFinishingOnTimeoutTransition implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { @SuppressWarnings("unchecked") @Override public void transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { taskAttempt.appContext.getTaskAttemptFinishingMonitor().unregister( taskAttempt.attemptId); // The attempt stays in finishing state for too long String msg = "Task attempt " + taskAttempt.getID() + " is done from " + "TaskUmbilicalProtocol's point of view. However, it stays in " + "finishing state for too long"; LOG.warn(msg); taskAttempt.addDiagnosticInfo(msg); sendContainerCleanup(taskAttempt, event); } } /** * Finish and clean up the container */ private static class CleanupContainerTransition implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { @SuppressWarnings("unchecked") @Override public void transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { // unregister it to TaskAttemptListener so that it stops listening // for it. finalizeProgress(taskAttempt); sendContainerCleanup(taskAttempt, event); } } @SuppressWarnings("unchecked") private static void sendContainerCleanup(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { if (event instanceof TaskAttemptKillEvent) { taskAttempt.addDiagnosticInfo( ((TaskAttemptKillEvent) event).getMessage()); } //send the cleanup event to containerLauncher taskAttempt.eventHandler.handle(new ContainerLauncherEvent( taskAttempt.attemptId, taskAttempt.container.getId(), StringInterner .weakIntern(taskAttempt.container.getNodeId().toString()), taskAttempt.container.getContainerToken(), ContainerLauncher.EventType.CONTAINER_REMOTE_CLEANUP)); } /** * Transition to SUCCESS_FINISHING_CONTAINER upon receiving TA_DONE event */ private static class MoveContainerToSucceededFinishingTransition implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { @SuppressWarnings("unchecked") @Override public void transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { finalizeProgress(taskAttempt); // register it to finishing state taskAttempt.appContext.getTaskAttemptFinishingMonitor().register( taskAttempt.attemptId); // set the finish time taskAttempt.setFinishTime(); // notify job history taskAttempt.eventHandler.handle( createJobCounterUpdateEventTASucceeded(taskAttempt)); taskAttempt.logAttemptFinishedEvent(TaskAttemptStateInternal.SUCCEEDED); //notify the task even though the container might not have exited yet. taskAttempt.eventHandler.handle(new TaskTAttemptEvent( taskAttempt.attemptId, TaskEventType.T_ATTEMPT_SUCCEEDED)); taskAttempt.eventHandler.handle (new SpeculatorEvent (taskAttempt.reportedStatus, taskAttempt.clock.getTime())); } } /** * Transition to FAIL_FINISHING_CONTAINER upon receiving TA_FAILMSG event */ private static class MoveContainerToFailedFinishingTransition implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { @SuppressWarnings("unchecked") @Override public void transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { finalizeProgress(taskAttempt); // register it to finishing state taskAttempt.appContext.getTaskAttemptFinishingMonitor().register( taskAttempt.attemptId); notifyTaskAttemptFailed(taskAttempt); } } @SuppressWarnings("unchecked") private static void notifyTaskAttemptFailed(TaskAttemptImpl taskAttempt) { // set the finish time taskAttempt.setFinishTime(); if (taskAttempt.getLaunchTime() != 0) { taskAttempt.eventHandler .handle(createJobCounterUpdateEventTAFailed(taskAttempt, false)); TaskAttemptUnsuccessfulCompletionEvent tauce = createTaskAttemptUnsuccessfulCompletionEvent(taskAttempt, TaskAttemptStateInternal.FAILED); taskAttempt.eventHandler.handle(new JobHistoryEvent( taskAttempt.attemptId.getTaskId().getJobId(), tauce)); // taskAttempt.logAttemptFinishedEvent(TaskAttemptStateInternal.FAILED); Not // handling failed map/reduce events. }else { LOG.debug("Not generating HistoryFinish event since start event not " + "generated for taskAttempt: " + taskAttempt.getID()); } taskAttempt.eventHandler.handle(new TaskTAttemptEvent( taskAttempt.attemptId, TaskEventType.T_ATTEMPT_FAILED)); } private void addDiagnosticInfo(String diag) { if (diag != null && !diag.equals("")) { diagnostics.add(diag); } } private static class StatusUpdater implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { @SuppressWarnings("unchecked") @Override public void transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { // Status update calls don't really change the state of the attempt. TaskAttemptStatus newReportedStatus = ((TaskAttemptStatusUpdateEvent) event) .getReportedTaskAttemptStatus(); // Now switch the information in the reportedStatus taskAttempt.reportedStatus = newReportedStatus; taskAttempt.reportedStatus.taskState = taskAttempt.getState(); // send event to speculator about the reported status taskAttempt.eventHandler.handle (new SpeculatorEvent (taskAttempt.reportedStatus, taskAttempt.clock.getTime())); taskAttempt.updateProgressSplits(); //if fetch failures are present, send the fetch failure event to job //this only will happen in reduce attempt type if (taskAttempt.reportedStatus.fetchFailedMaps != null && taskAttempt.reportedStatus.fetchFailedMaps.size() > 0) { taskAttempt.eventHandler.handle(new JobTaskAttemptFetchFailureEvent( taskAttempt.attemptId, taskAttempt.reportedStatus.fetchFailedMaps)); } } } private static class DiagnosticInformationUpdater implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { @Override public void transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { TaskAttemptDiagnosticsUpdateEvent diagEvent = (TaskAttemptDiagnosticsUpdateEvent) event; LOG.info("Diagnostics report from " + taskAttempt.attemptId + ": " + diagEvent.getDiagnosticInfo()); taskAttempt.addDiagnosticInfo(diagEvent.getDiagnosticInfo()); } } private void initTaskAttemptStatus(TaskAttemptStatus result) { result.progress = 0.0f; result.phase = Phase.STARTING; result.stateString = "NEW"; result.taskState = TaskAttemptState.NEW; Counters counters = EMPTY_COUNTERS; result.counters = counters; } }
{ "content_hash": "f58cd8b2bcaf7a1cb68bac68e04aca31", "timestamp": "", "source": "github", "line_count": 2230, "max_line_length": 129, "avg_line_length": 41.431838565022424, "alnum_prop": 0.7150325241089693, "repo_name": "wankunde/cloudera_hadoop", "id": "96d1ebcf84b47014e3fa1af842759779bf5d3696", "size": "93183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/job/impl/TaskAttemptImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "95943" }, { "name": "Batchfile", "bytes": "63910" }, { "name": "C", "bytes": "1745962" }, { "name": "C++", "bytes": "2134903" }, { "name": "CMake", "bytes": "55692" }, { "name": "CSS", "bytes": "53463" }, { "name": "HTML", "bytes": "2441631" }, { "name": "Java", "bytes": "59302604" }, { "name": "JavaScript", "bytes": "46290" }, { "name": "M4", "bytes": "39811" }, { "name": "Makefile", "bytes": "57929" }, { "name": "Objective-C", "bytes": "118273" }, { "name": "PHP", "bytes": "152555" }, { "name": "Perl", "bytes": "159384" }, { "name": "Python", "bytes": "714987" }, { "name": "Ruby", "bytes": "28847" }, { "name": "Shell", "bytes": "446018" }, { "name": "Smalltalk", "bytes": "56562" }, { "name": "TLA", "bytes": "14993" }, { "name": "TeX", "bytes": "45082" }, { "name": "Thrift", "bytes": "3965" }, { "name": "XSLT", "bytes": "41310" } ], "symlink_target": "" }
(function () { 'use strict'; angular .module('app') .factory('Navigation', Navigation); Navigation.$inject = ['$http', 'config']; function Navigation($http, config ) { var service = { get: get }; return service; //////////////// function get() { return $http.get(config.baseApiUrl + '/navigation'); }; } })();
{ "content_hash": "7c4bf0482fe97ad8ff08896da1846856", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 64, "avg_line_length": 20.136363636363637, "alnum_prop": 0.435665914221219, "repo_name": "Alberto19/nuflow-web", "id": "ade8ba5f28b49855b6ba613fa19db40c47212711", "size": "443", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/services/navigation.service.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "697200" }, { "name": "HTML", "bytes": "66962" }, { "name": "JavaScript", "bytes": "166579" } ], "symlink_target": "" }
""" Time zone utilities. """ from datetime import datetime, timedelta, tzinfo __all__ = [ "FixedOffsetTimeZone", "UTC", ] class FixedOffsetTimeZone(tzinfo): """ Represents a fixed timezone offset (without daylight saving time). @ivar name: A L{str} giving the name of this timezone; the name just includes how much time this offset represents. @ivar offset: A L{timedelta} giving the amount of time this timezone is offset. """ def __init__(self, offset, name=None): """ Construct a L{FixedOffsetTimeZone} with a fixed offset. @param offset: a delta representing the offset from UTC. @type offset: L{timedelta} @param name: A name to be given for this timezone. @type name: L{str} or L{NoneType} """ self.offset = offset self.name = name @classmethod def fromSignHoursMinutes(cls, sign, hours, minutes): """ Construct a L{FixedOffsetTimeZone} from an offset described by sign ('+' or '-'), hours, and minutes. @note: For protocol compatibility with AMP, this method never uses 'Z' @param sign: A string describing the positive or negative-ness of the offset. @param hours: The number of hours in the offset. @type hours: L{int} @param minutes: The number of minutes in the offset @type minutes: L{int} @return: A time zone with the given offset, and a name describing the offset. @rtype: L{FixedOffsetTimeZone} """ name = "%s%02i:%02i" % (sign, hours, minutes) if sign == "-": hours = -hours minutes = -minutes elif sign != "+": raise ValueError("Invalid sign for timezone %r" % (sign,)) return cls(timedelta(hours=hours, minutes=minutes), name) @classmethod def fromLocalTimeStamp(cls, timeStamp): """ Create a time zone with a fixed offset corresponding to a time stamp in the system's locally configured time zone. @param timeStamp: a time stamp @type timeStamp: L{int} @return: a time zone @rtype: L{FixedOffsetTimeZone} """ offset = ( datetime.fromtimestamp(timeStamp) - datetime.utcfromtimestamp(timeStamp) ) return cls(offset) def utcoffset(self, dt): """ Return this timezone's offset from UTC. """ return self.offset def dst(self, dt): """ Return a zero C{datetime.timedelta} for the daylight saving time offset, since there is never one. """ return timedelta(0) def tzname(self, dt): """ Return a string describing this timezone. """ if self.name is not None: return self.name # XXX this is wrong; the tests are dt = datetime.fromtimestamp(0, self) return dt.strftime("UTC%z") UTC = FixedOffsetTimeZone.fromSignHoursMinutes("+", 0, 0)
{ "content_hash": "35bbf76c441d9c2822f3658ce58cf453", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 79, "avg_line_length": 26.63478260869565, "alnum_prop": 0.5902709761671564, "repo_name": "mollstam/UnrealPy", "id": "614f62bf6b170623abe36b4cdbc3cb11dac5f34b", "size": "3196", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/Twisted-15.2.1/twisted/python/_tzhelper.py", "mode": "33188", "license": "mit", "language": [ { "name": "APL", "bytes": "587" }, { "name": "ASP", "bytes": "2753" }, { "name": "ActionScript", "bytes": "5686" }, { "name": "Ada", "bytes": "94225" }, { "name": "Agda", "bytes": "3154" }, { "name": "Alloy", "bytes": "6579" }, { "name": "ApacheConf", "bytes": "12482" }, { "name": "AppleScript", "bytes": "421" }, { "name": "Assembly", "bytes": "1093261" }, { "name": "AutoHotkey", "bytes": "3733" }, { "name": "AutoIt", "bytes": "667" }, { "name": "Awk", "bytes": "63276" }, { "name": "Batchfile", "bytes": "147828" }, { "name": "BlitzBasic", "bytes": "185102" }, { "name": "BlitzMax", "bytes": "2387" }, { "name": "Boo", "bytes": "1111" }, { "name": "Bro", "bytes": "7337" }, { "name": "C", "bytes": "108397183" }, { "name": "C#", "bytes": "156749" }, { "name": "C++", "bytes": "13535833" }, { "name": "CLIPS", "bytes": "6933" }, { "name": "CMake", "bytes": "12441" }, { "name": "COBOL", "bytes": "114812" }, { "name": "CSS", "bytes": "430375" }, { "name": "Ceylon", "bytes": "1387" }, { "name": "Chapel", "bytes": "4366" }, { "name": "Cirru", "bytes": "2574" }, { "name": "Clean", "bytes": "9679" }, { "name": "Clojure", "bytes": "23871" }, { "name": "CoffeeScript", "bytes": "20149" }, { "name": "ColdFusion", "bytes": "9006" }, { "name": "Common Lisp", "bytes": "49017" }, { "name": "Coq", "bytes": "66" }, { "name": "Cucumber", "bytes": "390" }, { "name": "Cuda", "bytes": "776" }, { "name": "D", "bytes": "7556" }, { "name": "DIGITAL Command Language", "bytes": "425938" }, { "name": "DTrace", "bytes": "6706" }, { "name": "Dart", "bytes": "591" }, { "name": "Dylan", "bytes": "6343" }, { "name": "Ecl", "bytes": "2599" }, { "name": "Eiffel", "bytes": "2145" }, { "name": "Elixir", "bytes": "4340" }, { "name": "Emacs Lisp", "bytes": "18303" }, { "name": "Erlang", "bytes": "5746" }, { "name": "F#", "bytes": "19156" }, { "name": "FORTRAN", "bytes": "38458" }, { "name": "Factor", "bytes": "10194" }, { "name": "Fancy", "bytes": "2581" }, { "name": "Fantom", "bytes": "25331" }, { "name": "GAP", "bytes": "29880" }, { "name": "GLSL", "bytes": "450" }, { "name": "Gnuplot", "bytes": "11501" }, { "name": "Go", "bytes": "5444" }, { "name": "Golo", "bytes": "1649" }, { "name": "Gosu", "bytes": "2853" }, { "name": "Groff", "bytes": "3458639" }, { "name": "Groovy", "bytes": "2586" }, { "name": "HTML", "bytes": "92126540" }, { "name": "Haskell", "bytes": "49593" }, { "name": "Haxe", "bytes": "16812" }, { "name": "Hy", "bytes": "7237" }, { "name": "IDL", "bytes": "2098" }, { "name": "Idris", "bytes": "2771" }, { "name": "Inform 7", "bytes": "1944" }, { "name": "Inno Setup", "bytes": "18796" }, { "name": "Ioke", "bytes": "469" }, { "name": "Isabelle", "bytes": "21392" }, { "name": "Jasmin", "bytes": "9428" }, { "name": "Java", "bytes": "4040623" }, { "name": "JavaScript", "bytes": "223927" }, { "name": "Julia", "bytes": "27687" }, { "name": "KiCad", "bytes": "475" }, { "name": "Kotlin", "bytes": "971" }, { "name": "LSL", "bytes": "160" }, { "name": "Lasso", "bytes": "18650" }, { "name": "Lean", "bytes": "6921" }, { "name": "Limbo", "bytes": "9891" }, { "name": "Liquid", "bytes": "862" }, { "name": "LiveScript", "bytes": "972" }, { "name": "Logos", "bytes": "19509" }, { "name": "Logtalk", "bytes": "7260" }, { "name": "Lua", "bytes": "8677" }, { "name": "Makefile", "bytes": "2053844" }, { "name": "Mask", "bytes": "815" }, { "name": "Mathematica", "bytes": "191" }, { "name": "Max", "bytes": "296" }, { "name": "Modelica", "bytes": "6213" }, { "name": "Modula-2", "bytes": "23838" }, { "name": "Module Management System", "bytes": "14798" }, { "name": "Monkey", "bytes": "2587" }, { "name": "Moocode", "bytes": "3343" }, { "name": "MoonScript", "bytes": "14862" }, { "name": "Myghty", "bytes": "3939" }, { "name": "NSIS", "bytes": "7663" }, { "name": "Nemerle", "bytes": "1517" }, { "name": "NewLisp", "bytes": "42726" }, { "name": "Nimrod", "bytes": "37191" }, { "name": "Nit", "bytes": "55581" }, { "name": "Nix", "bytes": "2448" }, { "name": "OCaml", "bytes": "42416" }, { "name": "Objective-C", "bytes": "104883" }, { "name": "Objective-J", "bytes": "15340" }, { "name": "Opa", "bytes": "172" }, { "name": "OpenEdge ABL", "bytes": "49943" }, { "name": "PAWN", "bytes": "6555" }, { "name": "PHP", "bytes": "68611" }, { "name": "PLSQL", "bytes": "45772" }, { "name": "Pan", "bytes": "1241" }, { "name": "Pascal", "bytes": "349743" }, { "name": "Perl", "bytes": "5931502" }, { "name": "Perl6", "bytes": "113623" }, { "name": "PigLatin", "bytes": "6657" }, { "name": "Pike", "bytes": "8479" }, { "name": "PostScript", "bytes": "18216" }, { "name": "PowerShell", "bytes": "14236" }, { "name": "Prolog", "bytes": "43750" }, { "name": "Protocol Buffer", "bytes": "3401" }, { "name": "Puppet", "bytes": "130" }, { "name": "Python", "bytes": "122886305" }, { "name": "QML", "bytes": "3912" }, { "name": "R", "bytes": "49247" }, { "name": "Racket", "bytes": "11341" }, { "name": "Rebol", "bytes": "17708" }, { "name": "Red", "bytes": "10536" }, { "name": "Redcode", "bytes": "830" }, { "name": "Ruby", "bytes": "91403" }, { "name": "Rust", "bytes": "6788" }, { "name": "SAS", "bytes": "15603" }, { "name": "SaltStack", "bytes": "1040" }, { "name": "Scala", "bytes": "730" }, { "name": "Scheme", "bytes": "50346" }, { "name": "Scilab", "bytes": "943" }, { "name": "Shell", "bytes": "2925518" }, { "name": "ShellSession", "bytes": "320" }, { "name": "Smali", "bytes": "832" }, { "name": "Smalltalk", "bytes": "158636" }, { "name": "Smarty", "bytes": "523" }, { "name": "SourcePawn", "bytes": "130" }, { "name": "Standard ML", "bytes": "36869" }, { "name": "Swift", "bytes": "2035" }, { "name": "SystemVerilog", "bytes": "265" }, { "name": "Tcl", "bytes": "6077233" }, { "name": "TeX", "bytes": "487999" }, { "name": "Tea", "bytes": "391" }, { "name": "TypeScript", "bytes": "535" }, { "name": "VHDL", "bytes": "4446" }, { "name": "VimL", "bytes": "32053" }, { "name": "Visual Basic", "bytes": "19441" }, { "name": "XQuery", "bytes": "4289" }, { "name": "XS", "bytes": "178055" }, { "name": "XSLT", "bytes": "1995174" }, { "name": "Xtend", "bytes": "727" }, { "name": "Yacc", "bytes": "25665" }, { "name": "Zephir", "bytes": "485" }, { "name": "eC", "bytes": "31545" }, { "name": "mupad", "bytes": "2442" }, { "name": "nesC", "bytes": "23697" }, { "name": "xBase", "bytes": "3349" } ], "symlink_target": "" }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = companiesResponse; function companiesResponse(data) { var companiesByOperationArea = data.e, informationDate = data.hr; return { informationDate: informationDate, companiesByOperationArea: companiesByOperationArea.map(function (companyByOperationArea) { return { operationCode: companyByOperationArea.a, companies: companyByOperationArea.e.map(function (company) { return { operationAreaCode: company.a, referenceCode: company.c, name: company.n }; }) }; }) }; }
{ "content_hash": "554073cebbdf32edcd0ee17a2597247e", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 94, "avg_line_length": 26.03846153846154, "alnum_prop": 0.6484490398818316, "repo_name": "thiagommedeiros/bus-promise", "id": "6536a32d045132f09d4fadba337530cc47ed8be2", "size": "677", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "build/server/helpers/companies-response.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "45339" } ], "symlink_target": "" }
package com.qreal.stepic.robots.checker; import com.qreal.stepic.robots.constants.PathConstants; import java.io.*; /** * Created by vladimir-zakharov on 31.08.15. */ public class Compressor { public void compress(String taskId, String pathToFolder) throws IOException, InterruptedException { File folder = new File(pathToFolder); ProcessBuilder compressorProcBuilder = new ProcessBuilder(PathConstants.COMPRESSOR_PATH, taskId); compressorProcBuilder.directory(folder); compressorProcBuilder.start().waitFor(); } public void decompress(String kit, String taskId) throws IOException, InterruptedException { String pathToFile = String.format("%s/trikKit%s/tasks/%s", PathConstants.STEPIC_PATH, kit, taskId); File folder = new File(pathToFile); File diagramDirectory = new File(pathToFile + "/" + taskId); if (!diagramDirectory.exists()) { ProcessBuilder processBuilder = new ProcessBuilder(PathConstants.COMPRESSOR_PATH, taskId + ".qrs"); processBuilder.directory(folder); final Process process = processBuilder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader bufferedReader = new BufferedReader(isr); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } process.waitFor(); } } }
{ "content_hash": "4fe01ebc86ec27515e64b8cdd3290cff", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 111, "avg_line_length": 36.285714285714285, "alnum_prop": 0.6653543307086615, "repo_name": "qreal/qreal-web", "id": "f3468a15aa00b163578d12909d5603287795be18", "size": "2120", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "StepicRobotsWeb/src/main/java/com/qreal/stepic/robots/checker/Compressor.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "32659" }, { "name": "Groovy", "bytes": "26543" }, { "name": "Java", "bytes": "312402" }, { "name": "JavaScript", "bytes": "1123117" }, { "name": "Shell", "bytes": "5358" }, { "name": "TypeScript", "bytes": "458275" } ], "symlink_target": "" }
namespace System.Data.SqlClient { [Flags] public enum SqlBulkCopyOptions { Default = 0, KeepIdentity = 1 << 0, CheckConstraints = 1 << 1, TableLock = 1 << 2, KeepNulls = 1 << 3, FireTriggers = 1 << 4, UseInternalTransaction = 1 << 5, } }
{ "content_hash": "ffeacc1f81a253af8d390c56306e0dfb", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 40, "avg_line_length": 22.142857142857142, "alnum_prop": 0.5193548387096775, "repo_name": "shimingsg/corefx", "id": "7011fcd4a502dc60115c8ddb552326b21461239e", "size": "598", "binary": false, "copies": "29", "ref": "refs/heads/master", "path": "src/System.Data.SqlClient/src/System/Data/SqlClient/SqlBulkCopyOptions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "327222" }, { "name": "ASP", "bytes": "1687" }, { "name": "Batchfile", "bytes": "24745" }, { "name": "C", "bytes": "1113348" }, { "name": "C#", "bytes": "139667788" }, { "name": "C++", "bytes": "712083" }, { "name": "CMake", "bytes": "63626" }, { "name": "DIGITAL Command Language", "bytes": "26402" }, { "name": "Groovy", "bytes": "41755" }, { "name": "HTML", "bytes": "653" }, { "name": "Makefile", "bytes": "9085" }, { "name": "Objective-C", "bytes": "9948" }, { "name": "OpenEdge ABL", "bytes": "139178" }, { "name": "Perl", "bytes": "3895" }, { "name": "PowerShell", "bytes": "43073" }, { "name": "Python", "bytes": "1535" }, { "name": "Roff", "bytes": "4236" }, { "name": "Shell", "bytes": "72621" }, { "name": "Visual Basic", "bytes": "827108" }, { "name": "XSLT", "bytes": "462346" } ], "symlink_target": "" }
<!-- Login --> <section id="login" class="padding"> <div class="container"> <h3 class="hidden">hidden</h3> <?php if($this->session->flashdata('successsub')) { echo "<br> <div class='col-md-offset-3 col-md-6'> <div id='alert-pop' class='text-center alert alert-danger'>"; echo $this->session->flashdata('successsub'); echo "</div> </div>"; } ?> <div class="row"> <div class="col-md-12 text-center"> <div class="profile-login"> <!-- Nav tabs --> <ul class="nav nav-tabs" id="ver_tabs" role="tablist"> <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Login</a></li> <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Register</a></li> <li role="presentation"><a href="#register" aria-controls="register" role="tab" data-toggle="tab">Register as Agent</a></li> </ul> <!-- Tab panes --> <div class="tab-content padding_half"> <div role="tabpanel" class="tab-pane fade in active" id="home"> <div class="agent-p-form"> <form action="user_login" method="POST" class="callus clearfix"> <div class="single-query form-group col-sm-12"> <input type="text" class="keyword-input" name="username" placeholder="Username" required> </div> <div class="single-query form-group col-sm-12"> <input type="password" name="password" required class="keyword-input" placeholder="Password"> </div> <div class="row"> <div class="col-sm-12"> <div class="col-sm-6"> <div class="search-form-group white form-group text-left"> <div class="check-box-2"><i><input type="checkbox" name="check-box"></i></div> <span>Remember Me</span> </div> </div> <div class="col-sm-6 text-right"> <a href="forgot_pass" class="lost-pass">Lost your password?</a> </div> </div> </div> <div class=" col-sm-12"> <input type="submit" value="submit now" class="btn-slide border_radius"> </div> </form> </div> </div> <div role="tabpanel" class="tab-pane fade" id="profile"> <div class="agent-p-form" id="#user_form"> <form class="callus clearfix" action="user_reg" method="POST"> <div class="single-query col-sm-12 form-group"> <input type="text" class="keyword-input" placeholder="username" name="username" > <span class="text-danger"><?php echo form_error('username');?></span> </div> <div class="single-query col-sm-12 form-group"> <input type="text" class="keyword-input" name="email" placeholder="Email Address" > <span class="text-danger"><?php echo form_error('email');?></span> </div> <div class="single-query col-sm-12 form-group"> <input type="password" class="keyword-input" name="password" placeholder="Password" > <span class="text-danger"><?php echo form_error('password');?></span> </div> <div class="single-query col-sm-12 form-group"> <input type="password" class="keyword-input" name="cpassword" placeholder="Confirm Password" > <span class="text-danger"><?php echo form_error('cpassword');?></span> </div> <div class="search-form-group white col-sm-12 form-group text-left"> <div class="check-box-2"><i><input type="checkbox" name="check-box"></i></div> <span> Favouritemove can contact me with relevant properties, offers and news </span> </div> <div class="col-md-12 col-sm-12 col-xs-12 text-center"> <div class="query-submit-button"> <input type="submit" value="Creat an Account" class="btn-slide"> </div> </div> </form> </div> </div> <!-- AGENT REGISTRATION --> <div role="tabpanel" class="tab-pane fade" id="register"> <div class="agent-p-form"> <form class="callus clearfix" method="post" id="agregform" action="addagent" enctype="multipart/form-data"> <div class="col-md-12"> <div class=" col-sm-3 col-md-4"> <div class="form-group"> <select class="form-control" name="title" required> <option class="active">Title</option> <option value="Mr">Mr</option> <option value="Mrs">Mrs</option> </select> <span class="text-danger"><?php echo form_error('title');?></span> </div> </div> <div class="col-sm-3 col-md-4"> <div class="form-group"> <input type="text" class="form-control" placeholder="First Name" id="usr" name="fname" value="Danish"> </div> <span class="text-danger"><?php echo form_error('fname');?></span> </div> <div class="col-sm-3 col-md-4"> <div class="form-group"> <input type="text" class="form-control" placeholder="Last Name" id="usr" name="lname" value="Ali"> </div> <span class="text-danger"><?php echo form_error('lname');?></span> </div> <div class="col-md-6 col-sm-12"> <div class="form-group"> <input type="text" class="form-control" placeholder="Username" name="username" value="DanishAli"> </div> <span class="text-danger"><?php echo form_error('username');?></span> </div> <div class="col-md-6 col-sm-12"> <div class="form-group"> <input type="text" class="form-control" placeholder="Email Address" name="email" value="Danish@gmail.com"> </div> <span class="text-danger"><?php echo form_error('email');?></span> </div> <div class="col-md-6 col-sm-12"> <div class="form-group"> <input type="password" class="form-control" placeholder="Password" name="password" value="Danish"> </div> <span class="text-danger"><?php echo form_error('password');?></span> </div> <div class="col-md-6 col-sm-12 "> <div class="form-group"> <input type="password" class="form-control" placeholder="Confirm Password" name="cpassword"value="Danish" > </div> <span class="text-danger"><?php echo form_error('cpassword');?></span> </div> <div class="col-sm-12"> <div class="form-group"> <textarea class="form-control" name="description" placeholder="Description" rows="3" >Danish ali</textarea> </div> <span class="text-danger"><?php echo form_error('description');?></span> </div> <div class="col-md-6 col-sm-12"> <!-- <div class="input-group form-group image-preview"> <label style="color:white;" class="input-group form-group">Upload Profile Picture</label> <input type="file" name="user_file" placeholder="Upload Agent Image" > </div> --> <div class="input-group form-group "> <div class="input-group agncy_btn"> <label class="input-group-btn"> <span class="btn btn-primary"> Upload Image&hellip; <input type="file" multiple="multiple" name="user_file" id="upload_image" style="display: none;" /> </span> </label> <input type="text" placeholder="Upload Profile Image" id="upload_image_sho" class="form-control" readonly> </div> </div> <span class="text-danger"><?php echo form_error('address');?></span> </div> <div class="col-md-6 col-sm-12"> <div class="form-group"> <input type="text" name="ag_phone" class="form-control" placeholder="Phone" value="9309835"> </div> <span class="text-danger"><?php echo form_error('ag_phone');?></span> </div> <div class="col-md-12 col-sm-12"> <div class="form-group"> <input type="text" name="address" class="form-control" placeholder="Address" value="LAhore, Pakistan"> </div> </div> <div class="col-sm-6"> <div class="input-group bottom10"> <span class="input-group-addon"><i class="icon-facebook-1"></i></span> <input type="text" class="form-control" name="fb_link" placeholder="Facebook" value="Danish"> </div> <span class="text-danger"><?php echo form_error('fb_link');?></span> </div> <div class="col-sm-6"> <div class="input-group bottom10"> <span class="input-group-addon"><i class="icon-twitter-1"></i></span> <input type="text" class="form-control" name="twit_link" placeholder="Twitter" value="Danish"> </div> <span class="text-danger"><?php echo form_error('twit_link');?></span> </div> <div class="col-sm-6"> <div class="input-group bottom10"> <span class="input-group-addon"><i class="icon-google4"></i></span> <input type="text" class="form-control" name="gplus_link" placeholder="Google+" value="Danish"> </div> <span class="text-danger"><?php echo form_error('gplus_link');?></span> </div> <div class="col-sm-6"> <div class="input-group bottom10"> <span class="input-group-addon"><i class="fa fa-linkedin"></i></span> <input type="text" class="form-control" name="li_link" placeholder="LinkedIn" value="Danish"> </div> <span class="text-danger"><?php echo form_error('li_link');?></span> </div> <div class="col-sm-6"> <div class="input-group bottom10"> <span class="input-group-addon"><i class="fa fa-youtube"></i></span> <input type="text" class="form-control" name="you_link" placeholder="Youtube" value="Danish"> </div> <span class="text-danger"><?php echo form_error('you_link');?></span> </div> <div class="col-sm-6"> <div class="input-group bottom10"> <span class="input-group-addon"><i class="fa fa-pinterest"></i></span> <input type="text" class="form-control" name="pin_link" placeholder="Pinterest" value="Danish"> </div> <span class="text-danger"><?php echo form_error('pin_link');?></span> </div> <div class="col-sm-12"> <div class="input-group bottom10"> <span class="input-group-addon"><i class="fa fa-instagram"></i></span> <input type="text" class="form-control" name="insta_link" placeholder="Instagram" value="Danish"> </div> <span class="text-danger"><?php echo form_error('insta_link');?></span> </div> <div class="col-md-12 col-sm-12 col-xs-12 text-center"> <div class="query-submit-button"> <div class="btn-slide" id="show" >NEXT</div> </div> </div> <div class="" id="packagedeal" style="display:none;"> <?php foreach($easy['allpackages'] as $val) { ?> <br > <input type="radio" name="package" > <?php echo $val['package_name']; echo $val['package_price']; echo $val['start_date']; echo $val['end_date']; echo $val['num_listing_limit']; echo $val['num_featured_limit']; echo $val['user_type']; echo $val['package_duration']; echo $val['package_days']; ?> <?php } ?> </div> <span class="text-danger"><?php echo form_error('package');?></span> <div class="col-md-12 col-sm-12 col-xs-12 text-center"> <div class="query-submit-button top30"> <button type="submit" class="btn-slide">Submit</button> </div> </div> </form> </div> </div> </div> </div> </div> </div> </div> </section> <!-- Login end -->
{ "content_hash": "3b6cb6d4b5f0fd3d202c56d8ff941e63", "timestamp": "", "source": "github", "line_count": 285, "max_line_length": 148, "avg_line_length": 51.29824561403509, "alnum_prop": 0.45492476060191517, "repo_name": "qasim902/favmove1", "id": "1ca08ee91ad0483dbb771e39b28184a07eab9253", "size": "14620", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/views/frontend/views/login.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "470673" }, { "name": "HTML", "bytes": "74271" }, { "name": "JavaScript", "bytes": "543363" }, { "name": "PHP", "bytes": "2822795" } ], "symlink_target": "" }
This file is used to list changes made in each version of the phpenv cookbook. ## 0.5.0 - [Pierre Rambaud] - Update dependencies ## 0.4.0 - [Pierre Rambaud] - Add libssl and libreadline packages ## 0.3.0 - [Pierre Rambaud] - Fix bug on ubuntu 14.04 ## 0.2.0 - [Pierre Rambaud] - More Attributes, add supported OS, remove useless comments, more tests ## 0.1.0 - [Pierre Rambaud] - Initial release of phpenv cookbook
{ "content_hash": "26336b29a124b3c21eaeb76a3b2bbbb8", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 91, "avg_line_length": 20.238095238095237, "alnum_prop": 0.7011764705882353, "repo_name": "NoMan2000/chefRecipes", "id": "142cde865a23f1c4813164b09e3a8bb49612751f", "size": "445", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "phpenv/CHANGELOG.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "44114" }, { "name": "Makefile", "bytes": "455" }, { "name": "Perl", "bytes": "1694" }, { "name": "Python", "bytes": "1654898" }, { "name": "Ruby", "bytes": "2089488" }, { "name": "Shell", "bytes": "15236" } ], "symlink_target": "" }
<?php use yii\helpers\Url; use yii\helpers\Html; use yii\widgets\ActiveForm; use yii\captcha\Captcha; ?> <style type="text/css"> #finuser-verifycode{ border: 1px solid #ccc; color: #999; font-size: 12px; height: 36px; padding: 0 5px; width: 130px; } </style> <script type="text/javascript" src='public/js/user.js'></script> <div id='bbba'></div> <div class="t_reg"> <div class="t_regtit" id="regType"> <ul> <li> <a href="#" class="col">学生注册</a> </li> <li> <a href="<?= Url::to(['user/enterprise']); ?>">企业注册</a> </li> </ul> <div class="clear"></div> </div> <?php $form = ActiveForm::begin([ 'action' => ['user/getpost'], 'method'=>'post', 'id'=>'studentRegForm', /*'fieldConfig' => ['template'=>'<span class="wida"><label style="color:red;">*</label>&nbsp;&nbsp;{label}</span><span>{input}</span><font color="red">{error}</font><div class="clear"></div>']*/ ]); ?> <!--<form id="studentRegForm">--> <!--注册信息--> <div class="t_regif"> <ul> <li> <?= $form->field($model, 'user_phone',['template'=>'<div class="form-group field-user-user_phone required">&nbsp;&nbsp;<label style="color: red;">*</label>&nbsp;&nbsp;&nbsp;{label}{input}<div style="margin-left:100px;"><font color="red" id="phone">{error}</font></div></div>'])->textInput(['maxlength' => 11, 'class' =>'in1 validate[required,custom[mobile]]', 'placeholder'=>'请输入手机号']) ?> </li> <!--用户类型--> <?= Html::hiddenInput('user_type','1', ['value'=>'1']) ?> <!--<input name="phone" id="phone" class="in1 validate[required,custom[mobile]] " placeholder="请输入手机号码" type="text">--> <li> <?= $form->field($model, 'smsValCode',['template'=>'<div class="form-group field-studentregister-smsValidCode" style="float:left;"><label style="color: red;">*</label>&nbsp;{label}{input}<div style="margin-left:100px;"><font color="red">{error}</font></div>'])->textInput(['maxlength' => 11, 'class' =>'in2 validate[required]', 'placeholder'=>'请输入验证码']) ?> <span class="mag" style="margin-top:1px;" id="smsValidCodeText" atr="0">获取验证码</span> </li> <li> <?= $form->field($model, 'verifyCode', ['template'=>'<div class="form-group field-user-user_phone required">&nbsp;&nbsp;<label style="color: red;">*</label>&nbsp;&nbsp;&nbsp;{label}{input}<div style="margin-left:100px;"><font color="red">{error}</font></div></div>', 'options' => ['class' => 'form-group form-group-lg']])->widget(Captcha::className(),[ 'template' => "{input}{image}", 'imageOptions' => ['alt' => '验证码'], 'captchaAction' => 'site/captcha', ]); ?> </li> <li></li> <li> <?= $form->field($model, 'user_password',['template'=>'<div class="form-group field-studentregister-user_password">&nbsp;<label style="color: red;">*</label>&nbsp;&nbsp;&nbsp;{label}{input}<div style="margin-left:100px;"><font color="red">{error}</font></div></div>'])->passwordInput(['maxlength' => 20, 'class' =>'in1 validate[required,custom[pwd]]', 'placeholder'=>'请输入密码']) ?> </li> <li> <?= $form->field($model, 'isPassword',['template'=>'<div class="form-group field-studentregister-confirm_password">&nbsp;<label style="color: red;">*</label>&nbsp;&nbsp;&nbsp;{label}{input}<div style="margin-left:100px;"><font color="red">{error}</font></div></div>'])->passwordInput(['maxlength' => 20, 'class' =>'in1 validate[required,custom[pwd]]', 'placeholder'=>'请输入密码']) ?> </li> <p> <input id="agreement" name="agreement" data-prompt-position="centerRight:250,0" class="validate[required]" type="checkbox"> 我已阅读并同意《 <a href="http://www.qutaoxue.net/protocol">趣玩注册协议</a> 》 </p> <li> <span class="wida">&nbsp;</span> <span> <input name="button" id="studentRegBtn" value="下一步" class="bt1" type="submit" disabled="disabled"> </span> <div class="clear"></div> </li> </ul> </div> <?php ActiveForm::end(); ?> <!--</form>--> </div> <!-- 注册学生成功弹窗 <!-- 图片验证码 --> <div class="verificationTip" id="verificationTipID" atr="0" style="display:none"> <h1>请输入图片验证码</h1> <form action="" method="get"> <div class="verificationImg"> <input placeholder="不区分大小写" id="imgCode1" type="text"> <img src="#" id="imgverCode1" alt="验证码"> </div> <div class="verificationBut"> <button type="button" class="confirmBut but verificationButWidth butBlue" id="registerverificationBut">确认</button> <button type="button" class="cancelBut but verificationButWidth" id="btnCodeEsc">取消</button> </div> </form> </div> <!-- 图片验证码 -->
{ "content_hash": "7a8ec9892cf49393c66696f9a89886cc", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 393, "avg_line_length": 39.15126050420168, "alnum_prop": 0.596479931315733, "repo_name": "zcwzz/gittao", "id": "148186065845540b6d0d712c0c4233641bb0022e", "size": "4879", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "frontend/views/user/register.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "31784" }, { "name": "ApacheConf", "bytes": "354" }, { "name": "Batchfile", "bytes": "1541" }, { "name": "C#", "bytes": "16030" }, { "name": "CSS", "bytes": "589263" }, { "name": "Groff", "bytes": "29" }, { "name": "HTML", "bytes": "1928767" }, { "name": "Java", "bytes": "137421" }, { "name": "JavaScript", "bytes": "6557835" }, { "name": "PHP", "bytes": "10588486" }, { "name": "Perl", "bytes": "5213" }, { "name": "Shell", "bytes": "5891" } ], "symlink_target": "" }
layout: post title: Tweets date: 2018-02-28 summary: These are the tweets for February 28, 2018. categories: ---
{ "content_hash": "ec7e9cd6330f4e7352d40b5db7d9e521", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 55, "avg_line_length": 18.857142857142858, "alnum_prop": 0.6363636363636364, "repo_name": "alexlitel/congresstweets", "id": "c5ec3e70e33b90fe749a920515495e549b1c7508", "size": "136", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2018-02-28--tweets.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "16982" }, { "name": "Ruby", "bytes": "2102" }, { "name": "SCSS", "bytes": "25903" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace JMS\Serializer\Tests\Serializer\Naming; use JMS\Serializer\Naming\CamelCaseNamingStrategy; use PHPUnit\Framework\TestCase; class CamelCaseNamingStrategyTest extends TestCase { public function providePropertyNames() { return [ ['getUrl', 'get_url'], ['getURL', 'get_url'], ]; } /** * @dataProvider providePropertyNames */ public function testCamelCaseNamingHandlesMultipleUppercaseLetters($propertyName, $expected) { $mockProperty = $this->getMockBuilder('JMS\Serializer\Metadata\PropertyMetadata')->disableOriginalConstructor()->getMock(); $mockProperty->name = $propertyName; $strategy = new CamelCaseNamingStrategy(); self::assertEquals($expected, $strategy->translateName($mockProperty)); } }
{ "content_hash": "170e44942167d9c0f8d506eedacc131e", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 131, "avg_line_length": 27.516129032258064, "alnum_prop": 0.6834701055099648, "repo_name": "mpoiriert/serializer", "id": "6de01f42a13bb32f07973c991078f6299d5c74d4", "size": "853", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tests/Serializer/Naming/CamelCaseNamingStrategyTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "858142" } ], "symlink_target": "" }
package com.google.common.primitives; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.ImmutableSet; import com.google.common.testing.EqualsTester; import com.google.common.testing.NullPointerTester; import com.google.common.testing.SerializableTester; import junit.framework.TestCase; import java.math.BigInteger; /** * Tests for {@code UnsignedLong}. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class UnsignedLongTest extends TestCase { private static final ImmutableSet<Long> TEST_LONGS; static { ImmutableSet.Builder<Long> testLongsBuilder = ImmutableSet.builder(); for (long i = -3; i <= 3; i++) { testLongsBuilder .add(i) .add(Long.MAX_VALUE + i) .add(Long.MIN_VALUE + i) .add(Integer.MIN_VALUE + i) .add(Integer.MAX_VALUE + i); } TEST_LONGS = testLongsBuilder.build(); } public void testAsUnsignedAndLongValueAreInverses() { for (long value : TEST_LONGS) { assertEquals( UnsignedLongs.toString(value), value, UnsignedLong.asUnsigned(value).longValue()); } } public void testAsUnsignedBigIntegerValue() { for (long value : TEST_LONGS) { BigInteger expected = (value >= 0) ? BigInteger.valueOf(value) : BigInteger.valueOf(value).add(BigInteger.ZERO.setBit(64)); assertEquals(UnsignedLongs.toString(value), expected, UnsignedLong.asUnsigned(value).bigIntegerValue()); } } public void testToString() { for (long value : TEST_LONGS) { UnsignedLong unsignedValue = UnsignedLong.asUnsigned(value); assertEquals(unsignedValue.bigIntegerValue().toString(), unsignedValue.toString()); } } @GwtIncompatible("too slow") public void testToStringRadix() { for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) { for (long l : TEST_LONGS) { UnsignedLong value = UnsignedLong.asUnsigned(l); assertEquals(value.bigIntegerValue().toString(radix), value.toString(radix)); } } } public void testToStringRadixQuick() { int[] radices = {2, 3, 5, 7, 10, 12, 16, 21, 31, 36}; for (int radix : radices) { for (long l : TEST_LONGS) { UnsignedLong value = UnsignedLong.asUnsigned(l); assertEquals(value.bigIntegerValue().toString(radix), value.toString(radix)); } } } public void testFloatValue() { for (long value : TEST_LONGS) { UnsignedLong unsignedValue = UnsignedLong.asUnsigned(value); assertEquals(unsignedValue.bigIntegerValue().floatValue(), unsignedValue.floatValue()); } } public void testDoubleValue() { for (long value : TEST_LONGS) { UnsignedLong unsignedValue = UnsignedLong.asUnsigned(value); assertEquals(unsignedValue.bigIntegerValue().doubleValue(), unsignedValue.doubleValue()); } } public void testAdd() { for (long a : TEST_LONGS) { for (long b : TEST_LONGS) { UnsignedLong aUnsigned = UnsignedLong.asUnsigned(a); UnsignedLong bUnsigned = UnsignedLong.asUnsigned(b); long expected = aUnsigned .bigIntegerValue() .add(bUnsigned.bigIntegerValue()) .longValue(); UnsignedLong unsignedSum = aUnsigned.add(bUnsigned); assertEquals(expected, unsignedSum.longValue()); } } } public void testSubtract() { for (long a : TEST_LONGS) { for (long b : TEST_LONGS) { UnsignedLong aUnsigned = UnsignedLong.asUnsigned(a); UnsignedLong bUnsigned = UnsignedLong.asUnsigned(b); long expected = aUnsigned .bigIntegerValue() .subtract(bUnsigned.bigIntegerValue()) .longValue(); UnsignedLong unsignedSub = aUnsigned.subtract(bUnsigned); assertEquals(expected, unsignedSub.longValue()); } } } public void testMultiply() { for (long a : TEST_LONGS) { for (long b : TEST_LONGS) { UnsignedLong aUnsigned = UnsignedLong.asUnsigned(a); UnsignedLong bUnsigned = UnsignedLong.asUnsigned(b); long expected = aUnsigned .bigIntegerValue() .multiply(bUnsigned.bigIntegerValue()) .longValue(); UnsignedLong unsignedMul = aUnsigned.multiply(bUnsigned); assertEquals(expected, unsignedMul.longValue()); } } } public void testDivide() { for (long a : TEST_LONGS) { for (long b : TEST_LONGS) { if (b != 0) { UnsignedLong aUnsigned = UnsignedLong.asUnsigned(a); UnsignedLong bUnsigned = UnsignedLong.asUnsigned(b); long expected = aUnsigned .bigIntegerValue() .divide(bUnsigned.bigIntegerValue()) .longValue(); UnsignedLong unsignedDiv = aUnsigned.divide(bUnsigned); assertEquals(expected, unsignedDiv.longValue()); } } } } public void testDivideByZeroThrows() { for (long a : TEST_LONGS) { try { UnsignedLong.asUnsigned(a).divide(UnsignedLong.ZERO); fail("Expected ArithmeticException"); } catch (ArithmeticException expected) {} } } public void testRemainder() { for (long a : TEST_LONGS) { for (long b : TEST_LONGS) { if (b != 0) { UnsignedLong aUnsigned = UnsignedLong.asUnsigned(a); UnsignedLong bUnsigned = UnsignedLong.asUnsigned(b); long expected = aUnsigned .bigIntegerValue() .remainder(bUnsigned.bigIntegerValue()) .longValue(); UnsignedLong unsignedRem = aUnsigned.remainder(bUnsigned); assertEquals(expected, unsignedRem.longValue()); } } } } public void testRemainderByZero() { for (long a : TEST_LONGS) { try { UnsignedLong.asUnsigned(a).remainder(UnsignedLong.ZERO); fail("Expected ArithmeticException"); } catch (ArithmeticException expected) {} } } public void testCompare() { for (long a : TEST_LONGS) { for (long b : TEST_LONGS) { UnsignedLong aUnsigned = UnsignedLong.asUnsigned(a); UnsignedLong bUnsigned = UnsignedLong.asUnsigned(b); assertEquals(aUnsigned.bigIntegerValue().compareTo(bUnsigned.bigIntegerValue()), aUnsigned.compareTo(bUnsigned)); } } } @GwtIncompatible("too slow") public void testEqualsAndValueOf() { EqualsTester equalsTester = new EqualsTester(); for (long a : TEST_LONGS) { BigInteger big = (a >= 0) ? BigInteger.valueOf(a) : BigInteger.valueOf(a).add(BigInteger.ZERO.setBit(64)); equalsTester.addEqualityGroup(UnsignedLong.asUnsigned(a), UnsignedLong.valueOf(big), UnsignedLong.valueOf(big.toString()), UnsignedLong.valueOf(big.toString(16), 16)); } equalsTester.testEquals(); } public void testIntValue() { for (long a : TEST_LONGS) { UnsignedLong aUnsigned = UnsignedLong.asUnsigned(a); int intValue = aUnsigned.bigIntegerValue().intValue(); assertEquals(intValue, aUnsigned.intValue()); } } @GwtIncompatible("serialization") public void testSerialization() { for (long a : TEST_LONGS) { SerializableTester.reserializeAndAssert(UnsignedLong.asUnsigned(a)); } } @GwtIncompatible("NullPointerTester") public void testNulls() throws Exception { NullPointerTester tester = new NullPointerTester(); tester.setDefault(UnsignedLong.class, UnsignedLong.ONE); tester.testAllPublicStaticMethods(UnsignedLong.class); } }
{ "content_hash": "625da03e5e1fee1ee8b94a47c849f96c", "timestamp": "", "source": "github", "line_count": 237, "max_line_length": 99, "avg_line_length": 32.20675105485232, "alnum_prop": 0.6492859950216167, "repo_name": "mkeesey/guava-for-small-classpaths", "id": "3901ab0b0587c000460685c6c887f2e46dadece5", "size": "8227", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "guava-tests/test/com/google/common/primitives/UnsignedLongTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "7830515" }, { "name": "Shell", "bytes": "1443" } ], "symlink_target": "" }
(function (global, factory) { if (typeof define === "function" && define.amd) { define(['exports', 'knockout', 'lodash'], factory); } else if (typeof exports !== "undefined") { factory(exports, require('knockout'), require('lodash')); } else { var mod = { exports: {} }; factory(mod.exports, global.knockout, global.lodash); global.componentLoader = mod.exports; } })(this, function (exports, _knockout, _lodash) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _knockout2 = _interopRequireDefault(_knockout); var _lodash2 = _interopRequireDefault(_lodash); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { loadViewModel: function loadViewModel(name, componentConfig, callback) { //pour bypass //callback(null); if (componentConfig.htmlOnly === true) { callback(null); } if (componentConfig.type === 'page') { _knockout2.default.components.defaultLoader.loadViewModel(name, { createViewModel: function createViewModel(viewModel, componentInfo) { if (viewModel && viewModel.init) { viewModel.init(componentInfo); } return viewModel; } }, callback); } else { _knockout2.default.components.defaultLoader.loadViewModel(name, { createViewModel: function createViewModel(params, componentInfo) { if (_lodash2.default.isFunction(componentConfig)) { return new componentConfig(params, componentInfo); } return componentConfig; } }, callback); } }, loadComponent: function loadComponent(name, componentConfig, callback) { //pour bypass //callback(null); var kocoComponentConfig = createComponentConfigWithKocoConventions(name, componentConfig); _knockout2.default.components.defaultLoader.loadComponent(name, kocoComponentConfig, callback); } }; function createComponentConfigWithKocoConventions(name, componentConfig) { var basePath = componentConfig.basePath || 'components/' + name; if (!componentConfig.type) { componentConfig.type = 'component'; } if (componentConfig.isBower) { basePath = 'bower_components/koco-' + name + '/src'; } var requirePath = basePath + '/' + name; var templateRequirePath; if (componentConfig.template) { templateRequirePath = 'text!' + componentConfig.template; } else { templateRequirePath = 'text!' + requirePath + '.html'; } componentConfig.template = { require: templateRequirePath }; if (componentConfig.htmlOnly !== true) { if (componentConfig.type === 'page') { componentConfig.viewModel = componentConfig; } else { componentConfig.viewModel = { require: requirePath + '-ui' }; } } return componentConfig; } });
{ "content_hash": "d071a1e99f56950c7a9bdecebcc78fb2", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 107, "avg_line_length": 32.08181818181818, "alnum_prop": 0.5381127798243128, "repo_name": "cbcrc/koco-component-loader", "id": "2e08e9e792fe25535ed8f9df5d379ef0649687d2", "size": "3529", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dist/component-loader.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2766" } ], "symlink_target": "" }
require 'sinatra/base' require 'sass' require 'maruku' module Sinatra module MercuryHelpers SASS = 'sass' JS = 'js' MDOWN = 'md' COFFEE = 'coffee' CSS = 'css' SCSS = 'scss' RUBY = 'rb' # parses and evals ruby partials def ruby(rubyfile) instance_eval(open_file(find_file(rubyfile, RUBY))) end # renders css files def css(cssfile, mediatype="all") render_style open_file(find_file(cssfile, CSS)), mediatype end # renders sass files def sass(sassfile, mediatype="all") render_style Sass::Engine.new(open_file(find_file(sassfile, SASS))).render, mediatype end # renders scss files def scss(scssfile, mediatype="all") render_style Sass::Engine.new(open_file(find_file(scssfile, SCSS)), :syntax => :scss).render, mediatype end # renders javascript files def javascript(jsfile) render_script open_file(find_file(jsfile, JS)), 'javascript' end # renders markdown files def markdown(mdfile) Maruku.new(open_file(find_file(mdfile, MDOWN))).to_html end # renders coffee files def coffee(coffeefile) render_script open_file(find_file(coffeefile, COFFEE)), 'coffeescript' end #private # renders script tag based on file type def render_script(text, file_type) ["<script type='text/#{file_type}'>", text, "</script>\n"].join("\n") end # renders style tag based on media type def render_style(text, mediatype="all") ["<style type='text/css' media='#{mediatype}' >", text, "</style>\n"].join("\n") end # finds file def find_file(filename, ext) Dir.glob(File.join(options.views, "**/*.#{ext}")).select { |extfile| extfile.downcase =~ /\/#{filename.to_s.downcase}.#{ext}$/ }.first end # def open_file(full_path_and_filename) # open(full_path_and_filename,'r') { |file| file.read } # end end helpers MercuryHelpers end
{ "content_hash": "e554eedda536ca7eb5e94180f6b64c42", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 140, "avg_line_length": 25.098765432098766, "alnum_prop": 0.6064928676832267, "repo_name": "jackhq/mercury", "id": "06f67606d202548996f54ffb9c3afac96dc3c748", "size": "2033", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/mercury/helpers.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "67" }, { "name": "JavaScript", "bytes": "1035693" }, { "name": "Ruby", "bytes": "12964" } ], "symlink_target": "" }
"use strict"; var generators = require('yeoman-generator'); module.exports = generators.Base.extend({ });
{ "content_hash": "283155e465e926b7085c568e82bf4f9d", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 45, "avg_line_length": 17.833333333333332, "alnum_prop": 0.719626168224299, "repo_name": "icefox0801/generator-wuba", "id": "9ac2c6c694da2bef775323737e1984dd4d569864", "size": "107", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2848" } ], "symlink_target": "" }
package org.zstack.header.cluster; import org.zstack.header.vo.ForeignKey; import org.zstack.header.vo.ForeignKey.ReferenceOption; import org.zstack.header.vo.Index; import org.zstack.header.vo.ResourceVO; import org.zstack.header.zone.ZoneEO; import javax.persistence.*; import java.sql.Timestamp; /** */ @MappedSuperclass public class ClusterAO extends ResourceVO { @Column @ForeignKey(parentEntityClass = ZoneEO.class, onDeleteAction = ReferenceOption.RESTRICT) private String zoneUuid; @Column @Index private String name; @Column private String type; @Column private String description; @Column @Enumerated(EnumType.STRING) private ClusterState state; @Column private String hypervisorType; @Column private Timestamp createDate; @Column private Timestamp lastOpDate; @Column private String managementNodeId; public ClusterAO() { this.state = ClusterState.Disabled; } @PreUpdate private void preUpdate() { lastOpDate = null; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public ClusterState getState() { return state; } public void setState(ClusterState state) { this.state = state; } public String getZoneUuid() { return zoneUuid; } public void setZoneUuid(String zoneUuid) { this.zoneUuid = zoneUuid; } public String getHypervisorType() { return hypervisorType; } public void setHypervisorType(String hypervisorType) { this.hypervisorType = hypervisorType; } public String getManagementNodeId() { return managementNodeId; } public void setManagementNodeId(String managementNodeId) { this.managementNodeId = managementNodeId; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Timestamp getCreateDate() { return createDate; } public void setCreateDate(Timestamp createDate) { this.createDate = createDate; } public Timestamp getLastOpDate() { return lastOpDate; } public void setLastOpDate(Timestamp lastOpDate) { this.lastOpDate = lastOpDate; } }
{ "content_hash": "2951442e7880fbe471f744e13f2141e1", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 92, "avg_line_length": 20.126984126984127, "alnum_prop": 0.6573343848580442, "repo_name": "mingjian2049/zstack", "id": "160dbe5c38dfdfa4212a6049765be1d505f1bd9e", "size": "2536", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "header/src/main/java/org/zstack/header/cluster/ClusterAO.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "59182" }, { "name": "Batchfile", "bytes": "1132" }, { "name": "Groovy", "bytes": "2363847" }, { "name": "Java", "bytes": "15748239" }, { "name": "Python", "bytes": "490042" }, { "name": "Shell", "bytes": "154983" } ], "symlink_target": "" }
using Glimpse.AspNet.Extensions; using Glimpse.Core.Extensibility; using Shop.Net.Resources; namespace Shop.Net.Web { public class GlimpseSecurityPolicy : IRuntimePolicy { public RuntimePolicy Execute(IRuntimePolicyContext policyContext) { // You can perform a check like the one below to control Glimpse's permissions within your application. // More information about RuntimePolicies can be found at http://getglimpse.com/Help/Custom-Runtime-Policy var httpContext = policyContext.GetHttpContext(); if (!httpContext.User.IsInRole(GlobalConstants.AdministratorRole)) { return RuntimePolicy.Off; } return RuntimePolicy.On; } public RuntimeEvent ExecuteOn { // The RuntimeEvent.ExecuteResource is only needed in case you create a security policy // Have a look at http://blog.getglimpse.com/2013/12/09/protect-glimpse-axd-with-your-custom-runtime-policy/ for more details get { return RuntimeEvent.EndRequest | RuntimeEvent.ExecuteResource; } } } }
{ "content_hash": "9bde64b396a1f81e2d0093fa7b4bcd31", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 137, "avg_line_length": 39.55172413793103, "alnum_prop": 0.6704446381865736, "repo_name": "webdude21/Shop.NET", "id": "b474a8a8204170d4e506162375bb5190e3ceebaa", "size": "1218", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Shop.Net.Web/GlimpseSecurityPolicy.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "103" }, { "name": "C#", "bytes": "273268" }, { "name": "CSS", "bytes": "9009" }, { "name": "HTML", "bytes": "4877" }, { "name": "JavaScript", "bytes": "59841" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="15dp" android:background="#8000"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:layout_marginTop="15dp" android:text="未来三天" android:textColor="#fff" android:textSize="20sp"/> <LinearLayout android:id="@+id/forecast_layout" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> </LinearLayout> </LinearLayout>
{ "content_hash": "dfb21d0494b604f13ccb8ff5849265ef", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 72, "avg_line_length": 38.523809523809526, "alnum_prop": 0.6551297898640297, "repo_name": "wgh2755/kingweather", "id": "e32ab98e1894df76ab9b5714c1f8ebad0d644cc0", "size": "817", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/forecast.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "39881" } ], "symlink_target": "" }
import array import struct import io import warnings from struct import unpack_from from PIL import Image, ImageFile, TiffImagePlugin, _binary from PIL.JpegPresets import presets from PIL._util import isStringType i8 = _binary.i8 o8 = _binary.o8 i16 = _binary.i16be i32 = _binary.i32be __version__ = "0.6" # # Parser def Skip(self, marker): n = i16(self.fp.read(2))-2 ImageFile._safe_read(self.fp, n) def APP(self, marker): # # Application marker. Store these in the APP dictionary. # Also look for well-known application markers. n = i16(self.fp.read(2))-2 s = ImageFile._safe_read(self.fp, n) app = "APP%d" % (marker & 15) self.app[app] = s # compatibility self.applist.append((app, s)) if marker == 0xFFE0 and s[:4] == b"JFIF": # extract JFIF information self.info["jfif"] = version = i16(s, 5) # version self.info["jfif_version"] = divmod(version, 256) # extract JFIF properties try: jfif_unit = i8(s[7]) jfif_density = i16(s, 8), i16(s, 10) except: pass else: if jfif_unit == 1: self.info["dpi"] = jfif_density self.info["jfif_unit"] = jfif_unit self.info["jfif_density"] = jfif_density elif marker == 0xFFE1 and s[:5] == b"Exif\0": # extract Exif information (incomplete) self.info["exif"] = s # FIXME: value will change elif marker == 0xFFE2 and s[:5] == b"FPXR\0": # extract FlashPix information (incomplete) self.info["flashpix"] = s # FIXME: value will change elif marker == 0xFFE2 and s[:12] == b"ICC_PROFILE\0": # Since an ICC profile can be larger than the maximum size of # a JPEG marker (64K), we need provisions to split it into # multiple markers. The format defined by the ICC specifies # one or more APP2 markers containing the following data: # Identifying string ASCII "ICC_PROFILE\0" (12 bytes) # Marker sequence number 1, 2, etc (1 byte) # Number of markers Total of APP2's used (1 byte) # Profile data (remainder of APP2 data) # Decoders should use the marker sequence numbers to # reassemble the profile, rather than assuming that the APP2 # markers appear in the correct sequence. self.icclist.append(s) elif marker == 0xFFEE and s[:5] == b"Adobe": self.info["adobe"] = i16(s, 5) # extract Adobe custom properties try: adobe_transform = i8(s[1]) except: pass else: self.info["adobe_transform"] = adobe_transform elif marker == 0xFFE2 and s[:4] == b"MPF\0": # extract MPO information self.info["mp"] = s[4:] # offset is current location minus buffer size # plus constant header size self.info["mpoffset"] = self.fp.tell() - n + 4 def COM(self, marker): # # Comment marker. Store these in the APP dictionary. n = i16(self.fp.read(2))-2 s = ImageFile._safe_read(self.fp, n) self.app["COM"] = s # compatibility self.applist.append(("COM", s)) def SOF(self, marker): # # Start of frame marker. Defines the size and mode of the # image. JPEG is colour blind, so we use some simple # heuristics to map the number of layers to an appropriate # mode. Note that this could be made a bit brighter, by # looking for JFIF and Adobe APP markers. n = i16(self.fp.read(2))-2 s = ImageFile._safe_read(self.fp, n) self.size = i16(s[3:]), i16(s[1:]) self.bits = i8(s[0]) if self.bits != 8: raise SyntaxError("cannot handle %d-bit layers" % self.bits) self.layers = i8(s[5]) if self.layers == 1: self.mode = "L" elif self.layers == 3: self.mode = "RGB" elif self.layers == 4: self.mode = "CMYK" else: raise SyntaxError("cannot handle %d-layer images" % self.layers) if marker in [0xFFC2, 0xFFC6, 0xFFCA, 0xFFCE]: self.info["progressive"] = self.info["progression"] = 1 if self.icclist: # fixup icc profile self.icclist.sort() # sort by sequence number if i8(self.icclist[0][13]) == len(self.icclist): profile = [] for p in self.icclist: profile.append(p[14:]) icc_profile = b"".join(profile) else: icc_profile = None # wrong number of fragments self.info["icc_profile"] = icc_profile self.icclist = None for i in range(6, len(s), 3): t = s[i:i+3] # 4-tuples: id, vsamp, hsamp, qtable self.layer.append((t[0], i8(t[1])//16, i8(t[1]) & 15, i8(t[2]))) def DQT(self, marker): # # Define quantization table. Support baseline 8-bit tables # only. Note that there might be more than one table in # each marker. # FIXME: The quantization tables can be used to estimate the # compression quality. n = i16(self.fp.read(2))-2 s = ImageFile._safe_read(self.fp, n) while len(s): if len(s) < 65: raise SyntaxError("bad quantization table marker") v = i8(s[0]) if v//16 == 0: self.quantization[v & 15] = array.array("B", s[1:65]) s = s[65:] else: return # FIXME: add code to read 16-bit tables! # raise SyntaxError, "bad quantization table element size" # # JPEG marker table MARKER = { 0xFFC0: ("SOF0", "Baseline DCT", SOF), 0xFFC1: ("SOF1", "Extended Sequential DCT", SOF), 0xFFC2: ("SOF2", "Progressive DCT", SOF), 0xFFC3: ("SOF3", "Spatial lossless", SOF), 0xFFC4: ("DHT", "Define Huffman table", Skip), 0xFFC5: ("SOF5", "Differential sequential DCT", SOF), 0xFFC6: ("SOF6", "Differential progressive DCT", SOF), 0xFFC7: ("SOF7", "Differential spatial", SOF), 0xFFC8: ("JPG", "Extension", None), 0xFFC9: ("SOF9", "Extended sequential DCT (AC)", SOF), 0xFFCA: ("SOF10", "Progressive DCT (AC)", SOF), 0xFFCB: ("SOF11", "Spatial lossless DCT (AC)", SOF), 0xFFCC: ("DAC", "Define arithmetic coding conditioning", Skip), 0xFFCD: ("SOF13", "Differential sequential DCT (AC)", SOF), 0xFFCE: ("SOF14", "Differential progressive DCT (AC)", SOF), 0xFFCF: ("SOF15", "Differential spatial (AC)", SOF), 0xFFD0: ("RST0", "Restart 0", None), 0xFFD1: ("RST1", "Restart 1", None), 0xFFD2: ("RST2", "Restart 2", None), 0xFFD3: ("RST3", "Restart 3", None), 0xFFD4: ("RST4", "Restart 4", None), 0xFFD5: ("RST5", "Restart 5", None), 0xFFD6: ("RST6", "Restart 6", None), 0xFFD7: ("RST7", "Restart 7", None), 0xFFD8: ("SOI", "Start of image", None), 0xFFD9: ("EOI", "End of image", None), 0xFFDA: ("SOS", "Start of scan", Skip), 0xFFDB: ("DQT", "Define quantization table", DQT), 0xFFDC: ("DNL", "Define number of lines", Skip), 0xFFDD: ("DRI", "Define restart interval", Skip), 0xFFDE: ("DHP", "Define hierarchical progression", SOF), 0xFFDF: ("EXP", "Expand reference component", Skip), 0xFFE0: ("APP0", "Application segment 0", APP), 0xFFE1: ("APP1", "Application segment 1", APP), 0xFFE2: ("APP2", "Application segment 2", APP), 0xFFE3: ("APP3", "Application segment 3", APP), 0xFFE4: ("APP4", "Application segment 4", APP), 0xFFE5: ("APP5", "Application segment 5", APP), 0xFFE6: ("APP6", "Application segment 6", APP), 0xFFE7: ("APP7", "Application segment 7", APP), 0xFFE8: ("APP8", "Application segment 8", APP), 0xFFE9: ("APP9", "Application segment 9", APP), 0xFFEA: ("APP10", "Application segment 10", APP), 0xFFEB: ("APP11", "Application segment 11", APP), 0xFFEC: ("APP12", "Application segment 12", APP), 0xFFED: ("APP13", "Application segment 13", APP), 0xFFEE: ("APP14", "Application segment 14", APP), 0xFFEF: ("APP15", "Application segment 15", APP), 0xFFF0: ("JPG0", "Extension 0", None), 0xFFF1: ("JPG1", "Extension 1", None), 0xFFF2: ("JPG2", "Extension 2", None), 0xFFF3: ("JPG3", "Extension 3", None), 0xFFF4: ("JPG4", "Extension 4", None), 0xFFF5: ("JPG5", "Extension 5", None), 0xFFF6: ("JPG6", "Extension 6", None), 0xFFF7: ("JPG7", "Extension 7", None), 0xFFF8: ("JPG8", "Extension 8", None), 0xFFF9: ("JPG9", "Extension 9", None), 0xFFFA: ("JPG10", "Extension 10", None), 0xFFFB: ("JPG11", "Extension 11", None), 0xFFFC: ("JPG12", "Extension 12", None), 0xFFFD: ("JPG13", "Extension 13", None), 0xFFFE: ("COM", "Comment", COM) } def _accept(prefix): return prefix[0:1] == b"\377" ## # Image plugin for JPEG and JFIF images. class JpegImageFile(ImageFile.ImageFile): format = "JPEG" format_description = "JPEG (ISO 10918)" def _open(self): s = self.fp.read(1) if i8(s) != 255: raise SyntaxError("not a JPEG file") # Create attributes self.bits = self.layers = 0 # JPEG specifics (internal) self.layer = [] self.huffman_dc = {} self.huffman_ac = {} self.quantization = {} self.app = {} # compatibility self.applist = [] self.icclist = [] while True: i = i8(s) if i == 0xFF: s = s + self.fp.read(1) i = i16(s) else: # Skip non-0xFF junk s = self.fp.read(1) continue if i in MARKER: name, description, handler = MARKER[i] # print hex(i), name, description if handler is not None: handler(self, i) if i == 0xFFDA: # start of scan rawmode = self.mode if self.mode == "CMYK": rawmode = "CMYK;I" # assume adobe conventions self.tile = [("jpeg", (0, 0) + self.size, 0, (rawmode, ""))] # self.__offset = self.fp.tell() break s = self.fp.read(1) elif i == 0 or i == 0xFFFF: # padded marker or junk; move on s = b"\xff" elif i == 0xFF00: # Skip extraneous data (escaped 0xFF) s = self.fp.read(1) else: raise SyntaxError("no marker found") def draft(self, mode, size): if len(self.tile) != 1: return d, e, o, a = self.tile[0] scale = 0 if a[0] == "RGB" and mode in ["L", "YCbCr"]: self.mode = mode a = mode, "" if size: scale = max(self.size[0] // size[0], self.size[1] // size[1]) for s in [8, 4, 2, 1]: if scale >= s: break e = e[0], e[1], (e[2]-e[0]+s-1)//s+e[0], (e[3]-e[1]+s-1)//s+e[1] self.size = ((self.size[0]+s-1)//s, (self.size[1]+s-1)//s) scale = s self.tile = [(d, e, o, a)] self.decoderconfig = (scale, 0) return self def load_djpeg(self): # ALTERNATIVE: handle JPEGs via the IJG command line utilities import subprocess import tempfile import os f, path = tempfile.mkstemp() os.close(f) if os.path.exists(self.filename): subprocess.check_call(["djpeg", "-outfile", path, self.filename]) else: raise ValueError("Invalid Filename") try: _im = Image.open(path) _im.load() self.im = _im.im finally: try: os.unlink(path) except OSError: pass self.mode = self.im.mode self.size = self.im.size self.tile = [] def _getexif(self): return _getexif(self) def _getmp(self): return _getmp(self) def _fixup_dict(src_dict): # Helper function for _getexif() # returns a dict with any single item tuples/lists as individual values def _fixup(value): try: if len(value) == 1 and not isinstance(value, dict): return value[0] except: pass return value return dict([(k, _fixup(v)) for k, v in src_dict.items()]) def _getexif(self): # Extract EXIF information. This method is highly experimental, # and is likely to be replaced with something better in a future # version. # The EXIF record consists of a TIFF file embedded in a JPEG # application marker (!). try: data = self.info["exif"] except KeyError: return None file = io.BytesIO(data[6:]) head = file.read(8) # process dictionary info = TiffImagePlugin.ImageFileDirectory_v1(head) info.load(file) exif = dict(_fixup_dict(info)) # get exif extension try: # exif field 0x8769 is an offset pointer to the location # of the nested embedded exif ifd. # It should be a long, but may be corrupted. file.seek(exif[0x8769]) except (KeyError, TypeError): pass else: info = TiffImagePlugin.ImageFileDirectory_v1(head) info.load(file) exif.update(_fixup_dict(info)) # get gpsinfo extension try: # exif field 0x8825 is an offset pointer to the location # of the nested embedded gps exif ifd. # It should be a long, but may be corrupted. file.seek(exif[0x8825]) except (KeyError, TypeError): pass else: info = TiffImagePlugin.ImageFileDirectory_v1(head) info.load(file) exif[0x8825] = _fixup_dict(info) return exif def _getmp(self): # Extract MP information. This method was inspired by the "highly # experimental" _getexif version that's been in use for years now, # itself based on the ImageFileDirectory class in the TIFF plug-in. # The MP record essentially consists of a TIFF file embedded in a JPEG # application marker. try: data = self.info["mp"] except KeyError: return None file_contents = io.BytesIO(data) head = file_contents.read(8) endianness = '>' if head[:4] == b'\x4d\x4d\x00\x2a' else '<' # process dictionary try: info = TiffImagePlugin.ImageFileDirectory_v2(head) info.load(file_contents) mp = dict(info) except: raise SyntaxError("malformed MP Index (unreadable directory)") # it's an error not to have a number of images try: quant = mp[0xB001] except KeyError: raise SyntaxError("malformed MP Index (no number of images)") # get MP entries mpentries = [] try: rawmpentries = mp[0xB002] for entrynum in range(0, quant): unpackedentry = unpack_from( '{0}LLLHH'.format(endianness), rawmpentries, entrynum * 16) labels = ('Attribute', 'Size', 'DataOffset', 'EntryNo1', 'EntryNo2') mpentry = dict(zip(labels, unpackedentry)) mpentryattr = { 'DependentParentImageFlag': bool(mpentry['Attribute'] & (1 << 31)), 'DependentChildImageFlag': bool(mpentry['Attribute'] & (1 << 30)), 'RepresentativeImageFlag': bool(mpentry['Attribute'] & (1 << 29)), 'Reserved': (mpentry['Attribute'] & (3 << 27)) >> 27, 'ImageDataFormat': (mpentry['Attribute'] & (7 << 24)) >> 24, 'MPType': mpentry['Attribute'] & 0x00FFFFFF } if mpentryattr['ImageDataFormat'] == 0: mpentryattr['ImageDataFormat'] = 'JPEG' else: raise SyntaxError("unsupported picture format in MPO") mptypemap = { 0x000000: 'Undefined', 0x010001: 'Large Thumbnail (VGA Equivalent)', 0x010002: 'Large Thumbnail (Full HD Equivalent)', 0x020001: 'Multi-Frame Image (Panorama)', 0x020002: 'Multi-Frame Image: (Disparity)', 0x020003: 'Multi-Frame Image: (Multi-Angle)', 0x030000: 'Baseline MP Primary Image' } mpentryattr['MPType'] = mptypemap.get(mpentryattr['MPType'], 'Unknown') mpentry['Attribute'] = mpentryattr mpentries.append(mpentry) mp[0xB002] = mpentries except KeyError: raise SyntaxError("malformed MP Index (bad MP Entry)") # Next we should try and parse the individual image unique ID list; # we don't because I've never seen this actually used in a real MPO # file and so can't test it. return mp # -------------------------------------------------------------------- # stuff to save JPEG files RAWMODE = { "1": "L", "L": "L", "RGB": "RGB", "RGBA": "RGB", "RGBX": "RGB", "CMYK": "CMYK;I", # assume adobe conventions "YCbCr": "YCbCr", } zigzag_index = (0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63) samplings = {(1, 1, 1, 1, 1, 1): 0, (2, 1, 1, 1, 1, 1): 1, (2, 2, 1, 1, 1, 1): 2, } def convert_dict_qtables(qtables): qtables = [qtables[key] for key in range(len(qtables)) if key in qtables] for idx, table in enumerate(qtables): qtables[idx] = [table[i] for i in zigzag_index] return qtables def get_sampling(im): # There's no subsampling when image have only 1 layer # (grayscale images) or when they are CMYK (4 layers), # so set subsampling to default value. # # NOTE: currently Pillow can't encode JPEG to YCCK format. # If YCCK support is added in the future, subsampling code will have # to be updated (here and in JpegEncode.c) to deal with 4 layers. if not hasattr(im, 'layers') or im.layers in (1, 4): return -1 sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3] return samplings.get(sampling, -1) def _save(im, fp, filename): try: rawmode = RAWMODE[im.mode] except KeyError: raise IOError("cannot write mode %s as JPEG" % im.mode) if im.mode == 'RGBA': warnings.warn( 'You are saving RGBA image as JPEG. The alpha channel will be ' 'discarded. This conversion is deprecated and will be disabled ' 'in Pillow 3.7. Please, convert the image to RGB explicitly.', DeprecationWarning ) info = im.encoderinfo dpi = [int(round(x)) for x in info.get("dpi", (0, 0))] quality = info.get("quality", 0) subsampling = info.get("subsampling", -1) qtables = info.get("qtables") if quality == "keep": quality = 0 subsampling = "keep" qtables = "keep" elif quality in presets: preset = presets[quality] quality = 0 subsampling = preset.get('subsampling', -1) qtables = preset.get('quantization') elif not isinstance(quality, int): raise ValueError("Invalid quality setting") else: if subsampling in presets: subsampling = presets[subsampling].get('subsampling', -1) if isStringType(qtables) and qtables in presets: qtables = presets[qtables].get('quantization') if subsampling == "4:4:4": subsampling = 0 elif subsampling == "4:2:2": subsampling = 1 elif subsampling == "4:1:1": subsampling = 2 elif subsampling == "keep": if im.format != "JPEG": raise ValueError( "Cannot use 'keep' when original image is not a JPEG") subsampling = get_sampling(im) def validate_qtables(qtables): if qtables is None: return qtables if isStringType(qtables): try: lines = [int(num) for line in qtables.splitlines() for num in line.split('#', 1)[0].split()] except ValueError: raise ValueError("Invalid quantization table") else: qtables = [lines[s:s+64] for s in range(0, len(lines), 64)] if isinstance(qtables, (tuple, list, dict)): if isinstance(qtables, dict): qtables = convert_dict_qtables(qtables) elif isinstance(qtables, tuple): qtables = list(qtables) if not (0 < len(qtables) < 5): raise ValueError("None or too many quantization tables") for idx, table in enumerate(qtables): try: if len(table) != 64: raise table = array.array('B', table) except TypeError: raise ValueError("Invalid quantization table") else: qtables[idx] = list(table) return qtables if qtables == "keep": if im.format != "JPEG": raise ValueError( "Cannot use 'keep' when original image is not a JPEG") qtables = getattr(im, "quantization", None) qtables = validate_qtables(qtables) extra = b"" icc_profile = info.get("icc_profile") if icc_profile: ICC_OVERHEAD_LEN = 14 MAX_BYTES_IN_MARKER = 65533 MAX_DATA_BYTES_IN_MARKER = MAX_BYTES_IN_MARKER - ICC_OVERHEAD_LEN markers = [] while icc_profile: markers.append(icc_profile[:MAX_DATA_BYTES_IN_MARKER]) icc_profile = icc_profile[MAX_DATA_BYTES_IN_MARKER:] i = 1 for marker in markers: size = struct.pack(">H", 2 + ICC_OVERHEAD_LEN + len(marker)) extra += (b"\xFF\xE2" + size + b"ICC_PROFILE\0" + o8(i) + o8(len(markers)) + marker) i += 1 # "progressive" is the official name, but older documentation # says "progression" # FIXME: issue a warning if the wrong form is used (post-1.1.7) progressive = info.get("progressive", False) or\ info.get("progression", False) optimize = info.get("optimize", False) # get keyword arguments im.encoderconfig = ( quality, progressive, info.get("smooth", 0), optimize, info.get("streamtype", 0), dpi[0], dpi[1], subsampling, qtables, extra, info.get("exif", b"") ) # if we optimize, libjpeg needs a buffer big enough to hold the whole image # in a shot. Guessing on the size, at im.size bytes. (raw pizel size is # channels*size, this is a value that's been used in a django patch. # https://github.com/matthewwithanm/django-imagekit/issues/50 bufsize = 0 if optimize or progressive: # keep sets quality to 0, but the actual value may be high. if quality >= 95 or quality == 0: bufsize = 2 * im.size[0] * im.size[1] else: bufsize = im.size[0] * im.size[1] # The exif info needs to be written as one block, + APP1, + one spare byte. # Ensure that our buffer is big enough bufsize = max(ImageFile.MAXBLOCK, bufsize, len(info.get("exif", b"")) + 5) ImageFile._save(im, fp, [("jpeg", (0, 0)+im.size, 0, rawmode)], bufsize) def _save_cjpeg(im, fp, filename): # ALTERNATIVE: handle JPEGs via the IJG command line utilities. import os import subprocess tempfile = im._dump() subprocess.check_call(["cjpeg", "-outfile", filename, tempfile]) try: os.unlink(tempfile) except OSError: pass ## # Factory for making JPEG and MPO instances def jpeg_factory(fp=None, filename=None): im = JpegImageFile(fp, filename) try: mpheader = im._getmp() if mpheader[45057] > 1: # It's actually an MPO from .MpoImagePlugin import MpoImageFile im = MpoImageFile(fp, filename) except (TypeError, IndexError): # It is really a JPEG pass except SyntaxError: warnings.warn("Image appears to be a malformed MPO file, it will be " "interpreted as a base JPEG file") return im # -------------------------------------------------------------------q- # Registry stuff Image.register_open(JpegImageFile.format, jpeg_factory, _accept) Image.register_save(JpegImageFile.format, _save) Image.register_extension(JpegImageFile.format, ".jfif") Image.register_extension(JpegImageFile.format, ".jpe") Image.register_extension(JpegImageFile.format, ".jpg") Image.register_extension(JpegImageFile.format, ".jpeg") Image.register_mime(JpegImageFile.format, "image/jpeg")
{ "content_hash": "3f69d50b742c8e21da15c2c58af1a675", "timestamp": "", "source": "github", "line_count": 736, "max_line_length": 79, "avg_line_length": 34.08423913043478, "alnum_prop": 0.555608706051184, "repo_name": "Ali-aqrabawi/ezclinic", "id": "ef229e61157cc2a03c538b9d4d72beb35507674a", "size": "26462", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "lib/PIL/JpegImagePlugin.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "95195" }, { "name": "HTML", "bytes": "233888" }, { "name": "JavaScript", "bytes": "3747108" }, { "name": "Python", "bytes": "6361738" } ], "symlink_target": "" }
package mpasswd import ( "testing" ) func TestHashPasswd(t *testing.T) { passwd := "demo" hashPasswd, _ := GenerateHashPassword(passwd) if CompareHashAndPassword(hashPasswd, "demo") != nil { t.Error("hashpasswd and provide passwd not equal.") } }
{ "content_hash": "7ed06f561a39eed742a84e2e9128be12", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 55, "avg_line_length": 17.2, "alnum_prop": 0.7015503875968992, "repo_name": "mabetle/mgo", "id": "330915bb9d001be4901b95cbf09a767bd7ac580e", "size": "258", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "mcore/mpasswd/hash_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "338930" }, { "name": "Makefile", "bytes": "764" } ], "symlink_target": "" }
![Image](http://www.team-arg.org/masterfiles/team-arg-frmp/images/banner-ID-48.png) Fantasy Rampage : http://www.team-arg.org/frmp-manual.html **Download latest Arduboy version and source :** https://github.com/TEAMarg/ID-48-Fantasy-Rampage/releases/latest MADE by TEAM a.r.g. : http://www.team-arg.org/more-about.html 2017 - Trodoss - JO3RI
{ "content_hash": "4d0530f4e00235fd017b799b3a1bbdf2", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 115, "avg_line_length": 49.857142857142854, "alnum_prop": 0.7363896848137536, "repo_name": "TEAMarg/ID-48-Fantasy-Rampage", "id": "943c60973ba782804b6a8fc7481ea86c48842ab4", "size": "367", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "1213" }, { "name": "C", "bytes": "81845" }, { "name": "C++", "bytes": "3293" }, { "name": "Objective-C", "bytes": "20514" } ], "symlink_target": "" }
package com.zx.crawler.stock.util; import java.net.URL; import java.net.URLConnection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; public class DocumentUtil { public static Document getDocument(String url) throws Exception { Document doc = null; try { URLConnection conn = new URL(url).openConnection(); conn.setConnectTimeout(10000); doc = Jsoup.parse(conn.getInputStream(), "gbk", url); return doc; } catch (Exception e) { throw e; } } }
{ "content_hash": "0c9ed07cee555a3ac248a395f26ba956", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 69, "avg_line_length": 26.476190476190474, "alnum_prop": 0.6205035971223022, "repo_name": "pipingyishi/test", "id": "59a43baed6cf20817d2a6b0bf9fcd57638a202df", "size": "556", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "net-crawler/src/main/java/com/zx/crawler/stock/util/DocumentUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "105925" }, { "name": "HTML", "bytes": "96750" }, { "name": "Java", "bytes": "526385" }, { "name": "JavaScript", "bytes": "215528" }, { "name": "Shell", "bytes": "15042" } ], "symlink_target": "" }
import io import json import os import unittest from . import conformance from .fhirdate import FHIRDate class ConformanceTests(unittest.TestCase): def instantiate_from(self, filename): datadir = os.environ.get('FHIR_UNITTEST_DATADIR') or '' with io.open(os.path.join(datadir, filename), 'r', encoding='utf-8') as handle: js = json.load(handle) self.assertEqual("Conformance", js["resourceType"]) return conformance.Conformance(js) def testConformance1(self): inst = self.instantiate_from("conformance-example.json") self.assertIsNotNone(inst, "Must have instantiated a Conformance instance") self.implConformance1(inst) js = inst.as_json() self.assertEqual("Conformance", js["resourceType"]) inst2 = conformance.Conformance(js) self.implConformance1(inst2) def implConformance1(self, inst): self.assertEqual(inst.acceptUnknown, "both") self.assertEqual(inst.contact[0].name, "System Administrator") self.assertEqual(inst.contact[0].telecom[0].system, "email") self.assertEqual(inst.contact[0].telecom[0].value, "wile@acme.org") self.assertEqual(inst.copyright, "Copyright © Acme Healthcare and GoodCorp EHR Systems") self.assertEqual(inst.date.date, FHIRDate("2012-01-04").date) self.assertEqual(inst.date.as_json(), "2012-01-04") self.assertEqual(inst.description, "This is the FHIR conformance statement for the main EHR at ACME for the private interface - it does not describe the public interface") self.assertEqual(inst.document[0].documentation, "Basic rules for all documents in the EHR system") self.assertEqual(inst.document[0].mode, "consumer") self.assertTrue(inst.experimental) self.assertEqual(inst.fhirVersion, "1.0.0") self.assertEqual(inst.format[0], "xml") self.assertEqual(inst.format[1], "json") self.assertEqual(inst.id, "example") self.assertEqual(inst.implementation.description, "main EHR at ACME") self.assertEqual(inst.implementation.url, "http://10.2.3.4/fhir") self.assertEqual(inst.kind, "instance") self.assertEqual(inst.messaging[0].documentation, "ADT A08 equivalent for external system notifications") self.assertEqual(inst.messaging[0].endpoint[0].address, "mllp:10.1.1.10:9234") self.assertEqual(inst.messaging[0].endpoint[0].protocol.code, "mllp") self.assertEqual(inst.messaging[0].endpoint[0].protocol.system, "http://hl7.org/fhir/message-transport") self.assertEqual(inst.messaging[0].event[0].category, "Consequence") self.assertEqual(inst.messaging[0].event[0].code.code, "admin-notify") self.assertEqual(inst.messaging[0].event[0].code.system, "http://hl7.org/fhir/message-type") self.assertEqual(inst.messaging[0].event[0].documentation, "Notification of an update to a patient resource. changing the links is not supported") self.assertEqual(inst.messaging[0].event[0].focus, "Patient") self.assertEqual(inst.messaging[0].event[0].mode, "receiver") self.assertEqual(inst.messaging[0].reliableCache, 30) self.assertEqual(inst.name, "ACME EHR Conformance statement") self.assertEqual(inst.publisher, "ACME Corporation") self.assertEqual(inst.requirements, "Main EHR conformance statement, published for contracting and operational support") self.assertEqual(inst.rest[0].compartment[0], "http://hl7.org/fhir/compartment/Patient") self.assertEqual(inst.rest[0].documentation, "Main FHIR endpoint for acem health") self.assertEqual(inst.rest[0].interaction[0].code, "transaction") self.assertEqual(inst.rest[0].interaction[1].code, "history-system") self.assertEqual(inst.rest[0].mode, "server") self.assertTrue(inst.rest[0].resource[0].conditionalCreate) self.assertEqual(inst.rest[0].resource[0].conditionalDelete, "not-supported") self.assertFalse(inst.rest[0].resource[0].conditionalUpdate) self.assertEqual(inst.rest[0].resource[0].interaction[0].code, "read") self.assertEqual(inst.rest[0].resource[0].interaction[1].code, "vread") self.assertEqual(inst.rest[0].resource[0].interaction[1].documentation, "Only supported for patient records since 12-Dec 2012") self.assertEqual(inst.rest[0].resource[0].interaction[2].code, "update") self.assertEqual(inst.rest[0].resource[0].interaction[3].code, "history-instance") self.assertEqual(inst.rest[0].resource[0].interaction[4].code, "create") self.assertEqual(inst.rest[0].resource[0].interaction[5].code, "history-type") self.assertTrue(inst.rest[0].resource[0].readHistory) self.assertEqual(inst.rest[0].resource[0].searchInclude[0], "Organization") self.assertEqual(inst.rest[0].resource[0].searchParam[0].definition, "http://hl7.org/fhir/SearchParameter/Patient-identifier") self.assertEqual(inst.rest[0].resource[0].searchParam[0].documentation, "Only supports search by institution MRN") self.assertEqual(inst.rest[0].resource[0].searchParam[0].modifier[0], "missing") self.assertEqual(inst.rest[0].resource[0].searchParam[0].name, "identifier") self.assertEqual(inst.rest[0].resource[0].searchParam[0].type, "token") self.assertEqual(inst.rest[0].resource[0].searchParam[1].chain[0], "name") self.assertEqual(inst.rest[0].resource[0].searchParam[1].chain[1], "identifier") self.assertEqual(inst.rest[0].resource[0].searchParam[1].definition, "http://hl7.org/fhir/SearchParameter/Patient-careprovider") self.assertEqual(inst.rest[0].resource[0].searchParam[1].modifier[0], "missing") self.assertEqual(inst.rest[0].resource[0].searchParam[1].name, "careprovider") self.assertEqual(inst.rest[0].resource[0].searchParam[1].target[0], "Organization") self.assertEqual(inst.rest[0].resource[0].searchParam[1].type, "reference") self.assertEqual(inst.rest[0].resource[0].searchRevInclude[0], "Person") self.assertEqual(inst.rest[0].resource[0].type, "Patient") self.assertFalse(inst.rest[0].resource[0].updateCreate) self.assertEqual(inst.rest[0].resource[0].versioning, "versioned-update") self.assertEqual(inst.rest[0].security.certificate[0].blob, "IHRoaXMgYmxvYiBpcyBub3QgdmFsaWQ=") self.assertEqual(inst.rest[0].security.certificate[0].type, "application/jwt") self.assertTrue(inst.rest[0].security.cors) self.assertEqual(inst.rest[0].security.description, "See Smart on FHIR documentation") self.assertEqual(inst.rest[0].security.service[0].coding[0].code, "SMART-on-FHIR") self.assertEqual(inst.rest[0].security.service[0].coding[0].system, "http://hl7.org/fhir/restful-security-service") self.assertEqual(inst.software.name, "EHR") self.assertEqual(inst.software.releaseDate.date, FHIRDate("2012-01-04").date) self.assertEqual(inst.software.releaseDate.as_json(), "2012-01-04") self.assertEqual(inst.software.version, "0.00.020.2134") self.assertEqual(inst.status, "draft") self.assertEqual(inst.text.status, "generated") self.assertEqual(inst.url, "68D043B5-9ECF-4559-A57A-396E0D452311") self.assertEqual(inst.version, "20130510") def testConformance2(self): inst = self.instantiate_from("conformance-phr-example.json") self.assertIsNotNone(inst, "Must have instantiated a Conformance instance") self.implConformance2(inst) js = inst.as_json() self.assertEqual("Conformance", js["resourceType"]) inst2 = conformance.Conformance(js) self.implConformance2(inst2) def implConformance2(self, inst): self.assertEqual(inst.acceptUnknown, "no") self.assertEqual(inst.contact[0].telecom[0].system, "other") self.assertEqual(inst.contact[0].telecom[0].value, "http://hl7.org/fhir") self.assertEqual(inst.date.date, FHIRDate("2013-06-18").date) self.assertEqual(inst.date.as_json(), "2013-06-18") self.assertEqual(inst.description, "Prototype Conformance Statement for September 2013 Connectathon") self.assertEqual(inst.fhirVersion, "1.0.0") self.assertEqual(inst.format[0], "json") self.assertEqual(inst.format[1], "xml") self.assertEqual(inst.id, "phr") self.assertEqual(inst.kind, "capability") self.assertEqual(inst.name, "PHR Template") self.assertEqual(inst.publisher, "FHIR Project") self.assertEqual(inst.rest[0].documentation, "Protoype server conformance statement for September 2013 Connectathon") self.assertEqual(inst.rest[0].mode, "server") self.assertEqual(inst.rest[0].resource[0].interaction[0].code, "read") self.assertEqual(inst.rest[0].resource[0].interaction[1].code, "search-type") self.assertEqual(inst.rest[0].resource[0].interaction[1].documentation, "When a client searches patients with no search criteria, they get a list of all patients they have access too. Servers may elect to offer additional search parameters, but this is not required") self.assertEqual(inst.rest[0].resource[0].type, "Patient") self.assertEqual(inst.rest[0].resource[1].interaction[0].code, "read") self.assertEqual(inst.rest[0].resource[1].interaction[1].code, "search-type") self.assertEqual(inst.rest[0].resource[1].searchParam[0].documentation, "_id parameter always supported. For the connectathon, servers may elect which search parameters are supported") self.assertEqual(inst.rest[0].resource[1].searchParam[0].name, "_id") self.assertEqual(inst.rest[0].resource[1].searchParam[0].type, "token") self.assertEqual(inst.rest[0].resource[1].type, "DocumentReference") self.assertEqual(inst.rest[0].resource[2].interaction[0].code, "read") self.assertEqual(inst.rest[0].resource[2].interaction[1].code, "search-type") self.assertEqual(inst.rest[0].resource[2].searchParam[0].documentation, "Standard _id parameter") self.assertEqual(inst.rest[0].resource[2].searchParam[0].name, "_id") self.assertEqual(inst.rest[0].resource[2].searchParam[0].type, "token") self.assertEqual(inst.rest[0].resource[2].type, "Condition") self.assertEqual(inst.rest[0].resource[3].interaction[0].code, "read") self.assertEqual(inst.rest[0].resource[3].interaction[1].code, "search-type") self.assertEqual(inst.rest[0].resource[3].searchParam[0].documentation, "Standard _id parameter") self.assertEqual(inst.rest[0].resource[3].searchParam[0].name, "_id") self.assertEqual(inst.rest[0].resource[3].searchParam[0].type, "token") self.assertEqual(inst.rest[0].resource[3].searchParam[1].documentation, "which diagnostic discipline/department created the report") self.assertEqual(inst.rest[0].resource[3].searchParam[1].name, "service") self.assertEqual(inst.rest[0].resource[3].searchParam[1].type, "token") self.assertEqual(inst.rest[0].resource[3].type, "DiagnosticReport") self.assertEqual(inst.rest[0].security.service[0].text, "OAuth") self.assertEqual(inst.software.name, "ACME PHR Server") self.assertEqual(inst.text.status, "generated")
{ "content_hash": "d2586fa386e08b38a5377f3861f15ccb", "timestamp": "", "source": "github", "line_count": 163, "max_line_length": 275, "avg_line_length": 69.87116564417178, "alnum_prop": 0.6986565984722101, "repo_name": "all-of-us/raw-data-repository", "id": "37abfd901e6bbe39e28c186044988a703d537219", "size": "11515", "binary": false, "copies": "1", "ref": "refs/heads/devel", "path": "rdr_service/lib_fhir/fhirclient_1_0_6/models/conformance_tests.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Jupyter Notebook", "bytes": "1866" }, { "name": "Mako", "bytes": "1715" }, { "name": "Python", "bytes": "17040924" }, { "name": "R", "bytes": "2212" }, { "name": "Shell", "bytes": "92213" } ], "symlink_target": "" }
<resources> <string name="app_name">Unificiency</string> <string name="username">Email</string> <string name="password">Passwort</string> <string name="login">Login</string> <string name="register">Registrieren</string> <string name="nickname">Nickname</string> <string name="password_confirm">Passwort Wiederholen</string> <string name="major">Studiengang</string> <string name="creat_account">Konto anlegen</string> <string name="validation_email">Bitte eine gültige Email Adresse eingeben</string> <string name="validation_password">Passwort muss mindestens 6 Zeichen enthalten</string> <string name="validation_passwords_equal">Eingegebene Passwörter stimmen nicht überein</string> <string name="validation_topic">Topic muss mindestens 3 Zeichen enthalten</string> <string name="validation_nickname">Bitte einen Nickname eingeben</string> <string name="nav_item_buildings">Gebäude</string> <string name="nav_item_groups">Lerngruppen</string> <string name="nav_item_notes">Notizen</string> <string name="nav_item_setting">Profile</string> <string name="nav_item_account">Mein Konto</string> <string name="nav_item_logout">Abmelden</string> <!-- Groups Fragment --> <string name="groups_title">Lerngruppen</string> <string name="groups_new_group">Neue Gruppe erstellen</string> <string name="groups_details_description">Gruppenbeschreibung</string> <string name="groups_details_description_default">Diese Gruppe hat noch keine Beschreibung angegeben.</string> <string name="groups_details_members">Mitglieder</string> <string name="groups_details_join">Beitreten</string> <string name="groups_details_leave">Verlassen</string> <string name="groups_details_modify">Info Bearbeiten</string> <!-- Group Details --> <string name="groups_details_password_message">Passwort eingeben</string> <string name="groups_details_password_title">Diese Gruppe verlangt ein Passwort</string> <string name="groups_details_password_default">Hier Passwort eingeben</string> <string name="groups_details_password_send">Senden</string> <string name="groups_details_password_cancel">Abbrechen</string> <string name="groups_details_groupname_extra">groups_details_groupname</string> <string name="title_activity_group_details">GroupDetails</string> <string name="title_activity_maps">Map</string> <!-- Group --> <string name="groups_new_group_title">Neue Gruppe erstellen</string> <string name="groups_new_group_create">Erstellen</string> <string name="groups_new_group_information">Hier kannst du eine neue Lerngruppe erstellen. Wenn du kein Passwort eingibst, kann jeder der Gruppe beitreten.</string> <string name="groups_new_group_groupname">Gruppenname eingeben</string> <string name="groups_new_group_topic">Topic eingeben</string> <string name="groups_new_group_description">Gruppenbeschreibung eingeben</string> <string name="groups_new_group_password">Passwort eingeben (optional)</string> <string name="groups_new_group_error_description">Bitte mindestens 10 Zeichen eingeben!</string> <string name="groups_edit_group_save">Speichern</string> <string name="groups_edit_group_information">Hier kannst du die Beschreibung und Topic der Gruppe anpassen.</string> <!-- Notes --> <string name="notes_new_note_title">Neue Notiz erstellen</string> <string name="addPhoto_new_note">Bild hinzufügen</string> <string name="notes_new_goupsName_spinner">Gruppname auswälhen:</string> <string name="note_detail">Notizdetail</string> <string name="preview">Notiz Vorschau</string> <string name="notes_new_note_topic">Topic eingeben</string> <string name="notes_new_note_create">Erstellen</string> <string name="notes_new_note_name">Notizenname eingeben</string> <string name="notes_new_note_content">Notizinhalt eingeben</string> <string name="notes_new_note_password">Passwort eingeben (optional)</string> <string name="notes_new_note_information">Hier kannst du eine neue Notiz erstellen. Du kannst bei Bedarf auch ein Foto von der Kamera bzw. Gallerie auswählen und zur Notiz hinzufügen.</string> <string name="notes_edit_note_information">Hier kannst du diese Notiz bearbeiten.</string> <!-- Settings and Eidt --> <string name="setting_hint">Hier kannst du die Benachrichtigungen einstellen.</string> <string name="edit_hint">, hier kannst du deine Profile aktualisieren. Lass die Passwörter Felder leer, wenn du sie nicht ändern willst.</string> <string name="toolbar_edit_profile">Profile editieren</string> <string name="toolbar_edit_note">Notiz editieren</string> <string name="toolbar_edit_group">Gruppe editieren</string> <string name="exit">Abmeldung</string> <string name="camera_album">Kamera oder Galerie auswählen</string> <string name="dialog_exit">Unificieny beenden?</string> <!-- Server Feedback --> <string name="server_error">Fehler beim Server, bitte später nochmal versuchen</string> <!-- General --> <string name="save">Speichern</string> <string name="edit">Bearbeiten</string> <string name="fav">Favorisieren</string> <string name="unfav">Nicht mehr Mögen</string> <string name="remove">Löschen</string> <string name="yes">Ja</string> <string name="cancel">Abbrechen</string> <string name="invalid_input">Eingaben sind fehlerhaft. Bitte nochmal überprüfen!</string> <string name="there_letters_min">Bitte mindestens 3 Zeichen eingeben!</string> </resources>
{ "content_hash": "6fc2121167b8b821cd8a7f12dd9d607a", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 196, "avg_line_length": 56.61616161616162, "alnum_prop": 0.7302408563782338, "repo_name": "zhenhaoli/Unificiency", "id": "60011bb84e54a8050bc38188d610db672242af2f", "size": "5621", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "UnificiencyAndroid/app/src/main/res/values/strings.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "101" }, { "name": "HTML", "bytes": "8383" }, { "name": "Java", "bytes": "183708" }, { "name": "JavaScript", "bytes": "27246" } ], "symlink_target": "" }
<?php /** * @namespace */ namespace Yandex\Dictionary; use Yandex\Dictionary\DictionaryBaseItem; use Yandex\Dictionary\DictionaryExample; /** * Class DictionaryTranslation * * @category Yandex * @package Dictionary * * @author Nikolay Oleynikov <oleynikovny@mail.ru> * @created 07.11.14 20:05 */ class DictionaryTranslation extends DictionaryBaseItem { /** * @var */ protected $synonyms = array(); /** * @var */ protected $meanings = array(); /** * @var */ protected $examples = array(); /** * */ public function __construct($translation) { parent::__construct($translation); if (isset($translation->syn)) { foreach ($translation->syn as $synonym) { $this->synonyms[] = new DictionaryBaseItem($synonym); } } if (isset($translation->mean)) { foreach ($translation->mean as $meaning) { $this->meanings[] = new DictionaryBaseItem($meaning); } } if (isset($translation->ex)) { foreach ($translation->ex as $example) { $this->examples[] = new DictionaryExample($example); } } } /** * @return array */ public function getSynonyms() { return $this->synonyms; } /** * @return array */ public function getMeanings() { return $this->meanings; } /** * @return array */ public function getExamples() { return $this->examples; } }
{ "content_hash": "2b0ec4774a5ebeeef1314a8c9cfbc14a", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 69, "avg_line_length": 18.261363636363637, "alnum_prop": 0.5245799626633478, "repo_name": "malinink/yandex-php-library", "id": "363b2c7fc5fe21b56f08073f887ab075aa8fad39", "size": "1732", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Yandex/Dictionary/DictionaryTranslation.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "534984" } ], "symlink_target": "" }
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.1-master-342ee53 */ md-toolbar.md-menu-toolbar h2.md-toolbar-tools { line-height: 1rem; height: auto; padding: 28px; padding-bottom: 12px; } md-toolbar.md-has-open-menu { position: relative; z-index: 100; } md-menu-bar { padding: 0 20px; display: block; position: relative; z-index: 2; } md-menu-bar .md-menu { display: inline-block; padding: 0; position: relative; } md-menu-bar button { font-size: 14px; padding: 0 10px; margin: 0; border: 0; background-color: transparent; height: 40px; } md-menu-bar md-backdrop.md-menu-backdrop { z-index: -2; } md-menu-content.md-menu-bar-menu.md-dense { max-height: none; padding: 16px 0; } md-menu-content.md-menu-bar-menu.md-dense md-menu-item.md-indent { position: relative; } md-menu-content.md-menu-bar-menu.md-dense md-menu-item.md-indent > md-icon { position: absolute; padding: 0; width: 24px; top: 6px; left: 24px; } [dir=rtl] md-menu-content.md-menu-bar-menu.md-dense md-menu-item.md-indent > md-icon { left: auto; right: 24px; } md-menu-content.md-menu-bar-menu.md-dense md-menu-item.md-indent > .md-button, md-menu-content.md-menu-bar-menu.md-dense md-menu-item.md-indent .md-menu > .md-button { padding: 0 32px 0 64px; } [dir=rtl] md-menu-content.md-menu-bar-menu.md-dense md-menu-item.md-indent > .md-button, [dir=rtl] md-menu-content.md-menu-bar-menu.md-dense md-menu-item.md-indent .md-menu > .md-button { padding: 0 64px 0 32px; } md-menu-content.md-menu-bar-menu.md-dense .md-button { min-height: 0; height: 32px; display: -webkit-box; display: -webkit-flex; display: flex; } md-menu-content.md-menu-bar-menu.md-dense .md-button span { -webkit-box-flex: 1; -webkit-flex-grow: 1; flex-grow: 1; } md-menu-content.md-menu-bar-menu.md-dense .md-button span.md-alt-text { -webkit-box-flex: 0; -webkit-flex-grow: 0; flex-grow: 0; -webkit-align-self: flex-end; align-self: flex-end; margin: 0 8px; } md-menu-content.md-menu-bar-menu.md-dense md-menu-divider { margin: 8px 0; } md-menu-content.md-menu-bar-menu.md-dense md-menu-item > .md-button, md-menu-content.md-menu-bar-menu.md-dense .md-menu > .md-button { text-align: left; } [dir=rtl] md-menu-content.md-menu-bar-menu.md-dense md-menu-item > .md-button, [dir=rtl] md-menu-content.md-menu-bar-menu.md-dense .md-menu > .md-button { text-align: right; } md-menu-content.md-menu-bar-menu.md-dense .md-menu { padding: 0; } md-menu-content.md-menu-bar-menu.md-dense .md-menu > .md-button { position: relative; margin: 0; width: 100%; text-transform: none; font-weight: normal; border-radius: 0px; padding-left: 16px; } [dir=rtl] md-menu-content.md-menu-bar-menu.md-dense .md-menu > .md-button { padding-left: 0; padding-right: 16px; } md-menu-content.md-menu-bar-menu.md-dense .md-menu > .md-button:after { display: block; content: '\25BC'; position: absolute; top: 0px; speak: none; -webkit-transform: rotate(270deg) scaleY(0.45) scaleX(0.9); transform: rotate(270deg) scaleY(0.45) scaleX(0.9); right: 28px; } [dir=rtl] md-menu-content.md-menu-bar-menu.md-dense .md-menu > .md-button:after { -webkit-transform: rotate(90deg) scaleY(0.45) scaleX(0.9); transform: rotate(90deg) scaleY(0.45) scaleX(0.9); } [dir=rtl] md-menu-content.md-menu-bar-menu.md-dense .md-menu > .md-button:after { right: auto; left: 28px; }
{ "content_hash": "00cd3db392fd38102b923d635e400e3d", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 193, "avg_line_length": 36.69230769230769, "alnum_prop": 0.6176624737945493, "repo_name": "andream91/fusion-form", "id": "0c36940f1939d7e17a5dfeacd35a797aa65f1b63", "size": "3816", "binary": false, "copies": "4", "ref": "refs/heads/fusion-form", "path": "app/jspm_packages/github/angular/bower-material@master/modules/closure/menuBar/menuBar.css", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "106" }, { "name": "Batchfile", "bytes": "250" }, { "name": "C#", "bytes": "1090" }, { "name": "CSS", "bytes": "3642297" }, { "name": "HTML", "bytes": "54471" }, { "name": "Java", "bytes": "8887" }, { "name": "JavaScript", "bytes": "5838413" }, { "name": "Makefile", "bytes": "194" }, { "name": "Shell", "bytes": "1255" } ], "symlink_target": "" }
import { test } from 'qunit'; import moduleForAcceptance from '../helpers/module-for-acceptance'; moduleForAcceptance('Acceptance: Filters Test', { beforeEach() { this.store = this.application.__container__.lookup('service:simple-store'); }, afterEach() { this.store = null; } }); test('push will trigger filter for each subscription', function(assert) { visit('/filters'); andThen(() => { assert.equal(find('.one').find('option').length, 3); assert.equal(find('.two').find('option').length, 3); assert.equal(find('.three').find('option').length, 3); assert.equal(find('.four').find('option').length, 3); this.store.push('robot', {id: 2, size: 20}); this.store.push('robot', {id: 1, size: 10}); this.store.push('robot', {id: 3, size: 30}); this.store.push('zing', {id: 2, number: 80}); this.store.push('zing', {id: 1, number: 90}); this.store.push('zing', {id: 3, number: 70}); }); andThen(() => { assert.equal(find('.one').find('option').length, 0); assert.equal(find('.two').find('option').length, 2); assert.equal(find('.three').find('option').length, 0); assert.equal(find('.four').find('option').length, 2); }); }); test('filters can be thrown out when you navigate away from a given route', function(assert) { visit('/filters'); andThen(() => { assert.equal(currentURL(), '/filters'); let filtersMap = this.store.get('filtersMap'); let robotFilters = filtersMap['robot']; let zingFilters = filtersMap['zing']; assert.equal(robotFilters.length, 2); assert.equal(zingFilters.length, 2); }); click('.link-robots'); andThen(() => { assert.equal(currentURL(), '/robots'); let filtersMap = this.store.get('filtersMap'); let robotFilters = filtersMap['robot']; let zingFilters = filtersMap['zing']; //the filters route did cleanup so removed the filters used :) assert.equal(robotFilters.length, 2); assert.equal(zingFilters.length, 0); }); click('.link-wat'); andThen(() => { assert.equal(currentURL(), '/wat'); let filtersMap = this.store.get('filtersMap'); let robotFilters = filtersMap['robot']; let zingFilters = filtersMap['zing']; //the robots route did not cleanup so we now have a memory leak :( assert.equal(robotFilters.length, 2); assert.equal(zingFilters.length, 0); }); click('.link-filters'); andThen(() => { assert.equal(currentURL(), '/filters'); let filtersMap = this.store.get('filtersMap'); let robotFilters = filtersMap['robot']; let zingFilters = filtersMap['zing']; //the wat route did not cleanup so we now have a memory leak :( assert.equal(robotFilters.length, 4); assert.equal(zingFilters.length, 2); }); }); test('filters on models with custom primary keys can be thrown out when you leave a route', function(assert) { visit('/custom-key'); andThen(() => { assert.equal(currentURL(), '/custom-key'); let filtersMap = this.store.get('filtersMap'); let customKeyFilters = filtersMap['custom-key']; assert.equal(customKeyFilters.length, 1); }); click('.link-wat'); andThen(() => { assert.equal(currentURL(), '/wat'); let filtersMap = this.store.get('filtersMap'); let customKeyFilters = filtersMap['custom-key']; assert.equal(customKeyFilters.length, 0); }); }); test('each filter function will be updated during a push with multiple listeners across multiple routes', function(assert) { visit('/filters'); andThen(() => { assert.equal(currentURL(), '/filters'); assert.equal(find('.one').find('option').length, 3); assert.equal(find('.two').find('option').length, 3); assert.equal(find('.three').find('option').length, 3); assert.equal(find('.four').find('option').length, 3); this.store.push('robot', {id: 2, size: 20}); this.store.push('robot', {id: 1, size: 10}); this.store.push('robot', {id: 3, size: 30}); this.store.push('zing', {id: 2, number: 80}); this.store.push('zing', {id: 1, number: 90}); this.store.push('zing', {id: 3, number: 70}); }); andThen(() => { assert.equal(find('.one').find('option').length, 0); assert.equal(find('.two').find('option').length, 2); assert.equal(find('.three').find('option').length, 0); assert.equal(find('.four').find('option').length, 2); }); click('.link-robots'); andThen(() => { assert.equal(currentURL(), '/robots'); assert.equal(find('.nine').find('option').length, 1); assert.equal(find('.eight').find('option').length, 1); this.store.push('robot', {id: 15, name: 'seven', size: 15}); }); andThen(() => { assert.equal(find('.nine').find('option').length, 1); assert.equal(find('.eight').find('option').length, 2); }); click('.link-filters'); andThen(() => { assert.equal(currentURL(), '/filters'); assert.equal(find('.one').find('option').length, 1); assert.equal(find('.two').find('option').length, 5); assert.equal(find('.three').find('option').length, 0); assert.equal(find('.four').find('option').length, 2); }); });
{ "content_hash": "3100b8dc29120aeeacb198d72aaf8f41", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 124, "avg_line_length": 39.11194029850746, "alnum_prop": 0.6077084525853844, "repo_name": "toranb/ember-cli-simple-store", "id": "f0c9fde11e0623e6f7a46c954718895d6163dde9", "size": "5241", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/acceptance/filters-test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "31" }, { "name": "HTML", "bytes": "5360" }, { "name": "JavaScript", "bytes": "139682" } ], "symlink_target": "" }
from __future__ import absolute_import from __future__ import print_function import numpy as np import pandas as pd np.random.seed(1337) # for reproducibility from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation from keras.layers.normalization import BatchNormalization from keras.layers.advanced_activations import PReLU from keras.utils import np_utils, generic_utils from keras.optimizers import Adam, SGD, Optimizer from keras.callbacks import Callback, EarlyStopping, ModelCheckpoint from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.metrics import confusion_matrix, log_loss from sklearn.ensemble import BaggingClassifier from sklearn.cross_validation import StratifiedKFold, KFold path = '../Data/' class LossHistory(Callback): def on_train_begin(self, logs={}): self.losses = [] def on_batch_end(self, batch, logs={}): self.losses.append(logs.get('loss')) def load_data(path, train=True): df = pd.read_csv(path) X = df.values.copy() if train: X, labels = X[:, 1:-1].astype(np.float32), X[:, -1] return X, labels else: X, ids = X[:, 1:].astype(np.float32), X[:, 0].astype(str) return X, ids def preprocess_data(X, scaler=None): if not scaler: scaler = StandardScaler() scaler.fit(X) X = scaler.transform(X) return X, scaler def preprocess_labels(labels, encoder=None, categorical=True): if not encoder: encoder = LabelEncoder() encoder.fit(labels) y = encoder.transform(labels).astype(np.int32) if categorical: y = np_utils.to_categorical(y) return y, encoder def make_submission(y_prob, ids, encoder, fname): with open(fname, 'w') as f: f.write('id,') f.write(','.join([str(i) for i in encoder.classes_])) f.write('\n') for i, probs in zip(ids, y_prob): probas = ','.join([i] + [str(p) for p in probs.tolist()]) f.write(probas) f.write('\n') print("Wrote submission to file {}.".format(fname)) print("Loading data...") X, labels = load_data(path+'train.csv', train=True) #X=np.log(X+1) #X=np.sqrt(X+(3/8)) X, scaler = preprocess_data(X) y, encoder = preprocess_labels(labels) X_test, ids = load_data(path+'test.csv', train=False) #X_test=np.log(X_test+1) #X_test=np.sqrt(X_test+(3/8)) X_test, _ = preprocess_data(X_test, scaler) nb_classes = y.shape[1] print(nb_classes, 'classes') dims = X.shape[1] print(dims, 'dims') sample = pd.read_csv(path+'sampleSubmission.csv') N = X.shape[0] trainId = np.array(range(N)) submissionTr = pd.DataFrame(index=trainId,columns=sample.columns[1:]) nfold=8 RND = np.random.randint(0,10000,nfold) pred = np.zeros((X_test.shape[0],9)) score = np.zeros(nfold) i=0 skf = StratifiedKFold(labels, nfold, random_state=1337) for tr, te in skf: X_train, X_valid, y_train, y_valid = X[tr], X[te], y[tr], y[te] predTr = np.zeros((X_valid.shape[0],9)) n_bag=10 for j in range(n_bag): print('nfold: ',i,'/',nfold, ' n_bag: ',j,' /',n_bag) print("Building model...") model = Sequential() model.add(Dense(512, input_shape=(dims,))) model.add(PReLU()) model.add(BatchNormalization()) model.add(Dropout(0.5)) model.add(Dense(512)) model.add(PReLU()) model.add(BatchNormalization()) model.add(Dropout(0.5)) model.add(Dense(nb_classes)) model.add(Activation('softmax')) ADAM=Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-8) sgd=SGD(lr=0.01, momentum=0.9, decay=1e-6, nesterov=True) model.compile(loss='categorical_crossentropy', optimizer="adam") print("Training model...") earlystopping=EarlyStopping(monitor='val_loss', patience=10, verbose=1) checkpointer = ModelCheckpoint(filepath=path+"tmp/weights.hdf5", verbose=0, save_best_only=True) model.fit(X_train, y_train, nb_epoch=1000, batch_size=128, verbose=2, validation_data=(X_valid,y_valid), callbacks=[earlystopping,checkpointer]) model.load_weights(path+"tmp/weights.hdf5") print("Generating submission...") pred += model.predict_proba(X_test) predTr += model.predict_proba(X_valid) predTr /= n_bag submissionTr.iloc[te] = predTr score[i]= log_loss(y_valid,predTr,eps=1e-15, normalize=True) print(score[i]) i+=1 pred /= (nfold * n_bag) print("ave: "+ str(np.average(score)) + "stddev: " + str(np.std(score))) make_submission(pred, ids, encoder, fname=path+'kerasNN2.csv') print(log_loss(labels,submissionTr.values,eps=1e-15, normalize=True)) submissionTr.to_csv(path+"kerasNN2_retrain.csv",index_label='id') # nfold 3, bagging 5: 0.4800704 + 0.005194 # nfold 3, bagging 10: 0.4764856 + 0.0060724 # nfold 5, bagging 5: 0.470483 + 0.011645 # nfold 5, bagging 10: 0.468049 + 0.0118616 # nfold 8, bagging 10: 0.469461 + 0.0100765 # tsne, nfold 5, bagging 5: 0.474645 + 0.0109076
{ "content_hash": "2e43eaa32554f3b23344cada07d50580", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 98, "avg_line_length": 32.44, "alnum_prop": 0.6789971228935471, "repo_name": "puyokw/kaggle_Otto", "id": "8902b1c965397ea2c03526ac1fdcedf15814dcb9", "size": "4866", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "new/src/1st_level/kerasNN2.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "54362" }, { "name": "R", "bytes": "40237" } ], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE476_NULL_Pointer_Dereference__null_check_after_deref_14.c Label Definition File: CWE476_NULL_Pointer_Dereference.pointflaw.label.xml Template File: point-flaw-14.tmpl.c */ /* * @description * CWE: 476 NULL Pointer Dereference * Sinks: null_check_after_deref * GoodSink: Do not check for NULL after the pointer has been dereferenced * BadSink : Check for NULL after a pointer has already been dereferenced * Flow Variant: 14 Control flow: if(globalFive==5) and if(globalFive!=5) * * */ #include "std_testcase.h" #ifndef OMITBAD void CWE476_NULL_Pointer_Dereference__null_check_after_deref_14_bad() { if(globalFive==5) { { int *intPointer = NULL; intPointer = (int *)malloc(sizeof(int)); *intPointer = 5; printIntLine(*intPointer); /* FLAW: Check for NULL after dereferencing the pointer. This NULL check is unnecessary. */ if (intPointer != NULL) { *intPointer = 10; } printIntLine(*intPointer); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* good1() uses if(globalFive!=5) instead of if(globalFive==5) */ static void good1() { if(globalFive!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { { int *intPointer = NULL; intPointer = (int *)malloc(sizeof(int)); *intPointer = 5; printIntLine(*intPointer); /* FIX: Don't check for NULL since we wouldn't reach this line if the pointer was NULL */ *intPointer = 10; printIntLine(*intPointer); } } } /* good2() reverses the bodies in the if statement */ static void good2() { if(globalFive==5) { { int *intPointer = NULL; intPointer = (int *)malloc(sizeof(int)); *intPointer = 5; printIntLine(*intPointer); /* FIX: Don't check for NULL since we wouldn't reach this line if the pointer was NULL */ *intPointer = 10; printIntLine(*intPointer); } } } void CWE476_NULL_Pointer_Dereference__null_check_after_deref_14_good() { good1(); good2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE476_NULL_Pointer_Dereference__null_check_after_deref_14_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE476_NULL_Pointer_Dereference__null_check_after_deref_14_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
{ "content_hash": "5bf9ed071f075cc5a4b1b12c2e9cfa25", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 103, "avg_line_length": 28.57894736842105, "alnum_prop": 0.5914671577655003, "repo_name": "JianpingZeng/xcc", "id": "717a8756d0d7f267028867463cfdd45a8c234797", "size": "3258", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "xcc/test/juliet/testcases/CWE476_NULL_Pointer_Dereference/CWE476_NULL_Pointer_Dereference__null_check_after_deref_14.c", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
google-site-verification: google1e1c30c8d5f52a9f.html
{ "content_hash": "8c30a3896d70f8b62a293a52c222a2e4", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 53, "avg_line_length": 53, "alnum_prop": 0.9056603773584906, "repo_name": "jhonoryza/blog", "id": "63fca8a6cb6e089b2166d7c4220e9fcc315f393b", "size": "53", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "google1e1c30c8d5f52a9f.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "23703" }, { "name": "HTML", "bytes": "9959" }, { "name": "JavaScript", "bytes": "125" }, { "name": "Ruby", "bytes": "481" } ], "symlink_target": "" }
 using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using IdentityAdmin.Core.Metadata; namespace IdentityAdmin.Extensions { public static class PropertyInfoExtensions { public static bool IsValidAsPropertyMetadata(this PropertyInfo property) { if (property == null) throw new ArgumentNullException("property"); if (property.IsReadOnly()) { return false; } var type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType; if (type.IsInterface) { return false; } if (type.IsClass && type != typeof(string)) { return false; } return true; } public static bool IsReadOnly(this PropertyInfo property) { if (property == null) throw new ArgumentNullException("property"); if (!property.CanWrite) return true; return property.GetCustomAttributes<ReadOnlyAttribute>(false) .Where(x=>x.IsReadOnly).Any(); } public static bool IsRequired(this PropertyInfo property) { if (property == null) throw new ArgumentNullException("property"); if (property.PropertyType.IsValueType && property.PropertyType.IsPrimitive) { return true; } return property.GetCustomAttributes<RequiredAttribute>().Any(); } public static string GetName(this PropertyInfo property) { if (property == null) throw new ArgumentNullException("property"); var display = property.GetCustomAttribute<DisplayAttribute>(); if (display != null) { return display.Name; } var displayName = property.GetCustomAttribute<DisplayNameAttribute>(); if (displayName != null) { return displayName.DisplayName; } return property.Name; } public static string[] GetEnumValues(this PropertyInfo property) { if (property == null) throw new ArgumentNullException("property"); var returnValue = new List<string>(); if (property.PropertyType.IsEnum) { MemberInfo[] memberInfos = property.PropertyType.GetMembers().Where(type => type.MemberType ==MemberTypes.Field ).ToArray(); for (int i = 0; i < memberInfos.Length; i++) { var name = memberInfos[i].Name; if (name != "value__") { returnValue.Add(memberInfos[i].Name); } } } return returnValue.ToArray(); } public static PropertyDataType GetPropertyDataType(this PropertyInfo property) { if (property == null) throw new ArgumentNullException("property"); var dataTypeAttr = property.GetCustomAttribute<DataTypeAttribute>(); if (dataTypeAttr != null) { switch(dataTypeAttr.DataType) { case DataType.Password: return PropertyDataType.Password; case DataType.EmailAddress: return PropertyDataType.Email; case DataType.Url: return PropertyDataType.Url; } } return property.PropertyType.GetPropertyDataType(); } public static PropertyDataType GetPropertyDataType(this Type type) { if (type == null) throw new ArgumentNullException("type"); type = Nullable.GetUnderlyingType(type) ?? type; if (type.IsEnum) { return PropertyDataType.Enum; } if (type.IsInterface) { return PropertyDataType.Enumerable; } if (type == typeof(bool)) { return PropertyDataType.Boolean; } if (type == typeof(short) || type == typeof(int) || type == typeof(long) || type == typeof(float) || type == typeof(double) || type == typeof(decimal)) { return PropertyDataType.Number; } return PropertyDataType.String; } } }
{ "content_hash": "3ff7108aec066685fc50054559bbd3a2", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 140, "avg_line_length": 30.21019108280255, "alnum_prop": 0.5224541429475016, "repo_name": "IdentityServer/IdentityServer3.Admin", "id": "fc4d46c03ee7916b98762d8661bc388b12058002", "size": "5353", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "source/Core/Extensions/PropertyInfoExtensions.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "32" }, { "name": "C#", "bytes": "450562" }, { "name": "CSS", "bytes": "549504" }, { "name": "HTML", "bytes": "67907" }, { "name": "JavaScript", "bytes": "220044" }, { "name": "PowerShell", "bytes": "3685" }, { "name": "Smalltalk", "bytes": "226" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_112) on Fri Jun 16 09:55:15 MST 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.wildfly.swarm.config.security.security_domain.ClassicIdentityTrust.ClassicIdentityTrustResources (Public javadocs 2017.6.1 API)</title> <meta name="date" content="2017-06-16"> <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 org.wildfly.swarm.config.security.security_domain.ClassicIdentityTrust.ClassicIdentityTrustResources (Public javadocs 2017.6.1 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <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="../../../../../../../org/wildfly/swarm/config/security/security_domain/ClassicIdentityTrust.ClassicIdentityTrustResources.html" title="class in org.wildfly.swarm.config.security.security_domain">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../overview-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 class="aboutLanguage">WildFly Swarm API, 2017.6.1</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/wildfly/swarm/config/security/security_domain/class-use/ClassicIdentityTrust.ClassicIdentityTrustResources.html" target="_top">Frames</a></li> <li><a href="ClassicIdentityTrust.ClassicIdentityTrustResources.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.wildfly.swarm.config.security.security_domain.ClassicIdentityTrust.ClassicIdentityTrustResources" class="title">Uses of Class<br>org.wildfly.swarm.config.security.security_domain.ClassicIdentityTrust.ClassicIdentityTrustResources</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="../../../../../../../org/wildfly/swarm/config/security/security_domain/ClassicIdentityTrust.ClassicIdentityTrustResources.html" title="class in org.wildfly.swarm.config.security.security_domain">ClassicIdentityTrust.ClassicIdentityTrustResources</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="#org.wildfly.swarm.config.security.security_domain">org.wildfly.swarm.config.security.security_domain</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.wildfly.swarm.config.security.security_domain"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/security/security_domain/ClassicIdentityTrust.ClassicIdentityTrustResources.html" title="class in org.wildfly.swarm.config.security.security_domain">ClassicIdentityTrust.ClassicIdentityTrustResources</a> in <a href="../../../../../../../org/wildfly/swarm/config/security/security_domain/package-summary.html">org.wildfly.swarm.config.security.security_domain</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="../../../../../../../org/wildfly/swarm/config/security/security_domain/package-summary.html">org.wildfly.swarm.config.security.security_domain</a> that return <a href="../../../../../../../org/wildfly/swarm/config/security/security_domain/ClassicIdentityTrust.ClassicIdentityTrustResources.html" title="class in org.wildfly.swarm.config.security.security_domain">ClassicIdentityTrust.ClassicIdentityTrustResources</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><a href="../../../../../../../org/wildfly/swarm/config/security/security_domain/ClassicIdentityTrust.ClassicIdentityTrustResources.html" title="class in org.wildfly.swarm.config.security.security_domain">ClassicIdentityTrust.ClassicIdentityTrustResources</a></code></td> <td class="colLast"><span class="typeNameLabel">ClassicIdentityTrust.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/security/security_domain/ClassicIdentityTrust.html#subresources--">subresources</a></span>()</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <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="../../../../../../../org/wildfly/swarm/config/security/security_domain/ClassicIdentityTrust.ClassicIdentityTrustResources.html" title="class in org.wildfly.swarm.config.security.security_domain">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../overview-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 class="aboutLanguage">WildFly Swarm API, 2017.6.1</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/wildfly/swarm/config/security/security_domain/class-use/ClassicIdentityTrust.ClassicIdentityTrustResources.html" target="_top">Frames</a></li> <li><a href="ClassicIdentityTrust.ClassicIdentityTrustResources.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2017 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "e0e06229d537564cf034c92128519233", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 503, "avg_line_length": 49.517857142857146, "alnum_prop": 0.6707536963577353, "repo_name": "wildfly-swarm/wildfly-swarm-javadocs", "id": "ecea9dbf52751d05dfb3e7355d6d5fd63197d3ef", "size": "8319", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "2017.6.1/apidocs/org/wildfly/swarm/config/security/security_domain/class-use/ClassicIdentityTrust.ClassicIdentityTrustResources.html", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package de.hbrs.aspgen.jparser.type; import de.hbrs.aspgen.api.ast.JavaParameter; public class Java6Parameter extends Java6BasicElement implements JavaParameter { private int startPosition; @Override public int getStartPosition() { return startPosition; } public void setStartPosition(final int startPosition) { this.startPosition = startPosition; } }
{ "content_hash": "b989955e80abe0e713620d7ae02e8222", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 80, "avg_line_length": 22.11111111111111, "alnum_prop": 0.7311557788944724, "repo_name": "FuriKuri/aspgen", "id": "6338918173302392958e77b09b4b1301a6d16ccd", "size": "398", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aspgen-java/src/main/java/de/hbrs/aspgen/jparser/type/Java6Parameter.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Groovy", "bytes": "10400" }, { "name": "Java", "bytes": "940791" }, { "name": "Shell", "bytes": "108" } ], "symlink_target": "" }
class Animal(object): def run(self): print('Animal is Running...') class Dog(Animal): def run(self): print('Dog is Running...') class Cat(Animal): pass def run_twice(animal): animal.run() animal.run() run_twice(Dog()) dog = Dog() dog.run() print(isinstance(dog, Dog)) print(isinstance(dog, Animal))
{ "content_hash": "9ddc84e40d624f0ea0f3f8c563da05c1", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 37, "avg_line_length": 15.5, "alnum_prop": 0.6129032258064516, "repo_name": "KrisCheng/HackerPractice", "id": "d9e2b2e887f133510965c8ae2e05c0876063ac63", "size": "368", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Python/oop/inherit.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "305" }, { "name": "HTML", "bytes": "57696" }, { "name": "JavaScript", "bytes": "83921" }, { "name": "Python", "bytes": "18233" } ], "symlink_target": "" }
package org.apache.jena.shared; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.jena.graph.test.GraphTestBase ; import org.apache.jena.shared.PrefixMapping ; /** Test prefix mappings - subclass this test and override getMapping() to deliver the prefixMapping to be tested. */ public abstract class AbstractTestPrefixMapping extends GraphTestBase { public AbstractTestPrefixMapping( String name ) { super( name ); } /** Subclasses implement to return a new, empty prefixMapping of their preferred kind. */ abstract protected PrefixMapping getMapping(); static final String crispURI = "http://crisp.nosuch.net/"; static final String ropeURI = "scheme:rope/string#"; static final String butterURI = "ftp://ftp.nowhere.at.all/cream#"; /** The empty prefix is specifically allowed [for the default namespace]. */ public void testEmptyPrefix() { PrefixMapping pm = getMapping(); pm.setNsPrefix( "", crispURI ); assertEquals( crispURI, pm.getNsPrefixURI( "" ) ); } static final String [] badNames = { "<hello>", "foo:bar", "with a space", "-argument" }; /** Test that various illegal names are trapped. */ public void testCheckNames() { PrefixMapping ns = getMapping(); for ( String bad : badNames ) { try { ns.setNsPrefix( bad, crispURI ); fail( "'" + bad + "' is an illegal prefix and should be trapped" ); } catch ( PrefixMapping.IllegalPrefixException e ) { pass(); } } } public void testNullURITrapped() { try { getMapping().setNsPrefix( "xy", null ); fail( "shouild trap null URI in setNsPrefix" ); } catch (NullPointerException e) { pass(); } } /** test that a PrefixMapping maps names to URIs. The names and URIs are all fully distinct - overlapping names/uris are dealt with in other tests. */ public void testPrefixMappingMapping() { String toast = "ftp://ftp.nowhere.not/"; assertDiffer( "crisp and toast must differ", crispURI, toast ); /* */ PrefixMapping ns = getMapping(); assertEquals( "crisp should be unset", null, ns.getNsPrefixURI( "crisp" ) ); assertEquals( "toast should be unset", null, ns.getNsPrefixURI( "toast" ) ); assertEquals( "butter should be unset", null, ns.getNsPrefixURI( "butter" ) ); /* */ ns.setNsPrefix( "crisp", crispURI ); assertEquals( "crisp should be set", crispURI, ns.getNsPrefixURI( "crisp" ) ); assertEquals( "toast should still be unset", null, ns.getNsPrefixURI( "toast" ) ); assertEquals( "butter should still be unset", null, ns.getNsPrefixURI( "butter" ) ); /* */ ns.setNsPrefix( "toast", toast ); assertEquals( "crisp should be set", crispURI, ns.getNsPrefixURI( "crisp" ) ); assertEquals( "toast should be set", toast, ns.getNsPrefixURI( "toast" ) ); assertEquals( "butter should still be unset", null, ns.getNsPrefixURI( "butter" ) ); } /** Test that we can run the prefix mapping in reverse - from URIs to prefixes. uriB is a prefix of uriA to try and ensure that the ordering of the map doesn't matter. */ public void testReversePrefixMapping() { PrefixMapping ns = getMapping(); String uriA = "http://jena.hpl.hp.com/A#", uriB = "http://jena.hpl.hp.com/"; String uriC = "http://jena.hpl.hp.com/Csharp/"; String prefixA = "aa", prefixB = "bb"; ns.setNsPrefix( prefixA, uriA ).setNsPrefix( prefixB, uriB ); assertEquals( null, ns.getNsURIPrefix( uriC) ); assertEquals( prefixA, ns.getNsURIPrefix( uriA ) ); assertEquals( prefixB, ns.getNsURIPrefix( uriB ) ); } /** test that we can extract a proper Map from a PrefixMapping */ public void testPrefixMappingMap() { PrefixMapping ns = getCrispyRope(); Map<String, String> map = ns.getNsPrefixMap(); assertEquals( "map should have two elements", 2, map.size() ); assertEquals( crispURI, map.get( "crisp" ) ); assertEquals( "scheme:rope/string#", map.get( "rope" ) ); } /** test that the Map returned by getNsPrefixMap does not alias (parts of) the secret internal map of the PrefixMapping */ public void testPrefixMappingSecret() { PrefixMapping ns = getCrispyRope(); Map<String, String> map = ns.getNsPrefixMap(); /* */ map.put( "crisp", "with/onions" ); map.put( "sandwich", "with/cheese" ); assertEquals( crispURI, ns.getNsPrefixURI( "crisp" ) ); assertEquals( ropeURI, ns.getNsPrefixURI( "rope" ) ); assertEquals( null, ns.getNsPrefixURI( "sandwich" ) ); } private PrefixMapping getCrispyRope() { PrefixMapping ns = getMapping(); ns.setNsPrefix( "crisp", crispURI); ns.setNsPrefix( "rope", ropeURI ); return ns; } /** these are strings that should not change when they are prefix-expanded with crisp and rope as legal prefixes. */ static final String [] dontChange = { "", "http://www.somedomain.something/whatever#", "crispy:cabbage", "cris:isOnInfiniteEarths", "rop:tangled/web", "roped:abseiling" }; /** these are the required mappings which the test cases below should satisfy: an array of 2-arrays, where element 0 is the string to expand and element 1 is the string it should expand to. */ static final String [][] expansions = { { "crisp:pathPart", crispURI + "pathPart" }, { "rope:partPath", ropeURI + "partPath" }, { "crisp:path:part", crispURI + "path:part" }, }; public void testExpandPrefix() { PrefixMapping ns = getMapping(); ns.setNsPrefix( "crisp", crispURI ); ns.setNsPrefix( "rope", ropeURI ); /* */ for ( String aDontChange : dontChange ) { assertEquals( "should be unchanged", aDontChange, ns.expandPrefix( aDontChange ) ); } /* */ for ( String[] expansion : expansions ) { assertEquals( "should expand correctly", expansion[1], ns.expandPrefix( expansion[0] ) ); } } public void testUseEasyPrefix() { testUseEasyPrefix( "prefix mapping impl", getMapping() ); testShortForm( "prefix mapping impl", getMapping() ); } public static void testUseEasyPrefix( String title, PrefixMapping ns ) { testShortForm( title, ns ); } public static void testShortForm( String title, PrefixMapping ns ) { ns.setNsPrefix( "crisp", crispURI ); ns.setNsPrefix( "butter", butterURI ); assertEquals( title, "", ns.shortForm( "" ) ); assertEquals( title, ropeURI, ns.shortForm( ropeURI ) ); assertEquals( title, "crisp:tail", ns.shortForm( crispURI + "tail" ) ); assertEquals( title, "butter:here:we:are", ns.shortForm( butterURI + "here:we:are" ) ); } public void testEasyQName() { PrefixMapping ns = getMapping(); String alphaURI = "http://seasonal.song/preamble/"; ns.setNsPrefix( "alpha", alphaURI ); assertEquals( "alpha:rowboat", ns.qnameFor( alphaURI + "rowboat" ) ); } public void testNoQNameNoPrefix() { PrefixMapping ns = getMapping(); String alphaURI = "http://seasonal.song/preamble/"; ns.setNsPrefix( "alpha", alphaURI ); assertEquals( null, ns.qnameFor( "eg:rowboat" ) ); } public void testNoQNameBadLocal() { PrefixMapping ns = getMapping(); String alphaURI = "http://seasonal.song/preamble/"; ns.setNsPrefix( "alpha", alphaURI ); assertEquals( null, ns.qnameFor( alphaURI + "12345" ) ); } /** The tests implied by the email where Chris suggested adding qnameFor; shortForm generates illegal qnames but qnameFor does not. */ public void testQnameFromEmail() { String uri = "http://some.long.uri/for/a/namespace#"; PrefixMapping ns = getMapping(); ns.setNsPrefix( "x", uri ); assertEquals( null, ns.qnameFor( uri ) ); assertEquals( null, ns.qnameFor( uri + "non/fiction" ) ); } /** test that we can add the maplets from another PrefixMapping without losing our own. */ public void testAddOtherPrefixMapping() { PrefixMapping a = getMapping(); PrefixMapping b = getMapping(); assertFalse( "must have two diffferent maps", a == b ); a.setNsPrefix( "crisp", crispURI ); a.setNsPrefix( "rope", ropeURI ); b.setNsPrefix( "butter", butterURI ); assertEquals( null, b.getNsPrefixURI( "crisp") ); assertEquals( null, b.getNsPrefixURI( "rope") ); b.setNsPrefixes( a ); checkContainsMapping( b ); } private void checkContainsMapping( PrefixMapping b ) { assertEquals( crispURI, b.getNsPrefixURI( "crisp") ); assertEquals( ropeURI, b.getNsPrefixURI( "rope") ); assertEquals( butterURI, b.getNsPrefixURI( "butter") ); } /** as for testAddOtherPrefixMapping, except that it's a plain Map we're adding. */ public void testAddMap() { PrefixMapping b = getMapping(); Map<String, String> map = new HashMap<>(); map.put( "crisp", crispURI ); map.put( "rope", ropeURI ); b.setNsPrefix( "butter", butterURI ); b.setNsPrefixes( map ); checkContainsMapping( b ); } public void testAddDefaultMap() { PrefixMapping pm = getMapping(); PrefixMapping root = PrefixMapping.Factory.create(); pm.setNsPrefix( "a", "aPrefix:" ); pm.setNsPrefix( "b", "bPrefix:" ); root.setNsPrefix( "a", "pootle:" ); root.setNsPrefix( "z", "bPrefix:" ); root.setNsPrefix( "c", "cootle:" ); assertSame( pm, pm.withDefaultMappings( root ) ); assertEquals( "aPrefix:", pm.getNsPrefixURI( "a" ) ); assertEquals( null, pm.getNsPrefixURI( "z" ) ); assertEquals( "bPrefix:", pm.getNsPrefixURI( "b" ) ); assertEquals( "cootle:", pm.getNsPrefixURI( "c" ) ); } public void testSecondPrefixRetainsExistingMap() { PrefixMapping A = getMapping(); A.setNsPrefix( "a", crispURI ); A.setNsPrefix( "b", crispURI ); assertEquals( crispURI, A.getNsPrefixURI( "a" ) ); assertEquals( crispURI, A.getNsPrefixURI( "b" ) ); } public void testSecondPrefixReplacesReverseMap() { PrefixMapping A = getMapping(); A.setNsPrefix( "a", crispURI ); A.setNsPrefix( "b", crispURI ); assertEquals( "b", A.getNsURIPrefix( crispURI ) ); } public void testSecondPrefixDeletedUncoversPreviousMap() { PrefixMapping A = getMapping(); A.setNsPrefix( "x", crispURI ); A.setNsPrefix( "y", crispURI ); A.removeNsPrefix( "y" ); assertEquals( "x", A.getNsURIPrefix( crispURI ) ); } /** Test that the empty prefix does not wipe an existing prefix for the same URI. */ public void testEmptyDoesNotWipeURI() { PrefixMapping pm = getMapping(); pm.setNsPrefix( "frodo", ropeURI ); pm.setNsPrefix( "", ropeURI ); assertEquals( ropeURI, pm.getNsPrefixURI( "frodo" ) ); } /** Test that adding a new prefix mapping for U does not throw away a default mapping for U. */ public void testSameURIKeepsDefault() { PrefixMapping A = getMapping(); A.setNsPrefix( "", crispURI ); A.setNsPrefix( "crisp", crispURI ); assertEquals( crispURI, A.getNsPrefixURI( "" ) ); } public void testReturnsSelf() { PrefixMapping A = getMapping(); assertSame( A, A.setNsPrefix( "crisp", crispURI ) ); assertSame( A, A.setNsPrefixes( A ) ); assertSame( A, A.setNsPrefixes( new HashMap<String, String>() ) ); assertSame( A, A.removeNsPrefix( "rhubarb" ) ); } public void testRemovePrefix() { String hURI = "http://test.remove.prefixes/prefix#"; String bURI = "http://other.test.remove.prefixes/prefix#"; PrefixMapping A = getMapping(); A.setNsPrefix( "hr", hURI ); A.setNsPrefix( "br", bURI ); A.removeNsPrefix( "hr" ); assertEquals( null, A.getNsPrefixURI( "hr" ) ); assertEquals( bURI, A.getNsPrefixURI( "br" ) ); } public void testEquality() { testEquals( "" ); testEquals( "", "x=a", false ); testEquals( "x=a", "", false ); testEquals( "x=a" ); testEquals( "x=a y=b", "y=b x=a", true ); testEquals( "x=a x=b", "x=b x=a", false ); } protected void testEquals( String S ) { testEquals( S, S, true ); } protected void testEquals( String S, String T, boolean expected ) { testEqualsBase( S, T, expected ); testEqualsBase( T, S, expected ); } public void testEqualsBase( String S, String T, boolean expected ) { testEquals( S, T, expected, getMapping(), getMapping() ); testEquals( S, T, expected, PrefixMapping.Factory.create(), getMapping() ); } protected void testEquals( String S, String T, boolean expected, PrefixMapping A, PrefixMapping B ) { fill( A, S ); fill( B, T ); String title = "usual: '" + S + "', testing: '" + T + "', should be " + (expected ? "equal" : "different"); assertEquals( title, expected, A.samePrefixMappingAs( B ) ); assertEquals( title, expected, B.samePrefixMappingAs( A ) ); } protected void fill( PrefixMapping pm, String settings ) { List<String> L = listOfStrings( settings ); for ( String setting : L ) { int eq = setting.indexOf( '=' ); pm.setNsPrefix( setting.substring( 0, eq ), setting.substring( eq + 1 ) ); } } public void testAllowNastyNamespace() { // we now allow namespaces to end with non-punctuational characters getMapping().setNsPrefix( "abc", "def" ); } public void testLock() { PrefixMapping A = getMapping(); assertSame( A, A.lock() ); /* */ try { A.setNsPrefix( "crisp", crispURI ); fail( "mapping should be frozen" ); } catch (PrefixMapping.JenaLockedException e) { pass(); } /* */ try { A.setNsPrefixes( A ); fail( "mapping should be frozen" ); } catch (PrefixMapping.JenaLockedException e) { pass(); } /* */ try { A.setNsPrefixes( new HashMap<String, String>() ); fail( "mapping should be frozen" ); } catch (PrefixMapping.JenaLockedException e) { pass(); } /* */ try { A.removeNsPrefix( "toast" ); fail( "mapping should be frozen" ); } catch (PrefixMapping.JenaLockedException e) { pass(); } } }
{ "content_hash": "14f329ed043de99edd274a3d4015cbd3", "timestamp": "", "source": "github", "line_count": 453, "max_line_length": 115, "avg_line_length": 35.24503311258278, "alnum_prop": 0.5654515846173118, "repo_name": "kidaa/jena", "id": "ec72d9f357782c425a9ce6354e2703ddba3c574d", "size": "16771", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "jena-core/src/test/java/org/apache/jena/shared/AbstractTestPrefixMapping.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "145" }, { "name": "AspectJ", "bytes": "3446" }, { "name": "Batchfile", "bytes": "17281" }, { "name": "C++", "bytes": "5037" }, { "name": "CSS", "bytes": "26180" }, { "name": "Elixir", "bytes": "2548" }, { "name": "HTML", "bytes": "100718" }, { "name": "Java", "bytes": "25417777" }, { "name": "JavaScript", "bytes": "919794" }, { "name": "Lex", "bytes": "82672" }, { "name": "Perl", "bytes": "37209" }, { "name": "Ruby", "bytes": "355167" }, { "name": "Shell", "bytes": "225576" }, { "name": "Smarty", "bytes": "17096" }, { "name": "Thrift", "bytes": "3201" }, { "name": "Web Ontology Language", "bytes": "518275" }, { "name": "XSLT", "bytes": "101830" } ], "symlink_target": "" }
package eu.qualimaster.common.logging; import java.util.Map; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; /** * The QM specific logging functionality. By default, QMspecific logging is disabled as it requires an additional * event forwarding thread. You can enable it through {@link #enable(Map)} on a STORM topology configuration setting * {@link #ENABLING_PROPERTY} to true. * * To utilize this form of logging, please use either {@link eu.qualimaster.common.signal.BaseSignalBolt} or * {@link eu.qualimaster.common.signal.BaseSignalSpout} or call * {@link eu.qualimaster.common.signal.StormSignalConnection#configureEventBus(java.util.Map)}. * * @author Holger Eichelberger */ public class QmLogging { public static final String ENABLING_PROPERTY = "qmLogging.enable"; private static final QmAppender APPENDER = new QmAppender(); /** * Changes the root logging level. * * @param level the new logging level */ public static void setLogLevel(Level level) { setLogLevel(Logger.ROOT_LOGGER_NAME, level); } /** * Returns the logger instance for a certain class. * * @param cls the class the logger shall be returned for * @return the logger instance (may be <b>null</b>) */ private static Logger getLogger(Class<?> cls) { // getLogger(cls.getName()) would also do the job, but just to be sure Logger logger; Object tmp = LoggerFactory.getLogger(cls); if (tmp instanceof Logger) { // shall be the case in STORM logger = (Logger) tmp; } else { logger = null; } return logger; } /** * Returns the logger instance for a certain logger name. * * @param loggerName the logger name * @return the logger instance (may be <b>null</b>) */ private static Logger getLogger(String loggerName) { Logger logger; Object tmp = LoggerFactory.getLogger(loggerName); if (tmp instanceof Logger) { // shall be the case in STORM logger = (Logger) tmp; } else { logger = null; } return logger; } /** * Disables unwanted infrastructure logging. */ public static void disableUnwantedLogging() { disableLogger(getLogger(org.apache.storm.zookeeper.ClientCnxn.class)); disableLogger(getLogger(org.apache.storm.zookeeper.server.NIOServerCnxn.class)); disableLogger(getLogger(org.apache.storm.curator.framework.imps.CuratorFrameworkImpl.class)); } /** * Disables a logger. * * @param logger the logger to disable (may be <b>null</b>, ignored then) */ private static void disableLogger(Logger logger) { if (null != logger) { logger.setLevel(Level.OFF); } } /** * Changes the log level. * * @param loggerName the name of the logger * @param level the new logging level */ public static void setLogLevel(String loggerName, Level level) { Logger logger = getLogger(loggerName); if (null != logger) { logger.setLevel(level); } } /** * Installs the QM logging into slf4j/logback. */ public static void install() { Object tmp = LoggerFactory.getILoggerFactory(); if (tmp instanceof LoggerContext) { LoggerContext context = (LoggerContext) tmp; APPENDER.setContext(context); APPENDER.start(); } configureLogger(Logger.ROOT_LOGGER_NAME); } /** * Configures a logger for QM appending. * * @param loggerName the name of the logger */ private static void configureLogger(String loggerName) { Logger logger = getLogger(loggerName); if (null != logger && null == logger.getAppender(APPENDER.getName())) { logger.addAppender(APPENDER); } } /** * Enables logging on the given STORM topology configuration. * * @param cfg the configuration * @return <code>cfg</code> (builder pattern) */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static Map enable(Map cfg) { cfg.put(QmLogging.ENABLING_PROPERTY, Boolean.TRUE); return cfg; } }
{ "content_hash": "e07bc1e76f65071c3a9fa98380bdbf42", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 116, "avg_line_length": 32.19718309859155, "alnum_prop": 0.6084864391951006, "repo_name": "QualiMaster/Infrastructure", "id": "3f929350b3c8a3c0f4be937a496043f79238fd09", "size": "5227", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "StormCommons/src/eu/qualimaster/common/logging/QmLogging.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "575" }, { "name": "Java", "bytes": "4750737" }, { "name": "Shell", "bytes": "9223" } ], "symlink_target": "" }
<?php /** * @file * Contains \Drupal\views\Plugin\views\field\Date. */ namespace Drupal\views\Plugin\views\field; use Drupal\Core\Entity\EntityStorageInterface; use Drupal\Core\Form\FormStateInterface; use Drupal\views\ResultRow; use Symfony\Component\DependencyInjection\ContainerInterface; use Drupal\Core\Datetime\DateFormatter; /** * A handler to provide proper displays for dates. * * @ingroup views_field_handlers * * @ViewsField("date") */ class Date extends FieldPluginBase { /** * The date formatter service. * * @var \Drupal\Core\Datetime\DateFormatter */ protected $dateFormatter; /** * The date format storage. * * @var \Drupal\Core\Entity\EntityStorageInterface */ protected $dateFormatStorage; /** * Constructs a new Date object. * * @param array $configuration * A configuration array containing information about the plugin instance. * @param string $plugin_id * The plugin ID for the plugin instance. * @param mixed $plugin_definition * The plugin implementation definition. * @param \Drupal\Core\Datetime\DateFormatter $date_formatter * The date formatter service. * @param \Drupal\Core\Entity\EntityStorageInterface $date_format_storage * The date format storage. */ public function __construct(array $configuration, $plugin_id, $plugin_definition, DateFormatter $date_formatter, EntityStorageInterface $date_format_storage) { parent::__construct($configuration, $plugin_id, $plugin_definition); $this->dateFormatter = $date_formatter; $this->dateFormatStorage = $date_format_storage; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { return new static( $configuration, $plugin_id, $plugin_definition, $container->get('date.formatter'), $container->get('entity.manager')->getStorage('date_format') ); } /** * {@inheritdoc} */ protected function defineOptions() { $options = parent::defineOptions(); $options['date_format'] = array('default' => 'small'); $options['custom_date_format'] = array('default' => ''); $options['timezone'] = array('default' => ''); return $options; } /** * {@inheritdoc} */ public function buildOptionsForm(&$form, FormStateInterface $form_state) { $date_formats = array(); foreach ($this->dateFormatStorage->loadMultiple() as $machine_name => $value) { $date_formats[$machine_name] = $this->t('@name format: @date', array('@name' => $value->label(), '@date' => $this->dateFormatter->format(REQUEST_TIME, $machine_name))); } $form['date_format'] = array( '#type' => 'select', '#title' => $this->t('Date format'), '#options' => $date_formats + array( 'custom' => $this->t('Custom'), 'raw time ago' => $this->t('Time ago'), 'time ago' => $this->t('Time ago (with "ago" appended)'), 'raw time hence' => $this->t('Time hence'), 'time hence' => $this->t('Time hence (with "hence" appended)'), 'raw time span' => $this->t('Time span (future dates have "-" prepended)'), 'inverse time span' => $this->t('Time span (past dates have "-" prepended)'), 'time span' => $this->t('Time span (with "ago/hence" appended)'), ), '#default_value' => isset($this->options['date_format']) ? $this->options['date_format'] : 'small', ); $form['custom_date_format'] = array( '#type' => 'textfield', '#title' => $this->t('Custom date format'), '#description' => $this->t('If "Custom", see <a href="http://us.php.net/manual/en/function.date.php" target="_blank">the PHP docs</a> for date formats. Otherwise, enter the number of different time units to display, which defaults to 2.'), '#default_value' => isset($this->options['custom_date_format']) ? $this->options['custom_date_format'] : '', ); // Setup #states for all possible date_formats on the custom_date_format form element. foreach (array('custom', 'raw time ago', 'time ago', 'raw time hence', 'time hence', 'raw time span', 'time span', 'raw time span', 'inverse time span', 'time span') as $custom_date_possible) { $form['custom_date_format']['#states']['visible'][] = array( ':input[name="options[date_format]"]' => array('value' => $custom_date_possible), ); } $form['timezone'] = array( '#type' => 'select', '#title' => $this->t('Timezone'), '#description' => $this->t('Timezone to be used for date output.'), '#options' => array('' => $this->t('- Default site/user timezone -')) + system_time_zones(FALSE), '#default_value' => $this->options['timezone'], ); foreach (array_merge(array('custom'), array_keys($date_formats)) as $timezone_date_formats) { $form['timezone']['#states']['visible'][] = array( ':input[name="options[date_format]"]' => array('value' => $timezone_date_formats), ); } parent::buildOptionsForm($form, $form_state); } /** * {@inheritdoc} */ public function render(ResultRow $values) { $value = $this->getValue($values); $format = $this->options['date_format']; if (in_array($format, array('custom', 'raw time ago', 'time ago', 'raw time hence', 'time hence', 'raw time span', 'time span', 'raw time span', 'inverse time span', 'time span'))) { $custom_format = $this->options['custom_date_format']; } if ($value) { $timezone = !empty($this->options['timezone']) ? $this->options['timezone'] : NULL; $time_diff = REQUEST_TIME - $value; // will be positive for a datetime in the past (ago), and negative for a datetime in the future (hence) switch ($format) { case 'raw time ago': return $this->dateFormatter->formatTimeDiffSince($value, array('granularity' => is_numeric($custom_format) ? $custom_format : 2)); case 'time ago': return $this->t('%time ago', array('%time' => $this->dateFormatter->formatTimeDiffSince($value, array('granularity' => is_numeric($custom_format) ? $custom_format : 2)))); case 'raw time hence': return $this->dateFormatter->formatTimeDiffUntil($value, array('granularity' => is_numeric($custom_format) ? $custom_format : 2)); case 'time hence': return $this->t('%time hence', array('%time' => $this->dateFormatter->formatTimeDiffUntil($value, array('granularity' => is_numeric($custom_format) ? $custom_format : 2)))); case 'raw time span': return ($time_diff < 0 ? '-' : '') . $this->dateFormatter->formatTimeDiffSince($value, array('strict' => FALSE, 'granularity' => is_numeric($custom_format) ? $custom_format : 2)); case 'inverse time span': return ($time_diff > 0 ? '-' : '') . $this->dateFormatter->formatTimeDiffSince($value, array('strict' => FALSE, 'granularity' => is_numeric($custom_format) ? $custom_format : 2)); case 'time span': $time = $this->dateFormatter->formatTimeDiffSince($value, array('strict' => FALSE, 'granularity' => is_numeric($custom_format) ? $custom_format : 2)); return ($time_diff < 0) ? $this->t('%time hence', array('%time' => $time)) : $this->t('%time ago', array('%time' => $time)); case 'custom': if ($custom_format == 'r') { return format_date($value, $format, $custom_format, $timezone, 'en'); } return format_date($value, $format, $custom_format, $timezone); default: return format_date($value, $format, '', $timezone); } } } }
{ "content_hash": "abf2c8411ab323e43095ac793336441f", "timestamp": "", "source": "github", "line_count": 187, "max_line_length": 245, "avg_line_length": 40.903743315508024, "alnum_prop": 0.6182507517322526, "repo_name": "kaperkin/drupal_8_shelby_site", "id": "340518ca5da1232fee475cce015f7cc5251b98a4", "size": "7649", "binary": false, "copies": "33", "ref": "refs/heads/master", "path": "core/modules/views/src/Plugin/views/field/Date.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "673" }, { "name": "C++", "bytes": "13011" }, { "name": "CSS", "bytes": "292661" }, { "name": "HTML", "bytes": "319322" }, { "name": "JavaScript", "bytes": "812156" }, { "name": "PHP", "bytes": "26645010" }, { "name": "Shell", "bytes": "41324" } ], "symlink_target": "" }
For this initial release, and likely for the next several releases, we will be driven by internal, production needs and will therefore need to prioritize our internal users requirements. However, we want to encourage that you submit contributions, either as issues or PRs within this proejct or as an RFC in the [TensorFlow Community RFC](https://github.com/tensorflow/community/tree/master/rfcs) repo. # How to Contribute We'd love to have your contributions to this project! There are just a few small guidelines you need to follow. ### Step 1. Open an issue Before making any changes, we recommend opening an issue (if one doesn't already exist) and discussing your proposed changes. This way, we can give you feedback and validate the proposed changes. If the changes are minor (simple bug fix or documentation fix), then feel free to open a PR without discussion. ### Step 2. Make code changes To make code changes, you need to fork the repository. You will need to setup a development environment and run the unit tests. This is covered in the [developer guide](https://github.com/tensorflow/gnn/blob/main/tensorflow_gnn/docs/guide/developer.md). ### Step 3. Create a pull request Once the change is ready, open a pull request from your branch in your fork to the main branch in [tensorflow/gnn](https://github.com/tensorflow/gnn). ### Step 4. Sign the Contributor License Agreement Contributions to this project must be accompanied by a Contributor License Agreement. You (or your employer) retain the copyright to your contribution; this simply gives us permission to use and redistribute your contributions as part of the project. After creating a pull request, the `google-cla` bot will comment on your pull request with instructions on signing the Contributor License Agreement (CLA) if you haven't done so. Please follow the instructions to sign the CLA. A `cla:yes` tag is then added to the pull request. Head over to <https://cla.developers.google.com/> to see your current agreements on file or to sign a new one. You generally only need to submit a CLA once, so if you've already submitted one (even if it was for a different project), you probably don't need to do it again. ### Step 5. Code review A reviewer will review the pull request and provide comments. The reviewer may add a `kokoro:force-run` label to trigger the continuous integration tests. If the tests fail, look into the error messages and try to fix them. There may be several rounds of comments and code changes before the pull request gets approved by the reviewer. ### Step 6. Merging Once the pull request is approved, a `ready to pull` tag will be added to the pull request. A team member will take care of the merging. Here is an [example pull request](https://github.com/tensorflow/gnn/pull/37) for your reference. ## Community Guidelines This project follows [Google's Open Source Community Guidelines](https://opensource.google.com/conduct/).
{ "content_hash": "d1440d46b1e3ad285f86a8491fabb339", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 102, "avg_line_length": 41.083333333333336, "alnum_prop": 0.7816091954022989, "repo_name": "tensorflow/gnn", "id": "d29e6bbe36799b7cd7be05a2a8398700935e475c", "size": "2979", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "CONTRIBUTING.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "2491" }, { "name": "Python", "bytes": "1770047" }, { "name": "Shell", "bytes": "3120" }, { "name": "Starlark", "bytes": "47061" } ], "symlink_target": "" }
'use strict'; var should = require('should'); var util = require('util'); var CLITest = require('../../../framework/arm-cli-test'); var testUtils = require('../../../util/util'); var testprefix = 'arm-cli-vm-stoprestart-tests'; var groupPrefix = 'xplatTestGVMStart'; var VMTestUtil = require('../../../util/vmTestUtil'); var requiredEnvironment = [{ name: 'AZURE_VM_TEST_LOCATION', defaultValue: 'eastus' }, { name: 'SSHCERT', defaultValue: 'test/myCert.pem' }]; var groupName, timeout, vmPrefix = 'xplatvmStSp', nicName = 'xplattestnicStSp', location, username = 'azureuser', password = 'Brillio@2015', storageAccount = 'xplattstoragestsp', storageCont = 'xplatteststoragecntstsp', osdiskvhd = 'xplattestvhdstsp', vNetPrefix = 'xplattestvnetStSp', subnetName = 'xplattestsubnetStSp', publicipName = 'xplattestipStSp', dnsPrefix = 'xplattestipdnsstsp', sshcert; describe('arm', function() { describe('compute', function() { var suite, retry = 5; var vmTest = new VMTestUtil(); testUtils.TIMEOUT_INTERVAL = 5000; before(function(done) { suite = new CLITest(this, testprefix, requiredEnvironment); suite.setupSuite(function() { location = process.env.AZURE_VM_TEST_LOCATION; sshcert = process.env.SSHCERT; groupName = suite.isMocked ? groupPrefix : suite.generateId(groupPrefix, null); vmPrefix = suite.isMocked ? vmPrefix : suite.generateId(vmPrefix, null); nicName = suite.isMocked ? nicName : suite.generateId(nicName, null); storageAccount = suite.generateId(storageAccount, null); storageCont = suite.isMocked ? storageCont : suite.generateId(storageCont, null); osdiskvhd = suite.isMocked ? osdiskvhd : suite.generateId(osdiskvhd, null); vNetPrefix = suite.isMocked ? vNetPrefix : suite.generateId(vNetPrefix, null); subnetName = suite.isMocked ? subnetName : suite.generateId(subnetName, null); publicipName = suite.isMocked ? publicipName : suite.generateId(publicipName, null); dnsPrefix = suite.isMocked ? dnsPrefix : suite.generateId(dnsPrefix, null); done(); }); }); after(function(done) { vmTest.deleteUsedGroup(groupName, suite, function(result) { suite.teardownSuite(done); }); }); beforeEach(function(done) { suite.setupTest(done); }); afterEach(function(done) { suite.teardownTest(done); }); describe('vm', function() { it('create should pass for stop start & restart', function(done) { this.timeout(vmTest.timeoutLarge); vmTest.checkImagefile(function() { vmTest.createGroup(groupName, location, suite, function(result) { if (VMTestUtil.linuxImageUrn === '' || VMTestUtil.linuxImageUrn === undefined) { vmTest.GetLinuxSkusList(location, suite, function(result) { vmTest.GetLinuxImageList(location, suite, function(result) { var cmd = util.format('vm create %s %s %s Linux -f %s -Q %s -u %s -p %s -o %s -R %s -F %s -P %s -j %s -k %s -i %s -w %s -M %s --json', groupName, vmPrefix, location, nicName, VMTestUtil.linuxImageUrn, username, password, storageAccount, storageCont, vNetPrefix, '10.0.0.0/16', subnetName, '10.0.0.0/24', publicipName, dnsPrefix, sshcert).split(' '); testUtils.executeCommand(suite, retry, cmd, function(result) { result.exitStatus.should.equal(0); done(); }); }); }); } else { var cmd = util.format('vm create %s %s %s Linux -f %s -Q %s -u %s -p %s -o %s -R %s -F %s -P %s -j %s -k %s -i %s -w %s -M %s --json', groupName, vmPrefix, location, nicName, VMTestUtil.linuxImageUrn, username, password, storageAccount, storageCont, vNetPrefix, '10.0.0.0/16', subnetName, '10.0.0.0/24', publicipName, dnsPrefix, sshcert).split(' '); testUtils.executeCommand(suite, retry, cmd, function(result) { result.exitStatus.should.equal(0); done(); }); } }); }); }); it('get-instance-view should get instance view of the VM', function(done) { var cmd = util.format('vm get-instance-view %s %s --json', groupName, vmPrefix).split(' '); testUtils.executeCommand(suite, retry, cmd, function(result) { should(result.text.indexOf('diagnosticsProfile') == -1).ok; should(result.text.indexOf('bootDiagnostics') == -1).ok; should(result.text.indexOf('storageUri') == -1).ok; result.exitStatus.should.equal(0); done(); }); }); it('get-serial-output should get serial output of the VM', function(done) { var cmd = util.format('vm get-serial-output %s %s --json', groupName, vmPrefix).split(' '); testUtils.executeCommand(suite, retry, cmd, function(result) { result.exitStatus.should.equal(0); should(result.text.indexOf('bootdiagnostics') == -1).ok; done(); }); }); it('Stop and start VM should work', function(done) { this.timeout(vmTest.timeoutLarge); var cmd = util.format('vm stop %s %s --json', groupName, vmPrefix).split(' '); testUtils.executeCommand(suite, retry, cmd, function(result) { result.exitStatus.should.equal(0); setTimeout(function() { cmd = util.format('vm start %s %s --json', groupName, vmPrefix).split(' '); testUtils.executeCommand(suite, retry, cmd, function(result) { result.exitStatus.should.equal(0); done(); }); }, timeout); }); }); // VM Restart it('Restart should restart the VM', function(done) { var cmd = util.format('vm restart %s %s --json', groupName, vmPrefix).split(' '); testUtils.executeCommand(suite, retry, cmd, function(result) { result.exitStatus.should.equal(0); done(); }); }); it('Deallocate should release the compute resources', function(done) { this.timeout(vmTest.timeoutLarge); var cmd = util.format('vm deallocate %s %s --json', groupName, vmPrefix).split(' '); testUtils.executeCommand(suite, retry, cmd, function(result) { result.exitStatus.should.equal(0); done(); }); }); }); }); });
{ "content_hash": "fc7422db1f0b4bdbab16eda34c84ceb0", "timestamp": "", "source": "github", "line_count": 156, "max_line_length": 152, "avg_line_length": 41.80128205128205, "alnum_prop": 0.6008280938506364, "repo_name": "colrack/azure-xplat-cli", "id": "79627f440ea9b004e093504d8f7c83545df696c9", "size": "7131", "binary": false, "copies": "6", "ref": "refs/heads/dev", "path": "test/commands/arm/vm/arm.vm-stop-restart-tests.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Cucumber", "bytes": "1579" }, { "name": "HTML", "bytes": "69" }, { "name": "JavaScript", "bytes": "53149662" }, { "name": "Ruby", "bytes": "163" }, { "name": "Shell", "bytes": "550" } ], "symlink_target": "" }
var gulp = require('gulp'); var shell = require('gulp-shell') gulp.task('default', function() { // place code for your default task here console.log("Gulp is working"); }); gulp.task('dev', function() { // place code for your default task here console.log("Launching dev server"); shell([ 'npm start' ]); console.log("After"); });
{ "content_hash": "5da75d9b7b2a7bf14e1d8fc37e64081e", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 42, "avg_line_length": 23.4, "alnum_prop": 0.6410256410256411, "repo_name": "nemerkab/AngularSpike", "id": "21d396c9b86948d69a53d13a8d945d3e19a662b3", "size": "351", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gulpfile.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "366" }, { "name": "JavaScript", "bytes": "5281" } ], "symlink_target": "" }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Function template none_of</title> <link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="../../index.html" title="The Boost Algorithm Library"> <link rel="up" href="../../header/boost/algorithm/cxx11/none_of_hpp.html" title="Header &lt;boost/algorithm/cxx11/none_of.hpp&gt;"> <link rel="prev" href="none_of_idp30329056.html" title="Function template none_of"> <link rel="next" href="none_of_equal_idp30342144.html" title="Function template none_of_equal"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="none_of_idp30329056.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/algorithm/cxx11/none_of_hpp.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="none_of_equal_idp30342144.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.algorithm.none_of_idp30336176"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Function template none_of</span></h2> <p>boost::algorithm::none_of</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../header/boost/algorithm/cxx11/none_of_hpp.html" title="Header &lt;boost/algorithm/cxx11/none_of.hpp&gt;">boost/algorithm/cxx11/none_of.hpp</a>&gt; </span> <span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> Range<span class="special">,</span> <span class="keyword">typename</span> Predicate<span class="special">&gt;</span> <span class="keyword">bool</span> <span class="identifier">none_of</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">Range</span> <span class="special">&amp;</span> r<span class="special">,</span> <span class="identifier">Predicate</span> p<span class="special">)</span><span class="special">;</span></pre></div> <div class="refsect1"> <a name="idp103918688"></a><h2>Description</h2> <p> </p> <div class="note"><table border="0" summary="Note"> <tr> <td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="../../../../../../doc/src/images/note.png"></td> <th align="left">Note</th> </tr> <tr><td align="left" valign="top"><p>returns true on an empty range</p></td></tr> </table></div> <p> </p> <div class="variablelist"><table border="0" class="variablelist compact"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term">Parameters:</span></p></td> <td><div class="variablelist"><table border="0" class="variablelist compact"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term"><code class="computeroutput">p</code></span></p></td> <td><p>A predicate for testing the elements of the range </p></td> </tr> <tr> <td><p><span class="term"><code class="computeroutput">r</code></span></p></td> <td><p>The input range </p></td> </tr> </tbody> </table></div></td> </tr> <tr> <td><p><span class="term">Returns:</span></p></td> <td><p>true if none of the elements in the range satisfy the predicate 'p' </p></td> </tr> </tbody> </table></div> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2010-2012 Marshall Clow<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="none_of_idp30329056.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/algorithm/cxx11/none_of_hpp.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="none_of_equal_idp30342144.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{ "content_hash": "ddb6f57359b286ac1e0ef27e56f3753d", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 489, "avg_line_length": 55.649484536082475, "alnum_prop": 0.6450537236013338, "repo_name": "rkq/cxxexp", "id": "772e39d0b20ee643d0966ce488f5d7b990cb45c5", "size": "5398", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "third-party/src/boost_1_56_0/libs/algorithm/doc/html/boost/algorithm/none_of_idp30336176.html", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "65460" }, { "name": "Assembly", "bytes": "281439" }, { "name": "Awk", "bytes": "4270" }, { "name": "C", "bytes": "12760841" }, { "name": "C#", "bytes": "284333" }, { "name": "C++", "bytes": "168165192" }, { "name": "CSS", "bytes": "291858" }, { "name": "Cuda", "bytes": "26521" }, { "name": "D", "bytes": "644044" }, { "name": "Emacs Lisp", "bytes": "12952" }, { "name": "Erlang", "bytes": "137548" }, { "name": "FORTRAN", "bytes": "1387" }, { "name": "Gnuplot", "bytes": "2361" }, { "name": "Go", "bytes": "225070" }, { "name": "Haskell", "bytes": "55210" }, { "name": "IDL", "bytes": "14" }, { "name": "Java", "bytes": "2162335" }, { "name": "JavaScript", "bytes": "430303" }, { "name": "Max", "bytes": "36857" }, { "name": "OCaml", "bytes": "39133" }, { "name": "Objective-C", "bytes": "85640" }, { "name": "Objective-C++", "bytes": "207" }, { "name": "PHP", "bytes": "300052" }, { "name": "Pascal", "bytes": "311336" }, { "name": "Perl", "bytes": "549125" }, { "name": "Python", "bytes": "3145121" }, { "name": "Rebol", "bytes": "354" }, { "name": "Ruby", "bytes": "371639" }, { "name": "Shell", "bytes": "2701201" }, { "name": "Smalltalk", "bytes": "22944" }, { "name": "Tcl", "bytes": "1172" }, { "name": "TeX", "bytes": "181417" }, { "name": "VimL", "bytes": "6568" }, { "name": "Visual Basic", "bytes": "11578" }, { "name": "XSLT", "bytes": "751290" } ], "symlink_target": "" }
require 'rails_helper' RSpec.describe StaticPagesController, type: :controller do describe "GET #history" do it "returns http success" do get :history expect(response).to have_http_status(:success) end end describe "GET #sites" do it "returns http success" do get :sites expect(response).to have_http_status(:success) end end describe "GET #scholarship" do it "returns http success" do get :scholarship expect(response).to have_http_status(:success) end end end
{ "content_hash": "845b9077c5f2382e09b05fc2cf37dd63", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 58, "avg_line_length": 20.73076923076923, "alnum_prop": 0.6679035250463822, "repo_name": "VictorianResearchWeb/TheCurranIndex", "id": "232465450644c21ac32f638fd0824ac540c4d332", "size": "539", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/controllers/static_pages_controller_spec.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "538" }, { "name": "HTML", "bytes": "81229" }, { "name": "JavaScript", "bytes": "1151" }, { "name": "Ruby", "bytes": "61380" } ], "symlink_target": "" }
<?php namespace SMA\SMABundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('smasma'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
{ "content_hash": "e17a88860e8438a444a0c317b101c27b", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 131, "avg_line_length": 29.93103448275862, "alnum_prop": 0.7142857142857143, "repo_name": "matsuyuki/smanegeri11", "id": "1a8bd247d78668c94d18ef40d80fb86819333481", "size": "868", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/SMA/SMABundle/DependencyInjection/Configuration.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "200198" }, { "name": "JavaScript", "bytes": "1082542" }, { "name": "PHP", "bytes": "173769" } ], "symlink_target": "" }
package com.agimatec.validation; import com.agimatec.validation.model.MetaBean; /** * Description: interface for abstraction how to initialize a MetaBean * with information from somewhere<br/> * User: roman <br/> * Date: 07.10.2009 <br/> * Time: 11:38:03 <br/> * Copyright: Agimatec GmbH */ public interface MetaBeanFactory { void buildMetaBean(MetaBean metaBean) throws Exception; }
{ "content_hash": "e494a91a6337aa17a451b33159b86fff", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 70, "avg_line_length": 24.9375, "alnum_prop": 0.731829573934837, "repo_name": "google-code/agimatec-validation", "id": "7f98a266d3dd41dc149235db3de9beec900a492a", "size": "1212", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "agimatec-validation/src/main/java/com/agimatec/validation/MetaBeanFactory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "785294" } ], "symlink_target": "" }
(function( amplify, undefined ) { var store = amplify.store = function( key, value, options ) { var type = store.type; if ( options && options.type && options.type in store.types ) { type = options.type; } return store.types[ type ]( key, value, options || {} ); }; store.types = {}; store.type = null; store.addType = function( type, storage ) { if ( !store.type ) { store.type = type; } store.types[ type ] = storage; store[ type ] = function( key, value, options ) { options = options || {}; options.type = type; return store( key, value, options ); }; }; store.error = function() { return "amplify.store quota exceeded"; }; var rprefix = /^__amplify__/; function createFromStorageInterface( storageType, storage ) { store.addType( storageType, function( key, value, options ) { var storedValue, parsed, i, remove, ret = value, now = (new Date()).getTime(); if ( !key ) { ret = {}; remove = []; i = 0; try { // accessing the length property works around a localStorage bug // in Firefox 4.0 where the keys don't update cross-page // we assign to key just to avoid Closure Compiler from removing // the access as "useless code" // https://bugzilla.mozilla.org/show_bug.cgi?id=662511 key = storage.length; while ( key = storage.key( i++ ) ) { if ( rprefix.test( key ) ) { parsed = JSON.parse( storage.getItem( key ) ); if ( parsed.expires && parsed.expires <= now ) { remove.push( key ); } else { ret[ key.replace( rprefix, "" ) ] = parsed.data; } } } while ( key = remove.pop() ) { storage.removeItem( key ); } } catch ( error ) {} return ret; } // protect against name collisions with direct storage key = "__amplify__" + key; if ( value === undefined ) { storedValue = storage.getItem( key ); parsed = storedValue ? JSON.parse( storedValue ) : { expires: -1 }; if ( parsed.expires && parsed.expires <= now ) { storage.removeItem( key ); } else { return parsed.data; } } else { if ( value === null ) { storage.removeItem( key ); } else { parsed = JSON.stringify({ data: value, expires: options.expires ? now + options.expires : null }); try { storage.setItem( key, parsed ); // quota exceeded } catch( error ) { // expire old data and try again store[ storageType ](); try { storage.setItem( key, parsed ); } catch( error ) { throw store.error(); } } } } return ret; }); } // localStorage + sessionStorage // IE 8+, Firefox 3.5+, Safari 4+, Chrome 4+, Opera 10.5+, iPhone 2+, Android 2+ for ( var webStorageType in { localStorage: 1, sessionStorage: 1 } ) { // try/catch for file protocol in Firefox and Private Browsing in Safari 5 try { // Safari 5 in Private Browsing mode exposes localStorage // but doesn't allow storing data, so we attempt to store and remove an item. // This will unfortunately give us a false negative if we're at the limit. window[ webStorageType ].setItem( "__amplify__", "x" ); window[ webStorageType ].removeItem( "__amplify__" ); createFromStorageInterface( webStorageType, window[ webStorageType ] ); } catch( e ) {} } // globalStorage // non-standard: Firefox 2+ // https://developer.mozilla.org/en/dom/storage#globalStorage if ( !store.types.localStorage && window.globalStorage ) { // try/catch for file protocol in Firefox try { createFromStorageInterface( "globalStorage", window.globalStorage[ window.location.hostname ] ); // Firefox 2.0 and 3.0 have sessionStorage and globalStorage // make sure we default to globalStorage // but don't default to globalStorage in 3.5+ which also has localStorage if ( store.type === "sessionStorage" ) { store.type = "globalStorage"; } } catch( e ) {} } // userData // non-standard: IE 5+ // http://msdn.microsoft.com/en-us/library/ms531424(v=vs.85).aspx (function() { // IE 9 has quirks in userData that are a huge pain // rather than finding a way to detect these quirks // we just don't register userData if we have localStorage if ( store.types.localStorage ) { return; } // append to html instead of body so we can do this from the head var div = document.createElement( "div" ), attrKey = "amplify"; div.style.display = "none"; document.getElementsByTagName( "head" )[ 0 ].appendChild( div ); // we can't feature detect userData support // so just try and see if it fails // surprisingly, even just adding the behavior isn't enough for a failure // so we need to load the data as well try { div.addBehavior( "#default#userdata" ); div.load( attrKey ); } catch( e ) { div.parentNode.removeChild( div ); return; } store.addType( "userData", function( key, value, options ) { div.load( attrKey ); var attr, parsed, prevValue, i, remove, ret = value, now = (new Date()).getTime(); if ( !key ) { ret = {}; remove = []; i = 0; while ( attr = div.XMLDocument.documentElement.attributes[ i++ ] ) { parsed = JSON.parse( attr.value ); if ( parsed.expires && parsed.expires <= now ) { remove.push( attr.name ); } else { ret[ attr.name ] = parsed.data; } } while ( key = remove.pop() ) { div.removeAttribute( key ); } div.save( attrKey ); return ret; } // convert invalid characters to dashes // http://www.w3.org/TR/REC-xml/#NT-Name // simplified to assume the starting character is valid // also removed colon as it is invalid in HTML attribute names key = key.replace( /[^\-._0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c-\u200d\u203f\u2040\u2070-\u218f]/g, "-" ); // adjust invalid starting character to deal with our simplified sanitization key = key.replace( /^-/, "_-" ); if ( value === undefined ) { attr = div.getAttribute( key ); parsed = attr ? JSON.parse( attr ) : { expires: -1 }; if ( parsed.expires && parsed.expires <= now ) { div.removeAttribute( key ); } else { return parsed.data; } } else { if ( value === null ) { div.removeAttribute( key ); } else { // we need to get the previous value in case we need to rollback prevValue = div.getAttribute( key ); parsed = JSON.stringify({ data: value, expires: (options.expires ? (now + options.expires) : null) }); div.setAttribute( key, parsed ); } } try { div.save( attrKey ); // quota exceeded } catch ( error ) { // roll the value back to the previous value if ( prevValue === null ) { div.removeAttribute( key ); } else { div.setAttribute( key, prevValue ); } // expire old data and try again store.userData(); try { div.setAttribute( key, parsed ); div.save( attrKey ); } catch ( error ) { // roll the value back to the previous value if ( prevValue === null ) { div.removeAttribute( key ); } else { div.setAttribute( key, prevValue ); } throw store.error(); } } return ret; }); }() ); // in-memory storage // fallback for all browsers to enable the API even if we can't persist data (function() { var memory = {}, timeout = {}; function copy( obj ) { return obj === undefined ? undefined : JSON.parse( JSON.stringify( obj ) ); } store.addType( "memory", function( key, value, options ) { if ( !key ) { return copy( memory ); } if ( value === undefined ) { return copy( memory[ key ] ); } if ( timeout[ key ] ) { clearTimeout( timeout[ key ] ); delete timeout[ key ]; } if ( value === null ) { delete memory[ key ]; return null; } memory[ key ] = value; if ( options.expires ) { timeout[ key ] = setTimeout(function() { delete memory[ key ]; delete timeout[ key ]; }, options.expires ); } return value; }); }() ); }( this.amplify = this.amplify || {} ) );
{ "content_hash": "3b9f672422b09059d267223bdb0d3dd6", "timestamp": "", "source": "github", "line_count": 289, "max_line_length": 132, "avg_line_length": 27.27681660899654, "alnum_prop": 0.6179119624508436, "repo_name": "graemepatt/BerryCamExpress", "id": "d8e50572caf5134e2080c26544c0b6dc987070ff", "size": "7883", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "app/bower_components/amplify/src/store.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "172931" }, { "name": "JavaScript", "bytes": "644775" } ], "symlink_target": "" }
* [Draggable Object](#draggable-object) * [Draggable Object Target](#draggable-object-target) #### Examples * [Classify Posts](#classify-posts) # Primitives ## Draggable Object The `draggable-object` component represents an object you want to drag onto a target. The two things to provide to the component are: * The model - Represents the object to be dragged. Will be passed to the target after a completed drag. * The template code to render for the draggable object ```handlebars {{#draggable-object model=this}} {{name}} {{/draggable-object}} ``` -------------- ## Draggable Object Target The `draggable-object-target` represents a place to drag objects. This will trigger an action which accepts the dragged object as an argument. The two things to provide to the component are: * The action - Represents the action to be called with the dragged object. * The template code to render for the target. The action is called with two arguments: * The dragged object. * An options hash. Currently the only key is `target`, which is the draggable-object-target component. ```handlebars ... your regular template code {{#draggable-object-target action="increaseRating" amount="5"}} Drag here to increase rating {{/draggable-object-target}} ``` ```javascript // represents the controller backing the above template Ember.Controller.extend({ // your regular controller code actions: { increaseRating: function(obj,ops) { var amount = parseInt(ops.target.amount); obj.incrementProperty("rating",amount); obj.save(); } } } }); ``` # Examples ## Classify Posts In this example, we have a bunch of unclassified posts that we want to mark either Ready to Publish or Needs Revision. When you drag a post onto one of the Possible Statuses, it will be: * Assigned that rating. * Removed from the Unclassified Posts list, by virtue of now having a status. app/models/post.js ```javascript export default DS.Model.extend({ title: DS.attr('string'), body: DS.attr('string'), status: DS.attr('string') }); ``` app/controllers/posts.js ```javascript export default Ember.ArrayController.extend({ unclassifiedPosts: Ember.computed.filterBy('content', 'status', undefined), actions: { setStatus: function(post,ops) { var status = ops.target.status; post.set("status",status); post.save(); } } } }); ``` app/templates/posts.hbs ```handlebars <h3>Unclassified Posts</h3> {{#each post in unclassifiedPosts}} {{#draggable-object model=post}} {{post.title}} {{/draggable-object}} {{/each}} <h3>Possible Statuses</h3> {{#draggable-object-target action="setStatus" status="Ready to Publish"}} Ready to Publish {{/draggable-object-target}} {{#draggable-object-target action="setStatus" status="Needs Revision"}} Needs Revision {{/draggable-object-target}} ```
{ "content_hash": "455e525aec8ac047ab16bc35eb907209", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 142, "avg_line_length": 22.519685039370078, "alnum_prop": 0.7122377622377623, "repo_name": "jarredkenny/ember-drag-drop", "id": "c2f91813ca29612f3cf44602af03217562611395", "size": "2888", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "doc/full.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1332" }, { "name": "HTML", "bytes": "1906" }, { "name": "Handlebars", "bytes": "1403" }, { "name": "JavaScript", "bytes": "29729" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <translate xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator" android:fromXDelta="0" android:toXDelta="0" android:duration="300" />
{ "content_hash": "03b66f3425388de0e4f146f1ab701e10", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 69, "avg_line_length": 53, "alnum_prop": 0.690566037735849, "repo_name": "xinfan123/bulu", "id": "863c73dfb8704e7cabcf499c71c51c1baa784a0a", "size": "265", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "res/anim/hold.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "434817" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>label: Error with dependencies</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">dev / label - 1.0.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> label <small> 1.0.0 <span class="label label-warning">Error with dependencies</span> </small> </h1> <p><em><script>document.write(moment("2021-11-06 06:49:18 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-11-06 06:49:18 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 3 Virtual package relying on a GMP lib system installation coq dev Formal proof management system dune 2.9.1 Fast, portable, and opinionated build system ocaml 4.13.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.13.1 Official release 4.13.1 ocaml-config 2 OCaml Switch Configuration ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled ocamlfind 1.9.1 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;pierre-evariste.dagand@lip6.fr&quot; homepage: &quot;https://github.com/pedagand/coq-label&quot; dev-repo: &quot;git+https://github.com/pedagand/coq-label.git&quot; bug-reports: &quot;https://github.com/pedagand/coq-label/issues&quot; authors: [&quot;Pierre-Évariste Dagand&quot; &quot;Théo Zimmermann&quot; &quot;Pierre-Marie Pédrot&quot;] license: &quot;MIT&quot; build: [ [make &quot;-j%{jobs}%&quot;] ] install: [ [make &quot;install&quot;] ] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Label&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.8~&quot;} ] synopsis: &quot;&#39;label&#39; is a Coq plugin for referring to Propositional hypotheses by their type&quot; flags: light-uninstall url { src: &quot;https://github.com/pedagand/coq-label/releases/download/v1.0.0/coq-label-1.0.0.tar.gz&quot; checksum: &quot;md5=3ae47300d7985cf2ddb0ba87354d061c&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-label.1.0.0 coq.dev</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is dev). [ERROR] Package conflict! Sorry, no solution found: there seems to be a problem with your request. No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-label.1.0.0</code></dd> <dt>Return code</dt> <dd>512</dd> <dt>Output</dt> <dd><pre>The following actions will be performed: - remove coq dev &lt;&gt;&lt;&gt; Processing actions &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; While removing coq.dev: these files have been modified since installation: - share/texmf/tex/latex/misc/coqdoc.sty - man/man1/coqwc.1 - man/man1/coqtop.opt.1 - man/man1/coqtop.byte.1 - man/man1/coqtop.1 - man/man1/coqnative.1 - man/man1/coqdoc.1 - man/man1/coqdep.1 - man/man1/coqchk.1 - man/man1/coqc.1 - man/man1/coq_makefile.1 - man/man1/coq-tex.1 - lib/stublibs/dllcoqrun_stubs.so - lib/coqide-server/protocol/xmlprotocol.mli - lib/coqide-server/protocol/xmlprotocol.ml - lib/coqide-server/protocol/xmlprotocol.cmx - lib/coqide-server/protocol/xmlprotocol.cmti - lib/coqide-server/protocol/xmlprotocol.cmt - lib/coqide-server/protocol/xmlprotocol.cmi - lib/coqide-server/protocol/xml_printer.mli - lib/coqide-server/protocol/xml_printer.ml - lib/coqide-server/protocol/xml_printer.cmx - lib/coqide-server/protocol/xml_printer.cmti - lib/coqide-server/protocol/xml_printer.cmt - lib/coqide-server/protocol/xml_printer.cmi - lib/coqide-server/protocol/xml_parser.mli - lib/coqide-server/protocol/xml_parser.ml - lib/coqide-server/protocol/xml_parser.cmx - lib/coqide-server/protocol/xml_parser.cmti - lib/coqide-server/protocol/xml_parser.cmt - lib/coqide-server/protocol/xml_parser.cmi - lib/coqide-server/protocol/xml_lexer.mli - lib/coqide-server/protocol/xml_lexer.ml - lib/coqide-server/protocol/xml_lexer.cmx - lib/coqide-server/protocol/xml_lexer.cmti - lib/coqide-server/protocol/xml_lexer.cmt - lib/coqide-server/protocol/xml_lexer.cmi - lib/coqide-server/protocol/serialize.mli - lib/coqide-server/protocol/serialize.ml - lib/coqide-server/protocol/serialize.cmx - lib/coqide-server/protocol/serialize.cmti - lib/coqide-server/protocol/serialize.cmt - lib/coqide-server/protocol/serialize.cmi - lib/coqide-server/protocol/richpp.mli - lib/coqide-server/protocol/richpp.ml - lib/coqide-server/protocol/richpp.cmx - lib/coqide-server/protocol/richpp.cmti - lib/coqide-server/protocol/richpp.cmt - lib/coqide-server/protocol/richpp.cmi - lib/coqide-server/protocol/protocol.cmxs - lib/coqide-server/protocol/protocol.cmxa - lib/coqide-server/protocol/protocol.cma - lib/coqide-server/protocol/protocol.a - lib/coqide-server/protocol/interface.ml - lib/coqide-server/protocol/interface.cmx - lib/coqide-server/protocol/interface.cmt - lib/coqide-server/protocol/interface.cmi - lib/coqide-server/opam - lib/coqide-server/dune-package - lib/coqide-server/core/document.mli - lib/coqide-server/core/document.ml - lib/coqide-server/core/document.cmx - lib/coqide-server/core/document.cmti - lib/coqide-server/core/document.cmt - lib/coqide-server/core/document.cmi - lib/coqide-server/core/core.cmxs - lib/coqide-server/core/core.cmxa - lib/coqide-server/core/core.cma - lib/coqide-server/core/core.a - lib/coqide-server/META - lib/coq/user-contrib/Ltac2/String.vos - lib/coq/user-contrib/Ltac2/String.vo - lib/coq/user-contrib/Ltac2/String.v - lib/coq/user-contrib/Ltac2/String.glob - lib/coq/user-contrib/Ltac2/Std.vos - lib/coq/user-contrib/Ltac2/Std.vo - lib/coq/user-contrib/Ltac2/Std.v - lib/coq/user-contrib/Ltac2/Std.glob - lib/coq/user-contrib/Ltac2/Printf.vos - lib/coq/user-contrib/Ltac2/Printf.vo - lib/coq/user-contrib/Ltac2/Printf.v - lib/coq/user-contrib/Ltac2/Printf.glob - lib/coq/user-contrib/Ltac2/Pattern.vos - lib/coq/user-contrib/Ltac2/Pattern.vo - lib/coq/user-contrib/Ltac2/Pattern.v - lib/coq/user-contrib/Ltac2/Pattern.glob - lib/coq/user-contrib/Ltac2/Option.vos - lib/coq/user-contrib/Ltac2/Option.vo - lib/coq/user-contrib/Ltac2/Option.v - lib/coq/user-contrib/Ltac2/Option.glob - lib/coq/user-contrib/Ltac2/Notations.vos - lib/coq/user-contrib/Ltac2/Notations.vo - lib/coq/user-contrib/Ltac2/Notations.v - lib/coq/user-contrib/Ltac2/Notations.glob - lib/coq/user-contrib/Ltac2/Message.vos - lib/coq/user-contrib/Ltac2/Message.vo - lib/coq/user-contrib/Ltac2/Message.v - lib/coq/user-contrib/Ltac2/Message.glob - lib/coq/user-contrib/Ltac2/Ltac2.vos - lib/coq/user-contrib/Ltac2/Ltac2.vo - lib/coq/user-contrib/Ltac2/Ltac2.v - lib/coq/user-contrib/Ltac2/Ltac2.glob - lib/coq/user-contrib/Ltac2/Ltac1.vos - lib/coq/user-contrib/Ltac2/Ltac1.vo - lib/coq/user-contrib/Ltac2/Ltac1.v - lib/coq/user-contrib/Ltac2/Ltac1.glob - lib/coq/user-contrib/Ltac2/List.vos - lib/coq/user-contrib/Ltac2/List.vo - lib/coq/user-contrib/Ltac2/List.v - lib/coq/user-contrib/Ltac2/List.glob - lib/coq/user-contrib/Ltac2/Int.vos - lib/coq/user-contrib/Ltac2/Int.vo - lib/coq/user-contrib/Ltac2/Int.v - lib/coq/user-contrib/Ltac2/Int.glob - lib/coq/user-contrib/Ltac2/Init.vos - lib/coq/user-contrib/Ltac2/Init.vo - lib/coq/user-contrib/Ltac2/Init.v - lib/coq/user-contrib/Ltac2/Init.glob - lib/coq/user-contrib/Ltac2/Ind.vos - lib/coq/user-contrib/Ltac2/Ind.vo - lib/coq/user-contrib/Ltac2/Ind.v - lib/coq/user-contrib/Ltac2/Ind.glob - lib/coq/user-contrib/Ltac2/Ident.vos - lib/coq/user-contrib/Ltac2/Ident.vo - lib/coq/user-contrib/Ltac2/Ident.v - lib/coq/user-contrib/Ltac2/Ident.glob - lib/coq/user-contrib/Ltac2/Fresh.vos - lib/coq/user-contrib/Ltac2/Fresh.vo - lib/coq/user-contrib/Ltac2/Fresh.v - lib/coq/user-contrib/Ltac2/Fresh.glob - lib/coq/user-contrib/Ltac2/Env.vos - lib/coq/user-contrib/Ltac2/Env.vo - lib/coq/user-contrib/Ltac2/Env.v - lib/coq/user-contrib/Ltac2/Env.glob - lib/coq/user-contrib/Ltac2/Control.vos - lib/coq/user-contrib/Ltac2/Control.vo - lib/coq/user-contrib/Ltac2/Control.v - lib/coq/user-contrib/Ltac2/Control.glob - lib/coq/user-contrib/Ltac2/Constr.vos - lib/coq/user-contrib/Ltac2/Constr.vo - lib/coq/user-contrib/Ltac2/Constr.v - lib/coq/user-contrib/Ltac2/Constr.glob - lib/coq/user-contrib/Ltac2/Char.vos - lib/coq/user-contrib/Ltac2/Char.vo - lib/coq/user-contrib/Ltac2/Char.v - lib/coq/user-contrib/Ltac2/Char.glob - lib/coq/user-contrib/Ltac2/Bool.vos - lib/coq/user-contrib/Ltac2/Bool.vo - lib/coq/user-contrib/Ltac2/Bool.v - lib/coq/user-contrib/Ltac2/Bool.glob - lib/coq/user-contrib/Ltac2/Array.vos - lib/coq/user-contrib/Ltac2/Array.vo - lib/coq/user-contrib/Ltac2/Array.v - lib/coq/user-contrib/Ltac2/Array.glob - lib/coq/theories/ssrsearch/ssrsearch.vos - lib/coq/theories/ssrsearch/ssrsearch.vo - lib/coq/theories/ssrsearch/ssrsearch.v - lib/coq/theories/ssrsearch/ssrsearch.glob - lib/coq/theories/ssrmatching/ssrmatching.vos - lib/coq/theories/ssrmatching/ssrmatching.vo - lib/coq/theories/ssrmatching/ssrmatching.v - lib/coq/theories/ssrmatching/ssrmatching.glob - lib/coq/theories/ssr/ssrunder.vos - lib/coq/theories/ssr/ssrunder.vo - lib/coq/theories/ssr/ssrunder.v - lib/coq/theories/ssr/ssrunder.glob - lib/coq/theories/ssr/ssrsetoid.vos - lib/coq/theories/ssr/ssrsetoid.vo - lib/coq/theories/ssr/ssrsetoid.v - lib/coq/theories/ssr/ssrsetoid.glob - lib/coq/theories/ssr/ssrfun.vos - lib/coq/theories/ssr/ssrfun.vo - lib/coq/theories/ssr/ssrfun.v - lib/coq/theories/ssr/ssrfun.glob - lib/coq/theories/ssr/ssreflect.vos - lib/coq/theories/ssr/ssreflect.vo - lib/coq/theories/ssr/ssreflect.v - lib/coq/theories/ssr/ssreflect.glob - lib/coq/theories/ssr/ssrclasses.vos - lib/coq/theories/ssr/ssrclasses.vo - lib/coq/theories/ssr/ssrclasses.v - lib/coq/theories/ssr/ssrclasses.glob - lib/coq/theories/ssr/ssrbool.vos - lib/coq/theories/ssr/ssrbool.vo - lib/coq/theories/ssr/ssrbool.v - lib/coq/theories/ssr/ssrbool.glob - lib/coq/theories/setoid_ring/ZArithRing.vos - lib/coq/theories/setoid_ring/ZArithRing.vo - lib/coq/theories/setoid_ring/ZArithRing.v - lib/coq/theories/setoid_ring/ZArithRing.glob - lib/coq/theories/setoid_ring/Rings_Z.vos - lib/coq/theories/setoid_ring/Rings_Z.vo - lib/coq/theories/setoid_ring/Rings_Z.v - lib/coq/theories/setoid_ring/Rings_Z.glob - lib/coq/theories/setoid_ring/Rings_R.vos - lib/coq/theories/setoid_ring/Rings_R.vo - lib/coq/theories/setoid_ring/Rings_R.v - lib/coq/theories/setoid_ring/Rings_R.glob - lib/coq/theories/setoid_ring/Rings_Q.vos - lib/coq/theories/setoid_ring/Rings_Q.vo - lib/coq/theories/setoid_ring/Rings_Q.v - lib/coq/theories/setoid_ring/Rings_Q.glob - lib/coq/theories/setoid_ring/Ring_theory.vos - lib/coq/theories/setoid_ring/Ring_theory.vo - lib/coq/theories/setoid_ring/Ring_theory.v - lib/coq/theories/setoid_ring/Ring_theory.glob - lib/coq/theories/setoid_ring/Ring_tac.vos - lib/coq/theories/setoid_ring/Ring_tac.vo - lib/coq/theories/setoid_ring/Ring_tac.v - lib/coq/theories/setoid_ring/Ring_tac.glob - lib/coq/theories/setoid_ring/Ring_polynom.vos - lib/coq/theories/setoid_ring/Ring_polynom.vo - lib/coq/theories/setoid_ring/Ring_polynom.v - lib/coq/theories/setoid_ring/Ring_polynom.glob - lib/coq/theories/setoid_ring/Ring_base.vos - lib/coq/theories/setoid_ring/Ring_base.vo - lib/coq/theories/setoid_ring/Ring_base.v - lib/coq/theories/setoid_ring/Ring_base.glob - lib/coq/theories/setoid_ring/Ring.vos - lib/coq/theories/setoid_ring/Ring.vo - lib/coq/theories/setoid_ring/Ring.v - lib/coq/theories/setoid_ring/Ring.glob - lib/coq/theories/setoid_ring/RealField.vos - lib/coq/theories/setoid_ring/RealField.vo - lib/coq/theories/setoid_ring/RealField.v - lib/coq/theories/setoid_ring/RealField.glob - lib/coq/theories/setoid_ring/Ncring_tac.vos - lib/coq/theories/setoid_ring/Ncring_tac.vo - lib/coq/theories/setoid_ring/Ncring_tac.v - lib/coq/theories/setoid_ring/Ncring_tac.glob - lib/coq/theories/setoid_ring/Ncring_polynom.vos - lib/coq/theories/setoid_ring/Ncring_polynom.vo - lib/coq/theories/setoid_ring/Ncring_polynom.v - lib/coq/theories/setoid_ring/Ncring_polynom.glob - lib/coq/theories/setoid_ring/Ncring_initial.vos - lib/coq/theor [...] truncated predicate.cmt - lib/coq-core/clib/predicate.cmi - lib/coq-core/clib/orderedType.mli - lib/coq-core/clib/orderedType.ml - lib/coq-core/clib/orderedType.cmx - lib/coq-core/clib/orderedType.cmti - lib/coq-core/clib/orderedType.cmt - lib/coq-core/clib/orderedType.cmi - lib/coq-core/clib/option.mli - lib/coq-core/clib/option.ml - lib/coq-core/clib/option.cmx - lib/coq-core/clib/option.cmti - lib/coq-core/clib/option.cmt - lib/coq-core/clib/option.cmi - lib/coq-core/clib/neList.mli - lib/coq-core/clib/neList.ml - lib/coq-core/clib/neList.cmx - lib/coq-core/clib/neList.cmti - lib/coq-core/clib/neList.cmt - lib/coq-core/clib/neList.cmi - lib/coq-core/clib/monad.mli - lib/coq-core/clib/monad.ml - lib/coq-core/clib/monad.cmx - lib/coq-core/clib/monad.cmti - lib/coq-core/clib/monad.cmt - lib/coq-core/clib/monad.cmi - lib/coq-core/clib/minisys.ml - lib/coq-core/clib/minisys.cmx - lib/coq-core/clib/minisys.cmt - lib/coq-core/clib/minisys.cmi - lib/coq-core/clib/int.mli - lib/coq-core/clib/int.ml - lib/coq-core/clib/int.cmx - lib/coq-core/clib/int.cmti - lib/coq-core/clib/int.cmt - lib/coq-core/clib/int.cmi - lib/coq-core/clib/iStream.mli - lib/coq-core/clib/iStream.ml - lib/coq-core/clib/iStream.cmx - lib/coq-core/clib/iStream.cmti - lib/coq-core/clib/iStream.cmt - lib/coq-core/clib/iStream.cmi - lib/coq-core/clib/heap.mli - lib/coq-core/clib/heap.ml - lib/coq-core/clib/heap.cmx - lib/coq-core/clib/heap.cmti - lib/coq-core/clib/heap.cmt - lib/coq-core/clib/heap.cmi - lib/coq-core/clib/hashset.mli - lib/coq-core/clib/hashset.ml - lib/coq-core/clib/hashset.cmx - lib/coq-core/clib/hashset.cmti - lib/coq-core/clib/hashset.cmt - lib/coq-core/clib/hashset.cmi - lib/coq-core/clib/hashcons.mli - lib/coq-core/clib/hashcons.ml - lib/coq-core/clib/hashcons.cmx - lib/coq-core/clib/hashcons.cmti - lib/coq-core/clib/hashcons.cmt - lib/coq-core/clib/hashcons.cmi - lib/coq-core/clib/hMap.mli - lib/coq-core/clib/hMap.ml - lib/coq-core/clib/hMap.cmx - lib/coq-core/clib/hMap.cmti - lib/coq-core/clib/hMap.cmt - lib/coq-core/clib/hMap.cmi - lib/coq-core/clib/exninfo.mli - lib/coq-core/clib/exninfo.ml - lib/coq-core/clib/exninfo.cmx - lib/coq-core/clib/exninfo.cmti - lib/coq-core/clib/exninfo.cmt - lib/coq-core/clib/exninfo.cmi - lib/coq-core/clib/dyn.mli - lib/coq-core/clib/dyn.ml - lib/coq-core/clib/dyn.cmx - lib/coq-core/clib/dyn.cmti - lib/coq-core/clib/dyn.cmt - lib/coq-core/clib/dyn.cmi - lib/coq-core/clib/diff2.mli - lib/coq-core/clib/diff2.ml - lib/coq-core/clib/diff2.cmx - lib/coq-core/clib/diff2.cmti - lib/coq-core/clib/diff2.cmt - lib/coq-core/clib/diff2.cmi - lib/coq-core/clib/clib.cmxs - lib/coq-core/clib/clib.cmxa - lib/coq-core/clib/clib.cma - lib/coq-core/clib/clib.a - lib/coq-core/clib/cUnix.mli - lib/coq-core/clib/cUnix.ml - lib/coq-core/clib/cUnix.cmx - lib/coq-core/clib/cUnix.cmti - lib/coq-core/clib/cUnix.cmt - lib/coq-core/clib/cUnix.cmi - lib/coq-core/clib/cThread.mli - lib/coq-core/clib/cThread.ml - lib/coq-core/clib/cThread.cmx - lib/coq-core/clib/cThread.cmti - lib/coq-core/clib/cThread.cmt - lib/coq-core/clib/cThread.cmi - lib/coq-core/clib/cString.mli - lib/coq-core/clib/cString.ml - lib/coq-core/clib/cString.cmx - lib/coq-core/clib/cString.cmti - lib/coq-core/clib/cString.cmt - lib/coq-core/clib/cString.cmi - lib/coq-core/clib/cSig.mli - lib/coq-core/clib/cSig.cmti - lib/coq-core/clib/cSig.cmi - lib/coq-core/clib/cSet.mli - lib/coq-core/clib/cSet.ml - lib/coq-core/clib/cSet.cmx - lib/coq-core/clib/cSet.cmti - lib/coq-core/clib/cSet.cmt - lib/coq-core/clib/cSet.cmi - lib/coq-core/clib/cObj.mli - lib/coq-core/clib/cObj.ml - lib/coq-core/clib/cObj.cmx - lib/coq-core/clib/cObj.cmti - lib/coq-core/clib/cObj.cmt - lib/coq-core/clib/cObj.cmi - lib/coq-core/clib/cMap.mli - lib/coq-core/clib/cMap.ml - lib/coq-core/clib/cMap.cmx - lib/coq-core/clib/cMap.cmti - lib/coq-core/clib/cMap.cmt - lib/coq-core/clib/cMap.cmi - lib/coq-core/clib/cList.mli - lib/coq-core/clib/cList.ml - lib/coq-core/clib/cList.cmx - lib/coq-core/clib/cList.cmti - lib/coq-core/clib/cList.cmt - lib/coq-core/clib/cList.cmi - lib/coq-core/clib/cEphemeron.mli - lib/coq-core/clib/cEphemeron.ml - lib/coq-core/clib/cEphemeron.cmx - lib/coq-core/clib/cEphemeron.cmti - lib/coq-core/clib/cEphemeron.cmt - lib/coq-core/clib/cEphemeron.cmi - lib/coq-core/clib/cArray.mli - lib/coq-core/clib/cArray.ml - lib/coq-core/clib/cArray.cmx - lib/coq-core/clib/cArray.cmti - lib/coq-core/clib/cArray.cmt - lib/coq-core/clib/cArray.cmi - lib/coq-core/boot/util.ml - lib/coq-core/boot/path.ml - lib/coq-core/boot/env.mli - lib/coq-core/boot/env.ml - lib/coq-core/boot/boot__Util.cmx - lib/coq-core/boot/boot__Util.cmt - lib/coq-core/boot/boot__Util.cmi - lib/coq-core/boot/boot__Path.cmx - lib/coq-core/boot/boot__Path.cmt - lib/coq-core/boot/boot__Path.cmi - lib/coq-core/boot/boot__Env.cmx - lib/coq-core/boot/boot__Env.cmti - lib/coq-core/boot/boot__Env.cmt - lib/coq-core/boot/boot__Env.cmi - lib/coq-core/boot/boot.ml - lib/coq-core/boot/boot.cmxs - lib/coq-core/boot/boot.cmxa - lib/coq-core/boot/boot.cmx - lib/coq-core/boot/boot.cmt - lib/coq-core/boot/boot.cmi - lib/coq-core/boot/boot.cma - lib/coq-core/boot/boot.a - lib/coq-core/META - doc/coqide-server/README.md - doc/coqide-server/LICENSE - doc/coq-core/README.md - doc/coq-core/LICENSE - bin/votour - bin/ocamllibdep - bin/csdpcert - bin/coqworkmgr - bin/coqwc - bin/coqtop.opt - bin/coqtop.byte - bin/coqtop - bin/coqtacticworker.opt - bin/coqqueryworker.opt - bin/coqproofworker.opt - bin/coqpp - bin/coqnative - bin/coqidetop.opt - bin/coqidetop.byte - bin/coqdoc - bin/coqdep - bin/coqchk - bin/coqc.byte - bin/coqc - bin/coq_makefile - bin/coq-tex Remove them anyway? [y/N] y [NOTE] While removing coq.dev: not removing non-empty directories: - share/texmf/tex/latex/misc - lib/coqide-server/protocol - lib/coqide-server/core - lib/coq/user-contrib/Ltac2 - lib/coq/theories/ssrsearch - lib/coq/theories/ssrmatching - lib/coq/theories/setoid_ring - lib/coq/theories/rtauto - lib/coq/theories/omega - lib/coq/theories/nsatz - lib/coq/theories/micromega - lib/coq/theories/funind - lib/coq/theories/extraction - lib/coq/theories/derive - lib/coq/theories/btauto - lib/coq/theories/ZArith - lib/coq/theories/Wellfounded - lib/coq/theories/Vectors - lib/coq/theories/Unicode - lib/coq/theories/Structures - lib/coq/theories/Strings - lib/coq/theories/Sorting - lib/coq/theories/Sets - lib/coq/theories/Setoids - lib/coq/theories/Relations - lib/coq/theories/Reals/Cauchy - lib/coq/theories/Reals/Abstract - lib/coq/theories/QArith - lib/coq/theories/Program - lib/coq/theories/PArith - lib/coq/theories/Numbers/Natural/Peano - lib/coq/theories/Numbers/Natural/Binary - lib/coq/theories/Numbers/Natural/Abstract - lib/coq/theories/Numbers/NatInt - lib/coq/theories/Numbers/Integer/NatPairs - lib/coq/theories/Numbers/Integer/Binary - lib/coq/theories/Numbers/Integer/Abstract - lib/coq/theories/Numbers/Cyclic/ZModulo - lib/coq/theories/Numbers/Cyclic/Int63 - lib/coq/theories/Numbers/Cyclic/Int31 - lib/coq/theories/Numbers/Cyclic/Abstract - lib/coq/theories/NArith - lib/coq/theories/MSets - lib/coq/theories/Logic - lib/coq/theories/Lists - lib/coq/theories/Init - lib/coq/theories/Floats - lib/coq/theories/FSets - lib/coq/theories/Compat - lib/coq/theories/Classes - lib/coq/theories/Bool - lib/coq/theories/Array - lib/coq/theories/Arith - lib/coq-core/vm - lib/coq-core/vernac - lib/coq-core/toplevel - lib/coq-core/top_printers - lib/coq-core/tools/coqdoc - lib/coq-core/tactics - lib/coq-core/sysinit - lib/coq-core/stm - lib/coq-core/proofs - lib/coq-core/printing - lib/coq-core/pretyping - lib/coq-core/plugins/zify - lib/coq-core/plugins/tutorial/p3 - lib/coq-core/plugins/tutorial/p2 - lib/coq-core/plugins/tutorial/p1 - lib/coq-core/plugins/tutorial/p0 - lib/coq-core/plugins/tauto - lib/coq-core/plugins/ssrsearch - lib/coq-core/plugins/ssrmatching - lib/coq-core/plugins/ssreflect - lib/coq-core/plugins/rtauto - lib/coq-core/plugins/ring - lib/coq-core/plugins/number_string_notation - lib/coq-core/plugins/nsatz - lib/coq-core/plugins/micromega - lib/coq-core/plugins/ltac2 - lib/coq-core/plugins/funind - lib/coq-core/plugins/firstorder - lib/coq-core/plugins/extraction - lib/coq-core/plugins/derive - lib/coq-core/plugins/cc - lib/coq-core/plugins/btauto - lib/coq-core/parsing - lib/coq-core/library - lib/coq-core/kernel - lib/coq-core/interp - lib/coq-core/gramlib - lib/coq-core/engine - lib/coq-core/config - lib/coq-core/clib - lib/coq-core/boot - doc/coqide-server - doc/coq-core -&gt; removed coq.dev Done. # Run eval $(opam env) to update the current shell environment opam: --unlock-base was removed in version 2.1 of the opam CLI, but version 2.1 has been requested. Use --update-invariant instead or set OPAMCLI environment variable to 2.0. The middle of the output is truncated (maximum 20000 characters) </pre></dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "851e8d0ff589192998df312efe9b8c9e", "timestamp": "", "source": "github", "line_count": 706, "max_line_length": 260, "avg_line_length": 38.34985835694051, "alnum_prop": 0.655881809787627, "repo_name": "coq-bench/coq-bench.github.io", "id": "e5178018edf74220c667ed4d27de23cc0da731c4", "size": "27080", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.13.1-2.1.0/extra-dev/dev/label/1.0.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
module Travicator module Verifier # Verifier states. UNKNOWN = 0 RUNNING = 1 SUCCESS = 2 FAILURE = 3 end end
{ "content_hash": "6c32ba1eba25f790c63afeabd5f5d9a2", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 22, "avg_line_length": 13.4, "alnum_prop": 0.6119402985074627, "repo_name": "afterburner/travicator", "id": "e867afcfc35568a19fafc409a03cf1708a60e996", "size": "134", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/travicator/verifier.rb", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "1224" }, { "name": "Ruby", "bytes": "16749" } ], "symlink_target": "" }
import { FeatureRow } from '../../features/user/featureRow'; import { Geometry } from 'geojson'; import { CrsGeometry } from '../../types/CrsGeometry'; /** * Feature Paint Cache. * @module tiles/features */ /** * Constructor, created with cache size of {@link #DEFAULT_GEOMETRY_CACHE_SIZE} * @constructor */ export class GeometryCache { public static readonly DEFAULT_GEOMETRY_CACHE_SIZE = 100; geometryCache: Record<number, Geometry & CrsGeometry>; accessHistory: number[]; constructor(public cacheSize: number = GeometryCache.DEFAULT_GEOMETRY_CACHE_SIZE) { // this.cacheSize = size !== null ? size : GeometryCache.DEFAULT_GEOMETRY_CACHE_SIZE; this.geometryCache = {}; this.accessHistory = []; } /** * Get the cached geometry for the feature row * @param featureRow * @returns {module:tiles/features~Geometry} */ getGeometryForFeatureRow(featureRow: FeatureRow): Geometry & CrsGeometry { return this.getGeometry(featureRow.id); } /** * Get the cached geometry for the feature row id or null if not cached * @param {Number} featureRowId feature row id * @return {module:tiles/features~Geometry} geometry or null */ getGeometry(featureRowId: number): Geometry & CrsGeometry { const Geometry = this.geometryCache[featureRowId]; if (!!Geometry) { const index = this.accessHistory.indexOf(featureRowId); if (index > -1) { this.accessHistory.splice(index, 1); } this.accessHistory.push(featureRowId); } return Geometry; } /** * Cache the Geometry for the feature row id * @param {Number} featureRowId feature row id * @param {Object} geometry geometry */ setGeometry(featureRowId: number, geometry: Geometry & CrsGeometry): void { const index = this.accessHistory.indexOf(featureRowId); if (index > -1) { this.accessHistory.splice(index, 1); } this.geometryCache[featureRowId] = geometry; this.accessHistory.push(featureRowId); if (Object.keys(this.geometryCache).length > this.cacheSize) { const featureId = this.accessHistory.shift(); if (featureId) { delete this.geometryCache[featureId]; } } } /** * Remove the cached Geometry for the style row id * @param {Number} featureRowId style row id * @return {module:tiles/features~Geometry} removed feature paint or null */ remove(featureRowId: number): Geometry & CrsGeometry { const removed = this.geometryCache[featureRowId]; delete this.geometryCache[featureRowId]; if (!!removed) { const index = this.accessHistory.indexOf(featureRowId); if (index > -1) { this.accessHistory.splice(index, 1); } } return removed; } /** * Clear the cache */ clear(): void { this.geometryCache = {}; this.accessHistory = []; } /** * Resize the cache * @param {Number} maxSize max size */ resize(maxSize: number): void { this.cacheSize = maxSize; const keys = Object.keys(this.geometryCache); if (keys.length > maxSize) { const numberToRemove = keys.length - maxSize; for (let i = 0; i < numberToRemove; i++) { const featureRowId = this.accessHistory.shift(); if (!!featureRowId) { delete this.geometryCache[featureRowId]; } } } } }
{ "content_hash": "4872e2475112a9ae7d84bea8fd35fc09", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 89, "avg_line_length": 29.47787610619469, "alnum_prop": 0.6574602221555088, "repo_name": "ngageoint/geopackage-js", "id": "591da7acb91dfb028229cff0dcff304be79a5764", "size": "3331", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/tiles/features/geometryCache.ts", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "453" }, { "name": "JavaScript", "bytes": "591211" }, { "name": "TypeScript", "bytes": "1034978" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class IllegalOauthKey extends IllegalArgumentException { private final String MESSAGE; public IllegalOauthKey(final String MESSAGE) { this.MESSAGE = MESSAGE; } @Override public String getMessage() { return MESSAGE; } }
{ "content_hash": "15e7916af6640090740f22908a4c70a9", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 75, "avg_line_length": 28.93103448275862, "alnum_prop": 0.7127532777115614, "repo_name": "AWildBeard/WildChat", "id": "411315acdefa34e0f476f80b3c80ea8a3c83d881", "size": "839", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/main/java/IllegalOauthKey.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "650" }, { "name": "Java", "bytes": "130167" }, { "name": "Shell", "bytes": "133" } ], "symlink_target": "" }
require 'yt/models/comment' module Yt module Models # @private # Provides methods to interact with the snippet of YouTube resources. # @see https://developers.google.com/youtube/v3/docs/channels#resource # @see https://developers.google.com/youtube/v3/docs/videos#resource # @see https://developers.google.com/youtube/v3/docs/playlists#resource # @see https://developers.google.com/youtube/v3/docs/playlistItems#resource # @see https://developers.google.com/youtube/v3/docs/commentThreads#resource # @see https://developers.google.com/youtube/v3/docs/comments#resource class Snippet < Base attr_reader :data def initialize(options = {}) @data = options[:data] @auth = options[:auth] end has_attribute :title, default: '' has_attribute :description, default: '' has_attribute :published_at, type: Time has_attribute :channel_id has_attribute :channel_title has_attribute :tags, default: [] has_attribute :category_id has_attribute :live_broadcast_content has_attribute :playlist_id has_attribute :position, type: Integer has_attribute :resource_id, default: {} has_attribute :thumbnails, default: {} has_attribute :video_id has_attribute :total_reply_count, type: Integer has_attribute :author_display_name has_attribute :text_display has_attribute :parent_id has_attribute :like_count, type: Integer has_attribute :updated_at, type: Time def thumbnail_url(size = :default) thumbnails.fetch(size.to_s, {})['url'] end def public? @public ||= data.fetch 'isPublic', false end def can_reply? @can_reply ||= data.fetch 'canReply', false end def top_level_comment @top_level_comment ||= Yt::Comment.new data['topLevelComment'].symbolize_keys end # Returns whether YouTube API includes all attributes in this snippet. # For instance, YouTube API only returns tags and categoryId on # Videos#list, not on Videos#search. And returns position on # PlaylistItems#list, not on PlaylistItems#insert. # This method is used to guarantee that, when a video was instantiated # by one of the methods above, an additional call to is made to retrieve # the full snippet in case an attribute is missing. # @see https://developers.google.com/youtube/v3/docs/videos # @return [Boolean] whether YouTube API includes the complete snippet. def complete? @complete ||= data.fetch :complete, true end end end end
{ "content_hash": "a4b4e95591225d74b700dba769bc7ae3", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 85, "avg_line_length": 37.16901408450704, "alnum_prop": 0.6684350132625995, "repo_name": "jacknguyen/yt", "id": "603a7f4e2df704bff1a17d428914b1c406444bbb", "size": "2639", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/yt/models/snippet.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Logos", "bytes": "158" }, { "name": "Ruby", "bytes": "588883" } ], "symlink_target": "" }
/*** * Interface for Chatbox method * */ package RMIInterfaces; import ChatBox.ChatClient; import java.rmi.*; import java.util.ArrayList; public interface ChatServerInterface extends Remote { void registerChatClient(ChatClient peer) throws RemoteException; ArrayList<ChatClient> getChatClients() throws RemoteException; void kickClient(String userName) throws RemoteException; }
{ "content_hash": "dcb221d1d350023a8336eed6c7b186dd", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 68, "avg_line_length": 18.318181818181817, "alnum_prop": 0.771712158808933, "repo_name": "Karen-he/DS_Proj2", "id": "33aa86732cf3f63db67a57ec4b682f2c9d8ae81e", "size": "403", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/RMIInterfaces/ChatServerInterface.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "67719" } ], "symlink_target": "" }
package resourceapply import ( "k8s.io/klog" storagev1 "k8s.io/api/storage/v1" "k8s.io/apimachinery/pkg/api/equality" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" storageclientv1 "k8s.io/client-go/kubernetes/typed/storage/v1" "github.com/openshift/library-go/pkg/operator/events" "github.com/openshift/library-go/pkg/operator/resource/resourcemerge" ) // ApplyStorageClass merges objectmeta, tries to write everything else func ApplyStorageClass(client storageclientv1.StorageClassesGetter, recorder events.Recorder, required *storagev1.StorageClass) (*storagev1.StorageClass, bool, error) { existing, err := client.StorageClasses().Get(required.Name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { actual, err := client.StorageClasses().Create(required) reportCreateEvent(recorder, required, err) return actual, true, err } if err != nil { return nil, false, err } modified := resourcemerge.BoolPtr(false) existingCopy := existing.DeepCopy() resourcemerge.EnsureObjectMeta(modified, &existingCopy.ObjectMeta, required.ObjectMeta) contentSame := equality.Semantic.DeepEqual(existingCopy, required) if contentSame && !*modified { return existingCopy, false, nil } objectMeta := existingCopy.ObjectMeta.DeepCopy() existingCopy = required.DeepCopy() existingCopy.ObjectMeta = *objectMeta if klog.V(4) { klog.Infof("StorageClass %q changes: %v", required.Name, JSONPatch(existing, existingCopy)) } // TODO if provisioner, parameters, reclaimpolicy, or volumebindingmode are different, update will fail so delete and recreate actual, err := client.StorageClasses().Update(existingCopy) reportUpdateEvent(recorder, required, err) return actual, true, err }
{ "content_hash": "720e72cd2931179101d7e1aff14f9c91", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 159, "avg_line_length": 35.08, "alnum_prop": 0.774230330672748, "repo_name": "sdminonne/origin", "id": "28aaa8d83aa8aa9a1cbd60a101c4ba1e198e787b", "size": "1754", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "vendor/github.com/openshift/library-go/pkg/operator/resource/resourceapply/storage.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "921" }, { "name": "Dockerfile", "bytes": "1668" }, { "name": "Go", "bytes": "2136606" }, { "name": "Makefile", "bytes": "6549" }, { "name": "Python", "bytes": "14374" }, { "name": "Shell", "bytes": "315233" } ], "symlink_target": "" }
var config = require('./config') , async = require('async') , should = require('should') , Join = require('../lib').Join , mongodb = require('mongodb') , Db = mongodb.Db , Server = mongodb.Server ; describe('mongo-join', function() { describe('#join()', function() { it('Should join two documents into a third document based on keys in that third doc', function(done) { var client, collection, subCollection; // Construct 3 documents and insert them into a collection that will be removed. // There is a master document and 2 sub-documents referenced by the master doc in arbitrary fields. var master = { name: 'master-foo', created: new Date(), sub1: 'sub-bar', // there should be an index on the 'name' field of this referenced doc sub2: 'sub-baz' // there should be an index on the 'name' field of this referenced doc }; var otherMaster = { name: 'master-goo', created: new Date(), sub1: 'sub-bar', // there should be an index on the 'name' field of this referenced doc }; var subDoc1 = { name: 'sub-bar', // should have index amount: 10, created: new Date() }; var subDoc2 = { name: 'sub-baz', // should have index amount: 42, description: 'answer to life, the universe, and everything', created: new Date() }; var join; async.waterfall([ function openNewDbClient(callback) { var opts = {safe: true}; client = new Db(config.dbname, new Server(config.host, config.port), opts); client.open(callback); }, function authenticate(client, callback) { should.exist(client); join = new Join(client).on({ field: 'sub1', to: 'name', from: 'subord' }).on({ field: 'sub2', as: 'sub2-doc', to: 'name', from: 'subord' }); var doAuth = (config.username && config.password); doAuth ? client.authenticate(config.username, config.password, callback) : callback(null, true); }, function collection(authed, callback) { authed.should.be.true; client.collection('master', callback); }, function removeAll(coll, callback) { should.exist(coll); collection = coll; collection.remove({}, callback); }, function subCollection(result, callback) { client.collection('subord', callback); }, function subRemoveAll(coll, callback) { should.exist(coll); subCollection = coll; subCollection.remove({}, callback); }, function ensureIndex(result, callback) { subCollection.ensureIndex({name: 1}, {w: 1, unique: true}, callback); }, function insertDocs(index, callback) { collection.insert(master, {w: 0}); collection.insert(otherMaster, {w: 0}); subCollection.insert(subDoc1, {w: 0}); subCollection.insert(subDoc2, {w: 0}); return callback(null, true); }, function joinSubDoc1(cursor, callback) { join.findOne(collection, {name: 'master-foo'}, function(err, doc) { if (doc) { // console.log('\nJoined result (findOne):'); // console.dir(doc); callback(null, null) } }); }, function joinSubDoc2(ignore, callback) { join.findOne(collection, {name: 'master-goo'}, function(err, doc) { if (doc) { // console.log('\nJoined result (findOne):'); // console.dir(doc); callback(null, null); } }); }, function dropCollection(result, callback) { collection.drop(callback); }, function dropSubCollection(result, callback) { subCollection.drop(callback); }, function closeDbClient(ignore, callback) { client.close(); return done(); } ], function(err) { // test will fail here automatically if there is an error }); }); }) });
{ "content_hash": "beace460ee2da1f617d56a1c26436e02", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 106, "avg_line_length": 39.00909090909091, "alnum_prop": 0.5415986949429038, "repo_name": "cbumgard/node-mongo-join", "id": "9b8c63c76c409f28ae5e8173b698c511a2ea79bd", "size": "4291", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/mongodb-native-findone.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "38764" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="refresh" content="0;URL=type.N10000000.html"> </head> <body> <p>Redirecting to <a href="type.N10000000.html">type.N10000000.html</a>...</p> <script>location.replace("type.N10000000.html" + location.search + location.hash);</script> </body> </html>
{ "content_hash": "e4c0c6267b39df94a0c015c04b93c6bb", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 95, "avg_line_length": 31.7, "alnum_prop": 0.6750788643533123, "repo_name": "nitro-devs/nitro-game-engine", "id": "60786afc9b022246de40d9bdf9b5dd3cdff063c5", "size": "317", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/typenum/consts/N10000000.t.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CMake", "bytes": "1032" }, { "name": "Rust", "bytes": "59380" } ], "symlink_target": "" }
package org.apache.webbeans.test.interceptors.factory.beans; public interface PartialBeanSuperInterface2<E> { E test(E e); }
{ "content_hash": "9a5d1b39b3d5ca19b5303975918d0336", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 60, "avg_line_length": 18.714285714285715, "alnum_prop": 0.7709923664122137, "repo_name": "apache/openwebbeans", "id": "72870fc3a6d87fed6dcca25be9312abde565e059", "size": "932", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "webbeans-impl/src/test/java/org/apache/webbeans/test/interceptors/factory/beans/PartialBeanSuperInterface2.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4590" }, { "name": "HTML", "bytes": "1236" }, { "name": "Java", "bytes": "4551763" }, { "name": "Shell", "bytes": "10261" } ], "symlink_target": "" }
<html> <head> <title>jcoverage package summary for tools</title><style> <!-- body { background-color: white; } p { text-align: left; margin-top: 10pt; margin-bottom: 10pt; } p, h1, h2, h3, td, th, dt { font-family: verdana, arial, sans-serif; font-size: 10pt; line-height: 100%; margin-left: 0pt; } li { font-family: verdana, arial, sans-serif; font-size: 10pt; line-height: 100%; margin-left: 0pt; } h1 { font-size: 14pt; } h2 { font-size: 12pt; margin-top: 12pt; } pre { line-height: 100%; } tr.yin td { background: #f0f0f0; } tr.yin td { background: #f0f0f0; } tr.highlight td { background: #ffff44; } th { border-width: 1px 0px 1px 1px; border-color: black; border-style: solid; text-align: center; } th.remainder { border-width: 1px 1px 1px 1px; } td.lineno { border-width: 0px 0px 0px 1px; border-color: black; border-style: solid; text-align: right; } td.hits { border-width: 0px 0px 0px 1px; border-color: black; border-style: solid; text-align: right; } td.code { border-width: 0px 0px 0px 1px; border-color: black; border-style: solid; text-align: left; } td.coverage { text-align: right; } td.lines { text-align: right; } td.files { text-align: right; } .navbar { margin-top: 0pt; color: white; vertical-align: top; text-align: left; font-size: 10pt; margin-left: 0pt; background-color: green; padding: 2pt; padding-left: 4pt; line-height: 120%; } .navbar a { color: white; text-decoration: none; } .navbar a:visited { color: white; text-decoration: none; } .navbar a:link { color: white; text-decoration: none; } .navbar a:hover { color: white; text-decoration: none; } p.view a { color: #0000aa; text-decoration: none; } p.legalleft { font-size: 8pt; margin-top: 6pt; border-top: 1px solid black; color: #444444; text-align: left; } p.legalright { font-size: 8pt; margin-top: 6pt; border-top: 1px solid black; color: #444444; text-align: right; } a:link { color: #0000aa; text-decoration: none; } a:visited { color: #0000aa; text-decoration: none; } --> </style> </head> <body> <img src="http://jcoverage.com/images/shim@product.version@.gif" width="1" height="1"> <p class="navbar"><b><a href="http://jcoverage.com">jcoverage</a></b> | <a href="index.html">summary</a> | package <p> <h1>Package summary for tools</h1><h2>Overall package</h2><table cellpadding="2" cellspacing="0" width="85%"> <tr><th>packagename</th><th>files</th><th>lines</th><th>%line</th><th width="100">indicator</th><th>%branch</th><th width="100" class="remainder">indicator</th></tr> <tr class="yin"> <td class="packagename"> <a href=tools.html>tools</a></td> <td class="files"> <a href=tools.html>6</a></td> <td class="lines"> <a href=tools.html>1242</a></td> <td class="coverage"> <a href=tools.html>76%</a></td> <td><img src="images/green.gif" height="10" width="76"/><img src="images/red.gif" height="10" width="24"/></td> <td class="coverage"> <a href=tools.html>79%</a></td> <td><img src="images/green.gif" height="10" width="79"/><img src="images/red.gif" height="10" width="21"/></td> </tr> </table> <h2>Set view:</h2><p class="view"> <b>By Name</b> <br> <a href="cova/tools.html">By Coverage (Most covered first)</a> <br> <a href="covd/tools.html">By Coverage (Least covered first)</a> <br> <h2>Classes</h2><table cellpadding="2" cellspacing="0" width="85%"> <tr><th>file</th><th>lines</th><th>%line</th><th width="100">indicator</th><th>%branch</th><th width="100" class="remainder">indicator</th></tr> <tr class="yin"> <td class="filename"> <a href=tools.CrossPlatform.html>tools.CrossPlatform</a></td> <td class="lines"> <a href=tools.CrossPlatform.html>8</a></td> <td class="coverage"> <a href=tools.CrossPlatform.html>100%</a></td> <td><img src="images/green.gif" height="10" width="100"/></td> <td class="coverage"> <a href=tools.CrossPlatform.html>100%</a></td> <td><img src="images/green.gif" height="10" width="100"/></td> </tr> <tr class="yang"> <td class="filename"> <a href=tools.DateCalculator.html>tools.DateCalculator</a></td> <td class="lines"> <a href=tools.DateCalculator.html>200</a></td> <td class="coverage"> <a href=tools.DateCalculator.html>89%</a></td> <td><img src="images/green.gif" height="10" width="89"/><img src="images/red.gif" height="10" width="11"/></td> <td class="coverage"> <a href=tools.DateCalculator.html>86%</a></td> <td><img src="images/green.gif" height="10" width="86"/><img src="images/red.gif" height="10" width="14"/></td> </tr> <tr class="yin"> <td class="filename"> <a href=tools.FileFilter.html>tools.FileFilter</a></td> <td class="lines"> <a href=tools.FileFilter.html>43</a></td> <td class="coverage"> <a href=tools.FileFilter.html>58%</a></td> <td><img src="images/green.gif" height="10" width="58"/><img src="images/red.gif" height="10" width="42"/></td> <td class="coverage"> <a href=tools.FileFilter.html>64%</a></td> <td><img src="images/green.gif" height="10" width="64"/><img src="images/red.gif" height="10" width="36"/></td> </tr> <tr class="yang"> <td class="filename"> <a href=tools.MyImage.html>tools.MyImage</a></td> <td class="lines"> <a href=tools.MyImage.html>246</a></td> <td class="coverage"> <a href=tools.MyImage.html>89%</a></td> <td><img src="images/green.gif" height="10" width="89"/><img src="images/red.gif" height="10" width="11"/></td> <td class="coverage"> <a href=tools.MyImage.html>84%</a></td> <td><img src="images/green.gif" height="10" width="84"/><img src="images/red.gif" height="10" width="16"/></td> </tr> <tr class="yin"> <td class="filename"> <a href=tools.MyMath.html>tools.MyMath</a></td> <td class="lines"> <a href=tools.MyMath.html>248</a></td> <td class="coverage"> <a href=tools.MyMath.html>79%</a></td> <td><img src="images/green.gif" height="10" width="79"/><img src="images/red.gif" height="10" width="21"/></td> <td class="coverage"> <a href=tools.MyMath.html>70%</a></td> <td><img src="images/green.gif" height="10" width="70"/><img src="images/red.gif" height="10" width="30"/></td> </tr> <tr class="yang"> <td class="filename"> <a href=tools.ToolBox.html>tools.ToolBox</a></td> <td class="lines"> <a href=tools.ToolBox.html>497</a></td> <td class="coverage"> <a href=tools.ToolBox.html>65%</a></td> <td><img src="images/green.gif" height="10" width="65"/><img src="images/red.gif" height="10" width="35"/></td> <td class="coverage"> <a href=tools.ToolBox.html>71%</a></td> <td><img src="images/green.gif" height="10" width="71"/><img src="images/red.gif" height="10" width="29"/></td> </tr> </table> <p> <p class="navbar"><b><a href="http://jcoverage.com">jcoverage</a></b> | <a href="index.html">summary</a> | package <p> <table width="100%" cellpadding="0" cellspacing="0"><tr valign="top"><td> <p class="legalleft"> this report was generated by version @product.version@ of jcoverage.<br> visit <a href="http://www.jcoverage.com">www.jcoverage.com</a> for updates.<br> </td><td> <p class="legalright"> copyright &copy; 2003, jcoverage ltd. all rights reserved.<br> Java is a trademark of Sun Microsystems, Inc. in the United States and other countries.<br> </td></tr></table> </body> </html>
{ "content_hash": "d40b2fc9ed2e29c64cd8bd79a58e7c2a", "timestamp": "", "source": "github", "line_count": 285, "max_line_length": 165, "avg_line_length": 24.66315789473684, "alnum_prop": 0.6693697538767961, "repo_name": "kgidev/maserJ", "id": "f1bdc649ede5a9971e6e712c5e213ffa9c0c8bd4", "size": "7029", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Jcoverage/tools.html", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2471" }, { "name": "Java", "bytes": "2417387" }, { "name": "PHP", "bytes": "47" }, { "name": "Perl", "bytes": "4337" }, { "name": "Shell", "bytes": "2363" }, { "name": "XSLT", "bytes": "2394" } ], "symlink_target": "" }
""" Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. In order for this to work, the AWS credentials need to be set via environment variables! Make sure to set following environment variables: $ export AWS_ACCESS_KEY_ID=<Your AWS Access Key ID> $ export AWS_SECRET_ACCESS_KEY=<Your AWS Secret Access Key> """ import argparse from ConfigurationHandler import ConfigurationHandler from libs3 import download, logger from version import __version__ #################################################################### # # FUNCTIONS # #################################################################### def parse_shell_parameters(): """ Parse the provided shell parameters """ usage = '%(prog)s [-h, --help] [command]' description = '%(prog)s AWS S3 SquashFS Image Downloader' epilog = "And now you're in control!" parser = argparse.ArgumentParser(description=description, epilog=epilog, usage=usage) parser.add_argument('-v', '--version', action='version', version='%(prog)s ver.{0}'.format(__version__)) parser.add_argument('-o', '--output', action='store', help="Output file (under which to store the S3 object)", required=True) parser.add_argument('-k', '--key', action='store', help="The identifying key for this image in S3", required=True) parser.add_argument('-b', '--bucket', action='store', default=config.get('S3', 'bucket'), help="A valid AWS S3 bucket (default: \"{0}\")".format(config.get('S3', 'bucket'))) log.debug("Shell arguments: {0}".format(parser.parse_args())) return parser.parse_args() def main(): """ Run the whole thing """ # Get the shell arguments args = parse_shell_parameters() # Transfer shell arguments to variables destination_file = args.output bucket = args.bucket image_key = args.key # Ok, all set! We can download the file ... log.debug('Downloading with key: "{0}" from bucket: "{1}" to output file: "{2}" '.format(image_key, bucket, destination_file)) download(destination_file, image_key, bucket) return 0 #################################################################### # # MAIN # #################################################################### if __name__ == "__main__": log = logger.get_logger('s3-image-download') config = ConfigurationHandler().read_configuration() main()
{ "content_hash": "336c91965ad6c2be41b9a3551fb0da13", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 114, "avg_line_length": 35.4, "alnum_prop": 0.6180163214061519, "repo_name": "cloudControl/s3-image-load", "id": "d60bcb09a195e49c81900fc677cd740b53d04953", "size": "3210", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/s3-image-download.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "16214" }, { "name": "Shell", "bytes": "2050" } ], "symlink_target": "" }
import React from 'react'; import { shallow } from 'enzyme'; import ResourceItem from './ResourceItem'; import ResourcePercent from './ResourcePercent'; function createShallowResourceItem({ path = 'path' } = {}) { return shallow( <ResourceItem parameters={{ locale: 'locale', project: 'project', resource: 'resource', }} resource={{ path: path, }} />, ); } describe('<ResourceItem>', () => { it('renders correctly', () => { const wrapper = createShallowResourceItem(); expect(wrapper.find('li')).toHaveLength(1); expect(wrapper.find('a')).toHaveLength(1); expect(wrapper.find('span')).toHaveLength(1); expect(wrapper.find(ResourcePercent)).toHaveLength(1); expect(wrapper.find('a').prop('href')).toEqual('/locale/project/path/'); }); it('sets the className correctly', () => { let wrapper = createShallowResourceItem(); expect(wrapper.find('li.current')).toHaveLength(0); wrapper = createShallowResourceItem({ path: 'resource' }); expect(wrapper.find('li.current')).toHaveLength(1); }); });
{ "content_hash": "28ae8b3f0eb61edf5c47dc7ff2f004c2", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 80, "avg_line_length": 31.487179487179485, "alnum_prop": 0.5716612377850163, "repo_name": "jotes/pontoon", "id": "da194b1cb85b18d8dde70ec0f6f490536d9b8748", "size": "1228", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "frontend/src/core/resource/components/ResourceItem.test.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "226580" }, { "name": "Dockerfile", "bytes": "2640" }, { "name": "FreeMarker", "bytes": "35248" }, { "name": "HTML", "bytes": "151639" }, { "name": "JavaScript", "bytes": "1332848" }, { "name": "Makefile", "bytes": "3551" }, { "name": "Python", "bytes": "1391398" }, { "name": "Shell", "bytes": "3676" } ], "symlink_target": "" }
/** * Typecasts to number, then returns locale aware format (toLocaleString). * @param {*} value * @returns {string} */ module.exports = function(value) { return (+value).toLocaleString(); };
{ "content_hash": "fe2680246ae2149d339637063295a61c", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 74, "avg_line_length": 24.5, "alnum_prop": 0.6785714285714286, "repo_name": "viddamao/Software_paradigm_project", "id": "4a1d9e1279ccc4ef3ecb330554fb646004f5f3ab", "size": "196", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "kcoloring/node_modules/tiny-sprintf/src/f.js", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "1730" }, { "name": "HTML", "bytes": "1687" }, { "name": "Java", "bytes": "33896" }, { "name": "JavaScript", "bytes": "708000" }, { "name": "Makefile", "bytes": "5510" }, { "name": "Prolog", "bytes": "269" } ], "symlink_target": "" }
package org.jboss.resteasy.test.providers.multipart.resource; import org.jboss.resteasy.annotations.providers.multipart.PartType; import javax.ws.rs.FormParam; import javax.ws.rs.HeaderParam; public class ProxyAttachment { @HeaderParam("X-Atlassian-Token") @PartType("text/plain") private String multipartHeader = "nocheck"; @FormParam("file") @PartType("text/plain") private byte[] data; public String getMultipartHeader() { return multipartHeader; } public void setMultipartHeader(String multipartHeader) { this.multipartHeader = multipartHeader; } public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } }
{ "content_hash": "a5244bc248c5041f30b570aa2ab01511", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 67, "avg_line_length": 21.970588235294116, "alnum_prop": 0.6813922356091031, "repo_name": "awhitford/Resteasy", "id": "cb49c35f342bcdaa9de2d004a50739013f3102fe", "size": "747", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/ProxyAttachment.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "226" }, { "name": "Java", "bytes": "8760338" }, { "name": "JavaScript", "bytes": "17786" }, { "name": "Python", "bytes": "4868" }, { "name": "Shell", "bytes": "1606" } ], "symlink_target": "" }
package com.isoftechtraining; /** * Created by Rajesh on 6/25/2016. */ public class Bicycle { public int cadence; public int gear; public int speed; // the Bicycle class has // one constructor // constructor overload public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; } public Bicycle() { } public void printDescription() { System.out.println(cadence +" "+ gear+" " + speed); } // the Bicycle class has // four methods public void setCadence(int newValue) { cadence = newValue; } public void setGear(int newValue) { gear = newValue; } public void applyBrake(int decrement) { speed -= decrement; } public void speedUp(int increment) { speed += increment; } }
{ "content_hash": "370c6291f2024d744a6fb084f3e58f1e", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 69, "avg_line_length": 18.46153846153846, "alnum_prop": 0.559375, "repo_name": "SowjanyaRajesh/first-repo", "id": "e94952fbcfd7d24d86d8274ec8992a3d0ee3807e", "size": "960", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SeleniumTests/src/com/isoftechtraining/Bicycle.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "39730" } ], "symlink_target": "" }
sizers Package ============== :mod:`flow` Module ------------------ .. automodule:: pyface.sizers.flow :members: :undoc-members: :show-inheritance:
{ "content_hash": "0c7380686176d9f5ae77d62764f5b3eb", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 34, "avg_line_length": 14.818181818181818, "alnum_prop": 0.5276073619631901, "repo_name": "brett-patterson/pyface", "id": "822706368d1dcd08e4ae09f6b7cbe7c1b2b82ad2", "size": "163", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "docs/source/api/pyface.sizers.rst", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "648" }, { "name": "Python", "bytes": "2371056" } ], "symlink_target": "" }
package org.asteriskjava.manager.internal; import static org.asteriskjava.manager.ManagerConnectionState.CONNECTED; import static org.asteriskjava.manager.ManagerConnectionState.CONNECTING; import static org.asteriskjava.manager.ManagerConnectionState.DISCONNECTED; import static org.asteriskjava.manager.ManagerConnectionState.DISCONNECTING; import static org.asteriskjava.manager.ManagerConnectionState.INITIAL; import static org.asteriskjava.manager.ManagerConnectionState.RECONNECTING; import java.io.IOException; import java.io.Serializable; import java.net.Socket; import java.net.InetAddress; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.asteriskjava.AsteriskVersion; import org.asteriskjava.manager.*; import org.asteriskjava.manager.action.ChallengeAction; import org.asteriskjava.manager.action.CommandAction; import org.asteriskjava.manager.action.EventGeneratingAction; import org.asteriskjava.manager.action.LoginAction; import org.asteriskjava.manager.action.LogoffAction; import org.asteriskjava.manager.action.ManagerAction; import org.asteriskjava.manager.event.ConnectEvent; import org.asteriskjava.manager.event.DisconnectEvent; import org.asteriskjava.manager.event.ManagerEvent; import org.asteriskjava.manager.event.ProtocolIdentifierReceivedEvent; import org.asteriskjava.manager.event.ResponseEvent; import org.asteriskjava.manager.response.ChallengeResponse; import org.asteriskjava.manager.response.CommandResponse; import org.asteriskjava.manager.response.ManagerError; import org.asteriskjava.manager.response.ManagerResponse; import org.asteriskjava.util.DateUtil; import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; import org.asteriskjava.util.SocketConnectionFacade; import org.asteriskjava.util.internal.SocketConnectionFacadeImpl; import org.asteriskjava.manager.action.UserEventAction; /** * Internal implemention of the ManagerConnection interface. * * @author srt * @version $Id$ * @see org.asteriskjava.manager.ManagerConnectionFactory */ public class ManagerConnectionImpl implements ManagerConnection, Dispatcher { private static final int RECONNECTION_INTERVAL_1 = 50; private static final int RECONNECTION_INTERVAL_2 = 5000; private static final String DEFAULT_HOSTNAME = "localhost"; private static final int DEFAULT_PORT = 5038; private static final int RECONNECTION_VERSION_INTERVAL = 500; private static final int MAX_VERSION_ATTEMPTS = 4; private static final Pattern SHOW_VERSION_PATTERN = Pattern.compile("^(core )?show version.*"); private static final AtomicLong idCounter = new AtomicLong(0); /** * Instance logger. */ private final Log logger = LogFactory.getLog(getClass()); private final long id; /** * Used to construct the internalActionId. */ private AtomicLong actionIdCounter = new AtomicLong(0); /* Config attributes */ /** * Hostname of the Asterisk server to connect to. */ private String hostname = DEFAULT_HOSTNAME; /** * TCP port to connect to. */ private int port = DEFAULT_PORT; /** * <code>true</code> to use SSL for the connection, <code>false</code> * for a plain text connection. */ private boolean ssl = false; /** * The username to use for login as defined in Asterisk's * <code>manager.conf</code>. */ protected String username; /** * The password to use for login as defined in Asterisk's * <code>manager.conf</code>. */ protected String password; /** * The default timeout to wait for a ManagerResponse after sending a * ManagerAction. */ private long defaultResponseTimeout = 2000; /** * The default timeout to wait for the last ResponseEvent after sending an * EventGeneratingAction. */ private long defaultEventTimeout = 5000; /** * The timeout to use when connecting the the Asterisk server. */ private int socketTimeout = 0; /** * Closes the connection (and reconnects) if no input has been read for the given amount * of milliseconds. A timeout of zero is interpreted as an infinite timeout. * * @see Socket#setSoTimeout(int) */ private int socketReadTimeout = 0; /** * <code>true</code> to continue to reconnect after an authentication failure. */ private boolean keepAliveAfterAuthenticationFailure = true; /** * The socket to use for TCP/IP communication with Asterisk. */ private SocketConnectionFacade socket; /** * The thread that runs the reader. */ private Thread readerThread; private final AtomicLong readerThreadCounter = new AtomicLong(0); private final AtomicLong reconnectThreadCounter = new AtomicLong(0); /** * The reader to use to receive events and responses from asterisk. */ private ManagerReader reader; /** * The writer to use to send actions to asterisk. */ private ManagerWriter writer; /** * The protocol identifer Asterisk sends on connect wrapped into an object * to be used as mutex. */ private final ProtocolIdentifierWrapper protocolIdentifier; /** * The version of the Asterisk server we are connected to. */ private AsteriskVersion version; /** * Contains the registered handlers that process the ManagerResponses. * <p/> * Key is the internalActionId of the Action sent and value the * corresponding ResponseListener. */ private final Map<String, SendActionCallback> responseListeners; /** * Contains the event handlers that handle ResponseEvents for the * sendEventGeneratingAction methods. * <p/> * Key is the internalActionId of the Action sent and value the * corresponding EventHandler. */ private final Map<String, ManagerEventListener> responseEventListeners; /** * Contains the event handlers that users registered. */ private final List<ManagerEventListener> eventListeners; protected ManagerConnectionState state = INITIAL; private String eventMask; /** * Creates a new instance. */ public ManagerConnectionImpl() { this.id = idCounter.getAndIncrement(); this.responseListeners = new HashMap<String, SendActionCallback>(); this.responseEventListeners = new HashMap<String, ManagerEventListener>(); this.eventListeners = new ArrayList<ManagerEventListener>(); this.protocolIdentifier = new ProtocolIdentifierWrapper(); } // the following two methods can be overriden when running test cases to // return a mock object protected ManagerReader createReader(Dispatcher dispatcher, Object source) { return new ManagerReaderImpl(dispatcher, source); } protected ManagerWriter createWriter() { return new ManagerWriterImpl(); } /** * Sets the hostname of the asterisk server to connect to. * <p/> * Default is <code>localhost</code>. * * @param hostname the hostname to connect to */ public void setHostname(String hostname) { this.hostname = hostname; } /** * Sets the port to use to connect to the asterisk server. This is the port * specified in asterisk's <code>manager.conf</code> file. * <p/> * Default is 5038. * * @param port the port to connect to */ public void setPort(int port) { if (port <= 0) { this.port = DEFAULT_PORT; } else { this.port = port; } } /** * Sets whether to use SSL. * <p/> * Default is false. * * @param ssl <code>true</code> to use SSL for the connection, * <code>false</code> for a plain text connection. * @since 0.3 */ public void setSsl(boolean ssl) { this.ssl = ssl; } /** * Sets the username to use to connect to the asterisk server. This is the * username specified in asterisk's <code>manager.conf</code> file. * * @param username the username to use for login */ public void setUsername(String username) { this.username = username; } /** * Sets the password to use to connect to the asterisk server. This is the * password specified in Asterisk's <code>manager.conf</code> file. * * @param password the password to use for login */ public void setPassword(String password) { this.password = password; } /** * Sets the time in milliseconds the synchronous method * {@link #sendAction(ManagerAction)} will wait for a response before * throwing a TimeoutException. * <p/> * Default is 2000. * * @param defaultResponseTimeout default response timeout in milliseconds * @since 0.2 */ public void setDefaultResponseTimeout(long defaultResponseTimeout) { this.defaultResponseTimeout = defaultResponseTimeout; } /** * Sets the time in milliseconds the synchronous method * {@link #sendEventGeneratingAction(EventGeneratingAction)} will wait for a * response and the last response event before throwing a TimeoutException. * <p/> * Default is 5000. * * @param defaultEventTimeout default event timeout in milliseconds * @since 0.2 */ public void setDefaultEventTimeout(long defaultEventTimeout) { this.defaultEventTimeout = defaultEventTimeout; } /** * Set to <code>true</code> to try reconnecting to ther asterisk serve * even if the reconnection attempt threw an AuthenticationFailedException. * <p/> * Default is <code>true</code>. * * @param keepAliveAfterAuthenticationFailure * <code>true</code> to try reconnecting to ther asterisk serve * even if the reconnection attempt threw an AuthenticationFailedException, * <code>false</code> otherwise. */ public void setKeepAliveAfterAuthenticationFailure(boolean keepAliveAfterAuthenticationFailure) { this.keepAliveAfterAuthenticationFailure = keepAliveAfterAuthenticationFailure; } /* Implementation of ManagerConnection interface */ public String getUsername() { return username; } public String getPassword() { return password; } public AsteriskVersion getVersion() { return version; } public String getHostname() { return hostname; } public int getPort() { return port; } public boolean isSsl() { return ssl; } public InetAddress getLocalAddress() { return socket.getLocalAddress(); } public int getLocalPort() { return socket.getLocalPort(); } public InetAddress getRemoteAddress() { return socket.getRemoteAddress(); } public int getRemotePort() { return socket.getRemotePort(); } public void registerUserEventClass(Class<? extends ManagerEvent> userEventClass) { if (reader == null) { reader = createReader(this, this); } reader.registerEventClass(userEventClass); } public void setSocketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; } public void setSocketReadTimeout(int socketReadTimeout) { this.socketReadTimeout = socketReadTimeout; } public synchronized void login() throws IOException, AuthenticationFailedException, TimeoutException { login(null); } public synchronized void login(String eventMask) throws IOException, AuthenticationFailedException, TimeoutException { if (state != INITIAL && state != DISCONNECTED) { throw new IllegalStateException("Login may only be perfomed when in state " + "INITIAL or DISCONNECTED, but connection is in state " + state); } state = CONNECTING; this.eventMask = eventMask; try { doLogin(defaultResponseTimeout, eventMask); } finally { if (state != CONNECTED) { state = DISCONNECTED; } } } /** * Does the real login, following the steps outlined below. * <p/> * <ol> * <li>Connects to the asterisk server by calling {@link #connect()} if not * already connected * <li>Waits until the protocol identifier is received but not longer than * timeout ms. * <li>Sends a {@link ChallengeAction} requesting a challenge for authType * MD5. * <li>When the {@link ChallengeResponse} is received a {@link LoginAction} * is sent using the calculated key (MD5 hash of the password appended to * the received challenge). * </ol> * * @param timeout the maximum time to wait for the protocol identifier (in * ms) * @param eventMask the event mask. Set to "on" if all events should be * send, "off" if not events should be sent or a combination of * "system", "call" and "log" (separated by ',') to specify what * kind of events should be sent. * @throws IOException if there is an i/o problem. * @throws AuthenticationFailedException if username or password are * incorrect and the login action returns an error or if the MD5 * hash cannot be computed. The connection is closed in this * case. * @throws TimeoutException if a timeout occurs while waiting for the * protocol identifier. The connection is closed in this case. */ protected synchronized void doLogin(long timeout, String eventMask) throws IOException, AuthenticationFailedException, TimeoutException { ChallengeAction challengeAction; ManagerResponse challengeResponse; String challenge; String key; LoginAction loginAction; ManagerResponse loginResponse; if (socket == null) { connect(); } synchronized (protocolIdentifier) { if (protocolIdentifier.value == null) { try { protocolIdentifier.wait(timeout); } catch (InterruptedException e) // NOPMD { Thread.currentThread().interrupt(); } } if (protocolIdentifier.value == null) { disconnect(); if (reader != null && reader.getTerminationException() != null) { throw reader.getTerminationException(); } else { throw new TimeoutException("Timeout waiting for protocol identifier"); } } } challengeAction = new ChallengeAction("MD5"); try { challengeResponse = sendAction(challengeAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send challenge action", e); } if (challengeResponse instanceof ChallengeResponse) { challenge = ((ChallengeResponse) challengeResponse).getChallenge(); } else { disconnect(); throw new AuthenticationFailedException("Unable to get challenge from Asterisk. ChallengeAction returned: " + challengeResponse.getMessage()); } try { MessageDigest md; md = MessageDigest.getInstance("MD5"); if (challenge != null) { md.update(challenge.getBytes()); } if (password != null) { md.update(password.getBytes()); } key = ManagerUtil.toHexString(md.digest()); } catch (NoSuchAlgorithmException ex) { disconnect(); throw new AuthenticationFailedException("Unable to create login key using MD5 Message Digest", ex); } loginAction = new LoginAction(username, "MD5", key, eventMask); try { loginResponse = sendAction(loginAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send login action", e); } if (loginResponse instanceof ManagerError) { disconnect(); throw new AuthenticationFailedException(loginResponse.getMessage()); } logger.info("Successfully logged in"); version = determineVersion(); state = CONNECTED; writer.setTargetVersion(version); logger.info("Determined Asterisk version: " + version); // generate pseudo event indicating a successful login ConnectEvent connectEvent = new ConnectEvent(this); connectEvent.setProtocolIdentifier(getProtocolIdentifier()); connectEvent.setDateReceived(DateUtil.getDate()); // TODO could this cause a deadlock? fireEvent(connectEvent); } protected AsteriskVersion determineVersion() throws IOException, TimeoutException { int attempts = 0; // if ("Asterisk Call Manager/1.1".equals(protocolIdentifier.value)) // { // return AsteriskVersion.ASTERISK_1_6; // } while (attempts++ < MAX_VERSION_ATTEMPTS) { final ManagerResponse showVersionFilesResponse; final List<String> showVersionFilesResult; // increase timeout as output is quite large showVersionFilesResponse = sendAction(new CommandAction("show version files pbx.c"), defaultResponseTimeout * 2); if (!(showVersionFilesResponse instanceof CommandResponse)) { // return early in case of permission problems // org.asteriskjava.manager.response.ManagerError: // actionId='null'; message='Permission denied'; response='Error'; // uniqueId='null'; systemHashcode=15231583 break; } showVersionFilesResult = ((CommandResponse) showVersionFilesResponse).getResult(); if (showVersionFilesResult != null && showVersionFilesResult.size() > 0) { final String line1; line1 = showVersionFilesResult.get(0); if (line1 != null && line1.startsWith("File")) { final String rawVersion; rawVersion = getRawVersion(); if (rawVersion != null && rawVersion.startsWith("Asterisk 1.4")) { return AsteriskVersion.ASTERISK_1_4; } return AsteriskVersion.ASTERISK_1_2; } else if (line1 != null && line1.contains("No such command")) { final ManagerResponse coreShowVersionResponse = sendAction(new CommandAction("core show version"), defaultResponseTimeout * 2); if(coreShowVersionResponse != null && coreShowVersionResponse instanceof CommandResponse){ final List<String> coreShowVersionResult = ((CommandResponse) coreShowVersionResponse).getResult(); if(coreShowVersionResult != null && coreShowVersionResult.size() > 0){ final String coreLine = coreShowVersionResult.get(0); if (coreLine != null && coreLine.startsWith("Asterisk 1.6")) { return AsteriskVersion.ASTERISK_1_6; } else if (coreLine != null && coreLine.startsWith("Asterisk 1.8")) { return AsteriskVersion.ASTERISK_1_8; } else if (coreLine != null && coreLine.startsWith("Asterisk 10")) { return AsteriskVersion.ASTERISK_10; } else if (coreLine != null && coreLine.startsWith("Asterisk 11")) { return AsteriskVersion.ASTERISK_11; } } } try { Thread.sleep(RECONNECTION_VERSION_INTERVAL); } catch (Exception ex) { // ingnore } // NOPMD } else { // if it isn't the "no such command", break and return the lowest version immediately break; } } } // as a fallback assume 1.6 return AsteriskVersion.ASTERISK_1_6; } protected String getRawVersion() { final ManagerResponse showVersionResponse; try { showVersionResponse = sendAction(new CommandAction("show version"), defaultResponseTimeout * 2); } catch (Exception e) { return null; } if (showVersionResponse instanceof CommandResponse) { final List<String> showVersionResult; showVersionResult = ((CommandResponse) showVersionResponse).getResult(); if (showVersionResult != null && showVersionResult.size() > 0) { return showVersionResult.get(0); } } return null; } protected synchronized void connect() throws IOException { logger.info("Connecting to " + hostname + ":" + port); if (reader == null) { logger.debug("Creating reader for " + hostname + ":" + port); reader = createReader(this, this); } if (writer == null) { logger.debug("Creating writer"); writer = createWriter(); } logger.debug("Creating socket"); socket = createSocket(); logger.debug("Passing socket to reader"); reader.setSocket(socket); if (readerThread == null || !readerThread.isAlive() || reader.isDead()) { logger.debug("Creating and starting reader thread"); readerThread = new Thread(reader); readerThread.setName("Asterisk-Java ManagerConnection-" + id + "-Reader-" + readerThreadCounter.getAndIncrement()); readerThread.setDaemon(true); readerThread.start(); } logger.debug("Passing socket to writer"); writer.setSocket(socket); } protected SocketConnectionFacade createSocket() throws IOException { return new SocketConnectionFacadeImpl(hostname, port, ssl, socketTimeout, socketReadTimeout); } public synchronized void logoff() throws IllegalStateException { if (state != CONNECTED && state != RECONNECTING) { throw new IllegalStateException("Logoff may only be perfomed when in state " + "CONNECTED or RECONNECTING, but connection is in state " + state); } state = DISCONNECTING; if (socket != null) { try { sendAction(new LogoffAction()); } catch (Exception e) { logger.warn("Unable to send LogOff action", e); } } cleanup(); state = DISCONNECTED; } /** * Closes the socket connection. */ protected synchronized void disconnect() { if (socket != null) { logger.info("Closing socket."); try { socket.close(); } catch (IOException ex) { logger.warn("Unable to close socket: " + ex.getMessage()); } socket = null; } protocolIdentifier.value = null; } public ManagerResponse sendAction(ManagerAction action) throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException { return sendAction(action, defaultResponseTimeout); } /* * Implements synchronous sending of "simple" actions. */ public ManagerResponse sendAction(ManagerAction action, long timeout) throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException { ResponseHandlerResult result; SendActionCallback callbackHandler; result = new ResponseHandlerResult(); callbackHandler = new DefaultSendActionCallback(result); synchronized (result) { sendAction(action, callbackHandler); // definitely return null for the response of user events if (action instanceof UserEventAction) { return null; } // only wait if we did not yet receive the response. // Responses may be returned really fast. if (result.getResponse() == null) { try { result.wait(timeout); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting for result"); Thread.currentThread().interrupt(); } } } // still no response? if (result.getResponse() == null) { throw new TimeoutException("Timeout waiting for response to " + action.getAction() + (action.getActionId() == null ? "" : " (actionId: " + action.getActionId() + ")")); } return result.getResponse(); } public void sendAction(ManagerAction action, SendActionCallback callback) throws IOException, IllegalArgumentException, IllegalStateException { final String internalActionId; if (action == null) { throw new IllegalArgumentException("Unable to send action: action is null."); } // In general sending actions is only allowed while connected, though // there are a few exceptions, these are handled here: if ((state == CONNECTING || state == RECONNECTING) && (action instanceof ChallengeAction || action instanceof LoginAction || isShowVersionCommandAction(action))) { // when (re-)connecting challenge and login actions are ok. } // NOPMD else if (state == DISCONNECTING && action instanceof LogoffAction) { // when disconnecting logoff action is ok. } // NOPMD else if (state != CONNECTED) { throw new IllegalStateException("Actions may only be sent when in state " + "CONNECTED, but connection is in state " + state); } if (socket == null) { throw new IllegalStateException("Unable to send " + action.getAction() + " action: socket not connected."); } internalActionId = createInternalActionId(); // if the callbackHandler is null the user is obviously not interested // in the response, thats fine. if (callback != null) { synchronized (this.responseListeners) { this.responseListeners.put(internalActionId, callback); } } Class<? extends ManagerResponse> responseClass = getExpectedResponseClass(action.getClass()); if (responseClass != null) { reader.expectResponseClass(internalActionId, responseClass); } writer.sendAction(action, internalActionId); } boolean isShowVersionCommandAction(ManagerAction action) { if (! (action instanceof CommandAction)) { return false; } final Matcher showVersionMatcher = SHOW_VERSION_PATTERN.matcher(((CommandAction)action).getCommand()); return showVersionMatcher.matches(); } private Class<? extends ManagerResponse> getExpectedResponseClass(Class<? extends ManagerAction> actionClass) { final ExpectedResponse annotation = actionClass.getAnnotation(ExpectedResponse.class); if (annotation == null) { return null; } return annotation.value(); } public ResponseEvents sendEventGeneratingAction(EventGeneratingAction action) throws IOException, EventTimeoutException, IllegalArgumentException, IllegalStateException { return sendEventGeneratingAction(action, defaultEventTimeout); } /* * Implements synchronous sending of event generating actions. */ public ResponseEvents sendEventGeneratingAction(EventGeneratingAction action, long timeout) throws IOException, EventTimeoutException, IllegalArgumentException, IllegalStateException { final ResponseEventsImpl responseEvents; final ResponseEventHandler responseEventHandler; final String internalActionId; if (action == null) { throw new IllegalArgumentException("Unable to send action: action is null."); } else if (action.getActionCompleteEventClass() == null) { throw new IllegalArgumentException("Unable to send action: actionCompleteEventClass for " + action.getClass().getName() + " is null."); } else if (!ResponseEvent.class.isAssignableFrom(action.getActionCompleteEventClass())) { throw new IllegalArgumentException("Unable to send action: actionCompleteEventClass (" + action.getActionCompleteEventClass().getName() + ") for " + action.getClass().getName() + " is not a ResponseEvent."); } if (state != CONNECTED) { throw new IllegalStateException("Actions may only be sent when in state " + "CONNECTED but connection is in state " + state); } responseEvents = new ResponseEventsImpl(); responseEventHandler = new ResponseEventHandler(responseEvents, action.getActionCompleteEventClass()); internalActionId = createInternalActionId(); // register response handler... synchronized (this.responseListeners) { this.responseListeners.put(internalActionId, responseEventHandler); } // ...and event handler. synchronized (this.responseEventListeners) { this.responseEventListeners.put(internalActionId, responseEventHandler); } synchronized (responseEvents) { writer.sendAction(action, internalActionId); // only wait if response has not yet arrived. if ((responseEvents.getResponse() == null || !responseEvents.isComplete())) { try { responseEvents.wait(timeout); } catch (InterruptedException e) { logger.warn("Interrupted while waiting for response events."); Thread.currentThread().interrupt(); } } } // still no response or not all events received and timed out? if ((responseEvents.getResponse() == null || !responseEvents.isComplete())) { // clean up synchronized (this.responseEventListeners) { this.responseEventListeners.remove(internalActionId); } throw new EventTimeoutException("Timeout waiting for response or response events to " + action.getAction() + (action.getActionId() == null ? "" : " (actionId: " + action.getActionId() + ")"), responseEvents); } // remove the event handler // Note: The response handler has already been removed // when the response was received synchronized (this.responseEventListeners) { this.responseEventListeners.remove(internalActionId); } return responseEvents; } /** * Creates a new unique internal action id based on the hash code of this * connection and a sequence. * * @return a new internal action id * @see ManagerUtil#addInternalActionId(String,String) * @see ManagerUtil#getInternalActionId(String) * @see ManagerUtil#stripInternalActionId(String) */ private String createInternalActionId() { final StringBuffer sb; sb = new StringBuffer(); sb.append(this.hashCode()); sb.append("_"); sb.append(actionIdCounter.getAndIncrement()); return sb.toString(); } public void addEventListener(final ManagerEventListener listener) { synchronized (this.eventListeners) { // only add it if its not already there if (!this.eventListeners.contains(listener)) { this.eventListeners.add(listener); } } } public void removeEventListener(final ManagerEventListener listener) { synchronized (this.eventListeners) { if (this.eventListeners.contains(listener)) { this.eventListeners.remove(listener); } } } public String getProtocolIdentifier() { return protocolIdentifier.value; } public ManagerConnectionState getState() { return state; } /* Implementation of Dispatcher: callbacks for ManagerReader */ /** * This method is called by the reader whenever a {@link ManagerResponse} is * received. The response is dispatched to the associated * {@link SendActionCallback}. * * @param response the response received by the reader * @see ManagerReader */ public void dispatchResponse(ManagerResponse response) { final String actionId; String internalActionId; SendActionCallback listener; // shouldn't happen if (response == null) { logger.error("Unable to dispatch null response. This should never happen. Please file a bug."); return; } actionId = response.getActionId(); internalActionId = null; listener = null; if (actionId != null) { internalActionId = ManagerUtil.getInternalActionId(actionId); response.setActionId(ManagerUtil.stripInternalActionId(actionId)); } logger.debug("Dispatching response with internalActionId '" + internalActionId + "':\n" + response); if (internalActionId != null) { synchronized (this.responseListeners) { listener = responseListeners.get(internalActionId); if (listener != null) { this.responseListeners.remove(internalActionId); } else { // when using the async sendAction it's ok not to register a // callback so if we don't find a response handler thats ok logger.debug("No response listener registered for " + "internalActionId '" + internalActionId + "'"); } } } else { logger.error("Unable to retrieve internalActionId from response: " + "actionId '" + actionId + "':\n" + response); } if (listener != null) { try { listener.onResponse(response); } catch (Exception e) { logger.warn("Unexpected exception in response listener " + listener.getClass().getName(), e); } } } /** * This method is called by the reader whenever a ManagerEvent is received. * The event is dispatched to all registered ManagerEventHandlers. * * @param event the event received by the reader * @see #addEventListener(ManagerEventListener) * @see #removeEventListener(ManagerEventListener) * @see ManagerReader */ public void dispatchEvent(ManagerEvent event) { // shouldn't happen if (event == null) { logger.error("Unable to dispatch null event. This should never happen. Please file a bug."); return; } logger.debug("Dispatching event:\n" + event.toString()); // Some events need special treatment besides forwarding them to the // registered eventListeners (clients) // These events are handled here at first: // Dispatch ResponseEvents to the appropriate responseEventListener if (event instanceof ResponseEvent) { ResponseEvent responseEvent; String internalActionId; responseEvent = (ResponseEvent) event; internalActionId = responseEvent.getInternalActionId(); if (internalActionId != null) { synchronized (responseEventListeners) { ManagerEventListener listener; listener = responseEventListeners.get(internalActionId); if (listener != null) { try { listener.onManagerEvent(event); } catch (Exception e) { logger.warn("Unexpected exception in response event listener " + listener.getClass().getName(), e); } } } } else { // ResponseEvent without internalActionId: // this happens if the same event class is used as response // event // and as an event that is not triggered by a Manager command // Example: QueueMemberStatusEvent. // logger.debug("ResponseEvent without " // + "internalActionId:\n" + responseEvent); } // NOPMD } if (event instanceof DisconnectEvent) { // When we receive get disconnected while we are connected start // a new reconnect thread and set the state to RECONNECTING. if (state == CONNECTED) { state = RECONNECTING; // close socket if still open and remove reference to // readerThread // After sending the DisconnectThread that thread will die // anyway. cleanup(); Thread reconnectThread = new Thread(new Runnable() { public void run() { reconnect(); } }); reconnectThread.setName("Asterisk-Java ManagerConnection-" + id + "-Reconnect-" + reconnectThreadCounter.getAndIncrement()); reconnectThread.setDaemon(true); reconnectThread.start(); // now the DisconnectEvent is dispatched to registered // eventListeners // (clients) and after that the ManagerReaderThread is gone. // So effectively we replaced the reader thread by a // ReconnectThread. } else { // when we receive a DisconnectEvent while not connected we // ignore it and do not send it to clients return; } } if (event instanceof ProtocolIdentifierReceivedEvent) { ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent; String protocolIdentifier; protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event; protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier(); setProtocolIdentifier(protocolIdentifier); // no need to send this event to clients return; } fireEvent(event); } /** * Notifies all {@link ManagerEventListener}s registered by users. * * @param event the event to propagate */ private void fireEvent(ManagerEvent event) { synchronized (eventListeners) { for (ManagerEventListener listener : eventListeners) { try { listener.onManagerEvent(event); } catch (RuntimeException e) { logger.warn("Unexpected exception in eventHandler " + listener.getClass().getName(), e); } } } } /** * This method is called when a {@link ProtocolIdentifierReceivedEvent} is * received from the reader. Having received a correct protocol identifier * is the precodition for logging in. * * @param identifier the protocol version used by the Asterisk server. */ private void setProtocolIdentifier(final String identifier) { logger.info("Connected via " + identifier); if (!"Asterisk Call Manager/1.0".equals(identifier) && !"Asterisk Call Manager/1.1".equals(identifier) // Asterisk 1.6 && !"Asterisk Call Manager/1.2".equals(identifier) // bri stuffed && !"Asterisk Call Manager/1.3".equals(identifier) // Asterisk 11 && !"OpenPBX Call Manager/1.0".equals(identifier) && !"CallWeaver Call Manager/1.0".equals(identifier) && !(identifier != null && identifier.startsWith("Asterisk Call Manager Proxy/"))) { logger.warn("Unsupported protocol version '" + identifier + "'. Use at your own risk."); } synchronized (protocolIdentifier) { protocolIdentifier.value = identifier; protocolIdentifier.notifyAll(); } } /** * Reconnects to the asterisk server when the connection is lost. * <p/> * While keepAlive is <code>true</code> we will try to reconnect. * Reconnection attempts will be stopped when the {@link #logoff()} method * is called or when the login after a successful reconnect results in an * {@link AuthenticationFailedException} suggesting that the manager * credentials have changed and keepAliveAfterAuthenticationFailure is not * set. * <p/> * This method is called when a {@link DisconnectEvent} is received from the * reader. */ private void reconnect() { int numTries; // try to reconnect numTries = 0; while (state == RECONNECTING) { try { if (numTries < 10) { // try to reconnect quite fast for the firt 10 times // this succeeds if the server has just been restarted Thread.sleep(RECONNECTION_INTERVAL_1); } else { // slow down after 10 unsuccessful attempts asuming a // shutdown of the server Thread.sleep(RECONNECTION_INTERVAL_2); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } try { connect(); try { doLogin(defaultResponseTimeout, eventMask); logger.info("Successfully reconnected."); // everything is ok again, so we leave // when successful doLogin set the state to CONNECTED so no // need to adjust it break; } catch (AuthenticationFailedException e1) { if (keepAliveAfterAuthenticationFailure) { logger.error("Unable to log in after reconnect: " + e1.getMessage()); } else { logger.error("Unable to log in after reconnect: " + e1.getMessage() + ". Giving up."); state = DISCONNECTED; } } catch (TimeoutException e1) { // shouldn't happen - but happens! logger.error("TimeoutException while trying to log in " + "after reconnect."); } } catch (IOException e) { // server seems to be still down, just continue to attempt // reconnection logger.warn("Exception while trying to reconnect: " + e.getMessage()); } numTries++; } } private void cleanup() { disconnect(); this.readerThread = null; } @Override public String toString() { StringBuffer sb; sb = new StringBuffer("ManagerConnection["); sb.append("id='").append(id).append("',"); sb.append("hostname='").append(hostname).append("',"); sb.append("port=").append(port).append(","); sb.append("systemHashcode=").append(System.identityHashCode(this)).append("]"); return sb.toString(); } /* Helper classes */ /** * A simple data object to store a ManagerResult. */ private static class ResponseHandlerResult implements Serializable { /** * Serializable version identifier. */ private static final long serialVersionUID = 7831097958568769220L; private ManagerResponse response; public ResponseHandlerResult() { } public ManagerResponse getResponse() { return this.response; } public void setResponse(ManagerResponse response) { this.response = response; } } /** * A simple response handler that stores the received response in a * ResponseHandlerResult for further processing. */ private static class DefaultSendActionCallback implements SendActionCallback, Serializable { /** * Serializable version identifier. */ private static final long serialVersionUID = 2926598671855316803L; private final ResponseHandlerResult result; /** * Creates a new instance. * * @param result the result to store the response in */ public DefaultSendActionCallback(ResponseHandlerResult result) { this.result = result; } public void onResponse(ManagerResponse response) { synchronized (result) { result.setResponse(response); result.notifyAll(); } } } /** * A combinded event and response handler that adds received events and the * response to a ResponseEvents object. */ private static class ResponseEventHandler implements ManagerEventListener, SendActionCallback { private final ResponseEventsImpl events; private final Class<?> actionCompleteEventClass; /** * Creates a new instance. * * @param events the ResponseEventsImpl to store the events in * @param actionCompleteEventClass the type of event that indicates that * all events have been received */ public ResponseEventHandler(ResponseEventsImpl events, Class<?> actionCompleteEventClass) { this.events = events; this.actionCompleteEventClass = actionCompleteEventClass; } public void onManagerEvent(ManagerEvent event) { synchronized (events) { // should always be a ResponseEvent, anyway... if (event instanceof ResponseEvent) { ResponseEvent responseEvent; responseEvent = (ResponseEvent) event; events.addEvent(responseEvent); } // finished? if (actionCompleteEventClass.isAssignableFrom(event.getClass())) { events.setComplete(true); // notify if action complete event and response have been // received if (events.getResponse() != null) { events.notifyAll(); } } } } public void onResponse(ManagerResponse response) { synchronized (events) { events.setRepsonse(response); if (response instanceof ManagerError) { events.setComplete(true); } // finished? // notify if action complete event and response have been // received if (events.isComplete()) { events.notifyAll(); } } } } private static class ProtocolIdentifierWrapper { String value; } }
{ "content_hash": "85a5fdb48da00646142624f1119f5719", "timestamp": "", "source": "github", "line_count": 1544, "max_line_length": 147, "avg_line_length": 32.9119170984456, "alnum_prop": 0.5756454659949622, "repo_name": "milesje/asterisk-java", "id": "2b2a35744cb0b6fd61b5522f1cc13f4fa16f8c11", "size": "51430", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/org/asteriskjava/manager/internal/ManagerConnectionImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "337" }, { "name": "Java", "bytes": "2050124" }, { "name": "JavaScript", "bytes": "374" }, { "name": "PHP", "bytes": "348" } ], "symlink_target": "" }
@(branch: String, repository: service.RepositoryService.RepositoryInfo, pathList: List[String], content: util.JGitUtil.ContentInfo, latestCommit: util.JGitUtil.CommitInfo)(implicit context: app.Context) @import context._ @import view.helpers._ @html.main(s"${repository.owner}/${repository.name}", Some(repository)) { @html.header("code", repository) @tab(branch, repository, "files") <div class="head"> <a href="@url(repository)/tree/@encodeRefName(branch)">@repository.name</a> / @pathList.zipWithIndex.map { case (section, i) => @if(i == pathList.length - 1){ @section } else { <a href="@url(repository)/tree/@encodeRefName(branch)/@pathList.take(i + 1).mkString("/")">@section</a> / } } </div> <table class="table table-bordered"> <tr> <th style="font-weight: normal;"> <div class="pull-left"> @avatar(latestCommit, 20) @user(latestCommit.committer, latestCommit.mailAddress, "username strong") <span class="muted">@datetime(latestCommit.time)</span> <a href="@url(repository)/commit/@latestCommit.id" class="commit-message">@link(latestCommit.summary, repository)</a> </div> <div class="btn-group pull-right"> <a class="btn btn-mini" href="?raw=true">Raw</a> <a class="btn btn-mini" href="@url(repository)/commits/@encodeRefName(branch)/@pathList.mkString("/")">History</a> </div> </th> </tr> <tr> <td> @if(content.viewType == "text"){ <pre class="prettyprint linenums blob">@content.content.get</pre> } @if(content.viewType == "image"){ <img src="?raw=true"/> } @if(content.viewType == "large" || content.viewType == "binary"){ <div style="text-align: center"> <a href="?raw=true">View Raw</a><br> (Sorry about that, but we can't show files that are this big right now) </div> } </td> </tr> </table> }
{ "content_hash": "a845ace97fc5a4d7423ddc83b03e5898", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 127, "avg_line_length": 37.2037037037037, "alnum_prop": 0.5973120955699353, "repo_name": "martinx/gitbucket", "id": "ea6952d13659e1f02c93583b78b320d1b0193792", "size": "2009", "binary": false, "copies": "19", "ref": "refs/heads/master", "path": "src/main/twirl/repo/blob.scala.html", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
// ======================================================================== // Copyright 2002-2005 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== package org.mortbay.jetty.security; import java.io.IOException; import java.security.Principal; import javax.servlet.http.HttpServletResponse; import org.mortbay.jetty.HttpHeaders; import org.mortbay.jetty.Request; import org.mortbay.jetty.Response; import org.mortbay.log.Log; import org.mortbay.util.StringUtil; /* ------------------------------------------------------------ */ /** BASIC authentication. * * @author Greg Wilkins (gregw) */ public class BasicAuthenticator implements Authenticator { /* ------------------------------------------------------------ */ /** * @return UserPrinciple if authenticated or null if not. If * Authentication fails, then the authenticator may have committed * the response as an auth challenge or redirect. * @exception IOException */ public Principal authenticate(UserRealm realm, String pathInContext, Request request, Response response) throws IOException { // Get the user if we can Principal user=null; String credentials = request.getHeader(HttpHeaders.AUTHORIZATION); if (credentials!=null ) { try { if(Log.isDebugEnabled())Log.debug("Credentials: "+credentials); credentials = credentials.substring(credentials.indexOf(' ')+1); credentials = B64Code.decode(credentials,StringUtil.__ISO_8859_1); int i = credentials.indexOf(':'); String username = credentials.substring(0,i); String password = credentials.substring(i+1); user = realm.authenticate(username,password,request); if (user==null) { Log.warn("AUTH FAILURE: user {}",StringUtil.printable(username)); } else { request.setAuthType(Constraint.__BASIC_AUTH); request.setUserPrincipal(user); } } catch (Exception e) { Log.warn("AUTH FAILURE: "+e.toString()); Log.ignore(e); } } // Challenge if we have no user if (user==null && response!=null) sendChallenge(realm,response); return user; } /* ------------------------------------------------------------ */ public String getAuthMethod() { return Constraint.__BASIC_AUTH; } /* ------------------------------------------------------------ */ public void sendChallenge(UserRealm realm,Response response) throws IOException { response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\""+realm.getName()+'"'); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } }
{ "content_hash": "4cd0f85683137ef678b3c56222478667", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 95, "avg_line_length": 36.25242718446602, "alnum_prop": 0.5286555972147831, "repo_name": "napcs/qedserver", "id": "13ef599af1db1c66badc94ffcc48d1cba1b60a62", "size": "3734", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "jetty/modules/jetty/src/main/java/org/mortbay/jetty/security/BasicAuthenticator.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "16295" }, { "name": "CSS", "bytes": "14847" }, { "name": "Groovy", "bytes": "7099" }, { "name": "HTML", "bytes": "14346" }, { "name": "Java", "bytes": "5514807" }, { "name": "JavaScript", "bytes": "34952" }, { "name": "Ruby", "bytes": "53583" }, { "name": "Shell", "bytes": "68984" }, { "name": "XSLT", "bytes": "7153" } ], "symlink_target": "" }
package de.endrullis.sta import java.awt.Color /** * Default class for creating Tikz animations. * It extends the BaseTikzAni by functions of BaseVarIC. * Inherit from this class to describe your Tikz animation. * * @author Stefan Endrullis &lt;stefan@endrullis.de&gt; */ class ScalaTikzAni extends BaseTikzAni with BaseVarIC { /** Defines a LaTeX color. */ def defColor(name: String, definition: Generator[Color]) = ("""\definecolor{"""+name+"}{RGB}{")~definition~"}\n" /** Defines a tikz style. */ def defTikzStyle(name: String, definition: Generator[String]) = ("""\tikzstyle{"""+name+"} = [")~definition~"]\n" /** Opens a new scope. */ def scope(options: Generator[String], code: Generator[String]) = """\begin{scope}["""~options~"]"~code~"""\end{scope}""" /** Creates a shifted scope. */ def shift(code: Generator[String], pos: Generator[Pos]) = scope("shift={"~pos~"}", code) }
{ "content_hash": "5601a8fd82954330133f465675549d84", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 121, "avg_line_length": 35.80769230769231, "alnum_prop": 0.6573576799140709, "repo_name": "xylo/scala-tikz-animations", "id": "f1c8eced31673dcf39af6b3be927c061b8029827", "size": "931", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/de/endrullis/sta/ScalaTikzAni.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "44330" } ], "symlink_target": "" }
package com.xinyu.mwp.fragment; import android.support.v4.widget.DrawerLayout; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import com.jaeger.library.StatusBarUtil; import com.xinyu.mwp.R; import com.xinyu.mwp.entity.CurrentTimeLineReturnEntity; import com.xinyu.mwp.fragment.base.BaseFragment; import com.xinyu.mwp.listener.OnAPIListener; import com.xinyu.mwp.networkapi.NetworkAPIFactoryImpl; import com.xinyu.mwp.util.LogUtil; import com.xinyu.mwp.util.ToastUtils; import org.xutils.view.annotation.ViewInject; import java.util.List; /** * 晒单页面--敬请期待! */ public class ShareOrderExpectFragment extends BaseFragment { @ViewInject(R.id.leftImage) ImageButton leftImage; @ViewInject(R.id.titleText) TextView titleText; @Override protected int getLayoutID() { return R.layout.fragment_shareorder_expect; } @Override protected void initView() { super.initView(); titleText.setText("晒单"); leftImage.setVisibility(View.INVISIBLE); } @Override public void initStatusBar() { StatusBarUtil.setColorForDrawerLayout(getActivity(), (DrawerLayout) getActivity().findViewById(R.id.drawer), getResources().getColor(R.color.default_main_color), 0); } }
{ "content_hash": "e7c67314c44b37ed07a5a7ad9eb1e89d", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 72, "avg_line_length": 25.46153846153846, "alnum_prop": 0.7258308157099698, "repo_name": "yaobanglin/wpan", "id": "145fece7a3368034ca61d58ff60248db8e320b99", "size": "1344", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "app/src/main/java/com/xinyu/mwp/fragment/ShareOrderExpectFragment.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1155541" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "5b447ec7201112876022e2b24a741641", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "300b7c757fe22d1cd9f6efbbafb231df8dcf5ed3", "size": "184", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Chassalia/Chassalia simplex/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_80) on Thu Oct 15 19:27:56 UTC 2015 --> <title>ReplicationRuleStatus (AWS SDK for Java - 1.10.27)</title> <meta name="date" content="2015-10-15"> <link rel="stylesheet" type="text/css" href="../../../../../JavaDoc.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ReplicationRuleStatus (AWS SDK for Java - 1.10.27)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><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 class="navBarCell1Rev">Class</li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em> <!-- Scripts for Syntax Highlighter START--> <script id="syntaxhighlight_script_core" type="text/javascript" src = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/scripts/shCore.js"> </script> <script id="syntaxhighlight_script_java" type="text/javascript" src = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/scripts/shBrushJava.js"> </script> <link id="syntaxhighlight_css_core" rel="stylesheet" type="text/css" href = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/styles/shCoreDefault.css"/> <link id="syntaxhighlight_css_theme" rel="stylesheet" type="text/css" href = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/styles/shThemeDefault.css"/> <!-- Scripts for Syntax Highlighter END--> <div> <!-- BEGIN-SECTION --> <div id="divsearch" style="float:left;"> <span id="lblsearch" for="searchQuery"> <label>Search</label> </span> <form id="nav-search-form" target="_parent" method="get" action="http://docs.aws.amazon.com/search/doc-search.html#facet_doc_guide=API+Reference&facet_doc_product=AWS+SDK+for+Java"> <div id="nav-searchfield-outer" class="nav-sprite"> <div class="nav-searchfield-inner nav-sprite"> <div id="nav-searchfield-width"> <input id="nav-searchfield" name="searchQuery"> </div> </div> </div> <div id="nav-search-button" class="nav-sprite"> <input alt="" id="nav-search-button-inner" type="image"> </div> <input name="searchPath" type="hidden" value="documentation-guide" /> <input name="this_doc_product" type="hidden" value="AWS SDK for Java" /> <input name="this_doc_guide" type="hidden" value="API Reference" /> <input name="doc_locale" type="hidden" value="en_us" /> </form> </div> <!-- END-SECTION --> <!-- BEGIN-FEEDBACK-SECTION --> <div id="feedback-section"> <h3>Did this page help you?</h3> <div id="feedback-link-sectioin"> <a id="feedback_yes" target="_blank" style="display:inline;">Yes</a>&nbsp;&nbsp; <a id="feedback_no" target="_blank" style="display:inline;">No</a>&nbsp;&nbsp; <a id="go_cti" target="_blank" style="display:inline;">Tell us about it...</a> </div> </div> <script type="text/javascript"> window.onload = function(){ /* Dynamically add feedback links */ var javadoc_root_name = "/javadoc/"; var javadoc_path = location.href.substring(0, location.href.lastIndexOf(javadoc_root_name) + javadoc_root_name.length); var file_path = location.href.substring(location.href.lastIndexOf(javadoc_root_name) + javadoc_root_name.length); var feedback_yes_url = javadoc_path + "javadoc-resources/feedbackyes.html?topic_id="; var feedback_no_url = javadoc_path + "javadoc-resources/feedbackno.html?topic_id="; var feedback_tellmore_url = "https://aws-portal.amazon.com/gp/aws/html-forms-controller/documentation/aws_doc_feedback_04?service_name=Java-Ref&file_name="; if(file_path != "overview-frame.html") { var file_name = file_path.replace(/[/.]/g, '_'); document.getElementById("feedback_yes").setAttribute("href", feedback_yes_url + file_name); document.getElementById("feedback_no").setAttribute("href", feedback_no_url + file_name); document.getElementById("go_cti").setAttribute("href", feedback_tellmore_url + file_name); } else { // hide the search box and the feeback links in overview-frame page, // show "AWS SDK for Java" instead. document.getElementById("feedback-section").outerHTML = "AWS SDK for Java"; document.getElementById("divsearch").outerHTML = ""; } }; </script> <!-- END-FEEDBACK-SECTION --> </div> </em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/amazonaws/services/s3/model/ReplicationRule.html" title="class in com.amazonaws.services.s3.model"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../com/amazonaws/services/s3/model/RequestPaymentConfiguration.html" title="class in com.amazonaws.services.s3.model"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/amazonaws/services/s3/model/ReplicationRuleStatus.html" target="_top">Frames</a></li> <li><a href="ReplicationRuleStatus.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#enum_constant_summary">Enum Constants</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#enum_constant_detail">Enum Constants</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.amazonaws.services.s3.model</div> <h2 title="Enum ReplicationRuleStatus" class="title">Enum ReplicationRuleStatus</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>java.lang.Enum&lt;<a href="../../../../../com/amazonaws/services/s3/model/ReplicationRuleStatus.html" title="enum in com.amazonaws.services.s3.model">ReplicationRuleStatus</a>&gt;</li> <li> <ul class="inheritance"> <li>com.amazonaws.services.s3.model.ReplicationRuleStatus</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.io.Serializable, java.lang.Comparable&lt;<a href="../../../../../com/amazonaws/services/s3/model/ReplicationRuleStatus.html" title="enum in com.amazonaws.services.s3.model">ReplicationRuleStatus</a>&gt;</dd> </dl> <hr> <br> <pre>public enum <span class="strong">ReplicationRuleStatus</span> extends java.lang.Enum&lt;<a href="../../../../../com/amazonaws/services/s3/model/ReplicationRuleStatus.html" title="enum in com.amazonaws.services.s3.model">ReplicationRuleStatus</a>&gt;</pre> <div class="block">A enum class for status of a Amazon S3 bucket replication rule.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== ENUM CONSTANT SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="enum_constant_summary"> <!-- --> </a> <h3>Enum Constant Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Constant Summary table, listing enum constants, and an explanation"> <caption><span>Enum Constants</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Enum Constant and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../../com/amazonaws/services/s3/model/ReplicationRuleStatus.html#Disabled">Disabled</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../../../com/amazonaws/services/s3/model/ReplicationRuleStatus.html#Enabled">Enabled</a></strong></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</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> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/s3/model/ReplicationRuleStatus.html#getStatus()">getStatus</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../com/amazonaws/services/s3/model/ReplicationRuleStatus.html" title="enum in com.amazonaws.services.s3.model">ReplicationRuleStatus</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/s3/model/ReplicationRuleStatus.html#valueOf(java.lang.String)">valueOf</a></strong>(java.lang.String&nbsp;name)</code> <div class="block">Returns the enum constant of this type with the specified name.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../com/amazonaws/services/s3/model/ReplicationRuleStatus.html" title="enum in com.amazonaws.services.s3.model">ReplicationRuleStatus</a>[]</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/s3/model/ReplicationRuleStatus.html#values()">values</a></strong>()</code> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Enum"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Enum</h3> <code>compareTo, equals, getDeclaringClass, hashCode, name, ordinal, toString, valueOf</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>getClass, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ ENUM CONSTANT DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="enum_constant_detail"> <!-- --> </a> <h3>Enum Constant Detail</h3> <a name="Enabled"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>Enabled</h4> <pre>public static final&nbsp;<a href="../../../../../com/amazonaws/services/s3/model/ReplicationRuleStatus.html" title="enum in com.amazonaws.services.s3.model">ReplicationRuleStatus</a> Enabled</pre> </li> </ul> <a name="Disabled"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>Disabled</h4> <pre>public static final&nbsp;<a href="../../../../../com/amazonaws/services/s3/model/ReplicationRuleStatus.html" title="enum in com.amazonaws.services.s3.model">ReplicationRuleStatus</a> Disabled</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="values()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>values</h4> <pre>public static&nbsp;<a href="../../../../../com/amazonaws/services/s3/model/ReplicationRuleStatus.html" title="enum in com.amazonaws.services.s3.model">ReplicationRuleStatus</a>[]&nbsp;values()</pre> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows: <pre> for (ReplicationRuleStatus c : ReplicationRuleStatus.values()) &nbsp; System.out.println(c); </pre></div> <dl><dt><span class="strong">Returns:</span></dt><dd>an array containing the constants of this enum type, in the order they are declared</dd></dl> </li> </ul> <a name="valueOf(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>valueOf</h4> <pre>public static&nbsp;<a href="../../../../../com/amazonaws/services/s3/model/ReplicationRuleStatus.html" title="enum in com.amazonaws.services.s3.model">ReplicationRuleStatus</a>&nbsp;valueOf(java.lang.String&nbsp;name)</pre> <div class="block">Returns the enum constant of this type with the specified name. The string must match <i>exactly</i> an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>name</code> - the name of the enum constant to be returned.</dd> <dt><span class="strong">Returns:</span></dt><dd>the enum constant with the specified name</dd> <dt><span class="strong">Throws:</span></dt> <dd><code>java.lang.IllegalArgumentException</code> - if this enum type has no constant with the specified name</dd> <dd><code>java.lang.NullPointerException</code> - if the argument is null</dd></dl> </li> </ul> <a name="getStatus()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getStatus</h4> <pre>public&nbsp;java.lang.String&nbsp;getStatus()</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><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 class="navBarCell1Rev">Class</li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em> <div> <!-- Script for Syntax Highlighter START --> <script type="text/javascript"> SyntaxHighlighter.all() </script> <!-- Script for Syntax Highlighter END --> </div> <script src="http://a0.awsstatic.com/chrome/js/1.0.46/jquery.1.9.js" type="text/javascript"></script> <script>jQuery.noConflict();</script> <script> jQuery(function ($) { $("div.header").prepend('<!--REGION_DISCLAIMER_DO_NOT_REMOVE-->'); }); </script> <!-- BEGIN-URCHIN-TRACKER --> <script src="http://l0.awsstatic.com/js/urchin.js" type="text/javascript"></script> <script type="text/javascript">urchinTracker();</script> <!-- END-URCHIN-TRACKER --> <!-- SiteCatalyst code version: H.25.2. Copyright 1996-2012 Adobe, Inc. All Rights Reserved. More info available at http://www.omniture.com --> <script language="JavaScript" type="text/javascript" src="https://media.amazonwebservices.com/js/sitecatalyst/s_code.min.js (view-source:https://media.amazonwebservices.com/js/sitecatalyst/s_code.min.js)" /> <script language="JavaScript" type="text/javascript"> <!-- // Documentation Service Name s.prop66='AWS SDK for Java'; s.eVar66='D=c66'; // Documentation Guide Name s.prop65='API Reference'; s.eVar65='D=c65'; var s_code=s.t();if(s_code)document.write(s_code) //--> </script> <script language="JavaScript" type="text/javascript"> <!--if(navigator.appVersion.indexOf('MSIE')>=0)document.write(unescape('%3C')+'\!-'+'-') //--> </script> <noscript> <img src="http://amazonwebservices.d2.sc.omtrdc.net/b/ss/awsamazondev/1/H.25.2--NS/0" height="1" width="1" border="0" alt="" /> </noscript> <!--/DO NOT REMOVE/--> <!-- End SiteCatalyst code version: H.25.2. --> </em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/amazonaws/services/s3/model/ReplicationRule.html" title="class in com.amazonaws.services.s3.model"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../com/amazonaws/services/s3/model/RequestPaymentConfiguration.html" title="class in com.amazonaws.services.s3.model"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/amazonaws/services/s3/model/ReplicationRuleStatus.html" target="_top">Frames</a></li> <li><a href="ReplicationRuleStatus.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#enum_constant_summary">Enum Constants</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#enum_constant_detail">Enum Constants</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> Copyright &#169; 2013 Amazon Web Services, Inc. All Rights Reserved. </small></p> </body> </html>
{ "content_hash": "90e41e4de0ea66fefe6790b937345cdd", "timestamp": "", "source": "github", "line_count": 451, "max_line_length": 228, "avg_line_length": 43.80709534368071, "alnum_prop": 0.6204889406286379, "repo_name": "TomNong/Project2-Intel-Edison", "id": "3be4c3d64d4e8be25ee2a8e75914bc1797c2e768", "size": "19757", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "documentation/javadoc/com/amazonaws/services/s3/model/ReplicationRuleStatus.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "5522" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" ?> <class name="PacketPeerStream" inherits="PacketPeer" category="Core" version="3.1"> <brief_description> Wrapper to use a PacketPeer over a StreamPeer. </brief_description> <description> PacketStreamPeer provides a wrapper for working using packets over a stream. This allows for using packet based code with StreamPeers. PacketPeerStream implements a custom protocol over the StreamPeer, so the user should not read or write to the wrapped StreamPeer directly. </description> <tutorials> </tutorials> <demos> </demos> <methods> </methods> <members> <member name="input_buffer_max_size" type="int" setter="set_input_buffer_max_size" getter="get_input_buffer_max_size"> </member> <member name="output_buffer_max_size" type="int" setter="set_output_buffer_max_size" getter="get_output_buffer_max_size"> </member> <member name="stream_peer" type="StreamPeer" setter="set_stream_peer" getter="get_stream_peer"> The wrapped [StreamPeer] object. </member> </members> <constants> </constants> </class>
{ "content_hash": "1ed8af9a7810ca02852695de673f8d00", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 276, "avg_line_length": 41.03846153846154, "alnum_prop": 0.7366447985004686, "repo_name": "RandomShaper/godot", "id": "9e3195bb448ec5883a4d7f41dd156705398259b1", "size": "1067", "binary": false, "copies": "17", "ref": "refs/heads/master", "path": "doc/classes/PacketPeerStream.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "50004" }, { "name": "C#", "bytes": "210398" }, { "name": "C++", "bytes": "21200242" }, { "name": "GLSL", "bytes": "1271" }, { "name": "Java", "bytes": "493677" }, { "name": "JavaScript", "bytes": "15889" }, { "name": "Makefile", "bytes": "451" }, { "name": "Objective-C", "bytes": "2645" }, { "name": "Objective-C++", "bytes": "185290" }, { "name": "Python", "bytes": "332071" }, { "name": "Shell", "bytes": "20062" } ], "symlink_target": "" }
from __future__ import annotations # isort:skip import pytest ; pytest #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Standard library imports from time import sleep # External imports from selenium.webdriver.common.keys import Keys # Bokeh imports from bokeh.layouts import column from bokeh.models import ( ColumnDataSource, CustomJS, DataTable, TableColumn, TextInput, ) from tests.support.plugins.project import BokehModelPage from tests.support.util.selenium import ( RECORD, enter_text_in_element, find_element_for, get_table_row, shift_click, ) #----------------------------------------------------------------------------- # Tests #----------------------------------------------------------------------------- pytest_plugins = ( "tests.support.plugins.project", ) @pytest.mark.selenium class Test_DataTableCopyPaste: def test_single_row_copy(self, bokeh_model_page: BokehModelPage) -> None: data = {'x': [1,2,3,4], 'y': [1,1,1,1], 'd': ['foo', 'bar', 'baz', 'quux']} source = ColumnDataSource(data) table = DataTable(columns=[ TableColumn(field="x", title="x"), TableColumn(field="y", title="y"), TableColumn(field="d", title="d"), ], source=source) text_input = TextInput() text_input.js_on_change('value', CustomJS(code=RECORD("value", "cb_obj.value"))) page = bokeh_model_page(column(table, text_input)) row = get_table_row(page.driver, table, 2) row.click() enter_text_in_element(page.driver, row, Keys.INSERT, mod=Keys.CONTROL, click=0, enter=False) input_el = find_element_for(page.driver, text_input) enter_text_in_element(page.driver, input_el, Keys.INSERT, mod=Keys.SHIFT, enter=False) enter_text_in_element(page.driver, input_el, "") sleep(0.5) results = page.results assert results['value'] == '1\t2\t1\tbar' assert page.has_no_console_errors() def test_single_row_copy_with_zero(self, bokeh_model_page: BokehModelPage) -> None: data = {'x': [1,2,3,4], 'y': [0,0,0,0], 'd': ['foo', 'bar', 'baz', 'quux']} source = ColumnDataSource(data) table = DataTable(columns=[ TableColumn(field="x", title="x"), TableColumn(field="y", title="y"), TableColumn(field="d", title="d"), ], source=source) text_input = TextInput() text_input.js_on_change('value', CustomJS(code=RECORD("value", "cb_obj.value"))) page = bokeh_model_page(column(table, text_input)) row = get_table_row(page.driver, table, 2) row.click() enter_text_in_element(page.driver, row, Keys.INSERT, mod=Keys.CONTROL, click=0, enter=False) input_el = find_element_for(page.driver, text_input) enter_text_in_element(page.driver, input_el, Keys.INSERT, mod=Keys.SHIFT, enter=False) enter_text_in_element(page.driver, input_el, "") sleep(0.5) results = page.results assert results['value'] == '1\t2\t0\tbar' assert page.has_no_console_errors() def test_multi_row_copy(self, bokeh_model_page: BokehModelPage) -> None: data = {'x': [1,2,3,4], 'y': [0,1,2,3], 'd': ['foo', 'bar', 'baz', 'quux']} source = ColumnDataSource(data) table = DataTable(columns=[ TableColumn(field="x", title="x"), TableColumn(field="y", title="y"), TableColumn(field="d", title="d"), ], source=source) text_input = TextInput() text_input.js_on_change('value', CustomJS(code=RECORD("value", "cb_obj.value"))) page = bokeh_model_page(column(table, text_input)) row = get_table_row(page.driver, table, 1) row.click() row = get_table_row(page.driver, table, 3) shift_click(page.driver, row) enter_text_in_element(page.driver, row, Keys.INSERT, mod=Keys.CONTROL, click=0, enter=False) input_el = find_element_for(page.driver, text_input) enter_text_in_element(page.driver, input_el, Keys.INSERT, mod=Keys.SHIFT, enter=False) enter_text_in_element(page.driver, input_el, "") results = page.results # XXX (bev) these should be newlines with a TextAreaInput but TextAreaInput # is not working in tests for some reason presently assert results['value'] == '0\t1\t0\tfoo 1\t2\t1\tbar 2\t3\t2\tbaz' assert page.has_no_console_errors()
{ "content_hash": "236fcc16a84280c84bb08fd04cc37dc2", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 100, "avg_line_length": 33.98529411764706, "alnum_prop": 0.572263089571614, "repo_name": "bokeh/bokeh", "id": "40ba07e2112d8b8346c2edf6d5ba2f822aa902f9", "size": "5142", "binary": false, "copies": "1", "ref": "refs/heads/branch-3.1", "path": "tests/integration/widgets/tables/test_copy_paste.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1884" }, { "name": "Dockerfile", "bytes": "1924" }, { "name": "GLSL", "bytes": "44696" }, { "name": "HTML", "bytes": "53475" }, { "name": "JavaScript", "bytes": "20301" }, { "name": "Less", "bytes": "46376" }, { "name": "Python", "bytes": "4475226" }, { "name": "Shell", "bytes": "7673" }, { "name": "TypeScript", "bytes": "3652153" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using BiBilet.Domain.Entities.Application; namespace BiBilet.Domain.Repositories.Application { /// <summary> /// Repository interface for <see cref="SubTopic" /> /// </summary> public interface ISubTopicRepository : IRepository<SubTopic> { /// <summary> /// Returns a list of sub topics /// </summary> /// <param name="topicId"></param> /// <returns>A list of <see cref="SubTopic" /></returns> List<SubTopic> GetSubTopics(Guid topicId); /// <summary> /// Asynchronously returns a list of sub topics /// </summary> /// <param name="topicId"></param> /// <returns>A list of <see cref="SubTopic" /></returns> Task<List<SubTopic>> GetSubTopicsAsync(Guid topicId); /// <summary> /// Asynchronously returns a list of sub topics /// with cancellation support /// </summary> /// <param name="topicId"></param> /// <param name="cancellationToken"></param> /// <returns>A list of <see cref="SubTopic" /></returns> Task<List<SubTopic>> GetSubTopicsAsync(Guid topicId, CancellationToken cancellationToken); } }
{ "content_hash": "ba9bd41f44b7358f1717287e52ffff89", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 98, "avg_line_length": 34.810810810810814, "alnum_prop": 0.6149068322981367, "repo_name": "erenpinaz/BiBilet", "id": "f33cce3f170a19a66cbe6bbfdcf20601b9dadf98", "size": "1290", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BiBilet.Domain/Repositories/Application/ISubTopicRepository.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "93" }, { "name": "C#", "bytes": "312309" }, { "name": "CSS", "bytes": "164447" }, { "name": "HTML", "bytes": "210" }, { "name": "JavaScript", "bytes": "545991" } ], "symlink_target": "" }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.apache.cloudstack</groupId> <artifactId>cloudstack-plugins</artifactId> <version>4.16.0.0-SNAPSHOT</version> <relativePath>../../pom.xml</relativePath> </parent> <artifactId>cloud-plugin-example-dns-notifier</artifactId> <name>Apache CloudStack Plugin - Dns Notifier Example</name> <description>This is sample source code on how to write a plugin for CloudStack</description> <dependencies> <dependency> <groupId>org.apache.cloudstack</groupId> <artifactId>cloud-api</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.apache.cloudstack</groupId> <artifactId>cloud-utils</artifactId> <version>${project.version}</version> </dependency> </dependencies> </project>
{ "content_hash": "dbfcd4939dd2cd906398f7f32b2eadb6", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 104, "avg_line_length": 44.83720930232558, "alnum_prop": 0.6986514522821576, "repo_name": "GabrielBrascher/cloudstack", "id": "b5bf324c753cdb8d2e1689765b3672fb0b8bcbe8", "size": "1928", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugins/network-elements/dns-notifier/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "9979" }, { "name": "C#", "bytes": "2356211" }, { "name": "CSS", "bytes": "42504" }, { "name": "Dockerfile", "bytes": "4189" }, { "name": "FreeMarker", "bytes": "4887" }, { "name": "Groovy", "bytes": "146420" }, { "name": "HTML", "bytes": "53626" }, { "name": "Java", "bytes": "38859783" }, { "name": "JavaScript", "bytes": "995137" }, { "name": "Less", "bytes": "28250" }, { "name": "Makefile", "bytes": "871" }, { "name": "Python", "bytes": "12977377" }, { "name": "Ruby", "bytes": "22732" }, { "name": "Shell", "bytes": "744445" }, { "name": "Vue", "bytes": "2012353" }, { "name": "XSLT", "bytes": "57835" } ], "symlink_target": "" }
/* opensslconf.h */ /* WARNING: Generated automatically from opensslconf.h.in by Configure. */ /* OpenSSL was configured with the following options: */ #ifndef OPENSSL_SYSNAME_WIN32 # define OPENSSL_SYSNAME_WIN32 #endif #ifndef OPENSSL_DOING_MAKEDEPEND #ifndef OPENSSL_NO_EC_NISTP_64_GCC_128 # define OPENSSL_NO_EC_NISTP_64_GCC_128 #endif #ifndef OPENSSL_NO_GMP # define OPENSSL_NO_GMP #endif #ifndef OPENSSL_NO_JPAKE # define OPENSSL_NO_JPAKE #endif #ifndef OPENSSL_NO_KRB5 # define OPENSSL_NO_KRB5 #endif #ifndef OPENSSL_NO_MD2 # define OPENSSL_NO_MD2 #endif #ifndef OPENSSL_NO_RC5 # define OPENSSL_NO_RC5 #endif #ifndef OPENSSL_NO_RFC3779 # define OPENSSL_NO_RFC3779 #endif #ifndef OPENSSL_NO_SCTP # define OPENSSL_NO_SCTP #endif #ifndef OPENSSL_NO_STORE # define OPENSSL_NO_STORE #endif #endif /* OPENSSL_DOING_MAKEDEPEND */ #ifndef OPENSSL_THREADS # define OPENSSL_THREADS #endif /* The OPENSSL_NO_* macros are also defined as NO_* if the application asks for it. This is a transient feature that is provided for those who haven't had the time to do the appropriate changes in their applications. */ #ifdef OPENSSL_ALGORITHM_DEFINES # if defined(OPENSSL_NO_EC_NISTP_64_GCC_128) && !defined(NO_EC_NISTP_64_GCC_128) # define NO_EC_NISTP_64_GCC_128 # endif # if defined(OPENSSL_NO_GMP) && !defined(NO_GMP) # define NO_GMP # endif # if defined(OPENSSL_NO_JPAKE) && !defined(NO_JPAKE) # define NO_JPAKE # endif # if defined(OPENSSL_NO_KRB5) && !defined(NO_KRB5) # define NO_KRB5 # endif # if defined(OPENSSL_NO_MD2) && !defined(NO_MD2) # define NO_MD2 # endif # if defined(OPENSSL_NO_RC5) && !defined(NO_RC5) # define NO_RC5 # endif # if defined(OPENSSL_NO_RFC3779) && !defined(NO_RFC3779) # define NO_RFC3779 # endif # if defined(OPENSSL_NO_SCTP) && !defined(NO_SCTP) # define NO_SCTP # endif # if defined(OPENSSL_NO_STORE) && !defined(NO_STORE) # define NO_STORE # endif #endif #define OPENSSL_CPUID_OBJ /* crypto/opensslconf.h.in */ /* Generate 80386 code? */ #undef I386_ONLY #if !(defined(VMS) || defined(__VMS)) /* VMS uses logical names instead */ #if defined(HEADER_CRYPTLIB_H) && !defined(OPENSSLDIR) #define ENGINESDIR "c:/openssl/lib/engines" #define OPENSSLDIR "c:/openssl/ssl" #endif #endif #undef OPENSSL_UNISTD #define OPENSSL_UNISTD <unistd.h> #undef OPENSSL_EXPORT_VAR_AS_FUNCTION #define OPENSSL_EXPORT_VAR_AS_FUNCTION #if defined(HEADER_IDEA_H) && !defined(IDEA_INT) #define IDEA_INT unsigned int #endif #if defined(HEADER_MD2_H) && !defined(MD2_INT) #define MD2_INT unsigned int #endif #if defined(HEADER_RC2_H) && !defined(RC2_INT) /* I need to put in a mod for the alpha - eay */ #define RC2_INT unsigned int #endif #if defined(HEADER_RC4_H) #if !defined(RC4_INT) /* using int types make the structure larger but make the code faster * on most boxes I have tested - up to %20 faster. */ /* * I don't know what does "most" mean, but declaring "int" is a must on: * - Intel P6 because partial register stalls are very expensive; * - elder Alpha because it lacks byte load/store instructions; */ #define RC4_INT unsigned int #endif #if !defined(RC4_CHUNK) /* * This enables code handling data aligned at natural CPU word * boundary. See crypto/rc4/rc4_enc.c for further details. */ #undef RC4_CHUNK #endif #endif #if (defined(HEADER_NEW_DES_H) || defined(HEADER_DES_H)) && !defined(DES_LONG) /* If this is set to 'unsigned int' on a DEC Alpha, this gives about a * %20 speed up (longs are 8 bytes, int's are 4). */ #ifndef DES_LONG #define DES_LONG unsigned long #endif #endif #if defined(HEADER_BN_H) && !defined(CONFIG_HEADER_BN_H) #define CONFIG_HEADER_BN_H #define BN_LLONG /* Should we define BN_DIV2W here? */ /* Only one for the following should be defined */ #undef SIXTY_FOUR_BIT_LONG #undef SIXTY_FOUR_BIT #define THIRTY_TWO_BIT #endif #if defined(HEADER_RC4_LOCL_H) && !defined(CONFIG_HEADER_RC4_LOCL_H) #define CONFIG_HEADER_RC4_LOCL_H /* if this is defined data[i] is used instead of *data, this is a %20 * speedup on x86 */ #define RC4_INDEX #endif #if defined(HEADER_BF_LOCL_H) && !defined(CONFIG_HEADER_BF_LOCL_H) #define CONFIG_HEADER_BF_LOCL_H #undef BF_PTR #endif /* HEADER_BF_LOCL_H */ #if defined(HEADER_DES_LOCL_H) && !defined(CONFIG_HEADER_DES_LOCL_H) #define CONFIG_HEADER_DES_LOCL_H #ifndef DES_DEFAULT_OPTIONS /* the following is tweaked from a config script, that is why it is a * protected undef/define */ #ifndef DES_PTR #undef DES_PTR #endif /* This helps C compiler generate the correct code for multiple functional * units. It reduces register dependancies at the expense of 2 more * registers */ #ifndef DES_RISC1 #undef DES_RISC1 #endif #ifndef DES_RISC2 #undef DES_RISC2 #endif #if defined(DES_RISC1) && defined(DES_RISC2) YOU SHOULD NOT HAVE BOTH DES_RISC1 AND DES_RISC2 DEFINED!!!!! #endif /* Unroll the inner loop, this sometimes helps, sometimes hinders. * Very mucy CPU dependant */ #ifndef DES_UNROLL #undef DES_UNROLL #endif /* These default values were supplied by * Peter Gutman <pgut001@cs.auckland.ac.nz> * They are only used if nothing else has been defined */ #if !defined(DES_PTR) && !defined(DES_RISC1) && !defined(DES_RISC2) && !defined(DES_UNROLL) /* Special defines which change the way the code is built depending on the CPU and OS. For SGI machines you can use _MIPS_SZLONG (32 or 64) to find even newer MIPS CPU's, but at the moment one size fits all for optimization options. Older Sparc's work better with only UNROLL, but there's no way to tell at compile time what it is you're running on */ #if defined( sun ) /* Newer Sparc's */ # define DES_PTR # define DES_RISC1 # define DES_UNROLL #elif defined( __ultrix ) /* Older MIPS */ # define DES_PTR # define DES_RISC2 # define DES_UNROLL #elif defined( __osf1__ ) /* Alpha */ # define DES_PTR # define DES_RISC2 #elif defined ( _AIX ) /* RS6000 */ /* Unknown */ #elif defined( __hpux ) /* HP-PA */ /* Unknown */ #elif defined( __aux ) /* 68K */ /* Unknown */ #elif defined( __dgux ) /* 88K (but P6 in latest boxes) */ # define DES_UNROLL #elif defined( __sgi ) /* Newer MIPS */ # define DES_PTR # define DES_RISC2 # define DES_UNROLL #elif defined(i386) || defined(__i386__) /* x86 boxes, should be gcc */ # define DES_PTR # define DES_RISC1 # define DES_UNROLL #endif /* Systems-specific speed defines */ #endif #endif /* DES_DEFAULT_OPTIONS */ #endif /* HEADER_DES_LOCL_H */
{ "content_hash": "109f9cd8e57d446c8cf685fcd162234f", "timestamp": "", "source": "github", "line_count": 235, "max_line_length": 91, "avg_line_length": 28.28936170212766, "alnum_prop": 0.6850180505415162, "repo_name": "suhetao/srs.win", "id": "e7ea8b8e17cd3198482a7d016ce75fdad9431373", "size": "6648", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "trunk/win/lib/openssl-1.0.1e/inc32/openssl/opensslconf.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "864119" }, { "name": "C", "bytes": "14361551" }, { "name": "C++", "bytes": "1820949" }, { "name": "Emacs Lisp", "bytes": "1639" }, { "name": "Objective-C", "bytes": "5094" }, { "name": "Perl", "bytes": "3507919" }, { "name": "Python", "bytes": "2855" }, { "name": "Scheme", "bytes": "4249" }, { "name": "Shell", "bytes": "110044" }, { "name": "eC", "bytes": "5079" } ], "symlink_target": "" }
"""Python interface to GenoLogics LIMS via its REST API. Usage example: Get some projects. Per Kraulis, Science for Life Laboratory, Stockholm, Sweden. """ import codecs from genologics.lims import * # Login parameters for connecting to a LIMS instance. from genologics.config import BASEURI, USERNAME, PASSWORD # Create the LIMS interface instance, and check the connection and version. lims = Lims(BASEURI, USERNAME, PASSWORD) lims.check_version() # Get the list of all projects. projects = lims.get_projects() print len(projects), 'projects in total' # Get the list of all projects opened since May 30th 2012. day = '2012-05-30' projects = lims.get_projects(open_date=day) print len(projects), 'projects opened since', day # Get the project with the specified LIMS id, and print some info. project = Project(lims, id='P193') print project, project.name, project.open_date, project.close_date print ' UDFs:' for key, value in project.udf.items(): if isinstance(value, unicode): value = codecs.encode(value, 'UTF-8') print ' ', key, '=', value udt = project.udt print ' UDT:', udt.udt for key, value in udt.items(): if isinstance(value, unicode): value = codecs.encode(value, 'UTF-8') print ' ', key, '=', value print ' files:' for file in project.files: print file.id print file.content_location print file.original_location
{ "content_hash": "8780f0db7a50c8e6703bc7801037e32c", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 75, "avg_line_length": 27.333333333333332, "alnum_prop": 0.7116212338593975, "repo_name": "jwhite007/genologics", "id": "47c102e795458d376f9db5bdab7079ea5fd2cbe4", "size": "1394", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "examples/get_projects.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "232163" } ], "symlink_target": "" }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <html> <head> <meta charset='utf-8'> <script src='lib/simpleRequire.js'></script> <script src='lib/config.js'></script> <script src='lib/jquery.min.js'></script> <meta name="viewport" content="width=device-width, initial-scale=1" /> </head> <body> <style> html, body, #main { width: 100%; height: 100%; margin: 0; } #next { position: absolute; left: 10px; top: 10px; } </style> <div id='main'></div> <button id="next">NEXT</button> <script> require([ 'echarts', 'data/usa.json' ], function (echarts, geojson) { echarts.registerMap('USA', geojson, { Alaska: { // 把阿拉斯加移到美国主大陆左下方 left: -131, top: 25, width: 15 }, Hawaii: { left: -110, // 夏威夷 top: 28, width: 5 }, 'Puerto Rico': { // 波多黎各 left: -76, top: 26, width: 2 } }); const tmpChart = echarts.init(document.createElement('div'), null, { width: window.innerWidth, height: window.innerHeight }); tmpChart.setOption({ geo: { map: 'USA' } }); const geo = tmpChart.getModel().getComponent('geo').coordinateSystem; const regionsMap = geo.regions.reduce(function (obj, region) { obj[region.properties.name] = region; return obj; }, {}); const transform = geo.transform; const data = [ {name: 'Alabama', value: 4822023}, {name: 'Alaska', value: 731449}, {name: 'Arizona', value: 6553255}, {name: 'Arkansas', value: 2949131}, {name: 'California', value: 38041430}, {name: 'Colorado', value: 5187582}, {name: 'Connecticut', value: 3590347}, {name: 'Delaware', value: 917092}, {name: 'District of Columbia', value: 632323}, {name: 'Florida', value: 19317568}, {name: 'Georgia', value: 9919945}, {name: 'Hawaii', value: 1392313}, {name: 'Idaho', value: 1595728}, {name: 'Illinois', value: 12875255}, {name: 'Indiana', value: 6537334}, {name: 'Iowa', value: 3074186}, {name: 'Kansas', value: 2885905}, {name: 'Kentucky', value: 4380415}, {name: 'Louisiana', value: 4601893}, {name: 'Maine', value: 1329192}, {name: 'Maryland', value: 5884563}, {name: 'Massachusetts', value: 6646144}, {name: 'Michigan', value: 9883360}, {name: 'Minnesota', value: 5379139}, {name: 'Mississippi', value: 2984926}, {name: 'Missouri', value: 6021988}, {name: 'Montana', value: 1005141}, {name: 'Nebraska', value: 1855525}, {name: 'Nevada', value: 2758931}, {name: 'New Hampshire', value: 1320718}, {name: 'New Jersey', value: 8864590}, {name: 'New Mexico', value: 2085538}, {name: 'New York', value: 19570261}, {name: 'North Carolina', value: 9752073}, {name: 'North Dakota', value: 699628}, {name: 'Ohio', value: 11544225}, {name: 'Oklahoma', value: 3814820}, {name: 'Oregon', value: 3899353}, {name: 'Pennsylvania', value: 12763536}, {name: 'Rhode Island', value: 1050292}, {name: 'South Carolina', value: 4723723}, {name: 'South Dakota', value: 833354}, {name: 'Tennessee', value: 6456243}, {name: 'Texas', value: 26059203}, {name: 'Utah', value: 2855287}, {name: 'Vermont', value: 626011}, {name: 'Virginia', value: 8185867}, {name: 'Washington', value: 6897012}, {name: 'West Virginia', value: 1855413}, {name: 'Wisconsin', value: 5726398}, {name: 'Wyoming', value: 576412}, {name: 'Puerto Rico', value: 3667084} ]; const myChart = echarts.init(document.getElementById('main')); function createMapOption() { return { series: [{ coordinateSystem: 'none', type: 'custom', data, animationDurationUpdate: 2000, universalTransition: { enabled: true }, renderItem(params, api) { const dataItem = data[params.dataIndex]; const geometries = regionsMap[dataItem.name].geometries.slice(); // Pick the main polygon // TODO Multipolygon geometries.sort((a, b) => b.exterior.length - a.exterior.length); const points = geometries[0].exterior; const newPoints = []; for (let i = 0; i < points.length; i++) { newPoints.push([ points[i][0] * transform[0] + transform[4], points[i][1] * transform[3] + transform[5] ]); } return { type: 'polygon', shape: { points: newPoints }, style: { fill: '#aaa', stroke: '#555', strokeNoScale: true } } } }] }; } function renderBarItem(params, api) { const dataItem = data[params.dataIndex]; const start = api.coord([params.dataIndex, 0]); const size = api.size([0, api.value(1)]); const width = 20; return { type: 'rect', shape: { x: start[0] - width / 2, y: start[1], width: width, height: -size[1] }, style: { fill: '#aaa', stroke: '#555', strokeNoScale: true }, }; } function renderBubbleItem(params, api) { const dataItem = data[params.dataIndex]; const center = api.coord([params.dataIndex, api.value(1)]); return { type: 'circle', shape: { cx: center[0], cy: center[1], r: api.value(1) / 5e5 }, style: { fill: '#aaa', stroke: '#555', strokeNoScale: true }, }; } function createCartesianOption(renderItem) { return { xAxis: { data: data.map(item => item.name) }, yAxis: { }, series: [{ type: 'custom', data, animationDurationUpdate: 2000, universalTransition: { enabled: true }, renderItem }] }; } function createPieOption(renderItem) { const pieData = data.slice(); pieData.reverse(); const totalValue = pieData.reduce(function (val, item) { return val + item.value; }, 0); let angles = []; let currentAngle = -Math.PI / 2; for (let i = 0; i < pieData.length; i++) { const angle = pieData[i].value / totalValue * Math.PI * 2; angles.push([currentAngle, angle + currentAngle]); currentAngle += angle; } return { series: [{ type: 'custom', coordinateSystem: 'none', data: pieData, animationDurationUpdate: 2000, universalTransition: { enabled: true }, renderItem(params, api) { const width = myChart.getWidth(); const height = myChart.getHeight(); return { type: 'sector', shape: { cx: width / 2, cy: height / 2, r: Math.min(width, height) / 3, r0: Math.min(width, height) / 5, startAngle: angles[params.dataIndex][0], endAngle: angles[params.dataIndex][1], clockwise: true }, style: { fill: '#aaa', stroke: '#555', strokeNoScale: true }, }; } }] }; } const options = [ createMapOption(), createCartesianOption(renderBarItem), createCartesianOption(renderBubbleItem), createPieOption() ]; let currentIndex = 0; myChart.setOption(options[currentIndex]); function transitionToNext() { const nextIndex = (currentIndex + 1) % options.length; myChart.setOption(options[nextIndex], true); currentIndex = nextIndex; } document.querySelector('#next').onclick = function () { transitionToNext(); } }); </script> </body> </html>
{ "content_hash": "c2db311bae34b8fb54da121b53394db7", "timestamp": "", "source": "github", "line_count": 312, "max_line_length": 97, "avg_line_length": 42.256410256410255, "alnum_prop": 0.365063713592233, "repo_name": "apache/incubator-echarts", "id": "38df70e6e9e04a3478f98160196a0ec27805aeff", "size": "13229", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/custom-shape-morphing.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "13440" }, { "name": "HTML", "bytes": "4074349" }, { "name": "JavaScript", "bytes": "5201227" } ], "symlink_target": "" }
package org.elasticsearch.xpack.ml.rest.filter; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestRequest; import org.elasticsearch.rest.action.RestToXContentListener; import org.elasticsearch.xpack.core.ml.action.DeleteFilterAction; import org.elasticsearch.xpack.core.ml.action.DeleteFilterAction.Request; import org.elasticsearch.xpack.ml.MachineLearning; import java.io.IOException; import java.util.Collections; import java.util.List; import static org.elasticsearch.rest.RestRequest.Method.DELETE; public class RestDeleteFilterAction extends BaseRestHandler { @Override public List<Route> routes() { return Collections.singletonList( new Route(DELETE, MachineLearning.BASE_PATH + "filters/{" + Request.FILTER_ID.getPreferredName() + "}") ); } @Override public String getName() { return "ml_delete_filter_action"; } @Override protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) throws IOException { Request request = new Request(restRequest.param(Request.FILTER_ID.getPreferredName())); request.timeout(restRequest.paramAsTime("timeout", request.timeout())); request.masterNodeTimeout(restRequest.paramAsTime("master_timeout", request.masterNodeTimeout())); return channel -> client.execute(DeleteFilterAction.INSTANCE, request, new RestToXContentListener<>(channel)); } }
{ "content_hash": "3444d15260707f8db8268522db9d7236", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 118, "avg_line_length": 37.7, "alnum_prop": 0.7619363395225465, "repo_name": "gingerwizard/elasticsearch", "id": "9857d587b50a7e2bf84b4f2477dd14f1a63d81a5", "size": "1749", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/rest/filter/RestDeleteFilterAction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "10862" }, { "name": "Groovy", "bytes": "510" }, { "name": "HTML", "bytes": "1502" }, { "name": "Java", "bytes": "29923429" }, { "name": "Perl", "bytes": "264378" }, { "name": "Perl6", "bytes": "103207" }, { "name": "Python", "bytes": "91186" }, { "name": "Ruby", "bytes": "17776" }, { "name": "Shell", "bytes": "85779" } ], "symlink_target": "" }
@interface ZBShopCollectionViewCell() @property (weak, nonatomic) IBOutlet UILabel *PriceLabel; @property (weak, nonatomic) IBOutlet UIImageView *ClothesImage; @end @implementation ZBShopCollectionViewCell -(void)setShop:(ZBShop *)shop{ // 1.衣服的图片 [self.ClothesImage sd_setImageWithURL:[NSURL URLWithString:shop.img] placeholderImage:[UIImage imageNamed:@"loading.png"]]; // 2.衣服的价格 self.PriceLabel.text = shop.price; } @end
{ "content_hash": "6612ecd251c8963d1f1b8b699350d942", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 127, "avg_line_length": 27.8125, "alnum_prop": 0.755056179775281, "repo_name": "zb553828497/WaterFall", "id": "d81342e8886b640a4f1b443885c234fa4d3099fb", "size": "701", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WaterFall/ZBShopCollectionViewCell.m", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Objective-C", "bytes": "283291" } ], "symlink_target": "" }
package org.commonjava.indy.sli.metrics; import org.commonjava.o11yphant.metrics.api.MetricSet; import org.commonjava.o11yphant.metrics.MetricSetProvider; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; @ApplicationScoped public class IndyGoldenSignalsMetricSetProvider implements MetricSetProvider { @Inject private IndyGoldenSignalsMetricSet metricSet; @Override public MetricSet getMetricSet() { return metricSet; } @Override public String getName() { return "sli.golden"; } @Override public void reset() { metricSet.reset(); } }
{ "content_hash": "1f9b10e46e0aa6a04efd02cc2941f128", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 58, "avg_line_length": 19.38235294117647, "alnum_prop": 0.708649468892261, "repo_name": "ruhan1/indy", "id": "d760c38967f5d0b791a07c16a1e83add942bb736", "size": "1306", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "addons/sli/src/main/java/org/commonjava/indy/sli/metrics/IndyGoldenSignalsMetricSetProvider.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "6390" }, { "name": "Dockerfile", "bytes": "3740" }, { "name": "Groovy", "bytes": "45401" }, { "name": "HTML", "bytes": "72730" }, { "name": "Java", "bytes": "5848803" }, { "name": "JavaScript", "bytes": "75187" }, { "name": "Python", "bytes": "78715" }, { "name": "Ruby", "bytes": "13080" }, { "name": "Shell", "bytes": "32345" } ], "symlink_target": "" }
<?php namespace JsonApiHttp; class Included extends Resources {}
{ "content_hash": "7ecc98282795c4b06e125993fef233f7", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 35, "avg_line_length": 13.4, "alnum_prop": 0.7761194029850746, "repo_name": "tomblakemore/laravel-jsonapi-http", "id": "f5412410d1bdab6370d1c4b1d3a552ecf6f312d9", "size": "67", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Included.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "94226" } ], "symlink_target": "" }
<?php namespace UserFrosting\Sprinkle\Admin\Controller; use Illuminate\Database\Capsule\Manager as Capsule; use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use UserFrosting\Fortress\Adapter\JqueryValidationAdapter; use UserFrosting\Fortress\RequestDataTransformer; use UserFrosting\Fortress\RequestSchema; use UserFrosting\Fortress\ServerSideValidator; use UserFrosting\Sprinkle\Account\Database\Models\Role; use UserFrosting\Sprinkle\Core\Controller\SimpleController; use UserFrosting\Support\Exception\BadRequestException; use UserFrosting\Support\Exception\ForbiddenException; use UserFrosting\Support\Exception\NotFoundException; /** * Controller class for role-related requests, including listing roles, CRUD for roles, etc. * * @author Alex Weissman (https://alexanderweissman.com) */ class RoleController extends SimpleController { /** * Processes the request to create a new role. * * Processes the request from the role creation form, checking that: * 1. The role name and slug are not already in use; * 2. The user has permission to create a new role; * 3. The submitted data is valid. * This route requires authentication (and should generally be limited to admins or the root user). * * Request type: POST * * @see getModalCreateRole * * @param Request $request * @param Response $response * @param array $args * * @throws ForbiddenException If user is not authorized to access page */ public function create(Request $request, Response $response, $args) { // Get POST parameters: name, slug, description $params = $request->getParsedBody(); /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */ $authorizer = $this->ci->authorizer; /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */ $currentUser = $this->ci->currentUser; // Access-controlled page if (!$authorizer->checkAccess($currentUser, 'create_role')) { throw new ForbiddenException(); } /** @var \UserFrosting\Sprinkle\Core\Alert\AlertStream $ms */ $ms = $this->ci->alerts; // Load the request schema $schema = new RequestSchema('schema://requests/role/create.yaml'); // Whitelist and set parameter defaults $transformer = new RequestDataTransformer($schema); $data = $transformer->transform($params); $error = false; // Validate request data $validator = new ServerSideValidator($schema, $this->ci->translator); if (!$validator->validate($data)) { $ms->addValidationErrors($validator); $error = true; } /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */ $classMapper = $this->ci->classMapper; // Check if name or slug already exists if ($classMapper->getClassMapping('role')::where('name', $data['name'])->first()) { $ms->addMessageTranslated('danger', 'ROLE.NAME_IN_USE', $data); $error = true; } if ($classMapper->getClassMapping('role')::where('slug', $data['slug'])->first()) { $ms->addMessageTranslated('danger', 'SLUG_IN_USE', $data); $error = true; } if ($error) { return $response->withJson([], 400); } /** @var \UserFrosting\Support\Repository\Repository $config */ $config = $this->ci->config; // All checks passed! log events/activities and create role // Begin transaction - DB will be rolled back if an exception occurs Capsule::transaction(function () use ($classMapper, $data, $ms, $currentUser) { // Create the role $role = $classMapper->createInstance('role', $data); // Store new role to database $role->save(); // Create activity record $this->ci->userActivityLogger->info("User {$currentUser->user_name} created role {$role->name}.", [ 'type' => 'role_create', 'user_id' => $currentUser->id, ]); $ms->addMessageTranslated('success', 'ROLE.CREATION_SUCCESSFUL', $data); }); return $response->withJson([], 200); } /** * Processes the request to delete an existing role. * * Deletes the specified role. * Before doing so, checks that: * 1. The user has permission to delete this role; * 2. The role is not a default for new users; * 3. The role does not have any associated users; * 4. The submitted data is valid. * This route requires authentication (and should generally be limited to admins or the root user). * * Request type: DELETE * * @param Request $request * @param Response $response * @param array $args * * @throws NotFoundException If role is not found * @throws ForbiddenException If user is not authorized to access page * @throws BadRequestException */ public function delete(Request $request, Response $response, $args) { $role = $this->getRoleFromParams($args); // If the role doesn't exist, return 404 if (!$role) { throw new NotFoundException(); } /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */ $authorizer = $this->ci->authorizer; /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */ $currentUser = $this->ci->currentUser; // Access-controlled page if (!$authorizer->checkAccess($currentUser, 'delete_role', [ 'role' => $role, ])) { throw new ForbiddenException(); } /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */ $classMapper = $this->ci->classMapper; // Check that we are not deleting a default role $defaultRoleSlugs = $classMapper->getClassMapping('role')::getDefaultSlugs(); // Need to use loose comparison for now, because some DBs return `id` as a string if (in_array($role->slug, $defaultRoleSlugs)) { $e = new BadRequestException(); $e->addUserMessage('ROLE.DELETE_DEFAULT'); throw $e; } // Check if there are any users associated with this role $countUsers = $role->users()->count(); if ($countUsers > 0) { $e = new BadRequestException(); $e->addUserMessage('ROLE.HAS_USERS'); throw $e; } $roleName = $role->name; // Begin transaction - DB will be rolled back if an exception occurs Capsule::transaction(function () use ($role, $roleName, $currentUser) { $role->delete(); unset($role); // Create activity record $this->ci->userActivityLogger->info("User {$currentUser->user_name} deleted role {$roleName}.", [ 'type' => 'role_delete', 'user_id' => $currentUser->id, ]); }); /** @var \UserFrosting\Sprinkle\Core\Alert\AlertStream $ms */ $ms = $this->ci->alerts; $ms->addMessageTranslated('success', 'ROLE.DELETION_SUCCESSFUL', [ 'name' => $roleName, ]); return $response->withJson([], 200); } /** * Returns info for a single role, along with associated permissions. * * This page requires authentication. * * Request type: GET * * @param Request $request * @param Response $response * @param array $args * * @throws ForbiddenException If user is not authorized to access page * @throws NotFoundException If role is not found */ public function getInfo(Request $request, Response $response, $args) { /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager */ $authorizer = $this->ci->authorizer; /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */ $currentUser = $this->ci->currentUser; // Access-controlled page if (!$authorizer->checkAccess($currentUser, 'uri_roles')) { throw new ForbiddenException(); } $slug = $args['slug']; /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */ $classMapper = $this->ci->classMapper; $role = $classMapper->getClassMapping('role')::where('slug', $slug)->first(); // If the role doesn't exist, return 404 if (!$role) { throw new NotFoundException(); } // Get role $result = $role->load('permissions')->toArray(); // Be careful how you consume this data - it has not been escaped and contains untrusted user-supplied content. // For example, if you plan to insert it into an HTML DOM, you must escape it on the client side (or use client-side templating). return $response->withJson($result, 200, JSON_PRETTY_PRINT); } /** * Returns a list of Roles. * * Generates a list of roles, optionally paginated, sorted and/or filtered. * This page requires authentication. * * Request type: GET * * @param Request $request * @param Response $response * @param array $args * * @throws ForbiddenException If user is not authorized to access page */ public function getList(Request $request, Response $response, $args) { // GET parameters $params = $request->getQueryParams(); /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */ $authorizer = $this->ci->authorizer; /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */ $currentUser = $this->ci->currentUser; // Access-controlled page if (!$authorizer->checkAccess($currentUser, 'uri_roles')) { throw new ForbiddenException(); } /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */ $classMapper = $this->ci->classMapper; $sprunje = $classMapper->createInstance('role_sprunje', $classMapper, $params); // Be careful how you consume this data - it has not been escaped and contains untrusted user-supplied content. // For example, if you plan to insert it into an HTML DOM, you must escape it on the client side (or use client-side templating). return $sprunje->toResponse($response); } /** * Display deletion confirmation modal. * * @param Request $request * @param Response $response * @param array $args * * @throws NotFoundException If role is not found * @throws ForbiddenException If user is not authorized to access page * @throws BadRequestException */ public function getModalConfirmDelete(Request $request, Response $response, $args) { // GET parameters $params = $request->getQueryParams(); $role = $this->getRoleFromParams($params); // If the role no longer exists, forward to main role listing page if (!$role) { throw new NotFoundException(); } /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */ $authorizer = $this->ci->authorizer; /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */ $currentUser = $this->ci->currentUser; // Access-controlled page if (!$authorizer->checkAccess($currentUser, 'delete_role', [ 'role' => $role, ])) { throw new ForbiddenException(); } /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */ $classMapper = $this->ci->classMapper; // Check that we are not deleting a default role $defaultRoleSlugs = $classMapper->getClassMapping('role')::getDefaultSlugs(); // Need to use loose comparison for now, because some DBs return `id` as a string if (in_array($role->slug, $defaultRoleSlugs)) { $e = new BadRequestException(); $e->addUserMessage('ROLE.DELETE_DEFAULT', $role->toArray()); throw $e; } // Check if there are any users associated with this role $countUsers = $role->users()->count(); if ($countUsers > 0) { $e = new BadRequestException(); $e->addUserMessage('ROLE.HAS_USERS', $role->toArray()); throw $e; } return $this->ci->view->render($response, 'modals/confirm-delete-role.html.twig', [ 'role' => $role, 'form' => [ 'action' => "api/roles/r/{$role->slug}", ], ]); } /** * Renders the modal form for creating a new role. * * This does NOT render a complete page. Instead, it renders the HTML for the modal, which can be embedded in other pages. * This page requires authentication. * * Request type: GET * * @param Request $request * @param Response $response * @param array $args * * @throws ForbiddenException If user is not authorized to access page */ public function getModalCreate(Request $request, Response $response, $args) { // GET parameters $params = $request->getQueryParams(); /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */ $authorizer = $this->ci->authorizer; /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */ $currentUser = $this->ci->currentUser; /** @var \UserFrosting\I18n\Translator $translator */ $translator = $this->ci->translator; // Access-controlled page if (!$authorizer->checkAccess($currentUser, 'create_role')) { throw new ForbiddenException(); } /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */ $classMapper = $this->ci->classMapper; // Create a dummy role to prepopulate fields $role = $classMapper->createInstance('role', []); $fieldNames = ['name', 'slug', 'description']; $fields = [ 'hidden' => [], 'disabled' => [], ]; // Load validation rules $schema = new RequestSchema('schema://requests/role/create.yaml'); $validator = new JqueryValidationAdapter($schema, $this->ci->translator); return $this->ci->view->render($response, 'modals/role.html.twig', [ 'role' => $role, 'form' => [ 'action' => 'api/roles', 'method' => 'POST', 'fields' => $fields, 'submit_text' => $translator->translate('CREATE'), ], 'page' => [ 'validators' => $validator->rules('json', false), ], ]); } /** * Renders the modal form for editing an existing role. * * This does NOT render a complete page. Instead, it renders the HTML for the modal, which can be embedded in other pages. * This page requires authentication. * * Request type: GET * * @param Request $request * @param Response $response * @param array $args * * @throws NotFoundException If role is not found * @throws ForbiddenException If user is not authorized to access page */ public function getModalEdit(Request $request, Response $response, $args) { // GET parameters $params = $request->getQueryParams(); $role = $this->getRoleFromParams($params); // If the role doesn't exist, return 404 if (!$role) { throw new NotFoundException(); } /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */ $classMapper = $this->ci->classMapper; /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */ $authorizer = $this->ci->authorizer; /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */ $currentUser = $this->ci->currentUser; /** @var \UserFrosting\I18n\Translator $translator */ $translator = $this->ci->translator; // Access-controlled resource - check that currentUser has permission to edit basic fields "name", "slug", "description" for this role $fieldNames = ['name', 'slug', 'description']; if (!$authorizer->checkAccess($currentUser, 'update_role_field', [ 'role' => $role, 'fields' => $fieldNames, ])) { throw new ForbiddenException(); } // Generate form $fields = [ 'hidden' => [], 'disabled' => [], ]; // Load validation rules $schema = new RequestSchema('schema://requests/role/edit-info.yaml'); $validator = new JqueryValidationAdapter($schema, $translator); return $this->ci->view->render($response, 'modals/role.html.twig', [ 'role' => $role, 'form' => [ 'action' => "api/roles/r/{$role->slug}", 'method' => 'PUT', 'fields' => $fields, 'submit_text' => $translator->translate('UPDATE'), ], 'page' => [ 'validators' => $validator->rules('json', false), ], ]); } /** * Renders the modal form for editing a role's permissions. * * This does NOT render a complete page. Instead, it renders the HTML for the form, which can be embedded in other pages. * This page requires authentication. * * Request type: GET * * @param Request $request * @param Response $response * @param array $args * * @throws NotFoundException If role is not found * @throws ForbiddenException If user is not authorized to access page */ public function getModalEditPermissions(Request $request, Response $response, $args) { // GET parameters $params = $request->getQueryParams(); $role = $this->getRoleFromParams($params); // If the role doesn't exist, return 404 if (!$role) { throw new NotFoundException(); } /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */ $authorizer = $this->ci->authorizer; /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */ $currentUser = $this->ci->currentUser; // Access-controlled resource - check that currentUser has permission to edit "permissions" field for this role if (!$authorizer->checkAccess($currentUser, 'update_role_field', [ 'role' => $role, 'fields' => ['permissions'], ])) { throw new ForbiddenException(); } return $this->ci->view->render($response, 'modals/role-manage-permissions.html.twig', [ 'role' => $role, ]); } /** * Returns a list of Permissions for a specified Role. * * Generates a list of permissions, optionally paginated, sorted and/or filtered. * This page requires authentication. * * Request type: GET * * @param Request $request * @param Response $response * @param array $args * * @throws NotFoundException If role is not found * @throws ForbiddenException If user is not authorized to access page */ public function getPermissions(Request $request, Response $response, $args) { $role = $this->getRoleFromParams($args); // If the role no longer exists, forward to main role listing page if (!$role) { throw new NotFoundException(); } // GET parameters $params = $request->getQueryParams(); /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */ $authorizer = $this->ci->authorizer; /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */ $currentUser = $this->ci->currentUser; // Access-controlled page if (!$authorizer->checkAccess($currentUser, 'view_role_field', [ 'role' => $role, 'property' => 'permissions', ])) { throw new ForbiddenException(); } /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */ $classMapper = $this->ci->classMapper; $sprunje = $classMapper->createInstance('permission_sprunje', $classMapper, $params); $sprunje->extendQuery(function ($query) use ($role) { return $query->forRole($role->id); }); // Be careful how you consume this data - it has not been escaped and contains untrusted user-supplied content. // For example, if you plan to insert it into an HTML DOM, you must escape it on the client side (or use client-side templating). return $sprunje->toResponse($response); } /** * Returns users associated with a single role. * * This page requires authentication. * * Request type: GET * * @param Request $request * @param Response $response * @param array $args * * @throws NotFoundException If role is not found * @throws ForbiddenException If user is not authorized to access page */ public function getUsers(Request $request, Response $response, $args) { $role = $this->getRoleFromParams($args); // If the role doesn't exist, return 404 if (!$role) { throw new NotFoundException(); } /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */ $classMapper = $this->ci->classMapper; // GET parameters $params = $request->getQueryParams(); /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */ $authorizer = $this->ci->authorizer; /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */ $currentUser = $this->ci->currentUser; // Access-controlled page if (!$authorizer->checkAccess($currentUser, 'view_role_field', [ 'role' => $role, 'property' => 'users', ])) { throw new ForbiddenException(); } $sprunje = $classMapper->createInstance('user_sprunje', $classMapper, $params); $sprunje->extendQuery(function ($query) use ($role) { return $query->forRole($role->id); }); // Be careful how you consume this data - it has not been escaped and contains untrusted user-supplied content. // For example, if you plan to insert it into an HTML DOM, you must escape it on the client side (or use client-side templating). return $sprunje->toResponse($response); } /** * Renders a page displaying a role's information, in read-only mode. * * This checks that the currently logged-in user has permission to view the requested role's info. * It checks each field individually, showing only those that you have permission to view. * This will also try to show buttons for deleting and editing the role. * This page requires authentication. * * Request type: GET * * @param Request $request * @param Response $response * @param array $args * * @throws ForbiddenException If user is not authorized to access page */ public function pageInfo(Request $request, Response $response, $args) { $role = $this->getRoleFromParams($args); // If the role no longer exists, forward to main role listing page if (!$role) { throw new NotFoundException(); } /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */ $authorizer = $this->ci->authorizer; /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */ $currentUser = $this->ci->currentUser; // Access-controlled page if (!$authorizer->checkAccess($currentUser, 'uri_role', [ 'role' => $role, ])) { throw new ForbiddenException(); } // Determine fields that currentUser is authorized to view $fieldNames = ['name', 'slug', 'description']; // Generate form $fields = [ 'hidden' => [], ]; foreach ($fieldNames as $field) { if (!$authorizer->checkAccess($currentUser, 'view_role_field', [ 'role' => $role, 'property' => $field, ])) { $fields['hidden'][] = $field; } } // Determine buttons to display $editButtons = [ 'hidden' => [], ]; if (!$authorizer->checkAccess($currentUser, 'update_role_field', [ 'role' => $role, 'fields' => ['name', 'slug', 'description'], ])) { $editButtons['hidden'][] = 'edit'; } if (!$authorizer->checkAccess($currentUser, 'delete_role', [ 'role' => $role, ])) { $editButtons['hidden'][] = 'delete'; } return $this->ci->view->render($response, 'pages/role.html.twig', [ 'role' => $role, 'fields' => $fields, 'tools' => $editButtons, 'delete_redirect' => $this->ci->router->pathFor('uri_roles'), ]); } /** * Renders the role listing page. * * This page renders a table of roles, with dropdown menus for admin actions for each role. * Actions typically include: edit role, delete role. * This page requires authentication. * * Request type: GET * * @param Request $request * @param Response $response * @param array $args * * @throws ForbiddenException If user is not authorized to access page */ public function pageList(Request $request, Response $response, $args) { /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */ $authorizer = $this->ci->authorizer; /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */ $currentUser = $this->ci->currentUser; // Access-controlled page if (!$authorizer->checkAccess($currentUser, 'uri_roles')) { throw new ForbiddenException(); } return $this->ci->view->render($response, 'pages/roles.html.twig'); } /** * Processes the request to update an existing role's details. * * Processes the request from the role update form, checking that: * 1. The role name/slug are not already in use; * 2. The user has the necessary permissions to update the posted field(s); * 3. The submitted data is valid. * This route requires authentication (and should generally be limited to admins or the root user). * * Request type: PUT * * @see getModalRoleEdit * * @param Request $request * @param Response $response * @param array $args * * @throws NotFoundException If role is not found * @throws ForbiddenException If user is not authorized to access page */ public function updateInfo(Request $request, Response $response, $args) { // Get the role based on slug in the URL $role = $this->getRoleFromParams($args); if (!$role) { throw new NotFoundException(); } /** @var \UserFrosting\Support\Repository\Repository $config */ $config = $this->ci->config; // Get PUT parameters: (name, slug, description) $params = $request->getParsedBody(); /** @var \UserFrosting\I18n\Translator $translator */ $ms = $this->ci->alerts; // Load the request schema $schema = new RequestSchema('schema://requests/role/edit-info.yaml'); // Whitelist and set parameter defaults $transformer = new RequestDataTransformer($schema); $data = $transformer->transform($params); $error = false; // Validate request data $validator = new ServerSideValidator($schema, $this->ci->translator); if (!$validator->validate($data)) { $ms->addValidationErrors($validator); $error = true; } // Determine targeted fields $fieldNames = []; foreach ($data as $name => $value) { $fieldNames[] = $name; } /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */ $authorizer = $this->ci->authorizer; /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */ $currentUser = $this->ci->currentUser; // Access-controlled resource - check that currentUser has permission to edit submitted fields for this role if (!$authorizer->checkAccess($currentUser, 'update_role_field', [ 'role' => $role, 'fields' => array_values(array_unique($fieldNames)), ])) { throw new ForbiddenException(); } /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */ $classMapper = $this->ci->classMapper; // Check if name or slug already exists if ( isset($data['name']) && $data['name'] != $role->name && $classMapper->getClassMapping('role')::where('name', $data['name'])->first() ) { $ms->addMessageTranslated('danger', 'ROLE.NAME_IN_USE', $data); $error = true; } if ( isset($data['slug']) && $data['slug'] != $role->slug && $classMapper->getClassMapping('role')::where('slug', $data['slug'])->first() ) { $ms->addMessageTranslated('danger', 'SLUG_IN_USE', $data); $error = true; } if ($error) { return $response->withJson([], 400); } // Begin transaction - DB will be rolled back if an exception occurs Capsule::transaction(function () use ($data, $role, $currentUser) { // Update the role and generate success messages foreach ($data as $name => $value) { if ($value != $role->$name) { $role->$name = $value; } } $role->save(); // Create activity record $this->ci->userActivityLogger->info("User {$currentUser->user_name} updated details for role {$role->name}.", [ 'type' => 'role_update_info', 'user_id' => $currentUser->id, ]); }); $ms->addMessageTranslated('success', 'ROLE.UPDATED', [ 'name' => $role->name, ]); return $response->withJson([], 200); } /** * Processes the request to update a specific field for an existing role, including permissions. * * Processes the request from the role update form, checking that: * 1. The logged-in user has the necessary permissions to update the putted field(s); * 2. The submitted data is valid. * This route requires authentication. * * Request type: PUT * * @param Request $request * @param Response $response * @param array $args * * @throws NotFoundException If role is not found * @throws ForbiddenException If user is not authorized to access page * @throws BadRequestException */ public function updateField(Request $request, Response $response, $args) { // Get the username from the URL $role = $this->getRoleFromParams($args); if (!$role) { throw new NotFoundException(); } // Get key->value pair from URL and request body $fieldName = $args['field']; /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */ $authorizer = $this->ci->authorizer; /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */ $currentUser = $this->ci->currentUser; // Access-controlled resource - check that currentUser has permission to edit the specified field for this user if (!$authorizer->checkAccess($currentUser, 'update_role_field', [ 'role' => $role, 'fields' => [$fieldName], ])) { throw new ForbiddenException(); } /** @var \UserFrosting\Support\Repository\Repository $config */ $config = $this->ci->config; // Get PUT parameters: value $put = $request->getParsedBody(); if (!isset($put['value'])) { throw new BadRequestException(); } $params = [ $fieldName => $put['value'], ]; // Validate key -> value pair // Load the request schema $schema = new RequestSchema('schema://requests/role/edit-field.yaml'); $schema->set('password.validators.length.min', $config['site.password.length.min']); $schema->set('password.validators.length.max', $config['site.password.length.max']); // Whitelist and set parameter defaults $transformer = new RequestDataTransformer($schema); $data = $transformer->transform($params); // Validate, and throw exception on validation errors. $validator = new ServerSideValidator($schema, $this->ci->translator); if (!$validator->validate($data)) { // TODO: encapsulate the communication of error messages from ServerSideValidator to the BadRequestException $e = new BadRequestException(); foreach ($validator->errors() as $idx => $field) { foreach ($field as $eidx => $error) { $e->addUserMessage($error); } } throw $e; } // Get validated and transformed value $fieldValue = $data[$fieldName]; /** @var \UserFrosting\I18n\Translator $translator */ $ms = $this->ci->alerts; // Begin transaction - DB will be rolled back if an exception occurs Capsule::transaction(function () use ($fieldName, $fieldValue, $role, $currentUser) { if ($fieldName == 'permissions') { $newPermissions = collect($fieldValue)->pluck('permission_id')->all(); $role->permissions()->sync($newPermissions); } else { $role->$fieldName = $fieldValue; $role->save(); } // Create activity record $this->ci->userActivityLogger->info("User {$currentUser->user_name} updated property '$fieldName' for role {$role->name}.", [ 'type' => 'role_update_field', 'user_id' => $currentUser->id, ]); }); // Add success messages if ($fieldName == 'permissions') { $ms->addMessageTranslated('success', 'ROLE.PERMISSIONS_UPDATED', [ 'name' => $role->name, ]); } else { $ms->addMessageTranslated('success', 'ROLE.UPDATED', [ 'name' => $role->name, ]); } return $response->withJson([], 200); } /** * Get role instance from params. * * @param array $params * * @throws BadRequestException * * @return Role */ protected function getRoleFromParams($params) { // Load the request schema $schema = new RequestSchema('schema://requests/role/get-by-slug.yaml'); // Whitelist and set parameter defaults $transformer = new RequestDataTransformer($schema); $data = $transformer->transform($params); // Validate, and throw exception on validation errors. $validator = new ServerSideValidator($schema, $this->ci->translator); if (!$validator->validate($data)) { // TODO: encapsulate the communication of error messages from ServerSideValidator to the BadRequestException $e = new BadRequestException(); foreach ($validator->errors() as $idx => $field) { foreach ($field as $eidx => $error) { $e->addUserMessage($error); } } throw $e; } /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */ $classMapper = $this->ci->classMapper; // Get the role $role = $classMapper->getClassMapping('role')::where('slug', $data['slug']) ->first(); return $role; } }
{ "content_hash": "31d6e2ba553e2304f14edd77475e8a9e", "timestamp": "", "source": "github", "line_count": 1053, "max_line_length": 142, "avg_line_length": 35.533713200379864, "alnum_prop": 0.5855627121361948, "repo_name": "alexweissman/UserFrosting", "id": "602789ecec6d8bb6a93214315c631ff2d12efe0d", "size": "37679", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/sprinkles/admin/src/Controller/RoleController.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "7082" }, { "name": "CSS", "bytes": "363024" }, { "name": "HTML", "bytes": "169215" }, { "name": "JavaScript", "bytes": "1544614" }, { "name": "PHP", "bytes": "446275" }, { "name": "Shell", "bytes": "1490" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "cefc54c4147ab2df0a2c6c0d58e8760b", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "c7ffb82679b42ed71425eda0ed5096461e80a67f", "size": "181", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Caryophyllaceae/Mollia/Mollia alsinifolia/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.dcm4chex.archive.web.maverick.mwl.model; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.dcm4che.data.Dataset; import org.dcm4che.data.DcmElement; import org.dcm4che.data.DcmObjectFactory; import org.dcm4che.dict.Tags; import org.dcm4chex.archive.web.maverick.BasicFormPagingModel; import org.dcm4chex.archive.web.maverick.model.PatientModel; import org.dcm4chex.archive.web.maverick.mwl.MWLConsoleCtrl; /** * @author franz.willer * * The Model for Media Creation Managment WEB interface. */ public class MWLModel extends BasicFormPagingModel { /** The session attribute name to store the model in http session. */ public static final String MWLMODEL_ATTR_NAME = "mwlModel"; /** Errorcode: unsupported action */ public static final String ERROR_UNSUPPORTED_ACTION = "UNSUPPORTED_ACTION"; private String[] mppsIDs = null; /** Holds list of MWLEntries */ private Map mwlEntries = new HashMap(); private MWLFilter mwlFilter; /** True if mwlScpAET is 'local' to allow deletion */ private boolean isLocal = false; /** Comparator to sort list of SPS datasets. */ private Comparator comparator = new SpsDSComparator(); // hold patient infos for merge (same patients/stickyPatients model structure as FolderForm) private List patients = new ArrayList(); private final Set stickyPatients = new HashSet(); /** Holds reason of merge. */ private String mergeReason=null; /** Used to preselect dominant patient in patient_merge view */ private PatientModel dominantPat; /** * Creates the model. * <p> * Creates the filter instance for this model. */ private MWLModel( HttpServletRequest request ) { super(request); getFilter(); } /** * Get the model for an http request. * <p> * Look in the session for an associated model via <code>MWLMODEL_ATTR_NAME</code><br> * If there is no model stored in session (first request) a new model is created and stored in session. * * @param request A http request. * * @return The model for given request. */ public static final MWLModel getModel( HttpServletRequest request ) { MWLModel model = (MWLModel) request.getSession().getAttribute(MWLMODEL_ATTR_NAME); if (model == null) { model = new MWLModel(request); request.getSession().setAttribute(MWLMODEL_ATTR_NAME, model); model.setErrorCode( NO_ERROR ); //reset error code model.filterWorkList( true ); } return model; } public String getModelName() { return "MWL"; } /** * Returns the Filter of this model. * * @return MWLFilter instance that hold filter criteria values. */ public MWLFilter getFilter() { if ( mwlFilter == null ) { mwlFilter = new MWLFilter(); } return mwlFilter; } /** * Return a list of MWLEntries for display. * * @return Returns the mwlEntries. */ public Collection getMwlEntries() { return mwlEntries.values(); } public MWLEntry getMWLEntry(String spsID) { return (MWLEntry) mwlEntries.get(spsID); } /** * Returns true if the MwlScpAET is 'local'. * <p> * <DL> * <DT>If it is local:</DT> * <DD> 1) Entries can be deleted. (shows a button in view)</DD> * <DD> 2) The query for the working list is done directly without a CFIND.</DD> * </DL> * @return Returns the isLocal. */ public boolean isLocal() { return isLocal; } /** * Returns > 0 if MWL console is in 'link' mode. * <p> * This mode is set if mwl_console.m is called with action=link. * <p> * The value is euivalent to the number of selected MPPS (size of mppsIDs). * * @return Returns the linkMode. */ public int getLinkMode() { return mppsIDs == null ? 0 : mppsIDs.length; } /** * @return Returns the mppsIDs. */ public String[] getMppsIDs() { return mppsIDs; } /** * @param mppsIDs The mppsIDs to set. */ public void setMppsIDs(String[] mppsIDs) { this.mppsIDs = mppsIDs; } public void setPatMergeAttributes(Map map) { patients.clear(); stickyPatients.clear(); if ( map != null ) { dominantPat = new PatientModel( (Dataset) map.get("dominant") ); stickyPatients.add(new Long(dominantPat.getPk())); patients.add(dominantPat); Dataset[] dsa = (Dataset[]) map.get("priorPats"); PatientModel pat; for ( int i = 0 ; i < dsa.length ; i++ ) { pat = new PatientModel( dsa[i]); stickyPatients.add(new Long(pat.getPk())); patients.add(pat); } mergeReason="Linking MWL to MPPS requires patient merge!"; } else { dominantPat = null; mergeReason = null; } } public final List getPatients() { return patients; } public final Set getStickyPatients() { return stickyPatients; } public String getMergeReason() { return mergeReason; } /** * @return Returns the dominant patient for necessary merge. */ public PatientModel getMergeDominant() { return dominantPat; } /** returns the name of the view used after merge is done. (have to be configured in maverick.xml!) */ public String getMergeViewName() { return "mpps_link"; } /** * Update the list of MWLEntries for the view. * <p> * The query use the search criteria values from the filter and use offset and limit for paging. * <p> * if <code>newSearch is true</code> will reset paging (set <code>offset</code> to 0!) * @param newSearch */ public void filterWorkList(boolean newSearch) { if ( newSearch ) setOffset(0); Dataset searchDS = getSearchDS( mwlFilter ); isLocal = MWLConsoleCtrl.getMwlScuDelegate().isLocal(); List l = MWLConsoleCtrl.getMwlScuDelegate().findMWLEntries( searchDS ); Collections.sort( l, comparator ); int total = l.size(); int offset = getOffset(); int limit = getLimit(); int end; if ( offset >= total ) { offset = 0; end = limit < total ? limit : total; } else { end = offset + limit; if ( end > total ) end = total; } Dataset ds; mwlEntries.clear(); int countNull = 0; MWLEntry entry; for ( int i = offset ; i < end ; i++ ){ ds = (Dataset) l.get( i ); if ( ds != null ) { entry = new MWLEntry( ds ); mwlEntries.put( entry.getSpsID(), entry ); } else { countNull++; } } setTotal(total - countNull); // the real total (without null entries!) } /** * Returns the query Dataset with search criteria values from filter argument. * <p> * The Dataset contains all fields that should be in the result; * the 'merging' fields will be set to the values from the filter. * * @param mwlFilter2 The filter with search criteria values. * * @return The Dataset that can be used for query. */ private Dataset getSearchDS(MWLFilter filter) { Dataset ds = DcmObjectFactory.getInstance().newDataset(); //requested procedure ds.putSH( Tags.RequestedProcedureID ); ds.putUI( Tags.StudyInstanceUID ); //imaging service request ds.putSH( Tags.AccessionNumber, mwlFilter.getAccessionNumber() ); ds.putLT( Tags.ImagingServiceRequestComments ); ds.putPN( Tags.RequestingPhysician ); ds.putPN( Tags.ReferringPhysicianName ); ds.putLO( Tags.PlacerOrderNumber ); ds.putLO( Tags.FillerOrderNumber ); //Visit Identification ds.putLO( Tags.AdmissionID ); //Patient Identification String patientName = mwlFilter.getPatientName(); if ( patientName != null && patientName.length() > 0 && patientName.indexOf('*') == -1 && patientName.indexOf('?') == -1) patientName+="*"; ds.putPN( Tags.PatientName, patientName ); ds.putLO( Tags.PatientID); //Patient demographic ds.putDA( Tags.PatientBirthDate ); ds.putCS( Tags.PatientSex ); //Sched. procedure step seq DcmElement elem = ds.putSQ( Tags.SPSSeq ); Dataset ds1 = elem.addNewItem(); ds1.putAE( Tags.ScheduledStationAET, filter.getStationAET() ); ds1.putSH( Tags.SPSID ); ds1.putCS( Tags.Modality, filter.getModality() ); ds1.putPN( Tags.ScheduledPerformingPhysicianName ); if ( filter.getStartDate() != null || filter.getEndDate() != null ) { Date startDate = null, endDate = null; if ( filter.startDateAsLong() != null ) startDate = new Date ( filter.startDateAsLong().longValue() ); if ( filter.endDateAsLong() != null ) endDate = new Date ( filter.endDateAsLong().longValue() ); ds1.putDA( Tags.SPSStartDate, startDate, endDate ); ds1.putTM( Tags.SPSStartTime, startDate, endDate ); } else { ds1.putDA( Tags.SPSStartDate ); ds1.putTM( Tags.SPSStartTime ); } ds1.putSH( Tags.ScheduledStationName ); //sched. protocol code seq; DcmElement spcs = ds1.putSQ( Tags.ScheduledProtocolCodeSeq ); Dataset dsSpcs = spcs.addNewItem(); dsSpcs.putSH( Tags.CodeValue ); dsSpcs.putLO( Tags.CodeMeaning ); dsSpcs.putSH( Tags.CodingSchemeDesignator ); // or ds1.putLO( Tags.SPSDescription ); //Req. procedure code seq DcmElement rpcs = ds.putSQ( Tags.RequestedProcedureCodeSeq ); Dataset dsRpcs = rpcs.addNewItem(); dsRpcs.putSH( Tags.CodeValue ); dsRpcs.putLO( Tags.CodeMeaning ); dsRpcs.putSH( Tags.CodingSchemeDesignator ); // or ds.putLO( Tags.RequestedProcedureDescription ); return ds; } /* (non-Javadoc) * @see org.dcm4chex.archive.web.maverick.BasicFormPagingModel#gotoCurrentPage() */ public void gotoCurrentPage() { filterWorkList( false ); } /** * Inner class that compares two datasets for sorting Scheduled Procedure Steps * according scheduled Procedure step start date. * * @author franz.willer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class SpsDSComparator implements Comparator { private final Date DATE_0 = new Date(0l); public SpsDSComparator() { } /** * Compares the scheduled procedure step start date and time of two Dataset objects. * <p> * USe either SPSStartDateAndTime or SPSStartDate and SPSStartTime to get the date. * <p> * Use the '0' Date (new Date(0l)) if the date is not in the Dataset. * <p> * Compares its two arguments for order. Returns a negative integer, zero, or a positive integer * as the first argument is less than, equal to, or greater than the second. * <p> * Throws an Exception if one of the arguments is null or not a Dataset object. * * @param arg0 First argument * @param arg1 Second argument * * @return <0 if arg0<arg1, 0 if equal and >0 if arg0>arg1 */ public int compare(Object arg0, Object arg1) { Dataset ds1 = (Dataset) arg0; Dataset ds2 = (Dataset) arg1; Date d1 = _getStartDateAsLong( ds1 ); return d1.compareTo( _getStartDateAsLong( ds2 ) ); } /** * @param ds1 The dataset * * @return the date of this SPS Dataset. */ private Date _getStartDateAsLong(Dataset ds) { if ( ds == null ) return DATE_0; DcmElement e = ds.get( Tags.SPSSeq ); if ( e == null ) return DATE_0; Dataset spsItem = e.getItem();//scheduled procedure step sequence item. Date d = spsItem.getDate( Tags.SPSStartDateAndTime ); if ( d == null ) { d = spsItem.getDateTime( Tags.SPSStartDate, Tags.SPSStartTime ); } if ( d == null ) d = DATE_0; return d; } } }
{ "content_hash": "4f8b5b8f37dfb59fd7728188a86cee93", "timestamp": "", "source": "github", "line_count": 384, "max_line_length": 104, "avg_line_length": 29.6953125, "alnum_prop": 0.6818381127773393, "repo_name": "medicayun/medicayundicom", "id": "43e5a70276d4dbb7812731292475dcac35dc0fbd", "size": "13279", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "dcm4jboss-all/tags/DCM4CHEE_2_9_5/dcm4jboss-web/src/java/org/dcm4chex/archive/web/maverick/mwl/model/MWLModel.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
(function () { 'use strict'; var module = angular.module('fim.base'); module.run(function (plugins, $q, $rootScope, $templateCache, $translate, nxt) { var plugin = plugins.get('transaction'); /** * Arguments can be given either as a literal (string, boolean, number), * as a Promise, as a Function that returns a literal (meaning not a Promise) * or a function that returns a Promise. */ function evalSetFieldData(target, name, value, $scope) { if (typeof value == 'function') { value = value.call(target); } if (value && typeof value == 'object' && typeof value.then == 'function') { $q.when(value).then(function (_val) { $scope.$evalAsync(function () { target[name] = value; }) }); } else { target[name] = value; } } /** * Base field from which all other fields are derived. * The opts for this field type apply for all other fields. * * Available options: * * - label (Literal||Function||Promise) * The label above the field * * - value (Literal||Function||Promise) * The field value * * - required (Boolean||Function||Promise) * If the field is required to have a value and be "valid" * * - readonly (Boolean||Function||Promise) * The field is read only * * - validate (Function(text)) * Function that validates the field value, must throw a String * which will become the error message. * * function validate (text, fields) { * if (text != 'a') { * throw "Value must be 'a'"; * } * // to access another field refer to 'fields' which holds all other field * // value keyed by field name * if (fields.password.value != text) { * throw "Value is not equal to other field" * } * } * * - watch (String space delimited) * Name of other field(s) to observe, runs the validate function when a change to * one of those fields is detected. * * Usage: "watch: 'passwordConfirm userName'" * Will watch both the passwordConfirm and userName fields and call validate when they change. * Validate is always called when the field itself changes . * */ function CreateStandardField(fieldName, opts) { var field = { name: fieldName }; evalSetFieldData(field, 'label', opts.label, opts.$scope||$rootScope); evalSetFieldData(field, 'value', opts.value, opts.$scope||$rootScope); evalSetFieldData(field, 'required', opts.required, opts.$scope||$rootScope); evalSetFieldData(field, 'readonly', opts.readonly, opts.$scope||$rootScope); evalSetFieldData(field, 'hide', opts.hide, opts.$scope||$rootScope); evalSetFieldData(field, 'placeHolder', opts.placeHolder, opts.$scope||$rootScope); if (opts.validate) { if (typeof opts.validate != 'function') { throw new Error('validate option is not a function'); } field.validate = function (text, items) { this.errorMsg = null; try { // only prepare and pass 'fields' arg if validate has 2 or more formal arguments. if (opts.validate.length > 1) { var fields = {}; items.fields.forEach(function (f) { fields[f.name] = f }); opts.validate.call(this, text, fields); } else { opts.validate.call(this, text); } return true; } catch (ex) { if (typeof ex != 'string') throw ex; this.errorMsg = ex; } } if (angular.isString(opts.watch)) { field.watch = ['f.value'].concat( opts.watch.trim().split(/\s+/).map( function (n) { return (n == fieldName) ? '' : 'items.fields_map.'+n+'.value' } ) ); } else { field.watch = 'f.value'; } console.log('Field watch value: %s', field.watch); } field.onchange = function (items) { if (typeof opts.onchange == 'function') { // only prepare and pass 'fields' arg if onchange has a formal argument. if (opts.onchange.length > 0) { var fields = {}; items.fields.forEach(function (f) { fields[f.name] = f }); opts.onchange.call(this, fields); } else { opts.onchange.call(this); } } } field.changed = function (no_validate) { if (!no_validate) { this.validate(this.value, this.getScopeItems()); } this.onchange(this.getScopeItems()); } field.initialize = function (items) { if (typeof opts.initialize == 'function') { // only prepare and pass 'fields' arg if onchange has a formal argument. if (opts.initialize.length > 0) { var fields = {}; items.fields.forEach(function (f) { fields[f.name] = f }); opts.initialize.call(this, fields); } else { opts.initialize.call(this); } } } return field; } /** * Creates a static text field * @inherits from CreateStandardField * * Usage: * plugin.fields('static').create('nameOfField') * * The value is treated as HTML. */ plugin.addField('static', { create: function (fieldName, opts) { var field = CreateStandardField(fieldName, opts); field.type = 'static'; return field; } }); /** * Creates an input type=text * @inherits from CreateStandardField * * Usage: * plugin.fields('text').create('nameOfField', {}) */ plugin.addField('text', { create: function (fieldName, opts) { var field = CreateStandardField(fieldName, opts); field.type = 'input'; return field; } }); /** * Creates an input type=text money * @inherits from CreateStandardField * * Usage: * plugin.fields('money').create('nameOfField', {}) * * Required Arguments: * * - precision (Number) */ plugin.addField('money', { create: function (fieldName, opts) { var custom_validate = opts.validate; opts.validate = function (text) { if (typeof custom_validate == 'function') { custom_validate.call(this,text); } if (text) { var regexp = this.precision == 0 ? new RegExp('^\\d+$') : new RegExp('^\\d+(\\.)?(\\d{1,'+this.precision+'})?$'); if (!regexp.test(text)) { if (this.precision == 0 && new RegExp('\\.').test(text)) throw 'No decimals places allowed'; else if (new RegExp('^\\d+\\.\\d{9,}$').test(text)) throw 'Only '+this.precision+' decimals allowed'; else throw 'Allowed format is 12.345'; } } } var field = CreateStandardField(fieldName, opts); field.type = 'text'; field.precision = angular.isDefined(opts.precision) ? parseInt(opts.precision) : 0; return field; } }); /** * Creates a textarea * @inherits from CreateStandardField * * Usage: * plugin.fields('textarea').create('nameOfField', {}) */ plugin.addField('textarea', { create: function (fieldName, opts) { var field = CreateStandardField(fieldName, opts); field.type = 'textarea-v2'; return field; } }); /** * Creates an input type=text * @inherits from CreateStandardField * * Usage: * plugin.fields('password').create('nameOfField', {}) */ plugin.addField('password', { create: function (fieldName, opts) { var field = CreateStandardField(fieldName, opts); field.type = 'input'; field.inputType = 'password'; return field; } }); /** * Creates an input type=radio * @inherits from CreateStandardField * * Usage: * plugin.fields('radio').create('nameOfField', { * options: Array[ {label: String, value: Literal} ] * }) */ plugin.addField('radio', { create: function (fieldName, opts) { var field = CreateStandardField(fieldName, opts); field.type = 'radio-v2'; evalSetFieldData(field, 'options', opts.options, opts.$scope||$rootScope); return field; } }); /** * Creates an input type=checkbox * @inherits from CreateStandardField * Value is either true or valse * * Usage: * plugin.fields('checkbox').create('nameOfField') */ plugin.addField('checkbox', { create: function (fieldName, opts) { var field = CreateStandardField(fieldName, opts); field.type = 'checkbox'; field.inline_label = field.label; delete field.label; return field; } }); /** * Creates a hidden field * @inherits from CreateStandardField * * Usage: * plugin.fields('hidden').create('nameOfField') */ plugin.addField('hidden', { create: function (fieldName, opts) { var field = CreateStandardField(fieldName, opts); field.type = 'hidden'; field.hide = true; return field; } }); /** * Creates a standard autocomplete field. * @inherits from CreateStandardField * * Usage: * plugins.fields('autocomplete').create('nameOfField', { * template: [ * '<a class="monospace">', * '<span class="font-bold" ng-bind="match.model.label"></span>&nbsp;&nbsp;', * '<span class="pull-right" ng-bind="match.model.value"></span>', * '</a>' * ].join(''), * templateURL: String||Function||Promise, * getResults: Function(text) { * @returns Promise(array) * } * }); * * Other arguments: * * - templateURL (String||Function||Promise) * URL matching either a real file url or an entry in $templateCache * * - template (String) * Alternative to templateURL where you provide the template content * as string (HTML). The ID used to store in $templateCache is created * from the field name. * * - getResults (Function(text)) * Function that receives the input element value * * - wait (Literal) * Minimal wait time after last character typed before typeahead kicks-in */ plugin.addField('autocomplete', { create: function (fieldName, opts) { var field = CreateStandardField(fieldName, opts); field.type = 'autocomplete'; evalSetFieldData(field, 'templateURL', opts.templateURL, opts.$scope||$rootScope); if (opts.template) { field.templateURL = fieldName+'-auto-generated-template.html'; $templateCache.put(field.templateURL, opts.template); } if (typeof opts.getResults != 'function') { throw new Error('getResults is missing or not a function'); } field.wait = opts.wait||0; field.getResults = opts.getResults; return field; } }); /** * Generic account field. * @inherits from CreateStandardField * * Required arguments: * * - api (either nxt.nxt() or nxt.fim()) * * Optionsl arguuments: * * - accountColorId (String) * Limits results to accounts from the same account color */ plugin.addField('account', { create: function (name, opts) { var scope = opts.$scope||$rootScope; var format_account_label = function (data) { return ['<a href="#/accounts/',data.accountRS,'/activity/latest" target="_blank">',data.accountName||data.accountRS,'</a>'].join(''); }; var lazy_lookup_account = debounce( function (field) { scope.$evalAsync(function () { field.warnMsg = null; field.__label = ''; }); opts.api.engine.socket().callAPIFunction({ requestType: 'getAccount', account: field.value }).then( function (data) { scope.$evalAsync(function () { if (data.errorDescription=='Unknown account') { field.warnMsg = 'Account does not exist'; return; } if (!angular.isString(data.publicKey)) { field.warnMsg = 'Account has no publickey'; } field.__label = format_account_label(data); }); } ); }, 500); var field = plugin.fields('autocomplete').create(name, angular.extend(opts, { wait: 500, label: opts.label, template: [ '<a class="monospace">', '<span class="font-bold" ng-bind="match.model.label||match.model.value"></span>&nbsp;&nbsp;', '<span ng-if="match.model.label!=match.model.value" class="pull-right" ng-bind="match.model.value"></span>', '</a>' ].join(''), validate: function (text) { if (text && !opts.api.createAddress().set(text)) { throw "Invalid "+opts.api.engine.symbol+" address"; } if (text) { lazy_lookup_account(this); } }, getResults: function (query) { var deferred = $q.defer(); // if query starts with FIM- or NXT- remove that part // since the indexer does not use the FIM- or NXT- prefix query = (query||"").toLowerCase(); var regexp = opts.api.engine.type == nxt.TYPE_NXT ? (/^FIM-/) : (/^NXT-/); if (query.indexOf(regexp)==0) { query = query.replace(regexp,''); } var args = { requestType: 'searchAccountIdentifiers', query: query, firstIndex: 0, lastIndex: 15 }; if (opts.accountColorId && opts.accountColorId != '0') { args.accountColorId = opts.accountColorId; } opts.api.engine.socket().callAPIFunction(args).then( function (data) { var accounts = data.accounts||[]; if (accounts.length == 1 && accounts[0].accountEmail == accounts[0].accountRS && accounts[0].accountEmail == query) { deferred.resolve([]); } else { deferred.resolve(accounts.map( function (obj) { var v = { label: obj.accountEmail, value: obj.accountRS }; if ("FIM-"+v.label==v.value || "NXT-"+v.label==v.value) { v.label = v.value; } return v; } )); } }, deferred.reject ); return deferred.promise; } })); return field; } }); /** * Generic asset field. * @inherits from CreateStandardField * * Required arguments: * * - api (either nxt.nxt() or nxt.fim()) * * Optional arguments: * * - account (String||Function||Promise) * Limits results to assets owned by this account * * Extra methods/properties: * * - asset (Object) * Where "value" will contain the asset identtifier, the asset * property contains the full JSONData.asset response. */ plugin.addField('asset', { create: function (name, opts) { var scope = opts.$scope||$rootScope; var format_asset_label = function (data) { return [ '<a class="font-bold" href="#/assets/',opts.api.engine.symbol_lower,'/13664938383416975974/trade" target="_blank">',data.name,'</a> (', '<a href="#/accounts/',data.accountRS,'/activity/latest" target="_blank">',data.accountName||data.accountRS,'</a>)' ].join(''); }; var lazy_lookup_asset = debounce( function (field) { field.asset = null; scope.$evalAsync(function () { field.errorMsg = null; field.__label = ''; }); opts.api.engine.socket().callAPIFunction({ requestType: 'getAsset', asset: field.value }).then( function (data) { scope.$evalAsync(function () { if (data.asset == field.value) { field.asset = data; field.__label = format_asset_label(data); } else { field.errorMsg = 'Asset does not exist'; } field.changed(true); }); } ); }, 500); // load and remember all assets owned by account var account_assets_promise = null; var get_account_assets = function (account) { if (account_assets_promise) { return account_assets_promise; } var deferred = $q.defer(); opts.api.engine.socket().callAPIFunction({requestType:'getAccountAssets',account:account}).then(deferred.resolve); return account_assets_promise = deferred.promise; }; var field = plugin.fields('autocomplete').create(name, angular.extend(opts, { wait: 500, label: opts.label, template: [ '<a class="monospace">', '<span class="font-bold">{{match.model.value + "&nbsp;" + match.model.name}}</span>&nbsp;&nbsp;', '<span class="pull-right" ng-bind="match.model.accountName||match.model.accountRS"></span>', '</a>' ].join(''), validate: function (text) { if (text && !/\d+/.test) { throw "Not a valid asset identifier"; } if (text) { lazy_lookup_asset(this); } }, getResults: function (query) { var deferred = $q.defer(); var promise; if (opts.account) { promise = get_account_assets(opts.account); } else { promise = opts.api.engine.socket().callAPIFunction({ requestType: 'searchAssets', query: 'NAME:'+query+'*', firstIndex: 0, lastIndex: 15 }); } promise.then( function (data) { var assets = data.assets||data.accountAssets||[]; deferred.resolve(assets.map( function (d) { return { value: d.asset, name: d.name, accountName: d.accountName, accountRS: d.accountRS }; } )); } ); return deferred.promise; } })); return field; } }); /** * Generic alias field. * @inherits from CreateStandardField * * Required arguments: * * - api (either nxt.nxt() or nxt.fim()) * * Optional arguments: * * - account (String||Function||Promise) * Limits results to aliases owned by this account * * Extra methods/properties: * * - alias (Object) * Where "value" will contain the aliasName property, the alias * property contains the full JSONData.alias response. * */ plugin.addField('alias', { create: function (name, opts) { var scope = opts.$scope||$rootScope; var format_alias_label = function (data) { return ['<a href="#/accounts/',data.accountRS,'/activity/latest" target="_blank">',data.accountName||data.accountRS,'</a>'].join('') }; var lazy_lookup_alias = debounce( function (field) { field.alias = null; scope.$evalAsync(function () { field.warnMsg = null; field.__label = ''; }); opts.api.engine.socket().callAPIFunction({ requestType: 'getAlias', aliasName: field.value }).then( function (data) { scope.$evalAsync(function () { if (angular.isString(data.alias)) { field.alias = data; field.warnMsg = 'Alias exists'; field.__label = format_alias_label(data); } else { field.warnMsg = 'Alias available'; } }); } ); }, 500); var field = plugin.fields('autocomplete').create(name, angular.extend(opts, { wait: 500, label: opts.label, template: [ '<a class="monospace">', '<span class="font-bold">{{match.model.aliasName}}</span>&nbsp;&nbsp;', '<span class="pull-right" ng-bind="match.model.aliasURI"></span>', '</a>' ].join(''), validate: function (text) { if (text) { lazy_lookup_alias(this); } }, getResults: function (query) { var deferred = $q.defer(); if (query.length < 2) { deferred.resolve(null); } else { var args = { requestType: 'getAliasesLike', aliasPrefix: query, firstIndex: 0, lastIndex: 15 }; if (opts.account) { args.account = opts.account; } opts.api.engine.socket().callAPIFunction(args).then( function (data) { var aliases = data.aliases||[]; deferred.resolve(aliases.map( function (d) { d.value = d.aliasName; return d; } )); } ); } return deferred.promise; } })); return field; } }); /** * Generic namespaced-alias field. * @inherits from CreateStandardField * * Required arguments: * * - api (either nxt.nxt() or nxt.fim()) * * - account (String||Function||Promise) * Default is current logged in account * * Extra methods/properties: * * - alias (Object) * Where "value" will contain the aliasName property, the alias * property contains the full JSONData.alias response. * */ plugin.addField('namespaced-alias', { create: function (name, opts) { opts.account = opts.account || $rootScope.currentAccount.id_rs; var api = nxt.get(opts.account); if (api.engine.type != nxt.TYPE_FIM) { throw new Error('Namespaced aliases not supported on platform: '+api.engine.symbol); } var scope = opts.$scope||$rootScope; var lazy_lookup_alias = debounce( function (field) { field.alias = null; field.onchange(field.getScopeItems()); scope.$evalAsync(function () { field.warnMsg = null; field.__label = ''; }); if (field.value) { api.engine.socket().callAPIFunction({ requestType: 'getNamespacedAlias', aliasName: field.value, account: opts.account }).then( function (data) { scope.$evalAsync(function () { if (angular.isString(data.alias)) { field.alias = data; field.warnMsg = 'Last changed '+nxt.util.formatTimestamp(data.timestamp); field.onchange(field.getScopeItems()); } else { field.warnMsg = 'Unused'; } }); } ); } }, 500); var field = plugin.fields('autocomplete').create(name, angular.extend(opts, { wait: 500, label: opts.label, template: [ '<a class="monospace">', '<span class="font-bold">{{match.model.aliasName}}</span>&nbsp;&nbsp;', '<span class="pull-right" ng-bind="match.model.aliasURI"></span>', '</a>' ].join(''), validate: function (text) { lazy_lookup_alias(this); }, getResults: function (query) { var deferred = $q.defer(); var args = { requestType: 'getNamespacedAliases', account: opts.account, filter: query, firstIndex: 0, lastIndex: 15 }; api.engine.socket().callAPIFunction(args).then( function (data) { var aliases = data.aliases||[]; deferred.resolve(aliases.map( function (d) { d.value = d.aliasName; return d; } )); } ); return deferred.promise; } })); return field; } }); /** * Generic account-color field. * @inherits from CreateStandardField * * Required arguments: * * - api (either nxt.nxt() or nxt.fim()) * * - account (String||Function||Promise) * Default is current logged in account * * Extra methods/properties: * * - accountColor (Object) * Where "value" will contain the accountColorId property, the accountColor * property contains the full JSONData.accountColor response. * */ plugin.addField('account-color', { create: function (name, opts) { opts = opts||{}; opts.account = opts.account || $rootScope.currentAccount.id_rs; var api = nxt.get(opts.account); if (api.engine.type != nxt.TYPE_FIM) { throw new Error('Account colors not supported on platform: '+api.engine.symbol); } var scope = opts.$scope||$rootScope; var lazy_lookup_color = function (field) { field.accountColor = null; field.onchange(field.getScopeItems()); scope.$evalAsync(function () { field.errorMsg = null; field.__label = ''; }); if (field.value) { api.engine.socket().callAPIFunction({ requestType: 'accountColorGet', accountColorId: field.value }).then( function (data) { scope.$evalAsync(function () { if (data.errorDescription != 'Unknown accountColor') { field.accountColor = data; field.onchange(field.getScopeItems()); field.__label = data.accountColorName; } else { field.errorMsg = 'Not found'; } }); } ); } }.debounce(500); var field = plugin.fields('autocomplete').create(name, angular.extend(opts, { wait: 500, label: opts.label, template: [ '<a class="monospace">', '<span class="font-bold">{{match.model.accountColorName}}</span>&nbsp;&nbsp;', '<span class="pull-right" ng-bind="match.model.accountColorId"></span>', '</a>' ].join(''), validate: function (text) { lazy_lookup_color(this); }, getResults: function (query) { var deferred = $q.defer(); var args = { requestType: 'accountColorSearch', account: opts.account, name: query, firstIndex: 0, lastIndex: 15, includeAccountInfo: false, includeDescription: false }; api.engine.socket().callAPIFunction(args).then( function (data) { var accountColors = data.accountColors||[]; deferred.resolve(accountColors.map( function (d) { d.value = d.accountColorId; return d; } )); } ); return deferred.promise; } })); return field; } }); }); })();
{ "content_hash": "c68a97fa8cf308052c3facb39f52bb51", "timestamp": "", "source": "github", "line_count": 858, "max_line_length": 145, "avg_line_length": 32.137529137529135, "alnum_prop": 0.5269456734605062, "repo_name": "fimkrypto/mofowallet", "id": "db19fc45be4eb9e77ac6931d989e710702800165", "size": "28743", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/plugins/transaction/fields/standard-field-types.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "24139" }, { "name": "CSS", "bytes": "92207" }, { "name": "HTML", "bytes": "351218" }, { "name": "JavaScript", "bytes": "1259188" }, { "name": "Ruby", "bytes": "1867" }, { "name": "Shell", "bytes": "17908" } ], "symlink_target": "" }
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved using System; using System.Collections.ObjectModel; using System.Runtime.InteropServices; using System.Text; #if !WINRT_NOT_PRESENT using Windows.Data.Xml.Dom; #endif namespace NotificationsExtensions { internal sealed class NotificationContentText : INotificationContentText { internal NotificationContentText() { } public string Text { get { return m_Text; } set { m_Text = value; } } public string Lang { get { return m_Lang; } set { m_Lang = value; } } private string m_Text; private string m_Lang; } internal sealed class NotificationContentImage : INotificationContentImage { internal NotificationContentImage() { } public string Src { get { return m_Src; } set { m_Src = value; } } public string Alt { get { return m_Alt; } set { m_Alt = value; } } public bool AddImageQuery { get { if (m_AddImageQueryNullable == null || m_AddImageQueryNullable.Value == false) { return false; } else { return true; } } set { m_AddImageQueryNullable = value; } } public bool? AddImageQueryNullable { get { return m_AddImageQueryNullable; } set { m_AddImageQueryNullable = value; } } private string m_Src; private string m_Alt; private bool? m_AddImageQueryNullable; } internal static class Util { public const int NOTIFICATION_CONTENT_VERSION = 1; public static string HttpEncode(string value) { return value.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;").Replace("'", "&apos;"); } } /// <summary> /// Base class for the notification content creation helper classes. /// </summary> #if !WINRT_NOT_PRESENT internal abstract class NotificationBase #else abstract partial class NotificationBase #endif { protected NotificationBase(string templateName, int imageCount, int textCount) { m_TemplateName = templateName; m_Images = new NotificationContentImage[imageCount]; for (int i = 0; i < m_Images.Length; i++) { m_Images[i] = new NotificationContentImage(); } m_TextFields = new INotificationContentText[textCount]; for (int i = 0; i < m_TextFields.Length; i++) { m_TextFields[i] = new NotificationContentText(); } } public bool StrictValidation { get { return m_StrictValidation; } set { m_StrictValidation = value; } } public abstract string GetContent(); public override string ToString() { return GetContent(); } #if !WINRT_NOT_PRESENT public XmlDocument GetXml() { XmlDocument xml = new XmlDocument(); xml.LoadXml(GetContent()); return xml; } #endif /// <summary> /// Retrieves the list of images that can be manipulated on the notification content. /// </summary> public INotificationContentImage[] Images { get { return m_Images; } } /// <summary> /// Retrieves the list of text fields that can be manipulated on the notification content. /// </summary> public INotificationContentText[] TextFields { get { return m_TextFields; } } /// <summary> /// The base Uri path that should be used for all image references in the notification. /// </summary> public string BaseUri { get { return m_BaseUri; } set { if (this.StrictValidation && !String.IsNullOrEmpty(value)) { Uri uri; try { uri = new Uri(value); } catch (Exception e) { throw new ArgumentException("Invalid URI. Use a valid URI or turn off StrictValidation", e); } if (!(uri.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase) || uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase) || uri.Scheme.Equals("ms-appx", StringComparison.OrdinalIgnoreCase) || (uri.Scheme.Equals("ms-appdata", StringComparison.OrdinalIgnoreCase) && (String.IsNullOrEmpty(uri.Authority)) // check to make sure the Uri isn't ms-appdata://foo/local && (uri.AbsolutePath.StartsWith("/local/") || uri.AbsolutePath.StartsWith("local/"))))) // both ms-appdata:local/ and ms-appdata:/local/ are valid { throw new ArgumentException("The BaseUri must begin with http://, https://, ms-appx:///, or ms-appdata:///local/.", "value"); } } m_BaseUri = value; } } public string Lang { get { return m_Lang; } set { m_Lang = value; } } public bool AddImageQuery { get { if (m_AddImageQueryNullable == null || m_AddImageQueryNullable.Value == false) { return false; } else { return true; } } set { m_AddImageQueryNullable = value; } } public bool? AddImageQueryNullable { get { return m_AddImageQueryNullable; } set { m_AddImageQueryNullable = value; } } protected string SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) { globalLang = (globalLang != null) ? globalLang : String.Empty; globalBaseUri = String.IsNullOrWhiteSpace(globalBaseUri) ? null : globalBaseUri; StringBuilder builder = new StringBuilder(String.Empty); for (int i = 0; i < m_Images.Length; i++) { if (!String.IsNullOrEmpty(m_Images[i].Src)) { string escapedSrc = Util.HttpEncode(m_Images[i].Src); if (!String.IsNullOrWhiteSpace(m_Images[i].Alt)) { string escapedAlt = Util.HttpEncode(m_Images[i].Alt); if (m_Images[i].AddImageQueryNullable == null || m_Images[i].AddImageQueryNullable == globalAddImageQuery) { builder.AppendFormat("<image id='{0}' src='{1}' alt='{2}'/>", i + 1, escapedSrc, escapedAlt); } else { builder.AppendFormat("<image addImageQuery='{0}' id='{1}' src='{2}' alt='{3}'/>", m_Images[i].AddImageQuery.ToString().ToLowerInvariant(), i + 1, escapedSrc, escapedAlt); } } else { if (m_Images[i].AddImageQueryNullable == null || m_Images[i].AddImageQueryNullable == globalAddImageQuery) { builder.AppendFormat("<image id='{0}' src='{1}'/>", i + 1, escapedSrc); } else { builder.AppendFormat("<image addImageQuery='{0}' id='{1}' src='{2}'/>", m_Images[i].AddImageQuery.ToString().ToLowerInvariant(), i + 1, escapedSrc); } } } } for (int i = 0; i < m_TextFields.Length; i++) { if (!String.IsNullOrWhiteSpace(m_TextFields[i].Text)) { string escapedValue = Util.HttpEncode(m_TextFields[i].Text); if (!String.IsNullOrWhiteSpace(m_TextFields[i].Lang) && !m_TextFields[i].Lang.Equals(globalLang)) { string escapedLang = Util.HttpEncode(m_TextFields[i].Lang); builder.AppendFormat("<text id='{0}' lang='{1}'>{2}</text>", i + 1, escapedLang, escapedValue); } else { builder.AppendFormat("<text id='{0}'>{1}</text>", i + 1, escapedValue); } } } return builder.ToString(); } public string TemplateName { get { return m_TemplateName; } } private bool m_StrictValidation = true; private NotificationContentImage[] m_Images; private INotificationContentText[] m_TextFields; private string m_Lang; private string m_BaseUri; private string m_TemplateName; private bool? m_AddImageQueryNullable; } /// <summary> /// Exception returned when invalid notification content is provided. /// </summary> internal sealed class NotificationContentValidationException : COMException { public NotificationContentValidationException(string message) : base(message, unchecked((int)0x80070057)) { } } }
{ "content_hash": "710e6c7ecb44fb0e209b340b35a2f963", "timestamp": "", "source": "github", "line_count": 294, "max_line_length": 198, "avg_line_length": 34.156462585034014, "alnum_prop": 0.5064728141804421, "repo_name": "studio-nine/Nine.Application", "id": "5f591f1ef2290ddf66b2986875d6b4fb82bb2851", "size": "10044", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/Windows/Common.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "149836" } ], "symlink_target": "" }
"use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Test = function Test() { _classCallCheck(this, Test); }; "use strict"; arr.map(function (x) { return x * MULTIPLIER; }); //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNjcmlwdC5qcyIsInNjcmlwdDIuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7OztJQUFNLEk7Ozs7O0FDQU4sSUFBSSxHQUFKLENBQVE7QUFBQSxTQUFLLElBQUksVUFBVDtBQUFBLENBQVIiLCJmaWxlIjoic2NyaXB0My5qcyIsInNvdXJjZXNDb250ZW50IjpbImNsYXNzIFRlc3Qge1xuXG59IiwiYXJyLm1hcCh4ID0+IHggKiBNVUxUSVBMSUVSKTsiXX0=
{ "content_hash": "cfe4d961b5bbcb54f75f251e443e5a1c", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 372, "avg_line_length": 48.142857142857146, "alnum_prop": 0.8382789317507419, "repo_name": "kedromelon/babel", "id": "4a96b7518990d30b327c344e354c70fd975ce482", "size": "674", "binary": false, "copies": "2", "ref": "refs/heads/7.0", "path": "packages/babel-cli/test/fixtures/babel/filenames --out-file --source-maps inline/out-files/script3.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2747" }, { "name": "JavaScript", "bytes": "1854143" }, { "name": "Makefile", "bytes": "2245" }, { "name": "Shell", "bytes": "1461" } ], "symlink_target": "" }
module Compadre module Friendable extend ActiveSupport::Concern included do has_many :friendships, class_name: "Compadre::Friendship", foreign_key: :user_id has_many :friends, through: :friendships end def received_friend_requests Compadre::FriendRequest.where(requested_id: id) end def sent_friend_requests Compadre::FriendRequest.where(requester_id: id) end def send_friend_request_to(resource) Compadre::FriendRequest.create(requester_id: id, requested_id: resource.id) end def accept_friend_request_from(resource) friend_request = friend_request_from(resource) if friend_request requested_friendship = friendships.create(friend: resource) requester_friendship = resource.friendships.create(friend: self) end if requester_friendship.persisted? && requested_friendship.persisted? friend_request.destroy return true else return false end end def decline_friend_request_from(resource) friend_request = friend_request_from(resource) friend_request.destroy end def friend_request_from(resource) Compadre::FriendRequest. find_by_requested_id_and_requester_id(id, resource.id) end def friends_with(resource) friendships.find(resource.id).present? end def remove_friendship_with(resource) ids = [id, resource.id] Compadre::Friendship.where(user_id: ids, friend_id: ids).destroy_all end end end
{ "content_hash": "24550b866adc020a5737c3fffcfbdebe", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 75, "avg_line_length": 27.050847457627118, "alnum_prop": 0.6547619047619048, "repo_name": "essn/compadre", "id": "73516f8c0a71f7a7748ccf1bc4eba4356a934f13", "size": "1596", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/compadre/friendable.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1372" }, { "name": "HTML", "bytes": "5135" }, { "name": "JavaScript", "bytes": "1192" }, { "name": "Ruby", "bytes": "33091" } ], "symlink_target": "" }
@interface TPTwinPushRequest : TPRESTJSONRequest + (void)setServerURL:(NSString*)serverURL; @property (strong, nonatomic) NSString* notificationId; @property (strong, nonatomic) NSString* deviceId; @property (strong, nonatomic) NSString* appId; @property (strong, nonatomic) NSString* apiKey; @end
{ "content_hash": "3c4224f788cff1488cd4c2a6dfd0f3a9", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 55, "avg_line_length": 27.454545454545453, "alnum_prop": 0.7814569536423841, "repo_name": "TwinPush/ios-sdk", "id": "7a4bfa35450277e2025ffc94f3f9937ae0b348f5", "size": "480", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TwinPushSDK/Classes/Communications/Requests/TPTwinPushRequest.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "234852" }, { "name": "Ruby", "bytes": "2047" } ], "symlink_target": "" }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2015-2017 The Bitcoin Unlimited developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CHAIN_H #define BITCOIN_CHAIN_H #include "arith_uint256.h" #include "primitives/block.h" #include "pow.h" #include "tinyformat.h" #include "uint256.h" #include "util.h" #include <vector> struct CDiskBlockPos { int nFile; unsigned int nPos; ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(VARINT(nFile)); READWRITE(VARINT(nPos)); } CDiskBlockPos() { SetNull(); } CDiskBlockPos(int nFileIn, unsigned int nPosIn) { nFile = nFileIn; nPos = nPosIn; } friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) { return (a.nFile == b.nFile && a.nPos == b.nPos); } friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) { return !(a == b); } void SetNull() { nFile = -1; nPos = 0; } bool IsNull() const { return (nFile == -1); } std::string ToString() const { return strprintf("CBlockDiskPos(nFile=%i, nPos=%i)", nFile, nPos); } }; enum BlockStatus { //! Unused. BLOCK_VALID_UNKNOWN = 0, //! Parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future BLOCK_VALID_HEADER = 1, //! All parent headers found, difficulty matches, timestamp >= median previous, checkpoint. Implies all parents //! are also at least TREE. BLOCK_VALID_TREE = 2, /** * Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, * sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS. When all * parent blocks also have TRANSACTIONS, CBlockIndex::nChainTx will be set. */ BLOCK_VALID_TRANSACTIONS = 3, //! Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends, BIP30. //! Implies all parents are also at least CHAIN. BLOCK_VALID_CHAIN = 4, //! Scripts & signatures ok. Implies all parents are also at least SCRIPTS. BLOCK_VALID_SCRIPTS = 5, //! All validity bits. BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS | BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS, BLOCK_HAVE_DATA = 8, //! full block available in blk*.dat BLOCK_HAVE_UNDO = 16, //! undo data available in rev*.dat BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO, BLOCK_EXCESSIVE = 32, // BU: This block is bigger than what we really want to accept. BLOCK_FAILED_VALID = 64, //! stage after last reached validness failed BLOCK_FAILED_CHILD = 128, //! descends from failed block BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD, }; /** The block chain is a tree shaped structure starting with the * genesis block at the root, with each block potentially having multiple * candidates to be the next block. A blockindex may have multiple pprev pointing * to it, but at most one of them can be part of the currently active branch. */ class CBlockIndex { public: //! pointer to the hash of the block, if any. Memory is owned by this CBlockIndex const uint256* phashBlock; //! pointer to the index of the predecessor of this block CBlockIndex* pprev; //! pointer to the index of some further predecessor of this block CBlockIndex* pskip; //! height of the entry in the chain. The genesis block has height 0 int nHeight; //! Which # file this block is stored in (blk?????.dat) int nFile; //! Byte offset within blk?????.dat where this block's data is stored unsigned int nDataPos; //! Byte offset within rev?????.dat where this block's undo data is stored unsigned int nUndoPos; //! (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block arith_uint256 nChainWork; //! Number of transactions in this block. //! Note: in a potential headers-first mode, this number cannot be relied upon unsigned int nTx; //! (memory only) Number of transactions in the chain up to and including this block. //! This value will be non-zero only if and only if transactions for this block and all its parents are available. //! Change to 64-bit type when necessary; won't happen before 2030 unsigned int nChainTx; //! Verification status of this block. See enum BlockStatus unsigned int nStatus; //! block header int nVersion; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; //! (memory only) Sequential id assigned to distinguish order in which blocks are received. uint32_t nSequenceId; void SetNull() { phashBlock = NULL; pprev = NULL; pskip = NULL; nHeight = 0; nFile = 0; nDataPos = 0; nUndoPos = 0; nChainWork = arith_uint256(); nTx = 0; nChainTx = 0; nStatus = 0; nSequenceId = 0; nVersion = 0; hashMerkleRoot = uint256(); nTime = 0; nBits = 0; nNonce = 0; } CBlockIndex() { SetNull(); } CBlockIndex(const CBlockHeader& block) { SetNull(); nVersion = block.nVersion; hashMerkleRoot = block.hashMerkleRoot; nTime = block.nTime; nBits = block.nBits; nNonce = block.nNonce; } CDiskBlockPos GetBlockPos() const { CDiskBlockPos ret; if (nStatus & BLOCK_HAVE_DATA) { ret.nFile = nFile; ret.nPos = nDataPos; } return ret; } CDiskBlockPos GetUndoPos() const { CDiskBlockPos ret; if (nStatus & BLOCK_HAVE_UNDO) { ret.nFile = nFile; ret.nPos = nUndoPos; } return ret; } CBlockHeader GetBlockHeader() const { CBlockHeader block; block.nVersion = nVersion; if (pprev) block.hashPrevBlock = pprev->GetBlockHash(); block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block; } uint256 GetBlockHash() const { return *phashBlock; } int64_t GetBlockTime() const { return (int64_t)nTime; } enum { nMedianTimeSpan=11 }; int64_t GetMedianTimePast() const { int64_t pmedian[nMedianTimeSpan]; int64_t* pbegin = &pmedian[nMedianTimeSpan]; int64_t* pend = &pmedian[nMedianTimeSpan]; const CBlockIndex* pindex = this; for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev) *(--pbegin) = pindex->GetBlockTime(); std::sort(pbegin, pend); return pbegin[(pend - pbegin)/2]; } std::string ToString() const { return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)", pprev, nHeight, hashMerkleRoot.ToString(), GetBlockHash().ToString()); } //! Check whether this block index entry is valid up to the passed validity level. bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const { assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed. if (nStatus & BLOCK_FAILED_MASK) return false; return ((nStatus & BLOCK_VALID_MASK) >= nUpTo); } //! Raise the validity level of this block index entry. //! Returns true if the validity was changed. bool RaiseValidity(enum BlockStatus nUpTo) { assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed. if (nStatus & BLOCK_FAILED_MASK) return false; if ((nStatus & BLOCK_VALID_MASK) < nUpTo) { nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo; return true; } return false; } //! Build the skiplist pointer for this entry. void BuildSkip(); //! Efficiently find an ancestor of this block. CBlockIndex* GetAncestor(int height); const CBlockIndex* GetAncestor(int height) const; }; /** Used to marshal pointers into hashes for db storage. */ class CDiskBlockIndex : public CBlockIndex { public: uint256 hashPrev; CDiskBlockIndex() { hashPrev = uint256(); } explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex) { hashPrev = (pprev ? pprev->GetBlockHash() : uint256()); } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { if (!(nType & SER_GETHASH)) READWRITE(VARINT(nVersion)); READWRITE(VARINT(nHeight)); READWRITE(VARINT(nStatus)); READWRITE(VARINT(nTx)); if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO)) READWRITE(VARINT(nFile)); if (nStatus & BLOCK_HAVE_DATA) READWRITE(VARINT(nDataPos)); if (nStatus & BLOCK_HAVE_UNDO) READWRITE(VARINT(nUndoPos)); // block header READWRITE(this->nVersion); READWRITE(hashPrev); READWRITE(hashMerkleRoot); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce); } uint256 GetBlockHash() const { CBlockHeader block; block.nVersion = nVersion; block.hashPrevBlock = hashPrev; block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block.GetHash(); } std::string ToString() const { std::string str = "CDiskBlockIndex("; str += CBlockIndex::ToString(); str += strprintf("\n hashBlock=%s, hashPrev=%s)", GetBlockHash().ToString(), hashPrev.ToString()); return str; } }; /** An in-memory indexed chain of blocks. */ class CChain { private: std::vector<CBlockIndex*> vChain; public: /** Returns the index entry for the genesis block of this chain, or NULL if none. */ CBlockIndex *Genesis() const { return vChain.size() > 0 ? vChain[0] : NULL; } /** Returns the index entry for the tip of this chain, or NULL if none. */ CBlockIndex *Tip() const { return vChain.size() > 0 ? vChain[vChain.size() - 1] : NULL; } /** Returns the index entry at a particular height in this chain, or NULL if no such height exists. */ CBlockIndex *operator[](int nHeight) const { if (nHeight < 0 || nHeight >= (int)vChain.size()) return NULL; return vChain[nHeight]; } /** Compare two chains efficiently. */ friend bool operator==(const CChain &a, const CChain &b) { return a.vChain.size() == b.vChain.size() && a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1]; } /** Efficiently check whether a block is present in this chain. */ bool Contains(const CBlockIndex *pindex) const { /* null pointer isn't in this chain but caller should not send in the first place */ DbgAssert(pindex, return false); return (*this)[pindex->nHeight] == pindex; } /** Find the successor of a block in this chain, or NULL if the given index is not found or is the tip. */ CBlockIndex *Next(const CBlockIndex *pindex) const { if (Contains(pindex)) return (*this)[pindex->nHeight + 1]; else return NULL; } /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */ int Height() const { return vChain.size() - 1; } /** Set/initialize a chain with a given tip. */ void SetTip(CBlockIndex *pindex); /** Return a CBlockLocator that refers to a block in this chain (by default the tip). */ CBlockLocator GetLocator(const CBlockIndex *pindex = NULL) const; /** Find the last common block between this chain and a block index entry. */ const CBlockIndex *FindFork(const CBlockIndex *pindex) const; }; #endif // BITCOIN_CHAIN_H
{ "content_hash": "ea6da6236d37802829d02dac43c9ac21", "timestamp": "", "source": "github", "line_count": 410, "max_line_length": 118, "avg_line_length": 31.334146341463416, "alnum_prop": 0.6091694559041021, "repo_name": "AllanDoensen/BitcoinUnlimited", "id": "c24b0d42d2c5fb329f9e863c6d23e610170741d4", "size": "12847", "binary": false, "copies": "2", "ref": "refs/heads/release", "path": "src/chain.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "643089" }, { "name": "C++", "bytes": "4717607" }, { "name": "CSS", "bytes": "1127" }, { "name": "HTML", "bytes": "50621" }, { "name": "Java", "bytes": "2100" }, { "name": "M4", "bytes": "156775" }, { "name": "Makefile", "bytes": "98465" }, { "name": "Objective-C", "bytes": "5785" }, { "name": "Objective-C++", "bytes": "7360" }, { "name": "Protocol Buffer", "bytes": "2308" }, { "name": "Python", "bytes": "755390" }, { "name": "QMake", "bytes": "2020" }, { "name": "Roff", "bytes": "3821" }, { "name": "Shell", "bytes": "36574" } ], "symlink_target": "" }
namespace v8 { namespace internal { namespace compiler { #define KILL_ENVIRONMENT_LIST(V) \ V(Abort) \ V(ReThrow) \ V(Throw) #define CLEAR_ACCUMULATOR_LIST(V) \ V(CallRuntime) \ V(CloneObject) \ V(CreateArrayFromIterable) \ V(CreateEmptyObjectLiteral) \ V(CreateMappedArguments) \ V(CreateRestParameter) \ V(CreateUnmappedArguments) \ V(DeletePropertySloppy) \ V(DeletePropertyStrict) \ V(ForInContinue) \ V(ForInEnumerate) \ V(ForInStep) \ V(LogicalNot) \ V(SetPendingMessage) \ V(TestNull) \ V(TestReferenceEqual) \ V(TestTypeOf) \ V(TestUndefined) \ V(TestUndetectable) \ V(ToBooleanLogicalNot) \ V(ToName) \ V(ToString) \ V(TypeOf) #define UNCONDITIONAL_JUMPS_LIST(V) \ V(Jump) \ V(JumpConstant) \ V(JumpLoop) #define CONDITIONAL_JUMPS_LIST(V) \ V(JumpIfFalse) \ V(JumpIfFalseConstant) \ V(JumpIfJSReceiver) \ V(JumpIfJSReceiverConstant) \ V(JumpIfNotNull) \ V(JumpIfNotNullConstant) \ V(JumpIfNotUndefined) \ V(JumpIfNotUndefinedConstant) \ V(JumpIfNull) \ V(JumpIfNullConstant) \ V(JumpIfToBooleanFalse) \ V(JumpIfToBooleanFalseConstant) \ V(JumpIfToBooleanTrue) \ V(JumpIfToBooleanTrueConstant) \ V(JumpIfTrue) \ V(JumpIfTrueConstant) \ V(JumpIfUndefined) \ V(JumpIfUndefinedConstant) \ V(JumpIfUndefinedOrNull) \ V(JumpIfUndefinedOrNullConstant) #define IGNORED_BYTECODE_LIST(V) \ V(CallRuntimeForPair) \ V(CollectTypeProfile) \ V(DebugBreak0) \ V(DebugBreak1) \ V(DebugBreak2) \ V(DebugBreak3) \ V(DebugBreak4) \ V(DebugBreak5) \ V(DebugBreak6) \ V(DebugBreakExtraWide) \ V(DebugBreakWide) \ V(Debugger) \ V(IncBlockCounter) \ V(ResumeGenerator) \ V(SuspendGenerator) \ V(ThrowIfNotSuperConstructor) \ V(ThrowSuperAlreadyCalledIfNotHole) \ V(ThrowSuperNotCalledIfHole) \ V(ToObject) #define UNREACHABLE_BYTECODE_LIST(V) \ V(ExtraWide) \ V(Illegal) \ V(Wide) #define BINARY_OP_LIST(V) \ V(Add) \ V(AddSmi) \ V(BitwiseAnd) \ V(BitwiseAndSmi) \ V(BitwiseOr) \ V(BitwiseOrSmi) \ V(BitwiseXor) \ V(BitwiseXorSmi) \ V(Div) \ V(DivSmi) \ V(Exp) \ V(ExpSmi) \ V(Mod) \ V(ModSmi) \ V(Mul) \ V(MulSmi) \ V(ShiftLeft) \ V(ShiftLeftSmi) \ V(ShiftRight) \ V(ShiftRightSmi) \ V(ShiftRightLogical) \ V(ShiftRightLogicalSmi) \ V(Sub) \ V(SubSmi) #define UNARY_OP_LIST(V) \ V(BitwiseNot) \ V(Dec) \ V(Inc) \ V(Negate) #define COMPARE_OP_LIST(V) \ V(TestEqual) \ V(TestEqualStrict) \ V(TestGreaterThan) \ V(TestGreaterThanOrEqual) \ V(TestLessThan) \ V(TestLessThanOrEqual) #define SUPPORTED_BYTECODE_LIST(V) \ V(CallAnyReceiver) \ V(CallJSRuntime) \ V(CallNoFeedback) \ V(CallProperty) \ V(CallProperty0) \ V(CallProperty1) \ V(CallProperty2) \ V(CallUndefinedReceiver) \ V(CallUndefinedReceiver0) \ V(CallUndefinedReceiver1) \ V(CallUndefinedReceiver2) \ V(CallWithSpread) \ V(Construct) \ V(ConstructWithSpread) \ V(CreateArrayLiteral) \ V(CreateBlockContext) \ V(CreateCatchContext) \ V(CreateClosure) \ V(CreateEmptyArrayLiteral) \ V(CreateEvalContext) \ V(CreateFunctionContext) \ V(CreateObjectLiteral) \ V(CreateRegExpLiteral) \ V(CreateWithContext) \ V(ForInNext) \ V(ForInPrepare) \ V(GetIterator) \ V(GetSuperConstructor) \ V(GetTemplateObject) \ V(InvokeIntrinsic) \ V(LdaConstant) \ V(LdaContextSlot) \ V(LdaCurrentContextSlot) \ V(LdaImmutableContextSlot) \ V(LdaImmutableCurrentContextSlot) \ V(LdaModuleVariable) \ V(LdaFalse) \ V(LdaGlobal) \ V(LdaGlobalInsideTypeof) \ V(LdaKeyedProperty) \ V(LdaLookupContextSlot) \ V(LdaLookupContextSlotInsideTypeof) \ V(LdaLookupGlobalSlot) \ V(LdaLookupGlobalSlotInsideTypeof) \ V(LdaLookupSlot) \ V(LdaLookupSlotInsideTypeof) \ V(LdaNamedProperty) \ V(LdaNamedPropertyFromSuper) \ V(LdaNamedPropertyNoFeedback) \ V(LdaNull) \ V(Ldar) \ V(LdaSmi) \ V(LdaTheHole) \ V(LdaTrue) \ V(LdaUndefined) \ V(LdaZero) \ V(Mov) \ V(PopContext) \ V(PushContext) \ V(Return) \ V(StaContextSlot) \ V(StaCurrentContextSlot) \ V(StaDataPropertyInLiteral) \ V(StaGlobal) \ V(StaInArrayLiteral) \ V(StaKeyedProperty) \ V(StaLookupSlot) \ V(StaModuleVariable) \ V(StaNamedOwnProperty) \ V(StaNamedProperty) \ V(StaNamedPropertyNoFeedback) \ V(Star) \ V(SwitchOnGeneratorState) \ V(SwitchOnSmiNoFeedback) \ V(TestIn) \ V(TestInstanceOf) \ V(ThrowReferenceErrorIfHole) \ V(ToNumber) \ V(ToNumeric) \ BINARY_OP_LIST(V) \ COMPARE_OP_LIST(V) \ CLEAR_ACCUMULATOR_LIST(V) \ CONDITIONAL_JUMPS_LIST(V) \ IGNORED_BYTECODE_LIST(V) \ KILL_ENVIRONMENT_LIST(V) \ UNARY_OP_LIST(V) \ UNCONDITIONAL_JUMPS_LIST(V) \ UNREACHABLE_BYTECODE_LIST(V) struct HintsImpl : public ZoneObject { explicit HintsImpl(Zone* zone) : zone_(zone) {} ConstantsSet constants_; MapsSet maps_; VirtualClosuresSet virtual_closures_; VirtualContextsSet virtual_contexts_; VirtualBoundFunctionsSet virtual_bound_functions_; Zone* const zone_; }; void Hints::EnsureAllocated(Zone* zone, bool check_zone_equality) { if (IsAllocated()) { if (check_zone_equality) CHECK_EQ(zone, impl_->zone_); // ... else {zone} lives no longer than {impl_->zone_} but we have no way of // checking that. } else { impl_ = zone->New<HintsImpl>(zone); } DCHECK(IsAllocated()); } struct VirtualBoundFunction { Hints const bound_target; HintsVector const bound_arguments; VirtualBoundFunction(Hints const& target, const HintsVector& arguments) : bound_target(target), bound_arguments(arguments) {} bool operator==(const VirtualBoundFunction& other) const { if (bound_arguments.size() != other.bound_arguments.size()) return false; if (bound_target != other.bound_target) return false; for (size_t i = 0; i < bound_arguments.size(); ++i) { if (bound_arguments[i] != other.bound_arguments[i]) return false; } return true; } }; // A VirtualClosure is a SharedFunctionInfo and a FeedbackVector, plus // Hints about the context in which a closure will be created from them. class VirtualClosure { public: VirtualClosure(Handle<JSFunction> function, Isolate* isolate, Zone* zone); VirtualClosure(Handle<SharedFunctionInfo> shared, Handle<FeedbackVector> feedback_vector, Hints const& context_hints); Handle<SharedFunctionInfo> shared() const { return shared_; } Handle<FeedbackVector> feedback_vector() const { return feedback_vector_; } Hints const& context_hints() const { return context_hints_; } bool operator==(const VirtualClosure& other) const { // A feedback vector is never used for more than one SFI. There might, // however, be two virtual closures with the same SFI and vector, but // different context hints. crbug.com/1024282 has a link to a document // describing why the context_hints_ might be different in that case. DCHECK_IMPLIES(feedback_vector_.equals(other.feedback_vector_), shared_.equals(other.shared_)); return feedback_vector_.equals(other.feedback_vector_) && context_hints_ == other.context_hints_; } private: Handle<SharedFunctionInfo> const shared_; Handle<FeedbackVector> const feedback_vector_; Hints const context_hints_; }; // A CompilationSubject is a VirtualClosure, optionally with a matching // concrete closure. class CompilationSubject { public: explicit CompilationSubject(VirtualClosure virtual_closure) : virtual_closure_(virtual_closure), closure_() {} // The zone parameter is to correctly initialize the virtual closure, // which contains zone-allocated context information. CompilationSubject(Handle<JSFunction> closure, Isolate* isolate, Zone* zone); const VirtualClosure& virtual_closure() const { return virtual_closure_; } MaybeHandle<JSFunction> closure() const { return closure_; } private: VirtualClosure const virtual_closure_; MaybeHandle<JSFunction> const closure_; }; // A Callee is either a JSFunction (which may not have a feedback vector), or a // VirtualClosure. Note that this is different from CompilationSubject, which // always has a VirtualClosure. class Callee { public: explicit Callee(Handle<JSFunction> jsfunction) : jsfunction_(jsfunction), virtual_closure_() {} explicit Callee(VirtualClosure const& virtual_closure) : jsfunction_(), virtual_closure_(virtual_closure) {} Handle<SharedFunctionInfo> shared(Isolate* isolate) const { return virtual_closure_.has_value() ? virtual_closure_->shared() : handle(jsfunction_.ToHandleChecked()->shared(), isolate); } bool HasFeedbackVector() const { Handle<JSFunction> function; return virtual_closure_.has_value() || jsfunction_.ToHandleChecked()->has_feedback_vector(); } CompilationSubject ToCompilationSubject(Isolate* isolate, Zone* zone) const { CHECK(HasFeedbackVector()); return virtual_closure_.has_value() ? CompilationSubject(*virtual_closure_) : CompilationSubject(jsfunction_.ToHandleChecked(), isolate, zone); } private: MaybeHandle<JSFunction> const jsfunction_; base::Optional<VirtualClosure> const virtual_closure_; }; // If a list of arguments (hints) is shorter than the function's parameter // count, this enum expresses what we know about the missing arguments. enum MissingArgumentsPolicy { kMissingArgumentsAreUndefined, // ... as in the JS undefined value kMissingArgumentsAreUnknown, }; // The SerializerForBackgroundCompilation makes sure that the relevant function // data such as bytecode, SharedFunctionInfo and FeedbackVector, used by later // optimizations in the compiler, is copied to the heap broker. class SerializerForBackgroundCompilation { public: SerializerForBackgroundCompilation( ZoneStats* zone_stats, JSHeapBroker* broker, CompilationDependencies* dependencies, Handle<JSFunction> closure, SerializerForBackgroundCompilationFlags flags, BailoutId osr_offset); Hints Run(); // NOTE: Returns empty for an // already-serialized function. class Environment; private: SerializerForBackgroundCompilation( ZoneStats* zone_stats, JSHeapBroker* broker, CompilationDependencies* dependencies, CompilationSubject function, base::Optional<Hints> new_target, const HintsVector& arguments, MissingArgumentsPolicy padding, SerializerForBackgroundCompilationFlags flags, int nesting_level); bool BailoutOnUninitialized(ProcessedFeedback const& feedback); void TraverseBytecode(); #define DECLARE_VISIT_BYTECODE(name, ...) \ void Visit##name(interpreter::BytecodeArrayIterator* iterator); SUPPORTED_BYTECODE_LIST(DECLARE_VISIT_BYTECODE) #undef DECLARE_VISIT_BYTECODE Hints& register_hints(interpreter::Register reg); // Return a vector containing the hints for the given register range (in // order). Also prepare these hints for feedback backpropagation by allocating // any that aren't yet allocated. HintsVector PrepareArgumentsHints(interpreter::Register first, size_t count); // Like above except that the hints have to be given directly. template <typename... MoreHints> HintsVector PrepareArgumentsHints(Hints* hints, MoreHints... more); void ProcessCalleeForCallOrConstruct(Callee const& callee, base::Optional<Hints> new_target, const HintsVector& arguments, SpeculationMode speculation_mode, MissingArgumentsPolicy padding, Hints* result_hints); void ProcessCalleeForCallOrConstruct(Handle<Object> callee, base::Optional<Hints> new_target, const HintsVector& arguments, SpeculationMode speculation_mode, MissingArgumentsPolicy padding, Hints* result_hints); void ProcessCallOrConstruct(Hints callee, base::Optional<Hints> new_target, HintsVector* arguments, FeedbackSlot slot, MissingArgumentsPolicy padding); void ProcessCallOrConstructRecursive(Hints const& callee, base::Optional<Hints> new_target, const HintsVector& arguments, SpeculationMode speculation_mode, MissingArgumentsPolicy padding, Hints* result_hints); void ProcessNewTargetForConstruct(Hints const& new_target, Hints* result_hints); void ProcessCallVarArgs( ConvertReceiverMode receiver_mode, Hints const& callee, interpreter::Register first_reg, int reg_count, FeedbackSlot slot, MissingArgumentsPolicy padding = kMissingArgumentsAreUndefined); void ProcessApiCall(Handle<SharedFunctionInfo> target, const HintsVector& arguments); void ProcessReceiverMapForApiCall(FunctionTemplateInfoRef target, Handle<Map> receiver); void ProcessBuiltinCall(Handle<SharedFunctionInfo> target, base::Optional<Hints> new_target, const HintsVector& arguments, SpeculationMode speculation_mode, MissingArgumentsPolicy padding, Hints* result_hints); void ProcessJump(interpreter::BytecodeArrayIterator* iterator); void ProcessKeyedPropertyAccess(Hints* receiver, Hints const& key, FeedbackSlot slot, AccessMode access_mode, bool honor_bailout_on_uninitialized); void ProcessNamedPropertyAccess(Hints* receiver, NameRef const& name, FeedbackSlot slot, AccessMode access_mode); void ProcessNamedSuperPropertyAccess(Hints* receiver, NameRef const& name, FeedbackSlot slot, AccessMode access_mode); void ProcessNamedAccess(Hints* receiver, NamedAccessFeedback const& feedback, AccessMode access_mode, Hints* result_hints); void ProcessNamedSuperAccess(Hints* receiver, NamedAccessFeedback const& feedback, AccessMode access_mode, Hints* result_hints); void ProcessElementAccess(Hints const& receiver, Hints const& key, ElementAccessFeedback const& feedback, AccessMode access_mode); void ProcessMinimorphicPropertyAccess( MinimorphicLoadPropertyAccessFeedback const& feedback, FeedbackSource const& source); void ProcessModuleVariableAccess( interpreter::BytecodeArrayIterator* iterator); void ProcessHintsForObjectCreate(Hints const& prototype); void ProcessMapHintsForPromises(Hints const& receiver_hints); void ProcessHintsForPromiseResolve(Hints const& resolution_hints); void ProcessHintsForHasInPrototypeChain(Hints const& instance_hints); void ProcessHintsForRegExpTest(Hints const& regexp_hints); PropertyAccessInfo ProcessMapForRegExpTest(MapRef map); void ProcessHintsForFunctionBind(Hints const& receiver_hints); void ProcessHintsForObjectGetPrototype(Hints const& object_hints); void ProcessConstantForOrdinaryHasInstance(HeapObjectRef const& constructor, bool* walk_prototypes); void ProcessConstantForInstanceOf(ObjectRef const& constant, bool* walk_prototypes); void ProcessHintsForOrdinaryHasInstance(Hints const& constructor_hints, Hints const& instance_hints); void ProcessGlobalAccess(FeedbackSlot slot, bool is_load); void ProcessCompareOperation(FeedbackSlot slot); void ProcessForIn(FeedbackSlot slot); void ProcessUnaryOrBinaryOperation(FeedbackSlot slot, bool honor_bailout_on_uninitialized); PropertyAccessInfo ProcessMapForNamedPropertyAccess( Hints* receiver, base::Optional<MapRef> receiver_map, MapRef lookup_start_object_map, NameRef const& name, AccessMode access_mode, base::Optional<JSObjectRef> concrete_receiver, Hints* result_hints); void ProcessCreateContext(interpreter::BytecodeArrayIterator* iterator, int scopeinfo_operand_index); enum ContextProcessingMode { kIgnoreSlot, kSerializeSlot, }; void ProcessContextAccess(Hints const& context_hints, int slot, int depth, ContextProcessingMode mode, Hints* result_hints = nullptr); void ProcessImmutableLoad(ContextRef const& context, int slot, ContextProcessingMode mode, Hints* new_accumulator_hints); void ProcessLdaLookupGlobalSlot(interpreter::BytecodeArrayIterator* iterator); void ProcessLdaLookupContextSlot( interpreter::BytecodeArrayIterator* iterator); // Performs extension lookups for [0, depth) like // BytecodeGraphBuilder::CheckContextExtensions(). void ProcessCheckContextExtensions(int depth); Hints RunChildSerializer(CompilationSubject function, base::Optional<Hints> new_target, const HintsVector& arguments, MissingArgumentsPolicy padding); // When (forward-)branching bytecodes are encountered, e.g. a conditional // jump, we call ContributeToJumpTargetEnvironment to "remember" the current // environment, associated with the jump target offset. When serialization // eventually reaches that offset, we call IncorporateJumpTargetEnvironment to // merge that environment back into whatever is the current environment then. // Note: Since there may be multiple jumps to the same target, // ContributeToJumpTargetEnvironment may actually do a merge as well. void ContributeToJumpTargetEnvironment(int target_offset); void IncorporateJumpTargetEnvironment(int target_offset); VirtualClosure function() const { return function_; } Hints& return_value_hints() { return return_value_hints_; } Handle<FeedbackVector> feedback_vector() const; Handle<BytecodeArray> bytecode_array() const; BytecodeAnalysis const& GetBytecodeAnalysis( SerializationPolicy policy = SerializationPolicy::kAssumeSerialized); JSHeapBroker* broker() const { return broker_; } CompilationDependencies* dependencies() const { return dependencies_; } Zone* zone() { return zone_scope_.zone(); } Environment* environment() const { return environment_; } SerializerForBackgroundCompilationFlags flags() const { return flags_; } BailoutId osr_offset() const { return osr_offset_; } JSHeapBroker* const broker_; CompilationDependencies* const dependencies_; ZoneStats::Scope zone_scope_; SerializerForBackgroundCompilationFlags const flags_; // Instead of storing the virtual_closure here, we could extract it from the // {closure_hints_} but that would be cumbersome. VirtualClosure const function_; BailoutId const osr_offset_; ZoneUnorderedMap<int, Environment*> jump_target_environments_; Environment* const environment_; HintsVector const arguments_; Hints return_value_hints_; Hints closure_hints_; int nesting_level_ = 0; }; void RunSerializerForBackgroundCompilation( ZoneStats* zone_stats, JSHeapBroker* broker, CompilationDependencies* dependencies, Handle<JSFunction> closure, SerializerForBackgroundCompilationFlags flags, BailoutId osr_offset) { SerializerForBackgroundCompilation serializer( zone_stats, broker, dependencies, closure, flags, osr_offset); serializer.Run(); } using BytecodeArrayIterator = interpreter::BytecodeArrayIterator; VirtualClosure::VirtualClosure(Handle<SharedFunctionInfo> shared, Handle<FeedbackVector> feedback_vector, Hints const& context_hints) : shared_(shared), feedback_vector_(feedback_vector), context_hints_(context_hints) { // The checked invariant rules out recursion and thus avoids complexity. CHECK(context_hints_.virtual_closures().IsEmpty()); } VirtualClosure::VirtualClosure(Handle<JSFunction> function, Isolate* isolate, Zone* zone) : shared_(handle(function->shared(), isolate)), feedback_vector_(function->feedback_vector(), isolate), context_hints_( Hints::SingleConstant(handle(function->context(), isolate), zone)) { // The checked invariant rules out recursion and thus avoids complexity. CHECK(context_hints_.virtual_closures().IsEmpty()); } CompilationSubject::CompilationSubject(Handle<JSFunction> closure, Isolate* isolate, Zone* zone) : virtual_closure_(closure, isolate, zone), closure_(closure) { CHECK(closure->has_feedback_vector()); } Hints Hints::Copy(Zone* zone) const { if (!IsAllocated()) return *this; Hints result; result.EnsureAllocated(zone); result.impl_->constants_ = impl_->constants_; result.impl_->maps_ = impl_->maps_; result.impl_->virtual_contexts_ = impl_->virtual_contexts_; result.impl_->virtual_closures_ = impl_->virtual_closures_; result.impl_->virtual_bound_functions_ = impl_->virtual_bound_functions_; return result; } bool Hints::operator==(Hints const& other) const { if (impl_ == other.impl_) return true; if (IsEmpty() && other.IsEmpty()) return true; return IsAllocated() && other.IsAllocated() && constants() == other.constants() && virtual_closures() == other.virtual_closures() && maps() == other.maps() && virtual_contexts() == other.virtual_contexts() && virtual_bound_functions() == other.virtual_bound_functions(); } bool Hints::operator!=(Hints const& other) const { return !(*this == other); } #ifdef ENABLE_SLOW_DCHECKS bool Hints::Includes(Hints const& other) const { if (impl_ == other.impl_ || other.IsEmpty()) return true; return IsAllocated() && constants().Includes(other.constants()) && virtual_closures().Includes(other.virtual_closures()) && maps().Includes(other.maps()); } #endif Hints Hints::SingleConstant(Handle<Object> constant, Zone* zone) { Hints result; result.AddConstant(constant, zone, nullptr); return result; } Hints Hints::SingleMap(Handle<Map> map, Zone* zone) { Hints result; result.AddMap(map, zone, nullptr); return result; } ConstantsSet Hints::constants() const { return IsAllocated() ? impl_->constants_ : ConstantsSet(); } MapsSet Hints::maps() const { return IsAllocated() ? impl_->maps_ : MapsSet(); } VirtualClosuresSet Hints::virtual_closures() const { return IsAllocated() ? impl_->virtual_closures_ : VirtualClosuresSet(); } VirtualContextsSet Hints::virtual_contexts() const { return IsAllocated() ? impl_->virtual_contexts_ : VirtualContextsSet(); } VirtualBoundFunctionsSet Hints::virtual_bound_functions() const { return IsAllocated() ? impl_->virtual_bound_functions_ : VirtualBoundFunctionsSet(); } void Hints::AddVirtualContext(VirtualContext const& virtual_context, Zone* zone, JSHeapBroker* broker) { EnsureAllocated(zone); if (impl_->virtual_contexts_.Size() >= kMaxHintsSize) { TRACE_BROKER_MISSING(broker, "opportunity - limit for virtual contexts reached."); return; } impl_->virtual_contexts_.Add(virtual_context, impl_->zone_); } void Hints::AddConstant(Handle<Object> constant, Zone* zone, JSHeapBroker* broker) { EnsureAllocated(zone); if (impl_->constants_.Size() >= kMaxHintsSize) { TRACE_BROKER_MISSING(broker, "opportunity - limit for constants reached."); return; } impl_->constants_.Add(constant, impl_->zone_); } void Hints::AddMap(Handle<Map> map, Zone* zone, JSHeapBroker* broker, bool check_zone_equality) { EnsureAllocated(zone, check_zone_equality); if (impl_->maps_.Size() >= kMaxHintsSize) { TRACE_BROKER_MISSING(broker, "opportunity - limit for maps reached."); return; } impl_->maps_.Add(map, impl_->zone_); } void Hints::AddVirtualClosure(VirtualClosure const& virtual_closure, Zone* zone, JSHeapBroker* broker) { EnsureAllocated(zone); if (impl_->virtual_closures_.Size() >= kMaxHintsSize) { TRACE_BROKER_MISSING(broker, "opportunity - limit for virtual closures reached."); return; } impl_->virtual_closures_.Add(virtual_closure, impl_->zone_); } void Hints::AddVirtualBoundFunction(VirtualBoundFunction const& bound_function, Zone* zone, JSHeapBroker* broker) { EnsureAllocated(zone); if (impl_->virtual_bound_functions_.Size() >= kMaxHintsSize) { TRACE_BROKER_MISSING( broker, "opportunity - limit for virtual bound functions reached."); return; } // TODO(mslekova): Consider filtering the hints in the added bound function, // for example: a) Remove any non-JS(Bound)Function constants, b) Truncate the // argument vector the formal parameter count. impl_->virtual_bound_functions_.Add(bound_function, impl_->zone_); } void Hints::Add(Hints const& other, Zone* zone, JSHeapBroker* broker) { if (impl_ == other.impl_ || other.IsEmpty()) return; EnsureAllocated(zone); if (!Union(other)) { TRACE_BROKER_MISSING(broker, "opportunity - hints limit reached."); } } Hints Hints::CopyToParentZone(Zone* zone, JSHeapBroker* broker) const { if (!IsAllocated()) return *this; Hints result; for (auto const& x : constants()) result.AddConstant(x, zone, broker); for (auto const& x : maps()) result.AddMap(x, zone, broker); for (auto const& x : virtual_contexts()) result.AddVirtualContext(x, zone, broker); // Adding hints from a child serializer run means copying data out from // a zone that's being destroyed. VirtualClosures and VirtualBoundFunction // have zone allocated data, so we've got to make a deep copy to eliminate // traces of the dying zone. for (auto const& x : virtual_closures()) { VirtualClosure new_virtual_closure( x.shared(), x.feedback_vector(), x.context_hints().CopyToParentZone(zone, broker)); result.AddVirtualClosure(new_virtual_closure, zone, broker); } for (auto const& x : virtual_bound_functions()) { HintsVector new_arguments_hints(zone); for (auto hint : x.bound_arguments) { new_arguments_hints.push_back(hint.CopyToParentZone(zone, broker)); } VirtualBoundFunction new_bound_function( x.bound_target.CopyToParentZone(zone, broker), new_arguments_hints); result.AddVirtualBoundFunction(new_bound_function, zone, broker); } return result; } bool Hints::IsEmpty() const { if (!IsAllocated()) return true; return constants().IsEmpty() && maps().IsEmpty() && virtual_closures().IsEmpty() && virtual_contexts().IsEmpty() && virtual_bound_functions().IsEmpty(); } std::ostream& operator<<(std::ostream& out, const VirtualContext& virtual_context) { out << "Distance " << virtual_context.distance << " from " << Brief(*virtual_context.context) << std::endl; return out; } std::ostream& operator<<(std::ostream& out, const Hints& hints); std::ostream& operator<<(std::ostream& out, const VirtualClosure& virtual_closure) { out << Brief(*virtual_closure.shared()) << std::endl; out << Brief(*virtual_closure.feedback_vector()) << std::endl; !virtual_closure.context_hints().IsEmpty() && out << virtual_closure.context_hints() << "):" << std::endl; return out; } std::ostream& operator<<(std::ostream& out, const VirtualBoundFunction& virtual_bound_function) { out << std::endl << " Target: " << virtual_bound_function.bound_target; out << " Arguments:" << std::endl; for (auto hint : virtual_bound_function.bound_arguments) { out << " " << hint; } return out; } std::ostream& operator<<(std::ostream& out, const Hints& hints) { out << "(impl_ = " << hints.impl_ << ")\n"; for (Handle<Object> constant : hints.constants()) { out << " constant " << Brief(*constant) << std::endl; } for (Handle<Map> map : hints.maps()) { out << " map " << Brief(*map) << std::endl; } for (VirtualClosure const& virtual_closure : hints.virtual_closures()) { out << " virtual closure " << virtual_closure << std::endl; } for (VirtualContext const& virtual_context : hints.virtual_contexts()) { out << " virtual context " << virtual_context << std::endl; } for (VirtualBoundFunction const& virtual_bound_function : hints.virtual_bound_functions()) { out << " virtual bound function " << virtual_bound_function << std::endl; } return out; } void Hints::Reset(Hints* other, Zone* zone) { other->EnsureShareable(zone); *this = *other; DCHECK(IsAllocated()); } class SerializerForBackgroundCompilation::Environment : public ZoneObject { public: Environment(Zone* zone, CompilationSubject function); Environment(Zone* zone, Isolate* isolate, CompilationSubject function, base::Optional<Hints> new_target, const HintsVector& arguments, MissingArgumentsPolicy padding); bool IsDead() const { return !alive_; } void Kill() { DCHECK(!IsDead()); alive_ = false; DCHECK(IsDead()); } void Resurrect() { DCHECK(IsDead()); alive_ = true; DCHECK(!IsDead()); } // Merge {other} into {this} environment (leaving {other} unmodified). void Merge(Environment* other, Zone* zone, JSHeapBroker* broker); Hints const& current_context_hints() const { return current_context_hints_; } Hints const& accumulator_hints() const { return accumulator_hints_; } Hints& current_context_hints() { return current_context_hints_; } Hints& accumulator_hints() { return accumulator_hints_; } Hints& register_hints(interpreter::Register reg); private: friend std::ostream& operator<<(std::ostream& out, const Environment& env); Hints current_context_hints_; Hints accumulator_hints_; HintsVector parameters_hints_; // First parameter is the receiver. HintsVector locals_hints_; bool alive_ = true; }; SerializerForBackgroundCompilation::Environment::Environment( Zone* zone, CompilationSubject function) : parameters_hints_(function.virtual_closure() .shared() ->GetBytecodeArray() .parameter_count(), Hints(), zone), locals_hints_(function.virtual_closure() .shared() ->GetBytecodeArray() .register_count(), Hints(), zone) { // Consume the virtual_closure's context hint information. current_context_hints_ = function.virtual_closure().context_hints(); } SerializerForBackgroundCompilation::Environment::Environment( Zone* zone, Isolate* isolate, CompilationSubject function, base::Optional<Hints> new_target, const HintsVector& arguments, MissingArgumentsPolicy padding) : Environment(zone, function) { // Set the hints for the actually passed arguments, at most up to // the parameter_count. for (size_t i = 0; i < std::min(arguments.size(), parameters_hints_.size()); ++i) { parameters_hints_[i] = arguments[i]; } if (padding == kMissingArgumentsAreUndefined) { Hints const undefined_hint = Hints::SingleConstant(isolate->factory()->undefined_value(), zone); for (size_t i = arguments.size(); i < parameters_hints_.size(); ++i) { parameters_hints_[i] = undefined_hint; } } else { DCHECK_EQ(padding, kMissingArgumentsAreUnknown); } // Set hints for new_target. interpreter::Register new_target_reg = function.virtual_closure() .shared() ->GetBytecodeArray() .incoming_new_target_or_generator_register(); if (new_target_reg.is_valid()) { Hints& hints = register_hints(new_target_reg); CHECK(hints.IsEmpty()); if (new_target.has_value()) hints = *new_target; } } Hints& SerializerForBackgroundCompilation::register_hints( interpreter::Register reg) { if (reg.is_function_closure()) return closure_hints_; return environment()->register_hints(reg); } Hints& SerializerForBackgroundCompilation::Environment::register_hints( interpreter::Register reg) { if (reg.is_current_context()) return current_context_hints_; if (reg.is_parameter()) { return parameters_hints_[reg.ToParameterIndex( static_cast<int>(parameters_hints_.size()))]; } DCHECK(!reg.is_function_closure()); CHECK_LT(reg.index(), locals_hints_.size()); return locals_hints_[reg.index()]; } void SerializerForBackgroundCompilation::Environment::Merge( Environment* other, Zone* zone, JSHeapBroker* broker) { // {other} is guaranteed to have the same layout because it comes from an // earlier bytecode in the same function. DCHECK_EQ(parameters_hints_.size(), other->parameters_hints_.size()); DCHECK_EQ(locals_hints_.size(), other->locals_hints_.size()); if (IsDead()) { parameters_hints_ = other->parameters_hints_; locals_hints_ = other->locals_hints_; current_context_hints_ = other->current_context_hints_; accumulator_hints_ = other->accumulator_hints_; Resurrect(); } else { for (size_t i = 0; i < parameters_hints_.size(); ++i) { parameters_hints_[i].Merge(other->parameters_hints_[i], zone, broker); } for (size_t i = 0; i < locals_hints_.size(); ++i) { locals_hints_[i].Merge(other->locals_hints_[i], zone, broker); } current_context_hints_.Merge(other->current_context_hints_, zone, broker); accumulator_hints_.Merge(other->accumulator_hints_, zone, broker); } CHECK(!IsDead()); } bool Hints::Union(Hints const& other) { CHECK(IsAllocated()); if (impl_->constants_.Size() + other.constants().Size() > kMaxHintsSize || impl_->maps_.Size() + other.maps().Size() > kMaxHintsSize || impl_->virtual_closures_.Size() + other.virtual_closures().Size() > kMaxHintsSize || impl_->virtual_contexts_.Size() + other.virtual_contexts().Size() > kMaxHintsSize || impl_->virtual_bound_functions_.Size() + other.virtual_bound_functions().Size() > kMaxHintsSize) { return false; } Zone* zone = impl_->zone_; impl_->constants_.Union(other.constants(), zone); impl_->maps_.Union(other.maps(), zone); impl_->virtual_closures_.Union(other.virtual_closures(), zone); impl_->virtual_contexts_.Union(other.virtual_contexts(), zone); impl_->virtual_bound_functions_.Union(other.virtual_bound_functions(), zone); return true; } void Hints::Merge(Hints const& other, Zone* zone, JSHeapBroker* broker) { if (impl_ == other.impl_) { return; } if (!IsAllocated()) { *this = other.Copy(zone); DCHECK(IsAllocated()); return; } *this = this->Copy(zone); if (!Union(other)) { TRACE_BROKER_MISSING(broker, "opportunity - hints limit reached."); } DCHECK(IsAllocated()); } std::ostream& operator<<( std::ostream& out, const SerializerForBackgroundCompilation::Environment& env) { std::ostringstream output_stream; if (env.IsDead()) { output_stream << "dead\n"; } else { output_stream << "alive\n"; for (size_t i = 0; i < env.parameters_hints_.size(); ++i) { Hints const& hints = env.parameters_hints_[i]; if (!hints.IsEmpty()) { if (i == 0) { output_stream << "Hints for <this>: "; } else { output_stream << "Hints for a" << i - 1 << ": "; } output_stream << hints; } } for (size_t i = 0; i < env.locals_hints_.size(); ++i) { Hints const& hints = env.locals_hints_[i]; if (!hints.IsEmpty()) { output_stream << "Hints for r" << i << ": " << hints; } } } if (!env.current_context_hints().IsEmpty()) { output_stream << "Hints for <context>: " << env.current_context_hints(); } if (!env.accumulator_hints().IsEmpty()) { output_stream << "Hints for <accumulator>: " << env.accumulator_hints(); } out << output_stream.str(); return out; } SerializerForBackgroundCompilation::SerializerForBackgroundCompilation( ZoneStats* zone_stats, JSHeapBroker* broker, CompilationDependencies* dependencies, Handle<JSFunction> closure, SerializerForBackgroundCompilationFlags flags, BailoutId osr_offset) : broker_(broker), dependencies_(dependencies), zone_scope_(zone_stats, ZONE_NAME), flags_(flags), function_(closure, broker->isolate(), zone()), osr_offset_(osr_offset), jump_target_environments_(zone()), environment_(zone()->New<Environment>( zone(), CompilationSubject(closure, broker_->isolate(), zone()))), arguments_(zone()) { closure_hints_.AddConstant(closure, zone(), broker_); JSFunctionRef(broker, closure).Serialize(); TRACE_BROKER(broker_, "Hints for <closure>: " << closure_hints_); TRACE_BROKER(broker_, "Initial environment:\n" << *environment_); } SerializerForBackgroundCompilation::SerializerForBackgroundCompilation( ZoneStats* zone_stats, JSHeapBroker* broker, CompilationDependencies* dependencies, CompilationSubject function, base::Optional<Hints> new_target, const HintsVector& arguments, MissingArgumentsPolicy padding, SerializerForBackgroundCompilationFlags flags, int nesting_level) : broker_(broker), dependencies_(dependencies), zone_scope_(zone_stats, ZONE_NAME), flags_(flags), function_(function.virtual_closure()), osr_offset_(BailoutId::None()), jump_target_environments_(zone()), environment_(zone()->New<Environment>(zone(), broker_->isolate(), function, new_target, arguments, padding)), arguments_(arguments), nesting_level_(nesting_level) { Handle<JSFunction> closure; if (function.closure().ToHandle(&closure)) { closure_hints_.AddConstant(closure, zone(), broker); JSFunctionRef(broker, closure).Serialize(); } else { closure_hints_.AddVirtualClosure(function.virtual_closure(), zone(), broker); } TRACE_BROKER(broker_, "Hints for <closure>: " << closure_hints_); TRACE_BROKER(broker_, "Initial environment:\n" << *environment_); } bool SerializerForBackgroundCompilation::BailoutOnUninitialized( ProcessedFeedback const& feedback) { DCHECK(!environment()->IsDead()); if (!(flags() & SerializerForBackgroundCompilationFlag::kBailoutOnUninitialized)) { return false; } if (!osr_offset().IsNone()) { // Exclude OSR from this optimization because we might end up skipping the // OSR entry point. TODO(neis): Support OSR? return false; } if (broker()->is_turboprop() && feedback.slot_kind() == FeedbackSlotKind::kCall) { return false; } if (feedback.IsInsufficient()) { environment()->Kill(); return true; } return false; } Hints SerializerForBackgroundCompilation::Run() { TraceScope tracer(broker(), this, "SerializerForBackgroundCompilation::Run"); if (nesting_level_ >= FLAG_max_serializer_nesting) { TRACE_BROKER_MISSING( broker(), "opportunity - Reached max nesting level for " "SerializerForBackgroundCompilation::Run, bailing out.\n"); return Hints(); } TRACE_BROKER_MEMORY(broker(), "[serializer start] Broker zone usage: " << broker()->zone()->allocation_size()); SharedFunctionInfoRef shared(broker(), function().shared()); FeedbackVectorRef feedback_vector_ref(broker(), feedback_vector()); if (!broker()->ShouldBeSerializedForCompilation(shared, feedback_vector_ref, arguments_)) { TRACE_BROKER(broker(), "opportunity - Already ran serializer for SharedFunctionInfo " << Brief(*shared.object()) << ", bailing out.\n"); return Hints(); } { HintsVector arguments_copy_in_broker_zone(broker()->zone()); for (auto const& hints : arguments_) { arguments_copy_in_broker_zone.push_back( hints.CopyToParentZone(broker()->zone(), broker())); } broker()->SetSerializedForCompilation(shared, feedback_vector_ref, arguments_copy_in_broker_zone); } // We eagerly call the {EnsureSourcePositionsAvailable} for all serialized // SFIs while still on the main thread. Source positions will later be used // by JSInliner::ReduceJSCall. if (flags() & SerializerForBackgroundCompilationFlag::kCollectSourcePositions) { SharedFunctionInfo::EnsureSourcePositionsAvailable(broker()->isolate(), shared.object()); } feedback_vector_ref.Serialize(); TraverseBytecode(); if (return_value_hints().IsEmpty()) { TRACE_BROKER(broker(), "Return value hints: none"); } else { TRACE_BROKER(broker(), "Return value hints: " << return_value_hints()); } TRACE_BROKER_MEMORY(broker(), "[serializer end] Broker zone usage: " << broker()->zone()->allocation_size()); return return_value_hints(); } class HandlerRangeMatcher { public: HandlerRangeMatcher(BytecodeArrayIterator const& bytecode_iterator, Handle<BytecodeArray> bytecode_array) : bytecode_iterator_(bytecode_iterator) { HandlerTable table(*bytecode_array); for (int i = 0, n = table.NumberOfRangeEntries(); i < n; ++i) { ranges_.insert({table.GetRangeStart(i), table.GetRangeEnd(i), table.GetRangeHandler(i)}); } ranges_iterator_ = ranges_.cbegin(); } using OffsetReporter = std::function<void(int handler_offset)>; void HandlerOffsetForCurrentPosition(const OffsetReporter& offset_reporter) { CHECK(!bytecode_iterator_.done()); const int current_offset = bytecode_iterator_.current_offset(); // Remove outdated try ranges from the stack. while (!stack_.empty()) { const int end = stack_.top().end; if (end < current_offset) { stack_.pop(); } else { break; } } // Advance the iterator and maintain the stack. while (ranges_iterator_ != ranges_.cend() && ranges_iterator_->start <= current_offset) { if (ranges_iterator_->end >= current_offset) { stack_.push(*ranges_iterator_); if (ranges_iterator_->start == current_offset) { offset_reporter(ranges_iterator_->handler); } } ranges_iterator_++; } if (!stack_.empty() && stack_.top().start < current_offset) { offset_reporter(stack_.top().handler); } } private: BytecodeArrayIterator const& bytecode_iterator_; struct Range { int start; int end; int handler; friend bool operator<(const Range& a, const Range& b) { if (a.start < b.start) return true; if (a.start == b.start) { if (a.end < b.end) return true; CHECK_GT(a.end, b.end); } return false; } }; std::set<Range> ranges_; std::set<Range>::const_iterator ranges_iterator_; std::stack<Range> stack_; }; Handle<FeedbackVector> SerializerForBackgroundCompilation::feedback_vector() const { return function().feedback_vector(); } Handle<BytecodeArray> SerializerForBackgroundCompilation::bytecode_array() const { return handle(function().shared()->GetBytecodeArray(), broker()->isolate()); } BytecodeAnalysis const& SerializerForBackgroundCompilation::GetBytecodeAnalysis( SerializationPolicy policy) { return broker()->GetBytecodeAnalysis( bytecode_array(), osr_offset(), flags() & SerializerForBackgroundCompilationFlag::kAnalyzeEnvironmentLiveness, policy); } void SerializerForBackgroundCompilation::TraverseBytecode() { BytecodeAnalysis const& bytecode_analysis = GetBytecodeAnalysis(SerializationPolicy::kSerializeIfNeeded); BytecodeArrayRef(broker(), bytecode_array()).SerializeForCompilation(); BytecodeArrayIterator iterator(bytecode_array()); HandlerRangeMatcher try_start_matcher(iterator, bytecode_array()); bool has_one_shot_bytecode = false; for (; !iterator.done(); iterator.Advance()) { has_one_shot_bytecode = has_one_shot_bytecode || interpreter::Bytecodes::IsOneShotBytecode(iterator.current_bytecode()); int const current_offset = iterator.current_offset(); // TODO(mvstanton): we might want to ignore the current environment if we // are at the start of a catch handler. IncorporateJumpTargetEnvironment(current_offset); TRACE_BROKER(broker(), "Handling bytecode: " << current_offset << " " << iterator.current_bytecode()); TRACE_BROKER(broker(), "Current environment: " << *environment()); if (environment()->IsDead()) { continue; // Skip this bytecode since TF won't generate code for it. } auto save_handler_environments = [&](int handler_offset) { auto it = jump_target_environments_.find(handler_offset); if (it == jump_target_environments_.end()) { ContributeToJumpTargetEnvironment(handler_offset); TRACE_BROKER(broker(), "Handler offset for current pos: " << handler_offset); } }; try_start_matcher.HandlerOffsetForCurrentPosition( save_handler_environments); if (bytecode_analysis.IsLoopHeader(current_offset)) { // Graph builder might insert jumps to resume targets in the loop body. LoopInfo const& loop_info = bytecode_analysis.GetLoopInfoFor(current_offset); for (const auto& target : loop_info.resume_jump_targets()) { ContributeToJumpTargetEnvironment(target.target_offset()); } } switch (iterator.current_bytecode()) { #define DEFINE_BYTECODE_CASE(name) \ case interpreter::Bytecode::k##name: \ Visit##name(&iterator); \ break; SUPPORTED_BYTECODE_LIST(DEFINE_BYTECODE_CASE) #undef DEFINE_BYTECODE_CASE } } if (has_one_shot_bytecode) { broker()->isolate()->CountUsage( v8::Isolate::UseCounterFeature::kOptimizedFunctionWithOneShotBytecode); } } void SerializerForBackgroundCompilation::VisitGetIterator( BytecodeArrayIterator* iterator) { Hints* receiver = &register_hints(iterator->GetRegisterOperand(0)); FeedbackSlot load_slot = iterator->GetSlotOperand(1); FeedbackSlot call_slot = iterator->GetSlotOperand(2); Handle<Name> name = broker()->isolate()->factory()->iterator_symbol(); ProcessNamedPropertyAccess(receiver, NameRef(broker(), name), load_slot, AccessMode::kLoad); if (environment()->IsDead()) return; Hints callee; HintsVector args = PrepareArgumentsHints(receiver); ProcessCallOrConstruct(callee, base::nullopt, &args, call_slot, kMissingArgumentsAreUndefined); } void SerializerForBackgroundCompilation::VisitGetSuperConstructor( BytecodeArrayIterator* iterator) { interpreter::Register dst = iterator->GetRegisterOperand(0); Hints result_hints; for (auto constant : environment()->accumulator_hints().constants()) { // For JSNativeContextSpecialization::ReduceJSGetSuperConstructor. if (!constant->IsJSFunction()) continue; MapRef map(broker(), handle(HeapObject::cast(*constant).map(), broker()->isolate())); map.SerializePrototype(); ObjectRef proto = map.prototype(); if (proto.IsHeapObject() && proto.AsHeapObject().map().is_constructor()) { result_hints.AddConstant(proto.object(), zone(), broker()); } } register_hints(dst) = result_hints; } void SerializerForBackgroundCompilation::VisitGetTemplateObject( BytecodeArrayIterator* iterator) { TemplateObjectDescriptionRef description( broker(), iterator->GetConstantForIndexOperand(0, broker()->isolate())); FeedbackSlot slot = iterator->GetSlotOperand(1); FeedbackSource source(feedback_vector(), slot); SharedFunctionInfoRef shared(broker(), function().shared()); JSArrayRef template_object = shared.GetTemplateObject( description, source, SerializationPolicy::kSerializeIfNeeded); environment()->accumulator_hints() = Hints::SingleConstant(template_object.object(), zone()); } void SerializerForBackgroundCompilation::VisitLdaTrue( BytecodeArrayIterator* iterator) { environment()->accumulator_hints() = Hints::SingleConstant( broker()->isolate()->factory()->true_value(), zone()); } void SerializerForBackgroundCompilation::VisitLdaFalse( BytecodeArrayIterator* iterator) { environment()->accumulator_hints() = Hints::SingleConstant( broker()->isolate()->factory()->false_value(), zone()); } void SerializerForBackgroundCompilation::VisitLdaTheHole( BytecodeArrayIterator* iterator) { environment()->accumulator_hints() = Hints::SingleConstant( broker()->isolate()->factory()->the_hole_value(), zone()); } void SerializerForBackgroundCompilation::VisitLdaUndefined( BytecodeArrayIterator* iterator) { environment()->accumulator_hints() = Hints::SingleConstant( broker()->isolate()->factory()->undefined_value(), zone()); } void SerializerForBackgroundCompilation::VisitLdaNull( BytecodeArrayIterator* iterator) { environment()->accumulator_hints() = Hints::SingleConstant( broker()->isolate()->factory()->null_value(), zone()); } void SerializerForBackgroundCompilation::VisitLdaZero( BytecodeArrayIterator* iterator) { environment()->accumulator_hints() = Hints::SingleConstant( handle(Smi::FromInt(0), broker()->isolate()), zone()); } void SerializerForBackgroundCompilation::VisitLdaSmi( BytecodeArrayIterator* iterator) { Handle<Smi> smi(Smi::FromInt(iterator->GetImmediateOperand(0)), broker()->isolate()); environment()->accumulator_hints() = Hints::SingleConstant(smi, zone()); } void SerializerForBackgroundCompilation::VisitInvokeIntrinsic( BytecodeArrayIterator* iterator) { Runtime::FunctionId functionId = iterator->GetIntrinsicIdOperand(0); // For JSNativeContextSpecialization::ReduceJSAsyncFunctionResolve and // JSNativeContextSpecialization::ReduceJSResolvePromise. switch (functionId) { case Runtime::kInlineAsyncFunctionResolve: { ObjectRef(broker(), broker()->isolate()->builtins()->builtin_handle( Builtins::kAsyncFunctionResolve)); interpreter::Register first_reg = iterator->GetRegisterOperand(1); size_t reg_count = iterator->GetRegisterCountOperand(2); CHECK_EQ(reg_count, 3); HintsVector args = PrepareArgumentsHints(first_reg, reg_count); Hints const& resolution_hints = args[1]; // The resolution object. ProcessHintsForPromiseResolve(resolution_hints); return; } case Runtime::kInlineAsyncGeneratorReject: case Runtime::kAsyncGeneratorReject: { ObjectRef(broker(), broker()->isolate()->builtins()->builtin_handle( Builtins::kAsyncGeneratorReject)); break; } case Runtime::kInlineAsyncGeneratorResolve: case Runtime::kAsyncGeneratorResolve: { ObjectRef(broker(), broker()->isolate()->builtins()->builtin_handle( Builtins::kAsyncGeneratorResolve)); break; } case Runtime::kInlineAsyncGeneratorYield: case Runtime::kAsyncGeneratorYield: { ObjectRef(broker(), broker()->isolate()->builtins()->builtin_handle( Builtins::kAsyncGeneratorYield)); break; } case Runtime::kInlineAsyncGeneratorAwaitUncaught: case Runtime::kAsyncGeneratorAwaitUncaught: { ObjectRef(broker(), broker()->isolate()->builtins()->builtin_handle( Builtins::kAsyncGeneratorAwaitUncaught)); break; } case Runtime::kInlineAsyncGeneratorAwaitCaught: case Runtime::kAsyncGeneratorAwaitCaught: { ObjectRef(broker(), broker()->isolate()->builtins()->builtin_handle( Builtins::kAsyncGeneratorAwaitCaught)); break; } case Runtime::kInlineAsyncFunctionAwaitUncaught: case Runtime::kAsyncFunctionAwaitUncaught: { ObjectRef(broker(), broker()->isolate()->builtins()->builtin_handle( Builtins::kAsyncFunctionAwaitUncaught)); break; } case Runtime::kInlineAsyncFunctionAwaitCaught: case Runtime::kAsyncFunctionAwaitCaught: { ObjectRef(broker(), broker()->isolate()->builtins()->builtin_handle( Builtins::kAsyncFunctionAwaitCaught)); break; } case Runtime::kInlineAsyncFunctionReject: case Runtime::kAsyncFunctionReject: { ObjectRef(broker(), broker()->isolate()->builtins()->builtin_handle( Builtins::kAsyncFunctionReject)); break; } case Runtime::kAsyncFunctionResolve: { ObjectRef(broker(), broker()->isolate()->builtins()->builtin_handle( Builtins::kAsyncFunctionResolve)); break; } case Runtime::kInlineCopyDataProperties: case Runtime::kCopyDataProperties: { ObjectRef(broker(), broker()->isolate()->builtins()->builtin_handle( Builtins::kCopyDataProperties)); break; } case Runtime::kInlineGetImportMetaObject: { Hints const& context_hints = environment()->current_context_hints(); for (auto x : context_hints.constants()) { ContextRef(broker(), x) .GetModule(SerializationPolicy::kSerializeIfNeeded) .Serialize(); } for (auto x : context_hints.virtual_contexts()) { ContextRef(broker(), x.context) .GetModule(SerializationPolicy::kSerializeIfNeeded) .Serialize(); } break; } default: { break; } } environment()->accumulator_hints() = Hints(); } void SerializerForBackgroundCompilation::VisitLdaConstant( BytecodeArrayIterator* iterator) { ObjectRef object( broker(), iterator->GetConstantForIndexOperand(0, broker()->isolate())); environment()->accumulator_hints() = Hints::SingleConstant(object.object(), zone()); } void SerializerForBackgroundCompilation::VisitPushContext( BytecodeArrayIterator* iterator) { register_hints(iterator->GetRegisterOperand(0)) .Reset(&environment()->current_context_hints(), zone()); environment()->current_context_hints().Reset( &environment()->accumulator_hints(), zone()); } void SerializerForBackgroundCompilation::VisitPopContext( BytecodeArrayIterator* iterator) { environment()->current_context_hints().Reset( &register_hints(iterator->GetRegisterOperand(0)), zone()); } void SerializerForBackgroundCompilation::ProcessImmutableLoad( ContextRef const& context_ref, int slot, ContextProcessingMode mode, Hints* result_hints) { DCHECK_EQ(mode, kSerializeSlot); base::Optional<ObjectRef> slot_value = context_ref.get(slot, SerializationPolicy::kSerializeIfNeeded); // If requested, record the object as a hint for the result value. if (result_hints != nullptr && slot_value.has_value()) { result_hints->AddConstant(slot_value.value().object(), zone(), broker()); } } void SerializerForBackgroundCompilation::ProcessContextAccess( Hints const& context_hints, int slot, int depth, ContextProcessingMode mode, Hints* result_hints) { // This function is for JSContextSpecialization::ReduceJSLoadContext and // ReduceJSStoreContext. Those reductions attempt to eliminate as many // loads as possible by making use of constant Context objects. In the // case of an immutable load, ReduceJSLoadContext even attempts to load // the value at {slot}, replacing the load with a constant. for (auto x : context_hints.constants()) { if (x->IsContext()) { // Walk this context to the given depth and serialize the slot found. ContextRef context_ref(broker(), x); size_t remaining_depth = depth; context_ref = context_ref.previous( &remaining_depth, SerializationPolicy::kSerializeIfNeeded); if (remaining_depth == 0 && mode != kIgnoreSlot) { ProcessImmutableLoad(context_ref, slot, mode, result_hints); } } } for (auto x : context_hints.virtual_contexts()) { if (x.distance <= static_cast<unsigned int>(depth)) { ContextRef context_ref(broker(), x.context); size_t remaining_depth = depth - x.distance; context_ref = context_ref.previous( &remaining_depth, SerializationPolicy::kSerializeIfNeeded); if (remaining_depth == 0 && mode != kIgnoreSlot) { ProcessImmutableLoad(context_ref, slot, mode, result_hints); } } } } void SerializerForBackgroundCompilation::VisitLdaContextSlot( BytecodeArrayIterator* iterator) { Hints const& context_hints = register_hints(iterator->GetRegisterOperand(0)); const int slot = iterator->GetIndexOperand(1); const int depth = iterator->GetUnsignedImmediateOperand(2); Hints new_accumulator_hints; ProcessContextAccess(context_hints, slot, depth, kIgnoreSlot, &new_accumulator_hints); environment()->accumulator_hints() = new_accumulator_hints; } void SerializerForBackgroundCompilation::VisitLdaCurrentContextSlot( BytecodeArrayIterator* iterator) { const int slot = iterator->GetIndexOperand(0); const int depth = 0; Hints const& context_hints = environment()->current_context_hints(); Hints new_accumulator_hints; ProcessContextAccess(context_hints, slot, depth, kIgnoreSlot, &new_accumulator_hints); environment()->accumulator_hints() = new_accumulator_hints; } void SerializerForBackgroundCompilation::VisitLdaImmutableContextSlot( BytecodeArrayIterator* iterator) { const int slot = iterator->GetIndexOperand(1); const int depth = iterator->GetUnsignedImmediateOperand(2); Hints const& context_hints = register_hints(iterator->GetRegisterOperand(0)); Hints new_accumulator_hints; ProcessContextAccess(context_hints, slot, depth, kSerializeSlot, &new_accumulator_hints); environment()->accumulator_hints() = new_accumulator_hints; } void SerializerForBackgroundCompilation::VisitLdaImmutableCurrentContextSlot( BytecodeArrayIterator* iterator) { const int slot = iterator->GetIndexOperand(0); const int depth = 0; Hints const& context_hints = environment()->current_context_hints(); Hints new_accumulator_hints; ProcessContextAccess(context_hints, slot, depth, kSerializeSlot, &new_accumulator_hints); environment()->accumulator_hints() = new_accumulator_hints; } void SerializerForBackgroundCompilation::ProcessModuleVariableAccess( BytecodeArrayIterator* iterator) { const int slot = Context::EXTENSION_INDEX; const int depth = iterator->GetUnsignedImmediateOperand(1); Hints const& context_hints = environment()->current_context_hints(); Hints result_hints; ProcessContextAccess(context_hints, slot, depth, kSerializeSlot, &result_hints); for (Handle<Object> constant : result_hints.constants()) { ObjectRef object(broker(), constant); // For JSTypedLowering::BuildGetModuleCell. if (object.IsSourceTextModule()) object.AsSourceTextModule().Serialize(); } } void SerializerForBackgroundCompilation::VisitLdaModuleVariable( BytecodeArrayIterator* iterator) { ProcessModuleVariableAccess(iterator); } void SerializerForBackgroundCompilation::VisitStaModuleVariable( BytecodeArrayIterator* iterator) { ProcessModuleVariableAccess(iterator); } void SerializerForBackgroundCompilation::VisitStaLookupSlot( BytecodeArrayIterator* iterator) { ObjectRef(broker(), iterator->GetConstantForIndexOperand(0, broker()->isolate())); environment()->accumulator_hints() = Hints(); } void SerializerForBackgroundCompilation::VisitStaContextSlot( BytecodeArrayIterator* iterator) { const int slot = iterator->GetIndexOperand(1); const int depth = iterator->GetUnsignedImmediateOperand(2); Hints const& hints = register_hints(iterator->GetRegisterOperand(0)); ProcessContextAccess(hints, slot, depth, kIgnoreSlot); } void SerializerForBackgroundCompilation::VisitStaCurrentContextSlot( BytecodeArrayIterator* iterator) { const int slot = iterator->GetIndexOperand(0); const int depth = 0; Hints const& context_hints = environment()->current_context_hints(); ProcessContextAccess(context_hints, slot, depth, kIgnoreSlot); } void SerializerForBackgroundCompilation::VisitLdar( BytecodeArrayIterator* iterator) { environment()->accumulator_hints().Reset( &register_hints(iterator->GetRegisterOperand(0)), zone()); } void SerializerForBackgroundCompilation::VisitStar( BytecodeArrayIterator* iterator) { interpreter::Register reg = iterator->GetRegisterOperand(0); register_hints(reg).Reset(&environment()->accumulator_hints(), zone()); } void SerializerForBackgroundCompilation::VisitMov( BytecodeArrayIterator* iterator) { interpreter::Register src = iterator->GetRegisterOperand(0); interpreter::Register dst = iterator->GetRegisterOperand(1); register_hints(dst).Reset(&register_hints(src), zone()); } void SerializerForBackgroundCompilation::VisitCreateRegExpLiteral( BytecodeArrayIterator* iterator) { Handle<String> constant_pattern = Handle<String>::cast( iterator->GetConstantForIndexOperand(0, broker()->isolate())); StringRef description(broker(), constant_pattern); FeedbackSlot slot = iterator->GetSlotOperand(1); FeedbackSource source(feedback_vector(), slot); broker()->ProcessFeedbackForRegExpLiteral(source); environment()->accumulator_hints() = Hints(); } void SerializerForBackgroundCompilation::VisitCreateArrayLiteral( BytecodeArrayIterator* iterator) { Handle<ArrayBoilerplateDescription> array_boilerplate_description = Handle<ArrayBoilerplateDescription>::cast( iterator->GetConstantForIndexOperand(0, broker()->isolate())); ArrayBoilerplateDescriptionRef description(broker(), array_boilerplate_description); FeedbackSlot slot = iterator->GetSlotOperand(1); FeedbackSource source(feedback_vector(), slot); broker()->ProcessFeedbackForArrayOrObjectLiteral(source); environment()->accumulator_hints() = Hints(); } void SerializerForBackgroundCompilation::VisitCreateEmptyArrayLiteral( BytecodeArrayIterator* iterator) { FeedbackSlot slot = iterator->GetSlotOperand(0); FeedbackSource source(feedback_vector(), slot); broker()->ProcessFeedbackForArrayOrObjectLiteral(source); environment()->accumulator_hints() = Hints(); } void SerializerForBackgroundCompilation::VisitCreateObjectLiteral( BytecodeArrayIterator* iterator) { Handle<ObjectBoilerplateDescription> constant_properties = Handle<ObjectBoilerplateDescription>::cast( iterator->GetConstantForIndexOperand(0, broker()->isolate())); ObjectBoilerplateDescriptionRef description(broker(), constant_properties); FeedbackSlot slot = iterator->GetSlotOperand(1); FeedbackSource source(feedback_vector(), slot); broker()->ProcessFeedbackForArrayOrObjectLiteral(source); environment()->accumulator_hints() = Hints(); } void SerializerForBackgroundCompilation::VisitCreateFunctionContext( BytecodeArrayIterator* iterator) { ProcessCreateContext(iterator, 0); } void SerializerForBackgroundCompilation::VisitCreateBlockContext( BytecodeArrayIterator* iterator) { ProcessCreateContext(iterator, 0); } void SerializerForBackgroundCompilation::VisitCreateEvalContext( BytecodeArrayIterator* iterator) { ProcessCreateContext(iterator, 0); } void SerializerForBackgroundCompilation::VisitCreateWithContext( BytecodeArrayIterator* iterator) { ProcessCreateContext(iterator, 1); } void SerializerForBackgroundCompilation::VisitCreateCatchContext( BytecodeArrayIterator* iterator) { ProcessCreateContext(iterator, 1); } void SerializerForBackgroundCompilation::VisitForInNext( BytecodeArrayIterator* iterator) { FeedbackSlot slot = iterator->GetSlotOperand(3); ProcessForIn(slot); } void SerializerForBackgroundCompilation::VisitForInPrepare( BytecodeArrayIterator* iterator) { FeedbackSlot slot = iterator->GetSlotOperand(1); ProcessForIn(slot); } void SerializerForBackgroundCompilation::ProcessCreateContext( interpreter::BytecodeArrayIterator* iterator, int scopeinfo_operand_index) { Handle<ScopeInfo> scope_info = Handle<ScopeInfo>::cast(iterator->GetConstantForIndexOperand( scopeinfo_operand_index, broker()->isolate())); ScopeInfoRef scope_info_ref(broker(), scope_info); scope_info_ref.SerializeScopeInfoChain(); Hints const& current_context_hints = environment()->current_context_hints(); Hints result_hints; // For each constant context, we must create a virtual context from // it of distance one. for (auto x : current_context_hints.constants()) { if (x->IsContext()) { Handle<Context> as_context(Handle<Context>::cast(x)); result_hints.AddVirtualContext(VirtualContext(1, as_context), zone(), broker()); } } // For each virtual context, we must create a virtual context from // it of distance {existing distance} + 1. for (auto x : current_context_hints.virtual_contexts()) { result_hints.AddVirtualContext(VirtualContext(x.distance + 1, x.context), zone(), broker()); } environment()->accumulator_hints() = result_hints; } void SerializerForBackgroundCompilation::VisitCreateClosure( BytecodeArrayIterator* iterator) { Handle<SharedFunctionInfo> shared = Handle<SharedFunctionInfo>::cast( iterator->GetConstantForIndexOperand(0, broker()->isolate())); Handle<FeedbackCell> feedback_cell = feedback_vector()->GetClosureFeedbackCell(iterator->GetIndexOperand(1)); FeedbackCellRef feedback_cell_ref(broker(), feedback_cell); Handle<Object> cell_value(feedback_cell->value(), broker()->isolate()); ObjectRef cell_value_ref(broker(), cell_value); Hints result_hints; if (cell_value->IsFeedbackVector()) { VirtualClosure virtual_closure(shared, Handle<FeedbackVector>::cast(cell_value), environment()->current_context_hints()); result_hints.AddVirtualClosure(virtual_closure, zone(), broker()); } environment()->accumulator_hints() = result_hints; } void SerializerForBackgroundCompilation::VisitCallUndefinedReceiver( BytecodeArrayIterator* iterator) { Hints const& callee = register_hints(iterator->GetRegisterOperand(0)); interpreter::Register first_reg = iterator->GetRegisterOperand(1); int reg_count = static_cast<int>(iterator->GetRegisterCountOperand(2)); FeedbackSlot slot = iterator->GetSlotOperand(3); ProcessCallVarArgs(ConvertReceiverMode::kNullOrUndefined, callee, first_reg, reg_count, slot); } void SerializerForBackgroundCompilation::VisitCallUndefinedReceiver0( BytecodeArrayIterator* iterator) { Hints const& callee = register_hints(iterator->GetRegisterOperand(0)); FeedbackSlot slot = iterator->GetSlotOperand(1); Hints const receiver = Hints::SingleConstant( broker()->isolate()->factory()->undefined_value(), zone()); HintsVector parameters({receiver}, zone()); ProcessCallOrConstruct(callee, base::nullopt, &parameters, slot, kMissingArgumentsAreUndefined); } namespace { void PrepareArgumentsHintsInternal(Zone* zone, HintsVector* args) {} template <typename... MoreHints> void PrepareArgumentsHintsInternal(Zone* zone, HintsVector* args, Hints* hints, MoreHints... more) { hints->EnsureShareable(zone); args->push_back(*hints); PrepareArgumentsHintsInternal(zone, args, more...); } } // namespace template <typename... MoreHints> HintsVector SerializerForBackgroundCompilation::PrepareArgumentsHints( Hints* hints, MoreHints... more) { HintsVector args(zone()); PrepareArgumentsHintsInternal(zone(), &args, hints, more...); return args; } HintsVector SerializerForBackgroundCompilation::PrepareArgumentsHints( interpreter::Register first, size_t count) { HintsVector result(zone()); const int reg_base = first.index(); for (int i = 0; i < static_cast<int>(count); ++i) { Hints& hints = register_hints(interpreter::Register(reg_base + i)); hints.EnsureShareable(zone()); result.push_back(hints); } return result; } void SerializerForBackgroundCompilation::VisitCallUndefinedReceiver1( BytecodeArrayIterator* iterator) { Hints const& callee = register_hints(iterator->GetRegisterOperand(0)); Hints* arg0 = &register_hints(iterator->GetRegisterOperand(1)); FeedbackSlot slot = iterator->GetSlotOperand(2); Hints receiver = Hints::SingleConstant( broker()->isolate()->factory()->undefined_value(), zone()); HintsVector args = PrepareArgumentsHints(&receiver, arg0); ProcessCallOrConstruct(callee, base::nullopt, &args, slot, kMissingArgumentsAreUndefined); } void SerializerForBackgroundCompilation::VisitCallUndefinedReceiver2( BytecodeArrayIterator* iterator) { Hints const& callee = register_hints(iterator->GetRegisterOperand(0)); Hints* arg0 = &register_hints(iterator->GetRegisterOperand(1)); Hints* arg1 = &register_hints(iterator->GetRegisterOperand(2)); FeedbackSlot slot = iterator->GetSlotOperand(3); Hints receiver = Hints::SingleConstant( broker()->isolate()->factory()->undefined_value(), zone()); HintsVector args = PrepareArgumentsHints(&receiver, arg0, arg1); ProcessCallOrConstruct(callee, base::nullopt, &args, slot, kMissingArgumentsAreUndefined); } void SerializerForBackgroundCompilation::VisitCallAnyReceiver( BytecodeArrayIterator* iterator) { Hints const& callee = register_hints(iterator->GetRegisterOperand(0)); interpreter::Register first_reg = iterator->GetRegisterOperand(1); int reg_count = static_cast<int>(iterator->GetRegisterCountOperand(2)); FeedbackSlot slot = iterator->GetSlotOperand(3); ProcessCallVarArgs(ConvertReceiverMode::kAny, callee, first_reg, reg_count, slot); } void SerializerForBackgroundCompilation::VisitCallNoFeedback( BytecodeArrayIterator* iterator) { Hints const& callee = register_hints(iterator->GetRegisterOperand(0)); interpreter::Register first_reg = iterator->GetRegisterOperand(1); int reg_count = static_cast<int>(iterator->GetRegisterCountOperand(2)); ProcessCallVarArgs(ConvertReceiverMode::kAny, callee, first_reg, reg_count, FeedbackSlot::Invalid()); } void SerializerForBackgroundCompilation::VisitCallProperty( BytecodeArrayIterator* iterator) { Hints const& callee = register_hints(iterator->GetRegisterOperand(0)); interpreter::Register first_reg = iterator->GetRegisterOperand(1); int reg_count = static_cast<int>(iterator->GetRegisterCountOperand(2)); FeedbackSlot slot = iterator->GetSlotOperand(3); ProcessCallVarArgs(ConvertReceiverMode::kNotNullOrUndefined, callee, first_reg, reg_count, slot); } void SerializerForBackgroundCompilation::VisitCallProperty0( BytecodeArrayIterator* iterator) { Hints const& callee = register_hints(iterator->GetRegisterOperand(0)); Hints* receiver = &register_hints(iterator->GetRegisterOperand(1)); FeedbackSlot slot = iterator->GetSlotOperand(2); HintsVector args = PrepareArgumentsHints(receiver); ProcessCallOrConstruct(callee, base::nullopt, &args, slot, kMissingArgumentsAreUndefined); } void SerializerForBackgroundCompilation::VisitCallProperty1( BytecodeArrayIterator* iterator) { Hints const& callee = register_hints(iterator->GetRegisterOperand(0)); Hints* receiver = &register_hints(iterator->GetRegisterOperand(1)); Hints* arg0 = &register_hints(iterator->GetRegisterOperand(2)); FeedbackSlot slot = iterator->GetSlotOperand(3); HintsVector args = PrepareArgumentsHints(receiver, arg0); ProcessCallOrConstruct(callee, base::nullopt, &args, slot, kMissingArgumentsAreUndefined); } void SerializerForBackgroundCompilation::VisitCallProperty2( BytecodeArrayIterator* iterator) { Hints const& callee = register_hints(iterator->GetRegisterOperand(0)); Hints* receiver = &register_hints(iterator->GetRegisterOperand(1)); Hints* arg0 = &register_hints(iterator->GetRegisterOperand(2)); Hints* arg1 = &register_hints(iterator->GetRegisterOperand(3)); FeedbackSlot slot = iterator->GetSlotOperand(4); HintsVector args = PrepareArgumentsHints(receiver, arg0, arg1); ProcessCallOrConstruct(callee, base::nullopt, &args, slot, kMissingArgumentsAreUndefined); } void SerializerForBackgroundCompilation::VisitCallWithSpread( BytecodeArrayIterator* iterator) { Hints const& callee = register_hints(iterator->GetRegisterOperand(0)); interpreter::Register first_reg = iterator->GetRegisterOperand(1); int reg_count = static_cast<int>(iterator->GetRegisterCountOperand(2)); FeedbackSlot slot = iterator->GetSlotOperand(3); ProcessCallVarArgs(ConvertReceiverMode::kAny, callee, first_reg, reg_count, slot, kMissingArgumentsAreUnknown); } void SerializerForBackgroundCompilation::VisitCallJSRuntime( BytecodeArrayIterator* iterator) { const int runtime_index = iterator->GetNativeContextIndexOperand(0); ObjectRef constant = broker() ->target_native_context() .get(runtime_index, SerializationPolicy::kSerializeIfNeeded) .value(); Hints const callee = Hints::SingleConstant(constant.object(), zone()); interpreter::Register first_reg = iterator->GetRegisterOperand(1); int reg_count = static_cast<int>(iterator->GetRegisterCountOperand(2)); ProcessCallVarArgs(ConvertReceiverMode::kNullOrUndefined, callee, first_reg, reg_count, FeedbackSlot::Invalid()); } Hints SerializerForBackgroundCompilation::RunChildSerializer( CompilationSubject function, base::Optional<Hints> new_target, const HintsVector& arguments, MissingArgumentsPolicy padding) { SerializerForBackgroundCompilation child_serializer( zone_scope_.zone_stats(), broker(), dependencies(), function, new_target, arguments, padding, flags(), nesting_level_ + 1); Hints result = child_serializer.Run(); // The Hints returned by the call to Run are allocated in the zone // created by the child serializer. Adding those hints to a hints // object created in our zone will preserve the information. return result.CopyToParentZone(zone(), broker()); } void SerializerForBackgroundCompilation::ProcessCalleeForCallOrConstruct( Callee const& callee, base::Optional<Hints> new_target, const HintsVector& arguments, SpeculationMode speculation_mode, MissingArgumentsPolicy padding, Hints* result_hints) { Handle<SharedFunctionInfo> shared = callee.shared(broker()->isolate()); if (shared->IsApiFunction()) { ProcessApiCall(shared, arguments); DCHECK_NE(shared->GetInlineability(), SharedFunctionInfo::kIsInlineable); } else if (shared->HasBuiltinId()) { ProcessBuiltinCall(shared, new_target, arguments, speculation_mode, padding, result_hints); DCHECK_NE(shared->GetInlineability(), SharedFunctionInfo::kIsInlineable); } else if ((flags() & SerializerForBackgroundCompilationFlag::kEnableTurboInlining) && shared->GetInlineability() == SharedFunctionInfo::kIsInlineable && callee.HasFeedbackVector()) { CompilationSubject subject = callee.ToCompilationSubject(broker()->isolate(), zone()); result_hints->Add( RunChildSerializer(subject, new_target, arguments, padding), zone(), broker()); } } namespace { // Returns the innermost bound target and inserts all bound arguments and // {original_arguments} into {expanded_arguments} in the appropriate order. JSReceiverRef UnrollBoundFunction(JSBoundFunctionRef const& bound_function, JSHeapBroker* broker, const HintsVector& original_arguments, HintsVector* expanded_arguments, Zone* zone) { DCHECK(expanded_arguments->empty()); JSReceiverRef target = bound_function.AsJSReceiver(); HintsVector reversed_bound_arguments(zone); for (; target.IsJSBoundFunction(); target = target.AsJSBoundFunction().bound_target_function()) { for (int i = target.AsJSBoundFunction().bound_arguments().length() - 1; i >= 0; --i) { Hints const arg = Hints::SingleConstant( target.AsJSBoundFunction().bound_arguments().get(i).object(), zone); reversed_bound_arguments.push_back(arg); } Hints const arg = Hints::SingleConstant( target.AsJSBoundFunction().bound_this().object(), zone); reversed_bound_arguments.push_back(arg); } expanded_arguments->insert(expanded_arguments->end(), reversed_bound_arguments.rbegin(), reversed_bound_arguments.rend()); expanded_arguments->insert(expanded_arguments->end(), original_arguments.begin(), original_arguments.end()); return target; } } // namespace void SerializerForBackgroundCompilation::ProcessCalleeForCallOrConstruct( Handle<Object> callee, base::Optional<Hints> new_target, const HintsVector& arguments, SpeculationMode speculation_mode, MissingArgumentsPolicy padding, Hints* result_hints) { const HintsVector* actual_arguments = &arguments; HintsVector expanded_arguments(zone()); if (callee->IsJSBoundFunction()) { JSBoundFunctionRef bound_function(broker(), Handle<JSBoundFunction>::cast(callee)); if (!bound_function.Serialize()) return; callee = UnrollBoundFunction(bound_function, broker(), arguments, &expanded_arguments, zone()) .object(); actual_arguments = &expanded_arguments; } if (!callee->IsJSFunction()) return; JSFunctionRef function(broker(), Handle<JSFunction>::cast(callee)); function.Serialize(); Callee new_callee(function.object()); ProcessCalleeForCallOrConstruct(new_callee, new_target, *actual_arguments, speculation_mode, padding, result_hints); } void SerializerForBackgroundCompilation::ProcessCallOrConstruct( Hints callee, base::Optional<Hints> new_target, HintsVector* arguments, FeedbackSlot slot, MissingArgumentsPolicy padding) { SpeculationMode speculation_mode = SpeculationMode::kDisallowSpeculation; if (!slot.IsInvalid()) { FeedbackSource source(feedback_vector(), slot); ProcessedFeedback const& feedback = broker()->ProcessFeedbackForCall(source); if (BailoutOnUninitialized(feedback)) return; if (!feedback.IsInsufficient()) { // Incorporate feedback into hints copy to simplify processing. // TODO(neis): Modify the original hints instead? speculation_mode = feedback.AsCall().speculation_mode(); // Incorporate target feedback into hints copy to simplify processing. base::Optional<HeapObjectRef> target = feedback.AsCall().target(); if (target.has_value() && (target->map().is_callable() || target->IsFeedbackCell())) { callee = callee.Copy(zone()); // TODO(mvstanton): if the map isn't callable then we have an allocation // site, and it may make sense to add the Array JSFunction constant. if (new_target.has_value()) { // Construct; feedback is new_target, which often is also the callee. new_target = new_target->Copy(zone()); new_target->AddConstant(target->object(), zone(), broker()); callee.AddConstant(target->object(), zone(), broker()); } else { // Call; target is feedback cell or callee. if (target->IsFeedbackCell() && target->AsFeedbackCell().value().IsFeedbackVector()) { FeedbackVectorRef vector = target->AsFeedbackCell().value().AsFeedbackVector(); vector.Serialize(); VirtualClosure virtual_closure( vector.shared_function_info().object(), vector.object(), Hints()); callee.AddVirtualClosure(virtual_closure, zone(), broker()); } else { callee.AddConstant(target->object(), zone(), broker()); } } } } } Hints result_hints_from_new_target; if (new_target.has_value()) { ProcessNewTargetForConstruct(*new_target, &result_hints_from_new_target); // These hints are a good guess at the resulting object, so they are useful // for both the accumulator and the constructor call's receiver. The latter // is still missing completely in {arguments} so add it now. arguments->insert(arguments->begin(), result_hints_from_new_target); } // For JSNativeContextSpecialization::InferRootMap Hints new_accumulator_hints = result_hints_from_new_target.Copy(zone()); ProcessCallOrConstructRecursive(callee, new_target, *arguments, speculation_mode, padding, &new_accumulator_hints); environment()->accumulator_hints() = new_accumulator_hints; } void SerializerForBackgroundCompilation::ProcessCallOrConstructRecursive( Hints const& callee, base::Optional<Hints> new_target, const HintsVector& arguments, SpeculationMode speculation_mode, MissingArgumentsPolicy padding, Hints* result_hints) { // For JSCallReducer::ReduceJSCall and JSCallReducer::ReduceJSConstruct. for (auto constant : callee.constants()) { ProcessCalleeForCallOrConstruct(constant, new_target, arguments, speculation_mode, padding, result_hints); } // For JSCallReducer::ReduceJSCall and JSCallReducer::ReduceJSConstruct. for (auto hint : callee.virtual_closures()) { ProcessCalleeForCallOrConstruct(Callee(hint), new_target, arguments, speculation_mode, padding, result_hints); } for (auto hint : callee.virtual_bound_functions()) { HintsVector new_arguments = hint.bound_arguments; new_arguments.insert(new_arguments.end(), arguments.begin(), arguments.end()); ProcessCallOrConstructRecursive(hint.bound_target, new_target, new_arguments, speculation_mode, padding, result_hints); } } void SerializerForBackgroundCompilation::ProcessNewTargetForConstruct( Hints const& new_target_hints, Hints* result_hints) { for (Handle<Object> target : new_target_hints.constants()) { if (target->IsJSBoundFunction()) { // Unroll the bound function. while (target->IsJSBoundFunction()) { target = handle( Handle<JSBoundFunction>::cast(target)->bound_target_function(), broker()->isolate()); } } if (target->IsJSFunction()) { Handle<JSFunction> new_target(Handle<JSFunction>::cast(target)); if (new_target->has_prototype_slot(broker()->isolate()) && new_target->has_initial_map()) { result_hints->AddMap( handle(new_target->initial_map(), broker()->isolate()), zone(), broker()); } } } for (auto const& virtual_bound_function : new_target_hints.virtual_bound_functions()) { ProcessNewTargetForConstruct(virtual_bound_function.bound_target, result_hints); } } void SerializerForBackgroundCompilation::ProcessCallVarArgs( ConvertReceiverMode receiver_mode, Hints const& callee, interpreter::Register first_reg, int reg_count, FeedbackSlot slot, MissingArgumentsPolicy padding) { HintsVector args = PrepareArgumentsHints(first_reg, reg_count); // The receiver is either given in the first register or it is implicitly // the {undefined} value. if (receiver_mode == ConvertReceiverMode::kNullOrUndefined) { args.insert(args.begin(), Hints::SingleConstant( broker()->isolate()->factory()->undefined_value(), zone())); } ProcessCallOrConstruct(callee, base::nullopt, &args, slot, padding); } void SerializerForBackgroundCompilation::ProcessApiCall( Handle<SharedFunctionInfo> target, const HintsVector& arguments) { ObjectRef(broker(), broker()->isolate()->builtins()->builtin_handle( Builtins::kCallFunctionTemplate_CheckAccess)); ObjectRef(broker(), broker()->isolate()->builtins()->builtin_handle( Builtins::kCallFunctionTemplate_CheckCompatibleReceiver)); ObjectRef( broker(), broker()->isolate()->builtins()->builtin_handle( Builtins::kCallFunctionTemplate_CheckAccessAndCompatibleReceiver)); FunctionTemplateInfoRef target_template_info( broker(), handle(target->function_data(kAcquireLoad), broker()->isolate())); if (!target_template_info.has_call_code()) return; target_template_info.SerializeCallCode(); SharedFunctionInfoRef target_ref(broker(), target); target_ref.SerializeFunctionTemplateInfo(); if (target_template_info.accept_any_receiver() && target_template_info.is_signature_undefined()) { return; } if (arguments.empty()) return; Hints const& receiver_hints = arguments[0]; for (auto hint : receiver_hints.constants()) { if (hint->IsUndefined()) { // The receiver is the global proxy. Handle<JSGlobalProxy> global_proxy = broker()->target_native_context().global_proxy_object().object(); ProcessReceiverMapForApiCall( target_template_info, handle(global_proxy->map(), broker()->isolate())); continue; } if (!hint->IsJSReceiver()) continue; Handle<JSReceiver> receiver(Handle<JSReceiver>::cast(hint)); ProcessReceiverMapForApiCall(target_template_info, handle(receiver->map(), broker()->isolate())); } for (auto receiver_map : receiver_hints.maps()) { ProcessReceiverMapForApiCall(target_template_info, receiver_map); } } void SerializerForBackgroundCompilation::ProcessReceiverMapForApiCall( FunctionTemplateInfoRef target, Handle<Map> receiver) { if (!receiver->is_access_check_needed()) { MapRef receiver_map(broker(), receiver); TRACE_BROKER(broker(), "Serializing holder for target: " << target); target.LookupHolderOfExpectedType(receiver_map, SerializationPolicy::kSerializeIfNeeded); } } void SerializerForBackgroundCompilation::ProcessHintsForObjectCreate( Hints const& prototype) { for (Handle<Object> constant_handle : prototype.constants()) { ObjectRef constant(broker(), constant_handle); if (constant.IsJSObject()) constant.AsJSObject().SerializeObjectCreateMap(); } } void SerializerForBackgroundCompilation::ProcessBuiltinCall( Handle<SharedFunctionInfo> target, base::Optional<Hints> new_target, const HintsVector& arguments, SpeculationMode speculation_mode, MissingArgumentsPolicy padding, Hints* result_hints) { DCHECK(target->HasBuiltinId()); const int builtin_id = target->builtin_id(); const char* name = Builtins::name(builtin_id); TRACE_BROKER(broker(), "Serializing for call to builtin " << name); switch (builtin_id) { case Builtins::kObjectCreate: { if (arguments.size() >= 2) { ProcessHintsForObjectCreate(arguments[1]); } else { ProcessHintsForObjectCreate(Hints::SingleConstant( broker()->isolate()->factory()->undefined_value(), zone())); } break; } case Builtins::kPromisePrototypeCatch: { // For JSCallReducer::ReducePromisePrototypeCatch. if (speculation_mode != SpeculationMode::kDisallowSpeculation) { if (arguments.size() >= 1) { ProcessMapHintsForPromises(arguments[0]); } } break; } case Builtins::kPromisePrototypeFinally: { // For JSCallReducer::ReducePromisePrototypeFinally. if (speculation_mode != SpeculationMode::kDisallowSpeculation) { if (arguments.size() >= 1) { ProcessMapHintsForPromises(arguments[0]); } SharedFunctionInfoRef( broker(), broker()->isolate()->factory()->promise_catch_finally_shared_fun()); SharedFunctionInfoRef( broker(), broker()->isolate()->factory()->promise_then_finally_shared_fun()); } break; } case Builtins::kPromisePrototypeThen: { // For JSCallReducer::ReducePromisePrototypeThen. if (speculation_mode != SpeculationMode::kDisallowSpeculation) { if (arguments.size() >= 1) { ProcessMapHintsForPromises(arguments[0]); } } break; } case Builtins::kPromiseResolveTrampoline: // For JSCallReducer::ReducePromiseInternalResolve and // JSNativeContextSpecialization::ReduceJSResolvePromise. if (arguments.size() >= 1) { Hints const resolution_hints = arguments.size() >= 2 ? arguments[1] : Hints::SingleConstant( broker()->isolate()->factory()->undefined_value(), zone()); ProcessHintsForPromiseResolve(resolution_hints); } break; case Builtins::kRegExpPrototypeTest: case Builtins::kRegExpPrototypeTestFast: // For JSCallReducer::ReduceRegExpPrototypeTest. if (arguments.size() >= 1 && speculation_mode != SpeculationMode::kDisallowSpeculation) { Hints const& regexp_hints = arguments[0]; ProcessHintsForRegExpTest(regexp_hints); } break; case Builtins::kArrayEvery: case Builtins::kArrayFilter: case Builtins::kArrayForEach: case Builtins::kArrayPrototypeFind: case Builtins::kArrayPrototypeFindIndex: case Builtins::kArrayMap: case Builtins::kArraySome: if (arguments.size() >= 2 && speculation_mode != SpeculationMode::kDisallowSpeculation) { Hints const& callback = arguments[1]; // "Call(callbackfn, T, « kValue, k, O »)" HintsVector new_arguments(zone()); new_arguments.push_back( arguments.size() < 3 ? Hints::SingleConstant( broker()->isolate()->factory()->undefined_value(), zone()) : arguments[2]); // T new_arguments.push_back(Hints()); // kValue new_arguments.push_back(Hints()); // k new_arguments.push_back(arguments[0]); // O for (auto constant : callback.constants()) { ProcessCalleeForCallOrConstruct( constant, base::nullopt, new_arguments, speculation_mode, kMissingArgumentsAreUndefined, result_hints); } for (auto virtual_closure : callback.virtual_closures()) { ProcessCalleeForCallOrConstruct( Callee(virtual_closure), base::nullopt, new_arguments, speculation_mode, kMissingArgumentsAreUndefined, result_hints); } } break; case Builtins::kArrayReduce: case Builtins::kArrayReduceRight: if (arguments.size() >= 2 && speculation_mode != SpeculationMode::kDisallowSpeculation) { Hints const& callback = arguments[1]; // "Call(callbackfn, undefined, « accumulator, kValue, k, O »)" HintsVector new_arguments(zone()); new_arguments.push_back(Hints::SingleConstant( broker()->isolate()->factory()->undefined_value(), zone())); new_arguments.push_back(Hints()); // accumulator new_arguments.push_back(Hints()); // kValue new_arguments.push_back(Hints()); // k new_arguments.push_back(arguments[0]); // O for (auto constant : callback.constants()) { ProcessCalleeForCallOrConstruct( constant, base::nullopt, new_arguments, speculation_mode, kMissingArgumentsAreUndefined, result_hints); } for (auto virtual_closure : callback.virtual_closures()) { ProcessCalleeForCallOrConstruct( Callee(virtual_closure), base::nullopt, new_arguments, speculation_mode, kMissingArgumentsAreUndefined, result_hints); } } break; case Builtins::kFunctionPrototypeApply: if (arguments.size() >= 1) { // Drop hints for all arguments except the user-given receiver. Hints const new_receiver = arguments.size() >= 2 ? arguments[1] : Hints::SingleConstant( broker()->isolate()->factory()->undefined_value(), zone()); HintsVector new_arguments({new_receiver}, zone()); for (auto constant : arguments[0].constants()) { ProcessCalleeForCallOrConstruct( constant, base::nullopt, new_arguments, speculation_mode, kMissingArgumentsAreUnknown, result_hints); } for (auto const& virtual_closure : arguments[0].virtual_closures()) { ProcessCalleeForCallOrConstruct( Callee(virtual_closure), base::nullopt, new_arguments, speculation_mode, kMissingArgumentsAreUnknown, result_hints); } } break; case Builtins::kPromiseConstructor: if (arguments.size() >= 1) { // "Call(executor, undefined, « resolvingFunctions.[[Resolve]], // resolvingFunctions.[[Reject]] »)" HintsVector new_arguments( {Hints::SingleConstant( broker()->isolate()->factory()->undefined_value(), zone())}, zone()); for (auto constant : arguments[0].constants()) { ProcessCalleeForCallOrConstruct( constant, base::nullopt, new_arguments, SpeculationMode::kDisallowSpeculation, kMissingArgumentsAreUnknown, result_hints); } for (auto const& virtual_closure : arguments[0].virtual_closures()) { ProcessCalleeForCallOrConstruct( Callee(virtual_closure), base::nullopt, new_arguments, SpeculationMode::kDisallowSpeculation, kMissingArgumentsAreUnknown, result_hints); } } SharedFunctionInfoRef( broker(), broker() ->isolate() ->factory() ->promise_capability_default_reject_shared_fun()); SharedFunctionInfoRef( broker(), broker() ->isolate() ->factory() ->promise_capability_default_resolve_shared_fun()); break; case Builtins::kFunctionPrototypeCall: if (arguments.size() >= 1) { HintsVector new_arguments(arguments.begin() + 1, arguments.end(), zone()); for (auto constant : arguments[0].constants()) { ProcessCalleeForCallOrConstruct(constant, base::nullopt, new_arguments, speculation_mode, padding, result_hints); } for (auto const& virtual_closure : arguments[0].virtual_closures()) { ProcessCalleeForCallOrConstruct( Callee(virtual_closure), base::nullopt, new_arguments, speculation_mode, padding, result_hints); } } break; case Builtins::kReflectApply: case Builtins::kReflectConstruct: if (arguments.size() >= 2) { for (auto constant : arguments[1].constants()) { if (constant->IsJSFunction()) { JSFunctionRef(broker(), constant).Serialize(); } } } break; case Builtins::kObjectPrototypeIsPrototypeOf: if (arguments.size() >= 2) { ProcessHintsForHasInPrototypeChain(arguments[1]); } break; case Builtins::kFunctionPrototypeHasInstance: // For JSCallReducer::ReduceFunctionPrototypeHasInstance. if (arguments.size() >= 2) { ProcessHintsForOrdinaryHasInstance(arguments[0], arguments[1]); } break; case Builtins::kFastFunctionPrototypeBind: if (arguments.size() >= 1 && speculation_mode != SpeculationMode::kDisallowSpeculation) { Hints const& bound_target = arguments[0]; ProcessHintsForFunctionBind(bound_target); HintsVector new_arguments(arguments.begin() + 1, arguments.end(), zone()); result_hints->AddVirtualBoundFunction( VirtualBoundFunction(bound_target, new_arguments), zone(), broker()); } break; case Builtins::kObjectGetPrototypeOf: case Builtins::kReflectGetPrototypeOf: if (arguments.size() >= 2) { ProcessHintsForObjectGetPrototype(arguments[1]); } else { Hints const undefined_hint = Hints::SingleConstant( broker()->isolate()->factory()->undefined_value(), zone()); ProcessHintsForObjectGetPrototype(undefined_hint); } break; case Builtins::kObjectPrototypeGetProto: if (arguments.size() >= 1) { ProcessHintsForObjectGetPrototype(arguments[0]); } break; case Builtins::kMapIteratorPrototypeNext: ObjectRef(broker(), broker()->isolate()->builtins()->builtin_handle( Builtins::kOrderedHashTableHealIndex)); ObjectRef(broker(), broker()->isolate()->factory()->empty_ordered_hash_map()); break; case Builtins::kSetIteratorPrototypeNext: ObjectRef(broker(), broker()->isolate()->builtins()->builtin_handle( Builtins::kOrderedHashTableHealIndex)); ObjectRef(broker(), broker()->isolate()->factory()->empty_ordered_hash_set()); break; default: break; } } void SerializerForBackgroundCompilation::ProcessHintsForOrdinaryHasInstance( Hints const& constructor_hints, Hints const& instance_hints) { bool walk_prototypes = false; for (Handle<Object> constructor : constructor_hints.constants()) { // For JSNativeContextSpecialization::ReduceJSOrdinaryHasInstance. if (constructor->IsHeapObject()) { ProcessConstantForOrdinaryHasInstance( HeapObjectRef(broker(), constructor), &walk_prototypes); } } // For JSNativeContextSpecialization::ReduceJSHasInPrototypeChain. if (walk_prototypes) ProcessHintsForHasInPrototypeChain(instance_hints); } void SerializerForBackgroundCompilation::ProcessHintsForHasInPrototypeChain( Hints const& instance_hints) { auto processMap = [&](Handle<Map> map_handle) { MapRef map(broker(), map_handle); while (map.IsJSObjectMap()) { map.SerializePrototype(); map = map.prototype().map(); } }; for (auto hint : instance_hints.constants()) { if (!hint->IsHeapObject()) continue; Handle<HeapObject> object(Handle<HeapObject>::cast(hint)); processMap(handle(object->map(), broker()->isolate())); } for (auto map_hint : instance_hints.maps()) { processMap(map_hint); } } void SerializerForBackgroundCompilation::ProcessHintsForPromiseResolve( Hints const& resolution_hints) { auto processMap = [&](Handle<Map> map) { broker()->GetPropertyAccessInfo( MapRef(broker(), map), NameRef(broker(), broker()->isolate()->factory()->then_string()), AccessMode::kLoad, dependencies(), SerializationPolicy::kSerializeIfNeeded); }; for (auto hint : resolution_hints.constants()) { if (!hint->IsHeapObject()) continue; Handle<HeapObject> resolution(Handle<HeapObject>::cast(hint)); processMap(handle(resolution->map(), broker()->isolate())); } for (auto map_hint : resolution_hints.maps()) { processMap(map_hint); } } void SerializerForBackgroundCompilation::ProcessMapHintsForPromises( Hints const& receiver_hints) { // We need to serialize the prototypes on each receiver map. for (auto constant : receiver_hints.constants()) { if (!constant->IsJSPromise()) continue; Handle<Map> map(Handle<HeapObject>::cast(constant)->map(), broker()->isolate()); MapRef(broker(), map).SerializePrototype(); } for (auto map : receiver_hints.maps()) { if (!map->IsJSPromiseMap()) continue; MapRef(broker(), map).SerializePrototype(); } } PropertyAccessInfo SerializerForBackgroundCompilation::ProcessMapForRegExpTest( MapRef map) { PropertyAccessInfo ai_exec = broker()->GetPropertyAccessInfo( map, NameRef(broker(), broker()->isolate()->factory()->exec_string()), AccessMode::kLoad, dependencies(), SerializationPolicy::kSerializeIfNeeded); Handle<JSObject> holder; if (ai_exec.IsDataConstant() && ai_exec.holder().ToHandle(&holder)) { // The property is on the prototype chain. JSObjectRef holder_ref(broker(), holder); holder_ref.GetOwnDataProperty(ai_exec.field_representation(), ai_exec.field_index(), SerializationPolicy::kSerializeIfNeeded); } return ai_exec; } void SerializerForBackgroundCompilation::ProcessHintsForRegExpTest( Hints const& regexp_hints) { for (auto hint : regexp_hints.constants()) { if (!hint->IsJSRegExp()) continue; Handle<JSRegExp> regexp(Handle<JSRegExp>::cast(hint)); Handle<Map> regexp_map(regexp->map(), broker()->isolate()); PropertyAccessInfo ai_exec = ProcessMapForRegExpTest(MapRef(broker(), regexp_map)); Handle<JSObject> holder; if (ai_exec.IsDataConstant() && !ai_exec.holder().ToHandle(&holder)) { // The property is on the object itself. JSObjectRef holder_ref(broker(), regexp); holder_ref.GetOwnDataProperty(ai_exec.field_representation(), ai_exec.field_index(), SerializationPolicy::kSerializeIfNeeded); } } for (auto map : regexp_hints.maps()) { if (!map->IsJSRegExpMap()) continue; ProcessMapForRegExpTest(MapRef(broker(), map)); } } namespace { void ProcessMapForFunctionBind(MapRef map) { map.SerializePrototype(); int min_nof_descriptors = std::max({JSFunction::kLengthDescriptorIndex, JSFunction::kNameDescriptorIndex}) + 1; if (map.NumberOfOwnDescriptors() >= min_nof_descriptors) { map.SerializeOwnDescriptor( InternalIndex(JSFunction::kLengthDescriptorIndex)); map.SerializeOwnDescriptor(InternalIndex(JSFunction::kNameDescriptorIndex)); } } } // namespace void SerializerForBackgroundCompilation::ProcessHintsForFunctionBind( Hints const& receiver_hints) { for (auto constant : receiver_hints.constants()) { if (!constant->IsJSFunction()) continue; JSFunctionRef function(broker(), constant); function.Serialize(); ProcessMapForFunctionBind(function.map()); } for (auto map : receiver_hints.maps()) { if (!map->IsJSFunctionMap()) continue; MapRef map_ref(broker(), map); ProcessMapForFunctionBind(map_ref); } } void SerializerForBackgroundCompilation::ProcessHintsForObjectGetPrototype( Hints const& object_hints) { for (auto constant : object_hints.constants()) { if (!constant->IsHeapObject()) continue; HeapObjectRef object(broker(), constant); object.map().SerializePrototype(); } for (auto map : object_hints.maps()) { MapRef map_ref(broker(), map); map_ref.SerializePrototype(); } } void SerializerForBackgroundCompilation::ContributeToJumpTargetEnvironment( int target_offset) { auto it = jump_target_environments_.find(target_offset); if (it == jump_target_environments_.end()) { jump_target_environments_[target_offset] = zone()->New<Environment>(*environment()); } else { it->second->Merge(environment(), zone(), broker()); } } void SerializerForBackgroundCompilation::IncorporateJumpTargetEnvironment( int target_offset) { auto it = jump_target_environments_.find(target_offset); if (it != jump_target_environments_.end()) { environment()->Merge(it->second, zone(), broker()); jump_target_environments_.erase(it); } } void SerializerForBackgroundCompilation::ProcessJump( interpreter::BytecodeArrayIterator* iterator) { int jump_target = iterator->GetJumpTargetOffset(); if (iterator->current_offset() < jump_target) { ContributeToJumpTargetEnvironment(jump_target); } } void SerializerForBackgroundCompilation::VisitReturn( BytecodeArrayIterator* iterator) { return_value_hints().Add(environment()->accumulator_hints(), zone(), broker()); environment()->Kill(); } void SerializerForBackgroundCompilation::VisitSwitchOnSmiNoFeedback( interpreter::BytecodeArrayIterator* iterator) { interpreter::JumpTableTargetOffsets targets = iterator->GetJumpTableTargetOffsets(); for (const auto& target : targets) { ContributeToJumpTargetEnvironment(target.target_offset); } } void SerializerForBackgroundCompilation::VisitSwitchOnGeneratorState( interpreter::BytecodeArrayIterator* iterator) { for (const auto& target : GetBytecodeAnalysis().resume_jump_targets()) { ContributeToJumpTargetEnvironment(target.target_offset()); } } void SerializerForBackgroundCompilation::VisitConstruct( BytecodeArrayIterator* iterator) { Hints& new_target = environment()->accumulator_hints(); Hints const& callee = register_hints(iterator->GetRegisterOperand(0)); interpreter::Register first_reg = iterator->GetRegisterOperand(1); size_t reg_count = iterator->GetRegisterCountOperand(2); FeedbackSlot slot = iterator->GetSlotOperand(3); HintsVector args = PrepareArgumentsHints(first_reg, reg_count); ProcessCallOrConstruct(callee, new_target, &args, slot, kMissingArgumentsAreUndefined); } void SerializerForBackgroundCompilation::VisitConstructWithSpread( BytecodeArrayIterator* iterator) { Hints const& new_target = environment()->accumulator_hints(); Hints const& callee = register_hints(iterator->GetRegisterOperand(0)); interpreter::Register first_reg = iterator->GetRegisterOperand(1); size_t reg_count = iterator->GetRegisterCountOperand(2); FeedbackSlot slot = iterator->GetSlotOperand(3); DCHECK_GT(reg_count, 0); reg_count--; // Pop the spread element. HintsVector args = PrepareArgumentsHints(first_reg, reg_count); ProcessCallOrConstruct(callee, new_target, &args, slot, kMissingArgumentsAreUnknown); } void SerializerForBackgroundCompilation::ProcessGlobalAccess(FeedbackSlot slot, bool is_load) { if (slot.IsInvalid() || feedback_vector().is_null()) return; FeedbackSource source(feedback_vector(), slot); ProcessedFeedback const& feedback = broker()->ProcessFeedbackForGlobalAccess(source); if (is_load) { Hints result_hints; if (feedback.kind() == ProcessedFeedback::kGlobalAccess) { // We may be able to contribute to accumulator constant hints. base::Optional<ObjectRef> value = feedback.AsGlobalAccess().GetConstantHint(); if (value.has_value()) { result_hints.AddConstant(value->object(), zone(), broker()); } } else { DCHECK(feedback.IsInsufficient()); } environment()->accumulator_hints() = result_hints; } } void SerializerForBackgroundCompilation::VisitLdaGlobal( BytecodeArrayIterator* iterator) { NameRef(broker(), iterator->GetConstantForIndexOperand(0, broker()->isolate())); FeedbackSlot slot = iterator->GetSlotOperand(1); ProcessGlobalAccess(slot, true); } void SerializerForBackgroundCompilation::VisitLdaGlobalInsideTypeof( BytecodeArrayIterator* iterator) { VisitLdaGlobal(iterator); } void SerializerForBackgroundCompilation::VisitLdaLookupSlot( BytecodeArrayIterator* iterator) { ObjectRef(broker(), iterator->GetConstantForIndexOperand(0, broker()->isolate())); environment()->accumulator_hints() = Hints(); } void SerializerForBackgroundCompilation::VisitLdaLookupSlotInsideTypeof( BytecodeArrayIterator* iterator) { ObjectRef(broker(), iterator->GetConstantForIndexOperand(0, broker()->isolate())); environment()->accumulator_hints() = Hints(); } void SerializerForBackgroundCompilation::ProcessCheckContextExtensions( int depth) { // for BytecodeGraphBuilder::CheckContextExtensions. Hints const& context_hints = environment()->current_context_hints(); for (int i = 0; i < depth; i++) { ProcessContextAccess(context_hints, Context::EXTENSION_INDEX, i, kSerializeSlot); } SharedFunctionInfoRef shared(broker(), function().shared()); shared.SerializeScopeInfoChain(); } void SerializerForBackgroundCompilation::ProcessLdaLookupGlobalSlot( BytecodeArrayIterator* iterator) { ProcessCheckContextExtensions(iterator->GetUnsignedImmediateOperand(2)); // TODO(neis): BytecodeGraphBilder may insert a JSLoadGlobal. VisitLdaGlobal(iterator); } void SerializerForBackgroundCompilation::VisitLdaLookupGlobalSlot( BytecodeArrayIterator* iterator) { ProcessLdaLookupGlobalSlot(iterator); } void SerializerForBackgroundCompilation::VisitLdaLookupGlobalSlotInsideTypeof( BytecodeArrayIterator* iterator) { ProcessLdaLookupGlobalSlot(iterator); } void SerializerForBackgroundCompilation::VisitStaGlobal( BytecodeArrayIterator* iterator) { NameRef(broker(), iterator->GetConstantForIndexOperand(0, broker()->isolate())); FeedbackSlot slot = iterator->GetSlotOperand(1); ProcessGlobalAccess(slot, false); } void SerializerForBackgroundCompilation::ProcessLdaLookupContextSlot( BytecodeArrayIterator* iterator) { const int slot_index = iterator->GetIndexOperand(1); const int depth = iterator->GetUnsignedImmediateOperand(2); NameRef(broker(), iterator->GetConstantForIndexOperand(0, broker()->isolate())); ProcessCheckContextExtensions(depth); environment()->accumulator_hints() = Hints(); ProcessContextAccess(environment()->current_context_hints(), slot_index, depth, kIgnoreSlot); } void SerializerForBackgroundCompilation::VisitLdaLookupContextSlot( BytecodeArrayIterator* iterator) { ProcessLdaLookupContextSlot(iterator); } void SerializerForBackgroundCompilation::VisitLdaLookupContextSlotInsideTypeof( BytecodeArrayIterator* iterator) { ProcessLdaLookupContextSlot(iterator); } // TODO(neis): Avoid duplicating this. namespace { template <class MapContainer> MapHandles GetRelevantReceiverMaps(Isolate* isolate, MapContainer const& maps) { MapHandles result; for (Handle<Map> map : maps) { if (Map::TryUpdate(isolate, map).ToHandle(&map) && !map->is_abandoned_prototype_map()) { DCHECK(!map->is_deprecated()); result.push_back(map); } } return result; } } // namespace void SerializerForBackgroundCompilation::ProcessCompareOperation( FeedbackSlot slot) { if (slot.IsInvalid() || feedback_vector().is_null()) return; FeedbackSource source(function().feedback_vector(), slot); ProcessedFeedback const& feedback = broker()->ProcessFeedbackForCompareOperation(source); if (BailoutOnUninitialized(feedback)) return; environment()->accumulator_hints() = Hints(); } void SerializerForBackgroundCompilation::ProcessForIn(FeedbackSlot slot) { if (slot.IsInvalid() || feedback_vector().is_null()) return; FeedbackSource source(feedback_vector(), slot); ProcessedFeedback const& feedback = broker()->ProcessFeedbackForForIn(source); if (BailoutOnUninitialized(feedback)) return; environment()->accumulator_hints() = Hints(); } void SerializerForBackgroundCompilation::ProcessUnaryOrBinaryOperation( FeedbackSlot slot, bool honor_bailout_on_uninitialized) { if (slot.IsInvalid() || feedback_vector().is_null()) return; FeedbackSource source(feedback_vector(), slot); // Internally V8 uses binary op feedback also for unary ops. ProcessedFeedback const& feedback = broker()->ProcessFeedbackForBinaryOperation(source); if (honor_bailout_on_uninitialized && BailoutOnUninitialized(feedback)) { return; } environment()->accumulator_hints() = Hints(); } PropertyAccessInfo SerializerForBackgroundCompilation::ProcessMapForNamedPropertyAccess( Hints* receiver, base::Optional<MapRef> receiver_map, MapRef lookup_start_object_map, NameRef const& name, AccessMode access_mode, base::Optional<JSObjectRef> concrete_receiver, Hints* result_hints) { DCHECK_IMPLIES(concrete_receiver.has_value(), receiver_map.has_value()); // For JSNativeContextSpecialization::InferRootMap lookup_start_object_map.SerializeRootMap(); // For JSNativeContextSpecialization::ReduceNamedAccess. JSGlobalProxyRef global_proxy = broker()->target_native_context().global_proxy_object(); JSGlobalObjectRef global_object = broker()->target_native_context().global_object(); if (lookup_start_object_map.equals(global_proxy.map())) { base::Optional<PropertyCellRef> cell = global_object.GetPropertyCell( name, SerializationPolicy::kSerializeIfNeeded); if (access_mode == AccessMode::kLoad && cell.has_value()) { result_hints->AddConstant(cell->value().object(), zone(), broker()); } } PropertyAccessInfo access_info = broker()->GetPropertyAccessInfo( lookup_start_object_map, name, access_mode, dependencies(), SerializationPolicy::kSerializeIfNeeded); // For JSNativeContextSpecialization::InlinePropertySetterCall // and InlinePropertyGetterCall. if (access_info.IsAccessorConstant() && !access_info.constant().is_null()) { if (access_info.constant()->IsJSFunction()) { JSFunctionRef function(broker(), access_info.constant()); if (receiver_map.has_value()) { // For JSCallReducer and JSInlining(Heuristic). HintsVector arguments( {Hints::SingleMap(receiver_map->object(), zone())}, zone()); // In the case of a setter any added result hints won't make sense, but // they will be ignored anyways by Process*PropertyAccess due to the // access mode not being kLoad. ProcessCalleeForCallOrConstruct( function.object(), base::nullopt, arguments, SpeculationMode::kDisallowSpeculation, kMissingArgumentsAreUndefined, result_hints); // For JSCallReducer::ReduceCallApiFunction. Handle<SharedFunctionInfo> sfi = function.shared().object(); if (sfi->IsApiFunction()) { FunctionTemplateInfoRef fti_ref( broker(), handle(sfi->get_api_func_data(), broker()->isolate())); if (fti_ref.has_call_code()) { fti_ref.SerializeCallCode(); ProcessReceiverMapForApiCall(fti_ref, receiver_map->object()); } } } } else if (access_info.constant()->IsJSBoundFunction()) { JSBoundFunctionRef function(broker(), access_info.constant()); // For JSCallReducer::ReduceJSCall. function.Serialize(); } else { FunctionTemplateInfoRef fti(broker(), access_info.constant()); if (fti.has_call_code()) fti.SerializeCallCode(); } } else if (access_info.IsModuleExport()) { // For JSNativeContextSpecialization::BuildPropertyLoad DCHECK(!access_info.constant().is_null()); CellRef(broker(), access_info.constant()); } switch (access_mode) { case AccessMode::kLoad: // For PropertyAccessBuilder::TryBuildLoadConstantDataField if (access_info.IsDataConstant()) { base::Optional<JSObjectRef> holder; Handle<JSObject> prototype; if (access_info.holder().ToHandle(&prototype)) { holder = JSObjectRef(broker(), prototype); } else { CHECK_IMPLIES(concrete_receiver.has_value(), concrete_receiver->map().equals(*receiver_map)); holder = concrete_receiver; } if (holder.has_value()) { base::Optional<ObjectRef> constant(holder->GetOwnDataProperty( access_info.field_representation(), access_info.field_index(), SerializationPolicy::kSerializeIfNeeded)); if (constant.has_value()) { result_hints->AddConstant(constant->object(), zone(), broker()); } } } break; case AccessMode::kStore: case AccessMode::kStoreInLiteral: // For MapInference (StoreField case). if (access_info.IsDataField() || access_info.IsDataConstant()) { Handle<Map> transition_map; if (access_info.transition_map().ToHandle(&transition_map)) { MapRef map_ref(broker(), transition_map); TRACE_BROKER(broker(), "Propagating transition map " << map_ref << " to receiver hints."); receiver->AddMap(transition_map, zone(), broker_, false); } } break; case AccessMode::kHas: break; } return access_info; } void SerializerForBackgroundCompilation::ProcessMinimorphicPropertyAccess( MinimorphicLoadPropertyAccessFeedback const& feedback, FeedbackSource const& source) { broker()->GetPropertyAccessInfo(feedback, source, SerializationPolicy::kSerializeIfNeeded); } void SerializerForBackgroundCompilation::VisitLdaKeyedProperty( BytecodeArrayIterator* iterator) { Hints const& key = environment()->accumulator_hints(); Hints* receiver = &register_hints(iterator->GetRegisterOperand(0)); FeedbackSlot slot = iterator->GetSlotOperand(1); ProcessKeyedPropertyAccess(receiver, key, slot, AccessMode::kLoad, true); } void SerializerForBackgroundCompilation::ProcessKeyedPropertyAccess( Hints* receiver, Hints const& key, FeedbackSlot slot, AccessMode access_mode, bool honor_bailout_on_uninitialized) { if (slot.IsInvalid() || feedback_vector().is_null()) return; FeedbackSource source(feedback_vector(), slot); ProcessedFeedback const& feedback = broker()->ProcessFeedbackForPropertyAccess(source, access_mode, base::nullopt); if (honor_bailout_on_uninitialized && BailoutOnUninitialized(feedback)) { return; } Hints new_accumulator_hints; switch (feedback.kind()) { case ProcessedFeedback::kElementAccess: ProcessElementAccess(*receiver, key, feedback.AsElementAccess(), access_mode); break; case ProcessedFeedback::kNamedAccess: ProcessNamedAccess(receiver, feedback.AsNamedAccess(), access_mode, &new_accumulator_hints); break; case ProcessedFeedback::kInsufficient: break; default: UNREACHABLE(); } if (access_mode == AccessMode::kLoad) { environment()->accumulator_hints() = new_accumulator_hints; } } void SerializerForBackgroundCompilation::ProcessNamedPropertyAccess( Hints* receiver, NameRef const& name, FeedbackSlot slot, AccessMode access_mode) { if (slot.IsInvalid() || feedback_vector().is_null()) return; FeedbackSource source(feedback_vector(), slot); ProcessedFeedback const& feedback = broker()->ProcessFeedbackForPropertyAccess(source, access_mode, name); if (BailoutOnUninitialized(feedback)) return; Hints new_accumulator_hints; switch (feedback.kind()) { case ProcessedFeedback::kNamedAccess: DCHECK(name.equals(feedback.AsNamedAccess().name())); ProcessNamedAccess(receiver, feedback.AsNamedAccess(), access_mode, &new_accumulator_hints); break; case ProcessedFeedback::kMinimorphicPropertyAccess: DCHECK(name.equals(feedback.AsMinimorphicPropertyAccess().name())); ProcessMinimorphicPropertyAccess(feedback.AsMinimorphicPropertyAccess(), source); break; case ProcessedFeedback::kInsufficient: break; default: UNREACHABLE(); } if (access_mode == AccessMode::kLoad) { environment()->accumulator_hints() = new_accumulator_hints; } } void SerializerForBackgroundCompilation::ProcessNamedSuperPropertyAccess( Hints* receiver, NameRef const& name, FeedbackSlot slot, AccessMode access_mode) { if (slot.IsInvalid() || feedback_vector().is_null()) return; FeedbackSource source(feedback_vector(), slot); ProcessedFeedback const& feedback = broker()->ProcessFeedbackForPropertyAccess(source, access_mode, name); if (BailoutOnUninitialized(feedback)) return; Hints new_accumulator_hints; switch (feedback.kind()) { case ProcessedFeedback::kNamedAccess: DCHECK(name.equals(feedback.AsNamedAccess().name())); ProcessNamedSuperAccess(receiver, feedback.AsNamedAccess(), access_mode, &new_accumulator_hints); break; case ProcessedFeedback::kMinimorphicPropertyAccess: DCHECK(name.equals(feedback.AsMinimorphicPropertyAccess().name())); ProcessMinimorphicPropertyAccess(feedback.AsMinimorphicPropertyAccess(), source); break; case ProcessedFeedback::kInsufficient: break; default: UNREACHABLE(); } if (access_mode == AccessMode::kLoad) { environment()->accumulator_hints() = new_accumulator_hints; } } void SerializerForBackgroundCompilation::ProcessNamedAccess( Hints* receiver, NamedAccessFeedback const& feedback, AccessMode access_mode, Hints* result_hints) { for (Handle<Map> map : feedback.maps()) { MapRef map_ref(broker(), map); TRACE_BROKER(broker(), "Propagating feedback map " << map_ref << " to receiver hints."); receiver->AddMap(map, zone(), broker_, false); } for (Handle<Map> map : GetRelevantReceiverMaps(broker()->isolate(), receiver->maps())) { MapRef map_ref(broker(), map); ProcessMapForNamedPropertyAccess(receiver, map_ref, map_ref, feedback.name(), access_mode, base::nullopt, result_hints); } for (Handle<Object> hint : receiver->constants()) { ObjectRef object(broker(), hint); if (access_mode == AccessMode::kLoad && object.IsJSObject()) { MapRef map_ref = object.AsJSObject().map(); ProcessMapForNamedPropertyAccess(receiver, map_ref, map_ref, feedback.name(), access_mode, object.AsJSObject(), result_hints); } // For JSNativeContextSpecialization::ReduceJSLoadNamed. if (access_mode == AccessMode::kLoad && object.IsJSFunction() && feedback.name().equals(ObjectRef( broker(), broker()->isolate()->factory()->prototype_string()))) { JSFunctionRef function = object.AsJSFunction(); function.Serialize(); if (result_hints != nullptr && function.has_prototype()) { result_hints->AddConstant(function.prototype().object(), zone(), broker()); } } // TODO(neis): Also record accumulator hint for string.length and maybe // more? } } void SerializerForBackgroundCompilation::ProcessNamedSuperAccess( Hints* receiver, NamedAccessFeedback const& feedback, AccessMode access_mode, Hints* result_hints) { MapHandles receiver_maps = GetRelevantReceiverMaps(broker()->isolate(), receiver->maps()); for (Handle<Map> receiver_map : receiver_maps) { MapRef receiver_map_ref(broker(), receiver_map); for (Handle<Map> feedback_map : feedback.maps()) { MapRef feedback_map_ref(broker(), feedback_map); ProcessMapForNamedPropertyAccess( receiver, receiver_map_ref, feedback_map_ref, feedback.name(), access_mode, base::nullopt, result_hints); } } if (receiver_maps.empty()) { for (Handle<Map> feedback_map : feedback.maps()) { MapRef feedback_map_ref(broker(), feedback_map); ProcessMapForNamedPropertyAccess( receiver, base::nullopt, feedback_map_ref, feedback.name(), access_mode, base::nullopt, result_hints); } } } void SerializerForBackgroundCompilation::ProcessElementAccess( Hints const& receiver, Hints const& key, ElementAccessFeedback const& feedback, AccessMode access_mode) { for (auto const& group : feedback.transition_groups()) { for (Handle<Map> map_handle : group) { MapRef map(broker(), map_handle); switch (access_mode) { case AccessMode::kHas: case AccessMode::kLoad: map.SerializeForElementLoad(); break; case AccessMode::kStore: map.SerializeForElementStore(); break; case AccessMode::kStoreInLiteral: // This operation is fairly local and simple, nothing to serialize. break; } } } for (Handle<Object> hint : receiver.constants()) { ObjectRef receiver_ref(broker(), hint); // For JSNativeContextSpecialization::InferRootMap if (receiver_ref.IsHeapObject()) { receiver_ref.AsHeapObject().map().SerializeRootMap(); } // For JSNativeContextSpecialization::ReduceElementAccess. if (receiver_ref.IsJSTypedArray()) { receiver_ref.AsJSTypedArray().Serialize(); } // For JSNativeContextSpecialization::ReduceElementLoadFromHeapConstant. if (access_mode == AccessMode::kLoad || access_mode == AccessMode::kHas) { for (Handle<Object> hint : key.constants()) { ObjectRef key_ref(broker(), hint); // TODO(neis): Do this for integer-HeapNumbers too? if (key_ref.IsSmi() && key_ref.AsSmi() >= 0) { base::Optional<ObjectRef> element = receiver_ref.GetOwnConstantElement( key_ref.AsSmi(), SerializationPolicy::kSerializeIfNeeded); if (!element.has_value() && receiver_ref.IsJSArray()) { // We didn't find a constant element, but if the receiver is a // cow-array we can exploit the fact that any future write to the // element will replace the whole elements storage. receiver_ref.AsJSArray().GetOwnCowElement( key_ref.AsSmi(), SerializationPolicy::kSerializeIfNeeded); } } } } } // For JSNativeContextSpecialization::InferRootMap for (Handle<Map> map : receiver.maps()) { MapRef map_ref(broker(), map); map_ref.SerializeRootMap(); } } void SerializerForBackgroundCompilation::VisitLdaNamedProperty( BytecodeArrayIterator* iterator) { Hints* receiver = &register_hints(iterator->GetRegisterOperand(0)); NameRef name(broker(), iterator->GetConstantForIndexOperand(1, broker()->isolate())); FeedbackSlot slot = iterator->GetSlotOperand(2); ProcessNamedPropertyAccess(receiver, name, slot, AccessMode::kLoad); } void SerializerForBackgroundCompilation::VisitLdaNamedPropertyFromSuper( BytecodeArrayIterator* iterator) { Hints* receiver = &register_hints(iterator->GetRegisterOperand(0)); NameRef name(broker(), iterator->GetConstantForIndexOperand(1, broker()->isolate())); FeedbackSlot slot = iterator->GetSlotOperand(2); ProcessNamedSuperPropertyAccess(receiver, name, slot, AccessMode::kLoad); } // TODO(neis): Do feedback-independent serialization also for *NoFeedback // bytecodes. void SerializerForBackgroundCompilation::VisitLdaNamedPropertyNoFeedback( BytecodeArrayIterator* iterator) { NameRef(broker(), iterator->GetConstantForIndexOperand(1, broker()->isolate())); } void SerializerForBackgroundCompilation::VisitStaNamedProperty( BytecodeArrayIterator* iterator) { Hints* receiver = &register_hints(iterator->GetRegisterOperand(0)); NameRef name(broker(), iterator->GetConstantForIndexOperand(1, broker()->isolate())); FeedbackSlot slot = iterator->GetSlotOperand(2); ProcessNamedPropertyAccess(receiver, name, slot, AccessMode::kStore); } void SerializerForBackgroundCompilation::VisitStaNamedPropertyNoFeedback( BytecodeArrayIterator* iterator) { NameRef(broker(), iterator->GetConstantForIndexOperand(1, broker()->isolate())); } void SerializerForBackgroundCompilation::VisitStaNamedOwnProperty( BytecodeArrayIterator* iterator) { Hints* receiver = &register_hints(iterator->GetRegisterOperand(0)); NameRef name(broker(), iterator->GetConstantForIndexOperand(1, broker()->isolate())); FeedbackSlot slot = iterator->GetSlotOperand(2); ProcessNamedPropertyAccess(receiver, name, slot, AccessMode::kStoreInLiteral); } void SerializerForBackgroundCompilation::VisitTestIn( BytecodeArrayIterator* iterator) { Hints* receiver = &environment()->accumulator_hints(); Hints const& key = register_hints(iterator->GetRegisterOperand(0)); FeedbackSlot slot = iterator->GetSlotOperand(1); ProcessKeyedPropertyAccess(receiver, key, slot, AccessMode::kHas, false); } // For JSNativeContextSpecialization::ReduceJSOrdinaryHasInstance. void SerializerForBackgroundCompilation::ProcessConstantForOrdinaryHasInstance( HeapObjectRef const& constructor, bool* walk_prototypes) { if (constructor.IsJSBoundFunction()) { constructor.AsJSBoundFunction().Serialize(); ProcessConstantForInstanceOf( constructor.AsJSBoundFunction().bound_target_function(), walk_prototypes); } else if (constructor.IsJSFunction()) { constructor.AsJSFunction().Serialize(); *walk_prototypes = *walk_prototypes || (constructor.map().has_prototype_slot() && constructor.AsJSFunction().has_prototype() && !constructor.AsJSFunction().PrototypeRequiresRuntimeLookup()); } } void SerializerForBackgroundCompilation::ProcessConstantForInstanceOf( ObjectRef const& constructor, bool* walk_prototypes) { if (!constructor.IsHeapObject()) return; HeapObjectRef constructor_heap_object = constructor.AsHeapObject(); PropertyAccessInfo access_info = broker()->GetPropertyAccessInfo( constructor_heap_object.map(), NameRef(broker(), broker()->isolate()->factory()->has_instance_symbol()), AccessMode::kLoad, dependencies(), SerializationPolicy::kSerializeIfNeeded); if (access_info.IsNotFound()) { ProcessConstantForOrdinaryHasInstance(constructor_heap_object, walk_prototypes); } else if (access_info.IsDataConstant()) { Handle<JSObject> holder; bool found_on_proto = access_info.holder().ToHandle(&holder); JSObjectRef holder_ref = found_on_proto ? JSObjectRef(broker(), holder) : constructor.AsJSObject(); base::Optional<ObjectRef> constant = holder_ref.GetOwnDataProperty( access_info.field_representation(), access_info.field_index(), SerializationPolicy::kSerializeIfNeeded); CHECK(constant.has_value()); if (constant->IsJSFunction()) { JSFunctionRef function = constant->AsJSFunction(); function.Serialize(); if (function.shared().HasBuiltinId() && function.shared().builtin_id() == Builtins::kFunctionPrototypeHasInstance) { // For JSCallReducer::ReduceFunctionPrototypeHasInstance. ProcessConstantForOrdinaryHasInstance(constructor_heap_object, walk_prototypes); } } } } void SerializerForBackgroundCompilation::VisitTestInstanceOf( BytecodeArrayIterator* iterator) { Hints const& lhs = register_hints(iterator->GetRegisterOperand(0)); Hints rhs = environment()->accumulator_hints(); FeedbackSlot slot = iterator->GetSlotOperand(1); if (slot.IsInvalid() || feedback_vector().is_null()) return; FeedbackSource source(feedback_vector(), slot); ProcessedFeedback const& feedback = broker()->ProcessFeedbackForInstanceOf(source); // Incorporate feedback (about rhs) into hints copy to simplify processing. // TODO(neis): Propagate into original hints? if (!feedback.IsInsufficient()) { InstanceOfFeedback const& rhs_feedback = feedback.AsInstanceOf(); if (rhs_feedback.value().has_value()) { rhs = rhs.Copy(zone()); Handle<JSObject> constructor = rhs_feedback.value()->object(); rhs.AddConstant(constructor, zone(), broker()); } } bool walk_prototypes = false; for (Handle<Object> constant : rhs.constants()) { ProcessConstantForInstanceOf(ObjectRef(broker(), constant), &walk_prototypes); } if (walk_prototypes) ProcessHintsForHasInPrototypeChain(lhs); environment()->accumulator_hints() = Hints(); } void SerializerForBackgroundCompilation::VisitToNumeric( BytecodeArrayIterator* iterator) { FeedbackSlot slot = iterator->GetSlotOperand(0); ProcessUnaryOrBinaryOperation(slot, false); } void SerializerForBackgroundCompilation::VisitToNumber( BytecodeArrayIterator* iterator) { FeedbackSlot slot = iterator->GetSlotOperand(0); ProcessUnaryOrBinaryOperation(slot, false); } void SerializerForBackgroundCompilation::VisitThrowReferenceErrorIfHole( BytecodeArrayIterator* iterator) { ObjectRef(broker(), iterator->GetConstantForIndexOperand(0, broker()->isolate())); } void SerializerForBackgroundCompilation::VisitStaKeyedProperty( BytecodeArrayIterator* iterator) { Hints* receiver = &register_hints(iterator->GetRegisterOperand(0)); Hints const& key = register_hints(iterator->GetRegisterOperand(1)); FeedbackSlot slot = iterator->GetSlotOperand(2); ProcessKeyedPropertyAccess(receiver, key, slot, AccessMode::kStore, true); } void SerializerForBackgroundCompilation::VisitStaInArrayLiteral( BytecodeArrayIterator* iterator) { Hints* receiver = &register_hints(iterator->GetRegisterOperand(0)); Hints const& key = register_hints(iterator->GetRegisterOperand(1)); FeedbackSlot slot = iterator->GetSlotOperand(2); ProcessKeyedPropertyAccess(receiver, key, slot, AccessMode::kStoreInLiteral, true); } void SerializerForBackgroundCompilation::VisitStaDataPropertyInLiteral( BytecodeArrayIterator* iterator) { Hints* receiver = &register_hints(iterator->GetRegisterOperand(0)); Hints const& key = register_hints(iterator->GetRegisterOperand(1)); FeedbackSlot slot = iterator->GetSlotOperand(3); ProcessKeyedPropertyAccess(receiver, key, slot, AccessMode::kStoreInLiteral, false); } #define DEFINE_CLEAR_ACCUMULATOR(name, ...) \ void SerializerForBackgroundCompilation::Visit##name( \ BytecodeArrayIterator* iterator) { \ environment()->accumulator_hints() = Hints(); \ } CLEAR_ACCUMULATOR_LIST(DEFINE_CLEAR_ACCUMULATOR) #undef DEFINE_CLEAR_ACCUMULATOR #define DEFINE_CONDITIONAL_JUMP(name, ...) \ void SerializerForBackgroundCompilation::Visit##name( \ BytecodeArrayIterator* iterator) { \ ProcessJump(iterator); \ } CONDITIONAL_JUMPS_LIST(DEFINE_CONDITIONAL_JUMP) #undef DEFINE_CONDITIONAL_JUMP #define DEFINE_UNCONDITIONAL_JUMP(name, ...) \ void SerializerForBackgroundCompilation::Visit##name( \ BytecodeArrayIterator* iterator) { \ ProcessJump(iterator); \ environment()->Kill(); \ } UNCONDITIONAL_JUMPS_LIST(DEFINE_UNCONDITIONAL_JUMP) #undef DEFINE_UNCONDITIONAL_JUMP #define DEFINE_IGNORE(name, ...) \ void SerializerForBackgroundCompilation::Visit##name( \ BytecodeArrayIterator* iterator) {} IGNORED_BYTECODE_LIST(DEFINE_IGNORE) #undef DEFINE_IGNORE #define DEFINE_UNREACHABLE(name, ...) \ void SerializerForBackgroundCompilation::Visit##name( \ BytecodeArrayIterator* iterator) { \ UNREACHABLE(); \ } UNREACHABLE_BYTECODE_LIST(DEFINE_UNREACHABLE) #undef DEFINE_UNREACHABLE #define DEFINE_KILL(name, ...) \ void SerializerForBackgroundCompilation::Visit##name( \ BytecodeArrayIterator* iterator) { \ environment()->Kill(); \ } KILL_ENVIRONMENT_LIST(DEFINE_KILL) #undef DEFINE_KILL #define DEFINE_BINARY_OP(name, ...) \ void SerializerForBackgroundCompilation::Visit##name( \ BytecodeArrayIterator* iterator) { \ FeedbackSlot slot = iterator->GetSlotOperand(1); \ ProcessUnaryOrBinaryOperation(slot, true); \ } BINARY_OP_LIST(DEFINE_BINARY_OP) #undef DEFINE_BINARY_OP #define DEFINE_COMPARE_OP(name, ...) \ void SerializerForBackgroundCompilation::Visit##name( \ BytecodeArrayIterator* iterator) { \ FeedbackSlot slot = iterator->GetSlotOperand(1); \ ProcessCompareOperation(slot); \ } COMPARE_OP_LIST(DEFINE_COMPARE_OP) #undef DEFINE_COMPARE_OP #define DEFINE_UNARY_OP(name, ...) \ void SerializerForBackgroundCompilation::Visit##name( \ BytecodeArrayIterator* iterator) { \ FeedbackSlot slot = iterator->GetSlotOperand(0); \ ProcessUnaryOrBinaryOperation(slot, true); \ } UNARY_OP_LIST(DEFINE_UNARY_OP) #undef DEFINE_UNARY_OP #undef BINARY_OP_LIST #undef CLEAR_ACCUMULATOR_LIST #undef COMPARE_OP_LIST #undef CONDITIONAL_JUMPS_LIST #undef IGNORED_BYTECODE_LIST #undef KILL_ENVIRONMENT_LIST #undef SUPPORTED_BYTECODE_LIST #undef UNARY_OP_LIST #undef UNCONDITIONAL_JUMPS_LIST #undef UNREACHABLE_BYTECODE_LIST } // namespace compiler } // namespace internal } // namespace v8
{ "content_hash": "9aeba22274a53a1ac0a4dde8e159b3c3", "timestamp": "", "source": "github", "line_count": 3576, "max_line_length": 80, "avg_line_length": 39.503914988814316, "alnum_prop": 0.6645406538020472, "repo_name": "youtube/cobalt_sandbox", "id": "3e57da18a0e40600ca74e09e97973b85fab004c3", "size": "142206", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "third_party/v8/src/compiler/serializer-for-background-compilation.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
# Use this hook to configure devise mailer, warden hooks and so forth. # Many of these configuration options can be set straight in your model. Devise.setup do |config| # The secret key used by Devise. Devise uses this key to generate # random tokens. Changing this key will render invalid all existing # confirmation, reset password and unlock tokens in the database. # Devise will use the `secret_key_base` on Rails 4+ applications as its `secret_key` # by default. You can change it below and use your own secret key. # config.secret_key = 'a9ffe0dd88867ae233e8ff27f6257a079c6f08c714dfc510d192082e994ad87756f2e244997146d514af022f4939331e7cf2f9f2fe9aa310576f61a40d840c3e' # ==> Mailer Configuration # Configure the e-mail address which will be shown in Devise::Mailer, # note that it will be overwritten if you use your own mailer class # with default "from" parameter. config.mailer_sender = 'whattodo@gmail.com' # Configure the class responsible to send e-mails. # config.mailer = 'Devise::Mailer' # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and # :mongoid (bson_ext recommended) by default. Other ORMs may be # available as additional gems. require 'devise/orm/active_record' # ==> Configuration for any authentication mechanism # Configure which keys are used when authenticating a user. The default is # just :email. You can configure it to use [:username, :subdomain], so for # authenticating a user, both parameters are required. Remember that those # parameters are used only when authenticating and not when retrieving from # session. If you need permissions, you should implement that in a before filter. # You can also supply a hash where the value is a boolean determining whether # or not authentication should be aborted when the value is not present. # config.authentication_keys = [:email] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to the # find_for_authentication method and considered in your model lookup. For instance, # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. # The same considerations mentioned for authentication_keys also apply to request_keys. # config.request_keys = [] # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. config.case_insensitive_keys = [:email] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. config.strip_whitespace_keys = [:email] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the # given strategies, for example, `config.params_authenticatable = [:database]` will # enable it only for database (email + password) authentication. # config.params_authenticatable = true # Tell if authentication through HTTP Auth is enabled. False by default. # It can be set to an array that will enable http authentication only for the # given strategies, for example, `config.http_authenticatable = [:database]` will # enable it only for database authentication. The supported strategies are: # :database = Support basic authentication with authentication key + password # config.http_authenticatable = false # If 401 status code should be returned for AJAX requests. True by default. # config.http_authenticatable_on_xhr = true # The realm used in Http Basic Authentication. 'Application' by default. # config.http_authentication_realm = 'Application' # It will change confirmation, password recovery and other workflows # to behave the same regardless if the e-mail provided was right or wrong. # Does not affect registerable. # config.paranoid = true # By default Devise will store the user in session. You can skip storage for # particular strategies by setting this option. # Notice that if you are skipping storage for all authentication paths, you # may want to disable generating routes to Devise's sessions controller by # passing skip: :sessions to `devise_for` in your config/routes.rb config.skip_session_storage = [:http_auth] # By default, Devise cleans up the CSRF token on authentication to # avoid CSRF token fixation attacks. This means that, when using AJAX # requests for sign in and sign up, you need to get a new CSRF token # from the server. You can disable this option at your own risk. # config.clean_up_csrf_token_on_authentication = true # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 10. If # using other encryptors, it sets how many times you want the password re-encrypted. # # Limiting the stretches to just one in testing will increase the performance of # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use # a value less than 10 in other environments. Note that, for bcrypt (the default # encryptor), the cost increases exponentially with the number of stretches (e.g. # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). config.stretches = Rails.env.test? ? 1 : 10 # Setup a pepper to generate the encrypted password. # config.pepper = '61ec1e0871d0f1bd40fefa3c30b44450e14b2e43079781dea2020feb400560e21c1137416244b3c8671e1d57d14943f778fa61537a3da054c90fe2b1ae648a07' # Send a notification email when the user's password is changed # config.send_password_change_notification = false # ==> Configuration for :confirmable # A period that the user is allowed to access the website even without # confirming their account. For instance, if set to 2.days, the user will be # able to access the website for two days without confirming their account, # access will be blocked just in the third day. Default is 0.days, meaning # the user cannot access the website without confirming their account. # config.allow_unconfirmed_access_for = 2.days # A period that the user is allowed to confirm their account before their # token becomes invalid. For example, if set to 3.days, the user can confirm # their account within 3 days after the mail was sent, but on the fourth day # their account can't be confirmed with the token any more. # Default is nil, meaning there is no restriction on how long a user can take # before confirming their account. # config.confirm_within = 3.days # If true, requires any email changes to be confirmed (exactly the same way as # initial account confirmation) to be applied. Requires additional unconfirmed_email # db field (see migrations). Until confirmed, new email is stored in # unconfirmed_email column, and copied to email column on successful confirmation. config.reconfirmable = true # Defines which key will be used when confirming an account # config.confirmation_keys = [:email] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks # Invalidates all the remember me tokens when the user signs out. config.expire_all_remember_me_on_sign_out = true # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # Options to be passed to the created cookie. For instance, you can set # secure: true in order to force SSL only cookies. # config.rememberable_options = {} # ==> Configuration for :validatable # Range for password length. config.password_length = 8..72 # Email regex used to validate email formats. It simply asserts that # one (and only one) @ exists in the given string. This is mainly # to give user feedback and not to assert the e-mail validity. # config.email_regexp = /\A[^@]+@[^@]+\z/ # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. # config.timeout_in = 30.minutes # ==> Configuration for :lockable # Defines which strategy will be used to lock an account. # :failed_attempts = Locks an account after a number of failed attempts to sign in. # :none = No lock strategy. You should handle locking by yourself. # config.lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account # config.unlock_keys = [:email] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email # :time = Re-enables login after a certain amount of time (see :unlock_in below) # :both = Enables both strategies # :none = No unlock strategy. You should handle unlocking by yourself. # config.unlock_strategy = :both # Number of authentication tries before locking an account if lock_strategy # is failed attempts. # config.maximum_attempts = 20 # Time interval to unlock the account if :time is enabled as unlock_strategy. # config.unlock_in = 1.hour # Warn on the last attempt before the account is locked. # config.last_attempt_warning = true # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account # config.reset_password_keys = [:email] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to # change their passwords. config.reset_password_within = 6.hours # When set to false, does not sign a user in automatically after their password is # reset. Defaults to true, so a user is signed in automatically after a reset. # config.sign_in_after_reset_password = true # ==> Configuration for :encryptable # Allow you to use another encryption algorithm besides bcrypt (default). You can use # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1, # :authlogic_sha512 (then you should set stretches above to 20 for default behavior) # and :restful_authentication_sha1 (then you should set stretches to 10, and copy # REST_AUTH_SITE_KEY to pepper). # # Require the `devise-encryptable` gem when using anything other than bcrypt # config.encryptor = :sha512 # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for # "users/sessions/new". It's turned off by default because it's slower if you # are using only default views. # config.scoped_views = false # Configure the default scope given to Warden. By default it's the first # devise role declared in your routes (usually :user). # config.default_scope = :user # Set this configuration to false if you want /users/sign_out to sign out # only the current scope. By default, Devise signs out all scopes. # config.sign_out_all_scopes = true # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like # :html, should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # # If you have any extra navigational formats, like :iphone or :mobile, you # should add them to the navigational formats lists. # # The "*/*" below is required to match Internet Explorer requests. # config.navigational_formats = ['*/*', :html] # The default HTTP method used to sign out a resource. Default is :delete. config.sign_out_via = :delete # ==> OmniAuth # Add a new OmniAuth provider. Check the wiki for more information on setting # up on your models and hooks. # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' # ==> Warden configuration # If you want to use other strategies, that are not supported by Devise, or # change the failure app, you can configure them inside the config.warden block. # # config.warden do |manager| # manager.intercept_401 = false # manager.default_strategies(scope: :user).unshift :some_external_strategy # end # ==> Mountable engine configurations # When using Devise inside an engine, let's call it `MyEngine`, and this engine # is mountable, there are some extra configurations to be taken into account. # The following options are available, assuming the engine is mounted as: # # mount MyEngine, at: '/my_engine' # # The router that invoked `devise_for`, in the example above, would be: # config.router_name = :my_engine # # When using OmniAuth, Devise cannot automatically set OmniAuth path, # so you need to do it manually. For the users scope, it would be: # config.omniauth_path_prefix = '/my_engine/users/auth' end
{ "content_hash": "572335e54dc46fee2c86447a56d93872", "timestamp": "", "source": "github", "line_count": 265, "max_line_length": 154, "avg_line_length": 49.39245283018868, "alnum_prop": 0.7426082970433188, "repo_name": "lullman/WhatToDo", "id": "f444b1d9021c3ef236228533305c5ea84ad9b844", "size": "13089", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/initializers/devise.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "686" }, { "name": "HTML", "bytes": "13653" }, { "name": "JavaScript", "bytes": "661" }, { "name": "Ruby", "bytes": "41163" } ], "symlink_target": "" }
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="console" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d %-5p [%c] %m%n" /> </layout> </appender> <logger name="org.springframework"> <level value="INFO" /> </logger> <root> <priority value="ERROR" /> <appender-ref ref="console" /> </root> </log4j:configuration>
{ "content_hash": "207f06ec8019a62d95ac64c609fc0111", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 72, "avg_line_length": 29.57894736842105, "alnum_prop": 0.6174377224199288, "repo_name": "llavoie/platform-medical-records", "id": "9bd6c6abec97a124d07440a4a5d666ae4d18eba4", "size": "562", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/openmrs/api/src/test/resources/log4j.xml", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "61105d81933500f66b3ef4980523d6b5", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "fc1734a123901832cb0d1091455a893a19032054", "size": "171", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Guilandina/Guilandina moringa/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>V8 API Reference Guide for io.js v1.0.0 - v1.0.2: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for io.js v1.0.0 - v1.0.2 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1_unbound_script.html">UnboundScript</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">v8::UnboundScript Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="classv8_1_1_unbound_script.html">v8::UnboundScript</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="classv8_1_1_unbound_script.html#a0f3354dc71e3f831d10f6e82704a4c2b">BindToCurrentContext</a>()</td><td class="entry"><a class="el" href="classv8_1_1_unbound_script.html">v8::UnboundScript</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>GetId</b>() (defined in <a class="el" href="classv8_1_1_unbound_script.html">v8::UnboundScript</a>)</td><td class="entry"><a class="el" href="classv8_1_1_unbound_script.html">v8::UnboundScript</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classv8_1_1_unbound_script.html#a020ca8bbe6ea2313aeedc993ccac3741">GetLineNumber</a>(int code_pos)</td><td class="entry"><a class="el" href="classv8_1_1_unbound_script.html">v8::UnboundScript</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>GetScriptName</b>() (defined in <a class="el" href="classv8_1_1_unbound_script.html">v8::UnboundScript</a>)</td><td class="entry"><a class="el" href="classv8_1_1_unbound_script.html">v8::UnboundScript</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classv8_1_1_unbound_script.html#a00862170298ab31131a1fe43b6440f81">GetSourceMappingURL</a>()</td><td class="entry"><a class="el" href="classv8_1_1_unbound_script.html">v8::UnboundScript</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classv8_1_1_unbound_script.html#a415e7ba0382e95b9488e6125884754e0">GetSourceURL</a>()</td><td class="entry"><a class="el" href="classv8_1_1_unbound_script.html">v8::UnboundScript</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>kNoScriptId</b> (defined in <a class="el" href="classv8_1_1_unbound_script.html">v8::UnboundScript</a>)</td><td class="entry"><a class="el" href="classv8_1_1_unbound_script.html">v8::UnboundScript</a></td><td class="entry"><span class="mlabel">static</span></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Aug 11 2015 23:49:10 for V8 API Reference Guide for io.js v1.0.0 - v1.0.2 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
{ "content_hash": "9322ef6a0bfc2a6f677d676207605831", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 325, "avg_line_length": 57.32743362831859, "alnum_prop": 0.659771534424205, "repo_name": "v8-dox/v8-dox.github.io", "id": "43bd8a8c96413bdfc55367e23ad886c20f8daaeb", "size": "6478", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "b949437/html/classv8_1_1_unbound_script-members.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
'use strict'; var chai = require('chai'), should = require('chai').should(), SSML = require('../lib/to-ssml'); var PlainStrings = [ 'This output speech uses SSML.', 'This is a sentence', 'This is what Alexa sounds like without any SSML.' ], EmbeddedSSMLStrings = [ 'Here is a number <w role="ivona:VBD">read</w> as a cardinal number:', '<say-as interpret-as="cardinal">12345</say-as>.', 'Here is a word spelled out: <say-as interpret-as="spell-out">hello</say-as>.', 'You say, <phoneme alphabet="ipa" ph="pɪˈkɑːn">pecan</phoneme>. I say, <phoneme alphabet="ipa" ph="ˈpi.kæn">pecan</phoneme>.', '<s>This is a sentence</s>\n<s>There should be a short pause before this second sentence</s>\nThis sentence ends with a period and should have the same pause.' ]; describe('SSML', function() { describe('#conversion', function() { describe('convert to SSML', function() { describe('plain string to SSML conversion', function() { for (var i = 0; i < PlainStrings.length; i++) { (function(i) { it('should wrap a plain string in <speak> tags', function() { var expectedOutput = '<speak>' + PlainStrings[i] + '</speak>'; return SSML.fromStr(PlainStrings[i]).should.equal(expectedOutput); }); })(i); } }); describe('strings with embedded SSML tags', function() { for (var i = 0; i < EmbeddedSSMLStrings.length; i++) { (function(i) { it('should wrap these strings in <speak> tags', function() { var expectedOutput = '<speak>' + EmbeddedSSMLStrings[i] + '</speak>'; return SSML.fromStr(EmbeddedSSMLStrings[i]).should.equal(expectedOutput); }); })(i); } }); describe('strings appended to current SSML string', function() { it('should append prior to the trailing </speak> tag', function() { var outputSpeech = SSML.fromStr(PlainStrings[0]); for (var i = 1; i < PlainStrings.length; i++) { outputSpeech = SSML.fromStr(PlainStrings[i], outputSpeech); } return outputSpeech.should.equal('<speak>' + PlainStrings.join(' ') + '</speak>'); }); }); describe('SSML strings without embedded SSML tags appended to current SSML string', function() { it('should append prior to the trailing </speak> tag', function() { var outputSpeech = SSML.fromStr(PlainStrings[0]); for (var i = 1; i < PlainStrings.length; i++) { outputSpeech = SSML.fromStr('<speak>' + PlainStrings[i] + '</speak>', outputSpeech); } return outputSpeech.should.equal('<speak>' + PlainStrings.join(' ') + '</speak>'); }); }); describe('SSML strings with embedded SSML tags appended to current SSML string', function() { it('should append prior to the trailing </speak> tag', function() { var outputSpeech = SSML.fromStr(EmbeddedSSMLStrings[0]); for (var i = 1; i < EmbeddedSSMLStrings.length; i++) { outputSpeech = SSML.fromStr('<speak>' + EmbeddedSSMLStrings[i] + '</speak>', outputSpeech); } return outputSpeech.should.equal('<speak>' + EmbeddedSSMLStrings.join(' ') + '</speak>'); }); }); }); }); describe('#cleanse', function() { // the following are used to take SSML output and cleanse for use in Cards describe('cleanse SSML', function() { describe('cleanse simple SSML', function() { for (var i = 0; i < PlainStrings.length; i++) { (function(i) { it('should remove <speak> tags', function() { var expectedOutput = PlainStrings[i]; return SSML.cleanse(SSML.fromStr(PlainStrings[i])).should.equal(expectedOutput); }); })(i); } }); describe('cleanse SSML with embedded tags', function() { it('should remove <speak> and embedded <audio> SSML tags', function() { var input = '<speak>Welcome to Car-Fu. <audio src="https://carfu.com/audio/carfu-welcome.mp3" /> You can order a ride, or request a fare estimate. Which will it be?</speak>'; var expectedOutput = 'Welcome to Car-Fu. You can order a ride, or request a fare estimate. Which will it be?'; return SSML.cleanse(input).should.equal(expectedOutput); }); it('should remove <speak> and embedded <break> SSML tags', function() { var input = '<speak>There is a three second pause here <break time="3s"/> then the speech continues.</speak>'; var expectedOutput = 'There is a three second pause here then the speech continues.'; return SSML.cleanse(input).should.equal(expectedOutput); }); it('should remove <speak> but not embedded <p> SSML/HTML tags', function() { var input = '<speak><p>This is the first paragraph. There should be a pause after this text is spoken.</p><p>This is the second paragraph.</p></speak>'; var expectedOutput = '<p>This is the first paragraph. There should be a pause after this text is spoken.</p><p>This is the second paragraph.</p>'; return SSML.cleanse(input).should.equal(expectedOutput); }); it('should remove <speak> and embedded <phoneme> tags', function() { var input = '<speak>You say, <phoneme alphabet="ipa" ph="pɪˈkɑːn">pecan</phoneme>. I say, <phoneme alphabet="ipa" ph="ˈpi.kæn">pecan</phoneme>.</speak>'; var expectedOutput = 'You say, pecan. I say, pecan.'; return SSML.cleanse(input).should.equal(expectedOutput); }); it('should remove <speak> and embedded <s> SSML tags', function() { var input = '<speak><s>This is a sentence</s>\n<s>There should be a short pause before this second sentence</s>\nThis sentence ends with a period and should have the same pause.</speak>'; var expectedOutput = 'This is a sentence\nThere should be a short pause before this second sentence\nThis sentence ends with a period and should have the same pause.'; return SSML.cleanse(input).should.equal(expectedOutput); }); it('should remove <speak> and embedded <say-as> tags', function() { var input = '<speak><say-as interpret-as="cardinal">12345</say-as>.</speak>'; var expectedOutput = '12345.'; return SSML.cleanse(input).should.equal(expectedOutput); }); it('should remove <speak> and embedded <w> SSML tags', function() { var input = '<speak>Here is a number <w role="ivona:VBD">read</w> as a cardinal number:</speak>'; var expectedOutput = 'Here is a number read as a cardinal number:'; return SSML.cleanse(input).should.equal(expectedOutput); }); it('should remove <speak> and embedded SSML/non-HTML tags, leaving other tags', function() { var input = '<speak>This sentence has <say-as interpret-as="cardinal">1</say-as> embedded <strong>strong</strong>tag.</speak>'; var expectedOutput = 'This sentence has 1 embedded <strong>strong</strong>tag.'; return SSML.cleanse(input).should.equal(expectedOutput); }); it('should not truncate spaces before periods', function() { var input = '.1, .2, and .3'; var expectedOutput = '.1, .2, and .3'; return SSML.cleanse(input).should.equal(expectedOutput); }); it('should not truncate multiple line breaks', function() { var input = 'First line\n\nSecond line'; var expectedOutput = 'First line\n\nSecond line'; return SSML.cleanse(input).should.equal(expectedOutput); }); it('but should truncate whitespaces and tabs around line breaks', function() { var input = 'First line \n\t \n Second line'; var expectedOutput = 'First line\n\nSecond line'; return SSML.cleanse(input).should.equal(expectedOutput); }); }); }); }); });
{ "content_hash": "21f6f0f6f3e8553ae4ab7030686a0628", "timestamp": "", "source": "github", "line_count": 181, "max_line_length": 197, "avg_line_length": 44.55801104972376, "alnum_prop": 0.607315561066336, "repo_name": "alexa-js/alexa-app", "id": "cda865328fccca64204b3adfc12315bae335c3aa", "size": "8077", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/ssml.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "284" }, { "name": "JavaScript", "bytes": "201695" }, { "name": "TypeScript", "bytes": "1623" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <com.lyft.android.scissors.CropView android:id="@+id/crop_view" android:layout_width="match_parent" android:layout_height="match_parent" app:cropviewViewportRatio="1" /> <android.support.design.widget.FloatingActionButton android:id="@+id/crop_fab" style="@style/FloatingActionButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|center_horizontal" android:layout_margin="@dimen/crop_fab_margin" android:src="@drawable/ic_content_content_cut" /> <android.support.design.widget.FloatingActionButton android:id="@+id/pick_mini_fab" style="@style/FloatingActionButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="@dimen/pick_mini_fab_margin" android:src="@drawable/ic_content_add" app:fabSize="mini" /> </FrameLayout>
{ "content_hash": "e7fbfed7c1c13aaae2661e55e6d3f0a2", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 71, "avg_line_length": 45.13793103448276, "alnum_prop": 0.679144385026738, "repo_name": "mattleibow/XamarinComponents", "id": "1d698589c6da0283fb16ecb877415d6a384e3f7c", "size": "1309", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "Android/Scissors/samples/ScissorsSample/Resources/layout/activity_main.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2854635" }, { "name": "GLSL", "bytes": "2524" }, { "name": "HTML", "bytes": "1746" }, { "name": "Makefile", "bytes": "15731" }, { "name": "Objective-C", "bytes": "1020" }, { "name": "PowerShell", "bytes": "4616" }, { "name": "Ruby", "bytes": "254" }, { "name": "Shell", "bytes": "2873" }, { "name": "Smalltalk", "bytes": "6265" } ], "symlink_target": "" }
package org.springframework.boot.loader; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.util.Arrays; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link InputArgumentsJavaAgentDetector} * * @author Andy Wilkinson */ public class InputArgumentsJavaAgentDetectorTests { @Test public void nonAgentJarsDoNotProduceFalsePositives() throws MalformedURLException, IOException { InputArgumentsJavaAgentDetector detector = new InputArgumentsJavaAgentDetector( Arrays.asList("-javaagent:my-agent.jar")); assertThat(detector.isJavaAgentJar( new File("something-else.jar").getCanonicalFile().toURI().toURL())) .isFalse(); } @Test public void singleJavaAgent() throws MalformedURLException, IOException { InputArgumentsJavaAgentDetector detector = new InputArgumentsJavaAgentDetector( Arrays.asList("-javaagent:my-agent.jar")); assertThat(detector.isJavaAgentJar( new File("my-agent.jar").getCanonicalFile().toURI().toURL())).isTrue(); } @Test public void singleJavaAgentWithOptions() throws MalformedURLException, IOException { InputArgumentsJavaAgentDetector detector = new InputArgumentsJavaAgentDetector( Arrays.asList("-javaagent:my-agent.jar=a=alpha,b=bravo")); assertThat(detector.isJavaAgentJar( new File("my-agent.jar").getCanonicalFile().toURI().toURL())).isTrue(); } @Test public void multipleJavaAgents() throws MalformedURLException, IOException { InputArgumentsJavaAgentDetector detector = new InputArgumentsJavaAgentDetector( Arrays.asList("-javaagent:my-agent.jar", "-javaagent:my-other-agent.jar")); assertThat(detector.isJavaAgentJar( new File("my-agent.jar").getCanonicalFile().toURI().toURL())).isTrue(); assertThat(detector.isJavaAgentJar( new File("my-other-agent.jar").getCanonicalFile().toURI().toURL())) .isTrue(); } }
{ "content_hash": "a974d3b89fb630bd82ad17ab7ff31086", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 85, "avg_line_length": 32.847457627118644, "alnum_prop": 0.762641898864809, "repo_name": "joansmith/spring-boot", "id": "5ca75e65e0d7b9d789cf65834928d6b046441864", "size": "2558", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/InputArgumentsJavaAgentDetectorTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "6954" }, { "name": "CSS", "bytes": "5769" }, { "name": "FreeMarker", "bytes": "2116" }, { "name": "Groovy", "bytes": "39777" }, { "name": "HTML", "bytes": "69819" }, { "name": "Java", "bytes": "7739568" }, { "name": "JavaScript", "bytes": "37789" }, { "name": "Ruby", "bytes": "1305" }, { "name": "SQLPL", "bytes": "20085" }, { "name": "Shell", "bytes": "20227" }, { "name": "Smarty", "bytes": "3276" }, { "name": "XSLT", "bytes": "33894" } ], "symlink_target": "" }