text
stringlengths 4
5.48M
| meta
stringlengths 14
6.54k
|
---|---|
NeuronNetwork_11Stone
=====================
Игра 11 камней с искусственным самообучающимся интеллектом на основе простой нейронной сети.
Правила игры
---------------------
Два игрока по очереди убирают камни из общей кучи. В начале игры в куче лежит 11 камней.
Игрок за один ход может взять либо один камень, либо взять два камня.
Игрок, кто возьмет последний камень из кучи считается победителем.
Дополнительные возможности
---------------------
Так как в начале игры Нейронная система пустая, то есть ее надо обучить, а времени на обучение надо потратить много, специально для ее обучения в меню есть вкладка "Запустить тренер". Данный тренер обучает игру на 1000 итерациях, при этом это можно изменить в настройках в коде программы.
| {'content_hash': 'b4861fdb734a18068ad5b227a180b893', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 288, 'avg_line_length': 49.46666666666667, 'alnum_prop': 0.7425876010781671, 'repo_name': 'evgwed/NeuronNetwork_11Stone', 'id': '24ee502de8714dddd12af89957ab4ea72c30e968', 'size': '1265', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '12094'}]} |
package org.apache.druid.indexing.overlord;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.io.ByteStreams;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.druid.indexer.TaskLocation;
import org.apache.druid.indexer.TaskState;
import org.apache.druid.indexer.TaskStatus;
import org.apache.druid.indexing.common.IndexingServiceCondition;
import org.apache.druid.indexing.common.TestRealtimeTask;
import org.apache.druid.indexing.common.TestTasks;
import org.apache.druid.indexing.common.TestUtils;
import org.apache.druid.indexing.common.task.Task;
import org.apache.druid.indexing.common.task.TaskResource;
import org.apache.druid.indexing.overlord.config.RemoteTaskRunnerConfig;
import org.apache.druid.indexing.worker.Worker;
import org.apache.druid.indexing.worker.config.WorkerConfig;
import org.apache.druid.java.util.common.DateTimes;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.logger.Logger;
import org.apache.druid.java.util.emitter.EmittingLogger;
import org.apache.druid.java.util.emitter.service.ServiceEmitter;
import org.apache.druid.java.util.http.client.HttpClient;
import org.apache.druid.java.util.http.client.Request;
import org.apache.druid.server.metrics.NoopServiceEmitter;
import org.apache.druid.testing.DeadlockDetectingTimeout;
import org.easymock.Capture;
import org.easymock.EasyMock;
import org.joda.time.Period;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.mockito.Mockito;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class RemoteTaskRunnerTest
{
private static final Logger LOG = new Logger(RemoteTaskRunnerTest.class);
private static final Joiner JOINER = RemoteTaskRunnerTestUtils.JOINER;
private static final String WORKER_HOST = "worker";
private static final String ANNOUCEMENTS_PATH = JOINER.join(
RemoteTaskRunnerTestUtils.ANNOUNCEMENTS_PATH,
WORKER_HOST
);
private static final String STATUS_PATH = JOINER.join(RemoteTaskRunnerTestUtils.STATUS_PATH, WORKER_HOST);
// higher timeout to reduce flakiness on CI pipeline
private static final Period TIMEOUT_PERIOD = Period.millis(30000);
private RemoteTaskRunner remoteTaskRunner;
private HttpClient httpClient;
private RemoteTaskRunnerTestUtils rtrTestUtils = new RemoteTaskRunnerTestUtils();
private ObjectMapper jsonMapper;
private CuratorFramework cf;
private Task task;
private Worker worker;
@Rule
public TestRule watcher = new TestWatcher() {
@Override
protected void starting(Description description)
{
LOG.info("Starting test: " + description.getMethodName());
}
@Override
protected void finished(Description description)
{
LOG.info("Finishing test: " + description.getMethodName());
}
};
@Rule
public final TestRule timeout = new DeadlockDetectingTimeout(60, TimeUnit.SECONDS);
@Before
public void setUp() throws Exception
{
rtrTestUtils.setUp();
jsonMapper = rtrTestUtils.getObjectMapper();
cf = rtrTestUtils.getCuratorFramework();
task = TestTasks.unending("task id with spaces");
EmittingLogger.registerEmitter(new NoopServiceEmitter());
}
@After
public void tearDown() throws Exception
{
if (remoteTaskRunner != null) {
remoteTaskRunner.stop();
}
rtrTestUtils.tearDown();
}
@Test
public void testRun() throws Exception
{
doSetup();
Assert.assertEquals(3, remoteTaskRunner.getTotalTaskSlotCount().get(WorkerConfig.DEFAULT_CATEGORY).longValue());
Assert.assertEquals(3, remoteTaskRunner.getIdleTaskSlotCount().get(WorkerConfig.DEFAULT_CATEGORY).longValue());
Assert.assertEquals(0, remoteTaskRunner.getUsedTaskSlotCount().get(WorkerConfig.DEFAULT_CATEGORY).longValue());
ListenableFuture<TaskStatus> result = remoteTaskRunner.run(task);
Assert.assertTrue(taskAnnounced(task.getId()));
mockWorkerRunningTask(task);
Assert.assertTrue(workerRunningTask(task.getId()));
mockWorkerCompleteSuccessfulTask(task);
Assert.assertTrue(workerCompletedTask(result));
Assert.assertEquals(task.getId(), result.get().getId());
Assert.assertEquals(TaskState.SUCCESS, result.get().getStatusCode());
cf.delete().guaranteed().forPath(JOINER.join(STATUS_PATH, task.getId()));
Assert.assertEquals(3, remoteTaskRunner.getTotalTaskSlotCount().get(WorkerConfig.DEFAULT_CATEGORY).longValue());
Assert.assertEquals(3, remoteTaskRunner.getIdleTaskSlotCount().get(WorkerConfig.DEFAULT_CATEGORY).longValue());
Assert.assertEquals(0, remoteTaskRunner.getUsedTaskSlotCount().get(WorkerConfig.DEFAULT_CATEGORY).longValue());
}
@Test
public void testRunTaskThatAlreadyPending() throws Exception
{
doSetup();
remoteTaskRunner.addPendingTask(task);
remoteTaskRunner.runPendingTasks();
Assert.assertFalse(workerRunningTask(task.getId()));
ListenableFuture<TaskStatus> result = remoteTaskRunner.run(task);
Assert.assertTrue(taskAnnounced(task.getId()));
mockWorkerRunningTask(task);
Assert.assertTrue(workerRunningTask(task.getId()));
mockWorkerCompleteSuccessfulTask(task);
Assert.assertTrue(workerCompletedTask(result));
Assert.assertEquals(task.getId(), result.get().getId());
Assert.assertEquals(TaskState.SUCCESS, result.get().getStatusCode());
}
@Test
public void testStartWithNoWorker()
{
makeRemoteTaskRunner(new TestRemoteTaskRunnerConfig(TIMEOUT_PERIOD));
}
@Test
public void testRunExistingTaskThatHasntStartedRunning() throws Exception
{
doSetup();
remoteTaskRunner.run(task);
Assert.assertTrue(taskAnnounced(task.getId()));
ListenableFuture<TaskStatus> result = remoteTaskRunner.run(task);
Assert.assertFalse(result.isDone());
mockWorkerRunningTask(task);
Assert.assertTrue(workerRunningTask(task.getId()));
mockWorkerCompleteSuccessfulTask(task);
Assert.assertTrue(workerCompletedTask(result));
Assert.assertEquals(task.getId(), result.get().getId());
Assert.assertEquals(TaskState.SUCCESS, result.get().getStatusCode());
}
@Test
public void testRunExistingTaskThatHasStartedRunning() throws Exception
{
doSetup();
remoteTaskRunner.run(task);
Assert.assertTrue(taskAnnounced(task.getId()));
mockWorkerRunningTask(task);
Assert.assertTrue(workerRunningTask(task.getId()));
ListenableFuture<TaskStatus> result = remoteTaskRunner.run(task);
Assert.assertFalse(result.isDone());
mockWorkerCompleteSuccessfulTask(task);
Assert.assertTrue(workerCompletedTask(result));
Assert.assertEquals(task.getId(), result.get().getId());
Assert.assertEquals(TaskState.SUCCESS, result.get().getStatusCode());
}
@Test
public void testRunTooMuchZKData() throws Exception
{
ServiceEmitter emitter = EasyMock.createMock(ServiceEmitter.class);
EmittingLogger.registerEmitter(emitter);
EasyMock.replay(emitter);
doSetup();
remoteTaskRunner.run(TestTasks.unending(new String(new char[5000])));
EasyMock.verify(emitter);
}
@Test
public void testRunSameAvailabilityGroup() throws Exception
{
doSetup();
TestRealtimeTask task1 = new TestRealtimeTask(
"rt1",
new TaskResource("rt1", 1),
"foo",
TaskStatus.running("rt1"),
jsonMapper
);
remoteTaskRunner.run(task1);
Assert.assertTrue(taskAnnounced(task1.getId()));
mockWorkerRunningTask(task1);
TestRealtimeTask task2 = new TestRealtimeTask(
"rt2",
new TaskResource("rt1", 1),
"foo",
TaskStatus.running("rt2"),
jsonMapper
);
remoteTaskRunner.run(task2);
TestRealtimeTask task3 = new TestRealtimeTask(
"rt3",
new TaskResource("rt2", 1),
"foo",
TaskStatus.running("rt3"),
jsonMapper
);
remoteTaskRunner.run(task3);
Assert.assertTrue(
TestUtils.conditionValid(
new IndexingServiceCondition()
{
@Override
public boolean isValid()
{
return remoteTaskRunner.getRunningTasks().size() == 2;
}
}
)
);
Assert.assertTrue(
TestUtils.conditionValid(
new IndexingServiceCondition()
{
@Override
public boolean isValid()
{
return remoteTaskRunner.getPendingTasks().size() == 1;
}
}
)
);
Assert.assertTrue(remoteTaskRunner.getPendingTasks().iterator().next().getTaskId().equals("rt2"));
}
@Test
public void testRunWithCapacity() throws Exception
{
doSetup();
TestRealtimeTask task1 = new TestRealtimeTask(
"rt1",
new TaskResource("rt1", 1),
"foo",
TaskStatus.running("rt1"),
jsonMapper
);
remoteTaskRunner.run(task1);
Assert.assertTrue(taskAnnounced(task1.getId()));
mockWorkerRunningTask(task1);
TestRealtimeTask task2 = new TestRealtimeTask(
"rt2",
new TaskResource("rt2", 3),
"foo",
TaskStatus.running("rt2"),
jsonMapper
);
remoteTaskRunner.run(task2);
TestRealtimeTask task3 = new TestRealtimeTask(
"rt3",
new TaskResource("rt3", 2),
"foo",
TaskStatus.running("rt3"),
jsonMapper
);
remoteTaskRunner.run(task3);
Assert.assertTrue(taskAnnounced(task3.getId()));
mockWorkerRunningTask(task3);
Assert.assertTrue(
TestUtils.conditionValid(
new IndexingServiceCondition()
{
@Override
public boolean isValid()
{
return remoteTaskRunner.getRunningTasks().size() == 2;
}
}
)
);
Assert.assertTrue(
TestUtils.conditionValid(
new IndexingServiceCondition()
{
@Override
public boolean isValid()
{
return remoteTaskRunner.getPendingTasks().size() == 1;
}
}
)
);
Assert.assertTrue(remoteTaskRunner.getPendingTasks().iterator().next().getTaskId().equals("rt2"));
}
@Test
public void testStatusRemoved() throws Exception
{
doSetup();
ListenableFuture<TaskStatus> future = remoteTaskRunner.run(task);
Assert.assertTrue(taskAnnounced(task.getId()));
mockWorkerRunningTask(task);
Assert.assertTrue(workerRunningTask(task.getId()));
Assert.assertTrue(remoteTaskRunner.getRunningTasks().iterator().next().getTaskId().equals(task.getId()));
cf.delete().forPath(JOINER.join(STATUS_PATH, task.getId()));
TaskStatus status = future.get();
Assert.assertEquals(status.getStatusCode(), TaskState.FAILED);
Assert.assertNotNull(status.getErrorMsg());
Assert.assertTrue(status.getErrorMsg().contains("The worker that this task was assigned disappeared"));
}
@Test
public void testBootstrap() throws Exception
{
makeWorker();
RemoteTaskRunnerConfig rtrConfig = new TestRemoteTaskRunnerConfig(TIMEOUT_PERIOD);
rtrConfig.setMaxPercentageBlacklistWorkers(100);
makeRemoteTaskRunner(rtrConfig);
TestRealtimeTask task1 = new TestRealtimeTask(
"first",
new TaskResource("first", 1),
"foo",
TaskStatus.running("first"),
jsonMapper
);
remoteTaskRunner.run(task1);
Assert.assertTrue(taskAnnounced(task1.getId()));
mockWorkerRunningTask(task1);
TestRealtimeTask task = new TestRealtimeTask(
"second",
new TaskResource("task", 2),
"foo",
TaskStatus.running("task"),
jsonMapper
);
remoteTaskRunner.run(task);
TestRealtimeTask task2 = new TestRealtimeTask(
"second",
new TaskResource("second", 2),
"foo",
TaskStatus.running("second"),
jsonMapper
);
remoteTaskRunner.run(task2);
Assert.assertTrue(taskAnnounced(task2.getId()));
mockWorkerRunningTask(task2);
final Set<String> runningTasks = Sets.newHashSet(
Iterables.transform(
remoteTaskRunner.getRunningTasks(),
new Function<RemoteTaskRunnerWorkItem, String>()
{
@Override
public String apply(RemoteTaskRunnerWorkItem input)
{
return input.getTaskId();
}
}
)
);
Assert.assertEquals("runningTasks", ImmutableSet.of("first", "second"), runningTasks);
}
@Test
public void testRunWithTaskComplete() throws Exception
{
doSetup();
TestRealtimeTask task1 = new TestRealtimeTask(
"testTask",
new TaskResource("testTask", 2),
"foo",
TaskStatus.success("testTask"),
jsonMapper
);
remoteTaskRunner.run(task1);
Assert.assertTrue(taskAnnounced(task1.getId()));
mockWorkerRunningTask(task1);
mockWorkerCompleteSuccessfulTask(task1);
Assert.assertEquals(TaskState.SUCCESS, remoteTaskRunner.run(task1).get().getStatusCode());
}
@Test
public void testWorkerRemoved() throws Exception
{
doSetup();
Assert.assertEquals(3, remoteTaskRunner.getTotalTaskSlotCount().get(WorkerConfig.DEFAULT_CATEGORY).longValue());
Assert.assertEquals(3, remoteTaskRunner.getIdleTaskSlotCount().get(WorkerConfig.DEFAULT_CATEGORY).longValue());
Future<TaskStatus> future = remoteTaskRunner.run(task);
Assert.assertTrue(taskAnnounced(task.getId()));
mockWorkerRunningTask(task);
Assert.assertTrue(workerRunningTask(task.getId()));
cf.delete().forPath(ANNOUCEMENTS_PATH);
TaskStatus status = future.get();
Assert.assertEquals(TaskState.FAILED, status.getStatusCode());
Assert.assertNotNull(status.getErrorMsg());
Assert.assertTrue(status.getErrorMsg().contains("Canceled for worker cleanup"));
RemoteTaskRunnerConfig config = remoteTaskRunner.getRemoteTaskRunnerConfig();
Assert.assertTrue(
TestUtils.conditionValid(
new IndexingServiceCondition()
{
@Override
public boolean isValid()
{
return remoteTaskRunner.getRemovedWorkerCleanups().isEmpty();
}
},
// cleanup task is independently scheduled by event listener. we need to wait some more time.
config.getTaskCleanupTimeout().toStandardDuration().getMillis() * 2
)
);
Assert.assertNull(cf.checkExists().forPath(STATUS_PATH));
Assert.assertFalse(remoteTaskRunner.getTotalTaskSlotCount().containsKey(WorkerConfig.DEFAULT_CATEGORY));
Assert.assertFalse(remoteTaskRunner.getIdleTaskSlotCount().containsKey(WorkerConfig.DEFAULT_CATEGORY));
}
@Test
public void testWorkerDisabled() throws Exception
{
doSetup();
final ListenableFuture<TaskStatus> result = remoteTaskRunner.run(task);
Assert.assertTrue(taskAnnounced(task.getId()));
mockWorkerRunningTask(task);
Assert.assertTrue(workerRunningTask(task.getId()));
// Disable while task running
disableWorker();
// Continue test
mockWorkerCompleteSuccessfulTask(task);
Assert.assertTrue(workerCompletedTask(result));
Assert.assertEquals(task.getId(), result.get().getId());
Assert.assertEquals(TaskState.SUCCESS, result.get().getStatusCode());
// Confirm RTR thinks the worker is disabled.
Assert.assertEquals("", Iterables.getOnlyElement(remoteTaskRunner.getWorkers()).getWorker().getVersion());
}
@Test
public void testRestartRemoteTaskRunner() throws Exception
{
doSetup();
remoteTaskRunner.run(task);
Assert.assertTrue(taskAnnounced(task.getId()));
mockWorkerRunningTask(task);
Assert.assertTrue(workerRunningTask(task.getId()));
remoteTaskRunner.stop();
makeRemoteTaskRunner(new TestRemoteTaskRunnerConfig(TIMEOUT_PERIOD));
final RemoteTaskRunnerWorkItem newWorkItem = remoteTaskRunner
.getKnownTasks()
.stream()
.filter(workItem -> workItem.getTaskId().equals(task.getId()))
.findFirst()
.orElse(null);
final ListenableFuture<TaskStatus> result = newWorkItem.getResult();
mockWorkerCompleteSuccessfulTask(task);
Assert.assertTrue(workerCompletedTask(result));
Assert.assertEquals(task.getId(), result.get().getId());
Assert.assertEquals(TaskState.SUCCESS, result.get().getStatusCode());
}
@Test
public void testRunPendingTaskFailToAssignTask() throws Exception
{
doSetup();
Thread.sleep(100);
RemoteTaskRunnerWorkItem originalItem = remoteTaskRunner.addPendingTask(task);
// modify taskId to make task assignment failed
RemoteTaskRunnerWorkItem wankyItem = Mockito.mock(RemoteTaskRunnerWorkItem.class);
Mockito.when(wankyItem.getTaskId()).thenReturn(originalItem.getTaskId()).thenReturn("wrongId");
remoteTaskRunner.runPendingTask(wankyItem);
TaskStatus taskStatus = originalItem.getResult().get(0, TimeUnit.MILLISECONDS);
Assert.assertEquals(TaskState.FAILED, taskStatus.getStatusCode());
Assert.assertEquals(
"Failed to assign this task. See overlord logs for more details.",
taskStatus.getErrorMsg()
);
}
@Test
public void testRunPendingTaskTimeoutToAssign() throws Exception
{
makeWorker();
makeRemoteTaskRunner(new TestRemoteTaskRunnerConfig(TIMEOUT_PERIOD));
RemoteTaskRunnerWorkItem workItem = remoteTaskRunner.addPendingTask(task);
remoteTaskRunner.runPendingTask(workItem);
TaskStatus taskStatus = workItem.getResult().get(0, TimeUnit.MILLISECONDS);
Assert.assertEquals(TaskState.FAILED, taskStatus.getStatusCode());
Assert.assertNotNull(taskStatus.getErrorMsg());
Assert.assertTrue(
taskStatus.getErrorMsg().startsWith("The worker that this task is assigned did not start it in timeout")
);
}
private void doSetup() throws Exception
{
makeWorker();
makeRemoteTaskRunner(new TestRemoteTaskRunnerConfig(TIMEOUT_PERIOD));
}
private void makeRemoteTaskRunner(RemoteTaskRunnerConfig config)
{
httpClient = EasyMock.createMock(HttpClient.class);
remoteTaskRunner = rtrTestUtils.makeRemoteTaskRunner(config, httpClient);
}
private void makeWorker() throws Exception
{
worker = rtrTestUtils.makeWorker(WORKER_HOST, 3);
}
private void disableWorker() throws Exception
{
rtrTestUtils.disableWorker(worker);
}
private boolean taskAnnounced(final String taskId)
{
return rtrTestUtils.taskAnnounced(WORKER_HOST, taskId);
}
private boolean workerRunningTask(final String taskId)
{
return rtrTestUtils.workerRunningTask(WORKER_HOST, taskId);
}
private boolean workerCompletedTask(final ListenableFuture<TaskStatus> result)
{
return TestUtils.conditionValid(
new IndexingServiceCondition()
{
@Override
public boolean isValid()
{
return result.isDone();
}
}
);
}
private void mockWorkerRunningTask(final Task task) throws Exception
{
rtrTestUtils.mockWorkerRunningTask("worker", task);
}
private void mockWorkerCompleteSuccessfulTask(final Task task) throws Exception
{
rtrTestUtils.mockWorkerCompleteSuccessfulTask("worker", task);
}
private void mockWorkerCompleteFailedTask(final Task task) throws Exception
{
rtrTestUtils.mockWorkerCompleteFailedTask("worker", task);
}
@Test
public void testFindLazyWorkerTaskRunning() throws Exception
{
doSetup();
remoteTaskRunner.start();
remoteTaskRunner.run(task);
Assert.assertTrue(taskAnnounced(task.getId()));
mockWorkerRunningTask(task);
Collection<Worker> lazyworkers = remoteTaskRunner.markWorkersLazy(
new Predicate<ImmutableWorkerInfo>()
{
@Override
public boolean apply(ImmutableWorkerInfo input)
{
return true;
}
}, 1
);
Assert.assertTrue(lazyworkers.isEmpty());
Assert.assertTrue(remoteTaskRunner.getLazyWorkers().isEmpty());
Assert.assertEquals(1, remoteTaskRunner.getWorkers().size());
}
@Test
public void testFindLazyWorkerForWorkerJustAssignedTask() throws Exception
{
doSetup();
remoteTaskRunner.run(task);
Assert.assertTrue(taskAnnounced(task.getId()));
Collection<Worker> lazyworkers = remoteTaskRunner.markWorkersLazy(
new Predicate<ImmutableWorkerInfo>()
{
@Override
public boolean apply(ImmutableWorkerInfo input)
{
return true;
}
}, 1
);
Assert.assertTrue(lazyworkers.isEmpty());
Assert.assertTrue(remoteTaskRunner.getLazyWorkers().isEmpty());
Assert.assertEquals(1, remoteTaskRunner.getWorkers().size());
}
@Test
public void testFindLazyWorkerNotRunningAnyTask() throws Exception
{
doSetup();
Collection<Worker> lazyworkers = remoteTaskRunner.markWorkersLazy(
new Predicate<ImmutableWorkerInfo>()
{
@Override
public boolean apply(ImmutableWorkerInfo input)
{
return true;
}
}, 1
);
Assert.assertEquals(1, lazyworkers.size());
Assert.assertEquals(1, remoteTaskRunner.getLazyWorkers().size());
Assert.assertEquals(3, remoteTaskRunner.getTotalTaskSlotCount().get(WorkerConfig.DEFAULT_CATEGORY).longValue());
Assert.assertFalse(remoteTaskRunner.getIdleTaskSlotCount().containsKey(WorkerConfig.DEFAULT_CATEGORY));
Assert.assertEquals(3, remoteTaskRunner.getLazyTaskSlotCount().get(WorkerConfig.DEFAULT_CATEGORY).longValue());
}
@Test
public void testFindLazyWorkerNotRunningAnyTaskButWithZeroMaxWorkers() throws Exception
{
doSetup();
Collection<Worker> lazyworkers = remoteTaskRunner.markWorkersLazy(
new Predicate<ImmutableWorkerInfo>()
{
@Override
public boolean apply(ImmutableWorkerInfo input)
{
return true;
}
}, 0
);
Assert.assertEquals(0, lazyworkers.size());
Assert.assertEquals(0, remoteTaskRunner.getLazyWorkers().size());
}
@Test
public void testWorkerZKReconnect() throws Exception
{
makeWorker();
makeRemoteTaskRunner(new TestRemoteTaskRunnerConfig(new Period("PT5M")));
Future<TaskStatus> future = remoteTaskRunner.run(task);
Assert.assertTrue(taskAnnounced(task.getId()));
mockWorkerRunningTask(task);
Assert.assertTrue(workerRunningTask(task.getId()));
byte[] bytes = cf.getData().forPath(ANNOUCEMENTS_PATH);
cf.delete().forPath(ANNOUCEMENTS_PATH);
// worker task cleanup scheduled
Assert.assertTrue(
TestUtils.conditionValid(
new IndexingServiceCondition()
{
@Override
public boolean isValid()
{
return remoteTaskRunner.getRemovedWorkerCleanups().containsKey(worker.getHost());
}
}
)
);
// Worker got reconnected
cf.create().forPath(ANNOUCEMENTS_PATH, bytes);
// worker task cleanup should get cancelled and removed
Assert.assertTrue(
TestUtils.conditionValid(
new IndexingServiceCondition()
{
@Override
public boolean isValid()
{
return !remoteTaskRunner.getRemovedWorkerCleanups().containsKey(worker.getHost());
}
}
)
);
mockWorkerCompleteSuccessfulTask(task);
TaskStatus status = future.get();
Assert.assertEquals(status.getStatusCode(), TaskState.SUCCESS);
Assert.assertEquals(TaskState.SUCCESS, status.getStatusCode());
}
@Test
public void testSortByInsertionTime()
{
RemoteTaskRunnerWorkItem item1 = new RemoteTaskRunnerWorkItem("b", "t", null, null, "ds_test")
.withQueueInsertionTime(DateTimes.of("2015-01-01T00:00:03Z"));
RemoteTaskRunnerWorkItem item2 = new RemoteTaskRunnerWorkItem("a", "t", null, null, "ds_test")
.withQueueInsertionTime(DateTimes.of("2015-01-01T00:00:02Z"));
RemoteTaskRunnerWorkItem item3 = new RemoteTaskRunnerWorkItem("c", "t", null, null, "ds_test")
.withQueueInsertionTime(DateTimes.of("2015-01-01T00:00:01Z"));
ArrayList<RemoteTaskRunnerWorkItem> workItems = Lists.newArrayList(item1, item2, item3);
RemoteTaskRunner.sortByInsertionTime(workItems);
Assert.assertEquals(item3, workItems.get(0));
Assert.assertEquals(item2, workItems.get(1));
Assert.assertEquals(item1, workItems.get(2));
}
@Test
public void testBlacklistZKWorkers() throws Exception
{
makeWorker();
RemoteTaskRunnerConfig rtrConfig = new TestRemoteTaskRunnerConfig(TIMEOUT_PERIOD);
rtrConfig.setMaxPercentageBlacklistWorkers(100);
makeRemoteTaskRunner(rtrConfig);
TestRealtimeTask task1 = new TestRealtimeTask(
"realtime1",
new TaskResource("realtime1", 1),
"foo",
TaskStatus.success("realtime1"),
jsonMapper
);
Future<TaskStatus> taskFuture1 = remoteTaskRunner.run(task1);
Assert.assertTrue(taskAnnounced(task1.getId()));
mockWorkerRunningTask(task1);
mockWorkerCompleteFailedTask(task1);
Assert.assertTrue(taskFuture1.get().isFailure());
Assert.assertEquals(0, remoteTaskRunner.getBlackListedWorkers().size());
Assert.assertEquals(
1,
remoteTaskRunner.findWorkerRunningTask(task1.getId()).getContinuouslyFailedTasksCount()
);
TestRealtimeTask task2 = new TestRealtimeTask(
"realtime2",
new TaskResource("realtime2", 1),
"foo",
TaskStatus.running("realtime2"),
jsonMapper
);
Future<TaskStatus> taskFuture2 = remoteTaskRunner.run(task2);
Assert.assertTrue(taskAnnounced(task2.getId()));
mockWorkerRunningTask(task2);
mockWorkerCompleteFailedTask(task2);
Assert.assertTrue(taskFuture2.get().isFailure());
Assert.assertEquals(1, remoteTaskRunner.getBlackListedWorkers().size());
Assert.assertEquals(
2,
remoteTaskRunner.findWorkerRunningTask(task2.getId()).getContinuouslyFailedTasksCount()
);
((RemoteTaskRunnerTestUtils.TestableRemoteTaskRunner) remoteTaskRunner)
.setCurrentTimeMillis(System.currentTimeMillis());
remoteTaskRunner.checkBlackListedNodes();
Assert.assertEquals(1, remoteTaskRunner.getBlackListedWorkers().size());
((RemoteTaskRunnerTestUtils.TestableRemoteTaskRunner) remoteTaskRunner)
.setCurrentTimeMillis(System.currentTimeMillis() + 2 * TIMEOUT_PERIOD.toStandardDuration().getMillis());
remoteTaskRunner.checkBlackListedNodes();
// After backOffTime the nodes are removed from blacklist
Assert.assertEquals(0, remoteTaskRunner.getBlackListedWorkers().size());
Assert.assertEquals(
0,
remoteTaskRunner.findWorkerRunningTask(task2.getId()).getContinuouslyFailedTasksCount()
);
TestRealtimeTask task3 = new TestRealtimeTask(
"realtime3",
new TaskResource("realtime3", 1),
"foo",
TaskStatus.running("realtime3"),
jsonMapper
);
Future<TaskStatus> taskFuture3 = remoteTaskRunner.run(task3);
Assert.assertTrue(taskAnnounced(task3.getId()));
mockWorkerRunningTask(task3);
mockWorkerCompleteSuccessfulTask(task3);
Assert.assertTrue(taskFuture3.get().isSuccess());
Assert.assertEquals(0, remoteTaskRunner.getBlackListedWorkers().size());
Assert.assertEquals(
0,
remoteTaskRunner.findWorkerRunningTask(task3.getId()).getContinuouslyFailedTasksCount()
);
}
/**
* With 2 workers and maxPercentageBlacklistWorkers(25), neither worker should ever be blacklisted even after
* exceeding maxRetriesBeforeBlacklist.
*/
@Test
public void testBlacklistZKWorkers25Percent() throws Exception
{
rtrTestUtils.makeWorker("worker", 10);
rtrTestUtils.makeWorker("worker2", 10);
RemoteTaskRunnerConfig rtrConfig = new TestRemoteTaskRunnerConfig(TIMEOUT_PERIOD);
rtrConfig.setMaxPercentageBlacklistWorkers(25);
makeRemoteTaskRunner(rtrConfig);
String firstWorker = null;
String secondWorker = null;
for (int i = 1; i < 13; i++) {
String taskId = StringUtils.format("rt-%d", i);
TestRealtimeTask task = new TestRealtimeTask(
taskId,
new TaskResource(taskId, 1),
"foo",
TaskStatus.success(taskId),
jsonMapper
);
Future<TaskStatus> taskFuture = remoteTaskRunner.run(task);
if (i == 1) {
if (rtrTestUtils.taskAnnounced("worker2", task.getId())) {
firstWorker = "worker2";
secondWorker = "worker";
} else {
firstWorker = "worker";
secondWorker = "worker2";
}
}
final String expectedWorker = i % 2 == 0 ? secondWorker : firstWorker;
Assert.assertTrue(rtrTestUtils.taskAnnounced(expectedWorker, task.getId()));
rtrTestUtils.mockWorkerRunningTask(expectedWorker, task);
rtrTestUtils.mockWorkerCompleteFailedTask(expectedWorker, task);
Assert.assertTrue(taskFuture.get().isFailure());
Assert.assertEquals(0, remoteTaskRunner.getBlackListedWorkers().size());
Assert.assertEquals(
((i + 1) / 2),
remoteTaskRunner.findWorkerRunningTask(task.getId()).getContinuouslyFailedTasksCount()
);
}
}
/**
* With 2 workers and maxPercentageBlacklistWorkers(50), one worker should get blacklisted after the second failure
* and the second worker should never be blacklisted even after exceeding maxRetriesBeforeBlacklist.
*/
@Test
public void testBlacklistZKWorkers50Percent() throws Exception
{
rtrTestUtils.makeWorker("worker", 10);
rtrTestUtils.makeWorker("worker2", 10);
RemoteTaskRunnerConfig rtrConfig = new TestRemoteTaskRunnerConfig(TIMEOUT_PERIOD);
rtrConfig.setMaxPercentageBlacklistWorkers(50);
makeRemoteTaskRunner(rtrConfig);
String firstWorker = null;
String secondWorker = null;
for (int i = 1; i < 13; i++) {
String taskId = StringUtils.format("rt-%d", i);
TestRealtimeTask task = new TestRealtimeTask(
taskId,
new TaskResource(taskId, 1),
"foo",
TaskStatus.success(taskId),
jsonMapper
);
Future<TaskStatus> taskFuture = remoteTaskRunner.run(task);
if (i == 1) {
if (rtrTestUtils.taskAnnounced("worker2", task.getId())) {
firstWorker = "worker2";
secondWorker = "worker";
} else {
firstWorker = "worker";
secondWorker = "worker2";
}
}
final String expectedWorker = i % 2 == 0 || i > 4 ? secondWorker : firstWorker;
Assert.assertTrue(rtrTestUtils.taskAnnounced(expectedWorker, task.getId()));
rtrTestUtils.mockWorkerRunningTask(expectedWorker, task);
rtrTestUtils.mockWorkerCompleteFailedTask(expectedWorker, task);
Assert.assertTrue(taskFuture.get().isFailure());
Assert.assertEquals(i > 2 ? 1 : 0, remoteTaskRunner.getBlackListedWorkers().size());
Assert.assertEquals(
i > 4 ? i - 2 : ((i + 1) / 2),
remoteTaskRunner.findWorkerRunningTask(task.getId()).getContinuouslyFailedTasksCount()
);
}
}
@Test
public void testSuccessfulTaskOnBlacklistedWorker() throws Exception
{
makeWorker();
RemoteTaskRunnerConfig rtrConfig = new TestRemoteTaskRunnerConfig(TIMEOUT_PERIOD);
rtrConfig.setMaxPercentageBlacklistWorkers(100);
makeRemoteTaskRunner(rtrConfig);
TestRealtimeTask task1 = new TestRealtimeTask(
"realtime1", new TaskResource("realtime1", 1), "foo", TaskStatus.success("realtime1"), jsonMapper
);
TestRealtimeTask task2 = new TestRealtimeTask(
"realtime2", new TaskResource("realtime2", 1), "foo", TaskStatus.success("realtime2"), jsonMapper
);
TestRealtimeTask task3 = new TestRealtimeTask(
"realtime3", new TaskResource("realtime3", 1), "foo", TaskStatus.success("realtime3"), jsonMapper
);
Future<TaskStatus> taskFuture1 = remoteTaskRunner.run(task1);
Assert.assertTrue(taskAnnounced(task1.getId()));
mockWorkerRunningTask(task1);
mockWorkerCompleteFailedTask(task1);
Assert.assertTrue(taskFuture1.get().isFailure());
Assert.assertEquals(0, remoteTaskRunner.getBlackListedWorkers().size());
Assert.assertFalse(remoteTaskRunner.getBlacklistedTaskSlotCount().containsKey(WorkerConfig.DEFAULT_CATEGORY));
Future<TaskStatus> taskFuture2 = remoteTaskRunner.run(task2);
Assert.assertTrue(taskAnnounced(task2.getId()));
mockWorkerRunningTask(task2);
Assert.assertFalse(remoteTaskRunner.getBlacklistedTaskSlotCount().containsKey(WorkerConfig.DEFAULT_CATEGORY));
Future<TaskStatus> taskFuture3 = remoteTaskRunner.run(task3);
Assert.assertTrue(taskAnnounced(task3.getId()));
mockWorkerRunningTask(task3);
mockWorkerCompleteFailedTask(task3);
Assert.assertTrue(taskFuture3.get().isFailure());
Assert.assertEquals(1, remoteTaskRunner.getBlackListedWorkers().size());
Assert.assertEquals(
3,
remoteTaskRunner.getBlacklistedTaskSlotCount().get(WorkerConfig.DEFAULT_CATEGORY).longValue()
);
mockWorkerCompleteSuccessfulTask(task2);
Assert.assertTrue(taskFuture2.get().isSuccess());
Assert.assertEquals(0, remoteTaskRunner.getBlackListedWorkers().size());
Assert.assertFalse(remoteTaskRunner.getBlacklistedTaskSlotCount().containsKey(WorkerConfig.DEFAULT_CATEGORY));
}
@Test
public void testStatusListenerEventDataNullShouldNotThrowException() throws Exception
{
// Set up mock emitter to verify log alert when exception is thrown inside the status listener
Worker worker = EasyMock.createMock(Worker.class);
EasyMock.expect(worker.getHost()).andReturn("host").atLeastOnce();
EasyMock.replay(worker);
ServiceEmitter emitter = EasyMock.createMock(ServiceEmitter.class);
Capture<EmittingLogger.EmittingAlertBuilder> capturedArgument = Capture.newInstance();
emitter.emit(EasyMock.capture(capturedArgument));
EasyMock.expectLastCall().atLeastOnce();
EmittingLogger.registerEmitter(emitter);
EasyMock.replay(emitter);
PathChildrenCache cache = new PathChildrenCache(cf, "/test", true);
testStartWithNoWorker();
cache.getListenable()
.addListener(remoteTaskRunner.getStatusListener(worker, new ZkWorker(worker, cache, jsonMapper), null));
cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
// Status listener will recieve event with null data
Assert.assertTrue(
TestUtils.conditionValid(() -> cache.getCurrentData().size() == 1)
);
// Verify that the log emitter was called
EasyMock.verify(worker);
EasyMock.verify(emitter);
Map<String, Object> alertDataMap = capturedArgument.getValue().build(null).getDataMap();
Assert.assertTrue(alertDataMap.containsKey("znode"));
Assert.assertNull(alertDataMap.get("znode"));
// Status listener should successfully completes without throwing exception
}
@Test
public void testStreamTaskReportsUnknownTask() throws Exception
{
doSetup();
Assert.assertEquals(Optional.absent(), remoteTaskRunner.streamTaskReports("foo"));
}
@Test
public void testStreamTaskReportsKnownTask() throws Exception
{
doSetup();
final Capture<Request> capturedRequest = Capture.newInstance();
final String reportString = "my report!";
final ByteArrayInputStream reportResponse = new ByteArrayInputStream(StringUtils.toUtf8(reportString));
EasyMock.expect(httpClient.go(EasyMock.capture(capturedRequest), EasyMock.anyObject()))
.andReturn(Futures.immediateFuture(reportResponse));
EasyMock.replay(httpClient);
ListenableFuture<TaskStatus> result = remoteTaskRunner.run(task);
Assert.assertTrue(taskAnnounced(task.getId()));
mockWorkerRunningTask(task);
// Wait for the task to have a known location.
Assert.assertTrue(
TestUtils.conditionValid(
() ->
!remoteTaskRunner.getRunningTasks().isEmpty()
&& !Iterables.getOnlyElement(remoteTaskRunner.getRunningTasks())
.getLocation()
.equals(TaskLocation.unknown())
)
);
// Stream task reports from a running task.
final InputStream in = remoteTaskRunner.streamTaskReports(task.getId()).get();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteStreams.copy(in, baos);
Assert.assertEquals(reportString, StringUtils.fromUtf8(baos.toByteArray()));
// Stream task reports from a completed task.
mockWorkerCompleteSuccessfulTask(task);
Assert.assertTrue(workerCompletedTask(result));
Assert.assertEquals(Optional.absent(), remoteTaskRunner.streamTaskReports(task.getId()));
// Verify the HTTP request.
EasyMock.verify(httpClient);
Assert.assertEquals(
"http://dummy:9000/druid/worker/v1/chat/task%20id%20with%20spaces/liveReports",
capturedRequest.getValue().getUrl().toString()
);
}
}
| {'content_hash': 'd2b931f55a2fbc1b729b9782fa78b7c2', 'timestamp': '', 'source': 'github', 'line_count': 1120, 'max_line_length': 117, 'avg_line_length': 33.9375, 'alnum_prop': 0.7010786635096027, 'repo_name': 'monetate/druid', 'id': '796ba351c4ad0e69604fad9e3c6b8687fe887879', 'size': '38817', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'indexing-service/src/test/java/org/apache/druid/indexing/overlord/RemoteTaskRunnerTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '5547'}, {'name': 'CSS', 'bytes': '3690'}, {'name': 'Dockerfile', 'bytes': '13080'}, {'name': 'FreeMarker', 'bytes': '10369'}, {'name': 'HTML', 'bytes': '2540'}, {'name': 'Java', 'bytes': '44823997'}, {'name': 'JavaScript', 'bytes': '65990'}, {'name': 'Makefile', 'bytes': '659'}, {'name': 'PostScript', 'bytes': '5'}, {'name': 'Python', 'bytes': '76196'}, {'name': 'R', 'bytes': '17002'}, {'name': 'Roff', 'bytes': '3617'}, {'name': 'SCSS', 'bytes': '183582'}, {'name': 'Shell', 'bytes': '137617'}, {'name': 'Smarty', 'bytes': '3517'}, {'name': 'TeX', 'bytes': '399468'}, {'name': 'Thrift', 'bytes': '1003'}, {'name': 'TypeScript', 'bytes': '1985704'}]} |
<!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_25) on Sat Jan 30 13:02:51 EST 2016 -->
<title>Record</title>
<meta name="date" content="2016-01-30">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Record";
}
//-->
</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="class-use/Record.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li><a href="../../../../ec/algorithms/aco/core/WalkedPath.html" title="class in ec.algorithms.aco.core"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?ec/algorithms/aco/core/Record.html" target="_top">Frames</a></li>
<li><a href="Record.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: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#methods_inherited_from_class_java.lang.Object">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">ec.algorithms.aco.core</div>
<h2 title="Class Record" class="title">Class Record</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>ec.algorithms.aco.core.Record</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="strong">Record</span>
extends java.lang.Object</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>double</code></td>
<td class="colLast"><code><strong><a href="../../../../ec/algorithms/aco/core/Record.html#x">x</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>double</code></td>
<td class="colLast"><code><strong><a href="../../../../ec/algorithms/aco/core/Record.html#y">y</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../ec/algorithms/aco/core/Record.html#Record(double, double)">Record</a></strong>(double x,
double y)</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="x">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>x</h4>
<pre>public double x</pre>
</li>
</ul>
<a name="y">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>y</h4>
<pre>public double y</pre>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="Record(double, double)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>Record</h4>
<pre>public Record(double x,
double y)</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="class-use/Record.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li><a href="../../../../ec/algorithms/aco/core/WalkedPath.html" title="class in ec.algorithms.aco.core"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?ec/algorithms/aco/core/Record.html" target="_top">Frames</a></li>
<li><a href="Record.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: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#methods_inherited_from_class_java.lang.Object">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {'content_hash': '2f5c47f979bc73a0f1f066760a52f839', 'timestamp': '', 'source': 'github', 'line_count': 279, 'max_line_length': 152, 'avg_line_length': 30.2831541218638, 'alnum_prop': 0.614155521363475, 'repo_name': 'aawuley/evolutionary-computation', 'id': 'a90b642947c26414f41f1f93c1c2ac9233a026fc', 'size': '8449', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/ec/algorithms/aco/core/Record.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '760793'}]} |
@interface ViewController : UIViewController
- (IBAction)selectAPhoto:(id)sender;
@end
| {'content_hash': '5e0ecdc6c27c5371c682ecfb06f23a6a', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 44, 'avg_line_length': 29.0, 'alnum_prop': 0.8045977011494253, 'repo_name': 'Hazems-Camaroons/image-manipulation', 'id': 'e891c04981a5a8899c01c9593166ea065aad7445', 'size': '312', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Image Manipulator/ViewController~.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '32622'}]} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '9046b26aa191c31cb73603126b39372c', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': '62d59d1b9e81907166b44bac50d64d3696061795', 'size': '170', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Solanales/Solanaceae/Browallia/Browallia demissa/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
import sklearn.cluster
from kmeans_gap import GAP
import grace
import grace.mask
import numpy as np
import sys
parallel = int(sys.argv[1] if (len(sys.argv) > 1) else 1)
if __name__=='__main__':
shape = grace.grids.shape
X = grace.grids.reshape(shape[0] * shape[1], shape[2])
mask = grace.mask.world().reshape(shape[0] * shape[1])
X = X[mask, :]
optimizer = GAP(verbose=True)
estimator = sklearn.cluster.KMeans(n_init=1, n_jobs=parallel)
optimizer.calculate(X, estimator, sims=20, ks=range(1,21))
np.savez('HPC-output/gap.npz', **optimizer.dump())
(K, G, sd) = optimizer.optimal()
print "Optimal amount of clusters: %d" % (K)
| {'content_hash': '46c5133940bc92f5d300fb2d19b3ecf0', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 62, 'avg_line_length': 27.82608695652174, 'alnum_prop': 0.684375, 'repo_name': 'AndreasMadsen/grace', 'id': 'c93674f8b241375f9622e15ee5b80e96c86806b6', 'size': '641', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Code/kmeans_gap_job.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '107564'}, {'name': 'R', 'bytes': '6418'}, {'name': 'Shell', 'bytes': '314'}, {'name': 'TeX', 'bytes': '96384'}]} |
loan-default-prediction
=======================
Description
-----------
The code was written for [Loan Default Prediction Competition at Kaggle](https://www.kaggle.com/c/loan-default-prediction) and got the prize.
Dependencies and requirements
-----------------------------
[pandas](https://github.com/pydata/pandas): version 0.13.1 or later
[scikit learn](https://github.com/scikit-learn/scikit-learn): dev branch with version commit 884889a4cd36e63d53a067d9380dea7724a93ac5 or later
How to run
----------
1. Download data from [Kaggle](https://www.kaggle.com/c/loan-default-prediction)
2. Unzip the train and test csv files to path/to/data/folder and make sure that their names are train_v2.csv and test_v2.csv, respectively
3. Run `python train_predict.py path/to/data/folder`
4. The prediction submission-ready csv (submission.csv) will be found at path/to/data/folder
| {'content_hash': '10db8b35c58eaddf4aa31c403c06fe7c', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 142, 'avg_line_length': 41.95238095238095, 'alnum_prop': 0.720771850170261, 'repo_name': 'songgc/loan-default-prediction', 'id': '36dec8410eb5442f25970039f0976fe77f94d7ce', 'size': '881', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '9559'}]} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '225269b6facaea1be3687b6b5126b002', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': 'c8f56abeaba6e88b2de91e3acce7ce4901b46d4f', 'size': '176', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Cactaceae/Lobivia/Lobivia atrovirens/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
"""
Created on Tue Mar 29 09:31:26 2016
@author: pick
"""
import os
import sys
import subprocess
from PyQt5.QtWidgets import (QVBoxLayout, QHBoxLayout, QMessageBox,
QLineEdit, QPushButton, QLabel, QGroupBox,
QGridLayout, QTreeWidget, QTreeWidgetItem,
QToolButton, QFileDialog, QCheckBox, QComboBox,
QFrame, QSizePolicy, QRadioButton)
from PyQt5.QtCore import Qt
from .pageutils import QIWizardPage, clearLayout, shorten_path
import odml
import odmltables.compare_section_csv_table
import odmltables.compare_section_xls_table
class ChooseFilePage(QIWizardPage):
"""
"""
def __init__(self, parent=None, filename=None):
super(ChooseFilePage, self).__init__(parent)
if filename is None:
self.inputfilename = ''
else:
self.inputfilename = filename
self.settings.register('inputfilename', self, useconfig=False)
self.initUI()
def initUI(self):
# Adding input part
vbox = QVBoxLayout()
topLabel = QLabel(self.tr("Choose a file to load"))
topLabel.setWordWrap(True)
vbox.addWidget(topLabel)
vbox.addSpacing(20)
# Add first horizontal box
self.buttonbrowse = QPushButton("Browse")
self.buttonbrowse.clicked.connect(self.handlebuttonbrowse)
self.inputfile = QLabel(self.inputfilename)
self.inputfile.setWordWrap(True)
hbox1 = QHBoxLayout()
hbox1.addWidget(self.buttonbrowse)
hbox1.addWidget(self.inputfile)
hbox1.addStretch()
vbox.addLayout(hbox1)
vbox.addSpacing(10)
# Adding output part
bottomLabel = QLabel(self.tr("Select an output format"))
bottomLabel.setWordWrap(True)
vbox.addWidget(bottomLabel)
vbox.addWidget(bottomLabel)
# Add second horizontal box
self.rbuttonxls = QRadioButton(self.tr("xls"))
self.rbuttoncsv = QRadioButton(self.tr("csv"))
hbox2 = QHBoxLayout()
hbox2.addWidget(self.rbuttonxls)
hbox2.addSpacing(50)
hbox2.addWidget(self.rbuttoncsv)
hbox2.addStretch()
vbox.addLayout(hbox2)
vbox.addStretch()
self.setLayout(vbox)
def initializePage(self):
self.setTitle("Select an input file")
self.setSubTitle("Select the file you want to convert and specify the "
"output format you want to generate")
self.settings.register('RBoutputxls', self.rbuttonxls)
self.settings.register('RBoutputcsv', self.rbuttoncsv)
self.rbuttonxls.setChecked(True)
def handlebuttonbrowse(self):
dlg = QFileDialog()
dlg.setNameFilters(["%s files (*%s)" % ('odml', '.odml'),
"%s files (*%s)" % ('xml', '.xml')])
fn = self.settings.get_object('inputfilename')
if fn:
dlg.selectFile(fn)
if dlg.exec_():
self.inputfilename = str(dlg.selectedFiles()[0])
self.settings.register('inputfilename', self, useconfig=False)
self.inputfile.setText(shorten_path(self.inputfilename))
def validatePage(self):
if not any((self.settings.get_object('RBoutputxls').isChecked(),
self.settings.get_object('RBoutputcsv').isChecked())):
QMessageBox.warning(self, 'Select a format',
'You need to select a table format to '
'continue.')
return 0
if ((not self.settings.is_registered('inputfilename')) or
(not self.settings.get_object('inputfilename'))):
QMessageBox.warning(self, 'Select an input file',
'You need to select an input file to continue.')
return 0
return 1
class ChooseSectionsPage(QIWizardPage):
"""
page to choose the sections that should be compared in the table
"""
def __init__(self, parent=None):
super(ChooseSectionsPage, self).__init__(parent)
self.selected_sections = [] # sections in the right tree
self.sections = [] # all sections without the selected
self.filtered_sections = [] # filtered sections without the selected
self.initUI()
def initUI(self):
mainlayout = QVBoxLayout()
# layout containing the treewidgets
sectionlistlayout = QHBoxLayout()
# layout for filter form
filterbox = QGroupBox("Filter")
self.LEsecname = QLineEdit()
self.LEsectype = QLineEdit()
self.LEpropname = QLineEdit()
filterlayout = QGridLayout()
filterlayout.addWidget(QLabel("Section Name"), 1, 0)
filterlayout.addWidget(QLabel("Section Type"), 2, 0)
filterlayout.addWidget(QLabel("Property Name"), 3, 0)
filterlayout.addWidget(self.LEsecname, 1, 1)
filterlayout.addWidget(self.LEsectype, 2, 1)
filterlayout.addWidget(self.LEpropname, 3, 1)
filterbox.setLayout(filterlayout)
self.LEsecname.textChanged.connect(self.filterSections)
self.LEsectype.textChanged.connect(self.filterSections)
self.LEpropname.textChanged.connect(self.filterSections)
# define layout for the trre-widgets containing the sections
self.section_tree = QTreeWidget()
self.section_tree.setColumnCount(2)
self.section_tree.setHeaderLabels(["Name", "Path"])
self.section_tree.itemDoubleClicked.connect(self.toright)
self.selection_tree = QTreeWidget()
self.selection_tree.setColumnCount(2)
self.selection_tree.setHeaderLabels(["Name", "Path"])
self.selection_tree.itemDoubleClicked.connect(self.toleft)
self.selection_tree.setSelectionMode(3)
self.section_tree.setSelectionMode(3)
self.settings.register("selected_secs", self.selected_sections)
# buttons to move items of the tree-widgets
movebuttonlayout = QVBoxLayout()
btn_right = QToolButton()
btn_right.setArrowType(Qt.RightArrow)
btn_right.clicked.connect(self.toright)
btn_left = QToolButton()
btn_left.setArrowType(Qt.LeftArrow)
btn_left.clicked.connect(self.toleft)
movebuttonlayout.addStretch(1)
movebuttonlayout.addWidget(btn_right)
movebuttonlayout.addSpacing(1)
movebuttonlayout.addWidget(btn_left)
movebuttonlayout.addStretch(1)
sectionlistlayout.addWidget(self.section_tree)
sectionlistlayout.addSpacing(1)
sectionlistlayout.addLayout(movebuttonlayout)
sectionlistlayout.addSpacing(1)
sectionlistlayout.addWidget(self.selection_tree)
mainlayout.addLayout(sectionlistlayout)
self.selectallcb = QCheckBox('select all (Ctrl+A)')
self.selectallcb.stateChanged.connect(self.selectall)
mainlayout.addWidget(self.selectallcb)
mainlayout.addWidget(filterbox)
self.setTitle("Select Sections")
self.setLayout(mainlayout)
self.adjustSize()
def initializePage(self):
# load sections and properties from the selected file
odmldoc = odml.load(self.settings.get_object("inputfilename"))
# resolve links and includes
odmldoc.finalize()
for section in odmldoc.itersections():
self.sections.append([section.name,
section.get_path(),
[p.name for p in section.properties],
section.type])
# fill tree widget with sections and properties
for line in self.sections:
parent = QTreeWidgetItem([line[0], line[1]])
for p in line[2]:
QTreeWidgetItem(parent, [str(p)])
self.section_tree.addTopLevelItem(parent)
self.filtered_sections = list(self.sections)
self.setTitle("Choose Sections")
self.setSubTitle("Choose the sections you want to compare")
def _get_selected_rows(self, tree):
"""
function to determine the selected rows in a specified QTreeWidget
"""
rows = []
for index in tree.selectedIndexes():
if index.parent().row() is -1:
rows.append(index.row())
else:
# if a property is selected, the whole section containing this
# property shall be moved
rows.append(index.parent().row())
# sort rownumbers in descending order to prevent shifting when moving
# the items
return sorted(list(set(rows)), reverse=True)
def toright(self):
"""
function to shift items from the left TreeWidget to the right
"""
rows = self._get_selected_rows(self.section_tree)
for row in rows:
self.selection_tree.addTopLevelItem(
self.section_tree.takeTopLevelItem(row))
self.selected_sections.append(self.sections.pop(
self.sections.index(self.filtered_sections[row])))
self.filtered_sections.pop(row)
def toleft(self):
"""
function to shift items from the right TreeWidget to the left
"""
rows = self._get_selected_rows(self.selection_tree)
for row in rows:
self.section_tree.addTopLevelItem(
self.selection_tree.takeTopLevelItem(row))
item = self.selected_sections.pop(row)
self.sections.append(item)
self.filtered_sections.append(item)
def filterSections(self):
# find sections that match the filter
self.filtered_sections = [s for s in self.sections
if str(self.LEsecname.text()) in s[0]
and str(self.LEsectype.text()) in s[3]
and any([str(self.LEpropname.text())
in p for p in s[2]])]
# clear left treewidget
self.section_tree.clear()
# fill left treewidget with the filtered sections
for line in self.filtered_sections:
parent = QTreeWidgetItem([line[0], line[1]])
for p in line[2]:
QTreeWidgetItem(parent, [p])
self.section_tree.addTopLevelItem(parent)
def selectall(self):
if self.selectallcb.isChecked():
self.section_tree.selectAll()
else:
self.section_tree.clearSelection()
def validatePage(self):
if not self.settings.get_object("selected_secs"):
QMessageBox.warning(self, 'No sections chosen',
'You should choose at least two sections to be '
'compared in the table.')
return 0
return 1
class ChoosePropertiesPage(QIWizardPage):
# idea: page to choose the properties that should be compared.
# not useful yet, because odmltables doesnt provide this option
def __init__(self, parent=None):
super(ChoosePropertiesPage, self).__init__(parent)
class ChooseStylesPage(QIWizardPage):
def __init__(self, parent=None):
super(ChooseStylesPage, self).__init__(parent)
class SaveTablePage(QIWizardPage):
"""
may be replaced by SaveFilePage
"""
def __init__(self, parent=None):
super(SaveTablePage, self).__init__(parent)
self.setTitle("Save the result")
self.setSubTitle("Select a location to save your file.")
# Set up layout
self.vbox = QVBoxLayout()
self.setLayout(self.vbox)
def initializePage(self):
# Set up layout
vbox = QVBoxLayout()
clearLayout(self.layout())
self.layout().addLayout(vbox)
# adding pattern selection part
self.topLabel = QLabel(self.tr("Where do you want to save your file?"))
self.topLabel.setWordWrap(True)
vbox.addWidget(self.topLabel)
# vbox.addSpacing(40)
# Add first horizontal box
self.buttonbrowse = QPushButton("Save file")
self.buttonbrowse.clicked.connect(self.handlebuttonbrowse)
self.buttonbrowse.setFocus()
self.outputfilename = ''
self.outputfile = QLabel(self.outputfilename)
self.outputfile.setWordWrap(True)
self.buttonshow = QPushButton("Open file")
self.buttonshow.clicked.connect(self.show_file)
self.buttonshow.setEnabled(False)
hbox = QHBoxLayout()
hbox.addWidget(self.buttonbrowse)
hbox.addWidget(self.outputfile)
hbox.addStretch()
vbox.addLayout(hbox)
# vbox.addSpacing(10)
vbox.addWidget(self.buttonshow)
vbox.addStretch()
self.settings.register('outputfilename', self, useconfig=False)
short_filename = shorten_path(self.outputfilename)
self.outputfile.setText(short_filename)
if self.settings.get_object('RBoutputxls').isChecked():
self.expected_extension = '.xls'
elif self.settings.get_object('RBoutputcsv').isChecked():
self.expected_extension = '.csv'
else:
raise ValueError('Can not save file without selection of '
'output format.')
self.topLabel.setText("Where do you want to save your "
"%s file?" % self.expected_extension.strip('.'))
self.issaved = False
def handlebuttonbrowse(self):
dlg = QFileDialog()
dlg.setFileMode(QFileDialog.AnyFile)
dlg.setAcceptMode(QFileDialog.AcceptSave)
dlg.setLabelText(QFileDialog.Accept, "Save comparison")
dlg.setDefaultSuffix(self.expected_extension.strip('.'))
inputfilename = self.settings.get_object('inputfilename')
dirname = os.path.dirname(inputfilename)
suggested_filename = os.path.splitext(os.path.basename(
inputfilename))[0] + self.expected_extension
dlg.setDirectory(dirname)
dlg.selectFile(suggested_filename)
filternames = ["%s files (*%s)" % (ext.strip('.'), ext) for ext in
[self.expected_extension]]
filternames += ["all files (*)"]
dlg.setNameFilters(filternames)
if dlg.exec_():
self.outputfilename = str(dlg.selectedFiles()[0])
self.settings.register('outputfilename', self)
self.outputfile.setText(shorten_path(self.outputfilename))
if self.outputfilename:
self.compare()
self.issaved = True
print('Complete!')
self.buttonshow.setEnabled(True)
def show_file(self):
platform = sys.platform
if platform.startswith('linux'):
subprocess.Popen(["nohup", "see", self.outputfilename])
elif platform == 'darwin':
subprocess.Popen(["open", self.outputfilename])
elif platform.startswith('win'):
subprocess.Popen(["start", self.outputfilename])
else:
raise ValueError(f'Unknown operating platform "{platform}".')
def _saveXlsTable(self):
table = odmltables.compare_section_xls_table.CompareSectionXlsTable()
table.load_from_file(self.settings.get_object("inputfilename"))
selections = [s[0] for s in self.settings.get_object("selected_secs")]
table.choose_sections(*selections)
table.write2file(self.settings.get_object("outputfilename"))
def _saveCsvTable(self):
table = odmltables.compare_section_csv_table.CompareSectionCsvTable()
table.load_from_file(self.settings.get_object("inputfilename"))
selections = [s[0] for s in self.settings.get_object("selected_secs")]
table.choose_sections(*selections)
table.write2file(self.settings.get_object("outputfilename"))
def compare(self):
if not (self.settings.is_registered('outputfilename') and
self.settings.get_object('outputfilename')):
QMessageBox.warning(self, 'Select an outputfile',
'You need to select an outputfile to continue.')
return 0
if self.settings.get_object('RBoutputxls').isChecked():
self._saveXlsTable()
elif self.settings.get_object('RBoutputcsv').isChecked():
self._saveCsvTable()
else:
raise ValueError('No output format was selected.')
def validatePage(self):
if self.issaved == False:
quit_msg = "Are you sure you want to exit the program without " \
"saving your file?"
reply = QMessageBox.question(self, 'Message',
quit_msg, QMessageBox.Yes, QMessageBox.No)
if reply == QMessageBox.No:
return 0
return 1
| {'content_hash': '0ae907994f212265a3d68e0d157bf3da', 'timestamp': '', 'source': 'github', 'line_count': 464, 'max_line_length': 83, 'avg_line_length': 36.394396551724135, 'alnum_prop': 0.6132527980103037, 'repo_name': 'INM-6/python-odmltables', 'id': '75a0bcf10400392ff8f5cc16b176a9368c56faf4', 'size': '16911', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'odmltables/gui/compsectionpages.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '26'}, {'name': 'Jupyter Notebook', 'bytes': '120236'}, {'name': 'Python', 'bytes': '338119'}, {'name': 'Shell', 'bytes': '3498'}, {'name': 'TeX', 'bytes': '12438'}, {'name': 'XSLT', 'bytes': '18504'}]} |
<?php
namespace Nette\Forms;
use Nette;
/**
* Set of radio button controls.
*
* @copyright Copyright (c) 2004, 2010 David Grudl
* @package Nette\Forms
*
* @property array $items
* @property-read Nette\Web\Html $separatorPrototype
* @property-read Nette\Web\Html $containerPrototype
*/
class RadioList extends FormControl
{
/** @var Nette\Web\Html separator element template */
protected $separator;
/** @var Nette\Web\Html container element template */
protected $container;
/** @var array */
protected $items = array();
/**
* @param string label
* @param array options from which to choose
*/
public function __construct($label = NULL, array $items = NULL)
{
parent::__construct($label);
$this->control->type = 'radio';
$this->container = Nette\Web\Html::el();
$this->separator = Nette\Web\Html::el('br');
if ($items !== NULL) $this->setItems($items);
}
/**
* Returns selected radio value.
* @param bool
* @return mixed
*/
public function getValue($raw = FALSE)
{
return is_scalar($this->value) && ($raw || isset($this->items[$this->value])) ? $this->value : NULL;
}
/**
* Sets options from which to choose.
* @param array
* @return RadioList provides a fluent interface
*/
public function setItems(array $items)
{
$this->items = $items;
return $this;
}
/**
* Returns options from which to choose.
* @return array
*/
final public function getItems()
{
return $this->items;
}
/**
* Returns separator HTML element template.
* @return Nette\Web\Html
*/
final public function getSeparatorPrototype()
{
return $this->separator;
}
/**
* Returns container HTML element template.
* @return Nette\Web\Html
*/
final public function getContainerPrototype()
{
return $this->container;
}
/**
* Generates control's HTML element.
* @param mixed
* @return Nette\Web\Html
*/
public function getControl($key = NULL)
{
if ($key === NULL) {
$container = clone $this->container;
$separator = (string) $this->separator;
} elseif (!isset($this->items[$key])) {
return NULL;
}
$control = parent::getControl();
$id = $control->id;
$counter = -1;
$value = $this->value === NULL ? NULL : (string) $this->getValue();
$label = Nette\Web\Html::el('label');
foreach ($this->items as $k => $val) {
$counter++;
if ($key !== NULL && $key != $k) continue; // intentionally ==
$control->id = $label->for = $id . '-' . $counter;
$control->checked = (string) $k === $value;
$control->value = $k;
if ($val instanceof Nette\Web\Html) {
$label->setHtml($val);
} else {
$label->setText($this->translate($val));
}
if ($key !== NULL) {
return (string) $control . (string) $label;
}
$container->add((string) $control . (string) $label . $separator);
// TODO: separator after last item?
}
return $container;
}
/**
* Generates label's HTML element.
* @param string
* @return void
*/
public function getLabel($caption = NULL)
{
$label = parent::getLabel($caption);
$label->for = NULL;
return $label;
}
/**
* Filled validator: has been any radio button selected?
* @param IFormControl
* @return bool
*/
public static function validateFilled(IFormControl $control)
{
return $control->getValue() !== NULL;
}
}
| {'content_hash': '2239145d9db1eb6c3967627e5432105f', 'timestamp': '', 'source': 'github', 'line_count': 179, 'max_line_length': 102, 'avg_line_length': 18.70391061452514, 'alnum_prop': 0.6200716845878136, 'repo_name': 'nella/ActiveMapper', 'id': 'f5d4d3b0422cd2dffb827210df92bef3b31611c1', 'size': '3564', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'libs/Nette/Forms/Controls/RadioList.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'JavaScript', 'bytes': '7626'}, {'name': 'PHP', 'bytes': '1074012'}]} |
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8">
<title>isNotUnknown</title>
<link href="../../../../images/logo-icon.svg" rel="icon" type="image/svg">
<script>var pathToRoot = "../../../../";</script>
<script type="text/javascript" src="../../../../scripts/sourceset_dependencies.js" async="async"></script>
<link href="../../../../styles/style.css" rel="Stylesheet">
<link href="../../../../styles/logo-styles.css" rel="Stylesheet">
<link href="../../../../styles/jetbrains-mono.css" rel="Stylesheet">
<link href="../../../../styles/main.css" rel="Stylesheet">
<script type="text/javascript" src="../../../../scripts/clipboard.js" async="async"></script>
<script type="text/javascript" src="../../../../scripts/navigation-loader.js" async="async"></script>
<script type="text/javascript" src="../../../../scripts/platform-content-handler.js" async="async"></script>
<script type="text/javascript" src="../../../../scripts/main.js" async="async"></script>
</head>
<body>
<div id="container">
<div id="leftColumn">
<div id="logo"></div>
<div id="paneSearch"></div>
<div id="sideMenu"></div>
</div>
<div id="main">
<div id="leftToggler"><span class="icon-toggler"></span></div>
<script type="text/javascript" src="../../../../scripts/pages.js"></script>
<script type="text/javascript" src="../../../../scripts/main.js"></script>
<div class="main-content" id="content" pageIds="org.hexworks.zircon.internal.resource/BuiltInCP437TilesetResource.CURSES_24X24/isNotUnknown/#/PointingToDeclaration//-755115832">
<div class="navigation-wrapper" id="navigation-wrapper">
<div class="breadcrumbs"><a href="../../../index.html">zircon.core</a>/<a href="../../index.html">org.hexworks.zircon.internal.resource</a>/<a href="../index.html">BuiltInCP437TilesetResource</a>/<a href="index.html">CURSES_24X24</a>/<a href="is-not-unknown.html">isNotUnknown</a></div>
<div class="pull-right d-flex">
<div class="filter-section" id="filter-section"><button class="platform-tag platform-selector common-like" data-active="" data-filter=":zircon.core:dokkaHtml/commonMain">common</button></div>
<div id="searchBar"></div>
</div>
</div>
<div class="cover ">
<h1 class="cover"><span>is</span><wbr></wbr><span>Not</span><wbr></wbr><span>Unknown</span></h1>
</div>
<div class="divergent-group" data-filterable-current=":zircon.core:dokkaHtml/commonMain" data-filterable-set=":zircon.core:dokkaHtml/commonMain"><div class="with-platform-tags"><span class="pull-right"></span></div>
<div>
<div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-depenent-content" data-active="" data-togglable=":zircon.core:dokkaHtml/commonMain"><div class="symbol monospace">open val <a href="is-not-unknown.html">isNotUnknown</a>: <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html">Boolean</a><span class="top-right-position"><span class="copy-icon"></span><div class="copy-popup-wrapper popup-to-left"><span class="copy-popup-icon"></span><span>Content copied to clipboard</span></div></span></div></div></div>
</div>
</div>
</div>
<div class="footer"><span class="go-to-top-icon"><a href="#content"></a></span><span>© 2020 Copyright</span><span class="pull-right"><span>Sponsored and developed by dokka</span><a href="https://github.com/Kotlin/dokka"><span class="padded-icon"></span></a></span></div>
</div>
</div>
</body>
</html>
| {'content_hash': 'd2afb09833340410e0dc618a63324022', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 590, 'avg_line_length': 72.76470588235294, 'alnum_prop': 0.6348693074642954, 'repo_name': 'Hexworks/zircon', 'id': '4bfbc92baac637bfbffa467c558d6afcd2d62a13', 'size': '3712', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/2021.1.0-RELEASE-KOTLIN/zircon.core/zircon.core/org.hexworks.zircon.internal.resource/-built-in-c-p437-tileset-resource/-c-u-r-s-e-s_24-x24/is-not-unknown.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '121457'}, {'name': 'Kotlin', 'bytes': '1792092'}, {'name': 'Shell', 'bytes': '152'}]} |
from mygrations.core.definitions.columns.date import Date as DateBase
from typing import List, Union
class Date(DateBase):
def __init__(
self,
name: str = '',
column_type: str = '',
length: Union[str, int] = None,
null: bool = True,
has_default: bool = False,
default: Union[str, int] = None,
unsigned: bool = None,
character_set: str = None,
collate: str = None,
auto_increment: bool = False,
enum_values: List[str] = None,
parsing_errors: List[str] = None,
parsing_warnings: List[str] = None,
):
# it would be nice to just do `def __init__(**kwargs)` and then `super().__init__(**kwargs)`
# but then we would lose our type hints. :shrug:
super().__init__(
name=name,
column_type=column_type,
length=length,
null=null,
has_default=has_default,
default=default,
character_set=character_set,
collate=collate,
auto_increment=auto_increment,
enum_values=enum_values,
parsing_errors=parsing_errors,
parsing_warnings=parsing_warnings,
unsigned=unsigned,
)
| {'content_hash': 'a049694c71197ffbad07990ab7d323b9', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 100, 'avg_line_length': 35.0, 'alnum_prop': 0.5452380952380952, 'repo_name': 'cmancone/mygrations', 'id': '819ae8072fe93261ec9ef0e57ba9e542ce05724f', 'size': '1260', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'mygrations/formats/mysql/definitions/columns/date.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '416430'}, {'name': 'Shell', 'bytes': '331'}]} |
.. toctree::
===============
Developer Guide
===============
Setup Development Environment
=============================
#. Install ``pip3`` and development dependencies:
.. code-block:: sh
wget https://bootstrap.pypa.io/get-pip.py
sudo python3 get-pip.py
sudo pip3 install tox flake8 pep8-naming
#. Install a C/C++ toolchain for native extensions and cythonized binary wheel
packaging:
.. code-block:: sh
sudo apt install python3-dev build-essential cmake graphviz
#. Optionally, it is recommended to install the ``webdev`` package to run a
development web server from a local directory:
.. code-block:: sh
sudo pip3 install webdev
webdev .tox/doc/tmp/html
Building Package
================
.. code-block:: sh
tox -e build
Output will be available at ``dist/``.
- Source distribution: ``tse2sql-<version>.tar.gz``.
- Python wheel: ``tse2sql-<version>-py3-none-any.whl``
- Binary wheel: ``tse2sql-<version>-cp35-cp35m-linux_x86_64.whl``
.. note::
The tags of the binary wheel will change depending on the interpreter and
operating system you build the binary wheel on.
Running Test Suite
==================
.. code-block:: sh
tox -e test
Output will be available at ``.tox/test/tmp/``.
.. code-block:: sh
webdev .tox/doc/tmp/
- Test results: ``tests.xml``.
- Coverage results: ``coverage.xml``.
- Coverage report: ``coverage.html``.
Building Documentation
======================
.. code-block:: sh
tox -e doc
Output will be available at ``.tox/doc/tmp/html``.
.. code-block:: sh
webdev .tox/doc/tmp/html
| {'content_hash': '5c232cca23cb67c18872b132a2dab2a0', 'timestamp': '', 'source': 'github', 'line_count': 83, 'max_line_length': 78, 'avg_line_length': 19.40963855421687, 'alnum_prop': 0.6319056486654252, 'repo_name': 'carlos-jenkins/tse2sql', 'id': '50e6e2bbfea8b0569314d6dd90cbb7285692315e', 'size': '1611', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/developer.rst', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '6017'}, {'name': 'Python', 'bytes': '52264'}]} |
@extends(config('cms.layout'))
@section(config('cms.content_section'))
<script type="text/javascript">
var minimumPasswordLength = {{ Fractal::getSetting('Minimum Password Length') }};
</script>
<script type="text/javascript" src="{{ Site::js('fractal/forms/user', 'regulus/fractal') }}"></script>
{!! Form::open() !!}
<div class="row">
<div class="col-md-6">
{!! Form::field('name', 'text', ['label' => Fractal::trans('labels.username')]) !!}
</div>
<div class="col-md-6">
{!! Form::field('email') !!}
</div>
</div>
<div class="row">
<div class="col-md-6">
{!! Form::field('first_name') !!}
</div>
<div class="col-md-6">
{!! Form::field('last_name') !!}
</div>
</div>
<div class="row">
<div class="col-md-4">
{!! Form::field('city') !!}
</div>
<div class="col-md-4">
{!! Form::field('country', 'select', [
'label' => Fractal::trans('labels.country'),
'options' => Form::countryOptions(),
'null-option' => Fractal::trans('messages.select_item', ['item' => Format::a(strtolower(Fractal::trans('labels.country')))])
]) !!}
</div>
<div class="col-md-4">
{!! Form::field('region', 'select', [
'label' => Fractal::getRegionLabel(Form::value('country')),
'options' => Form::provinceOptions(),
'null-option' => Fractal::trans('messages.select_item', ['item' => Format::a(strtolower(Fractal::getRegionLabel(Form::value('country'))))])
]) !!}
</div>
</div>
<div class="row">
<div class="col-md-4">
{!! Form::field('phone', 'text', array('label' => 'Phone Number')) !!}
</div>
<div class="col-md-4">
{!! Form::field('website') !!}
</div>
<div class="col-md-4">
{!! Form::field('twitter', 'text', array('maxlength' => 16)) !!}
</div>
</div>
<div class="row">
<div class="col-md-12">
{!! Form::field('about', 'textarea', array('class-field' => 'ckeditor')) !!}
</div>
</div>
@if (!isset($update) || !$update)
<div class="row">
<div class="col-md-4">
{!! Form::field('password') !!}
</div>
<div class="col-md-4">
{!! Form::field('password_confirmation', null, array('label' => 'Confirm Password')) !!}
</div>
<div class="col-md-4 passwords-check">
<span class="glyphicon glyphicon-ok-circle passwords-match green hidden"></span>
<span class="glyphicon glyphicon-remove-circle passwords-mismatch red hidden"></span>
</div>
</div>
@endif
<div class="row">
<div class="col-md-12">
{!! Form::field(Form::submitResource(null, true), 'button') !!}
</div>
</div>
{!! Form::close() !!}
@stop | {'content_hash': '6d9b65113ec277e2d26f588c3956af98', 'timestamp': '', 'source': 'github', 'line_count': 99, 'max_line_length': 144, 'avg_line_length': 26.7979797979798, 'alnum_prop': 0.5548435733132303, 'repo_name': 'Regulus343/Fractal', 'id': 'fafcc0ff37f17aaac8b319af2cda3b1396f549fe', 'size': '2653', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/resources/views/account/form.blade.php', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '97697'}, {'name': 'HTML', 'bytes': '173207'}, {'name': 'JavaScript', 'bytes': '577189'}, {'name': 'PHP', 'bytes': '630284'}]} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Voodle.BLL.Models.Base
{
public class UserModel : UserLoginModel
{
[DisplayName("Created")]
public DateTime CreatedAt { get; set; }
[DisplayName("Modifed")]
public DateTime ModifiedAt { get; set; }
[DisplayName("Last login")]
public DateTime LastLoggedAt { get; set; }
public string Email { get; set; }
public bool Saved { get; set; }
}
}
| {'content_hash': '74349d5bee1a63c4e98935f6a91bff9f', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 50, 'avg_line_length': 27.238095238095237, 'alnum_prop': 0.6520979020979021, 'repo_name': 'vmandic/voodle', 'id': '1d4011127c24947d2f98460a82108c014ee031e3', 'size': '574', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Voodle.Web/Voodle.BLL/Models/Base/UserModel.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '104'}, {'name': 'C#', 'bytes': '345153'}, {'name': 'CSS', 'bytes': '75714'}, {'name': 'JavaScript', 'bytes': '816684'}, {'name': 'Pascal', 'bytes': '107094'}, {'name': 'PowerShell', 'bytes': '13265'}, {'name': 'Puppet', 'bytes': '26989'}]} |
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title><?php echo $titulo; ?></title>
<meta name="Description" content="<?php echo $metadescripcion;?>"/>
<meta name="keywords" content="<?php echo $metapalabras_clave;?>"/>
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"/>
<link rel="icon" href="<?=base_url()?>/favicon.png" type="image/png"/>
<link href="<?php echo base_url('assets/css/bootstrap.min.css')?>" rel="stylesheet"/>
<link href="<?php echo base_url('assets/fonts/css/font-awesome.min.css')?>" rel="stylesheet"/>
<link href="<?php echo base_url('assets/plugins/fancybox/source/jquery.fancybox.css"')?>" rel="stylesheet" media="screen"/>
<link href="<?php echo base_url('assets/css/score-content.css')?>" rel="stylesheet"/>
<link href="<?php echo base_url('assets/css/score.css')?>" rel="stylesheet"/>
<link href="<?php echo base_url('assets/css/frontend.css')?>" rel="stylesheet"/>
<link href="<?php echo base_url('assets/css/custom.css')?>" rel="stylesheet"/>
</head>
<body>
<!-- inicio menu -->
<?php $this->load->view('frontend/comunes/menu',array('menus'=>$menus,'navbar_transparente'=>FALSE));?>
<!-- fin menu -->
<!-- inicio contenido-->
<main style="padding-left: 0px;padding-right: 0px;">
<div class=""><div class="testi-contenido">
<div class="col-xs-12 score-content">
<h3 style="padding-left:10px;"><?php echo $this->lang->line('score_sitio_testimonios_empresas'); ?></h3>
</div>
<?php
if(count($testimonios_empresas)>0)
{
foreach ($testimonios_empresas as $testimonio):
$testimonio = (object) $testimonio;
if(!empty($testimonio->url_video))
$url_video = $testimonio->url_video;
else
$url_video = 'javascript:;';
if(!empty($testimonio->thumb))
$url_imagen = base_url('assets/img/testimonios/thumb/'.$testimonio->thumb);
else
$url_imagen = '';
?>
<!-- inicio testimonio empresa-->
<div class="">
<div class="col-xs-12 col-md-3">
<div class="testi-panel">
<div class="noti-titulo" style="background-color: #fff;border-left: 1px solid #ccc;border-right: 1px solid #ccc;padding: 1px 20px;height:65px;">
<a class="video" href="<?php echo $url_video;?>">
<h4 class=""><?php echo $testimonio->titulo;?></h4>
</a>
</div>
<a class="video" title="<?php echo $testimonio->titulo;?>" href="<?php echo $url_video;?>">
<div class="testi-image" style="background-image: url('<?php echo $url_imagen; ?>')">
</div>
</a>
<div class="testi-text">
<p class="">
<?php echo get_palabras($testimonio->contenido,55);?>
</p>
</div>
</div>
</div>
</div>
<!-- fin testimonio empresa -->
<?php
endforeach;
}
else
{
?>
<div class="">
<div class="col-xs-12 col-sm-6 col-md-4">
<p style="padding-left:10px;">Lo sentimos, no hay registros.</p>
</div>
</div>
<?php
}
?>
<div class="col-xs-12 score-content">
<h3 style="padding-left:10px;"><?php echo $this->lang->line('score_sitio_testimonios_personal'); ?></h3>
</div>
<?php
if(count($testimonios_personal)>0)
{
foreach ($testimonios_personal as $testimonio):
$testimonio = (object) $testimonio;
?>
<!-- inicio testimonio personal-->
<div class="">
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="brief-panel">
<div class="col-xs-4">
<div class="centered-parent">
<?php
if(!empty($testimonio->thumb))
$url_imagen = base_url('assets/img/testimonios/thumb/'.$testimonio->thumb);
else
$url_imagen = '';
?>
<div class="testi-foto h centered-child centered-parent" style="background-image: url('<?php echo $url_imagen; ?>');">
</div>
</div>
<div class="testi-titulo">
<p class=""><?php echo $testimonio->titulo;?></p>
</div>
</div>
<div class="col-xs-8 testi-content ">
<?php
if(!empty($testimonio->contenido))
{
$contenido = $testimonio->contenido;
$contenido = preg_replace("/<p[^>]*?>/", "", $contenido);
$contenido = str_replace("</p>", "<br/>", $contenido);
$array = explode('<br/>',$contenido);
$array_ = array();
for($i = 0; $i<count($array)-1;$i++)
{
$array_[] = $array[$i];
}
//var_dump($array_);
$contenido = implode('<br/>',$array_);
}
else
$contenido = '';
?>
<img class="inicio" src="<?php echo base_url('assets/img/comilla_abrir.png');?>"><?php echo $contenido;?><img class="fin" src="<?php echo base_url('assets/img/comilla_cerrar.png');?>">
</div>
</div>
</div>
</div>
<!-- fin testimonio personal -->
<?php
endforeach;
}
else
{
?>
<div class="">
<div class="col-xs-12 col-sm-6 col-md-4">
<p style="padding-left:10px;">Lo sentimos, no hay registros.</p>
</div>
</div>
<?php
}
?>
</div></div>
</main>
<!-- fin contenido -->
<!-- inicio pie -->
<?php
if(isset($mod_pie) AND !empty($mod_pie))
{
?>
<div class="col-xs-12" style="padding-right: 0px !important; padding-left: 0px !important; background-image: url('<?php echo base_url('assets/img/banner.png'); ?>');background-size: cover;">
<div>
<footer class="app-footer">
<?php echo $mod_pie->contenido; ?>
</footer>
</div>
</div>
<?php
}
?>
<!-- fin pie -->
<!-- inicio scripts -->
<script src="<?php echo base_url('assets/plugins/jQuery/jquery-2.2.3.min.js')?>"></script>
<script src="<?php echo base_url('assets/js/bootstrap.min.js')?>"></script>
<script src="<?php echo base_url('assets/plugins/fancybox/source/jquery.fancybox.js')?>"></script>
<script src="<?php echo base_url('assets/js/frontend.js')?>"></script>
<!-- fin scripts -->
</body>
</html> | {'content_hash': '8a259ff81b3d8c8dca02dededc4d5b98', 'timestamp': '', 'source': 'github', 'line_count': 183, 'max_line_length': 190, 'avg_line_length': 36.52459016393443, 'alnum_prop': 0.5163076002393776, 'repo_name': 'HugoMontes/si_maestras', 'id': 'ffb47cb8bbed3b84ceaf6446df59ef3db0b7ac18', 'size': '6684', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'application/views/frontend/testimonios.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '20185'}, {'name': 'ApacheConf', 'bytes': '662'}, {'name': 'Batchfile', 'bytes': '68'}, {'name': 'CSS', 'bytes': '1778592'}, {'name': 'CoffeeScript', 'bytes': '109703'}, {'name': 'HTML', 'bytes': '4698487'}, {'name': 'Java', 'bytes': '297102'}, {'name': 'JavaScript', 'bytes': '6238908'}, {'name': 'PHP', 'bytes': '4396614'}, {'name': 'Python', 'bytes': '37980'}, {'name': 'Ruby', 'bytes': '739'}]} |
<!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.4"/>
<title>tbb::filter Class Reference</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="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<!-- end header part -->
<!-- Generated by Doxygen 1.8.4 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="modules.html"><span>Modules</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>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="a00240.html">tbb</a></li><li class="navelem"><a class="el" href="a00062.html">filter</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pro-static-attribs">Static Protected Attributes</a> |
<a href="a00289.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">tbb::filter Class Reference<div class="ingroups"><a class="el" href="a00255.html">Algorithms</a></div></div> </div>
</div><!--header-->
<div class="contents">
<p>A stage in a pipeline.
<a href="a00062.html#details">More...</a></p>
<p><code>#include <pipeline.h></code></p>
<div class="dynheader">
Inheritance diagram for tbb::filter:</div>
<div class="dyncontent">
<div class="center">
<img src="a00062.png" usemap="#tbb::filter_map" alt=""/>
<map id="tbb::filter_map" name="tbb::filter_map">
<area href="a00165.html" title="A stage in a pipeline served by a user thread. " alt="tbb::thread_bound_filter" shape="rect" coords="0,112,145,136"/>
</map>
</div></div>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pro-static-attribs"></a>
Static Protected Attributes</h2></td></tr>
<tr class="memitem:ae9dab2e01b0963b341ab04b59eec1475"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae9dab2e01b0963b341ab04b59eec1475"></a>
static const unsigned char </td><td class="memItemRight" valign="bottom"><a class="el" href="a00062.html#ae9dab2e01b0963b341ab04b59eec1475">filter_is_serial</a> = 0x1</td></tr>
<tr class="memdesc:ae9dab2e01b0963b341ab04b59eec1475"><td class="mdescLeft"> </td><td class="mdescRight">The lowest bit 0 is for parallel vs. serial. <br/></td></tr>
<tr class="separator:ae9dab2e01b0963b341ab04b59eec1475"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a091fcf6abc79edfa5c8bf01f742e2392"><td class="memItemLeft" align="right" valign="top">static const unsigned char </td><td class="memItemRight" valign="bottom"><a class="el" href="a00062.html#a091fcf6abc79edfa5c8bf01f742e2392">filter_is_out_of_order</a> = 0x1<<4</td></tr>
<tr class="memdesc:a091fcf6abc79edfa5c8bf01f742e2392"><td class="mdescLeft"> </td><td class="mdescRight">4th bit distinguishes ordered vs unordered filters. <a href="#a091fcf6abc79edfa5c8bf01f742e2392">More...</a><br/></td></tr>
<tr class="separator:a091fcf6abc79edfa5c8bf01f742e2392"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a1382f216bd094064a18eb48ecc43c86b"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a1382f216bd094064a18eb48ecc43c86b"></a>
static const unsigned char </td><td class="memItemRight" valign="bottom"><a class="el" href="a00062.html#a1382f216bd094064a18eb48ecc43c86b">filter_is_bound</a> = 0x1<<5</td></tr>
<tr class="memdesc:a1382f216bd094064a18eb48ecc43c86b"><td class="mdescLeft"> </td><td class="mdescRight">5th bit distinguishes thread-bound and regular filters. <br/></td></tr>
<tr class="separator:a1382f216bd094064a18eb48ecc43c86b"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a6645ec56872b6ba2056dcaa467e292f7"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a6645ec56872b6ba2056dcaa467e292f7"></a>
static const unsigned char </td><td class="memItemRight" valign="bottom"><a class="el" href="a00062.html#a6645ec56872b6ba2056dcaa467e292f7">filter_may_emit_null</a> = 0x1<<6</td></tr>
<tr class="memdesc:a6645ec56872b6ba2056dcaa467e292f7"><td class="mdescLeft"> </td><td class="mdescRight">6th bit marks input filters emitting small objects <br/></td></tr>
<tr class="separator:a6645ec56872b6ba2056dcaa467e292f7"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aab9689e23a96c6c9bf1c8caae74d92ee"><td class="memItemLeft" align="right" valign="top">static const unsigned char </td><td class="memItemRight" valign="bottom"><a class="el" href="a00062.html#aab9689e23a96c6c9bf1c8caae74d92ee">exact_exception_propagation</a></td></tr>
<tr class="memdesc:aab9689e23a96c6c9bf1c8caae74d92ee"><td class="mdescLeft"> </td><td class="mdescRight">7th bit defines exception propagation mode expected by the application. <a href="#aab9689e23a96c6c9bf1c8caae74d92ee">More...</a><br/></td></tr>
<tr class="separator:aab9689e23a96c6c9bf1c8caae74d92ee"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>A stage in a pipeline. </p>
</div><h2 class="groupheader">Member Data Documentation</h2>
<a class="anchor" id="aab9689e23a96c6c9bf1c8caae74d92ee"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">const unsigned char tbb::filter::exact_exception_propagation</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">static</span><span class="mlabel">protected</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<b>Initial value:</b><div class="fragment"><div class="line">=</div>
<div class="line"><span class="preprocessor">#if TBB_USE_CAPTURED_EXCEPTION</span></div>
<div class="line"><span class="preprocessor"> 0x0</span></div>
</div><!-- fragment -->
<p>7th bit defines exception propagation mode expected by the application. </p>
</div>
</div>
<a class="anchor" id="a091fcf6abc79edfa5c8bf01f742e2392"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">const unsigned char tbb::filter::filter_is_out_of_order = 0x1<<4</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">static</span><span class="mlabel">protected</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>4th bit distinguishes ordered vs unordered filters. </p>
<p>The bit was not set for parallel filters in TBB 2.1 and earlier, but is_ordered() function always treats parallel filters as out of order. </p>
</div>
</div>
<hr/>The documentation for this class was generated from the following file:<ul>
<li>pipeline.h</li>
</ul>
</div><!-- contents -->
<hr>
<p></p>
Copyright © 2005-2015 Intel Corporation. All Rights Reserved.
<p></p>
Intel, Pentium, Intel Xeon, Itanium, Intel XScale and VTune are
registered trademarks or trademarks of Intel Corporation or its
subsidiaries in the United States and other countries.
<p></p>
* Other names and brands may be claimed as the property of others.
| {'content_hash': '205494a476e02794f06695cbf997078b', 'timestamp': '', 'source': 'github', 'line_count': 146, 'max_line_length': 301, 'avg_line_length': 57.445205479452056, 'alnum_prop': 0.6963157267199237, 'repo_name': 'DrPizza/reed-solomon', 'id': '679c993352e18ae4156f9bd14de0d480bd7eb099', 'size': '8387', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'tbb/doc/html/a00062.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '125597'}, {'name': 'Batchfile', 'bytes': '14199'}, {'name': 'C', 'bytes': '522308'}, {'name': 'C++', 'bytes': '6155224'}, {'name': 'CSS', 'bytes': '21672'}, {'name': 'HTML', 'bytes': '4229477'}, {'name': 'Java', 'bytes': '11966'}, {'name': 'JavaScript', 'bytes': '14447'}, {'name': 'Makefile', 'bytes': '81911'}, {'name': 'Objective-C', 'bytes': '13678'}, {'name': 'PHP', 'bytes': '6205'}, {'name': 'Shell', 'bytes': '33928'}, {'name': 'SourcePawn', 'bytes': '4814'}]} |
var AmpersandView = require('ampersand-view'),
models = require('../models');
module.exports = AmpersandView.extend({
template: require('./index.jade')
});
| {'content_hash': '62e3c53ae8a0d3794d3dfdd0b23a5b71', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 46, 'avg_line_length': 26.833333333333332, 'alnum_prop': 0.6894409937888198, 'repo_name': 'mongodb-js/khaos-spa', 'id': 'b57793c24a46b9e3416cfb89f86bb51b3a8b5d5f', 'size': '161', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'template/src/home/index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '27246'}, {'name': 'HTML', 'bytes': '369'}, {'name': 'JavaScript', 'bytes': '10986'}]} |
<p>
The server object created on application start.
<br /><br />
This singleton object exists in the application lifecycle passed among all components, exposing application level properties as the following:
</p>
<dcs-definition>
<dcs-definition-title type="object">app</dcs-definition-title>
<dcs-definition-desc>
the app instance that the server deployed on
<dcs-definition>
<dcs-definition-title type="string">version</dcs-definition-title>
<dcs-definition-desc>the jsnbt version of the app running</dcs-definition-desc>
<dcs-definition-title type="string">path</dcs-definition-title>
<dcs-definition-desc>the path from which the app is running</dcs-definition-desc>
<dcs-definition-title type="bool">dbg</dcs-definition-title>
<dcs-definition-desc>the debug status of the app running</dcs-definition-desc>
<dcs-definition-title type="string">environment</dcs-definition-title>
<dcs-definition-desc>the environment status of the app running (dev/prod)</dcs-definition-desc>
<dcs-definition-title type="object">localization</dcs-definition-title>
<dcs-definition-desc>the localization status</dcs-definition-desc>
<dcs-definition-sample>{
enabled: true,
locale: 'en'
}</dcs-definition-sample>
<dcs-definition-title type="bool">ssl</dcs-definition-title>
<dcs-definition-desc>the ssl status</dcs-definition-desc>
<dcs-definition-title type="object">modules</dcs-definition-title>
<dcs-definition-desc>the modules loaded into the engine</dcs-definition-desc>
<dcs-definition-sample>{
core: {},
rest: [{}, {}, {}],
public: {},
all: [{}, {}, {}, {}, {}]
}</dcs-definition-sample>
<dcs-definition-title type="object">config</dcs-definition-title>
<dcs-definition-desc>the merged configuration of all loaded modules. module configuration will be covered in next chapters.</dcs-definition-desc>
<dcs-definition-title type="function">init(options, module)</dcs-definition-title>
<dcs-definition-desc>initiates the application</dcs-definition-desc>
<dcs-definition-sample>app.init({
title: 'custom title'
});</dcs-definition-sample>
<dcs-definition-title type="function">createServer(options)</dcs-definition-title>
<dcs-definition-desc>creates the server for the application</dcs-definition-desc>
<dcs-definition-sample>var server = app.createServer({
host: 'localhost:3000',
port: 3000,
db: {
host: 'localhost',
port: 27017,
name: 'jsnbt'
}
});</dcs-definition-sample>
</dcs-definition>
</dcs-definition-desc>
<dcs-definition-title type="object">messager</dcs-definition-title>
<dcs-definition-desc>the messager engine. it serves the below for mail and sms
<dcs-definition>
<dcs-definition-title type="function">getTemplate(templateCode, callback)</dcs-definition-title>
<dcs-definition-desc>retrieves a template and returns it as an argument on the callback function</dcs-definition-desc>
<dcs-definition-title type="function">getModel(templateCode, callback)</dcs-definition-title>
<dcs-definition-desc>retrieves the debug model for a template code and returns it as an argument on the callback function</dcs-definition-desc>
<dcs-definition-title type="function">parseTemplate(template, model, callback)</dcs-definition-title>
<dcs-definition-desc>parses a template with a model and returns the parsed result as an argument on the callback function</dcs-definition-desc>
<dcs-definition-title type="function">getSender(dpd, callback)</dcs-definition-title>
<dcs-definition-desc>creates a sender and returns it as an argument on the callback function</dcs-definition-desc>
<dcs-definition-sample>var templateCode = 'registration';
server.messager.mail.getTemplate(templateCode, function (err, tmpl) {
if (err) {
ctx.error(err);
}
else {
server.messager.mail.getModel(templateCode, function (modelErr, model) {
if (modelErr) {
ctx.error(modelErr);
}
else {
server.messager.mail.parseTemplate(tmpl, model, function (parseErr, parsedTmpl) {
if (parseErr) {
ctx.error(parseErr);
}
else {
server.messager.mail.getSender(ctx.dpd, function (senderErr, sender) {
if (senderErr) {
ctx.error(senderErr);
}
else {
sender.send({
to: '[email protected]',
subject: parsedTmpl.subject,
body: parsedTmpl.body
}, function (sendErr, response) {
if (sendErr) {
ctx.error(sendErr);
}
else {
ctx.json({ sent: true });
}
});
}
});
}
});
}
});
}
});</dcs-definition-sample>
</dcs-definition>
</dcs-definition-desc>
<dcs-definition-title type="object">cache</dcs-definition-title>
<dcs-definition-desc>returns the server cache</dcs-definition-desc>
<dcs-definition-title type="function">mapPath(path)</dcs-definition-title>
<dcs-definition-desc>returns the server path of a relative path</dcs-definition-desc>
<dcs-definition-title type="function">start(next)</dcs-definition-title>
<dcs-definition-desc>starts the server</dcs-definition-desc>
<dcs-definition-sample>server.start();</dcs-definition-sample>
</dcs-definition> | {'content_hash': '13026d5a4fcd6c833afa9a268473d9be', 'timestamp': '', 'source': 'github', 'line_count': 137, 'max_line_length': 157, 'avg_line_length': 45.70802919708029, 'alnum_prop': 0.5883104439476206, 'repo_name': 'akonoupakis/jsnbt', 'id': '6237480570eabe23f8232d307b9ca3b524b62d17', 'size': '6264', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'docs/partials/server.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '40052'}, {'name': 'HTML', 'bytes': '143056'}, {'name': 'JavaScript', 'bytes': '937606'}]} |
local p = premake
local suite = test.declare("tools_msc")
local msc = p.tools.msc
--
-- Setup/teardown
--
local wks, prj, cfg
function suite.setup()
wks, prj = test.createWorkspace()
kind "SharedLib"
end
local function prepare()
cfg = test.getconfig(prj, "Debug")
end
--
-- Check the optimization flags.
--
function suite.cflags_onNoOptimize()
optimize "Off"
prepare()
test.contains("/Od", msc.getcflags(cfg))
end
function suite.cflags_onOptimize()
optimize "On"
prepare()
test.contains("/Ot", msc.getcflags(cfg))
end
function suite.cflags_onOptimizeSize()
optimize "Size"
prepare()
test.contains("/O1", msc.getcflags(cfg))
end
function suite.cflags_onOptimizeSpeed()
optimize "Speed"
prepare()
test.contains("/O2", msc.getcflags(cfg))
end
function suite.cflags_onOptimizeFull()
optimize "Full"
prepare()
test.contains("/Ox", msc.getcflags(cfg))
end
function suite.cflags_onOptimizeDebug()
optimize "Debug"
prepare()
test.contains("/Od", msc.getcflags(cfg))
end
function suite.cflags_onNoFramePointers()
flags "NoFramePointer"
prepare()
test.contains("/Oy", msc.getcflags(cfg))
end
function suite.ldflags_onLinkTimeOptimizations()
flags "LinkTimeOptimization"
prepare()
test.contains("/GL", msc.getldflags(cfg))
end
function suite.cflags_onStringPoolingOn()
stringpooling "On"
prepare()
test.contains("/GF", msc.getcflags(cfg))
end
function suite.cflags_onStringPoolingOff()
stringpooling "Off"
prepare()
test.contains("/GF-", msc.getcflags(cfg))
end
function suite.cflags_onStringPoolingNotSpecified()
prepare()
test.excludes("/GF", msc.getcflags(cfg))
test.excludes("/GF-", msc.getcflags(cfg))
end
function suite.cflags_onFloatingPointExceptionsOn()
floatingpointexceptions "On"
prepare()
test.contains("/fp:except", msc.getcflags(cfg))
end
function suite.cflags_onFloatingPointExceptionsOff()
floatingpointexceptions "Off"
prepare()
test.contains("/fp:except-", msc.getcflags(cfg))
end
function suite.cflags_onFloatingPointExceptionsNotSpecified()
prepare()
test.excludes("/fp:except", msc.getcflags(cfg))
test.excludes("/fp:except-", msc.getcflags(cfg))
end
function suite.cflags_onFunctionLevelLinkingOn()
functionlevellinking "On"
prepare()
test.contains("/Gy", msc.getcflags(cfg))
end
function suite.cflags_onFunctionLevelLinkingOff()
functionlevellinking "Off"
prepare()
test.contains("/Gy-", msc.getcflags(cfg))
end
function suite.cflags_onFunctionLevelLinkingNotSpecified()
prepare()
test.excludes("/Gy", msc.getcflags(cfg))
test.excludes("/Gy-", msc.getcflags(cfg))
end
function suite.cflags_onIntrinsicsOn()
intrinsics "On"
prepare()
test.contains("/Oi", msc.getcflags(cfg))
end
--
-- Check the translation of symbols.
--
function suite.cflags_onDefaultSymbols()
prepare()
test.excludes({ "/Z7" }, msc.getcflags(cfg))
end
function suite.cflags_onNoSymbols()
symbols "Off"
prepare()
test.excludes({ "/Z7" }, msc.getcflags(cfg))
end
function suite.cflags_onSymbols()
symbols "On"
prepare()
test.contains({ "/Z7" }, msc.getcflags(cfg))
end
--
-- Check handling of debugging support.
--
function suite.ldflags_onSymbols()
symbols "On"
prepare()
test.contains("/DEBUG", msc.getldflags(cfg))
end
--
-- Check handling warnings and errors.
--
function suite.cflags_OnNoWarnings()
warnings "Off"
prepare()
test.contains("/W0", msc.getcflags(cfg))
end
function suite.cflags_OnExtraWarnings()
warnings "Extra"
prepare()
test.contains("/W4", msc.getcflags(cfg))
end
function suite.cflags_OnFatalWarnings()
flags "FatalWarnings"
prepare()
test.contains("/WX", msc.getcflags(cfg))
end
function suite.cflags_onSpecificWarnings()
enablewarnings { "enable" }
disablewarnings { "disable" }
fatalwarnings { "fatal" }
prepare()
test.contains({ '/wd"disable"', '/we"fatal"' }, msc.getcflags(cfg))
end
function suite.ldflags_OnFatalWarnings()
flags "FatalWarnings"
prepare()
test.contains("/WX", msc.getldflags(cfg))
end
--
-- Check handling of library search paths.
--
function suite.libdirs_onLibdirs()
libdirs { "../libs" }
prepare()
test.contains('/LIBPATH:"../libs"', msc.getLibraryDirectories(cfg))
end
--
-- Check handling of forced includes.
--
function suite.forcedIncludeFiles()
forceincludes { "include/sys.h" }
prepare()
test.contains('/FIinclude/sys.h', msc.getforceincludes(cfg))
end
--
-- Check handling of floating point modifiers.
--
function suite.cflags_onFloatingPointFast()
floatingpoint "Fast"
prepare()
test.contains("/fp:fast", msc.getcflags(cfg))
end
function suite.cflags_onFloatingPointStrict()
floatingpoint "Strict"
prepare()
test.contains("/fp:strict", msc.getcflags(cfg))
end
function suite.cflags_onSSE()
vectorextensions "SSE"
prepare()
test.contains("/arch:SSE", msc.getcflags(cfg))
end
function suite.cflags_onSSE2()
vectorextensions "SSE2"
prepare()
test.contains("/arch:SSE2", msc.getcflags(cfg))
end
function suite.cflags_onAVX()
vectorextensions "AVX"
prepare()
test.contains("/arch:AVX", msc.getcflags(cfg))
end
function suite.cflags_onAVX2()
vectorextensions "AVX2"
prepare()
test.contains("/arch:AVX2", msc.getcflags(cfg))
end
--
-- Check the defines and undefines.
--
function suite.defines()
defines "DEF"
prepare()
test.contains({ '/D"DEF"' }, msc.getdefines(cfg.defines, cfg))
end
function suite.undefines()
undefines "UNDEF"
prepare()
test.contains({ '/U"UNDEF"' }, msc.getundefines(cfg.undefines))
end
--
-- Check compilation options.
--
function suite.cflags_onNoMinimalRebuild()
flags "NoMinimalRebuild"
prepare()
test.contains("/Gm-", msc.getcflags(cfg))
end
function suite.cflags_onMultiProcessorCompile()
flags "MultiProcessorCompile"
prepare()
test.contains("/MP", msc.getcflags(cfg))
end
--
-- Check handling of C++ language features.
--
function suite.cxxflags_onExceptions()
exceptionhandling "on"
prepare()
test.contains("/EHsc", msc.getcxxflags(cfg))
end
function suite.cxxflags_onSEH()
exceptionhandling "SEH"
prepare()
test.contains("/EHa", msc.getcxxflags(cfg))
end
function suite.cxxflags_onNoExceptions()
exceptionhandling "Off"
prepare()
test.missing("/EHsc", msc.getcxxflags(cfg))
end
function suite.cxxflags_onNoRTTI()
rtti "Off"
prepare()
test.contains("/GR-", msc.getcxxflags(cfg))
end
--
-- Check handling of additional linker options.
--
function suite.ldflags_onOmitDefaultLibrary()
flags "OmitDefaultLibrary"
prepare()
test.contains("/NODEFAULTLIB", msc.getldflags(cfg))
end
function suite.ldflags_onNoIncrementalLink()
flags "NoIncrementalLink"
prepare()
test.contains("/INCREMENTAL:NO", msc.getldflags(cfg))
end
function suite.ldflags_onNoManifest()
flags "NoManifest"
prepare()
test.contains("/MANIFEST:NO", msc.getldflags(cfg))
end
function suite.ldflags_onDLL()
kind "SharedLib"
prepare()
test.contains("/DLL", msc.getldflags(cfg))
end
--
-- Check handling of CLR settings.
--
function suite.cflags_onClrOn()
clr "On"
prepare()
test.contains("/clr", msc.getcflags(cfg))
end
function suite.cflags_onClrUnsafe()
clr "Unsafe"
prepare()
test.contains("/clr", msc.getcflags(cfg))
end
function suite.cflags_onClrSafe()
clr "Safe"
prepare()
test.contains("/clr:safe", msc.getcflags(cfg))
end
function suite.cflags_onClrPure()
clr "Pure"
prepare()
test.contains("/clr:pure", msc.getcflags(cfg))
end
--
-- Check handling of character set switches
--
function suite.cflags_onCharSetDefault()
prepare()
test.contains('/D"_UNICODE"', msc.getdefines(cfg.defines, cfg))
end
function suite.cflags_onCharSetUnicode()
characterset "Unicode"
prepare()
test.contains('/D"_UNICODE"', msc.getdefines(cfg.defines, cfg))
end
function suite.cflags_onCharSetMBCS()
characterset "MBCS"
prepare()
test.contains('/D"_MBCS"', msc.getdefines(cfg.defines, cfg))
end
--
-- Check handling of system search paths.
--
function suite.includeDirs_onSysIncludeDirs()
sysincludedirs { "/usr/local/include" }
prepare()
test.contains("-I/usr/local/include", msc.getincludedirs(cfg, cfg.includedirs, cfg.sysincludedirs))
end
function suite.libDirs_onSysLibDirs()
syslibdirs { "/usr/local/lib" }
prepare()
test.contains('/LIBPATH:"/usr/local/lib"', msc.getLibraryDirectories(cfg))
end
--
-- Check handling of ignore default libraries
--
function suite.ignoreDefaultLibraries_WithExtensions()
ignoredefaultlibraries { "lib1.lib" }
prepare()
test.contains('/NODEFAULTLIB:lib1.lib', msc.getldflags(cfg))
end
function suite.ignoreDefaultLibraries_WithoutExtensions()
ignoredefaultlibraries { "lib1" }
prepare()
test.contains('/NODEFAULTLIB:lib1.lib', msc.getldflags(cfg))
end
--
-- Check handling of shared C/C++ flags.
--
function suite.mixedToolFlags_onCFlags()
flags { "FatalCompileWarnings" }
prepare()
test.isequal({ "/WX", "/MD" }, msc.getcflags(cfg))
end
function suite.mixedToolFlags_onCxxFlags()
flags { "FatalCompileWarnings" }
prepare()
test.isequal({ "/WX", "/MD", "/EHsc" }, msc.getcxxflags(cfg))
end
| {'content_hash': '9b225227a44555d97a1028e0aa5c05a6', 'timestamp': '', 'source': 'github', 'line_count': 459, 'max_line_length': 101, 'avg_line_length': 20.100217864923746, 'alnum_prop': 0.7091914155647084, 'repo_name': 'bravnsgaard/premake-core', 'id': 'efc8cc8cf96d3323f01a312ae83aede0d1eda647', 'size': '9383', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/tools/test_msc.lua', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '4406'}, {'name': 'Batchfile', 'bytes': '1143'}, {'name': 'C', 'bytes': '8368526'}, {'name': 'C++', 'bytes': '211556'}, {'name': 'CMake', 'bytes': '60161'}, {'name': 'CSS', 'bytes': '708'}, {'name': 'Groff', 'bytes': '9450'}, {'name': 'HTML', 'bytes': '284725'}, {'name': 'Lua', 'bytes': '1218009'}, {'name': 'Makefile', 'bytes': '15711'}, {'name': 'Perl', 'bytes': '79383'}, {'name': 'Shell', 'bytes': '225717'}, {'name': 'Tcl', 'bytes': '110'}, {'name': 'Visual Basic', 'bytes': '11282'}]} |
class BallotOptionsController < ApplicationController
respond_to :html, :json
before_filter :find_membership
before_filter :require_admin
def index
@options = @current_member.group.ballot_options
respond_to do |format|
format.html
format.json {render :json=>{options:@options} }
end
end
def create
if params[:existing_id]
unless @option = BallotOption.find_by_id(params[:existing_id])
render :json=>{success:false, errors:{id:"Option not found."}}
return
end
else
#create a new option
@option = BallotOption.option_from_params params[:ballot_option]
unless @current_member.group.ballot_options << @option
render :json=>{success:false, errors:@option.errors}
return
end
end
render :json=>{success:true, option_id:@option.id}
end
def destroy
@group = @current_member.group
@option = @group.ballot_options.where(:id=>params[:id]).first
if @option && @group.ballot_options.delete(@option)
render :json=>{success:true}
else
render :json=>{success:false, errors:{id:"Member not found."}}
end
end
end
| {'content_hash': 'ba8a37bd1864d6d2004a5788d73c7a58', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 70, 'avg_line_length': 27.209302325581394, 'alnum_prop': 0.647008547008547, 'repo_name': 'pseudopeach/lunch-picker', 'id': 'e2a89d10b86b041211b936b46715414b323ea19f', 'size': '1170', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/controllers/ballot_options_controller.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2536'}, {'name': 'CoffeeScript', 'bytes': '1374'}, {'name': 'ColdFusion', 'bytes': '23329'}, {'name': 'JavaScript', 'bytes': '641'}, {'name': 'Ruby', 'bytes': '38687'}]} |
package org.deeplearning4j.nn.api;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.api.DataSet;
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
import java.util.List;
public interface Classifier extends Model {
/**
* Sets the input and labels and returns a score for the prediction
* wrt true labels
* @param data the data to score
* @return the score for the given input,label pairs
*/
double f1Score(DataSet data);
/**
* Returns the f1 score for the given examples.
* Think of this to be like a percentage right.
* The higher the number the more it got right.
* This is on a scale from 0 to 1.
* @param examples te the examples to classify (one example in each row)
* @param labels the true labels
* @return the scores for each ndarray
*/
double f1Score(INDArray examples, INDArray labels);
/**
* Returns the number of possible labels
* @return the number of possible labels for this classifier
* @deprecated Will be removed in a future release
*/
@Deprecated
int numLabels();
/**
* Train the model based on the datasetiterator
* @param iter the iterator to train on
*/
void fit(DataSetIterator iter);
/**
* Takes in a list of examples
* For each row, returns a label
* @param examples the examples to classify (one example in each row)
* @return the labels for each example
*/
int[] predict(INDArray examples);
/**
* Takes in a DataSet of examples
* For each row, returns a label
* @param dataSet the examples to classify
* @return the labels for each example
*/
List<String> predict(DataSet dataSet);
/**
* Fit the model
* @param examples the examples to classify (one example in each row)
* @param labels the example labels(a binary outcome matrix)
*/
void fit(INDArray examples, INDArray labels);
/**
* Fit the model
* @param data the data to train on
*/
void fit(DataSet data);
/**
* Fit the model
* @param examples the examples to classify (one example in each row)
* @param labels the labels for each example (the number of labels must match
* the number of rows in the example
*/
void fit(INDArray examples, int[] labels);
}
| {'content_hash': '70a559e9831ef8548a6ee79c47ec9af6', 'timestamp': '', 'source': 'github', 'line_count': 91, 'max_line_length': 81, 'avg_line_length': 26.36263736263736, 'alnum_prop': 0.6477699041267194, 'repo_name': 'deeplearning4j/deeplearning4j', 'id': '3643297d3c748331ace9ac4288f1ade7423cb137', 'size': '3290', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/api/Classifier.java', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '1458'}, {'name': 'C', 'bytes': '165340'}, {'name': 'C++', 'bytes': '17817311'}, {'name': 'CMake', 'bytes': '112697'}, {'name': 'CSS', 'bytes': '12974'}, {'name': 'Cuda', 'bytes': '2413085'}, {'name': 'Cython', 'bytes': '12094'}, {'name': 'FreeMarker', 'bytes': '77257'}, {'name': 'HTML', 'bytes': '18609'}, {'name': 'Java', 'bytes': '47657420'}, {'name': 'JavaScript', 'bytes': '296767'}, {'name': 'Kotlin', 'bytes': '2041047'}, {'name': 'PureBasic', 'bytes': '12254'}, {'name': 'Python', 'bytes': '77566'}, {'name': 'Ruby', 'bytes': '4558'}, {'name': 'Scala', 'bytes': '1026'}, {'name': 'Shell', 'bytes': '92012'}, {'name': 'Smarty', 'bytes': '975'}, {'name': 'Starlark', 'bytes': '931'}, {'name': 'TypeScript', 'bytes': '81217'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>concurrency-proxy: Not compatible 👼</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 / concurrency-proxy - 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>
concurrency-proxy
<small>
1.0.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-05-24 01:37:32 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-24 01:37:32 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 4 Virtual package relying on a GMP lib system installation
coq dev Formal proof management system
dune 3.1.1 Fast, portable, and opinionated build system
ocaml 4.10.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.10.2 Official release 4.10.2
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-concurrency/proxy"
dev-repo: "git+https://github.com/coq-concurrency/proxy.git"
bug-reports: "https://github.com/coq-concurrency/proxy/issues"
authors: ["Guillaume Claret"]
license: "MIT"
build: [
[make "-j%{jobs}%"]
]
depends: [
"ocaml" {>= "4.02.0" & < "4.06"}
"base-unix"
"lwt" {>= "2.4.5" & < "5"}
"num"
"base64" {>= "1.0.0" & < "2"}
]
conflicts: [
"ocaml-secondary-compiler"
]
tags: [
"date:2015-01-28"
"keyword:effects"
"keyword:extraction"
]
synopsis: "A proxy to interface concurrent Coq programs with the operating system"
extra-files: [
"coq-concurrency-proxy.install" "md5=96f86b964fc4cd99c310011b83de5f61"
]
url {
src: "https://github.com/coq-concurrency/proxy/archive/1.0.0.tar.gz"
checksum: "md5=36d201bf65ccc649b4704e71e94de712"
}
</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-concurrency-proxy.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).
The following dependencies couldn't be met:
- coq-concurrency-proxy -> ocaml < 4.06
base of this switch (use `--unlock-base' to force)
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-concurrency-proxy.1.0.0</code></dd>
<dt>Return code</dt>
<dd>0</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">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</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': '8a838b1dfa82557e43405d9d824d717e', 'timestamp': '', 'source': 'github', 'line_count': 173, 'max_line_length': 159, 'avg_line_length': 39.79190751445087, 'alnum_prop': 0.53849506101104, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': '565b065697c266af9030aeed96dd9a43f6f9d3e7', 'size': '6909', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.10.2-2.0.6/extra-dev/dev/concurrency-proxy/1.0.0.html', 'mode': '33188', 'license': 'mit', 'language': []} |
var gulp = require('gulp'),
html5Lint = require('gulp-html5-lint');
gulp.task('html:lint', function() {
return gulp.src('./app/*.html')
.pipe(html5Lint());
});
| {'content_hash': 'bc8004d4a60f6f29eaa84c002a899166', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 43, 'avg_line_length': 21.5, 'alnum_prop': 0.6046511627906976, 'repo_name': 'Affiction/Affiction.github.io', 'id': '0a0f90f0060992308aad8a9f378d30568f2823e3', 'size': '319', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tasks/html-lint.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '3166'}, {'name': 'CSS', 'bytes': '583174'}, {'name': 'HTML', 'bytes': '465232'}, {'name': 'JavaScript', 'bytes': '962692'}, {'name': 'Makefile', 'bytes': '30'}, {'name': 'Roff', 'bytes': '320'}, {'name': 'Ruby', 'bytes': '4860'}]} |
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Três</logradouro><bairro>Adelmolândia</bairro><cidade>Sabará</cidade><uf>MG</uf><cep>34525435</cep></feed>
| {'content_hash': '9e0dc5351f3d1d10f928999591177ee2', 'timestamp': '', 'source': 'github', 'line_count': 2, 'max_line_length': 140, 'avg_line_length': 98.5, 'alnum_prop': 0.7208121827411168, 'repo_name': 'chesarex/webservice-cep', 'id': '5db7805c86268f13fcfc1925e86b8f782304b7dc', 'size': '200', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'public/ceps/34/525/435/cep.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
import React, { Component, PropTypes } from 'react'
import { Form } from 'semantic-ui-react'
import { browserHistory } from 'react-router'
import { signup } from '../actions/entities'
const propTypes = {
dispatch: PropTypes.func.isRequired,
size: PropTypes.string.isRequired,
loading: PropTypes.bool.isRequired
}
class SignupForm extends Component {
state = {
email: '',
password: ''
}
handleChange = event => {
const target = event.target
const { value, name } = target
this.setState({
[name]: value
})
}
handleSubmit = event => {
event.preventDefault()
const { dispatch } = this.props
dispatch(signup(this.state)).then(() => browserHistory.goBack())
}
render() {
const { size, loading } = this.props
return (
<Form size={size} onSubmit={this.handleSubmit}>
<Form.Input
icon="user"
iconPosition="left"
name="username"
placeholder="Username"
onChange={this.handleChange}
/>
<Form.Input
icon="mail"
iconPosition="left"
name="email"
type="email"
placeholder="Email"
onChange={this.handleChange}
/>
<Form.Input
icon="lock"
iconPosition="left"
name="password"
type="password"
pattern=".{8,}"
placeholder="Password (at least 8 characters)"
onChange={this.handleChange}
title="Your password length is less than 8"
/>
<Form.Button type="submit" size={size} loading={loading} fluid primary>
Sign Up
</Form.Button>
</Form>
)
}
}
SignupForm.propTypes = propTypes
export default SignupForm
| {'content_hash': 'c6cb780db66272e06d85579f58045bc4', 'timestamp': '', 'source': 'github', 'line_count': 79, 'max_line_length': 79, 'avg_line_length': 22.10126582278481, 'alnum_prop': 0.5773195876288659, 'repo_name': 'kingdido999/atogatari', 'id': 'a25c7e5e8ee8a519aed60cd9ab4ac3483734203c', 'size': '1746', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'client/src/components/SignupForm.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '596618'}, {'name': 'HTML', 'bytes': '1428'}, {'name': 'JavaScript', 'bytes': '1079155'}]} |
#ifndef MMPROTEINPLUGIN_SIMPLEMOLECULERENDERER_H_INCLUDED
#define MMPROTEINPLUGIN_SIMPLEMOLECULERENDERER_H_INCLUDED
#if (defined(_MSC_VER) && (_MSC_VER > 1000))
#pragma once
#endif /* (defined(_MSC_VER) && (_MSC_VER > 1000)) */
#include "mmcore/CallerSlot.h"
#include "mmcore/param/ParamSlot.h"
#include "mmstd/light/CallLight.h"
#include "mmstd_gl/renderer/CallRender3DGL.h"
#include "mmstd_gl/renderer/Renderer3DModuleGL.h"
#include "protein_calls/BindingSiteCall.h"
#include "protein_calls/MolecularDataCall.h"
#include "protein_calls/ProteinColor.h"
#include "protein_gl/DeferredRenderingProvider.h"
#include "glowl/BufferObject.hpp"
#include "glowl/FramebufferObject.hpp"
#include "glowl/GLSLProgram.hpp"
namespace megamol {
namespace protein_gl {
/*
* Simple Molecular Renderer class
*/
class SimpleMoleculeRenderer : public megamol::mmstd_gl::Renderer3DModuleGL {
public:
/** The names of the render modes */
enum RenderMode {
LINES = 0,
STICK = 1,
BALL_AND_STICK = 2,
SPACEFILLING = 3,
SAS = 4,
LINES_FILTER = 5,
STICK_FILTER = 6,
SPACEFILL_FILTER = 7
};
/**
* Answer the name of this module.
*
* @return The name of this module.
*/
static const char* ClassName(void) {
return "SimpleMoleculeRenderer";
}
/**
* Answer a human readable description of this module.
*
* @return A human readable description of this module.
*/
static const char* Description(void) {
return "Offers molecule renderings.";
}
/**
* Answers whether this module is available on the current system.
*
* @return 'true' if the module is available, 'false' otherwise.
*/
static bool IsAvailable(void) {
return true;
}
/** Ctor. */
SimpleMoleculeRenderer(void);
/** Dtor. */
virtual ~SimpleMoleculeRenderer(void);
protected:
/**
* Implementation of 'Create'.
*
* @return 'true' on success, 'false' otherwise.
*/
virtual bool create(void);
/**
* Implementation of 'release'.
*/
virtual void release(void);
private:
/**********************************************************************
* 'render'-functions
**********************************************************************/
/**
* The get extents callback. The module should set the members of
* 'call' to tell the caller the extents of its data (bounding boxes
* and times).
*
* @param call The calling call.
*
* @return The return value of the function.
*/
virtual bool GetExtents(mmstd_gl::CallRender3DGL& call);
/**
* The Open GL Render callback.
*
* @param call The calling call.
* @return The return value of the function.
*/
virtual bool Render(mmstd_gl::CallRender3DGL& call);
/**
* Render the molecular data using lines and points.
*
* @param mol Pointer to the data call.
* @param atomPos Pointer to the interpolated atom positions.
*/
void RenderLines(const megamol::protein_calls::MolecularDataCall* mol, const float* atomPos,
bool useFiltering = false, bool useClipplane = false);
/**
* Render the molecular data in stick mode.
*
* @param mol Pointer to the data call.
* @param atomPos Pointer to the interpolated atom positions.
* @param useFiltering Enables atom filtering in the renderer
* @param useClipplane Enables the a clipplane cutting in the renderer
*/
void RenderStick(const megamol::protein_calls::MolecularDataCall* mol, const float* atomPos,
bool useFiltering = false, bool useClipplane = false);
/**
* Render the molecular data in ball-and-stick mode.
*
* @param mol Pointer to the data call.
* @param atomPos Pointer to the interpolated atom positions.
*/
void RenderBallAndStick(const megamol::protein_calls::MolecularDataCall* mol, const float* atomPos);
/**
* Render the molecular data in spacefilling mode.
*
* @param mol Pointer to the data call.
* @param atomPos Pointer to the interpolated atom positions.
* @param useFiltering Enables atom filtering in the renderer
* @param useClipplane Enables the a clipplane cutting in the renderer
*/
void RenderSpacefilling(const megamol::protein_calls::MolecularDataCall* mol, const float* atomPos,
bool useFiltering = false, bool useClipplane = false);
/**
* Render the molecular data in solvent accessible surface mode.
*
* @param mol Pointer to the data call.
* @param atomPos Pointer to the interpolated atom positions.
*/
void RenderSAS(const megamol::protein_calls::MolecularDataCall* mol, const float* atomPos);
/**
* Update all parameter slots.
*
* @param mol Pointer to the data call.
*/
void UpdateParameters(
const megamol::protein_calls::MolecularDataCall* mol, const protein_calls::BindingSiteCall* bs = 0);
/**********************************************************************
* variables
**********************************************************************/
struct LightParams {
float x, y, z, intensity;
};
/** MolecularDataCall caller slot */
megamol::core::CallerSlot molDataCallerSlot;
/** BindingSiteCall caller slot */
megamol::core::CallerSlot bsDataCallerSlot;
/** Slot to get the lights */
megamol::core::CallerSlot getLightsSlot;
/** camera information */
core::view::Camera cam;
float viewportStuff[4];
glm::mat4 view;
glm::mat4 proj;
glm::mat4 invProj;
glm::mat4 MVinv;
glm::mat4 NormalM;
glm::mat4 MVP;
glm::mat4 MVPinv;
glm::mat4 MVPtransp;
/** parameter slot for color table filename */
megamol::core::param::ParamSlot colorTableFileParam;
/** parameter slot for coloring mode */
megamol::core::param::ParamSlot coloringModeParam0;
/** parameter slot for coloring mode */
megamol::core::param::ParamSlot coloringModeParam1;
/** parameter slot for coloring mode weighting*/
megamol::core::param::ParamSlot cmWeightParam;
/** parameter slot for rendering mode */
megamol::core::param::ParamSlot renderModeParam;
/** parameter slot for stick radius */
megamol::core::param::ParamSlot stickRadiusParam;
/** parameter slot for SAS probe radius */
megamol::core::param::ParamSlot probeRadiusParam;
/** parameter slot for min color of gradient color mode */
megamol::core::param::ParamSlot minGradColorParam;
/** parameter slot for mid color of gradient color mode */
megamol::core::param::ParamSlot midGradColorParam;
/** parameter slot for max color of gradient color mode */
megamol::core::param::ParamSlot maxGradColorParam;
/** list of molecule indices */
megamol::core::param::ParamSlot molIdxListParam;
/** parameter slot for special color */
megamol::core::param::ParamSlot specialColorParam;
/** parameter slot for positional interpolation */
megamol::core::param::ParamSlot interpolParam;
/** Toggle the use of geometry shaders for glyph raycasting */
megamol::core::param::ParamSlot toggleZClippingParam;
/** */
megamol::core::param::ParamSlot clipPlaneTimeOffsetParam;
/** */
megamol::core::param::ParamSlot clipPlaneDurationParam;
/** Toggle use of neighborhood colors for own color */
megamol::core::param::ParamSlot useNeighborColors;
float currentZClipPos;
// shader programs
std::shared_ptr<glowl::GLSLProgram> sphereShader_;
std::shared_ptr<glowl::GLSLProgram> cylinderShader_;
std::shared_ptr<glowl::GLSLProgram> lineShader_;
// buffer objects
enum class Buffers : GLuint {
POSITION = 0,
COLOR = 1,
CYL_PARAMS = 2,
CYL_QUAT = 3,
CYL_COL1 = 4,
CYL_COL2 = 5,
FILTER = 6,
BUFF_COUNT = 7
};
GLuint vertex_array_;
std::array<std::unique_ptr<glowl::BufferObject>, static_cast<int>(Buffers::BUFF_COUNT)> buffers_;
/** The current coloring mode */
protein_calls::ProteinColor::ColoringMode currentColoringMode0;
protein_calls::ProteinColor::ColoringMode currentColoringMode1;
/** The color lookup table (for chains, amino acids,...) */
std::vector<glm::vec3> colorLookupTable_;
/** The color lookup table read from file */
std::vector<glm::vec3> fileColorTable_;
/** The color lookup table which stores the rainbow colors */
std::vector<glm::vec3> rainbowColors_;
bool tableFromFile_;
/** The atom color table for rendering */
std::vector<glm::vec3> atomColorTable_;
/** The current rendering mode */
RenderMode currentRenderMode;
/** vertex array for spheres */
std::vector<glm::vec4> vertSpheres_;
/** vertex array for cylinders */
std::vector<glm::vec4> vertCylinders_;
/** attribute array for quaterinons of the cylinders */
std::vector<glm::vec4> quatCylinders_;
/** attribute array for inParam of the cylinders (radius and length) */
std::vector<glm::vec2> inParaCylinders_;
/** first color array for cylinder */
std::vector<glm::vec3> color1Cylinders_;
/** second color array for cylinder */
std::vector<glm::vec3> color2Cylinders_;
/** Connections filter */
std::vector<int> conFilter_;
/** vertex array for points */
std::vector<glm::vec4> vertPoints_;
/** vertex array for lines */
std::vector<glm::vec4> vertLines_;
/** color array for the lines */
std::vector<glm::vec3> colorLines_;
// the list of molecular indices
vislib::Array<vislib::StringA> molIdxList;
/** The module providing the fbo and the deferred shading */
DeferredRenderingProvider deferredProvider_;
/** The hash of the lastly rendered molecular data call*/
SIZE_T lastDataHash;
};
} // namespace protein_gl
} // namespace megamol
#endif // MMPROTEINPLUGIN_SIMPLEMOLECULERENDERER_H_INCLUDED
| {'content_hash': '9c83950c6a90b7100b7a05cb8968da0d', 'timestamp': '', 'source': 'github', 'line_count': 307, 'max_line_length': 108, 'avg_line_length': 32.96416938110749, 'alnum_prop': 0.6400197628458498, 'repo_name': 'UniStuttgart-VISUS/megamol', 'id': '4a20bf4e3a66296e24b0cdb94451636a422f7624', 'size': '10238', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'plugins/protein_gl/src/SimpleMoleculeRenderer.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '2002354'}, {'name': 'C++', 'bytes': '19542760'}, {'name': 'CMake', 'bytes': '132146'}, {'name': 'Cuda', 'bytes': '1153909'}, {'name': 'Dockerfile', 'bytes': '931'}, {'name': 'GLSL', 'bytes': '1171090'}, {'name': 'Lua', 'bytes': '6010'}, {'name': 'NASL', 'bytes': '603109'}, {'name': 'Perl', 'bytes': '60620'}, {'name': 'Python', 'bytes': '32166'}, {'name': 'Roff', 'bytes': '8819'}, {'name': 'Shell', 'bytes': '5349'}, {'name': 'TeX', 'bytes': '4486'}]} |
package debop4k.data.orm.mapping.associations.join.model;
import debop4k.core.utils.Hashx;
import debop4k.data.orm.model.AbstractHibernateEntity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import javax.persistence.*;
import java.util.Date;
@Entity(name = "Join_Customer")
@Cache(region = "associations", usage = CacheConcurrencyStrategy.READ_WRITE)
@SecondaryTable(name = "JoinCustomerAddress", pkJoinColumns = {@PrimaryKeyJoinColumn(name = "customerId")})
@Getter
@Setter
@ToString
public class Customer extends AbstractHibernateEntity<Integer> {
@Id
@GeneratedValue
@Column(name = "customerId")
Integer id;
String name;
String email;
@Embedded @AttributeOverrides({
@AttributeOverride(name = "street", column = @Column(name = "street", table = "JoinCustomerAddress")),
@AttributeOverride(name = "city", column = @Column(name = "city", table = "JoinCustomerAddress")),
@AttributeOverride(name = "zipcode", column = @Column(name = "zipcode", table = "JoinCustomerAddress")),
})
Address address = new Address();
@CreatedDate
Date createdAt;
@LastModifiedDate
Date lastModifiedAt;
@Override
public int hashCode() {
return Hashx.compute(name, email);
}
private static final long serialVersionUID = 7169746850817753252L;
}
| {'content_hash': 'de51f67e5f7f43f6477438f00e7710b4', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 140, 'avg_line_length': 30.537037037037038, 'alnum_prop': 0.6998180715585203, 'repo_name': 'debop/debop4k', 'id': 'ff1af22616d829e8c8fb372020ad1c0f82f207ff', 'size': '2278', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'debop4k-data-orm/src/test/java/debop4k/data/orm/mapping/associations/join/model/Customer.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1616903'}, {'name': 'Kotlin', 'bytes': '1763466'}, {'name': 'TSQL', 'bytes': '78075'}]} |
require 'open-uri'
require 'open_uri_redirections'
require 'nokogiri'
class IndexAccountJob
include Resque::Plugins::UniqueJob
@queue = :account_queue
def self.perform(seller)
seller = Seller.find(seller)
if seller.region.name == 'Garena'
url = 'http://web.poe.garena.com/account/view-profile/'+seller.account_name
else
url = 'http://www.pathofexile.com/account/view-profile/'+seller.account_name
end
profile = Nokogiri::HTML(open(URI.encode(url), allow_redirections: :safe).read, nil, 'utf-8')
ign = profile.css('div.characters div.profile-character div.character-info span.characterName')
unless ign.first.nil?
ign = ign.first.text
else
ign = '(!) Private'
end
seller.ign = ign
challenge = profile.css('div.challenge-level img.achievement')
seller.challenge_icon = challenge.first["src"] unless challenge.first.nil?
account_id = profile.xpath('/html/body/script[5]').first.content.scan(/accountID: \d+/).first
seller.account_id = account_id.sub('accountID: ', '') if account_id
seller.updated_at = Time.now
seller.save
seller = nil
profile = nil
challenge = nil
ign = nil
end
end | {'content_hash': '6d953bd86eb4211faa120086cb2722db', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 99, 'avg_line_length': 32.5945945945946, 'alnum_prop': 0.6749585406301825, 'repo_name': 'renews/poemarkets', 'id': '5ef0dc603d13801ab245eeaeadc0688546899378', 'size': '1206', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/index_account_job.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '66562'}, {'name': 'CoffeeScript', 'bytes': '10838'}, {'name': 'JavaScript', 'bytes': '143200'}, {'name': 'Ruby', 'bytes': '172414'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/com360.github.com.iml" filepath="$PROJECT_DIR$/.idea/com360.github.com.iml" />
</modules>
</component>
</project> | {'content_hash': '440e1e4afa69f506d20caacd96f1bb64', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 128, 'avg_line_length': 35.75, 'alnum_prop': 0.6678321678321678, 'repo_name': 'com360/com360.github.com', 'id': '378581426155005d8f0f42ddda06202dd29ce544', 'size': '286', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '.idea/modules.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '11626'}, {'name': 'HTML', 'bytes': '4547'}]} |
function [dat] = ft_read_data(filename, varargin)
% FT_READ_DATA reads electrophysiological data from a variety of EEG, MEG and LFP
% files and represents it in a common data-independent format. The supported formats
% are listed in the accompanying FT_READ_HEADER function.
%
% Use as
% dat = ft_read_data(filename, ...)
%
% Additional options should be specified in key-value pairs and can be
% 'header' header structure, see FT_READ_HEADER
% 'begsample' first sample to read
% 'endsample' last sample to read
% 'begtrial' first trial to read, mutually exclusive with begsample+endsample
% 'endtrial' last trial to read, mutually exclusive with begsample+endsample
% 'chanindx' list with channel indices to read
% 'chanunit' cell-array with strings, the desired unit of each channel
% 'checkboundary' boolean, whether to check for reading segments over a trial boundary
% 'checkmaxfilter' boolean, whether to check that maxfilter has been correctly applied (default = true)
% 'cache' boolean, whether to use caching for multiple reads
% 'dataformat' string
% 'headerformat' string
% 'fallback' can be empty or 'biosig' (default = [])
% 'blocking' wait for the selected number of events (default = 'no')
% 'timeout' amount of time in seconds to wait when blocking (default = 5)
%
% This function returns a 2-D matrix of size Nchans*Nsamples for continuous
% data when begevent and endevent are specified, or a 3-D matrix of size
% Nchans*Nsamples*Ntrials for epoched or trial-based data when begtrial
% and endtrial are specified.
%
% The list of supported file formats can be found in FT_READ_HEADER.
%
% See also FT_READ_HEADER, FT_READ_EVENT, FT_WRITE_DATA, FT_WRITE_EVENT
% Copyright (C) 2003-2015 Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_read_data.m 11104 2016-01-22 11:31:09Z roboos $
persistent cachedata % for caching
persistent db_blob % for fcdc_mysql
if isempty(db_blob)
db_blob = 0;
end
if iscell(filename)
ft_warning(sprintf('concatenating data from %d files', numel(filename)));
% this only works if the data is indexed by means of samples, not trials
assert(isempty(ft_getopt(varargin, 'begtrial')));
assert(isempty(ft_getopt(varargin, 'endtrial')));
% use recursion to read data from multiple files
hdr = ft_getopt(varargin, 'header');
if isempty(hdr) || ~isfield(hdr, 'orig') || ~iscell(hdr.orig)
for i=1:numel(filename)
% read the individual file headers
hdr{i} = ft_read_header(filename{i}, varargin{:});
end
else
% use the individual file headers that were read previously
hdr = hdr.orig;
end
nsmp = nan(size(filename));
for i=1:numel(filename)
nsmp(i) = hdr{i}.nSamples*hdr{i}.nTrials;
end
offset = [0 cumsum(nsmp(1:end-1))];
dat = cell(size(filename));
begsample = ft_getopt(varargin, 'begsample', 1);
endsample = ft_getopt(varargin, 'endsample', sum(nsmp));
for i=1:numel(filename)
thisbegsample = begsample - offset(i);
thisendsample = endsample - offset(i);
if thisbegsample<=nsmp(i) && thisendsample>=1
varargin = ft_setopt(varargin, 'header', hdr{i});
varargin = ft_setopt(varargin, 'begsample', max(thisbegsample,1));
varargin = ft_setopt(varargin, 'endsample', min(thisendsample,nsmp(i)));
dat{i} = ft_read_data(filename{i}, varargin{:});
else
dat{i} = [];
end
end
% return the concatenated data
dat = cat(2, dat{:});
return
end
% optionally get the data from the URL and make a temporary local copy
filename = fetch_url(filename);
% get the optional input arguments
hdr = ft_getopt(varargin, 'header');
begsample = ft_getopt(varargin, 'begsample');
endsample = ft_getopt(varargin, 'endsample');
begtrial = ft_getopt(varargin, 'begtrial');
endtrial = ft_getopt(varargin, 'endtrial');
chanindx = ft_getopt(varargin, 'chanindx');
checkboundary = ft_getopt(varargin, 'checkboundary');
checkmaxfilter = ft_getopt(varargin, 'checkmaxfilter', 'yes');
headerformat = ft_getopt(varargin, 'headerformat');
fallback = ft_getopt(varargin, 'fallback');
cache = ft_getopt(varargin, 'cache', false);
dataformat = ft_getopt(varargin, 'dataformat');
chanunit = ft_getopt(varargin, 'chanunit');
timestamp = ft_getopt(varargin, 'timestamp');
% this allows blocking reads to avoid having to poll many times for online processing
blocking = ft_getopt(varargin, 'blocking', false); % true or false
timeout = ft_getopt(varargin, 'timeout', 5); % seconds
% convert from 'yes'/'no' into boolean
blocking = istrue(blocking);
if isempty(dataformat)
% only do the autodetection if the format was not specified
dataformat = ft_filetype(filename);
end
if iscell(dataformat)
% this happens for datasets specified as cell-array for concatenation
dataformat = dataformat{1};
end
% test whether the file or directory exists
if ~any(strcmp(dataformat, {'fcdc_buffer', 'ctf_shm', 'fcdc_mysql'})) && ~exist(filename, 'file')
error('FILEIO:InvalidFileName', 'file or directory ''%s'' does not exist', filename);
end
% ensure that these are double precision and not integers, otherwise the subsequent computations will be messed up
begsample = double(begsample);
endsample = double(endsample);
begtrial = double(begtrial);
endtrial = double(endtrial);
% ensure that the requested sample and trial numbers are integers
if ~isempty(begsample) && mod(begsample, 1)
warning('rounding "begsample" to the nearest integer');
begsample = round(begsample);
end
if ~isempty(endsample) && ~isinf(endsample) && mod(endsample, 1)
warning('rounding "endsample" to the nearest integer');
endsample = round(endsample);
end
if ~isempty(begtrial) && mod(begtrial, 1)
warning('rounding "begtrial" to the nearest integer');
begtrial = round(begtrial);
end
if ~isempty(endtrial) && mod(endtrial, 1)
warning('rounding "endtrial" to the nearest integer');
endtrial = round(endtrial);
end
if strcmp(dataformat, 'compressed')
% the file is compressed, unzip on the fly
inflated = true;
filename = inflate_file(filename);
dataformat = ft_filetype(filename);
else
inflated = false;
end
% ensure that the headerfile and datafile are defined, which are sometimes different than the name of the dataset
[filename, headerfile, datafile] = dataset2files(filename, dataformat);
if ~strcmp(filename, datafile) && ~any(strcmp(dataformat, {'ctf_ds', 'ctf_old', 'fcdc_buffer_offline'}))
filename = datafile; % this function will read the data
dataformat = ft_filetype(filename); % update the filetype
end
% for backward compatibility, default is to check when it is not continous
if isempty(checkboundary)
checkboundary = ~ft_getopt(varargin, 'continuous');
end
% read the header if it is not provided
if isempty(hdr)
hdr = ft_read_header(filename, 'headerformat', headerformat, 'chanindx', chanindx);
if isempty(chanindx)
chanindx = 1:hdr.nChans;
end
else
% set the default channel selection, which is all channels
if isempty(chanindx)
chanindx = 1:hdr.nChans;
end
% test whether the requested channels can be accomodated
if min(chanindx)<1 || max(chanindx)>hdr.nChans
error('FILEIO:InvalidChanIndx', 'selected channels are not present in the data');
end
end
% read until the end of the file if the endsample is "inf"
if any(isinf(endsample)) && any(endsample>0)
endsample = hdr.nSamples*hdr.nTrials;
end
% test whether the requested data segment is not outside the file
if any(begsample<1)
error('FILEIO:InvalidBegSample', 'cannot read data before the begin of the file');
elseif any(endsample>(hdr.nSamples*hdr.nTrials)) && ~blocking
error('FILEIO:InvalidEndSample', 'cannot read data after the end of the file');
end
requesttrials = isempty(begsample) && isempty(endsample);
requestsamples = isempty(begtrial) && isempty(endtrial);
if cache && requesttrials
error('caching is not supported when reading trials')
end
if isempty(begsample) && isempty(endsample) && isempty(begtrial) && isempty(endtrial)
% neither samples nor trials are specified, set the defaults to read the complete data trial-wise (also works for continuous)
requestsamples = 0;
requesttrials = 1;
begtrial = 1;
endtrial = hdr.nTrials;
end
% set the default, which is to assume that it is should check for boundaries when samples are requested
if isempty(checkboundary) && requesttrials
checkboundary = false;
elseif isempty(checkboundary) && requestsamples
checkboundary = true;
end
if requesttrials && requestsamples
error('you cannot select both trials and samples at the same time');
elseif requesttrials
% this allows for support using a continuous reader
if isinf(hdr.nSamples) && begtrial==1
begsample = 1; % computing it here does not work (0*inf=nan)
else
begsample = (begtrial-1)*hdr.nSamples + 1; % compute it the normal way
end
endsample = (endtrial )*hdr.nSamples;
elseif requestsamples
% this allows for support using a trial-based reader
begtrial = floor((begsample-1)/hdr.nSamples)+1;
endtrial = floor((endsample-1)/hdr.nSamples)+1;
else
error('you should either specify begin/end trial or begin/end sample');
end
% test whether the requested data segment does not extend over a discontinuous trial boundary
if checkboundary && hdr.nTrials>1
if begtrial~=endtrial
error('requested data segment extends over a discontinuous trial boundary');
end
end
if strcmp(dataformat, 'bci2000_dat') || strcmp(dataformat, 'eyelink_asc') || strcmp(dataformat, 'gtec_mat')
% caching for these formats is handled in the main section and in read_header
else
% implement the caching in a data-format independent way
if cache && (isempty(cachedata) || ~isequal(cachedata.label,hdr.label(chanindx)))
% create a new FieldTrip raw data structure that will hold the data
cachedata.label = hdr.label(chanindx);
cachedata.fsample = hdr.Fs;
cachedata.time = {};
cachedata.trial = {};
cachedata.cfg = [];
cachedata.sampleinfo = zeros(0,2);
elseif cache && ~isempty(cachedata)
% try to fetch the requested segment from the cache
try
dat = ft_fetch_data(cachedata, 'begsample', begsample', 'endsample', endsample);
% fprintf('caching succeeded\n');
return
catch
% fprintf('caching failed\n');
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read the data with the low-level reading function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch dataformat
case 'AnyWave'
dat = read_ah5_data(filename, hdr, begsample, endsample, chanindx);
case {'4d' '4d_pdf', '4d_m4d', '4d_xyz'}
[fid,message] = fopen(datafile,'rb','ieee-be');
% determine the type and size of the samples
sampletype = lower(hdr.orig.Format);
switch sampletype
case 'short'
samplesize = 2;
case 'long'
samplesize = 4;
case 'float'
samplesize = 4;
case 'double'
samplesize = 8;
otherwise
error('unsupported data format');
end
% 4D/BTi MEG data is multiplexed, can be epoched/discontinuous
offset = (begsample-1)*samplesize*hdr.nChans;
numsamples = endsample-begsample+1;
gain = hdr.orig.ChannelGain;
if isfield(hdr.orig, 'ChannelUnitsPerBit')
upb = hdr.orig.ChannelUnitsPerBit;
else
warning('cannot determine ChannelUnitsPerBit');
upb = 1;
end
% jump to the desired data
fseek(fid, offset, 'cof');
% read the desired data
if length(chanindx)==1
% read only one channel
fseek(fid, (chanindx-1)*samplesize, 'cof'); % seek to begin of channel
dat = fread(fid, numsamples, ['1*' sampletype], (hdr.nChans-1)*samplesize)'; % read one channel, skip the rest
else
% read all channels
dat = fread(fid, [hdr.nChans, numsamples], sampletype);
end
fclose(fid);
if length(chanindx)==1
% only one channel was selected, which is managed by the code above
% nothing to do
elseif ~isequal(chanindx(:)', 1:hdr.nChans)
dat = dat(chanindx,:); % select the desired channels
else
% all channels have been selected
% nothing to do
end
% determine how to calibrate the data
switch sampletype
case {'short', 'long'}
% include both the gain values and the integer-to-double conversion in the calibration
calib = diag(gain(chanindx) .* upb(chanindx));
case {'float', 'double'}
% only include the gain values in the calibration
calib = diag(gain(chanindx));
otherwise
error('unsupported data format');
end
% calibrate the data
dat = double(full(sparse(calib)*dat));
case 'bci2000_dat'
% this requires the load_bcidat mex file to be present on the path
ft_hastoolbox('BCI2000', 1);
% this is inefficient, since it reads the complete data
if isfield(hdr.orig, 'signal') && isfield(hdr.orig, 'states')
% assume that the complete data is stored in the header, this speeds up subsequent read operations
signal = hdr.orig.signal;
states = hdr.orig.states;
parameters = hdr.orig.parameters;
total_samples = hdr.orig.total_samples;
else
[signal, states, parameters, total_samples] = load_bcidat(filename);
end
% apply the callibration from AD units to uV
dat = double(signal(begsample:endsample,chanindx)');
for i=chanindx(:)'
dat(i,:) = dat(i,:).* parameters.SourceChGain.NumericValue(i) + parameters.SourceChOffset.NumericValue(i);
end
dimord = 'chans_samples';
case 'besa_besa'
dat = read_besa_besa(filename, hdr, begsample, endsample, chanindx);
case 'besa_avr'
% BESA average data
orig = readBESAavr(filename);
dat = orig.Data(chanindx, begsample:endsample);
case 'besa_swf'
% BESA source waveform
orig = readBESAswf(filename);
dat = orig.data(chanindx, begsample:endsample);
case {'biosemi_bdf', 'bham_bdf'}
% this uses a mex file for reading the 24 bit data
dat = read_biosemi_bdf(filename, hdr, begsample, endsample, chanindx);
case 'biosemi_old'
% this uses the openbdf and readbdf functions that I copied from the EEGLAB toolbox
epochlength = hdr.orig.Head.SampleRate(1);
% it has already been checked in read_header that all channels have the same sampling rate
begepoch = floor((begsample-1)/epochlength) + 1;
endepoch = floor((endsample-1)/epochlength) + 1;
nepochs = endepoch - begepoch + 1;
orig = openbdf(filename);
dat = zeros(length(chanindx),nepochs*epochlength);
for i=begepoch:endepoch
% read and concatenate all required data epochs
[orig, buf] = readbdf(orig, i, 0);
if size(buf,2)~=hdr.nChans || size(buf,1)~=epochlength
error('error reading selected data from bdf-file');
else
dat(:,((i-begepoch)*epochlength+1):((i-begepoch+1)*epochlength)) = buf(:,chanindx)';
end
end
begsample = begsample - (begepoch-1)*epochlength; % correct for the number of bytes that were skipped
endsample = endsample - (begepoch-1)*epochlength; % correct for the number of bytes that were skipped
dat = dat(:, begsample:endsample);
% close the file between separate read operations
fclose(orig.Head.FILE.FID);
case {'biosig'}
% this requires the biosig toolbox
ft_hastoolbox('BIOSIG', 1);
dat = read_biosig_data(filename, hdr, begsample, endsample, chanindx);
case {'gdf'}
% this requires the biosig toolbox
ft_hastoolbox('BIOSIG', 1);
% In the case that the gdf files are written by one of the FieldTrip
% realtime applications, such as biosig2ft, the gdf recording can be
% split over multiple 1GB files. The sequence of files is then
% filename.gdf <- this is the one that should be specified as the filename/dataset
% filename_1.gdf
% filename_2.gdf
% ...
[p, f, x] = fileparts(filename);
if exist(sprintf('%s_%d%s', fullfile(p, f), 1, x), 'file')
% there are multiple files, count the number of additional files (excluding the first one)
fileset = {filename};
count = 0;
while exist(sprintf('%s_%d%s', fullfile(p, f), count+1, x), 'file')
fileset{end+1} = sprintf('%s_%d%s', fullfile(p, f), count+1, x);
count = count+1;
end
% determine which parts have to be read from which file
nSamples = [hdr.orig.nSamples] .* [hdr.orig.nTrials];
fileBegSample = [0 cumsum(nSamples(1:end-1))]+1;
fileEndSample = cumsum(nSamples);
dat = cell(1,length(fileset));
for i=1:length(fileset)
if begsample<=fileEndSample(i) && endsample>=fileBegSample(i)
% read a piece of data from this file
thisBegSample = begsample - fileBegSample(i) + 1;
thisEndSample = endsample - fileBegSample(i) + 1;
thisBegSample = max(1, thisBegSample);
thisEndSample = min(nSamples(i), thisEndSample);
dat{i} = read_biosig_data(fileset{i}, hdr.orig(i), thisBegSample, thisEndSample, chanindx);
else
dat{i} = zeros(length(chanindx),0);
end
end
% concatenate the data from the different files
dat = cat(2, dat{:});
else
% there is only a single file
dat = read_biosig_data(filename, hdr, begsample, endsample, chanindx);
end
case {'brainvision_eeg', 'brainvision_dat', 'brainvision_seg'}
dat = read_brainvision_eeg(filename, hdr.orig, begsample, endsample, chanindx);
case 'ced_son'
% chek the availability of the required low-level toolbox
ft_hastoolbox('neuroshare', 1);
% use the reading function supplied by Gijs van Elswijk
%
% CED ADC is done in sequence, thus the analog channels
% do not share the same time axis. This is _ignored_ here.
%
% Set the READ_CED_SON parameter 'readtimestamps' to
% 'yes' to get time axis for each data channel returned.
% This time information can be used to do
% a temporal realignment of the data.
tmp = read_ced_son(filename,'readdata','yes',...
'begsample',begsample,...
'endsample',endsample,...
'channels',chanindx);
dat = cell2mat(tmp.data');
case {'deymed_ini' 'deymed_dat'}
% the data is stored in a binary *.dat file
if isempty(hdr)
hdr.orig = [];
end
dat = read_deymed_dat(datafile, hdr.orig, begsample, endsample);
dat = dat(chanindx, :);
case 'emotiv_mat'
% This is a MATLAB *.mat file that is created using the Emotiv MATLAB
% example code. It contains a 25xNsamples matrix and some other stuff.
dat = hdr.orig.data_eeg';
dat = dat(chanindx, begsample:endsample);
case 'gtec_mat'
if isfield(hdr, 'orig')
% these are remembered in the hdr.orig field for fast reading of subsequent segments
log = hdr.orig.log;
names = hdr.orig.names;
else
% this is a simple MATLAB format, it contains a log and a names variable
tmp = load(headerfile);
log = tmp.log;
names = tmp.names;
end
dat = log(chanindx, begsample:endsample);
dimord = 'chans_samples';
case 'itab_raw'
if any(hdr.orig.data_type==[0 1 2])
% big endian
fid = fopen(datafile, 'rb', 'ieee-be');
elseif any(hdr.orig.data_type==[3 4 5])
% little endian
fid = fopen(datafile, 'rb', 'ieee-le');
else
error('unsuppported data_type in itab format');
end
% skip the ascii header
fseek(fid, hdr.orig.start_data, 'bof');
if any(hdr.orig.data_type==[0 3])
% short
fseek(fid, (begsample-1)*hdr.orig.nchan*2, 'cof');
dat = fread(fid, [hdr.orig.nchan endsample-begsample+1], 'int16');
elseif any(hdr.orig.data_type==[1 4])
% long
fseek(fid, (begsample-1)*hdr.orig.nchan*4, 'cof');
dat = fread(fid, [hdr.orig.nchan endsample-begsample+1], 'int32');
elseif any(hdr.orig.data_type==[2 5])
% float
fseek(fid, (begsample-1)*hdr.orig.nchan*4, 'cof');
dat = fread(fid, [hdr.orig.nchan endsample-begsample+1], 'float');
else
error('unsuppported data_type in itab format');
end
% these are the channels that are visible to fieldtrip
chansel = 1:hdr.orig.nchan;
tmp = [hdr.orig.ch(chansel).calib];
tmp = tmp(:);
tmp(tmp==0) = 1;
dat = dat ./ tmp(:,ones(1,size(dat,2)));
% select the subset of visible channels that the user requested
if ~isequal(chanindx(:)', 1:hdr.nChans)
dat = dat(chanindx,:); % select the desired channels
end
case 'combined_ds'
dat = read_combined_ds(filename, hdr, begsample, endsample, chanindx);
case {'ctf_ds', 'ctf_meg4', 'ctf_res4'}
% check that the required low-level toolbox is available
ft_hastoolbox('ctf', 1);
% this returns SQUIDs in T, EEGs in V, ADC's and DACS in V, HLC channels in m, clock channels in s.
if begtrial==endtrial
% specify selection as 3x1 vector
trlbegsample = begsample - hdr.nSamples*(begtrial-1); % within the trial
trlendsample = endsample - hdr.nSamples*(begtrial-1); % within the trial
dat = getCTFdata(hdr.orig, [trlbegsample; trlendsample; begtrial], chanindx, 'T', 'double');
dimord = 'samples_chans';
else
% specify selection as 1xN vector
dat = getCTFdata(hdr.orig, [begtrial:endtrial], chanindx, 'T', 'double');
dimord = 'samples_chans_trials';
end
case {'ctf_old', 'read_ctf_meg4'}
% read it using the open-source MATLAB code that originates from CTF and that was modified by the FCDC
dat = read_ctf_meg4(datafile, hdr.orig, begsample, endsample, chanindx);
case 'ctf_read_meg4'
% check that the required low-level toolbox is available
ft_hastoolbox('eegsf', 1);
% read it using the CTF importer from the NIH and Darren Weber
tmp = ctf_read_meg4(fileparts(datafile), hdr.orig, chanindx, 'all', begtrial:endtrial);
dat = cat(3, tmp.data{:});
% the data is shaped in a 3-D array
dimord = 'samples_chans_trials';
case 'ctf_shm'
% contact Robert Oostenveld if you are interested in real-time acquisition on the CTF system
% read the data from shared memory
[dat, dimord] = read_shm_data(hdr, chanindx, begtrial, endtrial);
case 'dataq_wdq'
dat = read_wdq_data(filename, hdr.orig, begsample, endsample, chanindx);
case 'eeglab_set'
dat = read_eeglabdata(filename, 'header', hdr, 'begtrial', begtrial, 'endtrial', endtrial, 'chanindx', chanindx);
dimord = 'chans_samples_trials';
case 'eeglab_erp'
dat = read_erplabdata(filename, 'header', hdr, 'begtrial', begtrial, 'endtrial', endtrial, 'chanindx', chanindx);
dimord = 'chans_samples_trials';
case 'spmeeg_mat'
dat = read_spmeeg_data(filename, 'header', hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx);
case 'ced_spike6mat'
dat = read_spike6mat_data(filename, 'header', hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx);
case {'edf'}
% this reader is largely similar to the one for bdf
% it uses a mex file for reading the 16 bit data
dat = read_edf(filename, hdr, begsample, endsample, chanindx);
case 'eep_avr'
% check that the required low-level toolbos ix available
ft_hastoolbox('eeprobe', 1);
dat = read_eep_avr(filename);
dat = dat.data(chanindx,begsample:endsample); % select the desired channels and samples
case 'eep_cnt'
% check that the required low-level toolbos ix available
ft_hastoolbox('eeprobe', 1);
dat = read_eep_cnt(filename, begsample, endsample);
dat = dat.data(chanindx,:); % select the desired channels
case 'eyelink_asc'
if isfield(hdr.orig, 'dat')
% this is inefficient, since it keeps the complete data in memory
% but it does speed up subsequent read operations without the user
% having to care about it
asc = hdr.orig;
else
asc = read_eyelink_asc(filename);
end
dat = asc.dat(chanindx,begsample:endsample);
case 'fcdc_buffer'
% read from a networked buffer for realtime analysis
[host, port] = filetype_check_uri(filename);
if blocking
nsamples = endsample; % indices should be zero-offset
nevents = 0; % disable waiting for events
available = buffer_wait_dat([nsamples nevents timeout], host, port);
if available.nsamples<nsamples
error('buffer timed out while waiting for %d samples', nsamples);
end
end
dat = buffer('get_dat', [begsample-1 endsample-1], host, port); % indices should be zero-offset
dat = dat.buf(chanindx,:); % select the desired channels
case 'fcdc_buffer_offline'
% read from a offline FieldTrip buffer data files
dat = read_buffer_offline_data(datafile, hdr, [begsample endsample]);
if ~isequal(chanindx(:)', 1:hdr.nChans)
dat = dat(chanindx,:); % select the desired channels
end
case 'fcdc_matbin'
% multiplexed data in a *.bin file, accompanied by a MATLAB file containing the header
offset = begsample-1;
numsamples = endsample-begsample+1;
if isfield(hdr, 'precision'),
sampletype = hdr.precision;
else
sampletype = 'double'; %original format without precision info in hdr is always in double
end
if strcmp(sampletype, 'single')
samplesize = 4;
elseif strcmp(sampletype, 'double')
samplesize = 8;
end
[fid,message] = fopen(datafile,'rb','ieee-le');
% jump to the desired data
fseek(fid, offset*samplesize*hdr.nChans, 'cof');
% read the desired data
if length(chanindx)==1
% read only one channel
fseek(fid, (chanindx-1)*samplesize, 'cof'); % seek to begin of channel
dat = fread(fid, numsamples, ['1*' sampletype], (hdr.nChans-1)*samplesize)'; % read one channel, skip the rest
else
% read all channels
dat = fread(fid, [hdr.nChans, numsamples], sampletype);
end
fclose(fid);
if length(chanindx)==1
% only one channel was selected, which is managed by the code above
% nothing to do
elseif ~isequal(chanindx(:)', 1:hdr.nChans)
dat = dat(chanindx,:); % select the desired channels
else
% all channels have been selected
% nothing to do
end
case 'fcdc_mysql'
% check that the required low-level toolbox is available
ft_hastoolbox('mysql', 1);
% read from a MySQL server listening somewhere else on the network
db_open(filename);
if db_blob
error('not implemented');
else
for i=begtrial:endtrial
s = db_select('fieldtrip.data', {'nChans', 'nSamples', 'data'}, i);
dum{i-begtrial+1} = mxDeserialize(s.data);
end
dat = zeros(length(chanindx), s.nSamples, endtrial-begtrial+1);
for i=begtrial:endtrial
dat(:,:,i-begtrial+1) = dum{i-begtrial+1}(chanindx,:);
end
dimord = 'chans_samples_trials';
end
case {'egi_egia', 'egi_egis'}
dat = read_egis_data(filename, hdr, begtrial, endtrial, chanindx);
dimord = 'chans_samples_trials';
case 'egi_sbin'
if (bitand(hdr.orig.header_array(1),1) == 0) && ~((hdr.orig.header_array(14)==0) && (hdr.orig.header_array(15) > 1)),
%unsegmented data contains only 1 trial, don't read the whole file
dat = read_sbin_data(filename, hdr, begsample, endsample, chanindx);
requestsamples = 0;
else
%segmented data
dat = read_sbin_data(filename, hdr, begtrial, endtrial, chanindx);
end
dimord = 'chans_samples_trials';
case {'egi_mff_v1' 'egi_mff'} % this is currently the default
% The following represents the code that was written by Ingrid, Robert
% and Giovanni to get started with the EGI mff dataset format. It might
% not support all details of the file formats.
% An alternative implementation has been provided by EGI, this is
% released as fieldtrip/external/egi_mff and referred further down in
% this function as 'egi_mff_v2'.
% check if requested data contains multiple epochs and not segmented. If so, give error
if isfield(hdr.orig.xml,'epochs') && length(hdr.orig.xml.epochs) > 1
if hdr.nTrials ==1
data_in_epoch = zeros(1,length(hdr.orig.xml.epochs));
for iEpoch = 1:length(hdr.orig.xml.epochs)
begsamp_epoch = hdr.orig.epochdef(iEpoch,1);
endsamp_epoch = hdr.orig.epochdef(iEpoch,2);
data_in_epoch(iEpoch) = length(intersect(begsamp_epoch:endsamp_epoch,begsample:endsample));
end
if sum(data_in_epoch>1) > 1
warning('The requested segment from %i to %i is spread out over multiple epochs with possibly discontinuous boundaries', begsample, endsample);
end
end
end
% read in data in different signals
binfiles = dir(fullfile(filename, 'signal*.bin'));
if isempty(binfiles)
error('FieldTrip:read_mff_header:nobin', ['could not find any signal.bin in ' filename_mff ])
end
% determine which channels are in which signal
for iSig = 1:length(hdr.orig.signal)
if iSig == 1
chan2sig_ind(1:hdr.orig.signal(iSig).blockhdr(1).nsignals(1)) = iSig;
else
chan2sig_ind(end+1:end+1+hdr.orig.signal(iSig).blockhdr(1).nsignals(1)) = iSig;
end
end
for iSig = 1:length(hdr.orig.signal)
% adjust chanindx to match with current signal
[dum1, dum2, chanind_sig] = intersect(chanindx, find(chan2sig_ind==iSig));
if isempty(chanind_sig)
% no channels requested from current signal
else
blockhdr = hdr.orig.signal(iSig).blockhdr;
signalname = binfiles(iSig).name;
fullsignalname = fullfile(filename, signalname);
% the number of samples per block can be different
% assume that all channels have the same sampling frequency and number of samples per block
nsamples = zeros(size(blockhdr));
for i=1:length(blockhdr)
nsamples(i) = blockhdr(i).nsamples(1);
end
cumsamples = cumsum(nsamples);
begblock = find(begsample<=cumsamples, 1, 'first');
endblock = find(endsample<=cumsamples, 1, 'first');
datsig = read_mff_bin(fullsignalname, begblock, endblock, chanind_sig);
% concatenate in a matrix
if exist('dat', 'var')
dat{length(dat)+1} = cell2mat(datsig(:,:));
else
dat{1} = cell2mat(datsig(:,:));
end
% select the desired samples from the concatenated blocks
if begblock==1
prevsamples = 0;
else
prevsamples = cumsamples(begblock-1);
end
begsel = begsample-prevsamples;
endsel = endsample-prevsamples;
dat{end} = dat{end}(:,begsel:endsel);
end
end
% concat signals
dat = cat(1,dat{:});
if hdr.nTrials > 1
dat2=zeros(hdr.nChans,hdr.nSamples,hdr.nTrials);
for i=1:hdr.nTrials
dat2(:,:,i)=dat(:,hdr.orig.epochdef(i,1):hdr.orig.epochdef(i,2));
end;
dat=dat2;
end
case 'egi_mff_v2'
% ensure that the EGI_MFF toolbox is on the path
ft_hastoolbox('egi_mff', 1);
% ensure that the JVM is running and the jar file is on the path
%%%%%%%%%%%%%%%%%%%%%%
%workaround for MATLAB bug resulting in global variables being cleared
globalTemp=cell(0);
globalList=whos('global');
varList=whos;
for i=1:length(globalList)
eval(['global ' globalList(i).name ';']);
eval(['globalTemp{end+1}=' globalList(i).name ';']);
end;
%%%%%%%%%%%%%%%%%%%%%%
mff_setup;
%%%%%%%%%%%%%%%%%%%%%%
%workaround for MATLAB bug resulting in global variables being cleared
varNames={varList.name};
for i=1:length(globalList)
eval([globalList(i).name '=globalTemp{i};']);
if ~any(strcmp(globalList(i).name,varNames)) %was global variable originally out of scope?
eval(['clear ' globalList(i).name ';']); %clears link to global variable without affecting it
end;
end;
clear globalTemp globalList varNames varList;
%%%%%%%%%%%%%%%%%%%%%%
if isunix && filename(1)~=filesep
% add the full path to the dataset directory
filename = fullfile(pwd, filename);
elseif ispc && filename(2)~=':'
% add the full path, including drive letter
filename = fullfile(pwd, filename);
end
% pass the header along to speed it up, it will be read on the fly in case it is empty
dat = read_mff_data(filename, 'sample', begsample, endsample, chanindx, hdr);
case 'jaga16'
fid = fopen(filename, 'r');
fseek(fid, hdr.orig.offset + (begtrial-1)*hdr.orig.packetsize, 'bof');
buf = fread(fid, (endtrial-begtrial+1)*hdr.orig.packetsize/2, 'uint16');
fclose(fid);
% the packet is 1396 bytes with timestamp or 1388 without
packet = jaga16_packet(buf, hdr.orig.packetsize==1396);
% Our amplifier was rated as +/- 5mV input signal range, and we use 16
% bit ADC. However when we actually measured the signal range in our
% device the input range can go as high as +/- 6 mV. In this case our
% bit resolution is about 0.2uV/bit. (instead of 0.16uV/bit)
calib = 0.2;
dat = calib * packet.dat;
dimord = 'chans_samples';
case 'micromed_trc'
dat = read_micromed_trc(filename, begsample, endsample);
if ~isequal(chanindx(:)', 1:hdr.nChans)
dat = dat(chanindx,:); % select the desired channels
end
dimord = 'chans_samples';
case {'mpi_ds', 'mpi_dap'}
[hdr, dat] = read_mpi_ds(filename);
dat = dat(chanindx, begsample:endsample); % select the desired channels and samples
case 'netmeg'
% the data is in the same NetCDF file as the header and is cached in the header structure
dat = hdr.orig.Var.waveforms;
dat = dat(:,:,chanindx);
% at the bottom of ft_read_data there is a general handling of the permuting and reshaping
dimord = 'trials_samples_chans';
case 'neuralynx_dma'
dat = read_neuralynx_dma(filename, begsample, endsample, chanindx);
case 'neuralynx_sdma'
dat = read_neuralynx_sdma(filename, begsample, endsample, chanindx);
case 'neuralynx_ncs'
NRecords = hdr.nSamples/512;
begrecord = ceil(begsample/512);
endrecord = ceil(endsample/512);
% read the records that contain the desired samples
ncs = read_neuralynx_ncs(filename, begrecord, endrecord);
% cut out the desired samples
begsample = begsample - (begrecord-1)*512;
endsample = endsample - (begrecord-1)*512;
if istrue(timestamp)
ncs.dat = cast(ncs.dat, class(ncs.TimeStamp));
d = ncs.TimeStamp(2:end)-ncs.TimeStamp(1:end-1);
medianTimestampPerBlock = median(double(d)); % to avoid influence of the gaps
TimestampPerSample = medianTimestampPerBlock/512; % divide by known block size
cls = class(ncs.TimeStamp);
% replace the data with the timestamp of each sample
for i=1:512
ncs.dat(i,:) = ncs.TimeStamp + cast((i-1)*TimestampPerSample,cls);
end
end
% this selects samples and also reshape the data from 512*Nrecords into a linear array (row)
dat = ncs.dat(begsample:endsample);
dat = dat(:)';
case 'neuralynx_nse'
% read all records
nse = read_neuralynx_nse(filename);
% convert timestamps to samples
sample = round((nse.TimeStamp - hdr.FirstTimeStamp)./hdr.TimeStampPerSample + 1);
% select the timestamps that are between begin and endsample
sample = sample(sample>=begsample & sample<=endsample) - begsample + 1;
dat = zeros(1,endsample-begsample+1);
dat(sample) = 1;
case 'neuralynx_nte'
% read all records
nte = read_neuralynx_nte(filename);
% convert timestamps to samples
sample = round((nte.TimeStamp - hdr.FirstTimeStamp)./hdr.TimeStampPerSample + 1);
% select the timestamps that are between begin and endsample
sample = sample(sample>=begsample & sample<=endsample) - begsample + 1;
dat = zeros(1,endsample-begsample+1);
dat(sample) = 1;
case {'neuralynx_ttl', 'neuralynx_tsl', 'neuralynx_tsh'}
% single channel files
dat = read_neuralynx_ttl(filename, begsample, endsample);
case 'neuralynx_bin'
% single channel files
dat = read_neuralynx_bin(filename, begsample, endsample);
case 'neuralynx_ds'
dat = read_neuralynx_ds(filename, hdr, begsample, endsample, chanindx);
case 'neuralynx_cds'
dat = read_neuralynx_cds(filename, hdr, begsample, endsample, chanindx);
case 'nexstim_nxe'
dat = read_nexstim_nxe(filename, begsample, endsample, chanindx);
case 'ns_avg'
% NeuroScan average data
orig = read_ns_avg(filename);
dat = orig.data(chanindx, begsample:endsample);
case {'ns_cnt' 'ns_cnt16', 'ns_cnt32'}
ft_hastoolbox('eeglab', 1);
% Neuroscan continuous data
sample1 = begsample-1;
ldnsamples = endsample-begsample+1; % number of samples to read
if sample1<0
error('begin sample cannot be for the beginning of the file');
end
% the hdr.nsdf was the initial fieldtrip hack to get 32 bit support, now it is realized using a extended dataformat string
if isfield(hdr, 'nsdf') && hdr.nsdf==16
dataformat = 'ns_cnt16';
elseif isfield(hdr, 'nsdf') && hdr.nsdf==32
dataformat = 'ns_cnt32';
end
if strcmp(dataformat, 'ns_cnt')
tmp = loadcnt(filename, 'sample1', sample1, 'ldnsamples', ldnsamples); % let loadcnt figure it out
elseif strcmp(dataformat, 'ns_cnt16')
tmp = loadcnt(filename, 'sample1', sample1, 'ldnsamples', ldnsamples, 'dataformat', 'int16');
elseif strcmp(dataformat, 'ns_cnt32')
tmp = loadcnt(filename, 'sample1', sample1, 'ldnsamples', ldnsamples, 'dataformat', 'int32');
end
dat = tmp.data(chanindx,:);
case 'ns_eeg'
% Neuroscan epoched file
tmp = read_ns_eeg(filename, begtrial:endtrial);
siz = [(endtrial-begtrial+1) hdr.nChans hdr.nSamples];
dat = reshape(tmp.data, siz); % ensure 3-D array
dat = dat(:,chanindx,:); % select channels
dimord = 'trials_chans_samples'; % selection using begsample and endsample will be done later
case {'neuromag_fif' 'neuromag_mne'}
% check that the required low-level toolbox is available
ft_hastoolbox('mne', 1);
if (hdr.orig.iscontinuous)
dat = fiff_read_raw_segment(hdr.orig.raw,begsample+hdr.orig.raw.first_samp-1,endsample+hdr.orig.raw.first_samp-1,chanindx);
dimord = 'chans_samples';
elseif (hdr.orig.isepoched)
data = permute(hdr.orig.epochs.data, [2 3 1]); % Chan X Sample X Trials
if requesttrials
dat = data(chanindx, :, begtrial:endtrial);
else
dat = data(chanindx, begsample:endsample); % reading over boundaries
end
elseif (hdr.orig.isaverage)
assert(isfield(hdr.orig, 'evoked'), '%s does not contain evoked data', filename);
dat = cat(2, hdr.orig.evoked.epochs); % concatenate all epochs, this works both when they are of constant or variable length
if checkboundary
trialnumber = [];
for i = 1:numel(hdr.orig.evoked)
trialnumber = [trialnumber i*ones(size(hdr.orig.evoked(i).times))];
end
if trialnumber(begsample) ~= trialnumber(endsample)
error('requested data segment extends over a discontinuous trial boundary');
end
end
dat = dat(chanindx, begsample:endsample); % select the desired channels and samples
dimord = 'chans_samples';
end
case 'neuromag_mex'
% check that the required low-level toolbox is available
ft_hastoolbox('meg-pd', 1);
begtime = (begsample-1)/hdr.Fs;
begepoch = floor((begsample-1)/hdr.nSamples) + 1;
endepoch = floor((endsample-1)/hdr.nSamples) + 1;
rawdata('any',filename);
rawdata('goto', begtime);
dat = [];
for i=begepoch:endepoch
[buf, status] = rawdata('next');
if ~strcmp(status, 'ok')
error('error reading selected data from fif-file');
else
dat(:,((i-begepoch)*hdr.nSamples+1):((i-begepoch+1)*hdr.nSamples)) = buf(chanindx,:);
end
end
rawdata('close');
begsample = begsample - (begepoch-1)*hdr.nSamples; % correct for the number of bytes that were skipped
endsample = endsample - (begepoch-1)*hdr.nSamples; % correct for the number of bytes that were skipped
dat = dat(:, begsample:endsample);
case 'neuroprax_eeg'
tmp = np_readdata(filename, hdr.orig, begsample - 1, endsample - begsample + 1, 'samples');
dat = tmp.data(:,chanindx)';
case 'oxy3'
dat = read_artinis_oxy3(filename, hdr, begsample, endsample, chanindx);
case 'plexon_ds'
dat = read_plexon_ds(filename, hdr, begsample, endsample, chanindx);
case 'plexon_ddt'
dat = read_plexon_ddt(filename, begsample, endsample);
dat = dat.data(chanindx,:);
case {'read_nex_data'} % this is an alternative reader for nex files
dat = read_nex_data(filename, hdr, begsample, endsample, chanindx);
case {'read_plexon_nex' 'plexon_nex'} % this is the default reader for nex files
dat = zeros(length(chanindx), endsample-begsample+1);
for i=1:length(chanindx)
if hdr.orig.VarHeader(chanindx(i)).Type==5
% this is a continuous channel
if hdr.orig.VarHeader(chanindx(i)).Count==1
[nex, chanhdr] = read_plexon_nex(filename, 'header', hdr.orig, 'channel', chanindx(i), 'tsonly', 1);
% the AD channel contains a single fragment
% determine the sample offset into this fragment
offset = round(double(nex.ts-hdr.FirstTimeStamp)./hdr.TimeStampPerSample);
chanbegsmp = begsample - offset;
chanendsmp = endsample - offset;
if chanbegsmp<1
% the first sample of this channel is later than the beginning of the dataset
% and we are trying to read the beginning of the dataset
[nex, chanhdr] = read_plexon_nex(filename, 'header', hdr.orig, 'channel', chanindx(i), 'tsonly', 0, 'begsample', 1, 'endsample', chanendsmp);
% padd the beginning of this channel with NaNs
nex.dat = [nan(1,offset) nex.dat];
else
[nex, chanhdr] = read_plexon_nex(filename, 'header', hdr.orig, 'channel', chanindx(i), 'tsonly', 0, 'begsample', chanbegsmp, 'endsample', chanendsmp);
end
% copy the desired samples into the output matrix
dat(i,:) = nex.dat;
else
% the AD channel contains multiple fragments
[nex, chanhdr] = read_plexon_nex(filename, 'header', hdr.orig, 'channel', chanindx(i), 'tsonly', 0);
% reconstruct the full AD timecourse with NaNs at all missing samples
offset = round(double(nex.ts-hdr.FirstTimeStamp)./hdr.TimeStampPerSample); % of each fragment, in AD samples
nsample = diff([nex.indx length(nex.dat)]); % of each fragment, in AD samples
% allocate memory to hold the complete continuous record
cnt = nan(1, offset(end)+nsample(end));
for j=1:length(offset)
cntbegsmp = offset(j) + 1;
cntendsmp = offset(j) + nsample(j);
fragbegsmp = nex.indx(j) + 1;
fragendsmp = nex.indx(j) + nsample(j);
cnt(cntbegsmp:cntendsmp) = nex.dat(fragbegsmp:fragendsmp);
end
% copy the desired samples into the output matrix
dat(i,:) = cnt(begsample:endsample);
end
elseif any(hdr.orig.VarHeader(chanindx(i)).Type==[0 1 3])
% it is a neuron(0), event(1) or waveform(3) channel and therefore it has timestamps
[nex, chanhdr] = read_plexon_nex(filename, 'header', hdr.orig, 'channel', chanindx(i), 'tsonly', 1);
% convert the timestamps to samples
sample = round(double(nex.ts - hdr.FirstTimeStamp)./hdr.TimeStampPerSample) + 1;
% select only timestamps that are between begin and endsample
sample = sample(sample>=begsample & sample<=endsample) - begsample + 1;
for j=sample(:)'
dat(i,j) = dat(i,j) + 1;
end
end
end
if any(isnan(dat(:)))
warning('data has been padded with NaNs');
end
case 'plexon_plx'
% determine the continuous channels
contlabel = {hdr.orig.SlowChannelHeader.Name};
for i=1:length(contlabel)
contlabel{i} = deblank(contlabel{i});
end
[contindx, contsel] = match_str(contlabel, hdr.label(chanindx));
% determine the channels with spike waveforms
spikelabel = {hdr.orig.ChannelHeader.Name};
for i=1:length(spikelabel)
spikelabel{i} = deblank(spikelabel{i});
end
[spikeindx, spikesel] = match_str(spikelabel, hdr.label(chanindx));
if (length(contindx)+length(spikeindx))<length(chanindx)
error('not all selected channels could be located in the data');
end
% allocate memory to hold all data
dat = zeros(length(chanindx), endsample-begsample+1);
% this is inefficient, since it reads all samples from each continuous channel
% FIXME different continuous channels may start at a different timestamp
for i=1:length(contsel)
cont = read_plexon_plx(filename, 'header', hdr.orig, 'SlowChannelIndex', contindx(i), 'feedback', 1);
dat(contsel(i),:) = cont(begsample:endsample);
end
% the timestamps of the spikes are in the header and do not have to be read
for i=1:length(spikesel)
% determine the timstamps of this channel
sel = ([hdr.orig.DataBlockHeader.Type]==1 & [hdr.orig.DataBlockHeader.Channel]==hdr.orig.ChannelHeader(spikeindx(i)).Channel);
tsl = [hdr.orig.DataBlockHeader(sel).TimeStamp];
tsh = [hdr.orig.DataBlockHeader(sel).UpperByteOf5ByteTimestamp];
ts = timestamp_plexon(tsl, tsh); % use helper function, this returns an uint64 array
% convert timestamps to samples
sample = round(double(ts - hdr.FirstTimeStamp)./hdr.TimeStampPerSample + 1);
% select only timestamps that are between begin and endsample
sample = sample(sample>=begsample & sample<=endsample) - begsample + 1;
for j=sample(:)'
dat(spikesel(i),j) = dat(spikesel(i),j) + 1;
end
end
case {'yokogawa_ave', 'yokogawa_con', 'yokogawa_raw'}
% the data can be read with three toolboxes: Yokogawa MEG Reader, Maryland sqdread,
% or Yokogawa MEG160 (old inofficial toolbox)
% newest toolbox takes precedence over others.
if ft_hastoolbox('yokogawa_meg_reader', 3); %stay silent if it cannot be added
dat = read_yokogawa_data_new(filename, hdr, begsample, endsample, chanindx);
elseif ft_hastoolbox('sqdproject', 2) % give warning if it cannot be added
% channels are counted 0-based, samples are counted 1-based
[dat, info] = sqdread(filename, 'channels', chanindx-1, 'samples', [begsample endsample]);
dat = dat';
else
ft_hastoolbox('yokogawa', 1); % error if it cannot be added
dat = read_yokogawa_data(filename, hdr, begsample, endsample, chanindx);
end
case 'nmc_archive_k'
dat = read_nmc_archive_k_data(filename, hdr, begsample, endsample, chanindx);
case 'neuroshare' % NOTE: still under development
% check that the required neuroshare toolbox is available
ft_hastoolbox('neuroshare', 1);
tmp = read_neuroshare(filename, 'readanalog', 'yes', 'chanindx', chanindx, 'begsample', begsample, 'endsample', endsample);
dat = tmp.analog.data';
case 'bucn_nirs'
dat = read_bucn_nirsdata(filename, hdr, begsample, endsample, chanindx);
case 'riff_wave'
dat = wavread(filename, [begsample endsample])';
dat = dat(chanindx,:);
case {'neurosim_ds' 'neurosim_signals'}
[hdr, dat] = read_neurosim_signals(filename);
if endsample>size(dat,2)
warning('Simulation was not completed, reading in part of the data')
endsample=size(dat,2);
end
dat = dat(chanindx,begsample:endsample);
case 'neurosim_evolution'
[hdr, dat] = read_neurosim_evolution(filename);
if endsample>size(dat,2)
warning('Simulation was not completed, reading in part of the data')
endsample=size(dat,2);
end
dat = dat(chanindx,begsample:endsample);
case 'neurosim_spikes'
warning('Reading Neurosim spikes as continuous data, for better memory efficiency use spike structure provided by ft_read_spike instead.');
spike = ft_read_spike(filename);
cfg = [];
cfg.trialdef.triallength = inf;
cfg.trialfun = 'ft_trialfun_general';
cfg.trlunit='samples'; %ft_trialfun_general gives us samples, not timestamps
cfg.datafile=filename;
cfg.hdr = ft_read_header(cfg.datafile);
warning('off','FieldTrip:ft_read_event:unsupported_event_format')
cfg = ft_definetrial(cfg);
warning('on','FieldTrip:ft_read_event:unsupported_event_format')
spiketrl = ft_spike_maketrials(cfg,spike);
dat=ft_checkdata(spiketrl,'datatype', 'raw', 'fsample', spiketrl.hdr.Fs);
dat=dat.trial{1};
case {'manscan_mb2', 'manscan_mbi'}
[p, f, x] = fileparts(filename);
filename = fullfile(p, [f, '.mb2']);
trlind = [];
if isfield(hdr.orig, 'epochs') && ~isempty(hdr.orig.epochs)
for i = 1:numel(hdr.orig.epochs)
trlind = [trlind i*ones(1, diff(hdr.orig.epochs(i).samples) + 1)];
end
if checkboundary && (trlind(begsample)~=trlind(endsample))
error('requested data segment extends over a discontinuous trial boundary');
end
else
trlind = ones(1, hdr.nSamples);
end
iEpoch = unique(trlind(begsample:endsample));
sfid = fopen(filename, 'r');
dat = zeros(hdr.nChans, endsample - begsample + 1);
for i = 1:length(iEpoch)
dat(:, trlind(begsample:endsample) == iEpoch(i)) =...
in_fread_manscan(hdr.orig, sfid, iEpoch(i), ...
[sum(trlind==iEpoch(i) & (1:length(trlind))<begsample) ...
sum(trlind==iEpoch(i) & (1:length(trlind))<=endsample)-1]);
end
dat = dat(chanindx, :);
case 'neuroscope_bin'
switch hdr.orig.nBits
case 16
precision = 'int16';
case 32
precision = 'int32';
otherwise
error('unknown precision');
end
dat = LoadBinary(filename, 'frequency', hdr.Fs, 'offset', begsample-1, 'nRecords', endsample-begsample, 'nChannels', hdr.orig.nChannels, 'channels', chanindx, 'precision', precision).';
scaling = hdr.orig.voltageRange/hdr.orig.amplification/(2^hdr.orig.nBits); % scale to S.I. units, i.e. V
dat = scaling.*dat;
case 'blackrock_nsx'
% use the NPMK toolbox for the file reading
ft_hastoolbox('NPMK', 1);
% ensure that the filename contains a full path specification,
% otherwise the low-level function fails
[p,f,e] = fileparts(filename);
if ~isempty(p)
% this is OK
elseif isempty(p)
filename = which(filename);
end
orig = openNSx(filename, 'duration', [begsample endsample]);
keyboard
case 'videomeg_aud'
dat = read_videomeg_aud(filename, hdr, begsample, endsample);
dat = dat(chanindx,:);
case 'videomeg_vid'
dat = read_videomeg_vid(filename, hdr, begsample, endsample);
dat = dat(chanindx,:);
otherwise
if strcmp(fallback, 'biosig') && ft_hastoolbox('BIOSIG', 1)
dat = read_biosig_data(filename, hdr, begsample, endsample, chanindx);
else
error('unsupported data format (%s)', dataformat);
end
end % switch dataformat
if ~exist('dimord', 'var')
dimord = 'chans_samples'; % almost all low-level readers return the data as 2D array
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% reshape the 2-D or 3-D matrix to a common order of the dimensions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch dimord
case {'chans_samples', 'chans_samples_trials'}
% nothing to do
case 'samples_chans'
dat = permute(dat, [2 1]);
dimord = 'chans_samples';
case 'samples_chans_trials'
dat = permute(dat, [2 1 3]);
dimord = 'chans_samples_trials';
case 'trials_samples_chans'
dat = permute(dat, [3 2 1]);
dimord = 'chans_samples_trials';
case 'trials_chans_samples'
dat = permute(dat, [2 3 1]);
dimord = 'chans_samples_trials';
otherwise
error('unexpected dimord');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert the channel data to the desired units
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(chanunit)
if length(chanunit)~=length(chanindx)
error('the number of channel units is inconsistent with the number of channels');
end
% determine the scaling factor for each channel
scaling = cellfun(@ft_scalingfactor, hdr.chanunit(chanindx(:)), chanunit(:));
switch dimord
case 'chans_samples'
for i=1:length(scaling)
dat(i,:) = scaling(i) .* dat(i,:);
end
case'chans_samples_trials';
for i=1:length(scaling)
dat(i,:,:) = scaling(i) .* dat(i,:,:);
end
otherwise
error('unexpected dimord');
end % switch
end % if
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between 3-D trial based and 2-D continuous output
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if requesttrials && strcmp(dimord, 'chans_samples')
% reformat the continuous representation into trials
nchans = size(dat,1);
nsamples = hdr.nSamples;
ntrials = size(dat,2)/hdr.nSamples;
if ntrials>1
dat = reshape(dat, [nchans nsamples ntrials]); % convert into a 3-D array
end
elseif requestsamples && strcmp(dimord, 'chans_samples_trials')
% reformat the trials into a continuous representation
nchans = size(dat,1);
nsamples = size(dat,2);
ntrials = size(dat,3);
dat = reshape(dat, [nchans nsamples*ntrials]); % convert into a 2-D array
% determine the selection w.r.t. the data as it is on disk
begselection = (begtrial-1)*hdr.nSamples + 1;
endselection = (endtrial )*hdr.nSamples;
% determine the selection w.r.t. the data that has been read in
begselection2 = begsample - begselection + 1;
endselection2 = endsample - begselection + 1;
dat = dat(:,begselection2:endselection2);
end
if inflated
% compressed file has been unzipped on the fly, clean up
delete(filename);
end
if strcmp(dataformat, 'bci2000_dat') || strcmp(dataformat, 'eyelink_asc') || strcmp(dataformat, 'gtec_mat')
% caching for these formats is handled in the main section and in read_header
else
% implement caching in a data independent way
if cache && requestsamples
% add the new segment to the cache
% FIMXE the cache size should be limited
cachedata.sampleinfo(end+1,:) = [begsample endsample];
cachedata.trial{end+1} = dat;
cachedata.time{end+1} = (1:size(dat,2))/cachedata.fsample;
end
end
| {'content_hash': 'bdd5840c94a7f63c1fda2ec5b3bcddbc', 'timestamp': '', 'source': 'github', 'line_count': 1404, 'max_line_length': 193, 'avg_line_length': 40.11965811965812, 'alnum_prop': 0.6472802158784263, 'repo_name': 'pchrapka/brain-modelling', 'id': 'a9f67780d520a1ddfa24fffc3a872ddbedc443a9', 'size': '56328', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'external/fieldtrip-20160128/fileio/ft_read_data.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Jupyter Notebook', 'bytes': '2265630'}, {'name': 'M', 'bytes': '2270'}, {'name': 'MATLAB', 'bytes': '1750479'}, {'name': 'Makefile', 'bytes': '305'}, {'name': 'Objective-C', 'bytes': '1122'}, {'name': 'Shell', 'bytes': '45091'}]} |
<!doctype html>
<title>CodeMirror: User Manual</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="docs.css">
<script src="activebookmark.js"></script>
<script src="../lib/codemirror.js"></script>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../addon/runmode/runmode.js"></script>
<script src="../addon/runmode/colorize.js"></script>
<script src="../mode/javascript/javascript.js"></script>
<script src="../mode/xml/xml.js"></script>
<script src="../mode/css/css.js"></script>
<script src="../mode/htmlmixed/htmlmixed.js"></script>
<style>
dt { text-indent: -2em; padding-left: 2em; margin-top: 1em; }
dd { margin-left: 1.5em; margin-bottom: 1em; }
dt {margin-top: 1em;}
dd dl, dd dt, dd dd, dd ul { margin-top: 0; margin-bottom: 0; }
dt + dt { margin-top: 0; }
dt.command { position: relative; }
span.keybinding { position: absolute; right: 0; font-size: 80%; color: #555; text-indent: 0; }
</style>
<div id=nav>
<a href="https://codemirror.net"><h1>CodeMirror</h1><img id=logo src="logo.png"></a>
<ul>
<li><a href="../index.html">Home</a></li>
<li><a href="#overview" class=active data-default="true">Manual</a></li>
<li><a href="https://github.com/codemirror/codemirror">Code</a></li>
</ul>
<ul>
<li><a href="#usage">Basic Usage</a></li>
<li><a href="#config">Configuration</a></li>
<li><a href="#events">Events</a></li>
<li><a href="#keymaps">Key maps</a></li>
<li><a href="#commands">Commands</a></li>
<li><a href="#styling">Customized Styling</a></li>
<li><a href="#api">Programming API</a>
<ul>
<li><a href="#api_constructor">Constructor</a></li>
<li><a href="#api_content">Content manipulation</a></li>
<li><a href="#api_selection">Selection</a></li>
<li><a href="#api_configuration">Configuration</a></li>
<li><a href="#api_doc">Document management</a></li>
<li><a href="#api_history">History</a></li>
<li><a href="#api_marker">Text-marking</a></li>
<li><a href="#api_decoration">Widget, gutter, and decoration</a></li>
<li><a href="#api_sizing">Sizing, scrolling, and positioning</a></li>
<li><a href="#api_mode">Mode, state, and tokens</a></li>
<li><a href="#api_misc">Miscellaneous methods</a></li>
<li><a href="#api_static">Static properties</a></li>
</ul>
</li>
<li><a href="#addons">Addons</a></li>
<li><a href="#modeapi">Writing CodeMirror Modes</a></li>
<li><a href="#vimapi">Vim Mode API</a>
<ul>
<li><a href="#vimapi_configuration">Configuration</a></li>
<li><a href="#vimapi_extending">Extending VIM</a></li>
</ul>
</li>
</ul>
</div>
<article>
<section class=first id=overview>
<h2 style="position: relative">
User manual and reference guide
<span style="color: #888; font-size: 1rem; position: absolute; right: 0; bottom: 0">version 5.49.0</span>
</h2>
<p>CodeMirror is a code-editor component that can be embedded in
Web pages. The core library provides <em>only</em> the editor
component, no accompanying buttons, auto-completion, or other IDE
functionality. It does provide a rich API on top of which such
functionality can be straightforwardly implemented. See
the <a href="#addons">addons</a> included in the distribution,
and the <a href="https://github.com/codemirror/CodeMirror/wiki/CodeMirror-addons">list
of externally hosted addons</a>, for reusable
implementations of extra features.</p>
<p>CodeMirror works with language-specific modes. Modes are
JavaScript programs that help color (and optionally indent) text
written in a given language. The distribution comes with a number
of modes (see the <a href="../mode/"><code>mode/</code></a>
directory), and it isn't hard to <a href="#modeapi">write new
ones</a> for other languages.</p>
</section>
<section id=usage>
<h2>Basic Usage</h2>
<p>The easiest way to use CodeMirror is to simply load the script
and style sheet found under <code>lib/</code> in the distribution,
plus a mode script from one of the <code>mode/</code> directories.
For example:</p>
<pre data-lang="text/html"><script src="lib/codemirror.js"></script>
<link rel="stylesheet" href="lib/codemirror.css">
<script src="mode/javascript/javascript.js"></script></pre>
<p>(Alternatively, use a module loader. <a href="#modloader">More
about that later.</a>)</p>
<p>Having done this, an editor instance can be created like
this:</p>
<pre data-lang="javascript">var myCodeMirror = CodeMirror(document.body);</pre>
<p>The editor will be appended to the document body, will start
empty, and will use the mode that we loaded. To have more control
over the new editor, a configuration object can be passed
to <a href="#CodeMirror"><code>CodeMirror</code></a> as a second
argument:</p>
<pre data-lang="javascript">var myCodeMirror = CodeMirror(document.body, {
value: "function myScript(){return 100;}\n",
mode: "javascript"
});</pre>
<p>This will initialize the editor with a piece of code already in
it, and explicitly tell it to use the JavaScript mode (which is
useful when multiple modes are loaded).
See <a href="#config">below</a> for a full discussion of the
configuration options that CodeMirror accepts.</p>
<p>In cases where you don't want to append the editor to an
element, and need more control over the way it is inserted, the
first argument to the <code>CodeMirror</code> function can also
be a function that, when given a DOM element, inserts it into the
document somewhere. This could be used to, for example, replace a
textarea with a real editor:</p>
<pre data-lang="javascript">var myCodeMirror = CodeMirror(function(elt) {
myTextArea.parentNode.replaceChild(elt, myTextArea);
}, {value: myTextArea.value});</pre>
<p>However, for this use case, which is a common way to use
CodeMirror, the library provides a much more powerful
shortcut:</p>
<pre data-lang="javascript">var myCodeMirror = CodeMirror.fromTextArea(myTextArea);</pre>
<p>This will, among other things, ensure that the textarea's value
is updated with the editor's contents when the form (if it is part
of a form) is submitted. See the <a href="#fromTextArea">API
reference</a> for a full description of this method.</p>
<h3 id=modloader>Module loaders</h3>
<p>The files in the CodeMirror distribution contain shims for
loading them (and their dependencies) in AMD or CommonJS
environments. If the variables <code>exports</code>
and <code>module</code> exist and have type object, CommonJS-style
require will be used. If not, but there is a
function <code>define</code> with an <code>amd</code> property
present, AMD-style (RequireJS) will be used.</p>
<p>It is possible to
use <a href="http://browserify.org/">Browserify</a> or similar
tools to statically build modules using CodeMirror. Alternatively,
use <a href="http://requirejs.org/">RequireJS</a> to dynamically
load dependencies at runtime. Both of these approaches have the
advantage that they don't use the global namespace and can, thus,
do things like load multiple versions of CodeMirror alongside each
other.</p>
<p>Here's a simple example of using RequireJS to load CodeMirror:</p>
<pre data-lang="javascript">require([
"cm/lib/codemirror", "cm/mode/htmlmixed/htmlmixed"
], function(CodeMirror) {
CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
mode: "htmlmixed"
});
});</pre>
<p>It will automatically load the modes that the mixed HTML mode
depends on (XML, JavaScript, and CSS). Do <em>not</em> use
RequireJS' <code>paths</code> option to configure the path to
CodeMirror, since it will break loading submodules through
relative paths. Use
the <a href="http://requirejs.org/docs/api.html#packages"><code>packages</code></a>
configuration option instead, as in:</p>
<pre data-lang=javascript>require.config({
packages: [{
name: "codemirror",
location: "../path/to/codemirror",
main: "lib/codemirror"
}]
});</pre>
</section>
<section id=config>
<h2>Configuration</h2>
<p>Both the <a href="#CodeMirror"><code>CodeMirror</code></a>
function and its <code>fromTextArea</code> method take as second
(optional) argument an object containing configuration options.
Any option not supplied like this will be taken
from <a href="#defaults"><code>CodeMirror.defaults</code></a>, an
object containing the default options. You can update this object
to change the defaults on your page.</p>
<p>Options are not checked in any way, so setting bogus option
values is bound to lead to odd errors.</p>
<p>These are the supported options:</p>
<dl>
<dt id="option_value"><code><strong>value</strong>: string|CodeMirror.Doc</code></dt>
<dd>The starting value of the editor. Can be a string, or
a <a href="#api_doc">document object</a>.</dd>
<dt id="option_mode"><code><strong>mode</strong>: string|object</code></dt>
<dd>The mode to use. When not given, this will default to the
first mode that was loaded. It may be a string, which either
simply names the mode or is
a <a href="http://en.wikipedia.org/wiki/MIME">MIME</a> type
associated with the mode. Alternatively, it may be an object
containing configuration options for the mode, with
a <code>name</code> property that names the mode (for
example <code>{name: "javascript", json: true}</code>). The demo
pages for each mode contain information about what configuration
parameters the mode supports. You can ask CodeMirror which modes
and MIME types have been defined by inspecting
the <code>CodeMirror.modes</code>
and <code>CodeMirror.mimeModes</code> objects. The first maps
mode names to their constructors, and the second maps MIME types
to mode specs.</dd>
<dt id="option_lineSeparator"><code><strong>lineSeparator</strong>: string|null</code></dt>
<dd>Explicitly set the line separator for the editor. By default
(value <code>null</code>), the document will be split on CRLFs
as well as lone CRs and LFs, and a single LF will be used as
line separator in all output (such
as <a href="#getValue"><code>getValue</code></a>). When a
specific string is given, lines will only be split on that
string, and output will, by default, use that same
separator.</dd>
<dt id="option_theme"><code><strong>theme</strong>: string</code></dt>
<dd>The theme to style the editor with. You must make sure the
CSS file defining the corresponding <code>.cm-s-[name]</code>
styles is loaded (see
the <a href="../theme/"><code>theme</code></a> directory in the
distribution). The default is <code>"default"</code>, for which
colors are included in <code>codemirror.css</code>. It is
possible to use multiple theming classes at once—for
example <code>"foo bar"</code> will assign both
the <code>cm-s-foo</code> and the <code>cm-s-bar</code> classes
to the editor.</dd>
<dt id="option_indentUnit"><code><strong>indentUnit</strong>: integer</code></dt>
<dd>How many spaces a block (whatever that means in the edited
language) should be indented. The default is 2.</dd>
<dt id="option_smartIndent"><code><strong>smartIndent</strong>: boolean</code></dt>
<dd>Whether to use the context-sensitive indentation that the
mode provides (or just indent the same as the line before).
Defaults to true.</dd>
<dt id="option_tabSize"><code><strong>tabSize</strong>: integer</code></dt>
<dd>The width of a tab character. Defaults to 4.</dd>
<dt id="option_indentWithTabs"><code><strong>indentWithTabs</strong>: boolean</code></dt>
<dd>Whether, when indenting, the first N*<code>tabSize</code>
spaces should be replaced by N tabs. Default is false.</dd>
<dt id="option_electricChars"><code><strong>electricChars</strong>: boolean</code></dt>
<dd>Configures whether the editor should re-indent the current
line when a character is typed that might change its proper
indentation (only works if the mode supports indentation).
Default is true.</dd>
<dt id="option_specialChars"><code><strong>specialChars</strong>: RegExp</code></dt>
<dd>A regular expression used to determine which characters
should be replaced by a
special <a href="#option_specialCharPlaceholder">placeholder</a>.
Mostly useful for non-printing special characters. The default
is <code>/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/</code>.</dd>
<dt id="option_specialCharPlaceholder"><code><strong>specialCharPlaceholder</strong>: function(char) → Element</code></dt>
<dd>A function that, given a special character identified by
the <a href="#option_specialChars"><code>specialChars</code></a>
option, produces a DOM node that is used to represent the
character. By default, a red dot (<span style="color: red">•</span>)
is shown, with a title tooltip to indicate the character code.</dd>
<dt id="option_direction"><code><strong>direction</strong>: "ltr" | "rtl"</code></dt>
<dd>Flips overall layout and selects base paragraph direction to
be left-to-right or right-to-left. Default is "ltr".
CodeMirror applies the Unicode Bidirectional Algorithm to each
line, but does not autodetect base direction — it's set to the
editor direction for all lines. The resulting order is
sometimes wrong when base direction doesn't match user intent
(for example, leading and trailing punctuation jumps to the
wrong side of the line). Therefore, it's helpful for
multilingual input to let users toggle this option.
<dt id="option_rtlMoveVisually"><code><strong>rtlMoveVisually</strong>: boolean</code></dt>
<dd>Determines whether horizontal cursor movement through
right-to-left (Arabic, Hebrew) text is visual (pressing the left
arrow moves the cursor left) or logical (pressing the left arrow
moves to the next lower index in the string, which is visually
right in right-to-left text). The default is <code>false</code>
on Windows, and <code>true</code> on other platforms.</dd>
<dt id="option_keyMap"><code><strong>keyMap</strong>: string</code></dt>
<dd>Configures the key map to use. The default
is <code>"default"</code>, which is the only key map defined
in <code>codemirror.js</code> itself. Extra key maps are found in
the <a href="../keymap/"><code>key map</code></a> directory. See
the <a href="#keymaps">section on key maps</a> for more
information.</dd>
<dt id="option_extraKeys"><code><strong>extraKeys</strong>: object</code></dt>
<dd>Can be used to specify extra key bindings for the editor,
alongside the ones defined
by <a href="#option_keyMap"><code>keyMap</code></a>. Should be
either null, or a valid <a href="#keymaps">key map</a> value.</dd>
<dt id="option_configureMouse"><code><strong>configureMouse</strong>: fn(cm: CodeMirror, repeat: "single" | "double" | "triple", event: Event) → Object</code></dt>
<dd>Allows you to configure the behavior of mouse selection and
dragging. The function is called when the left mouse button is
pressed. The returned object may have the following properties:
<dl>
<dt><code><strong>unit</strong>: "char" | "word" | "line" | "rectangle" | fn(CodeMirror, Pos) → {from: Pos, to: Pos}</code></dt>
<dd>The unit by which to select. May be one of the built-in
units or a function that takes a position and returns a
range around that, for a custom unit. The default is to
return <code>"word"</code> for double
clicks, <code>"line"</code> for triple
clicks, <code>"rectangle"</code> for alt-clicks (or, on
Chrome OS, meta-shift-clicks), and <code>"single"</code>
otherwise.</dd>
<dt><code><strong>extend</strong>: bool</code></dt>
<dd>Whether to extend the existing selection range or start
a new one. By default, this is enabled when shift
clicking.</dd>
<dt><code><strong>addNew</strong>: bool</code></dt>
<dd>When enabled, this adds a new range to the existing
selection, rather than replacing it. The default behavior is
to enable this for command-click on Mac OS, and
control-click on other platforms.</dd>
<dt><code><strong>moveOnDrag</strong>: bool</code></dt>
<dd>When the mouse even drags content around inside the
editor, this controls whether it is copied (false) or moved
(true). By default, this is enabled by alt-clicking on Mac
OS, and ctrl-clicking elsewhere.</dd>
</dl>
</dd>
<dt id="option_lineWrapping"><code><strong>lineWrapping</strong>: boolean</code></dt>
<dd>Whether CodeMirror should scroll or wrap for long lines.
Defaults to <code>false</code> (scroll).</dd>
<dt id="option_lineNumbers"><code><strong>lineNumbers</strong>: boolean</code></dt>
<dd>Whether to show line numbers to the left of the editor.</dd>
<dt id="option_firstLineNumber"><code><strong>firstLineNumber</strong>: integer</code></dt>
<dd>At which number to start counting lines. Default is 1.</dd>
<dt id="option_lineNumberFormatter"><code><strong>lineNumberFormatter</strong>: function(line: integer) → string</code></dt>
<dd>A function used to format line numbers. The function is
passed the line number, and should return a string that will be
shown in the gutter.</dd>
<dt id="option_gutters"><code><strong>gutters</strong>: array<string | {className: string, style: ?string}></code></dt>
<dd>Can be used to add extra gutters (beyond or instead of the
line number gutter). Should be an array of CSS class names or
class name / CSS string pairs, each of which defines
a <code>width</code> (and optionally a background), and which
will be used to draw the background of the gutters. <em>May</em>
include the <code>CodeMirror-linenumbers</code> class, in order
to explicitly set the position of the line number gutter (it
will default to be to the right of all other gutters). These
class names are the keys passed
to <a href="#setGutterMarker"><code>setGutterMarker</code></a>.</dd>
<dt id="option_fixedGutter"><code><strong>fixedGutter</strong>: boolean</code></dt>
<dd>Determines whether the gutter scrolls along with the content
horizontally (false) or whether it stays fixed during horizontal
scrolling (true, the default).</dd>
<dt id="option_scrollbarStyle"><code><strong>scrollbarStyle</strong>: string</code></dt>
<dd>Chooses a scrollbar implementation. The default
is <code>"native"</code>, showing native scrollbars. The core
library also provides the <code>"null"</code> style, which
completely hides the
scrollbars. <a href="#addon_simplescrollbars">Addons</a> can
implement additional scrollbar models.</dd>
<dt id="option_coverGutterNextToScrollbar"><code><strong>coverGutterNextToScrollbar</strong>: boolean</code></dt>
<dd>When <a href="#option_fixedGutter"><code>fixedGutter</code></a>
is on, and there is a horizontal scrollbar, by default the
gutter will be visible to the left of this scrollbar. If this
option is set to true, it will be covered by an element with
class <code>CodeMirror-gutter-filler</code>.</dd>
<dt id="option_inputStyle"><code><strong>inputStyle</strong>: string</code></dt>
<dd>Selects the way CodeMirror handles input and focus. The core
library defines the <code>"textarea"</code>
and <code>"contenteditable"</code> input models. On mobile
browsers, the default is <code>"contenteditable"</code>. On
desktop browsers, the default is <code>"textarea"</code>.
Support for IME and screen readers is better in
the <code>"contenteditable"</code> model. The intention is to
make it the default on modern desktop browsers in the
future.</dd>
<dt id="option_readOnly"><code><strong>readOnly</strong>: boolean|string</code></dt>
<dd>This disables editing of the editor content by the user. If
the special value <code>"nocursor"</code> is given (instead of
simply <code>true</code>), focusing of the editor is also
disallowed.</dd>
<dt id="option_showCursorWhenSelecting"><code><strong>showCursorWhenSelecting</strong>: boolean</code></dt>
<dd>Whether the cursor should be drawn when a selection is
active. Defaults to false.</dd>
<dt id="option_lineWiseCopyCut"><code><strong>lineWiseCopyCut</strong>: boolean</code></dt>
<dd>When enabled, which is the default, doing copy or cut when
there is no selection will copy or cut the whole lines that have
cursors on them.</dd>
<dt id="option_pasteLinesPerSelection"><code><strong>pasteLinesPerSelection</strong>: boolean</code></dt>
<dd>When pasting something from an external source (not from the
editor itself), if the number of lines matches the number of
selection, CodeMirror will by default insert one line per
selection. You can set this to <code>false</code> to disable
that behavior.</dd>
<dt id="option_selectionsMayTouch"><code><strong>selectionsMayTouch</strong>: boolean</code></dt>
<dd>Determines whether multiple selections are joined as soon as
they touch (the default) or only when they overlap (true).</dd>
<dt id="option_undoDepth"><code><strong>undoDepth</strong>: integer</code></dt>
<dd>The maximum number of undo levels that the editor stores.
Note that this includes selection change events. Defaults to
200.</dd>
<dt id="option_historyEventDelay"><code><strong>historyEventDelay</strong>: integer</code></dt>
<dd>The period of inactivity (in milliseconds) that will cause a
new history event to be started when typing or deleting.
Defaults to 1250.</dd>
<dt id="option_tabindex"><code><strong>tabindex</strong>: integer</code></dt>
<dd>The <a href="http://www.w3.org/TR/html401/interact/forms.html#adef-tabindex">tab
index</a> to assign to the editor. If not given, no tab index
will be assigned.</dd>
<dt id="option_autofocus"><code><strong>autofocus</strong>: boolean</code></dt>
<dd>Can be used to make CodeMirror focus itself on
initialization. Defaults to off.
When <a href="#fromTextArea"><code>fromTextArea</code></a> is
used, and no explicit value is given for this option, it will be
set to true when either the source textarea is focused, or it
has an <code>autofocus</code> attribute and no other element is
focused.</dd>
<dt id="option_phrases"><code><strong>phrases</strong>: ?object</code></dt>
<dd>Some addons run user-visible strings (such as labels in the
interface) through the <a href="#phrase"><code>phrase</code></a>
method to allow for translation. This option determines the
return value of that method. When it is null or an object that
doesn't have a property named by the input string, that string
is returned. Otherwise, the value of the property corresponding
to that string is returned.</dd>
</dl>
<p>Below this a few more specialized, low-level options are
listed. These are only useful in very specific situations, you
might want to skip them the first time you read this manual.</p>
<dl>
<dt id="option_dragDrop"><code><strong>dragDrop</strong>: boolean</code></dt>
<dd>Controls whether drag-and-drop is enabled. On by default.</dd>
<dt id="option_allowDropFileTypes"><code><strong>allowDropFileTypes</strong>: array<string></code></dt>
<dd>When set (default is <code>null</code>) only files whose
type is in the array can be dropped into the editor. The strings
should be MIME types, and will be checked against
the <a href="https://w3c.github.io/FileAPI/#dfn-type"><code>type</code></a>
of the <code>File</code> object as reported by the browser.</dd>
<dt id="option_cursorBlinkRate"><code><strong>cursorBlinkRate</strong>: number</code></dt>
<dd>Half-period in milliseconds used for cursor blinking. The default blink
rate is 530ms. By setting this to zero, blinking can be disabled. A
negative value hides the cursor entirely.</dd>
<dt id="option_cursorScrollMargin"><code><strong>cursorScrollMargin</strong>: number</code></dt>
<dd>How much extra space to always keep above and below the
cursor when approaching the top or bottom of the visible view in
a scrollable document. Default is 0.</dd>
<dt id="option_cursorHeight"><code><strong>cursorHeight</strong>: number</code></dt>
<dd>Determines the height of the cursor. Default is 1, meaning
it spans the whole height of the line. For some fonts (and by
some tastes) a smaller height (for example <code>0.85</code>),
which causes the cursor to not reach all the way to the bottom
of the line, looks better</dd>
<dt id="option_resetSelectionOnContextMenu"><code><strong>resetSelectionOnContextMenu</strong>: boolean</code></dt>
<dd>Controls whether, when the context menu is opened with a
click outside of the current selection, the cursor is moved to
the point of the click. Defaults to <code>true</code>.</dd>
<dt id="option_workTime"><code id="option_wordkDelay"><strong>workTime</strong>, <strong>workDelay</strong>: number</code></dt>
<dd>Highlighting is done by a pseudo background-thread that will
work for <code>workTime</code> milliseconds, and then use
timeout to sleep for <code>workDelay</code> milliseconds. The
defaults are 200 and 300, you can change these options to make
the highlighting more or less aggressive.</dd>
<dt id="option_pollInterval"><code><strong>pollInterval</strong>: number</code></dt>
<dd>Indicates how quickly CodeMirror should poll its input
textarea for changes (when focused). Most input is captured by
events, but some things, like IME input on some browsers, don't
generate events that allow CodeMirror to properly detect it.
Thus, it polls. Default is 100 milliseconds.</dd>
<dt id="option_flattenSpans"><code><strong>flattenSpans</strong>: boolean</code></dt>
<dd>By default, CodeMirror will combine adjacent tokens into a
single span if they have the same class. This will result in a
simpler DOM tree, and thus perform better. With some kinds of
styling (such as rounded corners), this will change the way the
document looks. You can set this option to false to disable this
behavior.</dd>
<dt id="option_addModeClass"><code><strong>addModeClass</strong>: boolean</code></dt>
<dd>When enabled (off by default), an extra CSS class will be
added to each token, indicating the
(<a href="#innerMode">inner</a>) mode that produced it, prefixed
with <code>"cm-m-"</code>. For example, tokens from the XML mode
will get the <code>cm-m-xml</code> class.</dd>
<dt id="option_maxHighlightLength"><code><strong>maxHighlightLength</strong>: number</code></dt>
<dd>When highlighting long lines, in order to stay responsive,
the editor will give up and simply style the rest of the line as
plain text when it reaches a certain position. The default is
10 000. You can set this to <code>Infinity</code> to turn off
this behavior.</dd>
<dt id="option_viewportMargin"><code><strong>viewportMargin</strong>: integer</code></dt>
<dd>Specifies the amount of lines that are rendered above and
below the part of the document that's currently scrolled into
view. This affects the amount of updates needed when scrolling,
and the amount of work that such an update does. You should
usually leave it at its default, 10. Can be set
to <code>Infinity</code> to make sure the whole document is
always rendered, and thus the browser's text search works on it.
This <em>will</em> have bad effects on performance of big
documents.</dd>
<dt id="option_spellcheck"><code><strong>spellcheck</strong>: boolean</code></dt>
<dd>Specifies whether or not spellcheck will be enabled on the input.</dd>
<dt id="option_autocorrect"><code><strong>autocorrect</strong>: boolean</code></dt>
<dd>Specifies whether or not autocorrect will be enabled on the input.</dd>
<dt id="option_autocapitalize"><code><strong>autocapitalize</strong>: boolean</code></dt>
<dd>Specifies whether or not autocapitalization will be enabled on the input.</dd>
</dl>
</section>
<section id=events>
<h2>Events</h2>
<p>Various CodeMirror-related objects emit events, which allow
client code to react to various situations. Handlers for such
events can be registered with the <a href="#on"><code>on</code></a>
and <a href="#off"><code>off</code></a> methods on the objects
that the event fires on. To fire your own events,
use <code>CodeMirror.signal(target, name, args...)</code>,
where <code>target</code> is a non-DOM-node object.</p>
<p>An editor instance fires the following events.
The <code>instance</code> argument always refers to the editor
itself.</p>
<dl>
<dt id="event_change"><code><strong>"change"</strong> (instance: CodeMirror, changeObj: object)</code></dt>
<dd>Fires every time the content of the editor is changed.
The <code>changeObj</code> is a <code>{from, to, text, removed,
origin}</code> object containing information about the changes
that occurred as second argument. <code>from</code>
and <code>to</code> are the positions (in the pre-change
coordinate system) where the change started and ended (for
example, it might be <code>{ch:0, line:18}</code> if the
position is at the beginning of line #19). <code>text</code> is
an array of strings representing the text that replaced the
changed range (split by line). <code>removed</code> is the text
that used to be between <code>from</code> and <code>to</code>,
which is overwritten by this change. This event is
fired <em>before</em> the end of
an <a href="#operation">operation</a>, before the DOM updates
happen.</dd>
<dt id="event_changes"><code><strong>"changes"</strong> (instance: CodeMirror, changes: array<object>)</code></dt>
<dd>Like the <a href="#event_change"><code>"change"</code></a>
event, but batched per <a href="#operation">operation</a>,
passing an array containing all the changes that happened in the
operation. This event is fired after the operation finished, and
display changes it makes will trigger a new operation.</dd>
<dt id="event_beforeChange"><code><strong>"beforeChange"</strong> (instance: CodeMirror, changeObj: object)</code></dt>
<dd>This event is fired before a change is applied, and its
handler may choose to modify or cancel the change.
The <code>changeObj</code> object
has <code>from</code>, <code>to</code>, and <code>text</code>
properties, as with
the <a href="#event_change"><code>"change"</code></a> event. It
also has a <code>cancel()</code> method, which can be called to
cancel the change, and, <strong>if</strong> the change isn't
coming from an undo or redo event, an <code>update(from, to,
text)</code> method, which may be used to modify the change.
Undo or redo changes can't be modified, because they hold some
metainformation for restoring old marked ranges that is only
valid for that specific change. All three arguments
to <code>update</code> are optional, and can be left off to
leave the existing value for that field
intact. <strong>Note:</strong> you may not do anything from
a <code>"beforeChange"</code> handler that would cause changes
to the document or its visualization. Doing so will, since this
handler is called directly from the bowels of the CodeMirror
implementation, probably cause the editor to become
corrupted.</dd>
<dt id="event_cursorActivity"><code><strong>"cursorActivity"</strong> (instance: CodeMirror)</code></dt>
<dd>Will be fired when the cursor or selection moves, or any
change is made to the editor content.</dd>
<dt id="event_keyHandled"><code><strong>"keyHandled"</strong> (instance: CodeMirror, name: string, event: Event)</code></dt>
<dd>Fired after a key is handled through a
key map. <code>name</code> is the name of the handled key (for
example <code>"Ctrl-X"</code> or <code>"'q'"</code>),
and <code>event</code> is the DOM <code>keydown</code>
or <code>keypress</code> event.</dd>
<dt id="event_inputRead"><code><strong>"inputRead"</strong> (instance: CodeMirror, changeObj: object)</code></dt>
<dd>Fired whenever new input is read from the hidden textarea
(typed or pasted by the user).</dd>
<dt id="event_electricInput"><code><strong>"electricInput"</strong> (instance: CodeMirror, line: integer)</code></dt>
<dd>Fired if text input matched the
mode's <a href="#option_electricChars">electric</a> patterns,
and this caused the line's indentation to change.</dd>
<dt id="event_beforeSelectionChange"><code><strong>"beforeSelectionChange"</strong> (instance: CodeMirror, obj: {ranges, origin, update})</code></dt>
<dd>This event is fired before the selection is moved. Its
handler may inspect the set of selection ranges, present as an
array of <code>{anchor, head}</code> objects in
the <code>ranges</code> property of the <code>obj</code>
argument, and optionally change them by calling
the <code>update</code> method on this object, passing an array
of ranges in the same format. The object also contains
an <code>origin</code> property holding the origin string passed
to the selection-changing method, if any. Handlers for this
event have the same restriction
as <a href="#event_beforeChange"><code>"beforeChange"</code></a>
handlers — they should not do anything to directly update the
state of the editor.</dd>
<dt id="event_viewportChange"><code><strong>"viewportChange"</strong> (instance: CodeMirror, from: number, to: number)</code></dt>
<dd>Fires whenever the <a href="#getViewport">view port</a> of
the editor changes (due to scrolling, editing, or any other
factor). The <code>from</code> and <code>to</code> arguments
give the new start and end of the viewport.</dd>
<dt id="event_swapDoc"><code><strong>"swapDoc"</strong> (instance: CodeMirror, oldDoc: Doc)</code></dt>
<dd>This is signalled when the editor's document is replaced
using the <a href="#swapDoc"><code>swapDoc</code></a>
method.</dd>
<dt id="event_gutterClick"><code><strong>"gutterClick"</strong> (instance: CodeMirror, line: integer, gutter: string, clickEvent: Event)</code></dt>
<dd>Fires when the editor gutter (the line-number area) is
clicked. Will pass the editor instance as first argument, the
(zero-based) number of the line that was clicked as second
argument, the CSS class of the gutter that was clicked as third
argument, and the raw <code>mousedown</code> event object as
fourth argument.</dd>
<dt id="event_gutterContextMenu"><code><strong>"gutterContextMenu"</strong> (instance: CodeMirror, line: integer, gutter: string, contextMenu: Event: Event)</code></dt>
<dd>Fires when the editor gutter (the line-number area)
receives a <code>contextmenu</code> event. Will pass the editor
instance as first argument, the (zero-based) number of the line
that was clicked as second argument, the CSS class of the
gutter that was clicked as third argument, and the raw
<code>contextmenu</code> mouse event object as fourth argument.
You can <code>preventDefault</code> the event, to signal that
CodeMirror should do no further handling.</dd>
<dt id="event_focus"><code><strong>"focus"</strong> (instance: CodeMirror, event: Event)</code></dt>
<dd>Fires whenever the editor is focused.</dd>
<dt id="event_blur"><code><strong>"blur"</strong> (instance: CodeMirror, event: Event)</code></dt>
<dd>Fires whenever the editor is unfocused.</dd>
<dt id="event_scroll"><code><strong>"scroll"</strong> (instance: CodeMirror)</code></dt>
<dd>Fires when the editor is scrolled.</dd>
<dt id="event_refresh"><code><strong>"refresh"</strong> (instance: CodeMirror)</code></dt>
<dd>Fires when the editor is <a href="#refresh">refreshed</a>
or <a href="#setSize">resized</a>. Mostly useful to invalidate
cached values that depend on the editor or character size.</dd>
<dt id="event_optionChange"><code><strong>"optionChange"</strong> (instance: CodeMirror, option: string)</code></dt>
<dd>Dispatched every time an option is changed with <a href="#setOption"><code>setOption</code></a>.</dd>
<dt id="event_scrollCursorIntoView"><code><strong>"scrollCursorIntoView"</strong> (instance: CodeMirror, event: Event)</code></dt>
<dd>Fires when the editor tries to scroll its cursor into view.
Can be hooked into to take care of additional scrollable
containers around the editor. When the event object has
its <code>preventDefault</code> method called, CodeMirror will
not itself try to scroll the window.</dd>
<dt id="event_update"><code><strong>"update"</strong> (instance: CodeMirror)</code></dt>
<dd>Will be fired whenever CodeMirror updates its DOM display.</dd>
<dt id="event_renderLine"><code><strong>"renderLine"</strong> (instance: CodeMirror, line: LineHandle, element: Element)</code></dt>
<dd>Fired whenever a line is (re-)rendered to the DOM. Fired
right after the DOM element is built, <em>before</em> it is
added to the document. The handler may mess with the style of
the resulting element, or add event handlers, but
should <em>not</em> try to change the state of the editor.</dd>
<dt id="event_dom"><code><strong>"mousedown"</strong>,
<strong>"dblclick"</strong>, <strong>"touchstart"</strong>, <strong>"contextmenu"</strong>,
<strong>"keydown"</strong>, <strong>"keypress"</strong>,
<strong>"keyup"</strong>, <strong>"cut"</strong>, <strong>"copy"</strong>, <strong>"paste"</strong>,
<strong>"dragstart"</strong>, <strong>"dragenter"</strong>,
<strong>"dragover"</strong>, <strong>"dragleave"</strong>,
<strong>"drop"</strong>
(instance: CodeMirror, event: Event)</code></dt>
<dd>Fired when CodeMirror is handling a DOM event of this type.
You can <code>preventDefault</code> the event, or give it a
truthy <code>codemirrorIgnore</code> property, to signal that
CodeMirror should do no further handling.</dd>
</dl>
<p>Document objects (instances
of <a href="#Doc"><code>CodeMirror.Doc</code></a>) emit the
following events:</p>
<dl>
<dt id="event_doc_change"><code><strong>"change"</strong> (doc: CodeMirror.Doc, changeObj: object)</code></dt>
<dd>Fired whenever a change occurs to the
document. <code>changeObj</code> has a similar type as the
object passed to the
editor's <a href="#event_change"><code>"change"</code></a>
event.</dd>
<dt id="event_doc_beforeChange"><code><strong>"beforeChange"</strong> (doc: CodeMirror.Doc, change: object)</code></dt>
<dd>See the <a href="#event_beforeChange">description of the
same event</a> on editor instances.</dd>
<dt id="event_doc_cursorActivity"><code><strong>"cursorActivity"</strong> (doc: CodeMirror.Doc)</code></dt>
<dd>Fired whenever the cursor or selection in this document
changes.</dd>
<dt id="event_doc_beforeSelectionChange"><code><strong>"beforeSelectionChange"</strong> (doc: CodeMirror.Doc, selection: {head, anchor})</code></dt>
<dd>Equivalent to
the <a href="#event_beforeSelectionChange">event by the same
name</a> as fired on editor instances.</dd>
</dl>
<p>Line handles (as returned by, for
example, <a href="#getLineHandle"><code>getLineHandle</code></a>)
support these events:</p>
<dl>
<dt id="event_delete"><code><strong>"delete"</strong> ()</code></dt>
<dd>Will be fired when the line object is deleted. A line object
is associated with the <em>start</em> of the line. Mostly useful
when you need to find out when your <a href="#setGutterMarker">gutter
markers</a> on a given line are removed.</dd>
<dt id="event_line_change"><code><strong>"change"</strong> (line: LineHandle, changeObj: object)</code></dt>
<dd>Fires when the line's text content is changed in any way
(but the line is not deleted outright). The <code>change</code>
object is similar to the one passed
to <a href="#event_change">change event</a> on the editor
object.</dd>
</dl>
<p>Marked range handles (<code>CodeMirror.TextMarker</code>), as returned
by <a href="#markText"><code>markText</code></a>
and <a href="#setBookmark"><code>setBookmark</code></a>, emit the
following events:</p>
<dl>
<dt id="event_beforeCursorEnter"><code><strong>"beforeCursorEnter"</strong> ()</code></dt>
<dd>Fired when the cursor enters the marked range. From this
event handler, the editor state may be inspected
but <em>not</em> modified, with the exception that the range on
which the event fires may be cleared.</dd>
<dt id="event_clear"><code><strong>"clear"</strong> (from: {line, ch}, to: {line, ch})</code></dt>
<dd>Fired when the range is cleared, either through cursor
movement in combination
with <a href="#mark_clearOnEnter"><code>clearOnEnter</code></a>
or through a call to its <code>clear()</code> method. Will only
be fired once per handle. Note that deleting the range through
text editing does not fire this event, because an undo action
might bring the range back into existence. <code>from</code>
and <code>to</code> give the part of the document that the range
spanned when it was cleared.</dd>
<dt id="event_hide"><code><strong>"hide"</strong> ()</code></dt>
<dd>Fired when the last part of the marker is removed from the
document by editing operations.</dd>
<dt id="event_unhide"><code><strong>"unhide"</strong> ()</code></dt>
<dd>Fired when, after the marker was removed by editing, a undo
operation brought the marker back.</dd>
</dl>
<p>Line widgets (<code>CodeMirror.LineWidget</code>), returned
by <a href="#addLineWidget"><code>addLineWidget</code></a>, fire
these events:</p>
<dl>
<dt id="event_redraw"><code><strong>"redraw"</strong> ()</code></dt>
<dd>Fired whenever the editor re-adds the widget to the DOM.
This will happen once right after the widget is added (if it is
scrolled into view), and then again whenever it is scrolled out
of view and back in again, or when changes to the editor options
or the line the widget is on require the widget to be
redrawn.</dd>
</dl>
</section>
<section id=keymaps>
<h2>Key Maps</h2>
<p>Key maps are ways to associate keys and mouse buttons with
functionality. A key map is an object mapping strings that
identify the buttons to functions that implement their
functionality.</p>
<p>The CodeMirror distributions comes
with <a href="../demo/emacs.html">Emacs</a>, <a href="../demo/vim.html">Vim</a>,
and <a href="../demo/sublime.html">Sublime Text</a>-style keymaps.</p>
<p>Keys are identified either by name or by character.
The <code>CodeMirror.keyNames</code> object defines names for
common keys and associates them with their key codes. Examples of
names defined here are <code>Enter</code>, <code>F5</code>,
and <code>Q</code>. These can be prefixed
with <code>Shift-</code>, <code>Cmd-</code>, <code>Ctrl-</code>,
and <code>Alt-</code> to specify a modifier. So for
example, <code>Shift-Ctrl-Space</code> would be a valid key
identifier.</p>
<p>Common example: map the Tab key to insert spaces instead of a tab
character.</p>
<pre data-lang="javascript">
editor.setOption("extraKeys", {
Tab: function(cm) {
var spaces = Array(cm.getOption("indentUnit") + 1).join(" ");
cm.replaceSelection(spaces);
}
});</pre>
<p>Alternatively, a character can be specified directly by
surrounding it in single quotes, for example <code>'$'</code>
or <code>'q'</code>. Due to limitations in the way browsers fire
key events, these may not be prefixed with modifiers.</p>
<p>To bind mouse buttons, use the names `LeftClick`,
`MiddleClick`, and `RightClick`. These can also be prefixed with
modifiers, and in addition, the word `Double` or `Triple` can be
put before `Click` (as in `LeftDoubleClick`) to bind a double- or
triple-click. The function for such a binding is passed the
position that was clicked as second argument.</p>
<p id="normalizeKeyMap">Multi-stroke key bindings can be specified
by separating the key names by spaces in the property name, for
example <code>Ctrl-X Ctrl-V</code>. When a map contains
multi-stoke bindings or keys with modifiers that are not specified
in the default order (<code>Shift-Cmd-Ctrl-Alt</code>), you must
call <code>CodeMirror.normalizeKeyMap</code> on it before it can
be used. This function takes a keymap and modifies it to normalize
modifier order and properly recognize multi-stroke bindings. It
will return the keymap itself.</p>
<p>The <code>CodeMirror.keyMap</code> object associates key maps
with names. User code and key map definitions can assign extra
properties to this object. Anywhere where a key map is expected, a
string can be given, which will be looked up in this object. It
also contains the <code>"default"</code> key map holding the
default bindings.</p>
<p>The values of properties in key maps can be either functions of
a single argument (the CodeMirror instance), strings, or
<code>false</code>. Strings refer
to <a href="#commands">commands</a>, which are described below. If
the property is set to <code>false</code>, CodeMirror leaves
handling of the key up to the browser. A key handler function may
return <code>CodeMirror.Pass</code> to indicate that it has
decided not to handle the key, and other handlers (or the default
behavior) should be given a turn.</p>
<p>Keys mapped to command names that start with the
characters <code>"go"</code> or to functions that have a
truthy <code>motion</code> property (which should be used for
cursor-movement actions) will be fired even when an
extra <code>Shift</code> modifier is present (i.e. <code>"Up":
"goLineUp"</code> matches both up and shift-up). This is used to
easily implement shift-selection.</p>
<p>Key maps can defer to each other by defining
a <code>fallthrough</code> property. This indicates that when a
key is not found in the map itself, one or more other maps should
be searched. It can hold either a single key map or an array of
key maps.</p>
<p>When a key map needs to set something up when it becomes
active, or tear something down when deactivated, it can
contain <code>attach</code> and/or <code>detach</code> properties,
which should hold functions that take the editor instance and the
next or previous keymap. Note that this only works for the
<a href="#option_keyMap">top-level keymap</a>, not for fallthrough
maps or maps added
with <a href="#option_extraKeys"><code>extraKeys</code></a>
or <a href="#addKeyMap"><code>addKeyMap</code></a>.</p>
</section>
<section id=commands>
<h2>Commands</h2>
<p>Commands are parameter-less actions that can be performed on an
editor. Their main use is for key bindings. Commands are defined by
adding properties to the <code>CodeMirror.commands</code> object.
A number of common commands are defined by the library itself,
most of them used by the default key bindings. The value of a
command property must be a function of one argument (an editor
instance).</p>
<p>Some of the commands below are referenced in the default
key map, but not defined by the core library. These are intended to
be defined by user code or addons.</p>
<p>Commands can also be run with
the <a href="#execCommand"><code>execCommand</code></a>
method.</p>
<dl>
<dt class=command id=command_selectAll><code><strong>selectAll</strong></code><span class=keybinding>Ctrl-A (PC), Cmd-A (Mac)</span></dt>
<dd>Select the whole content of the editor.</dd>
<dt class=command id=command_singleSelection><code><strong>singleSelection</strong></code><span class=keybinding>Esc</span></dt>
<dd>When multiple selections are present, this deselects all but
the primary selection.</dd>
<dt class=command id=command_killLine><code><strong>killLine</strong></code><span class=keybinding>Ctrl-K (Mac)</span></dt>
<dd>Emacs-style line killing. Deletes the part of the line after
the cursor. If that consists only of whitespace, the newline at
the end of the line is also deleted.</dd>
<dt class=command id=command_deleteLine><code><strong>deleteLine</strong></code><span class=keybinding>Ctrl-D (PC), Cmd-D (Mac)</span></dt>
<dd>Deletes the whole line under the cursor, including newline at the end.</dd>
<dt class=command id=command_delLineLeft><code><strong>delLineLeft</strong></code></dt>
<dd>Delete the part of the line before the cursor.</dd>
<dt class=command id=command_delWrappedLineLeft><code><strong>delWrappedLineLeft</strong></code><span class=keybinding>Cmd-Backspace (Mac)</span></dt>
<dd>Delete the part of the line from the left side of the visual line the cursor is on to the cursor.</dd>
<dt class=command id=command_delWrappedLineRight><code><strong>delWrappedLineRight</strong></code><span class=keybinding>Cmd-Delete (Mac)</span></dt>
<dd>Delete the part of the line from the cursor to the right side of the visual line the cursor is on.</dd>
<dt class=command id=command_undo><code><strong>undo</strong></code><span class=keybinding>Ctrl-Z (PC), Cmd-Z (Mac)</span></dt>
<dd>Undo the last change. Note that, because browsers still
don't make it possible for scripts to react to or customize the
context menu, selecting undo (or redo) from the context menu in
a CodeMirror instance does not work.</dd>
<dt class=command id=command_redo><code><strong>redo</strong></code><span class=keybinding>Ctrl-Y (PC), Shift-Cmd-Z (Mac), Cmd-Y (Mac)</span></dt>
<dd>Redo the last undone change.</dd>
<dt class=command id=command_undoSelection><code><strong>undoSelection</strong></code><span class=keybinding>Ctrl-U (PC), Cmd-U (Mac)</span></dt>
<dd>Undo the last change to the selection, or if there are no
selection-only changes at the top of the history, undo the last
change.</dd>
<dt class=command id=command_redoSelection><code><strong>redoSelection</strong></code><span class=keybinding>Alt-U (PC), Shift-Cmd-U (Mac)</span></dt>
<dd>Redo the last change to the selection, or the last text change if
no selection changes remain.</dd>
<dt class=command id=command_goDocStart><code><strong>goDocStart</strong></code><span class=keybinding>Ctrl-Home (PC), Cmd-Up (Mac), Cmd-Home (Mac)</span></dt>
<dd>Move the cursor to the start of the document.</dd>
<dt class=command id=command_goDocEnd><code><strong>goDocEnd</strong></code><span class=keybinding>Ctrl-End (PC), Cmd-End (Mac), Cmd-Down (Mac)</span></dt>
<dd>Move the cursor to the end of the document.</dd>
<dt class=command id=command_goLineStart><code><strong>goLineStart</strong></code><span class=keybinding>Alt-Left (PC), Ctrl-A (Mac)</span></dt>
<dd>Move the cursor to the start of the line.</dd>
<dt class=command id=command_goLineStartSmart><code><strong>goLineStartSmart</strong></code><span class=keybinding>Home</span></dt>
<dd>Move to the start of the text on the line, or if we are
already there, to the actual start of the line (including
whitespace).</dd>
<dt class=command id=command_goLineEnd><code><strong>goLineEnd</strong></code><span class=keybinding>Alt-Right (PC), Ctrl-E (Mac)</span></dt>
<dd>Move the cursor to the end of the line.</dd>
<dt class=command id=command_goLineRight><code><strong>goLineRight</strong></code><span class=keybinding>Cmd-Right (Mac)</span></dt>
<dd>Move the cursor to the right side of the visual line it is on.</dd>
<dt class=command id=command_goLineLeft><code><strong>goLineLeft</strong></code><span class=keybinding>Cmd-Left (Mac)</span></dt>
<dd>Move the cursor to the left side of the visual line it is on. If
this line is wrapped, that may not be the start of the line.</dd>
<dt class=command id=command_goLineLeftSmart><code><strong>goLineLeftSmart</strong></code></dt>
<dd>Move the cursor to the left side of the visual line it is
on. If that takes it to the start of the line, behave
like <a href="#command_goLineStartSmart"><code>goLineStartSmart</code></a>.</dd>
<dt class=command id=command_goLineUp><code><strong>goLineUp</strong></code><span class=keybinding>Up, Ctrl-P (Mac)</span></dt>
<dd>Move the cursor up one line.</dd>
<dt class=command id=command_goLineDown><code><strong>goLineDown</strong></code><span class=keybinding>Down, Ctrl-N (Mac)</span></dt>
<dd>Move down one line.</dd>
<dt class=command id=command_goPageUp><code><strong>goPageUp</strong></code><span class=keybinding>PageUp, Shift-Ctrl-V (Mac)</span></dt>
<dd>Move the cursor up one screen, and scroll up by the same distance.</dd>
<dt class=command id=command_goPageDown><code><strong>goPageDown</strong></code><span class=keybinding>PageDown, Ctrl-V (Mac)</span></dt>
<dd>Move the cursor down one screen, and scroll down by the same distance.</dd>
<dt class=command id=command_goCharLeft><code><strong>goCharLeft</strong></code><span class=keybinding>Left, Ctrl-B (Mac)</span></dt>
<dd>Move the cursor one character left, going to the previous line
when hitting the start of line.</dd>
<dt class=command id=command_goCharRight><code><strong>goCharRight</strong></code><span class=keybinding>Right, Ctrl-F (Mac)</span></dt>
<dd>Move the cursor one character right, going to the next line
when hitting the end of line.</dd>
<dt class=command id=command_goColumnLeft><code><strong>goColumnLeft</strong></code></dt>
<dd>Move the cursor one character left, but don't cross line boundaries.</dd>
<dt class=command id=command_goColumnRight><code><strong>goColumnRight</strong></code></dt>
<dd>Move the cursor one character right, don't cross line boundaries.</dd>
<dt class=command id=command_goWordLeft><code><strong>goWordLeft</strong></code><span class=keybinding>Alt-B (Mac)</span></dt>
<dd>Move the cursor to the start of the previous word.</dd>
<dt class=command id=command_goWordRight><code><strong>goWordRight</strong></code><span class=keybinding>Alt-F (Mac)</span></dt>
<dd>Move the cursor to the end of the next word.</dd>
<dt class=command id=command_goGroupLeft><code><strong>goGroupLeft</strong></code><span class=keybinding>Ctrl-Left (PC), Alt-Left (Mac)</span></dt>
<dd>Move to the left of the group before the cursor. A group is
a stretch of word characters, a stretch of punctuation
characters, a newline, or a stretch of <em>more than one</em>
whitespace character.</dd>
<dt class=command id=command_goGroupRight><code><strong>goGroupRight</strong></code><span class=keybinding>Ctrl-Right (PC), Alt-Right (Mac)</span></dt>
<dd>Move to the right of the group after the cursor
(see <a href="#command_goGroupLeft">above</a>).</dd>
<dt class=command id=command_delCharBefore><code><strong>delCharBefore</strong></code><span class=keybinding>Shift-Backspace, Ctrl-H (Mac)</span></dt>
<dd>Delete the character before the cursor.</dd>
<dt class=command id=command_delCharAfter><code><strong>delCharAfter</strong></code><span class=keybinding>Delete, Ctrl-D (Mac)</span></dt>
<dd>Delete the character after the cursor.</dd>
<dt class=command id=command_delWordBefore><code><strong>delWordBefore</strong></code><span class=keybinding>Alt-Backspace (Mac)</span></dt>
<dd>Delete up to the start of the word before the cursor.</dd>
<dt class=command id=command_delWordAfter><code><strong>delWordAfter</strong></code><span class=keybinding>Alt-D (Mac)</span></dt>
<dd>Delete up to the end of the word after the cursor.</dd>
<dt class=command id=command_delGroupBefore><code><strong>delGroupBefore</strong></code><span class=keybinding>Ctrl-Backspace (PC), Alt-Backspace (Mac)</span></dt>
<dd>Delete to the left of the <a href="#command_goGroupLeft">group</a> before the cursor.</dd>
<dt class=command id=command_delGroupAfter><code><strong>delGroupAfter</strong></code><span class=keybinding>Ctrl-Delete (PC), Ctrl-Alt-Backspace (Mac), Alt-Delete (Mac)</span></dt>
<dd>Delete to the start of the <a href="#command_goGroupLeft">group</a> after the cursor.</dd>
<dt class=command id=command_indentAuto><code><strong>indentAuto</strong></code><span class=keybinding>Shift-Tab</span></dt>
<dd>Auto-indent the current line or selection.</dd>
<dt class=command id=command_indentMore><code><strong>indentMore</strong></code><span class=keybinding>Ctrl-] (PC), Cmd-] (Mac)</span></dt>
<dd>Indent the current line or selection by one <a href="#option_indentUnit">indent unit</a>.</dd>
<dt class=command id=command_indentLess><code><strong>indentLess</strong></code><span class=keybinding>Ctrl-[ (PC), Cmd-[ (Mac)</span></dt>
<dd>Dedent the current line or selection by one <a href="#option_indentUnit">indent unit</a>.</dd>
<dt class=command id=command_insertTab><code><strong>insertTab</strong></code></dt>
<dd>Insert a tab character at the cursor.</dd>
<dt class=command id=command_insertSoftTab><code><strong>insertSoftTab</strong></code></dt>
<dd>Insert the amount of spaces that match the width a tab at
the cursor position would have.</dd>
<dt class=command id=command_defaultTab><code><strong>defaultTab</strong></code><span class=keybinding>Tab</span></dt>
<dd>If something is selected, indent it by
one <a href="#option_indentUnit">indent unit</a>. If nothing is
selected, insert a tab character.</dd>
<dt class=command id=command_transposeChars><code><strong>transposeChars</strong></code><span class=keybinding>Ctrl-T (Mac)</span></dt>
<dd>Swap the characters before and after the cursor.</dd>
<dt class=command id=command_newlineAndIndent><code><strong>newlineAndIndent</strong></code><span class=keybinding>Enter</span></dt>
<dd>Insert a newline and auto-indent the new line.</dd>
<dt class=command id=command_toggleOverwrite><code><strong>toggleOverwrite</strong></code><span class=keybinding>Insert</span></dt>
<dd>Flip the <a href="#toggleOverwrite">overwrite</a> flag.</dd>
<dt class=command id=command_save><code><strong>save</strong></code><span class=keybinding>Ctrl-S (PC), Cmd-S (Mac)</span></dt>
<dd>Not defined by the core library, only referred to in
key maps. Intended to provide an easy way for user code to define
a save command.</dd>
<dt class=command id=command_find><code><strong>find</strong></code><span class=keybinding>Ctrl-F (PC), Cmd-F (Mac)</span></dt>
<dt class=command id=command_findNext><code><strong>findNext</strong></code><span class=keybinding>Ctrl-G (PC), Cmd-G (Mac)</span></dt>
<dt class=command id=command_findPrev><code><strong>findPrev</strong></code><span class=keybinding>Shift-Ctrl-G (PC), Shift-Cmd-G (Mac)</span></dt>
<dt class=command id=command_replace><code><strong>replace</strong></code><span class=keybinding>Shift-Ctrl-F (PC), Cmd-Alt-F (Mac)</span></dt>
<dt class=command id=command_replaceAll><code><strong>replaceAll</strong></code><span class=keybinding>Shift-Ctrl-R (PC), Shift-Cmd-Alt-F (Mac)</span></dt>
<dd>Not defined by the core library, but defined in
the <a href="#addon_search">search addon</a> (or custom client
addons).</dd>
</dl>
</section>
<section id=styling>
<h2>Customized Styling</h2>
<p>Up to a certain extent, CodeMirror's look can be changed by
modifying style sheet files. The style sheets supplied by modes
simply provide the colors for that mode, and can be adapted in a
very straightforward way. To style the editor itself, it is
possible to alter or override the styles defined
in <a href="../lib/codemirror.css"><code>codemirror.css</code></a>.</p>
<p>Some care must be taken there, since a lot of the rules in this
file are necessary to have CodeMirror function properly. Adjusting
colors should be safe, of course, and with some care a lot of
other things can be changed as well. The CSS classes defined in
this file serve the following roles:</p>
<dl>
<dt id="class_CodeMirror"><code><strong>CodeMirror</strong></code></dt>
<dd>The outer element of the editor. This should be used for the
editor width, height, borders and positioning. Can also be used
to set styles that should hold for everything inside the editor
(such as font and font size), or to set a background. Setting
this class' <code>height</code> style to <code>auto</code> will
make the editor <a href="../demo/resize.html">resize to fit its
content</a> (it is recommended to also set
the <a href="#option_viewportMargin"><code>viewportMargin</code>
option</a> to <code>Infinity</code> when doing this.</dd>
<dt id="class_CodeMirror_focused"><code><strong>CodeMirror-focused</strong></code></dt>
<dd>Whenever the editor is focused, the top element gets this
class. This is used to hide the cursor and give the selection a
different color when the editor is not focused.</dd>
<dt id="class_CodeMirror_gutters"><code><strong>CodeMirror-gutters</strong></code></dt>
<dd>This is the backdrop for all gutters. Use it to set the
default gutter background color, and optionally add a border on
the right of the gutters.</dd>
<dt id="class_CodeMirror_linenumbers"><code><strong>CodeMirror-linenumbers</strong></code></dt>
<dd>Use this for giving a background or width to the line number
gutter.</dd>
<dt id="class_CodeMirror_linenumber"><code><strong>CodeMirror-linenumber</strong></code></dt>
<dd>Used to style the actual individual line numbers. These
won't be children of the <code>CodeMirror-linenumbers</code>
(plural) element, but rather will be absolutely positioned to
overlay it. Use this to set alignment and text properties for
the line numbers.</dd>
<dt id="class_CodeMirror_lines"><code><strong>CodeMirror-lines</strong></code></dt>
<dd>The visible lines. This is where you specify vertical
padding for the editor content.</dd>
<dt id="class_CodeMirror_cursor"><code><strong>CodeMirror-cursor</strong></code></dt>
<dd>The cursor is a block element that is absolutely positioned.
You can make it look whichever way you want.</dd>
<dt id="class_CodeMirror_selected"><code><strong>CodeMirror-selected</strong></code></dt>
<dd>The selection is represented by <code>span</code> elements
with this class.</dd>
<dt id="class_CodeMirror_matchingbracket"><code><strong>CodeMirror-matchingbracket</strong></code>,
<code><strong>CodeMirror-nonmatchingbracket</strong></code></dt>
<dd>These are used to style matched (or unmatched) brackets.</dd>
</dl>
<p>If your page's style sheets do funky things to
all <code>div</code> or <code>pre</code> elements (you probably
shouldn't do that), you'll have to define rules to cancel these
effects out again for elements under the <code>CodeMirror</code>
class.</p>
<p>Themes are also simply CSS files, which define colors for
various syntactic elements. See the files in
the <a href="../theme/"><code>theme</code></a> directory.</p>
</section>
<section id=api>
<h2>Programming API</h2>
<p>A lot of CodeMirror features are only available through its
API. Thus, you need to write code (or
use <a href="#addons">addons</a>) if you want to expose them to
your users.</p>
<p>Whenever points in the document are represented, the API uses
objects with <code>line</code> and <code>ch</code> properties.
Both are zero-based. CodeMirror makes sure to 'clip' any positions
passed by client code so that they fit inside the document, so you
shouldn't worry too much about sanitizing your coordinates. If you
give <code>ch</code> a value of <code>null</code>, or don't
specify it, it will be replaced with the length of the specified
line. Such positions may also have a <code>sticky</code> property
holding <code>"before"</code> or <code>"after"</code>, whether the
position is associated with the character before or after it. This
influences, for example, where the cursor is drawn on a
line-break or bidi-direction boundary.</p>
<p>Methods prefixed with <code>doc.</code> can, unless otherwise
specified, be called both on <code>CodeMirror</code> (editor)
instances and <code>CodeMirror.Doc</code> instances. Methods
prefixed with <code>cm.</code> are <em>only</em> available
on <code>CodeMirror</code> instances.</p>
<h3 id="api_constructor">Constructor</h3>
<p id="CodeMirror">Constructing an editor instance is done with
the <code><strong>CodeMirror</strong>(place: Element|fn(Element),
?option: object)</code> constructor. If the <code>place</code>
argument is a DOM element, the editor will be appended to it. If
it is a function, it will be called, and is expected to place the
editor into the document. <code>options</code> may be an element
mapping <a href="#config">option names</a> to values. The options
that it doesn't explicitly specify (or all options, if it is not
passed) will be taken
from <a href="#defaults"><code>CodeMirror.defaults</code></a>.</p>
<p>Note that the options object passed to the constructor will be
mutated when the instance's options
are <a href="#setOption">changed</a>, so you shouldn't share such
objects between instances.</p>
<p>See <a href="#fromTextArea"><code>CodeMirror.fromTextArea</code></a>
for another way to construct an editor instance.</p>
<h3 id="api_content">Content manipulation methods</h3>
<dl>
<dt id="getValue"><code><strong>doc.getValue</strong>(?separator: string) → string</code></dt>
<dd>Get the current editor content. You can pass it an optional
argument to specify the string to be used to separate lines
(defaults to <code>"\n"</code>).</dd>
<dt id="setValue"><code><strong>doc.setValue</strong>(content: string)</code></dt>
<dd>Set the editor content.</dd>
<dt id="getRange"><code><strong>doc.getRange</strong>(from: {line, ch}, to: {line, ch}, ?separator: string) → string</code></dt>
<dd>Get the text between the given points in the editor, which
should be <code>{line, ch}</code> objects. An optional third
argument can be given to indicate the line separator string to
use (defaults to <code>"\n"</code>).</dd>
<dt id="replaceRange"><code><strong>doc.replaceRange</strong>(replacement: string, from: {line, ch}, to: {line, ch}, ?origin: string)</code></dt>
<dd>Replace the part of the document between <code>from</code>
and <code>to</code> with the given string. <code>from</code>
and <code>to</code> must be <code>{line, ch}</code>
objects. <code>to</code> can be left off to simply insert the
string at position <code>from</code>. When <code>origin</code>
is given, it will be passed on
to <a href="#event_change"><code>"change"</code> events</a>, and
its first letter will be used to determine whether this change
can be merged with previous history events, in the way described
for <a href="#selection_origin">selection origins</a>.</dd>
<dt id="getLine"><code><strong>doc.getLine</strong>(n: integer) → string</code></dt>
<dd>Get the content of line <code>n</code>.</dd>
<dt id="lineCount"><code><strong>doc.lineCount</strong>() → integer</code></dt>
<dd>Get the number of lines in the editor.</dd>
<dt id="firstLine"><code><strong>doc.firstLine</strong>() → integer</code></dt>
<dd>Get the number of first line in the editor. This will
usually be zero but for <a href="#linkedDoc_from">linked sub-views</a>,
or <a href="#api_doc">documents</a> instantiated with a non-zero
first line, it might return other values.</dd>
<dt id="lastLine"><code><strong>doc.lastLine</strong>() → integer</code></dt>
<dd>Get the number of last line in the editor. This will
usually be <code>doc.lineCount() - 1</code>,
but for <a href="#linkedDoc_from">linked sub-views</a>,
it might return other values.</dd>
<dt id="getLineHandle"><code><strong>doc.getLineHandle</strong>(num: integer) → LineHandle</code></dt>
<dd>Fetches the line handle for the given line number.</dd>
<dt id="getLineNumber"><code><strong>doc.getLineNumber</strong>(handle: LineHandle) → integer</code></dt>
<dd>Given a line handle, returns the current position of that
line (or <code>null</code> when it is no longer in the
document).</dd>
<dt id="eachLine"><code><strong>doc.eachLine</strong>(f: (line: LineHandle))</code></dt>
<dt><code><strong>doc.eachLine</strong>(start: integer, end: integer, f: (line: LineHandle))</code></dt>
<dd>Iterate over the whole document, or if <code>start</code>
and <code>end</code> line numbers are given, the range
from <code>start</code> up to (not including) <code>end</code>,
and call <code>f</code> for each line, passing the line handle.
This is a faster way to visit a range of line handlers than
calling <a href="#getLineHandle"><code>getLineHandle</code></a>
for each of them. Note that line handles have
a <code>text</code> property containing the line's content (as a
string).</dd>
<dt id="markClean"><code><strong>doc.markClean</strong>()</code></dt>
<dd>Set the editor content as 'clean', a flag that it will
retain until it is edited, and which will be set again when such
an edit is undone again. Useful to track whether the content
needs to be saved. This function is deprecated in favor
of <a href="#changeGeneration"><code>changeGeneration</code></a>,
which allows multiple subsystems to track different notions of
cleanness without interfering.</dd>
<dt id="changeGeneration"><code><strong>doc.changeGeneration</strong>(?closeEvent: boolean) → integer</code></dt>
<dd>Returns a number that can later be passed
to <a href="#isClean"><code>isClean</code></a> to test whether
any edits were made (and not undone) in the meantime.
If <code>closeEvent</code> is true, the current history event
will be ‘closed’, meaning it can't be combined with further
changes (rapid typing or deleting events are typically
combined).</dd>
<dt id="isClean"><code><strong>doc.isClean</strong>(?generation: integer) → boolean</code></dt>
<dd>Returns whether the document is currently clean — not
modified since initialization or the last call
to <a href="#markClean"><code>markClean</code></a> if no
argument is passed, or since the matching call
to <a href="#changeGeneration"><code>changeGeneration</code></a>
if a generation value is given.</dd>
</dl>
<h3 id="api_selection">Cursor and selection methods</h3>
<dl>
<dt id="getSelection"><code><strong>doc.getSelection</strong>(?lineSep: string) → string</code></dt>
<dd>Get the currently selected code. Optionally pass a line
separator to put between the lines in the output. When multiple
selections are present, they are concatenated with instances
of <code>lineSep</code> in between.</dd>
<dt id="getSelections"><code><strong>doc.getSelections</strong>(?lineSep: string) → array<string></code></dt>
<dd>Returns an array containing a string for each selection,
representing the content of the selections.</dd>
<dt id="replaceSelection"><code><strong>doc.replaceSelection</strong>(replacement: string, ?select: string)</code></dt>
<dd>Replace the selection(s) with the given string. By default,
the new selection ends up after the inserted text. The
optional <code>select</code> argument can be used to change
this—passing <code>"around"</code> will cause the new text to be
selected, passing <code>"start"</code> will collapse the
selection to the start of the inserted text.</dd>
<dt id="replaceSelections"><code><strong>doc.replaceSelections</strong>(replacements: array<string>, ?select: string)</code></dt>
<dd>The length of the given array should be the same as the
number of active selections. Replaces the content of the
selections with the strings in the array.
The <code>select</code> argument works the same as
in <a href="#replaceSelection"><code>replaceSelection</code></a>.</dd>
<dt id="getCursor"><code><strong>doc.getCursor</strong>(?start: string) → {line, ch}</code></dt>
<dd>Retrieve one end of the <em>primary</em>
selection. <code>start</code> is an optional string indicating
which end of the selection to return. It may
be <code>"from"</code>, <code>"to"</code>, <code>"head"</code>
(the side of the selection that moves when you press
shift+arrow), or <code>"anchor"</code> (the fixed side of the
selection). Omitting the argument is the same as
passing <code>"head"</code>. A <code>{line, ch}</code> object
will be returned.</dd>
<dt id="listSelections"><code><strong>doc.listSelections</strong>() → array<{anchor, head}></code></dt>
<dd>Retrieves a list of all current selections. These will
always be sorted, and never overlap (overlapping selections are
merged). Each object in the array contains <code>anchor</code>
and <code>head</code> properties referring to <code>{line,
ch}</code> objects.</dd>
<dt id="somethingSelected"><code><strong>doc.somethingSelected</strong>() → boolean</code></dt>
<dd>Return true if any text is selected.</dd>
<dt id="setCursor"><code><strong>doc.setCursor</strong>(pos: {line, ch}|number, ?ch: number, ?options: object)</code></dt>
<dd>Set the cursor position. You can either pass a
single <code>{line, ch}</code> object, or the line and the
character as two separate parameters. Will replace all
selections with a single, empty selection at the given position.
The supported options are the same as for <a href="#setSelection"><code>setSelection</code></a>.</dd>
<dt id="setSelection"><code><strong>doc.setSelection</strong>(anchor: {line, ch}, ?head: {line, ch}, ?options: object)</code></dt>
<dd>Set a single selection range. <code>anchor</code>
and <code>head</code> should be <code>{line, ch}</code>
objects. <code>head</code> defaults to <code>anchor</code> when
not given. These options are supported:
<dl>
<dt id="selection_scroll"><code><strong>scroll</strong>: boolean</code></dt>
<dd>Determines whether the selection head should be scrolled
into view. Defaults to true.</dd>
<dt id="selection_origin"><code><strong>origin</strong>: string</code></dt>
<dd>Determines whether the selection history event may be
merged with the previous one. When an origin starts with the
character <code>+</code>, and the last recorded selection had
the same origin and was similar (close
in <a href="#option_historyEventDelay">time</a>, both
collapsed or both non-collapsed), the new one will replace the
old one. When it starts with <code>*</code>, it will always
replace the previous event (if that had the same origin).
Built-in motion uses the <code>"+move"</code> origin. User input uses the <code>"+input"</code> origin.</dd>
<dt id="selection_bias"><code><strong>bias</strong>: number</code></dt>
<dd>Determine the direction into which the selection endpoints
should be adjusted when they fall inside
an <a href="#mark_atomic">atomic</a> range. Can be either -1
(backward) or 1 (forward). When not given, the bias will be
based on the relative position of the old selection—the editor
will try to move further away from that, to prevent getting
stuck.</dd>
</dl></dd>
<dt id="setSelections"><code><strong>doc.setSelections</strong>(ranges: array<{anchor, head}>, ?primary: integer, ?options: object)</code></dt>
<dd>Sets a new set of selections. There must be at least one
selection in the given array. When <code>primary</code> is a
number, it determines which selection is the primary one. When
it is not given, the primary index is taken from the previous
selection, or set to the last range if the previous selection
had less ranges than the new one. Supports the same options
as <a href="#setSelection"><code>setSelection</code></a>.</dd>
<dt id="addSelection"><code><strong>doc.addSelection</strong>(anchor: {line, ch}, ?head: {line, ch})</code></dt>
<dd>Adds a new selection to the existing set of selections, and
makes it the primary selection.</dd>
<dt id="extendSelection"><code><strong>doc.extendSelection</strong>(from: {line, ch}, ?to: {line, ch}, ?options: object)</code></dt>
<dd>Similar
to <a href="#setSelection"><code>setSelection</code></a>, but
will, if shift is held or
the <a href="#setExtending">extending</a> flag is set, move the
head of the selection while leaving the anchor at its current
place. <code>to</code> is optional, and can be passed to ensure
a region (for example a word or paragraph) will end up selected
(in addition to whatever lies between that region and the
current anchor). When multiple selections are present, all but
the primary selection will be dropped by this method.
Supports the same options as <a href="#setSelection"><code>setSelection</code></a>.</dd>
<dt id="extendSelections"><code><strong>doc.extendSelections</strong>(heads: array<{line, ch}>, ?options: object)</code></dt>
<dd>An equivalent
of <a href="#extendSelection"><code>extendSelection</code></a>
that acts on all selections at once.</dd>
<dt id="extendSelectionsBy"><code><strong>doc.extendSelectionsBy</strong>(f: function(range: {anchor, head}) → {line, ch}), ?options: object)</code></dt>
<dd>Applies the given function to all existing selections, and
calls <a href="#extendSelections"><code>extendSelections</code></a>
on the result.</dd>
<dt id="setExtending"><code><strong>doc.setExtending</strong>(value: boolean)</code></dt>
<dd>Sets or clears the 'extending' flag, which acts similar to
the shift key, in that it will cause cursor movement and calls
to <a href="#extendSelection"><code>extendSelection</code></a>
to leave the selection anchor in place.</dd>
<dt id="getExtending"><code><strong>doc.getExtending</strong>() → boolean</code></dt>
<dd>Get the value of the 'extending' flag.</dd>
<dt id="hasFocus"><code><strong>cm.hasFocus</strong>() → boolean</code></dt>
<dd>Tells you whether the editor currently has focus.</dd>
<dt id="findPosH"><code><strong>cm.findPosH</strong>(start: {line, ch}, amount: integer, unit: string, visually: boolean) → {line, ch, ?hitSide: boolean}</code></dt>
<dd>Used to find the target position for horizontal cursor
motion. <code>start</code> is a <code>{line, ch}</code>
object, <code>amount</code> an integer (may be negative),
and <code>unit</code> one of the
string <code>"char"</code>, <code>"column"</code>,
or <code>"word"</code>. Will return a position that is produced
by moving <code>amount</code> times the distance specified
by <code>unit</code>. When <code>visually</code> is true, motion
in right-to-left text will be visual rather than logical. When
the motion was clipped by hitting the end or start of the
document, the returned value will have a <code>hitSide</code>
property set to true.</dd>
<dt id="findPosV"><code><strong>cm.findPosV</strong>(start: {line, ch}, amount: integer, unit: string) → {line, ch, ?hitSide: boolean}</code></dt>
<dd>Similar to <a href="#findPosH"><code>findPosH</code></a>,
but used for vertical motion. <code>unit</code> may
be <code>"line"</code> or <code>"page"</code>. The other
arguments and the returned value have the same interpretation as
they have in <code>findPosH</code>.</dd>
<dt id="findWordAt"><code><strong>cm.findWordAt</strong>(pos: {line, ch}) → {anchor: {line, ch}, head: {line, ch}}</code></dt>
<dd>Returns the start and end of the 'word' (the stretch of
letters, whitespace, or punctuation) at the given position.</dd>
</dl>
<h3 id="api_configuration">Configuration methods</h3>
<dl>
<dt id="setOption"><code><strong>cm.setOption</strong>(option: string, value: any)</code></dt>
<dd>Change the configuration of the editor. <code>option</code>
should the name of an <a href="#config">option</a>,
and <code>value</code> should be a valid value for that
option.</dd>
<dt id="getOption"><code><strong>cm.getOption</strong>(option: string) → any</code></dt>
<dd>Retrieves the current value of the given option for this
editor instance.</dd>
<dt id="addKeyMap"><code><strong>cm.addKeyMap</strong>(map: object, bottom: boolean)</code></dt>
<dd>Attach an additional <a href="#keymaps">key map</a> to the
editor. This is mostly useful for addons that need to register
some key handlers without trampling on
the <a href="#option_extraKeys"><code>extraKeys</code></a>
option. Maps added in this way have a higher precedence than
the <code>extraKeys</code>
and <a href="#option_keyMap"><code>keyMap</code></a> options,
and between them, the maps added earlier have a lower precedence
than those added later, unless the <code>bottom</code> argument
was passed, in which case they end up below other key maps added
with this method.</dd>
<dt id="removeKeyMap"><code><strong>cm.removeKeyMap</strong>(map: object)</code></dt>
<dd>Disable a keymap added
with <a href="#addKeyMap"><code>addKeyMap</code></a>. Either
pass in the key map object itself, or a string, which will be
compared against the <code>name</code> property of the active
key maps.</dd>
<dt id="addOverlay"><code><strong>cm.addOverlay</strong>(mode: string|object, ?options: object)</code></dt>
<dd>Enable a highlighting overlay. This is a stateless mini-mode
that can be used to add extra highlighting. For example,
the <a href="../demo/search.html">search addon</a> uses it to
highlight the term that's currently being
searched. <code>mode</code> can be a <a href="#option_mode">mode
spec</a> or a mode object (an object with
a <a href="#token"><code>token</code></a> method).
The <code>options</code> parameter is optional. If given, it
should be an object, optionally containing the following options:
<dl>
<dt><code><strong>opaque</strong>: bool</code></dt>
<dd>Defaults to off, but can be given to allow the overlay
styling, when not <code>null</code>, to override the styling of
the base mode entirely, instead of the two being applied
together.</dd>
<dt><code><strong>priority</strong>: number</code></dt>
<dd>Determines the ordering in which the overlays are
applied. Those with high priority are applied after those
with lower priority, and able to override the opaqueness of
the ones that come before. Defaults to 0.</dd>
</dl>
</dd>
<dt id="removeOverlay"><code><strong>cm.removeOverlay</strong>(mode: string|object)</code></dt>
<dd>Pass this the exact value passed for the <code>mode</code>
parameter to <a href="#addOverlay"><code>addOverlay</code></a>,
or a string that corresponds to the <code>name</code> property of
that value, to remove an overlay again.</dd>
<dt id="on"><code><strong>cm.on</strong>(type: string, func: (...args))</code></dt>
<dd>Register an event handler for the given event type (a
string) on the editor instance. There is also
a <code>CodeMirror.on(object, type, func)</code> version
that allows registering of events on any object.</dd>
<dt id="off"><code><strong>cm.off</strong>(type: string, func: (...args))</code></dt>
<dd>Remove an event handler on the editor instance. An
equivalent <code>CodeMirror.off(object, type,
func)</code> also exists.</dd>
</dl>
<h3 id="api_doc">Document management methods</h3>
<p id="Doc">Each editor is associated with an instance
of <code>CodeMirror.Doc</code>, its document. A document
represents the editor content, plus a selection, an undo history,
and a <a href="#option_mode">mode</a>. A document can only be
associated with a single editor at a time. You can create new
documents by calling the <code>CodeMirror.Doc(text: string, mode:
Object, firstLineNumber: ?number, lineSeparator: ?string)</code>
constructor. The last three arguments are optional and can be used
to set a mode for the document, make it start at a line number
other than 0, and set a specific line separator respectively.</p>
<dl>
<dt id="getDoc"><code><strong>cm.getDoc</strong>() → Doc</code></dt>
<dd>Retrieve the currently active document from an editor.</dd>
<dt id="getEditor"><code><strong>doc.getEditor</strong>() → CodeMirror</code></dt>
<dd>Retrieve the editor associated with a document. May
return <code>null</code>.</dd>
<dt id="swapDoc"><code><strong>cm.swapDoc</strong>(doc: CodeMirror.Doc) → Doc</code></dt>
<dd>Attach a new document to the editor. Returns the old
document, which is now no longer associated with an editor.</dd>
<dt id="copy"><code><strong>doc.copy</strong>(copyHistory: boolean) → Doc</code></dt>
<dd>Create an identical copy of the given doc.
When <code>copyHistory</code> is true, the history will also be
copied. Can not be called directly on an editor.</dd>
<dt id="linkedDoc"><code><strong>doc.linkedDoc</strong>(options: object) → Doc</code></dt>
<dd>Create a new document that's linked to the target document.
Linked documents will stay in sync (changes to one are also
applied to the other) until <a href="#unlinkDoc">unlinked</a>.
These are the options that are supported:
<dl>
<dt id="linkedDoc_sharedHist"><code><strong>sharedHist</strong>: boolean</code></dt>
<dd>When turned on, the linked copy will share an undo
history with the original. Thus, something done in one of
the two can be undone in the other, and vice versa.</dd>
<dt id="linkedDoc_from"><code><strong>from</strong>: integer</code></dt>
<dt id="linkedDoc_to"><code><strong>to</strong>: integer</code></dt>
<dd>Can be given to make the new document a subview of the
original. Subviews only show a given range of lines. Note
that line coordinates inside the subview will be consistent
with those of the parent, so that for example a subview
starting at line 10 will refer to its first line as line 10,
not 0.</dd>
<dt id="linkedDoc_mode"><code><strong>mode</strong>: string|object</code></dt>
<dd>By default, the new document inherits the mode of the
parent. This option can be set to
a <a href="#option_mode">mode spec</a> to give it a
different mode.</dd>
</dl></dd>
<dt id="unlinkDoc"><code><strong>doc.unlinkDoc</strong>(doc: CodeMirror.Doc)</code></dt>
<dd>Break the link between two documents. After calling this,
changes will no longer propagate between the documents, and, if
they had a shared history, the history will become
separate.</dd>
<dt id="iterLinkedDocs"><code><strong>doc.iterLinkedDocs</strong>(function: (doc: CodeMirror.Doc, sharedHist: boolean))</code></dt>
<dd>Will call the given function for all documents linked to the
target document. It will be passed two arguments, the linked document
and a boolean indicating whether that document shares history
with the target.</dd>
</dl>
<h3 id="api_history">History-related methods</h3>
<dl>
<dt id="undo"><code><strong>doc.undo</strong>()</code></dt>
<dd>Undo one edit (if any undo events are stored).</dd>
<dt id="redo"><code><strong>doc.redo</strong>()</code></dt>
<dd>Redo one undone edit.</dd>
<dt id="undoSelection"><code><strong>doc.undoSelection</strong>()</code></dt>
<dd>Undo one edit or selection change.</dd>
<dt id="redoSelection"><code><strong>doc.redoSelection</strong>()</code></dt>
<dd>Redo one undone edit or selection change.</dd>
<dt id="historySize"><code><strong>doc.historySize</strong>() → {undo: integer, redo: integer}</code></dt>
<dd>Returns an object with <code>{undo, redo}</code> properties,
both of which hold integers, indicating the amount of stored
undo and redo operations.</dd>
<dt id="clearHistory"><code><strong>doc.clearHistory</strong>()</code></dt>
<dd>Clears the editor's undo history.</dd>
<dt id="getHistory"><code><strong>doc.getHistory</strong>() → object</code></dt>
<dd>Get a (JSON-serializable) representation of the undo history.</dd>
<dt id="setHistory"><code><strong>doc.setHistory</strong>(history: object)</code></dt>
<dd>Replace the editor's undo history with the one provided,
which must be a value as returned
by <a href="#getHistory"><code>getHistory</code></a>. Note that
this will have entirely undefined results if the editor content
isn't also the same as it was when <code>getHistory</code> was
called.</dd>
</dl>
<h3 id="api_marker">Text-marking methods</h3>
<dl>
<dt id="markText"><code><strong>doc.markText</strong>(from: {line, ch}, to: {line, ch}, ?options: object) → TextMarker</code></dt>
<dd>Can be used to mark a range of text with a specific CSS
class name. <code>from</code> and <code>to</code> should
be <code>{line, ch}</code> objects. The <code>options</code>
parameter is optional. When given, it should be an object that
may contain the following configuration options:
<dl>
<dt id="mark_className"><code><strong>className</strong>: string</code></dt>
<dd>Assigns a CSS class to the marked stretch of text.</dd>
<dt id="mark_inclusiveLeft"><code><strong>inclusiveLeft</strong>: boolean</code></dt>
<dd>Determines whether
text inserted on the left of the marker will end up inside
or outside of it.</dd>
<dt id="mark_inclusiveRight"><code><strong>inclusiveRight</strong>: boolean</code></dt>
<dd>Like <code>inclusiveLeft</code>,
but for the right side.</dd>
<dt id="mark_selectLeft"><code><strong>selectLeft</strong>: boolean</code></dt>
<dd>For atomic ranges, determines whether the cursor is allowed
to be placed directly to the left of the range. Has no effect on
non-atomic ranges.</dd>
<dt id="mark_selectRight"><code><strong>selectRight</strong>: boolean</code></dt>
<dd>Like <code>selectLeft</code>,
but for the right side.</dd>
<dt id="mark_atomic"><code><strong>atomic</strong>: boolean</code></dt>
<dd>Atomic ranges act as a single unit when cursor movement is
concerned—i.e. it is impossible to place the cursor inside of
them. You can control whether the cursor is allowed to be placed
directly before or after them using <code>selectLeft</code>
or <code>selectRight</code>. If <code>selectLeft</code>
(or right) is not provided, then <code>inclusiveLeft</code> (or
right) will control this behavior.</dd>
<dt id="mark_collapsed"><code><strong>collapsed</strong>: boolean</code></dt>
<dd>Collapsed ranges do not show up in the display. Setting a
range to be collapsed will automatically make it atomic.</dd>
<dt id="mark_clearOnEnter"><code><strong>clearOnEnter</strong>: boolean</code></dt>
<dd>When enabled, will cause the mark to clear itself whenever
the cursor enters its range. This is mostly useful for
text-replacement widgets that need to 'snap open' when the
user tries to edit them. The
<a href="#event_clear"><code>"clear"</code></a> event
fired on the range handle can be used to be notified when this
happens.</dd>
<dt id="mark_clearWhenEmpty"><code><strong>clearWhenEmpty</strong>: boolean</code></dt>
<dd>Determines whether the mark is automatically cleared when
it becomes empty. Default is true.</dd>
<dt id="mark_replacedWith"><code><strong>replacedWith</strong>: Element</code></dt>
<dd>Use a given node to display this range. Implies both
collapsed and atomic. The given DOM node <em>must</em> be an
inline element (as opposed to a block element).</dd>
<dt><code><strong>handleMouseEvents</strong>: boolean</code></dt>
<dd>When <code>replacedWith</code> is given, this determines
whether the editor will capture mouse and drag events
occurring in this widget. Default is false—the events will be
left alone for the default browser handler, or specific
handlers on the widget, to capture.</dd>
<dt id="mark_readOnly"><code><strong>readOnly</strong>: boolean</code></dt>
<dd>A read-only span can, as long as it is not cleared, not be
modified except by
calling <a href="#setValue"><code>setValue</code></a> to reset
the whole document. <em>Note:</em> adding a read-only span
currently clears the undo history of the editor, because
existing undo events being partially nullified by read-only
spans would corrupt the history (in the current
implementation).</dd>
<dt id="mark_addToHistory"><code><strong>addToHistory</strong>: boolean</code></dt>
<dd>When set to true (default is false), adding this marker
will create an event in the undo history that can be
individually undone (clearing the marker).</dd>
<dt id="mark_startStyle"><code><strong>startStyle</strong>: string</code></dt><dd>Can be used to specify
an extra CSS class to be applied to the leftmost span that
is part of the marker.</dd>
<dt id="mark_endStyle"><code><strong>endStyle</strong>: string</code></dt><dd>Equivalent
to <code>startStyle</code>, but for the rightmost span.</dd>
<dt id="mark_css"><code><strong>css</strong>: string</code></dt>
<dd>A string of CSS to be applied to the covered text. For example <code>"color: #fe3"</code>.</dd>
<dt id="mark_attributes"><code><strong>attributes</strong>: object</code></dt>
<dd>When given, add the attributes in the given object to the
elements created for the marked text. Adding <code>class</code> or
<code>style</code> attributes this way is not supported.</dd>
<dt id="mark_shared"><code><strong>shared</strong>: boolean</code></dt><dd>When the
target document is <a href="#linkedDoc">linked</a> to other
documents, you can set <code>shared</code> to true to make the
marker appear in all documents. By default, a marker appears
only in its target document.</dd>
</dl>
The method will return an object that represents the marker
(with constructor <code>CodeMirror.TextMarker</code>), which
exposes three methods:
<code><strong>clear</strong>()</code>, to remove the mark,
<code><strong>find</strong>()</code>, which returns
a <code>{from, to}</code> object (both holding document
positions), indicating the current position of the marked range,
or <code>undefined</code> if the marker is no longer in the
document, and finally <code><strong>changed</strong>()</code>,
which you can call if you've done something that might change
the size of the marker (for example changing the content of
a <a href="#mark_replacedWith"><code>replacedWith</code></a>
node), and want to cheaply update the display.</dd>
<dt id="setBookmark"><code><strong>doc.setBookmark</strong>(pos: {line, ch}, ?options: object) → TextMarker</code></dt>
<dd>Inserts a bookmark, a handle that follows the text around it
as it is being edited, at the given position. A bookmark has two
methods <code>find()</code> and <code>clear()</code>. The first
returns the current position of the bookmark, if it is still in
the document, and the second explicitly removes the bookmark.
The options argument is optional. If given, the following
properties are recognized:
<dl>
<dt><code><strong>widget</strong>: Element</code></dt><dd>Can be used to display a DOM
node at the current location of the bookmark (analogous to
the <a href="#mark_replacedWith"><code>replacedWith</code></a>
option to <a href="#markText"><code>markText</code></a>).</dd>
<dt><code><strong>insertLeft</strong>: boolean</code></dt><dd>By default, text typed
when the cursor is on top of the bookmark will end up to the
right of the bookmark. Set this option to true to make it go
to the left instead.</dd>
<dt><code><strong>shared</strong>: boolean</code></dt><dd>See
the corresponding <a href="#mark_shared">option</a>
to <code>markText</code>.</dd>
<dt><code><strong>handleMouseEvents</strong>: boolean</code></dt>
<dd>As with <a href="#markText"><code>markText</code></a>,
this determines whether mouse events on the widget inserted
for this bookmark are handled by CodeMirror. The default is
false.</dd>
</dl></dd>
<dt id="findMarks"><code><strong>doc.findMarks</strong>(from: {line, ch}, to: {line, ch}) → array<TextMarker></code></dt>
<dd>Returns an array of all the bookmarks and marked ranges
found between the given positions (non-inclusive).</dd>
<dt id="findMarksAt"><code><strong>doc.findMarksAt</strong>(pos: {line, ch}) → array<TextMarker></code></dt>
<dd>Returns an array of all the bookmarks and marked ranges
present at the given position.</dd>
<dt id="getAllMarks"><code><strong>doc.getAllMarks</strong>() → array<TextMarker></code></dt>
<dd>Returns an array containing all marked ranges in the document.</dd>
</dl>
<h3 id="api_decoration">Widget, gutter, and decoration methods</h3>
<dl>
<dt id="setGutterMarker"><code><strong>doc.setGutterMarker</strong>(line: integer|LineHandle, gutterID: string, value: Element) → LineHandle</code></dt>
<dd>Sets the gutter marker for the given gutter (identified by
its CSS class, see
the <a href="#option_gutters"><code>gutters</code></a> option)
to the given value. Value can be either <code>null</code>, to
clear the marker, or a DOM element, to set it. The DOM element
will be shown in the specified gutter next to the specified
line.</dd>
<dt id="clearGutter"><code><strong>doc.clearGutter</strong>(gutterID: string)</code></dt>
<dd>Remove all gutter markers in
the <a href="#option_gutters">gutter</a> with the given ID.</dd>
<dt id="addLineClass"><code><strong>doc.addLineClass</strong>(line: integer|LineHandle, where: string, class: string) → LineHandle</code></dt>
<dd>Set a CSS class name for the given line. <code>line</code>
can be a number or a line handle. <code>where</code> determines
to which element this class should be applied, can can be one
of <code>"text"</code> (the text element, which lies in front of
the selection), <code>"background"</code> (a background element
that will be behind the selection), <code>"gutter"</code> (the
line's gutter space), or <code>"wrap"</code> (the wrapper node
that wraps all of the line's elements, including gutter
elements). <code>class</code> should be the name of the class to
apply.</dd>
<dt id="removeLineClass"><code><strong>doc.removeLineClass</strong>(line: integer|LineHandle, where: string, class: string) → LineHandle</code></dt>
<dd>Remove a CSS class from a line. <code>line</code> can be a
line handle or number. <code>where</code> should be one
of <code>"text"</code>, <code>"background"</code>,
or <code>"wrap"</code>
(see <a href="#addLineClass"><code>addLineClass</code></a>). <code>class</code>
can be left off to remove all classes for the specified node, or
be a string to remove only a specific class.</dd>
<dt id="lineInfo"><code><strong>doc.lineInfo</strong>(line: integer|LineHandle) → object</code></dt>
<dd>Returns the line number, text content, and marker status of
the given line, which can be either a number or a line handle.
The returned object has the structure <code>{line, handle, text,
gutterMarkers, textClass, bgClass, wrapClass, widgets}</code>,
where <code>gutterMarkers</code> is an object mapping gutter IDs
to marker elements, and <code>widgets</code> is an array
of <a href="#addLineWidget">line widgets</a> attached to this
line, and the various class properties refer to classes added
with <a href="#addLineClass"><code>addLineClass</code></a>.</dd>
<dt id="addWidget"><code><strong>cm.addWidget</strong>(pos: {line, ch}, node: Element, scrollIntoView: boolean)</code></dt>
<dd>Puts <code>node</code>, which should be an absolutely
positioned DOM node, into the editor, positioned right below the
given <code>{line, ch}</code> position.
When <code>scrollIntoView</code> is true, the editor will ensure
that the entire node is visible (if possible). To remove the
widget again, simply use DOM methods (move it somewhere else, or
call <code>removeChild</code> on its parent).</dd>
<dt id="addLineWidget"><code><strong>doc.addLineWidget</strong>(line: integer|LineHandle, node: Element, ?options: object) → LineWidget</code></dt>
<dd>Adds a line widget, an element shown below a line, spanning
the whole of the editor's width, and moving the lines below it
downwards. <code>line</code> should be either an integer or a
line handle, and <code>node</code> should be a DOM node, which
will be displayed below the given line. <code>options</code>,
when given, should be an object that configures the behavior of
the widget. The following options are supported (all default to
false):
<dl>
<dt><code><strong>coverGutter</strong>: boolean</code></dt>
<dd>Whether the widget should cover the gutter.</dd>
<dt><code><strong>noHScroll</strong>: boolean</code></dt>
<dd>Whether the widget should stay fixed in the face of
horizontal scrolling.</dd>
<dt><code><strong>above</strong>: boolean</code></dt>
<dd>Causes the widget to be placed above instead of below
the text of the line.</dd>
<dt><code><strong>handleMouseEvents</strong>: boolean</code></dt>
<dd>Determines whether the editor will capture mouse and
drag events occurring in this widget. Default is false—the
events will be left alone for the default browser handler,
or specific handlers on the widget, to capture.</dd>
<dt><code><strong>insertAt</strong>: integer</code></dt>
<dd>By default, the widget is added below other widgets for
the line. This option can be used to place it at a different
position (zero for the top, N to put it after the Nth other
widget). Note that this only has effect once, when the
widget is created.
</dl>
Note that the widget node will become a descendant of nodes with
CodeMirror-specific CSS classes, and those classes might in some
cases affect it. This method returns an object that represents
the widget placement. It'll have a <code>line</code> property
pointing at the line handle that it is associated with, and the following methods:
<dl>
<dt id="widget_clear"><code><strong>clear</strong>()</code></dt><dd>Removes the widget.</dd>
<dt id="widget_changed"><code><strong>changed</strong>()</code></dt><dd>Call
this if you made some change to the widget's DOM node that
might affect its height. It'll force CodeMirror to update
the height of the line that contains the widget.</dd>
</dl>
</dd>
</dl>
<h3 id="api_sizing">Sizing, scrolling and positioning methods</h3>
<dl>
<dt id="setSize"><code><strong>cm.setSize</strong>(width: number|string, height: number|string)</code></dt>
<dd>Programmatically set the size of the editor (overriding the
applicable <a href="#css-resize">CSS
rules</a>). <code>width</code> and <code>height</code>
can be either numbers (interpreted as pixels) or CSS units
(<code>"100%"</code>, for example). You can
pass <code>null</code> for either of them to indicate that that
dimension should not be changed.</dd>
<dt id="scrollTo"><code><strong>cm.scrollTo</strong>(x: number, y: number)</code></dt>
<dd>Scroll the editor to a given (pixel) position. Both
arguments may be left as <code>null</code>
or <code>undefined</code> to have no effect.</dd>
<dt id="getScrollInfo"><code><strong>cm.getScrollInfo</strong>() → {left, top, width, height, clientWidth, clientHeight}</code></dt>
<dd>Get an <code>{left, top, width, height, clientWidth,
clientHeight}</code> object that represents the current scroll
position, the size of the scrollable area, and the size of the
visible area (minus scrollbars).</dd>
<dt id="scrollIntoView"><code><strong>cm.scrollIntoView</strong>(what: {line, ch}|{left, top, right, bottom}|{from, to}|null, ?margin: number)</code></dt>
<dd>Scrolls the given position into view. <code>what</code> may
be <code>null</code> to scroll the cursor into view,
a <code>{line, ch}</code> position to scroll a character into
view, a <code>{left, top, right, bottom}</code> pixel range (in
editor-local coordinates), or a range <code>{from, to}</code>
containing either two character positions or two pixel squares.
The <code>margin</code> parameter is optional. When given, it
indicates the amount of vertical pixels around the given area
that should be made visible as well.</dd>
<dt id="cursorCoords"><code><strong>cm.cursorCoords</strong>(where: boolean|{line, ch}, mode: string) → {left, top, bottom}</code></dt>
<dd>Returns an <code>{left, top, bottom}</code> object
containing the coordinates of the cursor position.
If <code>mode</code> is <code>"local"</code>, they will be
relative to the top-left corner of the editable document. If it
is <code>"page"</code> or not given, they are relative to the
top-left corner of the page. If <code>mode</code>
is <code>"window"</code>, the coordinates are relative to the
top-left corner of the currently visible (scrolled)
window. <code>where</code> can be a boolean indicating whether
you want the start (<code>true</code>) or the end
(<code>false</code>) of the selection, or, if a <code>{line,
ch}</code> object is given, it specifies the precise position at
which you want to measure.</dd>
<dt id="charCoords"><code><strong>cm.charCoords</strong>(pos: {line, ch}, ?mode: string) → {left, right, top, bottom}</code></dt>
<dd>Returns the position and dimensions of an arbitrary
character. <code>pos</code> should be a <code>{line, ch}</code>
object. This differs from <code>cursorCoords</code> in that
it'll give the size of the whole character, rather than just the
position that the cursor would have when it would sit at that
position.</dd>
<dt id="coordsChar"><code><strong>cm.coordsChar</strong>(object: {left, top}, ?mode: string) → {line, ch}</code></dt>
<dd>Given an <code>{left, top}</code> object (e.g. coordinates of a mouse event) returns
the <code>{line, ch}</code> position that corresponds to it. The
optional <code>mode</code> parameter determines relative to what
the coordinates are interpreted. It may
be <code>"window"</code>, <code>"page"</code> (the default),
or <code>"local"</code>.</dd>
<dt id="lineAtHeight"><code><strong>cm.lineAtHeight</strong>(height: number, ?mode: string) → number</code></dt>
<dd>Computes the line at the given pixel
height. <code>mode</code> can be one of the same strings
that <a href="#coordsChar"><code>coordsChar</code></a>
accepts.</dd>
<dt id="heightAtLine"><code><strong>cm.heightAtLine</strong>(line: integer|LineHandle, ?mode: string, ?includeWidgets: bool) → number</code></dt>
<dd>Computes the height of the top of a line, in the coordinate
system specified by <code>mode</code>
(see <a href="#coordsChar"><code>coordsChar</code></a>), which
defaults to <code>"page"</code>. When a line below the bottom of
the document is specified, the returned value is the bottom of
the last line in the document. By default, the position of the
actual text is returned. If `includeWidgets` is true and the
line has line widgets, the position above the first line widget
is returned.</dd>
<dt id="defaultTextHeight"><code><strong>cm.defaultTextHeight</strong>() → number</code></dt>
<dd>Returns the line height of the default font for the editor.</dd>
<dt id="defaultCharWidth"><code><strong>cm.defaultCharWidth</strong>() → number</code></dt>
<dd>Returns the pixel width of an 'x' in the default font for
the editor. (Note that for non-monospace fonts, this is mostly
useless, and even for monospace fonts, non-ascii characters
might have a different width).</dd>
<dt id="getViewport"><code><strong>cm.getViewport</strong>() → {from: number, to: number}</code></dt>
<dd>Returns a <code>{from, to}</code> object indicating the
start (inclusive) and end (exclusive) of the currently rendered
part of the document. In big documents, when most content is
scrolled out of view, CodeMirror will only render the visible
part, and a margin around it. See also
the <a href="#event_viewportChange"><code>viewportChange</code></a>
event.</dd>
<dt id="refresh"><code><strong>cm.refresh</strong>()</code></dt>
<dd>If your code does something to change the size of the editor
element (window resizes are already listened for), or unhides
it, you should probably follow up by calling this method to
ensure CodeMirror is still looking as intended. See also
the <a href="#addon_autorefresh">autorefresh addon</a>.</dd>
</dl>
<h3 id="api_mode">Mode, state, and token-related methods</h3>
<p>When writing language-aware functionality, it can often be
useful to hook into the knowledge that the CodeMirror language
mode has. See <a href="#modeapi">the section on modes</a> for a
more detailed description of how these work.</p>
<dl>
<dt id="getMode"><code><strong>doc.getMode</strong>() → object</code></dt>
<dd>Gets the (outer) mode object for the editor. Note that this
is distinct from <code>getOption("mode")</code>, which gives you
the mode specification, rather than the resolved, instantiated
<a href="#defineMode">mode object</a>.</dd>
<dt id="getModeAt"><code><strong>cm.getModeAt</strong>(pos: {line, ch}) → object</code></dt>
<dd>Gets the inner mode at a given position. This will return
the same as <a href="#getMode"><code>getMode</code></a> for
simple modes, but will return an inner mode for nesting modes
(such as <code>htmlmixed</code>).</dd>
<dt id="getTokenAt"><code><strong>cm.getTokenAt</strong>(pos: {line, ch}, ?precise: boolean) → object</code></dt>
<dd>Retrieves information about the token the current mode found
before the given position (a <code>{line, ch}</code> object). The
returned object has the following properties:
<dl>
<dt><code><strong>start</strong></code></dt><dd>The character (on the given line) at which the token starts.</dd>
<dt><code><strong>end</strong></code></dt><dd>The character at which the token ends.</dd>
<dt><code><strong>string</strong></code></dt><dd>The token's string.</dd>
<dt><code><strong>type</strong></code></dt><dd>The token type the mode assigned
to the token, such as <code>"keyword"</code>
or <code>"comment"</code> (may also be null).</dd>
<dt><code><strong>state</strong></code></dt><dd>The mode's state at the end of this token.</dd>
</dl>
If <code>precise</code> is true, the token will be guaranteed to be accurate based on recent edits. If false or
not specified, the token will use cached state information, which will be faster but might not be accurate if
edits were recently made and highlighting has not yet completed.
</dd>
<dt id="getLineTokens"><code><strong>cm.getLineTokens</strong>(line: integer, ?precise: boolean) → array<{start, end, string, type, state}></code></dt>
<dd>This is similar
to <a href="#getTokenAt"><code>getTokenAt</code></a>, but
collects all tokens for a given line into an array. It is much
cheaper than repeatedly calling <code>getTokenAt</code>, which
re-parses the part of the line before the token for every call.</dd>
<dt id="getTokenTypeAt"><code><strong>cm.getTokenTypeAt</strong>(pos: {line, ch}) → string</code></dt>
<dd>This is a (much) cheaper version
of <a href="#getTokenAt"><code>getTokenAt</code></a> useful for
when you just need the type of the token at a given position,
and no other information. Will return <code>null</code> for
unstyled tokens, and a string, potentially containing multiple
space-separated style names, otherwise.</dd>
<dt id="getHelpers"><code><strong>cm.getHelpers</strong>(pos: {line, ch}, type: string) → array<helper></code></dt>
<dd>Fetch the set of applicable helper values for the given
position. Helpers provide a way to look up functionality
appropriate for a mode. The <code>type</code> argument provides
the helper namespace (see
<a href="#registerHelper"><code>registerHelper</code></a>), in
which the values will be looked up. When the mode itself has a
property that corresponds to the <code>type</code>, that
directly determines the keys that are used to look up the helper
values (it may be either a single string, or an array of
strings). Failing that, the mode's <code>helperType</code>
property and finally the mode's name are used.</dd>
<dd>For example, the JavaScript mode has a
property <code>fold</code> containing <code>"brace"</code>. When
the <code>brace-fold</code> addon is loaded, that defines a
helper named <code>brace</code> in the <code>fold</code>
namespace. This is then used by
the <a href="#addon_foldcode"><code>foldcode</code></a> addon to
figure out that it can use that folding function to fold
JavaScript code.</dd>
<dd>When any <a href="#registerGlobalHelper">'global'</a>
helpers are defined for the given namespace, their predicates
are called on the current mode and editor, and all those that
declare they are applicable will also be added to the array that
is returned.</dd>
<dt id="getHelper"><code><strong>cm.getHelper</strong>(pos: {line, ch}, type: string) → helper</code></dt>
<dd>Returns the first applicable helper value.
See <a href="#getHelpers"><code>getHelpers</code></a>.</dd>
<dt id="getStateAfter"><code><strong>cm.getStateAfter</strong>(?line: integer, ?precise: boolean) → object</code></dt>
<dd>Returns the mode's parser state, if any, at the end of the
given line number. If no line number is given, the state at the
end of the document is returned. This can be useful for storing
parsing errors in the state, or getting other kinds of
contextual information for a line. <code>precise</code> is defined
as in <code>getTokenAt()</code>.</dd>
</dl>
<h3 id="api_misc">Miscellaneous methods</h3>
<dl>
<dt id="operation"><code><strong>cm.operation</strong>(func: () → any) → any</code></dt>
<dd>CodeMirror internally buffers changes and only updates its
DOM structure after it has finished performing some operation.
If you need to perform a lot of operations on a CodeMirror
instance, you can call this method with a function argument. It
will call the function, buffering up all changes, and only doing
the expensive update after the function returns. This can be a
lot faster. The return value from this method will be the return
value of your function.</dd>
<dt id="startOperation"><code><strong>cm.startOperation</strong>()</code></dt>
<dt id="endOperation"><code><strong>cm.endOperation</strong>()</code></dt>
<dd>In normal circumstances, use the above <code>operation</code>
method. But if you want to buffer operations happening asynchronously,
or that can't all be wrapped in a callback function, you can
call <code>startOperation</code> to tell CodeMirror to start
buffering changes, and <code>endOperation</code> to actually
render all the updates. <em>Be careful:</em> if you use this
API and forget to call <code>endOperation</code>, the editor will
just never update.</dd>
<dt id="indentLine"><code><strong>cm.indentLine</strong>(line: integer, ?dir: string|integer)</code></dt>
<dd>Adjust the indentation of the given line. The second
argument (which defaults to <code>"smart"</code>) may be one of:
<dl>
<dt><code><strong>"prev"</strong></code></dt>
<dd>Base indentation on the indentation of the previous line.</dd>
<dt><code><strong>"smart"</strong></code></dt>
<dd>Use the mode's smart indentation if available, behave
like <code>"prev"</code> otherwise.</dd>
<dt><code><strong>"add"</strong></code></dt>
<dd>Increase the indentation of the line by
one <a href="#option_indentUnit">indent unit</a>.</dd>
<dt><code><strong>"subtract"</strong></code></dt>
<dd>Reduce the indentation of the line.</dd>
<dt><code><strong><integer></strong></code></dt>
<dd>Add (positive number) or reduce (negative number) the
indentation by the given amount of spaces.</dd>
</dl></dd>
<dt id="toggleOverwrite"><code><strong>cm.toggleOverwrite</strong>(?value: boolean)</code></dt>
<dd>Switches between overwrite and normal insert mode (when not
given an argument), or sets the overwrite mode to a specific
state (when given an argument).</dd>
<dt id="isReadOnly"><code><strong>cm.isReadOnly</strong>() → boolean</code></dt>
<dd>Tells you whether the editor's content can be edited by the
user.</dd>
<dt id="lineSeparator"><code><strong>doc.lineSeparator</strong>()</code></dt>
<dd>Returns the preferred line separator string for this
document, as per the <a href="#option_lineSeparator">option</a>
by the same name. When that option is <code>null</code>, the
string <code>"\n"</code> is returned.</dd>
<dt id="execCommand"><code><strong>cm.execCommand</strong>(name: string)</code></dt>
<dd>Runs the <a href="#commands">command</a> with the given name on the editor.</dd>
<dt id="posFromIndex"><code><strong>doc.posFromIndex</strong>(index: integer) → {line, ch}</code></dt>
<dd>Calculates and returns a <code>{line, ch}</code> object for a
zero-based <code>index</code> who's value is relative to the start of the
editor's text. If the <code>index</code> is out of range of the text then
the returned object is clipped to start or end of the text
respectively.</dd>
<dt id="indexFromPos"><code><strong>doc.indexFromPos</strong>(object: {line, ch}) → integer</code></dt>
<dd>The reverse of <a href="#posFromIndex"><code>posFromIndex</code></a>.</dd>
<dt id="focus"><code><strong>cm.focus</strong>()</code></dt>
<dd>Give the editor focus.</dd>
<dt id="phrase"><code><strong>cm.phrase</strong>(text: string) → string</code></dt>
<dd>Allow the given string to be translated with
the <a href="#option_phrases"><code>phrases</code>
option</a>.</dd>
<dt id="getInputField"><code><strong>cm.getInputField</strong>() → Element</code></dt>
<dd>Returns the input field for the editor. Will be a textarea
or an editable div, depending on the value of
the <a href="#option_inputStyle"><code>inputStyle</code></a>
option.</dd>
<dt id="getWrapperElement"><code><strong>cm.getWrapperElement</strong>() → Element</code></dt>
<dd>Returns the DOM node that represents the editor, and
controls its size. Remove this from your tree to delete an
editor instance.</dd>
<dt id="getScrollerElement"><code><strong>cm.getScrollerElement</strong>() → Element</code></dt>
<dd>Returns the DOM node that is responsible for the scrolling
of the editor.</dd>
<dt id="getGutterElement"><code><strong>cm.getGutterElement</strong>() → Element</code></dt>
<dd>Fetches the DOM node that contains the editor gutters.</dd>
</dl>
<h3 id="api_static">Static properties</h3>
<p>The <code>CodeMirror</code> object itself provides
several useful properties.</p>
<dl>
<dt id="version"><code><strong>CodeMirror.version</strong>: string</code></dt>
<dd>It contains a string that indicates the version of the
library. This is a triple of
integers <code>"major.minor.patch"</code>,
where <code>patch</code> is zero for releases, and something
else (usually one) for dev snapshots.</dd>
<dt id="fromTextArea"><code><strong>CodeMirror.fromTextArea</strong>(textArea: TextAreaElement, ?config: object)</code></dt>
<dd>This method provides another way to initialize an editor. It
takes a textarea DOM node as first argument and an optional
configuration object as second. It will replace the textarea
with a CodeMirror instance, and wire up the form of that
textarea (if any) to make sure the editor contents are put into
the textarea when the form is submitted. The text in the
textarea will provide the content for the editor. A CodeMirror
instance created this way has three additional methods:
<dl>
<dt id="save"><code><strong>cm.save</strong>()</code></dt>
<dd>Copy the content of the editor into the textarea.</dd>
<dt id="toTextArea"><code><strong>cm.toTextArea</strong>()</code></dt>
<dd>Remove the editor, and restore the original textarea (with
the editor's current content). If you dynamically create and
destroy editors made with `fromTextArea`, without destroying
the form they are part of, you should make sure to call
`toTextArea` to remove the editor, or its `"submit"` handler
on the form will cause a memory leak.</dd>
<dt id="getTextArea"><code><strong>cm.getTextArea</strong>() → TextAreaElement</code></dt>
<dd>Returns the textarea that the instance was based on.</dd>
</dl>
</dd>
<dt id="defaults"><code><strong>CodeMirror.defaults</strong>: object</code></dt>
<dd>An object containing default values for
all <a href="#config">options</a>. You can assign to its
properties to modify defaults (though this won't affect editors
that have already been created).</dd>
<dt id="defineExtension"><code><strong>CodeMirror.defineExtension</strong>(name: string, value: any)</code></dt>
<dd>If you want to define extra methods in terms of the
CodeMirror API, it is possible to
use <code>defineExtension</code>. This will cause the given
value (usually a method) to be added to all CodeMirror instances
created from then on.</dd>
<dt id="defineDocExtension"><code><strong>CodeMirror.defineDocExtension</strong>(name: string, value: any)</code></dt>
<dd>Like <a href="#defineExtension"><code>defineExtension</code></a>,
but the method will be added to the interface
for <a href="#Doc"><code>Doc</code></a> objects instead.</dd>
<dt id="defineOption"><code><strong>CodeMirror.defineOption</strong>(name: string,
default: any, updateFunc: function)</code></dt>
<dd>Similarly, <code>defineOption</code> can be used to define new options for
CodeMirror. The <code>updateFunc</code> will be called with the
editor instance and the new value when an editor is initialized,
and whenever the option is modified
through <a href="#setOption"><code>setOption</code></a>.</dd>
<dt id="defineInitHook"><code><strong>CodeMirror.defineInitHook</strong>(func: function)</code></dt>
<dd>If your extension just needs to run some
code whenever a CodeMirror instance is initialized,
use <code>CodeMirror.defineInitHook</code>. Give it a function as
its only argument, and from then on, that function will be called
(with the instance as argument) whenever a new CodeMirror instance
is initialized.</dd>
<dt id="registerHelper"><code><strong>CodeMirror.registerHelper</strong>(type: string, name: string, value: helper)</code></dt>
<dd>Registers a helper value with the given <code>name</code> in
the given namespace (<code>type</code>). This is used to define
functionality that may be looked up by mode. Will create (if it
doesn't already exist) a property on the <code>CodeMirror</code>
object for the given <code>type</code>, pointing to an object
that maps names to values. I.e. after
doing <code>CodeMirror.registerHelper("hint", "foo",
myFoo)</code>, the value <code>CodeMirror.hint.foo</code> will
point to <code>myFoo</code>.</dd>
<dt id="registerGlobalHelper"><code><strong>CodeMirror.registerGlobalHelper</strong>(type: string, name: string, predicate: fn(mode, CodeMirror), value: helper)</code></dt>
<dd>Acts
like <a href="#registerHelper"><code>registerHelper</code></a>,
but also registers this helper as 'global', meaning that it will
be included by <a href="#getHelpers"><code>getHelpers</code></a>
whenever the given <code>predicate</code> returns true when
called with the local mode and editor.</dd>
<dt id="Pos"><code><strong>CodeMirror.Pos</strong>(line: integer, ?ch: integer, ?sticky: string)</code></dt>
<dd>A constructor for the objects that are used to represent
positions in editor documents. <code>sticky</code> defaults to
null, but can be set to <code>"before"</code>
or <code>"after"</code> to make the position explicitly
associate with the character before or after it.</dd>
<dt id="changeEnd"><code><strong>CodeMirror.changeEnd</strong>(change: object) → {line, ch}</code></dt>
<dd>Utility function that computes an end position from a change
(an object with <code>from</code>, <code>to</code>,
and <code>text</code> properties, as passed to
various <a href="#event_change">event handlers</a>). The
returned position will be the end of the changed
range, <em>after</em> the change is applied.</dd>
<dt id="countColumn"><code><strong>CodeMirror.countColumn</strong>(line: string, index: number, tabSize: number) → number</code></dt>
<dd>Find the column position at a given string index using a given tabsize.</dd>
</dl>
</section>
<section id=addons>
<h2 id="addons">Addons</h2>
<p>The <code>addon</code> directory in the distribution contains a
number of reusable components that implement extra editor
functionality (on top of extension functions
like <a href="#defineOption"><code>defineOption</code></a>, <a href="#defineExtension"><code>defineExtension</code></a>,
and <a href="#registerHelper"><code>registerHelper</code></a>). In
brief, they are:</p>
<dl>
<dt id="addon_dialog"><a href="../addon/dialog/dialog.js"><code>dialog/dialog.js</code></a></dt>
<dd>Provides a very simple way to query users for text input.
Adds the <strong><code>openDialog(template, callback, options) →
closeFunction</code></strong> method to CodeMirror instances,
which can be called with an HTML fragment or a detached DOM
node that provides the prompt (should include an <code>input</code>
or <code>button</code> tag), and a callback function that is called
when the user presses enter. It returns a function <code>closeFunction</code>
which, if called, will close the dialog immediately.
<strong><code>openDialog</code></strong> takes the following options:
<dl>
<dt><code><strong>closeOnEnter</strong>: bool</code></dt>
<dd>If true, the dialog will be closed when the user presses
enter in the input. Defaults to <code>true</code>.</dd>
<dt><code><strong>closeOnBlur</strong>: bool</code></dt>
<dd>Determines whether the dialog is closed when it loses focus. Defaults to <code>true</code>.</dd>
<dt><code><strong>onKeyDown</strong>: fn(event: KeyboardEvent, value: string, close: fn()) → bool</code></dt>
<dd>An event handler that will be called whenever <code>keydown</code> fires in the
dialog's input. If your callback returns <code>true</code>,
the dialog will not do any further processing of the event.</dd>
<dt><code><strong>onKeyUp</strong>: fn(event: KeyboardEvent, value: string, close: fn()) → bool</code></dt>
<dd>Same as <code>onKeyDown</code> but for the
<code>keyup</code> event.</dd>
<dt><code><strong>onInput</strong>: fn(event: InputEvent, value: string, close: fn()) → bool</code></dt>
<dd>Same as <code>onKeyDown</code> but for the
<code>input</code> event.</dd>
<dt><code><strong>onClose</strong>: fn(instance)</code>:</dt>
<dd>A callback that will be called after the dialog has been closed and
removed from the DOM. No return value.</dd>
</dl>
<p>Also adds an <strong><code>openNotification(template, options) →
closeFunction</code></strong> function that simply shows an HTML
fragment as a notification at the top of the editor. It takes a
single option: <code>duration</code>, the amount of time after
which the notification will be automatically closed. If <code>
duration</code> is zero, the dialog will not be closed automatically.</p>
<p>Depends on <code>addon/dialog/dialog.css</code>.</p></dd>
<dt id="addon_searchcursor"><a href="../addon/search/searchcursor.js"><code>search/searchcursor.js</code></a></dt>
<dd>Adds the <code>getSearchCursor(query, start, options) →
cursor</code> method to CodeMirror instances, which can be used
to implement search/replace functionality. <code>query</code>
can be a regular expression or a string. <code>start</code>
provides the starting position of the search. It can be
a <code>{line, ch}</code> object, or can be left off to default
to the start of the document. <code>options</code> is an
optional object, which can contain the property `caseFold:
false` to disable case folding when matching a string, or the
property `multiline: disable` to disable multi-line matching for
regular expressions (which may help performance). A search
cursor has the following methods:
<dl>
<dt><code><strong>findNext</strong>() → boolean</code></dt>
<dt><code><strong>findPrevious</strong>() → boolean</code></dt>
<dd>Search forward or backward from the current position.
The return value indicates whether a match was found. If
matching a regular expression, the return value will be the
array returned by the <code>match</code> method, in case you
want to extract matched groups.</dd>
<dt><code><strong>from</strong>() → {line, ch}</code></dt>
<dt><code><strong>to</strong>() → {line, ch}</code></dt>
<dd>These are only valid when the last call
to <code>findNext</code> or <code>findPrevious</code> did
not return false. They will return <code>{line, ch}</code>
objects pointing at the start and end of the match.</dd>
<dt><code><strong>replace</strong>(text: string, ?origin: string)</code></dt>
<dd>Replaces the currently found match with the given text
and adjusts the cursor position to reflect the
replacement.</dd>
</dl></dd>
<dt id="addon_search"><a href="../addon/search/search.js"><code>search/search.js</code></a></dt>
<dd>Implements the search commands. CodeMirror has keys bound to
these by default, but will not do anything with them unless an
implementation is provided. Depends
on <code>searchcursor.js</code>, and will make use
of <a href="#addon_dialog"><code>openDialog</code></a> when
available to make prompting for search queries less ugly.</dd>
<dt id="addon_jump-to-line"><a href="../addon/search/jump-to-line.js"><code>search/jump-to-line.js</code></a></dt>
<dd>Implements a <code>jumpToLine</code> command and binding <code>Alt-G</code> to it.
Accepts <code>linenumber</code>, <code>+/-linenumber</code>, <code>line:char</code>,
<code>scroll%</code> and <code>:linenumber</code> formats.
This will make use of <a href="#addon_dialog"><code>openDialog</code></a>
when available to make prompting for line number neater.</dd>
<dt id="addon_matchesonscrollbar"><a href="../addon/search/matchesonscrollbar.js"><code>search/matchesonscrollbar.js</code></a></dt>
<dd>Adds a <code>showMatchesOnScrollbar</code> method to editor
instances, which should be given a query (string or regular
expression), optionally a case-fold flag (only applicable for
strings), and optionally a class name (defaults
to <code>CodeMirror-search-match</code>) as arguments. When
called, matches of the given query will be displayed on the
editor's vertical scrollbar. The method returns an object with
a <code>clear</code> method that can be called to remove the
matches. Depends on
the <a href="#addon_annotatescrollbar"><code>annotatescrollbar</code></a>
addon, and
the <a href="../addon/search/matchesonscrollbar.css"><code>matchesonscrollbar.css</code></a>
file provides a default (transparent yellowish) definition of
the CSS class applied to the matches. Note that the matches are
only perfectly aligned if your scrollbar does not have buttons
at the top and bottom. You can use
the <a href="#addon_simplescrollbars"><code>simplescrollbar</code></a>
addon to make sure of this. If this addon is loaded,
the <a href="#addon_search"><code>search</code></a> addon will
automatically use it.</dd>
<dt id="addon_matchbrackets"><a href="../addon/edit/matchbrackets.js"><code>edit/matchbrackets.js</code></a></dt>
<dd>Defines an option <code>matchBrackets</code> which, when set
to true or an options object, causes matching brackets to be
highlighted whenever the cursor is next to them. It also adds a
method <code>matchBrackets</code> that forces this to happen
once, and a method <code>findMatchingBracket</code> that can be
used to run the bracket-finding algorithm that this uses
internally. It takes a start position and an optional config
object. By default, it will find the match to a matchable
character either before or after the cursor (preferring the one
before), but you can control its behavior with these options:
<dl>
<dt><strong><code>afterCursor</code></strong></dt>
<dd>Only use the character after the start position, never the one before it.</dd>
<dt><strong><code>strict</code></strong></dt>
<dd>Causes only matches where both brackets are at the same side of the start position to be considered.</dd>
<dt><strong><code>maxScanLines</code></strong></dt>
<dd>Stop after scanning this amount of lines without a successful match. Defaults to 1000.</dd>
<dt><strong><code>maxScanLineLength</code></strong></dt>
<dd>Ignore lines longer than this. Defaults to 10000.</dd>
<dt><strong><code>maxHighlightLineLength</code></strong></dt>
<dd>Don't highlight a bracket in a line longer than this. Defaults to 1000.</dd>
</dl></dd>
<dt id="addon_closebrackets"><a href="../addon/edit/closebrackets.js"><code>edit/closebrackets.js</code></a></dt>
<dd>Defines an option <code>autoCloseBrackets</code> that will
auto-close brackets and quotes when typed. By default, it'll
auto-close <code>()[]{}''""</code>, but you can pass it a string
similar to that (containing pairs of matching characters), or an
object with <code>pairs</code> and
optionally <code>explode</code> properties to customize
it. <code>explode</code> should be a similar string that gives
the pairs of characters that, when enter is pressed between
them, should have the second character also moved to its own
line. By default, if the active mode has
a <code>closeBrackets</code> property, that overrides the
configuration given in the option. But you can add
an <code>override</code> property with a truthy value to
override mode-specific
configuration. <a href="../demo/closebrackets.html">Demo
here</a>.</dd>
<dt id="addon_matchtags"><a href="../addon/edit/matchtags.js"><code>edit/matchtags.js</code></a></dt>
<dd>Defines an option <code>matchTags</code> that, when enabled,
will cause the tags around the cursor to be highlighted (using
the <code>CodeMirror-matchingtag</code> class). Also
defines
a <a href="#commands">command</a> <code>toMatchingTag</code>,
which you can bind a key to in order to jump to the tag matching
the one under the cursor. Depends on
the <code>addon/fold/xml-fold.js</code>
addon. <a href="../demo/matchtags.html">Demo here.</a></dd>
<dt id="addon_trailingspace"><a href="../addon/edit/trailingspace.js"><code>edit/trailingspace.js</code></a></dt>
<dd>Adds an option <code>showTrailingSpace</code> which, when
enabled, adds the CSS class <code>cm-trailingspace</code> to
stretches of whitespace at the end of lines.
The <a href="../demo/trailingspace.html">demo</a> has a nice
squiggly underline style for this class.</dd>
<dt id="addon_closetag"><a href="../addon/edit/closetag.js"><code>edit/closetag.js</code></a></dt>
<dd>Defines an <code>autoCloseTags</code> option that will
auto-close XML tags when '<code>></code>' or '<code>/</code>'
is typed, and
a <code>closeTag</code> <a href="#commands">command</a> that
closes the nearest open tag. Depends on
the <code>fold/xml-fold.js</code> addon. See
the <a href="../demo/closetag.html">demo</a>.</dd>
<dt id="addon_continuelist"><a href="../addon/edit/continuelist.js"><code>edit/continuelist.js</code></a></dt>
<dd>Markdown specific. Defines
a <code>"newlineAndIndentContinueMarkdownList"</code> <a href="#commands">command</a>
that can be bound to <code>enter</code> to automatically
insert the leading characters for continuing a list. See
the <a href="../mode/markdown/index.html">Markdown mode
demo</a>.</dd>
<dt id="addon_comment"><a href="../addon/comment/comment.js"><code>comment/comment.js</code></a></dt>
<dd>Addon for commenting and uncommenting code. Adds four
methods to CodeMirror instances:
<dl>
<dt id="toggleComment"><code><strong>toggleComment</strong>(?options: object)</code></dt>
<dd>Tries to uncomment the current selection, and if that
fails, line-comments it.</dd>
<dt id="lineComment"><code><strong>lineComment</strong>(from: {line, ch}, to: {line, ch}, ?options: object)</code></dt>
<dd>Set the lines in the given range to be line comments. Will
fall back to <code>blockComment</code> when no line comment
style is defined for the mode.</dd>
<dt id="blockComment"><code><strong>blockComment</strong>(from: {line, ch}, to: {line, ch}, ?options: object)</code></dt>
<dd>Wrap the code in the given range in a block comment. Will
fall back to <code>lineComment</code> when no block comment
style is defined for the mode.</dd>
<dt id="uncomment"><code><strong>uncomment</strong>(from: {line, ch}, to: {line, ch}, ?options: object) → boolean</code></dt>
<dd>Try to uncomment the given range.
Returns <code>true</code> if a comment range was found and
removed, <code>false</code> otherwise.</dd>
</dl>
The <code>options</code> object accepted by these methods may
have the following properties:
<dl>
<dt><code>blockCommentStart, blockCommentEnd, blockCommentLead, lineComment: string</code></dt>
<dd>Override the <a href="#mode_comment">comment string
properties</a> of the mode with custom comment strings.</dd>
<dt><code><strong>padding</strong>: string</code></dt>
<dd>A string that will be inserted after opening and leading
markers, and before closing comment markers. Defaults to a
single space.</dd>
<dt><code><strong>commentBlankLines</strong>: boolean</code></dt>
<dd>Whether, when adding line comments, to also comment lines
that contain only whitespace.</dd>
<dt><code><strong>indent</strong>: boolean</code></dt>
<dd>When adding line comments and this is turned on, it will
align the comment block to the current indentation of the
first line of the block.</dd>
<dt><code><strong>fullLines</strong>: boolean</code></dt>
<dd>When block commenting, this controls whether the whole
lines are indented, or only the precise range that is given.
Defaults to <code>true</code>.</dd>
</dl>
The addon also defines
a <code>toggleComment</code> <a href="#commands">command</a>,
which is a shorthand command for calling
<code>toggleComment</code> with no options.</dd>
<dt id="addon_foldcode"><a href="../addon/fold/foldcode.js"><code>fold/foldcode.js</code></a></dt>
<dd>Helps with code folding. Adds a <code>foldCode</code> method
to editor instances, which will try to do a code fold starting
at the given line, or unfold the fold that is already present.
The method takes as first argument the position that should be
folded (may be a line number or
a <a href="#Pos"><code>Pos</code></a>), and as second optional
argument either a range-finder function, or an options object,
supporting the following properties:
<dl>
<dt><code><strong>rangeFinder</strong>: fn(CodeMirror, Pos)</code></dt>
<dd id="helper_fold_auto">The function that is used to find
foldable ranges. If this is not directly passed, it will
default to <code>CodeMirror.fold.auto</code>, which
uses <a href="#getHelpers"><code>getHelpers</code></a> with
a <code>"fold"</code> type to find folding functions
appropriate for the local mode. There are files in
the <a href="../addon/fold/"><code>addon/fold/</code></a>
directory providing <code>CodeMirror.fold.brace</code>, which
finds blocks in brace languages (JavaScript, C, Java,
etc), <code>CodeMirror.fold.indent</code>, for languages where
indentation determines block structure (Python, Haskell),
and <code>CodeMirror.fold.xml</code>, for XML-style languages,
and <code>CodeMirror.fold.comment</code>, for folding comment
blocks.</dd>
<dt><code><strong>widget</strong>: string|Element</code></dt>
<dd>The widget to show for folded ranges. Can be either a
string, in which case it'll become a span with
class <code>CodeMirror-foldmarker</code>, or a DOM node.</dd>
<dt><code><strong>scanUp</strong>: boolean</code></dt>
<dd>When true (default is false), the addon will try to find
foldable ranges on the lines above the current one if there
isn't an eligible one on the given line.</dd>
<dt><code><strong>minFoldSize</strong>: integer</code></dt>
<dd>The minimum amount of lines that a fold should span to be
accepted. Defaults to 0, which also allows single-line
folds.</dd>
</dl>
See <a href="../demo/folding.html">the demo</a> for an
example.</dd>
<dt id="addon_foldgutter"><a href="../addon/fold/foldgutter.js"><code>fold/foldgutter.js</code></a></dt>
<dd>Provides an option <code>foldGutter</code>, which can be
used to create a gutter with markers indicating the blocks that
can be folded. Create a gutter using
the <a href="#option_gutters"><code>gutters</code></a> option,
giving it the class <code>CodeMirror-foldgutter</code> or
something else if you configure the addon to use a different
class, and this addon will show markers next to folded and
foldable blocks, and handle clicks in this gutter. Note that
CSS styles should be applied to make the gutter, and the fold
markers within it, visible. A default set of CSS styles are
available in:
<a href="../addon/fold/foldgutter.css">
<code>addon/fold/foldgutter.css</code>
</a>.
The option
can be either set to <code>true</code>, or an object containing
the following optional option fields:
<dl>
<dt><code><strong>gutter</strong>: string</code></dt>
<dd>The CSS class of the gutter. Defaults
to <code>"CodeMirror-foldgutter"</code>. You will have to
style this yourself to give it a width (and possibly a
background). See the default gutter style rules above.</dd>
<dt><code><strong>indicatorOpen</strong>: string | Element</code></dt>
<dd>A CSS class or DOM element to be used as the marker for
open, foldable blocks. Defaults
to <code>"CodeMirror-foldgutter-open"</code>.</dd>
<dt><code><strong>indicatorFolded</strong>: string | Element</code></dt>
<dd>A CSS class or DOM element to be used as the marker for
folded blocks. Defaults to <code>"CodeMirror-foldgutter-folded"</code>.</dd>
<dt><code><strong>rangeFinder</strong>: fn(CodeMirror, Pos)</code></dt>
<dd>The range-finder function to use when determining whether
something can be folded. When not
given, <a href="#helper_fold_auto"><code>CodeMirror.fold.auto</code></a>
will be used as default.</dd>
</dl>
The <code>foldOptions</code> editor option can be set to an
object to provide an editor-wide default configuration.
Demo <a href="../demo/folding.html">here</a>.</dd>
<dt id="addon_runmode"><a href="../addon/runmode/runmode.js"><code>runmode/runmode.js</code></a></dt>
<dd>Can be used to run a CodeMirror mode over text without
actually opening an editor instance.
See <a href="../demo/runmode.html">the demo</a> for an example.
There are alternate versions of the file available for
running <a href="../addon/runmode/runmode-standalone.js">stand-alone</a>
(without including all of CodeMirror) and
for <a href="../addon/runmode/runmode.node.js">running under
node.js</a> (see <code>bin/source-highlight</code> for an example of using the latter).</dd>
<dt id="addon_colorize"><a href="../addon/runmode/colorize.js"><code>runmode/colorize.js</code></a></dt>
<dd>Provides a convenient way to syntax-highlight code snippets
in a webpage. Depends on
the <a href="#addon_runmode"><code>runmode</code></a> addon (or
its standalone variant). Provides
a <code>CodeMirror.colorize</code> function that can be called
with an array (or other array-ish collection) of DOM nodes that
represent the code snippets. By default, it'll get
all <code>pre</code> tags. Will read the <code>data-lang</code>
attribute of these nodes to figure out their language, and
syntax-color their content using the relevant CodeMirror mode
(you'll have to load the scripts for the relevant modes
yourself). A second argument may be provided to give a default
mode, used when no language attribute is found for a node. Used
in this manual to highlight example code.</dd>
<dt id="addon_overlay"><a href="../addon/mode/overlay.js"><code>mode/overlay.js</code></a></dt>
<dd>Mode combinator that can be used to extend a mode with an
'overlay' — a secondary mode is run over the stream, along with
the base mode, and can color specific pieces of text without
interfering with the base mode.
Defines <code>CodeMirror.overlayMode</code>, which is used to
create such a mode. See <a href="../demo/mustache.html">this
demo</a> for a detailed example.</dd>
<dt id="addon_multiplex"><a href="../addon/mode/multiplex.js"><code>mode/multiplex.js</code></a></dt>
<dd>Mode combinator that can be used to easily 'multiplex'
between several modes.
Defines <code>CodeMirror.multiplexingMode</code> which, when
given as first argument a mode object, and as other arguments
any number of <code>{open, close, mode [, delimStyle, innerStyle, parseDelimiters]}</code>
objects, will return a mode object that starts parsing using the
mode passed as first argument, but will switch to another mode
as soon as it encounters a string that occurs in one of
the <code>open</code> fields of the passed objects. When in a
sub-mode, it will go back to the top mode again when
the <code>close</code> string is encountered.
Pass <code>"\n"</code> for <code>open</code> or <code>close</code>
if you want to switch on a blank line.
<ul><li>When <code>delimStyle</code> is specified, it will be the token
style returned for the delimiter tokens (as well as
<code>[delimStyle]-open</code> on the opening token and
<code>[delimStyle]-close</code> on the closing token).</li>
<li>When <code>innerStyle</code> is specified, it will be the token
style added for each inner mode token.</li>
<li>When <code>parseDelimiters</code> is true, the content of
the delimiters will also be passed to the inner mode.
(And <code>delimStyle</code> is ignored.)</li></ul> The outer
mode will not see the content between the delimiters.
See <a href="../demo/multiplex.html">this demo</a> for an
example.</dd>
<dt id="addon_show-hint"><a href="../addon/hint/show-hint.js"><code>hint/show-hint.js</code></a></dt>
<dd>Provides a framework for showing autocompletion hints.
Defines <code>editor.showHint</code>, which takes an optional
options object, and pops up a widget that allows the user to
select a completion. Finding hints is done with a hinting
functions (the <code>hint</code> option), which is a function
that take an editor instance and options object, and return
a <code>{list, from, to}</code> object, where <code>list</code>
is an array of strings or objects (the completions),
and <code>from</code> and <code>to</code> give the start and end
of the token that is being completed as <code>{line, ch}</code>
objects. An optional <code>selectedHint</code> property (an
integer) can be added to the completion object to control the
initially selected hint.</dd>
<dd>If no hinting function is given, the addon will
use <code>CodeMirror.hint.auto</code>, which
calls <a href="#getHelpers"><code>getHelpers</code></a> with
the <code>"hint"</code> type to find applicable hinting
functions, and tries them one by one. If that fails, it looks
for a <code>"hintWords"</code> helper to fetch a list of
completable words for the mode, and
uses <code>CodeMirror.hint.fromList</code> to complete from
those.</dd>
<dd>When completions aren't simple strings, they should be
objects with the following properties:
<dl>
<dt><code><strong>text</strong>: string</code></dt>
<dd>The completion text. This is the only required
property.</dd>
<dt><code><strong>displayText</strong>: string</code></dt>
<dd>The text that should be displayed in the menu.</dd>
<dt><code><strong>className</strong>: string</code></dt>
<dd>A CSS class name to apply to the completion's line in the
menu.</dd>
<dt><code><strong>render</strong>: fn(Element, self, data)</code></dt>
<dd>A method used to create the DOM structure for showing the
completion by appending it to its first argument.</dd>
<dt><code><strong>hint</strong>: fn(CodeMirror, self, data)</code></dt>
<dd>A method used to actually apply the completion, instead of
the default behavior.</dd>
<dt><code><strong>from</strong>: {line, ch}</code></dt>
<dd>Optional <code>from</code> position that will be used by <code>pick()</code> instead
of the global one passed with the full list of completions.</dd>
<dt><code><strong>to</strong>: {line, ch}</code></dt>
<dd>Optional <code>to</code> position that will be used by <code>pick()</code> instead
of the global one passed with the full list of completions.</dd>
</dl></dd>
<dd>The plugin understands the following options, which may be
either passed directly in the argument to <code>showHint</code>,
or provided by setting an <code>hintOptions</code> editor
option to an object (the former takes precedence). The options
object will also be passed along to the hinting function, which
may understand additional options.
<dl>
<dt><code><strong>hint</strong>: function</code></dt>
<dd>A hinting function, as specified above. It is possible to
set the <code>async</code> property on a hinting function to
true, in which case it will be called with
arguments <code>(cm, callback, ?options)</code>, and the
completion interface will only be popped up when the hinting
function calls the callback, passing it the object holding the
completions.
The hinting function can also return a promise, and the completion
interface will only be popped when the promise resolves.
By default, hinting only works when there is no
selection. You can give a hinting function
a <code>supportsSelection</code> property with a truthy value
to indicate that it supports selections.</dd>
<dt><code><strong>completeSingle</strong>: boolean</code></dt>
<dd>Determines whether, when only a single completion is
available, it is completed without showing the dialog.
Defaults to true.</dd>
<dt><code><strong>alignWithWord</strong>: boolean</code></dt>
<dd>Whether the pop-up should be horizontally aligned with the
start of the word (true, default), or with the cursor (false).</dd>
<dt><code><strong>closeOnUnfocus</strong>: boolean</code></dt>
<dd>When enabled (which is the default), the pop-up will close
when the editor is unfocused.</dd>
<dt><code><strong>customKeys</strong>: keymap</code></dt>
<dd>Allows you to provide a custom key map of keys to be active
when the pop-up is active. The handlers will be called with an
extra argument, a handle to the completion menu, which
has <code>moveFocus(n)</code>, <code>setFocus(n)</code>, <code>pick()</code>,
and <code>close()</code> methods (see the source for details),
that can be used to change the focused element, pick the
current element or close the menu. Additionally <code>menuSize()</code>
can give you access to the size of the current dropdown menu,
<code>length</code> give you the number of available completions, and
<code>data</code> give you full access to the completion returned by the
hinting function.</dd>
<dt><code><strong>extraKeys</strong>: keymap</code></dt>
<dd>Like <code>customKeys</code> above, but the bindings will
be added to the set of default bindings, instead of replacing
them.</dd>
</dl>
The following events will be fired on the completions object
during completion:
<dl>
<dt><code><strong>"shown"</strong> ()</code></dt>
<dd>Fired when the pop-up is shown.</dd>
<dt><code><strong>"select"</strong> (completion, Element)</code></dt>
<dd>Fired when a completion is selected. Passed the completion
value (string or object) and the DOM node that represents it
in the menu.</dd>
<dt><code><strong>"pick"</strong> (completion)</code></dt>
<dd>Fired when a completion is picked. Passed the completion value
(string or object).</dd>
<dt><code><strong>"close"</strong> ()</code></dt>
<dd>Fired when the completion is finished.</dd>
</dl>
This addon depends on styles
from <code>addon/hint/show-hint.css</code>. Check
out <a href="../demo/complete.html">the demo</a> for an
example.</dd>
<dt id="addon_javascript-hint"><a href="../addon/hint/javascript-hint.js"><code>hint/javascript-hint.js</code></a></dt>
<dd>Defines a simple hinting function for JavaScript
(<code>CodeMirror.hint.javascript</code>) and CoffeeScript
(<code>CodeMirror.hint.coffeescript</code>) code. This will
simply use the JavaScript environment that the editor runs in as
a source of information about objects and their properties.</dd>
<dt id="addon_xml-hint"><a href="../addon/hint/xml-hint.js"><code>hint/xml-hint.js</code></a></dt>
<dd>Defines <code>CodeMirror.hint.xml</code>, which produces
hints for XML tagnames, attribute names, and attribute values,
guided by a <code>schemaInfo</code> option (a property of the
second argument passed to the hinting function, or the third
argument passed to <code>CodeMirror.showHint</code>).<br>The
schema info should be an object mapping tag names to information
about these tags, with optionally a <code>"!top"</code> property
containing a list of the names of valid top-level tags. The
values of the properties should be objects with optional
properties <code>children</code> (an array of valid child
element names, omit to simply allow all tags to appear)
and <code>attrs</code> (an object mapping attribute names
to <code>null</code> for free-form attributes, and an array of
valid values for restricted
attributes).<br>The hint options accept an additional property:
<dl>
<dt><code><strong>matchInMiddle</strong>: boolean</code></dt>
<dd>Determines whether typed characters are matched anywhere in
completions, not just at the beginning. Defaults to false.</dd>
</dl>
<a href="../demo/xmlcomplete.html">Demo here</a>.</dd>
<dt id="addon_html-hint"><a href="../addon/hint/html-hint.js"><code>hint/html-hint.js</code></a></dt>
<dd>Provides schema info to
the <a href="#addon_xml-hint">xml-hint</a> addon for HTML
documents. Defines a schema
object <code>CodeMirror.htmlSchema</code> that you can pass to
as a <code>schemaInfo</code> option, and
a <code>CodeMirror.hint.html</code> hinting function that
automatically calls <code>CodeMirror.hint.xml</code> with this
schema data. See
the <a href="../demo/html5complete.html">demo</a>.</dd>
<dt id="addon_css-hint"><a href="../addon/hint/css-hint.js"><code>hint/css-hint.js</code></a></dt>
<dd>A hinting function for CSS, SCSS, or LESS code.
Defines <code>CodeMirror.hint.css</code>.</dd>
<dt id="addon_anyword-hint"><a href="../addon/hint/anyword-hint.js"><code>hint/anyword-hint.js</code></a></dt>
<dd>A very simple hinting function
(<code>CodeMirror.hint.anyword</code>) that simply looks for
words in the nearby code and completes to those. Takes two
optional options, <code>word</code>, a regular expression that
matches words (sequences of one or more character),
and <code>range</code>, which defines how many lines the addon
should scan when completing (defaults to 500).</dd>
<dt id="addon_sql-hint"><a href="../addon/hint/sql-hint.js"><code>hint/sql-hint.js</code></a></dt>
<dd>A simple SQL hinter. Defines <code>CodeMirror.hint.sql</code>.
Takes two optional options, <code>tables</code>, a object with
table names as keys and array of respective column names as values,
and <code>defaultTable</code>, a string corresponding to a
table name in <code>tables</code> for autocompletion.</dd>
<dt id="addon_match-highlighter"><a href="../addon/search/match-highlighter.js"><code>search/match-highlighter.js</code></a></dt>
<dd>Adds a <code>highlightSelectionMatches</code> option that
can be enabled to highlight all instances of a currently
selected word. Can be set either to true or to an object
containing the following options: <code>minChars</code>, for the
minimum amount of selected characters that triggers a highlight
(default 2), <code>style</code>, for the style to be used to
highlight the matches (default <code>"matchhighlight"</code>,
which will correspond to CSS
class <code>cm-matchhighlight</code>), <code>trim</code>, which
controls whether whitespace is trimmed from the selection,
and <code>showToken</code> which can be set to <code>true</code>
or to a regexp matching the characters that make up a word. When
enabled, it causes the current word to be highlighted when
nothing is selected (defaults to off).
Demo <a href="../demo/matchhighlighter.html">here</a>.</dd>
<dt id="addon_lint"><a href="../addon/lint/lint.js"><code>lint/lint.js</code></a></dt>
<dd>Defines an interface component for showing linting warnings,
with pluggable warning sources
(see <a href="../addon/lint/html-lint.js"><code>html-lint.js</code></a>,
<a href="../addon/lint/json-lint.js"><code>json-lint.js</code></a>,
<a href="../addon/lint/javascript-lint.js"><code>javascript-lint.js</code></a>,
<a href="../addon/lint/coffeescript-lint.js"><code>coffeescript-lint.js</code></a>,
and <a href="../addon/lint/css-lint.js"><code>css-lint.js</code></a>
in the same directory). Defines a <code>lint</code> option that
can be set to an annotation source (for
example <code>CodeMirror.lint.javascript</code>), to an options
object (in which case the <code>getAnnotations</code> field is
used as annotation source), or simply to <code>true</code>. When
no annotation source is
specified, <a href="#getHelper"><code>getHelper</code></a> with
type <code>"lint"</code> is used to find an annotation function.
An annotation source function should, when given a document
string, an options object, and an editor instance, return an
array of <code>{message, severity, from, to}</code> objects
representing problems. When the function has
an <code>async</code> property with a truthy value, it will be
called with an additional second argument, which is a callback
to pass the array to.
The linting function can also return a promise, in that case the linter
will only be executed when the promise resolves.
By default, the linter will run (debounced) whenever the document is changed.
You can pass a <code>lintOnChange: false</code> option to disable that.
Depends on <code>addon/lint/lint.css</code>. A demo can be
found <a href="../demo/lint.html">here</a>.</dd>
<dt id="addon_mark-selection"><a href="../addon/selection/mark-selection.js"><code>selection/mark-selection.js</code></a></dt>
<dd>Causes the selected text to be marked with the CSS class
<code>CodeMirror-selectedtext</code> when the <code>styleSelectedText</code> option
is enabled. Useful to change the colour of the selection (in addition to the background),
like in <a href="../demo/markselection.html">this demo</a>.</dd>
<dt id="addon_active-line"><a href="../addon/selection/active-line.js"><code>selection/active-line.js</code></a></dt>
<dd>Defines a <code>styleActiveLine</code> option that, when
enabled, gives the wrapper of the line that contains the cursor
the class <code>CodeMirror-activeline</code>, adds a background
with the class <code>CodeMirror-activeline-background</code>,
and adds the class <code>CodeMirror-activeline-gutter</code> to
the line's gutter space is enabled. The option's value may be a
boolean or an object specifying the following options:
<dl>
<dt><code><strong>nonEmpty</strong>: bool</code></dt>
<dd>Controls whether single-line selections, or just cursor
selections, are styled. Defaults to false (only cursor
selections).</dd>
</dl>
See the <a href="../demo/activeline.html">demo</a>.</dd>
<dt id="addon_selection-pointer"><a href="../addon/selection/selection-pointer.js"><code>selection/selection-pointer.js</code></a></dt>
<dd>Defines a <code>selectionPointer</code> option which you can
use to control the mouse cursor appearance when hovering over
the selection. It can be set to a string,
like <code>"pointer"</code>, or to true, in which case
the <code>"default"</code> (arrow) cursor will be used. You can
see a demo <a href="../mode/htmlmixed/index.html">here</a>.</dd>
<dt id="addon_loadmode"><a href="../addon/mode/loadmode.js"><code>mode/loadmode.js</code></a></dt>
<dd>Defines a <code>CodeMirror.requireMode(modename,
callback)</code> function that will try to load a given mode and
call the callback when it succeeded. You'll have to
set <code>CodeMirror.modeURL</code> to a string that mode paths
can be constructed from, for
example <code>"mode/%N/%N.js"</code>—the <code>%N</code>'s will
be replaced with the mode name. Also
defines <code>CodeMirror.autoLoadMode(instance, mode)</code>,
which will ensure the given mode is loaded and cause the given
editor instance to refresh its mode when the loading
succeeded. See the <a href="../demo/loadmode.html">demo</a>.</dd>
<dt id="addon_meta"><a href="../mode/meta.js"><code>mode/meta.js</code></a></dt>
<dd>Provides meta-information about all the modes in the
distribution in a single file.
Defines <code>CodeMirror.modeInfo</code>, an array of objects
with <code>{name, mime, mode}</code> properties,
where <code>name</code> is the human-readable
name, <code>mime</code> the MIME type, and <code>mode</code> the
name of the mode file that defines this MIME. There are optional
properties <code>mimes</code>, which holds an array of MIME
types for modes with multiple MIMEs associated,
and <code>ext</code>, which holds an array of file extensions
associated with this mode. Four convenience
functions, <code>CodeMirror.findModeByMIME</code>,
<code>CodeMirror.findModeByExtension</code>,
<code>CodeMirror.findModeByFileName</code>
and <code>CodeMirror.findModeByName</code> are provided, which
return such an object given a MIME, extension, file name or mode name
string. Note that, for historical reasons, this file resides in the
top-level <code>mode</code> directory, not
under <code>addon</code>. <a href="../demo/loadmode.html">Demo</a>.</dd>
<dt id="addon_continuecomment"><a href="../addon/comment/continuecomment.js"><code>comment/continuecomment.js</code></a></dt>
<dd>Adds a <code>continueComments</code> option, which sets whether the
editor will make the next line continue a comment when you press Enter
inside a comment block. Can be set to a boolean to enable/disable this
functionality. Set to a string, it will continue comments using a custom
shortcut. Set to an object, it will use the <code>key</code> property for
a custom shortcut and the boolean <code>continueLineComment</code>
property to determine whether single-line comments should be continued
(defaulting to <code>true</code>).</dd>
<dt id="addon_placeholder"><a href="../addon/display/placeholder.js"><code>display/placeholder.js</code></a></dt>
<dd>Adds a <code>placeholder</code> option that can be used to
make content appear in the editor when it is empty and not
focused. It can hold either a string or a DOM node. Also gives
the editor a <code>CodeMirror-empty</code> CSS class whenever it
doesn't contain any text.
See <a href="../demo/placeholder.html">the demo</a>.</dd>
<dt id="addon_fullscreen"><a href="../addon/display/fullscreen.js"><code>display/fullscreen.js</code></a></dt>
<dd>Defines an option <code>fullScreen</code> that, when set
to <code>true</code>, will make the editor full-screen (as in,
taking up the whole browser window). Depends
on <a href="../addon/display/fullscreen.css"><code>fullscreen.css</code></a>. <a href="../demo/fullscreen.html">Demo
here</a>.</dd>
<dt id="addon_autorefresh"><a href="../addon/display/autorefresh.js"><code>display/autorefresh.js</code></a></dt>
<dd>This addon can be useful when initializing an editor in a
hidden DOM node, in cases where it is difficult to
call <a href="#refresh"><code>refresh</code></a> when the editor
becomes visible. It defines an option <code>autoRefresh</code>
which you can set to true to ensure that, if the editor wasn't
visible on initialization, it will be refreshed the first time
it becomes visible. This is done by polling every 250
milliseconds (you can pass a value like <code>{delay:
500}</code> as the option value to configure this). Note that
this addon will only refresh the editor <em>once</em> when it
first becomes visible, and won't take care of further restyling
and resizing.</dd>
<dt id="addon_simplescrollbars"><a href="../addon/scroll/simplescrollbars.js"><code>scroll/simplescrollbars.js</code></a></dt>
<dd>Defines two additional scrollbar
models, <code>"simple"</code> and <code>"overlay"</code>
(see <a href="../demo/simplescrollbars.html">demo</a>) that can
be selected with
the <a href="#option_scrollbarStyle"><code>scrollbarStyle</code></a>
option. Depends
on <a href="../addon/scroll/simplescrollbars.css"><code>simplescrollbars.css</code></a>,
which can be further overridden to style your own
scrollbars.</dd>
<dt id="addon_annotatescrollbar"><a href="../addon/scroll/annotatescrollbar.js"><code>scroll/annotatescrollbar.js</code></a></dt>
<dd>Provides functionality for showing markers on the scrollbar
to call out certain parts of the document. Adds a
method <code>annotateScrollbar</code> to editor instances that
can be called, with a CSS class name as argument, to create a
set of annotations. The method returns an object
whose <code>update</code> method can be called with a sorted array
of <code>{from: Pos, to: Pos}</code> objects marking the ranges
to be highlighted. To detach the annotations, call the
object's <code>clear</code> method.</dd>
<dt id="addon_rulers"><a href="../addon/display/rulers.js"><code>display/rulers.js</code></a></dt>
<dd>Adds a <code>rulers</code> option, which can be used to show
one or more vertical rulers in the editor. The option, if
defined, should be given an array of <code>{column [, className,
color, lineStyle, width]}</code> objects or numbers (which
indicate a column). The ruler will be displayed at the column
indicated by the number or the <code>column</code> property.
The <code>className</code> property can be used to assign a
custom style to a ruler. <a href="../demo/rulers.html">Demo
here</a>.</dd>
<dt id="addon_panel"><a href="../addon/display/panel.js"><code>display/panel.js</code></a></dt>
<dd>Defines an <code>addPanel</code> method for CodeMirror
instances, which places a DOM node above or below an editor, and
shrinks the editor to make room for the node. The method takes
as first argument as DOM node, and as second an optional options
object. The <code>Panel</code> object returned by this method
has a <code>clear</code> method that is used to remove the
panel, and a <code>changed</code> method that can be used to
notify the addon when the size of the panel's DOM node has
changed.<br/>
The method accepts the following options:
<dl>
<dt><code><strong>position</strong>: string</code></dt>
<dd>Controls the position of the newly added panel. The
following values are recognized:
<dl>
<dt><code><strong>top</strong> (default)</code></dt>
<dd>Adds the panel at the very top.</dd>
<dt><code><strong>after-top</strong></code></dt>
<dd>Adds the panel at the bottom of the top panels.</dd>
<dt><code><strong>bottom</strong></code></dt>
<dd>Adds the panel at the very bottom.</dd>
<dt><code><strong>before-bottom</strong></code></dt>
<dd>Adds the panel at the top of the bottom panels.</dd>
</dl>
</dd>
<dt><code><strong>before</strong>: Panel</code></dt>
<dd>The new panel will be added before the given panel.</dd>
<dt><code><strong>after</strong>: Panel</code></dt>
<dd>The new panel will be added after the given panel.</dd>
<dt><code><strong>replace</strong>: Panel</code></dt>
<dd>The new panel will replace the given panel.</dd>
<dt><code><strong>stable</strong>: bool</code></dt>
<dd>Whether to scroll the editor to keep the text's vertical
position stable, when adding a panel above it. Defaults to false.</dd>
</dl>
When using the <code>after</code>, <code>before</code> or <code>replace</code> options,
if the panel doesn't exists or has been removed,
the value of the <code>position</code> option will be used as a fallback.
<br>
A demo of the addon is available <a href="../demo/panel.html">here</a>.
</dd>
<dt id="addon_hardwrap"><a href="../addon/wrap/hardwrap.js"><code>wrap/hardwrap.js</code></a></dt>
<dd>Addon to perform hard line wrapping/breaking for paragraphs
of text. Adds these methods to editor instances:
<dl>
<dt><code><strong>wrapParagraph</strong>(?pos: {line, ch}, ?options: object)</code></dt>
<dd>Wraps the paragraph at the given position.
If <code>pos</code> is not given, it defaults to the cursor
position.</dd>
<dt><code><strong>wrapRange</strong>(from: {line, ch}, to: {line, ch}, ?options: object)</code></dt>
<dd>Wraps the given range as one big paragraph.</dd>
<dt><code><strong>wrapParagraphsInRange</strong>(from: {line, ch}, to: {line, ch}, ?options: object)</code></dt>
<dd>Wraps the paragraphs in (and overlapping with) the
given range individually.</dd>
</dl>
The following options are recognized:
<dl>
<dt><code><strong>paragraphStart</strong>, <strong>paragraphEnd</strong>: RegExp</code></dt>
<dd>Blank lines are always considered paragraph boundaries.
These options can be used to specify a pattern that causes
lines to be considered the start or end of a paragraph.</dd>
<dt><code><strong>column</strong>: number</code></dt>
<dd>The column to wrap at. Defaults to 80.</dd>
<dt><code><strong>wrapOn</strong>: RegExp</code></dt>
<dd>A regular expression that matches only those
two-character strings that allow wrapping. By default, the
addon wraps on whitespace and after dash characters.</dd>
<dt><code><strong>killTrailingSpace</strong>: boolean</code></dt>
<dd>Whether trailing space caused by wrapping should be
preserved, or deleted. Defaults to true.</dd>
</dl>
A demo of the addon is available <a href="../demo/hardwrap.html">here</a>.
</dd>
<dt id="addon_merge"><a href="../addon/merge/merge.js"><code>merge/merge.js</code></a></dt>
<dd>Implements an interface for merging changes, using either a
2-way or a 3-way view. The <code>CodeMirror.MergeView</code>
constructor takes arguments similar to
the <a href="#CodeMirror"><code>CodeMirror</code></a>
constructor, first a node to append the interface to, and then
an options object. Options are passed through to the editors
inside the view. These extra options are recognized:
<dl>
<dt><code><strong>origLeft</strong></code> and <code><strong>origRight</strong>: string</code></dt>
<dd>If given these provide original versions of the
document, which will be shown to the left and right of the
editor in non-editable CodeMirror instances. The merge
interface will highlight changes between the editable
document and the original(s). To create a 2-way (as opposed
to 3-way) merge view, provide only one of them.</dd>
<dt><code><strong>revertButtons</strong>: boolean</code></dt>
<dd>Determines whether buttons that allow the user to revert
changes are shown. Defaults to true.</dd>
<dt><code><strong>revertChunk</strong>: fn(mv: MergeView, from: CodeMirror, fromStart: Pos, fromEnd: Pos, to: CodeMirror, toStart: Pos, toEnd: Pos)</code></dt>
<dd>Can be used to define custom behavior when the user
reverts a changed chunk.</dd>
<dt><code><strong>connect</strong>: string</code></dt>
<dd>Sets the style used to connect changed chunks of code.
By default, connectors are drawn. When this is set
to <code>"align"</code>, the smaller chunk is padded to
align with the bigger chunk instead.</dd>
<dt><code><strong>collapseIdentical</strong>: boolean|number</code></dt>
<dd>When true (default is false), stretches of unchanged
text will be collapsed. When a number is given, this
indicates the amount of lines to leave visible around such
stretches (which defaults to 2).</dd>
<dt><code><strong>allowEditingOriginals</strong>: boolean</code></dt>
<dd>Determines whether the original editor allows editing.
Defaults to false.</dd>
<dt><code><strong>showDifferences</strong>: boolean</code></dt>
<dd>When true (the default), changed pieces of text are
highlighted.</dd>
<dt><code><strong>chunkClassLocation</strong>: string|Array</code></dt>
<dd>By default the chunk highlights are added
using <a href="#addLineClass"><code>addLineClass</code></a>
with "background". Override this to customize it to be any
valid `where` parameter or an Array of valid `where`
parameters.</dd>
</dl>
The addon also defines commands <code>"goNextDiff"</code>
and <code>"goPrevDiff"</code> to quickly jump to the next
changed chunk. <a href="../demo/merge.html">Demo
here</a>.</dd>
<dt id="addon_tern"><a href="../addon/tern/tern.js"><code>tern/tern.js</code></a></dt>
<dd>Provides integration with
the <a href="http://ternjs.net">Tern</a> JavaScript analysis
engine, for completion, definition finding, and minor
refactoring help. See the <a href="../demo/tern.html">demo</a>
for a very simple integration. For more involved scenarios, see
the comments at the top of
the <a href="../addon/tern/tern.js">addon</a> and the
implementation of the
(multi-file) <a href="http://ternjs.net/doc/demo.html">demonstration
on the Tern website</a>.</dd>
</dl>
</section>
<section id=modeapi>
<h2>Writing CodeMirror Modes</h2>
<p>Modes typically consist of a single JavaScript file. This file
defines, in the simplest case, a lexer (tokenizer) for your
language—a function that takes a character stream as input,
advances it past a token, and returns a style for that token. More
advanced modes can also handle indentation for the language.</p>
<p>This section describes the low-level mode interface. Many modes
are written directly against this, since it offers a lot of
control, but for a quick mode definition, you might want to use
the <a href="../demo/simplemode.html">simple mode addon</a>.</p>
<p id="defineMode">The mode script should
call <code><strong>CodeMirror.defineMode</strong></code> to
register itself with CodeMirror. This function takes two
arguments. The first should be the name of the mode, for which you
should use a lowercase string, preferably one that is also the
name of the files that define the mode (i.e. <code>"xml"</code> is
defined in <code>xml.js</code>). The second argument should be a
function that, given a CodeMirror configuration object (the thing
passed to the <code>CodeMirror</code> function) and an optional
mode configuration object (as in
the <a href="#option_mode"><code>mode</code></a> option), returns
a mode object.</p>
<p>Typically, you should use this second argument
to <code>defineMode</code> as your module scope function (modes
should not leak anything into the global scope!), i.e. write your
whole mode inside this function.</p>
<p>The main responsibility of a mode script is <em>parsing</em>
the content of the editor. Depending on the language and the
amount of functionality desired, this can be done in really easy
or extremely complicated ways. Some parsers can be stateless,
meaning that they look at one element (<em>token</em>) of the code
at a time, with no memory of what came before. Most, however, will
need to remember something. This is done by using a <em>state
object</em>, which is an object that is always passed when
reading a token, and which can be mutated by the tokenizer.</p>
<p id="startState">Modes that use a state must define
a <code><strong>startState</strong></code> method on their mode
object. This is a function of no arguments that produces a state
object to be used at the start of a document.</p>
<p id="token">The most important part of a mode object is
its <code><strong>token</strong>(stream, state)</code> method. All
modes must define this method. It should read one token from the
stream it is given as an argument, optionally update its state,
and return a style string, or <code>null</code> for tokens that do
not have to be styled. For your styles, you are encouraged to use
the 'standard' names defined in the themes (without
the <code>cm-</code> prefix). If that fails, it is also possible
to come up with your own and write your own CSS theme file.<p>
<p id="token_style_line">A typical token string would
be <code>"variable"</code> or <code>"comment"</code>. Multiple
styles can be returned (separated by spaces), for
example <code>"string error"</code> for a thing that looks like a
string but is invalid somehow (say, missing its closing quote).
When a style is prefixed by <code>"line-"</code>
or <code>"line-background-"</code>, the style will be applied to
the whole line, analogous to what
the <a href="#addLineClass"><code>addLineClass</code></a> method
does—styling the <code>"text"</code> in the simple case, and
the <code>"background"</code> element
when <code>"line-background-"</code> is prefixed.</p>
<p id="StringStream">The stream object that's passed
to <code>token</code> encapsulates a line of code (tokens may
never span lines) and our current position in that line. It has
the following API:</p>
<dl>
<dt><code><strong>eol</strong>() → boolean</code></dt>
<dd>Returns true only if the stream is at the end of the
line.</dd>
<dt><code><strong>sol</strong>() → boolean</code></dt>
<dd>Returns true only if the stream is at the start of the
line.</dd>
<dt><code><strong>peek</strong>() → string</code></dt>
<dd>Returns the next character in the stream without advancing
it. Will return a <code>null</code> at the end of the
line.</dd>
<dt><code><strong>next</strong>() → string</code></dt>
<dd>Returns the next character in the stream and advances it.
Also returns <code>null</code> when no more characters are
available.</dd>
<dt><code><strong>eat</strong>(match: string|regexp|function(char: string) → boolean) → string</code></dt>
<dd><code>match</code> can be a character, a regular expression,
or a function that takes a character and returns a boolean. If
the next character in the stream 'matches' the given argument,
it is consumed and returned. Otherwise, <code>undefined</code>
is returned.</dd>
<dt><code><strong>eatWhile</strong>(match: string|regexp|function(char: string) → boolean) → boolean</code></dt>
<dd>Repeatedly calls <code>eat</code> with the given argument,
until it fails. Returns true if any characters were eaten.</dd>
<dt><code><strong>eatSpace</strong>() → boolean</code></dt>
<dd>Shortcut for <code>eatWhile</code> when matching
white-space.</dd>
<dt><code><strong>skipToEnd</strong>()</code></dt>
<dd>Moves the position to the end of the line.</dd>
<dt><code><strong>skipTo</strong>(str: string) → boolean</code></dt>
<dd>Skips to the start of the next occurrence of the given string, if
found on the current line (doesn't advance the stream if the
string does not occur on the line). Returns true if the
string was found.</dd>
<dt><code><strong>match</strong>(pattern: string, ?consume: boolean, ?caseFold: boolean) → boolean</code></dt>
<dt><code><strong>match</strong>(pattern: regexp, ?consume: boolean) → array<string></code></dt>
<dd>Act like a
multi-character <code>eat</code>—if <code>consume</code> is true
or not given—or a look-ahead that doesn't update the stream
position—if it is false. <code>pattern</code> can be either a
string or a regular expression starting with <code>^</code>.
When it is a string, <code>caseFold</code> can be set to true to
make the match case-insensitive. When successfully matching a
regular expression, the returned value will be the array
returned by <code>match</code>, in case you need to extract
matched groups.</dd>
<dt><code><strong>backUp</strong>(n: integer)</code></dt>
<dd>Backs up the stream <code>n</code> characters. Backing it up
further than the start of the current token will cause things to
break, so be careful.</dd>
<dt><code><strong>column</strong>() → integer</code></dt>
<dd>Returns the column (taking into account tabs) at which the
current token starts.</dd>
<dt><code><strong>indentation</strong>() → integer</code></dt>
<dd>Tells you how far the current line has been indented, in
spaces. Corrects for tab characters.</dd>
<dt><code><strong>current</strong>() → string</code></dt>
<dd>Get the string between the start of the current token and
the current stream position.</dd>
<dt><code><strong>lookAhead</strong>(n: number) → ?string</code></dt>
<dd>Get the line <code>n</code> (>0) lines after the current
one, in order to scan ahead across line boundaries. Note that
you want to do this carefully, since looking far ahead will make
mode state caching much less effective.</dd>
<dt id="baseToken"><code><strong>baseToken</strong>() → ?{type: ?string, size: number}</code></dt>
<dd>Modes added
through <a href="#addOverlay"><code>addOverlay</code></a>
(and <em>only</em> such modes) can use this method to inspect
the current token produced by the underlying mode.</dd>
</dl>
<p id="blankLine">By default, blank lines are simply skipped when
tokenizing a document. For languages that have significant blank
lines, you can define
a <code><strong>blankLine</strong>(state)</code> method on your
mode that will get called whenever a blank line is passed over, so
that it can update the parser state.</p>
<p id="copyState">Because state object are mutated, and CodeMirror
needs to keep valid versions of a state around so that it can
restart a parse at any line, copies must be made of state objects.
The default algorithm used is that a new state object is created,
which gets all the properties of the old object. Any properties
which hold arrays get a copy of these arrays (since arrays tend to
be used as mutable stacks). When this is not correct, for example
because a mode mutates non-array properties of its state object, a
mode object should define
a <code><strong>copyState</strong></code> method, which is given a
state and should return a safe copy of that state.</p>
<p id="indent">If you want your mode to provide smart indentation
(through the <a href="#indentLine"><code>indentLine</code></a>
method and the <code>indentAuto</code>
and <code>newlineAndIndent</code> commands, to which keys can be
<a href="#option_extraKeys">bound</a>), you must define
an <code><strong>indent</strong>(state, textAfter)</code> method
on your mode object.</p>
<p>The indentation method should inspect the given state object,
and optionally the <code>textAfter</code> string, which contains
the text on the line that is being indented, and return an
integer, the amount of spaces to indent. It should usually take
the <a href="#option_indentUnit"><code>indentUnit</code></a>
option into account. An indentation method may
return <code>CodeMirror.Pass</code> to indicate that it
could not come up with a precise indentation.</p>
<p id="mode_comment">To work well with
the <a href="#addon_comment">commenting addon</a>, a mode may
define <code><strong>lineComment</strong></code> (string that
starts a line
comment), <code><strong>blockCommentStart</strong></code>, <code><strong>blockCommentEnd</strong></code>
(strings that start and end block comments),
and <code>blockCommentLead</code> (a string to put at the start of
continued lines in a block comment). All of these are
optional.</p>
<p id="electricChars">Finally, a mode may define either
an <code>electricChars</code> or an <code>electricInput</code>
property, which are used to automatically reindent the line when
certain patterns are typed and
the <a href="#option_electricChars"><code>electricChars</code></a>
option is enabled. <code>electricChars</code> may be a string, and
will trigger a reindent whenever one of the characters in that
string are typed. Often, it is more appropriate to
use <code>electricInput</code>, which should hold a regular
expression, and will trigger indentation when the part of the
line <em>before</em> the cursor matches the expression. It should
usually end with a <code>$</code> character, so that it only
matches when the indentation-changing pattern was just typed, not when something was
typed after the pattern.</p>
<p>So, to summarize, a mode <em>must</em> provide
a <code>token</code> method, and it <em>may</em>
provide <code>startState</code>, <code>copyState</code>,
and <code>indent</code> methods. For an example of a trivial mode,
see the <a href="../mode/diff/diff.js">diff mode</a>, for a more
involved example, see the <a href="../mode/clike/clike.js">C-like
mode</a>.</p>
<p>Sometimes, it is useful for modes to <em>nest</em>—to have one
mode delegate work to another mode. An example of this kind of
mode is the <a href="../mode/htmlmixed/htmlmixed.js">mixed-mode HTML
mode</a>. To implement such nesting, it is usually necessary to
create mode objects and copy states yourself. To create a mode
object, there are <code>CodeMirror.getMode(options,
parserConfig)</code>, where the first argument is a configuration
object as passed to the mode constructor function, and the second
argument is a mode specification as in
the <a href="#option_mode"><code>mode</code></a> option. To copy a
state object, call <code>CodeMirror.copyState(mode, state)</code>,
where <code>mode</code> is the mode that created the given
state.</p>
<p id="innerMode">In a nested mode, it is recommended to add an
extra method, <code><strong>innerMode</strong></code> which, given
a state object, returns a <code>{state, mode}</code> object with
the inner mode and its state for the current position. These are
used by utility scripts such as the <a href="#addon_closetag">tag
closer</a> to get context information. Use
the <code>CodeMirror.innerMode</code> helper function to, starting
from a mode and a state, recursively walk down to the innermost
mode and state.</p>
<p>To make indentation work properly in a nested parser, it is
advisable to give the <code>startState</code> method of modes that
are intended to be nested an optional argument that provides the
base indentation for the block of code. The JavaScript and CSS
parser do this, for example, to allow JavaScript and CSS code
inside the mixed-mode HTML mode to be properly indented.</p>
<p id="defineMIME">It is possible, and encouraged, to associate
your mode, or a certain configuration of your mode, with
a <a href="http://en.wikipedia.org/wiki/MIME">MIME</a> type. For
example, the JavaScript mode associates itself
with <code>text/javascript</code>, and its JSON variant
with <code>application/json</code>. To do this,
call <code><strong>CodeMirror.defineMIME</strong>(mime,
modeSpec)</code>, where <code>modeSpec</code> can be a string or
object specifying a mode, as in
the <a href="#option_mode"><code>mode</code></a> option.</p>
<p>If a mode specification wants to add some properties to the
resulting mode object, typically for use
with <a href="#getHelpers"><code>getHelpers</code></a>, it may
contain a <code>modeProps</code> property, which holds an object.
This object's properties will be copied to the actual mode
object.</p>
<p id="extendMode">Sometimes, it is useful to add or override mode
object properties from external code.
The <code><strong>CodeMirror.extendMode</strong></code> function
can be used to add properties to mode objects produced for a
specific mode. Its first argument is the name of the mode, its
second an object that specifies the properties that should be
added. This is mostly useful to add utilities that can later be
looked up through <a href="#getMode"><code>getMode</code></a>.</p>
</section>
<section id="vimapi">
<h2>VIM Mode API</h2>
<p>CodeMirror has a robust VIM mode that attempts to faithfully
emulate VIM's most useful features. It can be enabled by
including <a href="../keymap/vim.js"><code>keymap/vim.js</code>
</a> and setting the <code>keyMap</code> option to
<code>"vim"</code>.</p>
<h3 id="vimapi_configuration">Configuration</h3>
<p>VIM mode accepts configuration options for customizing
behavior at run time. These methods can be called at any time
and will affect all existing CodeMirror instances unless
specified otherwise. The methods are exposed on the
<code><strong>CodeMirror.Vim</strong></code> object.</p>
<dl>
<dt id="vimapi_setOption"><code><strong>setOption(name: string, value: any, ?cm: CodeMirror, ?cfg: object)</strong></code></dt>
<dd>Sets the value of a VIM option. <code>name</code> should
be the name of an option. If <code>cfg.scope</code> is not set
and <code>cm</code> is provided, then sets the global and
instance values of the option. Otherwise, sets either the
global or instance value of the option depending on whether
<code>cfg.scope</code> is <code>global</code> or
<code>local</code>.</dd>
<dt id="vimapi_getOption"><code><strong>getOption(name: string, ?cm: CodeMirror: ?cfg: object)</strong></code></dt>
<dd>Gets the current value of a VIM option. If
<code>cfg.scope</code> is not set and <code>cm</code> is
provided, then gets the instance value of the option, falling
back to the global value if not set. If <code>cfg.scope</code> is provided, then gets the <code>global</code> or
<code>local</code> value without checking the other.</dd>
<dt id="vimapi_map"><code><strong>map(lhs: string, rhs: string, ?context: string)</strong></code></dt>
<dd>Maps a key sequence to another key sequence. Implements
VIM's <code>:map</code> command. To map ; to : in VIM would be
<code><strong>:map ; :</strong></code>. That would translate to
<code><strong>CodeMirror.Vim.map(';', ':');</strong></code>.
The <code>context</code> can be <code>normal</code>,
<code>visual</code>, or <code>insert</code>, which correspond
to <code>:nmap</code>, <code>:vmap</code>, and
<code>:imap</code>
respectively.</dd>
<dt id="vimapi_mapCommand"><code><strong>mapCommand(keys: string, type: string, name: string, ?args: object, ?extra: object)</strong></code></dt>
<dd>Maps a key sequence to a <code>motion</code>,
<code>operator</code>, or <code>action</code> type command.
The args object is passed through to the command when it is
invoked by the provided key sequence.
<code>extras.context</code> can be <code>normal</code>,
<code>visual</code>, or <code>insert</code>, to map the key
sequence only in the corresponding mode.
<code>extras.isEdit</code> is applicable only to actions,
determining whether it is recorded for replay for the
<code>.</code> single-repeat command.
</dl>
<h3 id="vimapi_extending">Extending VIM</h3>
<p>CodeMirror's VIM mode implements a large subset of VIM's core
editing functionality. But since there's always more to be
desired, there is a set of APIs for extending VIM's
functionality. As with the configuration API, the methods are
exposed on <code><strong>CodeMirror.Vim</strong></code> and may
be called at any time.</p>
<dl>
<dt id="vimapi_defineOption"><code><strong>defineOption(name: string, default: any, type: string, ?aliases: array<string>, ?callback: function (?value: any, ?cm: CodeMirror) → ?any)</strong></code></dt>
<dd>Defines a VIM style option and makes it available to the
<code>:set</code> command. Type can be <code>boolean</code> or
<code>string</code>, used for validation and by
<code>:set</code> to determine which syntax to accept. If a
<code>callback</code> is passed in, VIM does not store the value of the
option itself, but instead uses the callback as a setter/getter. If the
first argument to the callback is <code>undefined</code>, then the
callback should return the value of the option. Otherwise, it should set
instead. Since VIM options have global and instance values, whether a
<code>CodeMirror</code> instance is passed in denotes whether the global
or local value should be used. Consequently, it's possible for the
callback to be called twice for a single <code>setOption</code> or
<code>getOption</code> call. Note that right now, VIM does not support
defining buffer-local options that do not have global values. If an
option should not have a global value, either always ignore the
<code>cm</code> parameter in the callback, or always pass in a
<code>cfg.scope</code> to <code>setOption</code> and
<code>getOption</code>.</dd>
<dt id="vimapi_defineMotion"><code><strong>defineMotion(name: string, fn: function(cm: CodeMirror, head: {line, ch}, ?motionArgs: object}) → {line, ch})</strong></code></dt>
<dd>Defines a motion command for VIM. The motion should return
the desired result position of the cursor. <code>head</code>
is the current position of the cursor. It can differ from
<code>cm.getCursor('head')</code> if VIM is in visual mode.
<code>motionArgs</code> is the object passed into
<strong><code>mapCommand()</code></strong>.</dd>
<dt id="vimapi_defineOperator"><strong><code>defineOperator(name: string, fn: function(cm: CodeMirror, ?operatorArgs: object, ranges: array<{anchor, head}>) → ?{line, ch})</code></strong></dt>
<dd>Defines an operator command, similar to <strong><code>
defineMotion</code></strong>. <code>ranges</code> is the range
of text the operator should operate on. If the cursor should
be set to a certain position after the operation finishes, it
can return a cursor object.</dd>
<dt id="vimapi_defineActon"><strong><code>defineAction(name: string, fn: function(cm: CodeMirror, ?actionArgs: object))</code></strong></dt>
<dd>Defines an action command, similar to
<strong><code>defineMotion</code></strong>. Action commands
can have arbitrary behavior, making them more flexible than
motions and operators, at the loss of orthogonality.</dd>
<dt id="vimapi_defineEx"><strong><code>defineEx(name: string, ?prefix: string, fn: function(cm: CodeMirror, ?params: object))</code></strong></dt>
<dd>Defines an Ex command, and maps it to <code>:name</code>.
If a prefix is provided, it, and any prefixed substring of the
<code>name</code> beginning with the <code>prefix</code> can
be used to invoke the command. If the <code>prefix</code> is
falsy, then <code>name</code> is used as the prefix. <code>
params.argString</code> contains the part of the prompted
string after the command name. <code>params.args</code> is
<code>params.argString</code> split by whitespace. If the
command was prefixed with a
<code><strong><a href="http://vimdoc.sourceforge.net/htmldoc/cmdline.html#cmdline-ranges">line range</a></strong></code>,
<code>params.line</code> and <code>params.lineEnd</code> will
be set.
</dl>
</section>
</article>
<script>setTimeout(function(){CodeMirror.colorize();}, 20);</script>
| {'content_hash': '447853272b1a4b2763fcb0f570232bf9', 'timestamp': '', 'source': 'github', 'line_count': 3592, 'max_line_length': 214, 'avg_line_length': 57.68485523385301, 'alnum_prop': 0.6738769521823903, 'repo_name': 'ugoertz/django-familio', 'id': '0a16b2e257d5164300ef579ba6ed1765dc1ce3df', 'size': '207469', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'notaro/static/codemirror/doc/manual.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '61023'}, {'name': 'HTML', 'bytes': '632961'}, {'name': 'JavaScript', 'bytes': '1352913'}, {'name': 'Makefile', 'bytes': '1735'}, {'name': 'Python', 'bytes': '532976'}, {'name': 'Shell', 'bytes': '352'}, {'name': 'TeX', 'bytes': '16522'}]} |
package com.dassmeta.passport.security.auth.impl;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cache.Cache;
import com.dassmeta.passport.security.auth.AuthConstants;
import com.dassmeta.passport.security.auth.AuthenticationProvider;
import com.dassmeta.passport.security.auth.entity.UserDetail;
import com.dassmeta.passport.security.auth.exception.AuthenticationException;
import com.dassmeta.passport.security.auth.service.CaptchaValidateService;
import com.dassmeta.passport.security.auth.service.UserDetailService;
import com.dassmeta.passport.security.context.SecurityContext;
public class AuthenticationProviderImpl implements AuthenticationProvider {
protected final Log logger = LogFactory.getLog(getClass());
private String loginURL;
private String defaultTargetURL;
private String authenticationFailureURL;
private String logoutSuccessURL;
private String passwordEncoder;
private boolean validateCaptcha;
private String parameters;
private boolean rememberURL = false;
private String loginIdKey = "specter_security_params_loginid";
private String passwordKey = "specter_security_params_password";
private Cache userDetailCache;
private UserDetailService userDetailService;
private CaptchaValidateService captchaValidateService;
public String getRequestURL() {
HttpServletRequest request = SecurityContext.getRequest();
String path = request.getServletPath();
if (StringUtils.isNotBlank(this.parameters)) {
String[] ps = StringUtils.split(this.parameters, ",");
StringBuffer sb = new StringBuffer();
String[] arrayOfString1;
int j = (arrayOfString1 = ps).length;
for (int i = 0; i < j; i++) {
String p = arrayOfString1[i];
String paramValue = request.getParameter(p);
if (StringUtils.isNotBlank(paramValue)) {
sb.append(p);
sb.append("=");
sb.append(paramValue);
sb.append("&");
}
}
if (StringUtils.isNotBlank(sb.toString())) {
sb.deleteCharAt(sb.length() - 1);
path = path + "?" + sb.toString();
}
}
return path;
}
public boolean authenticate() throws AuthenticationException {
// HttpSession session = SecurityContext.getSession();
// String loginId = (String) session.getAttribute("specter_session_login_key");
// if (StringUtils.isNotBlank(loginId)) {
// UserDetail detail = loadUserDetail(loginId);
// if (detail == null) {
// throw new UserNotExistException("could not load UserDetail.");
// }
// SecurityContext.setUserDetail(detail);
// return true;
// }
return false;
}
//
public boolean login() throws AuthenticationException {
// HttpServletRequest request = SecurityContext.getRequest();
// String loginId = request.getParameter(this.loginIdKey);
// String password = request.getParameter(this.passwordKey);
//
// String encode = PasswordEncodeUtils.encode(this.passwordEncoder, loginId, password);
//
// UserDetail detail = null;
// detail = this.userDetailService.loadUserDetailByLoginId(loginId);
// if (detail == null) {
// throw new UserNotExistException("user is not exist!");
// }
// if (!StringUtils.equals(detail.getLoginId(), loginId)) {
// throw new AuthenticationException("the request URL is wrong!");
// }
// if (!StringUtils.equals(encode, detail.getPassword())) {
// throw new PasswordErrorException("password is wrong!");
// }
// SecurityContext.setUserDetail(detail);
//
// HttpSession session = SecurityContext.getSession();
// session.setAttribute("specter_session_login_key", loginId);
//
// Element e = new Element(loginId, detail);
// this.userDetailCache.put(e);
//
return true;
}
//
public boolean logout() throws AuthenticationException {
// HttpSession session = SecurityContext.getSession();
//
// String loginId = (String) session.getAttribute("specter_session_login_key");
// if ((loginId != null) && (!"".equals(loginId))) {
// this.userDetailCache.remove(loginId);
// }
// Enumeration e = session.getAttributeNames();
// while (e.hasMoreElements()) {
// String atrr = (String) e.nextElement();
// session.removeAttribute(atrr);
// }
// session.invalidate();
return true;
}
//
public boolean validateCaptcha() throws AuthenticationException {
// boolean flag = false;
// if (this.captchaValidateService != null) {
// HttpServletRequest request = SecurityContext.getRequest();
// flag = this.captchaValidateService.vidateCaptcha(request);
// }
// if (!flag) {
// throw new CaptchaErrorException("the captcha validate wrong!");
// }
// return flag;
return false;
}
//
private UserDetail loadUserDetail(String loginId) {
// UserDetail detail = null;
// Element el = this.userDetailCache.get(loginId);
// if (el != null) {
// Serializable value = el.getValue();
// detail = (UserDetail) value;
// if (this.logger.isDebugEnabled()) {
// this.logger.debug("get the userDetail from the cache!");
// }
// }
// if (detail == null) {
// detail = this.userDetailService.loadUserDetailByLoginId(loginId);
// if (detail != null) {
// Element elt = new Element(loginId, detail);
// this.userDetailCache.put(elt);
// }
// }
// return detail;
return null;
}
public String getLoginURL() {
return this.loginURL;
}
public void setLoginURL(String loginURL) {
this.loginURL = loginURL;
}
public String getDefaultTargetURL() {
return this.defaultTargetURL;
}
public void setDefaultTargetURL(String defaultTargetURL) {
this.defaultTargetURL = defaultTargetURL;
}
public String getAuthenticationFailureURL() {
return this.authenticationFailureURL;
}
public void setAuthenticationFailureURL(String authenticationFailureURL) {
this.authenticationFailureURL = authenticationFailureURL;
}
public String getLogoutSuccessURL() {
return this.logoutSuccessURL;
}
public void setLogoutSuccessURL(String logoutSuccessURL) {
this.logoutSuccessURL = logoutSuccessURL;
}
public boolean isValidateCaptcha() {
return this.validateCaptcha;
}
public void setValidateCaptcha(boolean validateCaptcha) {
this.validateCaptcha = validateCaptcha;
}
public boolean isRememberURL() {
return this.rememberURL;
}
public void setRememberURL(boolean rememberURL) {
this.rememberURL = rememberURL;
}
public void setPasswordEncoder(String passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
public void setParameters(String parameters) {
this.parameters = parameters;
}
public void setLoginIdKey(String loginIdKey) {
this.loginIdKey = loginIdKey;
}
public void setPasswordKey(String passwordKey) {
this.passwordKey = passwordKey;
}
public void setUserDetailCache(Cache userDetailCache) {
this.userDetailCache = userDetailCache;
}
public void setUserDetailService(UserDetailService userDetailService) {
this.userDetailService = userDetailService;
}
public void setCaptchaValidateService(CaptchaValidateService captchaValidateService) {
this.captchaValidateService = captchaValidateService;
}
}
| {'content_hash': 'ccd05ac2f3670a557d7d02e89205d5de', 'timestamp': '', 'source': 'github', 'line_count': 232, 'max_line_length': 89, 'avg_line_length': 30.70689655172414, 'alnum_prop': 0.73385738349242, 'repo_name': 'dassmeta/passport', 'id': 'e3413521f20dc8f4f9e07e99d84b8a78f31a0b09', 'size': '7124', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'passport-security/src/main/java/com/dassmeta/passport/security/auth/impl/AuthenticationProviderImpl.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '491698'}, {'name': 'JavaScript', 'bytes': '87423'}]} |
package describe
import (
"fmt"
"io"
"sort"
"strconv"
"strings"
"text/tabwriter"
kapi "k8s.io/kubernetes/pkg/api"
kapierrors "k8s.io/kubernetes/pkg/api/errors"
"k8s.io/kubernetes/pkg/api/unversioned"
kclient "k8s.io/kubernetes/pkg/client/unversioned"
utilerrors "k8s.io/kubernetes/pkg/util/errors"
"k8s.io/kubernetes/pkg/util/sets"
osgraph "github.com/openshift/origin/pkg/api/graph"
"github.com/openshift/origin/pkg/api/graph/graphview"
kubeedges "github.com/openshift/origin/pkg/api/kubegraph"
kubeanalysis "github.com/openshift/origin/pkg/api/kubegraph/analysis"
kubegraph "github.com/openshift/origin/pkg/api/kubegraph/nodes"
buildapi "github.com/openshift/origin/pkg/build/api"
buildedges "github.com/openshift/origin/pkg/build/graph"
buildanalysis "github.com/openshift/origin/pkg/build/graph/analysis"
buildgraph "github.com/openshift/origin/pkg/build/graph/nodes"
"github.com/openshift/origin/pkg/client"
deployapi "github.com/openshift/origin/pkg/deploy/api"
deployedges "github.com/openshift/origin/pkg/deploy/graph"
deployanalysis "github.com/openshift/origin/pkg/deploy/graph/analysis"
deploygraph "github.com/openshift/origin/pkg/deploy/graph/nodes"
deployutil "github.com/openshift/origin/pkg/deploy/util"
imageapi "github.com/openshift/origin/pkg/image/api"
imageedges "github.com/openshift/origin/pkg/image/graph"
imagegraph "github.com/openshift/origin/pkg/image/graph/nodes"
projectapi "github.com/openshift/origin/pkg/project/api"
routeapi "github.com/openshift/origin/pkg/route/api"
routeedges "github.com/openshift/origin/pkg/route/graph"
routeanalysis "github.com/openshift/origin/pkg/route/graph/analysis"
routegraph "github.com/openshift/origin/pkg/route/graph/nodes"
"github.com/openshift/origin/pkg/util/errors"
"github.com/openshift/origin/pkg/util/parallel"
)
const ForbiddenListWarning = "Forbidden"
// ProjectStatusDescriber generates extended information about a Project
type ProjectStatusDescriber struct {
K kclient.Interface
C client.Interface
Server string
Suggest bool
LogsCommandName string
SecurityPolicyCommandFormat string
SetProbeCommandName string
}
func (d *ProjectStatusDescriber) MakeGraph(namespace string) (osgraph.Graph, sets.String, error) {
g := osgraph.New()
loaders := []GraphLoader{
&serviceLoader{namespace: namespace, lister: d.K},
&serviceAccountLoader{namespace: namespace, lister: d.K},
&secretLoader{namespace: namespace, lister: d.K},
&rcLoader{namespace: namespace, lister: d.K},
&podLoader{namespace: namespace, lister: d.K},
// TODO check swagger for feature enablement and selectively add bcLoader and buildLoader
// then remove errors.TolerateNotFoundError method.
&bcLoader{namespace: namespace, lister: d.C},
&buildLoader{namespace: namespace, lister: d.C},
&isLoader{namespace: namespace, lister: d.C},
&dcLoader{namespace: namespace, lister: d.C},
&routeLoader{namespace: namespace, lister: d.C},
}
loadingFuncs := []func() error{}
for _, loader := range loaders {
loadingFuncs = append(loadingFuncs, loader.Load)
}
forbiddenResources := sets.String{}
if errs := parallel.Run(loadingFuncs...); len(errs) > 0 {
actualErrors := []error{}
for _, err := range errs {
if kapierrors.IsForbidden(err) {
forbiddenErr := err.(*kapierrors.StatusError)
if (forbiddenErr.Status().Details != nil) && (len(forbiddenErr.Status().Details.Kind) > 0) {
forbiddenResources.Insert(forbiddenErr.Status().Details.Kind)
}
continue
}
actualErrors = append(actualErrors, err)
}
if len(actualErrors) > 0 {
return g, forbiddenResources, utilerrors.NewAggregate(actualErrors)
}
}
for _, loader := range loaders {
loader.AddToGraph(g)
}
kubeedges.AddAllExposedPodTemplateSpecEdges(g)
kubeedges.AddAllExposedPodEdges(g)
kubeedges.AddAllManagedByRCPodEdges(g)
kubeedges.AddAllRequestedServiceAccountEdges(g)
kubeedges.AddAllMountableSecretEdges(g)
kubeedges.AddAllMountedSecretEdges(g)
buildedges.AddAllInputOutputEdges(g)
buildedges.AddAllBuildEdges(g)
deployedges.AddAllTriggerEdges(g)
deployedges.AddAllDeploymentEdges(g)
imageedges.AddAllImageStreamRefEdges(g)
imageedges.AddAllImageStreamImageRefEdges(g)
routeedges.AddAllRouteEdges(g)
return g, forbiddenResources, nil
}
// Describe returns the description of a project
func (d *ProjectStatusDescriber) Describe(namespace, name string) (string, error) {
var f formatter = namespacedFormatter{}
g, forbiddenResources, err := d.MakeGraph(namespace)
if err != nil {
return "", err
}
allNamespaces := namespace == kapi.NamespaceAll
var project *projectapi.Project
if !allNamespaces {
p, err := d.C.Projects().Get(namespace)
if err != nil {
return "", err
}
project = p
f = namespacedFormatter{currentNamespace: namespace}
}
coveredNodes := graphview.IntSet{}
services, coveredByServices := graphview.AllServiceGroups(g, coveredNodes)
coveredNodes.Insert(coveredByServices.List()...)
standaloneDCs, coveredByDCs := graphview.AllDeploymentConfigPipelines(g, coveredNodes)
coveredNodes.Insert(coveredByDCs.List()...)
standaloneRCs, coveredByRCs := graphview.AllReplicationControllers(g, coveredNodes)
coveredNodes.Insert(coveredByRCs.List()...)
standaloneImages, coveredByImages := graphview.AllImagePipelinesFromBuildConfig(g, coveredNodes)
coveredNodes.Insert(coveredByImages.List()...)
standalonePods, coveredByPods := graphview.AllPods(g, coveredNodes)
coveredNodes.Insert(coveredByPods.List()...)
return tabbedString(func(out *tabwriter.Writer) error {
indent := " "
if allNamespaces {
fmt.Fprintf(out, describeAllProjectsOnServer(f, d.Server))
} else {
fmt.Fprintf(out, describeProjectAndServer(f, project, d.Server))
}
for _, service := range services {
if !service.Service.Found() {
continue
}
local := namespacedFormatter{currentNamespace: service.Service.Namespace}
var exposes []string
for _, routeNode := range service.ExposingRoutes {
exposes = append(exposes, describeRouteInServiceGroup(local, routeNode)...)
}
sort.Sort(exposedRoutes(exposes))
fmt.Fprintln(out)
printLines(out, "", 0, describeServiceInServiceGroup(f, service, exposes...)...)
for _, dcPipeline := range service.DeploymentConfigPipelines {
printLines(out, indent, 1, describeDeploymentInServiceGroup(local, dcPipeline)...)
}
rcNode:
for _, rcNode := range service.FulfillingRCs {
for _, coveredDC := range service.FulfillingDCs {
if deployedges.BelongsToDeploymentConfig(coveredDC.DeploymentConfig, rcNode.ReplicationController) {
continue rcNode
}
}
printLines(out, indent, 1, describeRCInServiceGroup(local, rcNode)...)
}
pod:
for _, podNode := range service.FulfillingPods {
// skip pods that have been displayed in a roll-up of RCs and DCs (by implicit usage of RCs)
for _, coveredRC := range service.FulfillingRCs {
if g.Edge(podNode, coveredRC) != nil {
continue pod
}
}
printLines(out, indent, 1, describePodInServiceGroup(local, podNode)...)
}
}
for _, standaloneDC := range standaloneDCs {
fmt.Fprintln(out)
printLines(out, indent, 0, describeDeploymentInServiceGroup(f, standaloneDC)...)
}
for _, standaloneImage := range standaloneImages {
fmt.Fprintln(out)
lines := describeStandaloneBuildGroup(f, standaloneImage, namespace)
lines = append(lines, describeAdditionalBuildDetail(standaloneImage.Build, standaloneImage.LastSuccessfulBuild, standaloneImage.LastUnsuccessfulBuild, standaloneImage.ActiveBuilds, standaloneImage.DestinationResolved, true)...)
printLines(out, indent, 0, lines...)
}
for _, standaloneRC := range standaloneRCs {
fmt.Fprintln(out)
printLines(out, indent, 0, describeRCInServiceGroup(f, standaloneRC.RC)...)
}
monopods, err := filterBoringPods(standalonePods)
if err != nil {
return err
}
for _, monopod := range monopods {
fmt.Fprintln(out)
printLines(out, indent, 0, describeMonopod(f, monopod.Pod)...)
}
allMarkers := osgraph.Markers{}
allMarkers = append(allMarkers, createForbiddenMarkers(forbiddenResources)...)
for _, scanner := range getMarkerScanners(d.LogsCommandName, d.SecurityPolicyCommandFormat, d.SetProbeCommandName) {
allMarkers = append(allMarkers, scanner(g, f)...)
}
// TODO: Provide an option to chase these hidden markers.
allMarkers = allMarkers.FilterByNamespace(namespace)
fmt.Fprintln(out)
sort.Stable(osgraph.ByKey(allMarkers))
sort.Stable(osgraph.ByNodeID(allMarkers))
errorMarkers := allMarkers.BySeverity(osgraph.ErrorSeverity)
errorSuggestions := 0
if len(errorMarkers) > 0 {
fmt.Fprintln(out, "Errors:")
for _, marker := range errorMarkers {
fmt.Fprintln(out, indent+"* "+marker.Message)
if len(marker.Suggestion) > 0 {
errorSuggestions++
if d.Suggest {
switch s := marker.Suggestion.String(); {
case strings.Contains(s, "\n"):
fmt.Fprintln(out)
for _, line := range strings.Split(s, "\n") {
fmt.Fprintln(out, indent+" "+line)
}
case len(s) > 0:
fmt.Fprintln(out, indent+" try: "+s)
}
}
}
}
}
warningMarkers := allMarkers.BySeverity(osgraph.WarningSeverity)
if len(warningMarkers) > 0 {
if d.Suggest {
fmt.Fprintln(out, "Warnings:")
}
for _, marker := range warningMarkers {
if d.Suggest {
fmt.Fprintln(out, indent+"* "+marker.Message)
switch s := marker.Suggestion.String(); {
case strings.Contains(s, "\n"):
fmt.Fprintln(out)
for _, line := range strings.Split(s, "\n") {
fmt.Fprintln(out, indent+" "+line)
}
case len(s) > 0:
fmt.Fprintln(out, indent+" try: "+s)
}
}
}
}
// We print errors by default and warnings if -v is used. If we get none,
// this would be an extra new line.
if len(errorMarkers) != 0 || (d.Suggest && len(warningMarkers) != 0) {
fmt.Fprintln(out)
}
errors, warnings := "", ""
if len(errorMarkers) == 1 {
errors = "1 error"
} else if len(errorMarkers) > 1 {
errors = fmt.Sprintf("%d errors", len(errorMarkers))
}
if len(warningMarkers) == 1 {
warnings = "1 warning"
} else if len(warningMarkers) > 1 {
warnings = fmt.Sprintf("%d warnings", len(warningMarkers))
}
switch {
case !d.Suggest && len(errorMarkers) > 0 && len(warningMarkers) > 0:
fmt.Fprintf(out, "%s and %s identified, use 'oc status -v' to see details.\n", errors, warnings)
case !d.Suggest && len(errorMarkers) > 0 && errorSuggestions > 0:
fmt.Fprintf(out, "%s identified, use 'oc status -v' to see details.\n", errors)
case !d.Suggest && len(warningMarkers) > 0:
fmt.Fprintf(out, "%s identified, use 'oc status -v' to see details.\n", warnings)
case (len(services) == 0) && (len(standaloneDCs) == 0) && (len(standaloneImages) == 0):
fmt.Fprintln(out, "You have no services, deployment configs, or build configs.")
fmt.Fprintln(out, "Run 'oc new-app' to create an application.")
default:
fmt.Fprintln(out, "View details with 'oc describe <resource>/<name>' or list everything with 'oc get all'.")
}
return nil
})
}
func createForbiddenMarkers(forbiddenResources sets.String) []osgraph.Marker {
markers := []osgraph.Marker{}
for forbiddenResource := range forbiddenResources {
markers = append(markers, osgraph.Marker{
Severity: osgraph.WarningSeverity,
Key: ForbiddenListWarning,
Message: fmt.Sprintf("Unable to list %s resources. Not all status relationships can be established.", forbiddenResource),
})
}
return markers
}
func getMarkerScanners(logsCommandName, securityPolicyCommandFormat, setProbeCommandName string) []osgraph.MarkerScanner {
return []osgraph.MarkerScanner{
func(g osgraph.Graph, f osgraph.Namer) []osgraph.Marker {
return kubeanalysis.FindRestartingPods(g, f, logsCommandName, securityPolicyCommandFormat)
},
kubeanalysis.FindDuelingReplicationControllers,
kubeanalysis.FindMissingSecrets,
buildanalysis.FindUnpushableBuildConfigs,
buildanalysis.FindCircularBuilds,
buildanalysis.FindPendingTags,
deployanalysis.FindDeploymentConfigTriggerErrors,
buildanalysis.FindMissingInputImageStreams,
func(g osgraph.Graph, f osgraph.Namer) []osgraph.Marker {
return deployanalysis.FindDeploymentConfigReadinessWarnings(g, f, setProbeCommandName)
},
routeanalysis.FindPortMappingIssues,
routeanalysis.FindMissingTLSTerminationType,
routeanalysis.FindPathBasedPassthroughRoutes,
routeanalysis.FindRouteAdmissionFailures,
routeanalysis.FindMissingRouter,
// We disable this feature by default and we don't have a capability detection for this sort of thing. Disable this check for now.
// kubeanalysis.FindUnmountableSecrets,
}
}
func printLines(out io.Writer, indent string, depth int, lines ...string) {
for i, s := range lines {
fmt.Fprintf(out, strings.Repeat(indent, depth))
if i != 0 {
fmt.Fprint(out, indent)
}
fmt.Fprintln(out, s)
}
}
func indentLines(indent string, lines ...string) []string {
ret := make([]string, 0, len(lines))
for _, line := range lines {
ret = append(ret, indent+line)
}
return ret
}
type formatter interface {
ResourceName(obj interface{}) string
}
func namespaceNameWithType(resource, name, namespace, defaultNamespace string, noNamespace bool) string {
if noNamespace || namespace == defaultNamespace || len(namespace) == 0 {
return resource + "/" + name
}
return resource + "/" + name + "[" + namespace + "]"
}
var namespaced = namespacedFormatter{}
type namespacedFormatter struct {
hideNamespace bool
currentNamespace string
}
func (f namespacedFormatter) ResourceName(obj interface{}) string {
switch t := obj.(type) {
case *kubegraph.PodNode:
return namespaceNameWithType("pod", t.Name, t.Namespace, f.currentNamespace, f.hideNamespace)
case *kubegraph.ServiceNode:
return namespaceNameWithType("svc", t.Name, t.Namespace, f.currentNamespace, f.hideNamespace)
case *kubegraph.SecretNode:
return namespaceNameWithType("secret", t.Name, t.Namespace, f.currentNamespace, f.hideNamespace)
case *kubegraph.ServiceAccountNode:
return namespaceNameWithType("sa", t.Name, t.Namespace, f.currentNamespace, f.hideNamespace)
case *kubegraph.ReplicationControllerNode:
return namespaceNameWithType("rc", t.Name, t.Namespace, f.currentNamespace, f.hideNamespace)
case *imagegraph.ImageStreamNode:
return namespaceNameWithType("is", t.ImageStream.Name, t.ImageStream.Namespace, f.currentNamespace, f.hideNamespace)
case *imagegraph.ImageStreamTagNode:
return namespaceNameWithType("istag", t.ImageStreamTag.Name, t.ImageStreamTag.Namespace, f.currentNamespace, f.hideNamespace)
case *imagegraph.ImageStreamImageNode:
return namespaceNameWithType("isi", t.ImageStreamImage.Name, t.ImageStreamImage.Namespace, f.currentNamespace, f.hideNamespace)
case *imagegraph.ImageNode:
return namespaceNameWithType("image", t.Image.Name, t.Image.Namespace, f.currentNamespace, f.hideNamespace)
case *buildgraph.BuildConfigNode:
return namespaceNameWithType("bc", t.BuildConfig.Name, t.BuildConfig.Namespace, f.currentNamespace, f.hideNamespace)
case *buildgraph.BuildNode:
return namespaceNameWithType("build", t.Build.Name, t.Build.Namespace, f.currentNamespace, f.hideNamespace)
case *deploygraph.DeploymentConfigNode:
return namespaceNameWithType("dc", t.DeploymentConfig.Name, t.DeploymentConfig.Namespace, f.currentNamespace, f.hideNamespace)
case *routegraph.RouteNode:
return namespaceNameWithType("route", t.Route.Name, t.Route.Namespace, f.currentNamespace, f.hideNamespace)
default:
return fmt.Sprintf("<unrecognized object: %#v>", obj)
}
}
func describeProjectAndServer(f formatter, project *projectapi.Project, server string) string {
if len(server) == 0 {
return fmt.Sprintf("In project %s on server %s\n", projectapi.DisplayNameAndNameForProject(project), server)
}
return fmt.Sprintf("In project %s on server %s\n", projectapi.DisplayNameAndNameForProject(project), server)
}
func describeAllProjectsOnServer(f formatter, server string) string {
if len(server) == 0 {
return "Showing all projects\n"
}
return fmt.Sprintf("Showing all projects on server %s\n", server)
}
func describeDeploymentInServiceGroup(f formatter, deploy graphview.DeploymentConfigPipeline) []string {
local := namespacedFormatter{currentNamespace: deploy.Deployment.Namespace}
includeLastPass := deploy.ActiveDeployment == nil
if len(deploy.Images) == 1 {
format := "%s deploys %s %s"
if deploy.Deployment.Spec.Test {
format = "%s test deploys %s %s"
}
lines := []string{fmt.Sprintf(format, f.ResourceName(deploy.Deployment), describeImageInPipeline(local, deploy.Images[0], deploy.Deployment.Namespace), describeDeploymentConfigTrigger(deploy.Deployment.DeploymentConfig))}
if len(lines[0]) > 120 && strings.Contains(lines[0], " <- ") {
segments := strings.SplitN(lines[0], " <- ", 2)
lines[0] = segments[0] + " <-"
lines = append(lines, segments[1])
}
lines = append(lines, indentLines(" ", describeAdditionalBuildDetail(deploy.Images[0].Build, deploy.Images[0].LastSuccessfulBuild, deploy.Images[0].LastUnsuccessfulBuild, deploy.Images[0].ActiveBuilds, deploy.Images[0].DestinationResolved, includeLastPass)...)...)
lines = append(lines, describeDeployments(local, deploy.Deployment, deploy.ActiveDeployment, deploy.InactiveDeployments, 3)...)
return lines
}
format := "%s deploys %s"
if deploy.Deployment.Spec.Test {
format = "%s test deploys %s"
}
lines := []string{fmt.Sprintf(format, f.ResourceName(deploy.Deployment), describeDeploymentConfigTrigger(deploy.Deployment.DeploymentConfig))}
for _, image := range deploy.Images {
lines = append(lines, describeImageInPipeline(local, image, deploy.Deployment.Namespace))
lines = append(lines, indentLines(" ", describeAdditionalBuildDetail(image.Build, image.LastSuccessfulBuild, image.LastUnsuccessfulBuild, image.ActiveBuilds, image.DestinationResolved, includeLastPass)...)...)
lines = append(lines, describeDeployments(local, deploy.Deployment, deploy.ActiveDeployment, deploy.InactiveDeployments, 3)...)
}
return lines
}
func describeRCInServiceGroup(f formatter, rcNode *kubegraph.ReplicationControllerNode) []string {
if rcNode.ReplicationController.Spec.Template == nil {
return []string{}
}
images := []string{}
for _, container := range rcNode.ReplicationController.Spec.Template.Spec.Containers {
images = append(images, container.Image)
}
lines := []string{fmt.Sprintf("%s runs %s", f.ResourceName(rcNode), strings.Join(images, ", "))}
lines = append(lines, describeRCStatus(rcNode.ReplicationController))
return lines
}
func describePodInServiceGroup(f formatter, podNode *kubegraph.PodNode) []string {
images := []string{}
for _, container := range podNode.Pod.Spec.Containers {
images = append(images, container.Image)
}
lines := []string{fmt.Sprintf("%s runs %s", f.ResourceName(podNode), strings.Join(images, ", "))}
return lines
}
func describeMonopod(f formatter, podNode *kubegraph.PodNode) []string {
images := []string{}
for _, container := range podNode.Pod.Spec.Containers {
images = append(images, container.Image)
}
lines := []string{fmt.Sprintf("%s runs %s", f.ResourceName(podNode), strings.Join(images, ", "))}
return lines
}
// exposedRoutes orders strings by their leading prefix (https:// -> http:// other prefixes), then by
// the shortest distance up to the first space (indicating a break), then alphabetically:
//
// https://test.com
// https://www.test.com
// http://t.com
// other string
//
type exposedRoutes []string
func (e exposedRoutes) Len() int { return len(e) }
func (e exposedRoutes) Swap(i, j int) { e[i], e[j] = e[j], e[i] }
func (e exposedRoutes) Less(i, j int) bool {
a, b := e[i], e[j]
prefixA, prefixB := strings.HasPrefix(a, "https://"), strings.HasPrefix(b, "https://")
switch {
case prefixA && !prefixB:
return true
case !prefixA && prefixB:
return false
case !prefixA && !prefixB:
prefixA, prefixB = strings.HasPrefix(a, "http://"), strings.HasPrefix(b, "http://")
switch {
case prefixA && !prefixB:
return true
case !prefixA && prefixB:
return false
case !prefixA && !prefixB:
return a < b
default:
a, b = a[7:], b[7:]
}
default:
a, b = a[8:], b[8:]
}
lA, lB := strings.Index(a, " "), strings.Index(b, " ")
if lA == -1 {
lA = len(a)
}
if lB == -1 {
lB = len(b)
}
switch {
case lA < lB:
return true
case lA > lB:
return false
default:
return a < b
}
}
func extractRouteInfo(route *routeapi.Route) (requested bool, other []string, errors []string) {
reasons := sets.NewString()
for _, ingress := range route.Status.Ingress {
exact := route.Spec.Host == ingress.Host
switch status, condition := routeapi.IngressConditionStatus(&ingress, routeapi.RouteAdmitted); status {
case kapi.ConditionFalse:
reasons.Insert(condition.Reason)
default:
if exact {
requested = true
} else {
other = append(other, ingress.Host)
}
}
}
return requested, other, reasons.List()
}
func describeRouteExposed(host string, route *routeapi.Route, errors bool) string {
var trailer string
if errors {
trailer = " (!)"
}
var prefix string
switch {
case route.Spec.TLS == nil:
prefix = fmt.Sprintf("http://%s", host)
case route.Spec.TLS.Termination == routeapi.TLSTerminationPassthrough:
prefix = fmt.Sprintf("https://%s (passthrough)", host)
case route.Spec.TLS.Termination == routeapi.TLSTerminationReencrypt:
prefix = fmt.Sprintf("https://%s (reencrypt)", host)
case route.Spec.TLS.Termination != routeapi.TLSTerminationEdge:
// future proof against other types of TLS termination being added
prefix = fmt.Sprintf("https://%s", host)
case route.Spec.TLS.InsecureEdgeTerminationPolicy == routeapi.InsecureEdgeTerminationPolicyRedirect:
prefix = fmt.Sprintf("https://%s (redirects)", host)
case route.Spec.TLS.InsecureEdgeTerminationPolicy == routeapi.InsecureEdgeTerminationPolicyAllow:
prefix = fmt.Sprintf("https://%s (and http)", host)
default:
prefix = fmt.Sprintf("https://%s", host)
}
if route.Spec.Port != nil && len(route.Spec.Port.TargetPort.String()) > 0 {
return fmt.Sprintf("%s to pod port %s%s", prefix, route.Spec.Port.TargetPort.String(), trailer)
}
return fmt.Sprintf("%s%s", prefix, trailer)
}
func describeRouteInServiceGroup(f formatter, routeNode *routegraph.RouteNode) []string {
// markers should cover printing information about admission failure
requested, other, errors := extractRouteInfo(routeNode.Route)
var lines []string
if requested {
lines = append(lines, describeRouteExposed(routeNode.Spec.Host, routeNode.Route, len(errors) > 0))
}
for _, s := range other {
lines = append(lines, describeRouteExposed(s, routeNode.Route, len(errors) > 0))
}
if len(lines) == 0 {
switch {
case len(errors) >= 1:
// router rejected the output
lines = append(lines, fmt.Sprintf("%s not accepted: %s", f.ResourceName(routeNode), errors[0]))
case len(routeNode.Spec.Host) == 0:
// no errors or output, likely no router running and no default domain
lines = append(lines, fmt.Sprintf("%s has no host set", f.ResourceName(routeNode)))
case len(routeNode.Status.Ingress) == 0:
// host set, but no ingress, an older legacy router
lines = append(lines, describeRouteExposed(routeNode.Spec.Host, routeNode.Route, false))
default:
// multiple conditions but no host exposed, use the generic legacy output
lines = append(lines, fmt.Sprintf("exposed as %s by %s", routeNode.Spec.Host, f.ResourceName(routeNode)))
}
}
return lines
}
func describeDeploymentConfigTrigger(dc *deployapi.DeploymentConfig) string {
if len(dc.Spec.Triggers) == 0 {
return "(manual)"
}
return ""
}
func describeStandaloneBuildGroup(f formatter, pipeline graphview.ImagePipeline, namespace string) []string {
switch {
case pipeline.Build != nil:
lines := []string{describeBuildInPipeline(f, pipeline.Build.BuildConfig, pipeline.BaseImage)}
if pipeline.Image != nil {
lines = append(lines, fmt.Sprintf("pushes to %s", describeImageTagInPipeline(f, pipeline.Image, namespace)))
}
return lines
case pipeline.Image != nil:
return []string{describeImageTagInPipeline(f, pipeline.Image, namespace)}
default:
return []string{"<unknown>"}
}
}
func describeImageInPipeline(f formatter, pipeline graphview.ImagePipeline, namespace string) string {
switch {
case pipeline.Image != nil && pipeline.Build != nil:
return fmt.Sprintf("%s <- %s", describeImageTagInPipeline(f, pipeline.Image, namespace), describeBuildInPipeline(f, pipeline.Build.BuildConfig, pipeline.BaseImage))
case pipeline.Image != nil:
return describeImageTagInPipeline(f, pipeline.Image, namespace)
case pipeline.Build != nil:
return describeBuildInPipeline(f, pipeline.Build.BuildConfig, pipeline.BaseImage)
default:
return "<unknown>"
}
}
func describeImageTagInPipeline(f formatter, image graphview.ImageTagLocation, namespace string) string {
switch t := image.(type) {
case *imagegraph.ImageStreamTagNode:
if t.ImageStreamTag.Namespace != namespace {
return image.ImageSpec()
}
return f.ResourceName(t)
default:
return image.ImageSpec()
}
}
func describeBuildInPipeline(f formatter, build *buildapi.BuildConfig, baseImage graphview.ImageTagLocation) string {
switch {
case build.Spec.Strategy.DockerStrategy != nil:
// TODO: handle case where no source repo
source, ok := describeSourceInPipeline(&build.Spec.Source)
if !ok {
return fmt.Sprintf("bc/%s unconfigured docker build - no source set", build.Name)
}
return fmt.Sprintf("bc/%s docker build of %s", build.Name, source)
case build.Spec.Strategy.SourceStrategy != nil:
source, ok := describeSourceInPipeline(&build.Spec.Source)
if !ok {
return fmt.Sprintf("bc/%s unconfigured source build", build.Name)
}
if baseImage == nil {
return fmt.Sprintf("bc/%s %s; no image set", build.Name, source)
}
return fmt.Sprintf("bc/%s builds %s with %s", build.Name, source, baseImage.ImageSpec())
case build.Spec.Strategy.CustomStrategy != nil:
source, ok := describeSourceInPipeline(&build.Spec.Source)
if !ok {
return fmt.Sprintf("bc/%s custom build ", build.Name)
}
return fmt.Sprintf("bc/%s custom build of %s", build.Name, source)
default:
return fmt.Sprintf("bc/%s unrecognized build", build.Name)
}
}
func describeAdditionalBuildDetail(build *buildgraph.BuildConfigNode, lastSuccessfulBuild *buildgraph.BuildNode, lastUnsuccessfulBuild *buildgraph.BuildNode, activeBuilds []*buildgraph.BuildNode, pushTargetResolved bool, includeSuccess bool) []string {
if build == nil {
return nil
}
out := []string{}
passTime := unversioned.Time{}
if lastSuccessfulBuild != nil {
passTime = buildTimestamp(lastSuccessfulBuild.Build)
}
failTime := unversioned.Time{}
if lastUnsuccessfulBuild != nil {
failTime = buildTimestamp(lastUnsuccessfulBuild.Build)
}
lastTime := failTime
if passTime.After(failTime.Time) {
lastTime = passTime
}
// display the last successful build if specifically requested or we're going to display an active build for context
if lastSuccessfulBuild != nil && (includeSuccess || len(activeBuilds) > 0) {
out = append(out, describeBuildPhase(lastSuccessfulBuild.Build, &passTime, build.BuildConfig.Name, pushTargetResolved))
}
if passTime.Before(failTime) {
out = append(out, describeBuildPhase(lastUnsuccessfulBuild.Build, &failTime, build.BuildConfig.Name, pushTargetResolved))
}
if len(activeBuilds) > 0 {
activeOut := []string{}
for i := range activeBuilds {
activeOut = append(activeOut, describeBuildPhase(activeBuilds[i].Build, nil, build.BuildConfig.Name, pushTargetResolved))
}
if buildTimestamp(activeBuilds[0].Build).Before(lastTime) {
out = append(out, activeOut...)
} else {
out = append(activeOut, out...)
}
}
if len(out) == 0 && lastSuccessfulBuild == nil {
out = append(out, "not built yet")
}
return out
}
func describeBuildPhase(build *buildapi.Build, t *unversioned.Time, parentName string, pushTargetResolved bool) string {
imageStreamFailure := ""
// if we're using an image stream and that image stream is the internal registry and that registry doesn't exist
if (build.Spec.Output.To != nil) && !pushTargetResolved {
imageStreamFailure = " (can't push to image)"
}
if t == nil {
ts := buildTimestamp(build)
t = &ts
}
var time string
if t.IsZero() {
time = "<unknown>"
} else {
time = strings.ToLower(formatRelativeTime(t.Time))
}
buildIdentification := fmt.Sprintf("build/%s", build.Name)
prefix := parentName + "-"
if strings.HasPrefix(build.Name, prefix) {
suffix := build.Name[len(prefix):]
if buildNumber, err := strconv.Atoi(suffix); err == nil {
buildIdentification = fmt.Sprintf("build #%d", buildNumber)
}
}
revision := describeSourceRevision(build.Spec.Revision)
if len(revision) != 0 {
revision = fmt.Sprintf(" - %s", revision)
}
switch build.Status.Phase {
case buildapi.BuildPhaseComplete:
return fmt.Sprintf("%s succeeded %s ago%s%s", buildIdentification, time, revision, imageStreamFailure)
case buildapi.BuildPhaseError:
return fmt.Sprintf("%s stopped with an error %s ago%s%s", buildIdentification, time, revision, imageStreamFailure)
case buildapi.BuildPhaseFailed:
return fmt.Sprintf("%s failed %s ago%s%s", buildIdentification, time, revision, imageStreamFailure)
default:
status := strings.ToLower(string(build.Status.Phase))
return fmt.Sprintf("%s %s for %s%s%s", buildIdentification, status, time, revision, imageStreamFailure)
}
}
func describeSourceRevision(rev *buildapi.SourceRevision) string {
if rev == nil {
return ""
}
switch {
case rev.Git != nil:
author := describeSourceControlUser(rev.Git.Author)
if len(author) == 0 {
author = describeSourceControlUser(rev.Git.Committer)
}
if len(author) != 0 {
author = fmt.Sprintf(" (%s)", author)
}
commit := rev.Git.Commit
if len(commit) > 7 {
commit = commit[:7]
}
return fmt.Sprintf("%s: %s%s", commit, rev.Git.Message, author)
default:
return ""
}
}
func describeSourceControlUser(user buildapi.SourceControlUser) string {
if len(user.Name) == 0 {
return user.Email
}
if len(user.Email) == 0 {
return user.Name
}
return fmt.Sprintf("%s <%s>", user.Name, user.Email)
}
func buildTimestamp(build *buildapi.Build) unversioned.Time {
if build == nil {
return unversioned.Time{}
}
if !build.Status.CompletionTimestamp.IsZero() {
return *build.Status.CompletionTimestamp
}
if !build.Status.StartTimestamp.IsZero() {
return *build.Status.StartTimestamp
}
return build.CreationTimestamp
}
func describeSourceInPipeline(source *buildapi.BuildSource) (string, bool) {
switch {
case source.Git != nil:
if len(source.Git.Ref) == 0 {
return source.Git.URI, true
}
return fmt.Sprintf("%s#%s", source.Git.URI, source.Git.Ref), true
case source.Dockerfile != nil:
return "Dockerfile", true
case source.Binary != nil:
return "uploaded code", true
case len(source.Images) > 0:
return "contents in other images", true
}
return "", false
}
func describeDeployments(f formatter, dcNode *deploygraph.DeploymentConfigNode, activeDeployment *kubegraph.ReplicationControllerNode, inactiveDeployments []*kubegraph.ReplicationControllerNode, count int) []string {
if dcNode == nil {
return nil
}
out := []string{}
deploymentsToPrint := append([]*kubegraph.ReplicationControllerNode{}, inactiveDeployments...)
if activeDeployment == nil {
on, auto := describeDeploymentConfigTriggers(dcNode.DeploymentConfig)
if dcNode.DeploymentConfig.Status.LatestVersion == 0 {
out = append(out, fmt.Sprintf("deployment #1 waiting %s", on))
} else if auto {
out = append(out, fmt.Sprintf("deployment #%d pending %s", dcNode.DeploymentConfig.Status.LatestVersion, on))
}
// TODO: detect new image available?
} else {
deploymentsToPrint = append([]*kubegraph.ReplicationControllerNode{activeDeployment}, inactiveDeployments...)
}
for i, deployment := range deploymentsToPrint {
out = append(out, describeDeploymentStatus(deployment.ReplicationController, i == 0, dcNode.DeploymentConfig.Spec.Test))
switch {
case count == -1:
if deployutil.DeploymentStatusFor(deployment) == deployapi.DeploymentStatusComplete {
return out
}
default:
if i+1 >= count {
return out
}
}
}
return out
}
func describeDeploymentStatus(deploy *kapi.ReplicationController, first, test bool) string {
timeAt := strings.ToLower(formatRelativeTime(deploy.CreationTimestamp.Time))
status := deployutil.DeploymentStatusFor(deploy)
version := deployutil.DeploymentVersionFor(deploy)
switch status {
case deployapi.DeploymentStatusFailed:
reason := deployutil.DeploymentStatusReasonFor(deploy)
if len(reason) > 0 {
reason = fmt.Sprintf(": %s", reason)
}
// TODO: encode fail time in the rc
return fmt.Sprintf("deployment #%d failed %s ago%s%s", version, timeAt, reason, describePodSummaryInline(deploy, false))
case deployapi.DeploymentStatusComplete:
// TODO: pod status output
if test {
return fmt.Sprintf("test deployment #%d deployed %s ago", version, timeAt)
}
return fmt.Sprintf("deployment #%d deployed %s ago%s", version, timeAt, describePodSummaryInline(deploy, first))
case deployapi.DeploymentStatusRunning:
format := "deployment #%d running for %s%s"
if test {
format = "test deployment #%d running for %s%s"
}
return fmt.Sprintf(format, version, timeAt, describePodSummaryInline(deploy, false))
default:
return fmt.Sprintf("deployment #%d %s %s ago%s", version, strings.ToLower(string(status)), timeAt, describePodSummaryInline(deploy, false))
}
}
func describeRCStatus(rc *kapi.ReplicationController) string {
timeAt := strings.ToLower(formatRelativeTime(rc.CreationTimestamp.Time))
return fmt.Sprintf("rc/%s created %s ago%s", rc.Name, timeAt, describePodSummaryInline(rc, false))
}
func describePodSummaryInline(rc *kapi.ReplicationController, includeEmpty bool) string {
s := describePodSummary(rc, includeEmpty)
if len(s) == 0 {
return s
}
change := ""
desired := rc.Spec.Replicas
switch {
case desired < rc.Status.Replicas:
change = fmt.Sprintf(" reducing to %d", desired)
case desired > rc.Status.Replicas:
change = fmt.Sprintf(" growing to %d", desired)
}
return fmt.Sprintf(" - %s%s", s, change)
}
func describePodSummary(rc *kapi.ReplicationController, includeEmpty bool) string {
actual, requested := rc.Status.Replicas, rc.Spec.Replicas
if actual == requested {
switch {
case actual == 0:
if !includeEmpty {
return ""
}
return "0 pods"
case actual > 1:
return fmt.Sprintf("%d pods", actual)
default:
return "1 pod"
}
}
return fmt.Sprintf("%d/%d pods", actual, requested)
}
func describeDeploymentConfigTriggers(config *deployapi.DeploymentConfig) (string, bool) {
hasConfig, hasImage := false, false
for _, t := range config.Spec.Triggers {
switch t.Type {
case deployapi.DeploymentTriggerOnConfigChange:
hasConfig = true
case deployapi.DeploymentTriggerOnImageChange:
hasImage = true
}
}
switch {
case hasConfig && hasImage:
return "on image or update", true
case hasConfig:
return "on update", true
case hasImage:
return "on image", true
default:
return "for manual", false
}
}
func describeServiceInServiceGroup(f formatter, svc graphview.ServiceGroup, exposed ...string) []string {
spec := svc.Service.Spec
ip := spec.ClusterIP
port := describeServicePorts(spec)
switch {
case len(exposed) > 1:
return append([]string{fmt.Sprintf("%s (%s)", exposed[0], f.ResourceName(svc.Service))}, exposed[1:]...)
case len(exposed) == 1:
return []string{fmt.Sprintf("%s (%s)", exposed[0], f.ResourceName(svc.Service))}
case spec.Type == kapi.ServiceTypeNodePort:
return []string{fmt.Sprintf("%s (all nodes)%s", f.ResourceName(svc.Service), port)}
case ip == "None":
return []string{fmt.Sprintf("%s (headless)%s", f.ResourceName(svc.Service), port)}
case len(ip) == 0:
return []string{fmt.Sprintf("%s <initializing>%s", f.ResourceName(svc.Service), port)}
default:
return []string{fmt.Sprintf("%s - %s%s", f.ResourceName(svc.Service), ip, port)}
}
}
func portOrNodePort(spec kapi.ServiceSpec, port kapi.ServicePort) string {
switch {
case spec.Type != kapi.ServiceTypeNodePort:
return strconv.Itoa(port.Port)
case port.NodePort == 0:
return "<initializing>"
default:
return strconv.Itoa(port.NodePort)
}
}
func describeServicePorts(spec kapi.ServiceSpec) string {
switch len(spec.Ports) {
case 0:
return " no ports"
case 1:
port := portOrNodePort(spec, spec.Ports[0])
if spec.Ports[0].TargetPort.String() == "0" || spec.ClusterIP == kapi.ClusterIPNone || port == spec.Ports[0].TargetPort.String() {
return fmt.Sprintf(":%s", port)
}
return fmt.Sprintf(":%s -> %s", port, spec.Ports[0].TargetPort.String())
default:
pairs := []string{}
for _, port := range spec.Ports {
externalPort := portOrNodePort(spec, port)
if port.TargetPort.String() == "0" || spec.ClusterIP == kapi.ClusterIPNone {
pairs = append(pairs, externalPort)
continue
}
if port.Port == int(port.TargetPort.IntVal) {
pairs = append(pairs, port.TargetPort.String())
} else {
pairs = append(pairs, fmt.Sprintf("%s->%s", externalPort, port.TargetPort.String()))
}
}
return " ports " + strings.Join(pairs, ", ")
}
}
func filterBoringPods(pods []graphview.Pod) ([]graphview.Pod, error) {
monopods := []graphview.Pod{}
for _, pod := range pods {
actualPod, ok := pod.Pod.Object().(*kapi.Pod)
if !ok {
continue
}
meta, err := kapi.ObjectMetaFor(actualPod)
if err != nil {
return nil, err
}
_, isDeployerPod := meta.Labels[deployapi.DeployerPodForDeploymentLabel]
_, isBuilderPod := meta.Annotations[buildapi.BuildAnnotation]
isFinished := actualPod.Status.Phase == kapi.PodSucceeded || actualPod.Status.Phase == kapi.PodFailed
if isDeployerPod || isBuilderPod || isFinished {
continue
}
monopods = append(monopods, pod)
}
return monopods, nil
}
// GraphLoader is a stateful interface that provides methods for building the nodes of a graph
type GraphLoader interface {
// Load is responsible for gathering and saving the objects this GraphLoader should AddToGraph
Load() error
// AddToGraph
AddToGraph(g osgraph.Graph) error
}
type rcLoader struct {
namespace string
lister kclient.ReplicationControllersNamespacer
items []kapi.ReplicationController
}
func (l *rcLoader) Load() error {
list, err := l.lister.ReplicationControllers(l.namespace).List(kapi.ListOptions{})
if err != nil {
return err
}
l.items = list.Items
return nil
}
func (l *rcLoader) AddToGraph(g osgraph.Graph) error {
for i := range l.items {
kubegraph.EnsureReplicationControllerNode(g, &l.items[i])
}
return nil
}
type serviceLoader struct {
namespace string
lister kclient.ServicesNamespacer
items []kapi.Service
}
func (l *serviceLoader) Load() error {
list, err := l.lister.Services(l.namespace).List(kapi.ListOptions{})
if err != nil {
return err
}
l.items = list.Items
return nil
}
func (l *serviceLoader) AddToGraph(g osgraph.Graph) error {
for i := range l.items {
kubegraph.EnsureServiceNode(g, &l.items[i])
}
return nil
}
type podLoader struct {
namespace string
lister kclient.PodsNamespacer
items []kapi.Pod
}
func (l *podLoader) Load() error {
list, err := l.lister.Pods(l.namespace).List(kapi.ListOptions{})
if err != nil {
return err
}
l.items = list.Items
return nil
}
func (l *podLoader) AddToGraph(g osgraph.Graph) error {
for i := range l.items {
kubegraph.EnsurePodNode(g, &l.items[i])
}
return nil
}
type serviceAccountLoader struct {
namespace string
lister kclient.ServiceAccountsNamespacer
items []kapi.ServiceAccount
}
func (l *serviceAccountLoader) Load() error {
list, err := l.lister.ServiceAccounts(l.namespace).List(kapi.ListOptions{})
if err != nil {
return err
}
l.items = list.Items
return nil
}
func (l *serviceAccountLoader) AddToGraph(g osgraph.Graph) error {
for i := range l.items {
kubegraph.EnsureServiceAccountNode(g, &l.items[i])
}
return nil
}
type secretLoader struct {
namespace string
lister kclient.SecretsNamespacer
items []kapi.Secret
}
func (l *secretLoader) Load() error {
list, err := l.lister.Secrets(l.namespace).List(kapi.ListOptions{})
if err != nil {
return err
}
l.items = list.Items
return nil
}
func (l *secretLoader) AddToGraph(g osgraph.Graph) error {
for i := range l.items {
kubegraph.EnsureSecretNode(g, &l.items[i])
}
return nil
}
type isLoader struct {
namespace string
lister client.ImageStreamsNamespacer
items []imageapi.ImageStream
}
func (l *isLoader) Load() error {
list, err := l.lister.ImageStreams(l.namespace).List(kapi.ListOptions{})
if err != nil {
return err
}
l.items = list.Items
return nil
}
func (l *isLoader) AddToGraph(g osgraph.Graph) error {
for i := range l.items {
imagegraph.EnsureImageStreamNode(g, &l.items[i])
imagegraph.EnsureAllImageStreamTagNodes(g, &l.items[i])
}
return nil
}
type dcLoader struct {
namespace string
lister client.DeploymentConfigsNamespacer
items []deployapi.DeploymentConfig
}
func (l *dcLoader) Load() error {
list, err := l.lister.DeploymentConfigs(l.namespace).List(kapi.ListOptions{})
if err != nil {
return err
}
l.items = list.Items
return nil
}
func (l *dcLoader) AddToGraph(g osgraph.Graph) error {
for i := range l.items {
deploygraph.EnsureDeploymentConfigNode(g, &l.items[i])
}
return nil
}
type bcLoader struct {
namespace string
lister client.BuildConfigsNamespacer
items []buildapi.BuildConfig
}
func (l *bcLoader) Load() error {
list, err := l.lister.BuildConfigs(l.namespace).List(kapi.ListOptions{})
if err != nil {
return errors.TolerateNotFoundError(err)
}
l.items = list.Items
return nil
}
func (l *bcLoader) AddToGraph(g osgraph.Graph) error {
for i := range l.items {
buildgraph.EnsureBuildConfigNode(g, &l.items[i])
}
return nil
}
type buildLoader struct {
namespace string
lister client.BuildsNamespacer
items []buildapi.Build
}
func (l *buildLoader) Load() error {
list, err := l.lister.Builds(l.namespace).List(kapi.ListOptions{})
if err != nil {
return errors.TolerateNotFoundError(err)
}
l.items = list.Items
return nil
}
func (l *buildLoader) AddToGraph(g osgraph.Graph) error {
for i := range l.items {
buildgraph.EnsureBuildNode(g, &l.items[i])
}
return nil
}
type routeLoader struct {
namespace string
lister client.RoutesNamespacer
items []routeapi.Route
}
func (l *routeLoader) Load() error {
list, err := l.lister.Routes(l.namespace).List(kapi.ListOptions{})
if err != nil {
return err
}
l.items = list.Items
return nil
}
func (l *routeLoader) AddToGraph(g osgraph.Graph) error {
for i := range l.items {
routegraph.EnsureRouteNode(g, &l.items[i])
}
return nil
}
| {'content_hash': '0808c251d468706b4df88a527e813f25', 'timestamp': '', 'source': 'github', 'line_count': 1344, 'max_line_length': 267, 'avg_line_length': 32.010416666666664, 'alnum_prop': 0.7211891590349123, 'repo_name': 'asiainfoLDP/datafactory', 'id': 'c7abc4726f06e260f540f6464185f162f76e8be0', 'size': '43022', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'pkg/cmd/cli/describe/projectstatus.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '921'}, {'name': 'CSS', 'bytes': '105562'}, {'name': 'DIGITAL Command Language', 'bytes': '117'}, {'name': 'Go', 'bytes': '9833536'}, {'name': 'Groff', 'bytes': '2049'}, {'name': 'HTML', 'bytes': '407467'}, {'name': 'JavaScript', 'bytes': '676038'}, {'name': 'Makefile', 'bytes': '4149'}, {'name': 'Python', 'bytes': '14204'}, {'name': 'Ruby', 'bytes': '242'}, {'name': 'Shell', 'bytes': '1238954'}]} |
<?php
namespace OekBundle\Export;
use AppBundle\Exception\AppException;
use AppBundle\Export\AbstractExport;
use OekBundle\Entity\Training;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class PresentielijstExport extends AbstractExport
{
public function create($training)
{
if (!$training instanceof Training) {
throw new AppException(sprintf(
'%s::create() expects object of type %s, %s given.',
__CLASS__,
Training::class,
get_class($training)
));
}
$this->excel = new Spreadsheet();
$sheet = $this->excel->getActiveSheet();
$sheet->getDefaultColumnDimension()->setAutoSize(true);
$aantal = $training->getGroep()->getAantalBijeenkomsten();
if ($aantal > 1) {
foreach (range(1, $aantal) as $i) {
$sheet->getCellByColumnAndRow($i + 1, 1)
->setValue('Bijeenkomst '.$i)
->getStyle()->getFont()->setBold(true);
}
}
$deelnames = $training->getDeelnames();
foreach ($deelnames as $i => $deelname) {
$sheet->getCellByColumnAndRow(1, $i + 2)
->setValue((string) $deelname->getDeelnemer())
->getStyle()->getFont()->setBold(true);
}
foreach ($sheet->getColumnIterator() as $column) {
$sheet->getColumnDimension($column->getColumnIndex())->setAutoSize(true);
}
return $this;
}
}
| {'content_hash': 'c0a550620d367ae970785bd479518396', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 85, 'avg_line_length': 31.040816326530614, 'alnum_prop': 0.556870479947403, 'repo_name': 'deregenboog/ecd', 'id': '5adb595a5c249cfded094052d4b79d81513d825f', 'size': '1521', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/OekBundle/Export/PresentielijstExport.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '39384'}, {'name': 'Dockerfile', 'bytes': '1506'}, {'name': 'JavaScript', 'bytes': '199321'}, {'name': 'PHP', 'bytes': '4527452'}, {'name': 'SCSS', 'bytes': '34'}, {'name': 'Shell', 'bytes': '7702'}, {'name': 'Twig', 'bytes': '1454381'}]} |
{image file-path="img/topics/computer-searching-number.png" alt="A computer is searching for a number."}
Imagine 15 numbers have been organised in ascending order in a list by a computer program.
Now the program has to find a number in the list, but it can only look at one number at a time.
Is it easier to find the number now, than if they were in a random order?
### Potential answers could include:
- The information is organised in a way that makes it more efficient to find.
By guessing one number and checking it, you can use logical thinking to eliminate the numbers below or above the number guessed because you know the numbers are in order.
- If they are in random order you can't use a strategy to find them quickly.
## Lesson starter
This is for students who are learning to identify numbers from 1 to 100.
We have 15 different numbers, one on each card.
You can’t see them but this time they are in order from the lowest number to the highest number.
The numbers range from 1 to 100.
Can you find number **52**
{panel type="teaching"}
# Teaching observations
You can adapt the range to suit what your students are working on in their mathematics lessons.
This lesson focuses on sorted lists and we are using a range of numbers from 1 - 100.
This activity works best if the numbers **are not** sequential because, for example, if there are 50 cards in the range 1 to 50 and they are sequential and you ask a student to find the number 10 they will probably just look at the 10th card straight away!
You can generate different sets of cards with various ranges of numbers [here]('resources:resource' 'searching-cards').
It's best if the numbers aren't spread evenly so that it's very hard to guess where a particular value might be.
{panel end}
## Lesson activities
Set up a line of cards, with the animal facing upwards.
Have a payment system ready such as tokens for your classroom, counters, sweets, or marbles.
The game is even better if you have some real stakes - for example: I have 10 marbles each is worth 2 minutes of game time.
For every token you use to find the number I’m thinking of, you will lose a marble.
Let’s see how many guesses it takes to find the number: 52
Who would like the first guess? (Choose a student).
Which animal should I turn over? Tell us why you chose that guess.
(They should be selecting the card that is exactly half way.
If they didn’t, check with the class if they agree with the choice or could they add to the student’s thinking to select the middle card.
If they decide not to, that's fine; they will learn the hard way if they use a less efficient approach.)
Turn over the chosen card to show the number under it.
If it's the correct one, you can stop, otherwise *remove that card and all other cards that the number can’t be* (which will either be all cards to the right or all cards to the left of the chosen one) and take away one token from your pile.
Repeat this process until a student chooses the card with your number on it; if they use all ten tokens then the teacher "wins".
How many guesses did it take to find the number?
With each guess, how many cards were eliminated from being a possibility?
(Answer: half the cards could be eliminated with each guess if you picked the middle card. )
Did the students win because they guessed within 4 guesses or did you win because it took them longer?
Repeat this game until the students have won 3 times or you have won 3 times.
{panel type="teaching"}
# Teaching observations
The number of guesses required can be anything from 1 (if you are lucky the first time), to 4 (if you have chosen the middle number each time).
Of course, they may use more than 4 guesses if they use a poor strategy. Most of the time they will need close to 4 guesses.
This also means that students will always have tokens left if they use a good strategy, since the maximum number of guesses to find the number is 4.
{panel end}
## Applying what we have just learnt
If any data is organised in order and a binary search is applied, then you can eliminate a lot of data quickly - cutting the number of items in half each time.
As a slightly different example, if we were trying to guess a number between 1 and 100, then asking if the number is over 50 would eliminate 50 options in one question, the second question eliminates 25, the third question 12 or 13, and so on.
So in 3 questions you have eliminated 87 numbers.
With just 7 questions you can find the one number between 1 and 100.
If you want to challenge students you could talk about how many guesses it would take to guess a number between 1 and 1000.
Asking if the number is over 500 would eliminate 500 options in one question, the second question eliminates 250, the third would eliminate 125, and so on.
In 3 questions you can eliminate 875 numbers, and you could find the answer in just 10 questions.
It's the same searching for objects that are sorted in descending order - each value that is checked halves the number of possible locations.
Dividing problems in half makes them very small very quickly.
This general process is called "divide and conquer" - you break the problem into (two) parts, and deal with each part separately, in turn break them into two parts.
Very soon you end up with very easy tasks, such as dealing with just one item.
It's a great strategy for reducing any big task or challenge to achievable goals!
## Lesson reflection
What is the algorithm for a binary search? Here is a possible answer:
- Ask to see the middle card
- Repeat until the correct number is found:
- Is the number greater than the number I want to find?
- If yes, then keep the cards above that number,
- Else, keep the cards below that number
| {'content_hash': 'fcba49b7e994248f7af9cd9406dbec7e', 'timestamp': '', 'source': 'github', 'line_count': 99, 'max_line_length': 256, 'avg_line_length': 58.17171717171717, 'alnum_prop': 0.7714881055738844, 'repo_name': 'uccser/cs-unplugged', 'id': '0f61a55e51d0012d484b7a2605fa20b44c452f1b', 'size': '5811', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'csunplugged/topics/content/en/searching-algorithms/lessons/divide-and-conquer-junior.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Dockerfile', 'bytes': '7927'}, {'name': 'HTML', 'bytes': '432891'}, {'name': 'JavaScript', 'bytes': '104806'}, {'name': 'Python', 'bytes': '1257568'}, {'name': 'SCSS', 'bytes': '67560'}, {'name': 'Shell', 'bytes': '12461'}]} |
package org.redisson;
import org.redisson.api.*;
import org.redisson.api.annotation.REntity;
import org.redisson.client.codec.Codec;
import org.redisson.liveobject.misc.ClassUtils;
import org.redisson.misc.BiHashMap;
import java.io.Serializable;
/**
*
* @author Rui Gu (https://github.com/jackygurui)
* @author Nikita Koksharov
*/
public class RedissonReference implements Serializable {
private static final long serialVersionUID = -2378564460151709127L;
private static final BiHashMap<String, String> REACTIVE_MAP = new BiHashMap<>();
private static final BiHashMap<String, String> RXJAVA_MAP = new BiHashMap<>();
static {
REACTIVE_MAP.put(RAtomicLongReactive.class.getName(), RAtomicLong.class.getName());
REACTIVE_MAP.put(RBitSetReactive.class.getName(), RBitSet.class.getName());
REACTIVE_MAP.put(RBlockingQueueReactive.class.getName(), RBlockingQueue.class.getName());
REACTIVE_MAP.put(RBucketReactive.class.getName(), RBucket.class.getName());
REACTIVE_MAP.put(RDequeReactive.class.getName(), RDeque.class.getName());
REACTIVE_MAP.put(RHyperLogLogReactive.class.getName(), RHyperLogLog.class.getName());
REACTIVE_MAP.put(RLexSortedSetReactive.class.getName(), RLexSortedSet.class.getName());
REACTIVE_MAP.put(RListReactive.class.getName(), RList.class.getName());
REACTIVE_MAP.put(RMapCacheReactive.class.getName(), RMapCache.class.getName());
REACTIVE_MAP.put(RMapReactive.class.getName(), RMap.class.getName());
REACTIVE_MAP.put(RQueueReactive.class.getName(), RQueue.class.getName());
REACTIVE_MAP.put(RScoredSortedSetReactive.class.getName(), RScoredSortedSet.class.getName());
REACTIVE_MAP.put(RSetCacheReactive.class.getName(), RSetCache.class.getName());
REACTIVE_MAP.put(RSetReactive.class.getName(), RSet.class.getName());
REACTIVE_MAP.makeImmutable();
RXJAVA_MAP.put(RAtomicLongRx.class.getName(), RAtomicLong.class.getName());
RXJAVA_MAP.put(RBitSetRx.class.getName(), RBitSet.class.getName());
RXJAVA_MAP.put(RBlockingQueueRx.class.getName(), RBlockingQueue.class.getName());
RXJAVA_MAP.put(RBucketRx.class.getName(), RBucket.class.getName());
RXJAVA_MAP.put(RDequeRx.class.getName(), RDeque.class.getName());
RXJAVA_MAP.put(RHyperLogLogRx.class.getName(), RHyperLogLog.class.getName());
RXJAVA_MAP.put(RLexSortedSetRx.class.getName(), RLexSortedSet.class.getName());
RXJAVA_MAP.put(RListRx.class.getName(), RList.class.getName());
RXJAVA_MAP.put(RMapCacheRx.class.getName(), RMapCache.class.getName());
RXJAVA_MAP.put(RMapRx.class.getName(), RMap.class.getName());
RXJAVA_MAP.put(RQueueRx.class.getName(), RQueue.class.getName());
RXJAVA_MAP.put(RScoredSortedSetRx.class.getName(), RScoredSortedSet.class.getName());
RXJAVA_MAP.put(RSetCacheRx.class.getName(), RSetCache.class.getName());
RXJAVA_MAP.put(RSetRx.class.getName(), RSet.class.getName());
RXJAVA_MAP.makeImmutable();
}
public static void warmUp() {}
public enum ReferenceType {RXJAVA, REACTIVE, DEFAULT}
private String type;
private String keyName;
private String codec;
public RedissonReference() {
}
public RedissonReference(Class<?> type, String keyName) {
this(type, keyName, null);
}
public RedissonReference(Class<?> type, String keyName, Codec codec) {
if (!ClassUtils.isAnnotationPresent(type, REntity.class)
&& !RObject.class.isAssignableFrom(type)
&& !RObjectReactive.class.isAssignableFrom(type)
&& !RObjectRx.class.isAssignableFrom(type)) {
throw new IllegalArgumentException("Class reference has to be a type of either RObject/RLiveObject/RObjectReactive/RObjectRx");
}
if (RObjectReactive.class.isAssignableFrom(type)) {
this.type = REACTIVE_MAP.get(type.getName());
if (this.type == null) {
throw new IllegalArgumentException("There is no Reactive compatible type for " + type);
}
} else if (RObjectRx.class.isAssignableFrom(type)) {
this.type = RXJAVA_MAP.get(type.getName());
if (this.type == null) {
throw new IllegalArgumentException("There is no RxJava compatible type for " + type);
}
} else {
this.type = type.getName();
}
this.keyName = keyName;
if (codec != null) {
this.codec = codec.getClass().getName();
}
}
/**
* @return the type
* @throws java.lang.ClassNotFoundException - if the class cannot be located
*/
public Class<?> getType() throws ClassNotFoundException {
return Class.forName(type);
}
public Class<?> getRxJavaType() throws ClassNotFoundException {
if (RXJAVA_MAP.containsValue(type)) {
return Class.forName(RXJAVA_MAP.reverseGet(type)); //live object is not supported in reactive client
}
throw new ClassNotFoundException("There is no RxJava compatible type for " + type);
}
/**
* @return the type
* @throws java.lang.ClassNotFoundException - if the class cannot be located
*/
public Class<?> getReactiveType() throws ClassNotFoundException {
if (REACTIVE_MAP.containsValue(type)) {
return Class.forName(REACTIVE_MAP.reverseGet(type)); //live object is not supported in reactive client
}
throw new ClassNotFoundException("There is no Reactive compatible type for " + type);
}
/**
* @return type name in string
*/
public String getTypeName() {
return type;
}
/**
* @return the keyName
*/
public String getKeyName() {
return keyName;
}
/**
* @param keyName the keyName to set
*/
public void setKeyName(String keyName) {
this.keyName = keyName;
}
public String getCodec() {
return codec;
}
/**
* @return the codec
* @throws java.lang.ClassNotFoundException - if the class cannot be located
*/
public Class<? extends Codec> getCodecType() throws ClassNotFoundException {
if (codec != null) {
return (Class<? extends Codec>) Class.forName(codec);
}
return null;
}
}
| {'content_hash': 'c9f91665b1c1904b5c124c84ac2bf021', 'timestamp': '', 'source': 'github', 'line_count': 162, 'max_line_length': 139, 'avg_line_length': 41.364197530864196, 'alnum_prop': 0.6294582898074914, 'repo_name': 'redisson/redisson', 'id': '61b26d3178c2a906778b6c2362828e1da271bc67', 'size': '7309', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'redisson/src/main/java/org/redisson/RedissonReference.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '12833620'}]} |
psql -d dbgeo1 < load.sql
psql -d dbgeo1 < cut.sql > render.html
| {'content_hash': 'ec8c9255430dc126d81c1ca173337a36', 'timestamp': '', 'source': 'github', 'line_count': 2, 'max_line_length': 38, 'avg_line_length': 32.5, 'alnum_prop': 0.6923076923076923, 'repo_name': 'wsdookadr/parcel-cut', 'id': '4ad9337d82ca75af6d14c558d6cb1d3750ac8664', 'size': '77', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'run.sh', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '57602'}, {'name': 'PLpgSQL', 'bytes': '24102'}, {'name': 'Shell', 'bytes': '188'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>coquelicot: Not compatible 👼</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 / released</a></li>
<li class="active"><a href="">8.4.6~camlp4 / coquelicot - 3.0.2</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
coquelicot
<small>
3.0.2
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-06 19:57:14 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-06 19:57:14 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler
base-threads base
base-unix base
camlp4 4.02+7 Camlp4 is a system for writing extensible parsers for programming languages
conf-findutils 1 Virtual package relying on findutils
conf-which 1 Virtual package relying on which
coq 8.4.6~camlp4 Formal proof management system.
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.02.3 The OCaml compiler (virtual package)
ocaml-base-compiler 4.02.3 Official 4.02.3 release
ocaml-config 1 OCaml Switch Configuration
ocamlbuild 0 Build system distributed with the OCaml compiler since OCaml 3.10.0
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "http://coquelicot.saclay.inria.fr/"
dev-repo: "git+https://gitlab.inria.fr/coquelicot/coquelicot.git"
bug-reports: "https://gitlab.inria.fr/coquelicot/coquelicot/issues"
license: "LGPL-3.0-or-later"
build: [
["./configure"]
["./remake" "-j%{jobs}%"]
]
install: ["./remake" "install"]
depends: [
"coq" {>= "8.5" & < "8.10~"}
"coq-mathcomp-ssreflect" {>= "1.6"}
]
tags: [ "keyword:real analysis" "keyword:topology" "keyword:filters" "keyword:metric spaces" "category:Mathematics/Real Calculus and Topology" ]
authors: [ "Sylvie Boldo <[email protected]>" "Catherine Lelay <[email protected]>" "Guillaume Melquiond <[email protected]>" ]
synopsis: "A Coq formalization of real analysis compatible with the standard library"
url {
src: "https://coquelicot.gitlabpages.inria.fr/releases/coquelicot-3.0.2.tar.gz"
checksum: "md5=3236249967dd36ca832dd10d1bddcd71"
}
</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-coquelicot.3.0.2 coq.8.4.6~camlp4</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.4.6~camlp4).
The following dependencies couldn't be met:
- coq-coquelicot -> coq >= 8.5 -> ocaml >= 4.05.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
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-coquelicot.3.0.2</code></dd>
<dt>Return code</dt>
<dd>0</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">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</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': 'b5b861cd67ad5abe254862dd92f3f10f', 'timestamp': '', 'source': 'github', 'line_count': 166, 'max_line_length': 197, 'avg_line_length': 44.10843373493976, 'alnum_prop': 0.5532641354821087, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': '55222bced772320045732baa6284e8a6dc3b4b07', 'size': '7347', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.02.3-2.0.6/released/8.4.6~camlp4/coquelicot/3.0.2.html', 'mode': '33188', 'license': 'mit', 'language': []} |
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" >
<title></title>
<link rel='stylesheet' href='styles/up_style.css' type='text/css'>
<script src="help/jquery.min.js"></script>
<script src="help/jquery.validate.min.js"></script>
<script src="help/additional-methods.js"></script>
</head>
<body>
<body>
<header>
<h1>Pinpoint</h1><div id="logout_button"><a href="/newupload">Upload</a><a href="{{ logout }}">Sign Out</a></div>
</header>
{% if user %}
Currently logged in as {{user.email}} - <a href="/account">log out</a>
<h3>Upload</h3>
<form id="form" action="{{upload_url}}" method="POST" enctype="multipart/form-data">
<input type="file" name="file" class="required" accept="image/*">
<input type="submit" name="submit" value="Submit">
</form>
{% else %}
Not logged in - <a href="/account">log in</a>
{% endif %}
<h3>Files</h3>
<ul>
{% if not wrappers %}
No files have been uploaded
{% endif %}
{% for wrapper in wrappers %}
<li><a href="/serve/{{wrapper.blob.key}}">{{wrapper.blob.filename}}</a> ({{wrapper.blob.size}})
<small>uploaded {{wrapper.date|date:"D d M Y g:i:s A"}} by
{% ifequal wrapper.user user %}
you - <form action="/delete" method="post">
<input type="hidden" name="key" value="{{wrapper.key}}">
<input type="submit" value="Delete">
{% else %}
{{wrapper.user.email}}
{% endifequal %}</small>
<br>
{{wrapper.lat}} <br> {{wrapper.lon}}
</li>
{% endfor %}
</ul>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#form").validate();
});
</script>
</body>
</html>
| {'content_hash': '7862e7e5e2ff3b267ebd05bd25a55c35', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 114, 'avg_line_length': 28.0, 'alnum_prop': 0.6009852216748769, 'repo_name': 'vishnurajv/pinpoint', 'id': '8eb335fffdd87610843a2c3b1a0ad9611deca476', 'size': '1624', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'templates/upload.html', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Addition_of_two_numbers_version2
{
class Program
{
static void Main(string[] args)
{
Calculator calculator = new Calculator();
Console.WriteLine("The sum of two numbers is " + calculator.addTwoNumbers(3, 5));
}
}
}
| {'content_hash': 'adcffb0c01e0c33797f33b519aeb423d', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 93, 'avg_line_length': 21.31578947368421, 'alnum_prop': 0.6469135802469136, 'repo_name': 'SwatDeva/Addition-of-two-numbers-version2', 'id': '5a81e94ea2bef565a523c9228e68bf66e938550d', 'size': '407', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Addition of two numbers version2/Addition of two numbers version2/Program.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '2164'}]} |
package edu.cmu.hcii.citrus;
public class CharLiteral extends Expression<Char> {
// Restricted in Boot.java
public static final Dec<Text> token = new Dec<Text>(new Text(" "));
public static final Dec<Char> value = new Dec<Char>(true, new BaseElement<Char>() {
public Char evaluate(Element<?> env) {
String tok = env.get(token).value;
if(tok.equals("")) return new Char((char)0);
else if(tok.startsWith("\\")) {
char second = tok.charAt(1);
if(second == 'b') return new Char('\b');
else if(second == 'n') return new Char('\n');
else if(second == 't') return new Char('\t');
else if(second == '`') return new Char('`');
else if(second == 'u') {
tok = tok.substring(2);
System.err.println("Not parsing hexidecimal " + tok + " to unicode!");
return new Char('\uFFFF');
}
else throw new ElementError("Ellegal escape code for character " + tok, null);
}
else return new Char(tok.charAt(0));
}
});
public CharLiteral() {}
public CharLiteral(ArgumentList args) { super(args); }
public CharLiteral(String value) { set(token, new Text(value)); }
public Char evaluate(Element<?> env) { return peek(value); }
public Type resultingType() { return Boot.CHAR; }
public Text toCitrus() { return get(value).toCitrus(); }
public String toString() { return get(value).toString(); }
} | {'content_hash': '6ca93c8a54ee5d6a817e6d37617514de', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 84, 'avg_line_length': 29.869565217391305, 'alnum_prop': 0.6317321688500728, 'repo_name': 'andyjko/citrus-barista', 'id': '3acce20dab85af765f7975d05abce1d2c22c737a', 'size': '2335', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'edu/cmu/hcii/citrus/CharLiteral.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Groff', 'bytes': '3490'}, {'name': 'Java', 'bytes': '933151'}]} |
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="cz.nudz.www.trainingapp.login.SignupFragment">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fitsSystemWindows="true">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:paddingTop="24dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:layout_gravity="center_horizontal"
android:textSize="24sp"
android:typeface="normal"
android:text="@string/newUserTitle"/>
<!-- Username Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="@+id/input_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textCapWords"
android:hint="@string/usernameLabel" />
</android.support.design.widget.TextInputLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<android.support.v7.widget.AppCompatButton
android:id="@+id/btn_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginBottom="24dp"
android:padding="12dp"
android:text="@string/cancelBtnText"/>
<!-- Signup Button -->
<android.support.v7.widget.AppCompatButton
android:id="@+id/btn_signup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginBottom="24dp"
android:padding="12dp"
android:text="@string/createUserBtnText"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
</layout>
| {'content_hash': '81a1354502700708853fff36f08f83df', 'timestamp': '', 'source': 'github', 'line_count': 68, 'max_line_length': 66, 'avg_line_length': 41.88235294117647, 'alnum_prop': 0.555126404494382, 'repo_name': 'ayraz/TrainingApp', 'id': '1e93779f66124bd12bec6c97050a618bd334fff9', 'size': '2848', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/layout/signup_fragment.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '4734'}, {'name': 'Java', 'bytes': '206758'}]} |
using System.Data.SqlClient;
namespace DapperIdentity.Core.Interfaces
{
public interface IConnectionFactory
{
SqlConnection CreateConnection();
}
}
| {'content_hash': 'b97ed0690ed54a5b2895c18e842eab7b', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 41, 'avg_line_length': 18.88888888888889, 'alnum_prop': 0.7235294117647059, 'repo_name': 'rantowork/MVC5-Dapper-Identity', 'id': 'd2fae92f023b681a04b1645698ad58664eb35d78', 'size': '172', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'DapperIdentity/DapperIdentity.Core/Interfaces/IConnectionFactory.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '109'}, {'name': 'C#', 'bytes': '85782'}, {'name': 'CSS', 'bytes': '513'}, {'name': 'HTML', 'bytes': '5127'}, {'name': 'JavaScript', 'bytes': '19635'}]} |
<?php
/**
* This file is part of the WebScale library. It is licenced under
* MIT licence. For more information, see LICENSE file that
* was distributed with this library.
*/
namespace WebScale\Tests\Driver;
use WebScale\Driver\Factory;
/**
* @requires extension memcache
*/
class MemcacheTest extends AbstractDriverTest
{
protected function getDriver()
{
return Factory::getMemcacheDriver();
}
}
| {'content_hash': '6410598cef8e140f92e19b39656e46fa', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 66, 'avg_line_length': 21.25, 'alnum_prop': 0.7152941176470589, 'repo_name': 'WebScalePHP/webscale', 'id': '3bf32f79ad5040b5bf6f1d5fef3ed3799a36d890', 'size': '425', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/Testsuite/Driver/MemcacheTest.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1137'}, {'name': 'PHP', 'bytes': '119042'}]} |
package org.snia.cdmiserver.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* <p>
* Exception that should be mapped to an HTTP Status 400 Response.
* </p>
*/
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
/**
* Generated serial version UID.
*/
private static final long serialVersionUID = 977549442582637698L;
public BadRequestException(String message) {
super(message);
}
public BadRequestException(String message, Throwable cause) {
super(message, cause);
}
public BadRequestException(Throwable cause) {
super(cause);
}
}
| {'content_hash': '73870bee9d8043c0379e8c16b439cd16', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 67, 'avg_line_length': 21.393939393939394, 'alnum_prop': 0.7393767705382436, 'repo_name': 'enricovianello/CDMI', 'id': '763349c18d0599495e941f2801c3e8bdc24dcc73', 'size': '2344', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/snia/cdmiserver/exception/BadRequestException.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '428098'}, {'name': 'Python', 'bytes': '16784'}, {'name': 'Shell', 'bytes': '633'}]} |
layout: post
title: Lesbian sex - Katherine J and Paula B
titleinfo: pornvd
desc: Watch Lesbian sex - Katherine J and Paula B. Pornhub is the ultimate xxx porn and sex site.
---
<iframe src="http://www.pornhub.com/embed/ph56f2b929b4410" frameborder="0" width="630" height="338" scrolling="no"></iframe>
<h2>Lesbian sex - Katherine J and Paula B</h2>
<h3>Watch Lesbian sex - Katherine J and Paula B. Pornhub is the ultimate xxx porn and sex site.</h3>
| {'content_hash': 'aa66155908153440f7d1e4706e3de837', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 124, 'avg_line_length': 46.8, 'alnum_prop': 0.7136752136752137, 'repo_name': 'pornvd/pornvd.github.io', 'id': '96849be6640eb076035e0b8189d870b1f21f3d92', 'size': '472', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '_posts/2016-03-25-Lesbian-sex---Katherine-J-and-Paula-B.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '18073'}, {'name': 'HTML', 'bytes': '10043'}, {'name': 'JavaScript', 'bytes': '1581'}, {'name': 'Python', 'bytes': '2932'}, {'name': 'Ruby', 'bytes': '3287'}, {'name': 'Shell', 'bytes': '310'}]} |
require 'spec_helper'
describe 'shared/notes/_form' do
include Devise::Test::ControllerHelpers
let(:user) { create(:user) }
let(:project) { create(:project, :repository) }
before do
project.team << [user, :master]
assign(:project, project)
assign(:note, note)
allow(view).to receive(:current_user).and_return(user)
render
end
%w[issue merge_request].each do |noteable|
context "with a note on #{noteable}" do
let(:note) { build(:"note_on_#{noteable}", project: project) }
it 'says that markdown and slash commands are supported' do
expect(rendered).to have_content('Markdown and slash commands are supported')
end
end
end
context 'with a note on a commit' do
let(:note) { build(:note_on_commit, project: project) }
it 'says that only markdown is supported, not slash commands' do
expect(rendered).to have_content('Markdown is supported')
end
end
end
| {'content_hash': 'b70147ffaee23a64a27512365f1a1c82', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 85, 'avg_line_length': 26.36111111111111, 'alnum_prop': 0.6649104320337197, 'repo_name': 'htve/GitlabForChinese', 'id': 'd7d0a5bf56a9b992e78ecff60b276e12842b9a4f', 'size': '949', 'binary': False, 'copies': '1', 'ref': 'refs/heads/9-2-zh', 'path': 'spec/views/shared/notes/_form.html.haml_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '499575'}, {'name': 'Gherkin', 'bytes': '140955'}, {'name': 'HTML', 'bytes': '979335'}, {'name': 'JavaScript', 'bytes': '1909827'}, {'name': 'Ruby', 'bytes': '10590735'}, {'name': 'Shell', 'bytes': '26903'}, {'name': 'Vue', 'bytes': '81150'}]} |
package it.unibz.inf.ontop.answering.reformulation.input;
import it.unibz.inf.ontop.answering.resultset.TupleResultSet;
public interface SelectQuery extends TupleSPARQLQuery<TupleResultSet> {
}
| {'content_hash': 'ab88e373f4b8699bff26daa789f57f5e', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 71, 'avg_line_length': 28.142857142857142, 'alnum_prop': 0.8375634517766497, 'repo_name': 'ontop/ontop', 'id': '8458c608c97e929c843e2203d7cef8bce1e6ee22', 'size': '197', 'binary': False, 'copies': '1', 'ref': 'refs/heads/version4', 'path': 'engine/reformulation/core/src/main/java/it/unibz/inf/ontop/answering/reformulation/input/SelectQuery.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '8054'}, {'name': 'Batchfile', 'bytes': '524'}, {'name': 'CSS', 'bytes': '2859'}, {'name': 'Dockerfile', 'bytes': '1577'}, {'name': 'FreeMarker', 'bytes': '1846'}, {'name': 'HTML', 'bytes': '1428712'}, {'name': 'Java', 'bytes': '8862515'}, {'name': 'JavaScript', 'bytes': '4759'}, {'name': 'Ruby', 'bytes': '28650'}, {'name': 'Shell', 'bytes': '24861'}, {'name': 'TSQL', 'bytes': '3316'}, {'name': 'TeX', 'bytes': '5188'}, {'name': 'XSLT', 'bytes': '19056'}, {'name': 'q', 'bytes': '93020'}]} |
<main>
<div *ngIf='!shiftService.isShiftStart' class='btn_moveTo' id="startPatrol" routerLink='../start_patrol'> התחל סיור</div>
<div *ngIf='shiftService.isShiftStart' class='btn_moveTo' id="endPatrol" routerLink='../end_patrol'> סיים סיור</div>
<div *ngIf='shiftService.isShiftStart' class='btn_moveTo' id="addSpot" routerLink='../mobile_spot'><img src='https://cdn3.iconfinder.com/data/icons/web-ui-color/128/Marker_green-128.png ' id="img"/> הוסף נקודה</div>
<div *ngIf='shiftService.isShiftStart' class='btn_moveTo' id="report" [routerLink]='["../report", 1]'><img src='https://cdn4.iconfinder.com/data/icons/web-ui-color/128/Chat2-128.png' id="img"/> דווח על אירוע</div>
<div *ngIf='!shiftService.isShiftStart' class='btn_moveTo_canceled' >הוסף נקודה</div>
<div *ngIf='!shiftService.isShiftStart' class='btn_moveTo_canceled' >דווח על אירוע</div>
<div class='statistic'>
<router-outlet></router-outlet>
</div>
</main>
| {'content_hash': '69dad3335121b4893f40707216b469b4', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 222, 'avg_line_length': 86.36363636363636, 'alnum_prop': 0.7031578947368421, 'repo_name': 'eranhd/Anti-Drug-Jerusalem', 'id': '8320ae0570c84b3ddde12c1ca0ad548c6dff0952', 'size': '1006', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Web/src/app/mobile/pages/mobile-home/mobile-home.component.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '34734'}, {'name': 'HTML', 'bytes': '40548'}, {'name': 'Java', 'bytes': '5745'}, {'name': 'JavaScript', 'bytes': '1884'}, {'name': 'TypeScript', 'bytes': '130593'}]} |
namespace cc {
class SolidColorLayer;
} // namespace cc
namespace content {
class Compositor;
} // namespace content
namespace ui {
class WindowAndroid;
} // namespace ui
namespace thin_webview {
namespace android {
// Native counterpart of CompositorViewImpl.java.
class CompositorViewImpl : public CompositorView,
public content::CompositorClient {
public:
CompositorViewImpl(JNIEnv* env,
jobject obj,
ui::WindowAndroid* window_android);
~CompositorViewImpl() override;
void Destroy(JNIEnv* env, const base::android::JavaParamRef<jobject>& object);
void SetNeedsComposite(JNIEnv* env,
const base::android::JavaParamRef<jobject>& object);
void SurfaceCreated(JNIEnv* env,
const base::android::JavaParamRef<jobject>& object);
void SurfaceDestroyed(JNIEnv* env,
const base::android::JavaParamRef<jobject>& object);
void SurfaceChanged(JNIEnv* env,
const base::android::JavaParamRef<jobject>& object,
jint format,
jint width,
jint height,
bool can_be_used_with_surface_control,
const base::android::JavaParamRef<jobject>& surface);
// CompositorView implementation.
void SetRootLayer(scoped_refptr<cc::Layer> layer) override;
// CompositorClient implementation.
void RecreateSurface() override;
void UpdateLayerTreeHost() override;
private:
base::android::ScopedJavaGlobalRef<jobject> obj_;
std::unique_ptr<content::Compositor> compositor_;
scoped_refptr<cc::SolidColorLayer> root_layer_;
int current_surface_format_;
DISALLOW_COPY_AND_ASSIGN(CompositorViewImpl);
};
} // namespace android
} // namespace thin_webview
#endif // CHROME_BROWSER_ANDROID_THIN_WEBVIEW_INTERNAL_COMPOSITOR_VIEW_IMPL_H_
| {'content_hash': 'dca1e9c9bdf4205bb99b8616a695a0bb', 'timestamp': '', 'source': 'github', 'line_count': 61, 'max_line_length': 80, 'avg_line_length': 31.508196721311474, 'alnum_prop': 0.6576482830385015, 'repo_name': 'endlessm/chromium-browser', 'id': '6bfe9fdf2ec9b0135377ed92140321d91be7682f', 'size': '2523', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'chrome/browser/android/thin_webview/internal/compositor_view_impl.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("IntermediateRankBehavior")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IntermediateRankBehavior")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5dd280b1-4775-46f2-831e-72c5f61aa641")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {'content_hash': 'f2dcce52d1fd95af54f63a360a735ece', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 84, 'avg_line_length': 39.47222222222222, 'alnum_prop': 0.7494722026741731, 'repo_name': 'Hansoft/Hansoft-Jean-IntermediateRankBehavior', 'id': 'd4cf4677a63673d188855ae3162d3f34da4536b6', 'size': '1424', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Properties/AssemblyInfo.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '6017'}]} |
package org.apache.commons.io;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.Checksum;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.FalseFileFilter;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.io.output.NullOutputStream;
/**
* General file manipulation utilities.
* <p>
* Facilities are provided in the following areas:
* <ul>
* <li>writing to a file
* <li>reading from a file
* <li>make a directory including parent directories
* <li>copying files and directories
* <li>deleting files and directories
* <li>converting to and from a URL
* <li>listing files and directories by filter and extension
* <li>comparing file content
* <li>file last changed date
* <li>calculating a checksum
* </ul>
* <p>
* Origin of code: Excalibur, Alexandria, Commons-Utils
*
* @author <a href="mailto:[email protected]">Kevin A. Burton</A>
* @author <a href="mailto:[email protected]">Scott Sanders</a>
* @author <a href="mailto:[email protected]">Daniel Rall</a>
* @author <a href="mailto:[email protected]">Christoph.Reck</a>
* @author <a href="mailto:[email protected]">Peter Donald</a>
* @author <a href="mailto:[email protected]">Jeff Turner</a>
* @author Matthew Hawthorne
* @author <a href="mailto:[email protected]">Jeremias Maerki</a>
* @author Stephen Colebourne
* @author Ian Springer
* @author Chris Eldredge
* @author Jim Harrington
* @author Sandy McArthur
* @version $Id: FileUtils.java 1153952 2011-08-04 17:47:24Z ggregory $
*/
public class FileUtils {
/**
* Instances should NOT be constructed in standard programming.
*/
public FileUtils() {
super();
}
/**
* The number of bytes in a kilobyte.
*/
public static final long ONE_KB = 1024;
/**
* The number of bytes in a megabyte.
*/
public static final long ONE_MB = ONE_KB * ONE_KB;
/**
* The file copy buffer size (30 MB)
*/
private static final long FILE_COPY_BUFFER_SIZE = ONE_MB * 30;
/**
* The number of bytes in a gigabyte.
*/
public static final long ONE_GB = ONE_KB * ONE_MB;
/**
* The number of bytes in a terabyte.
*/
public static final long ONE_TB = ONE_KB * ONE_GB;
/**
* The number of bytes in a petabyte.
*/
public static final long ONE_PB = ONE_KB * ONE_TB;
/**
* The number of bytes in an exabyte.
*/
public static final long ONE_EB = ONE_KB * ONE_PB;
/**
* The number of bytes in a zettabyte.
*/
public static final BigInteger ONE_ZB = BigInteger.valueOf(ONE_KB).multiply(BigInteger.valueOf(ONE_EB));
/**
* The number of bytes in a yottabyte.
*/
public static final BigInteger ONE_YB = ONE_ZB.multiply(BigInteger.valueOf(ONE_EB));
/**
* An empty array of type <code>File</code>.
*/
public static final File[] EMPTY_FILE_ARRAY = new File[0];
/**
* The UTF-8 character set, used to decode octets in URLs.
*/
private static final Charset UTF8 = Charset.forName("UTF-8");
//-----------------------------------------------------------------------
/**
* Construct a file from the set of name elements.
*
* @param directory the parent directory
* @param names the name elements
* @return the file
* @since Commons IO 2.1
*/
public static File getFile(File directory, String... names) {
if (directory == null) {
throw new NullPointerException("directorydirectory must not be null");
}
if (names == null) {
throw new NullPointerException("names must not be null");
}
File file = directory;
for (String name : names) {
file = new File(file, name);
}
return file;
}
/**
* Construct a file from the set of name elements.
*
* @param names the name elements
* @return the file
* @since Commons IO 2.1
*/
public static File getFile(String... names) {
if (names == null) {
throw new NullPointerException("names must not be null");
}
File file = null;
for (String name : names) {
if (file == null) {
file = new File(name);
} else {
file = new File(file, name);
}
}
return file;
}
/**
* Returns the path to the system temporary directory.
*
* @return the path to the system temporary directory.
*
* @since Commons IO 2.0
*/
public static String getTempDirectoryPath() {
return System.getProperty("java.io.tmpdir");
}
/**
* Returns a {@link File} representing the system temporary directory.
*
* @return the system temporary directory.
*
* @since Commons IO 2.0
*/
public static File getTempDirectory() {
return new File(getTempDirectoryPath());
}
/**
* Returns the path to the user's home directory.
*
* @return the path to the user's home directory.
*
* @since Commons IO 2.0
*/
public static String getUserDirectoryPath() {
return System.getProperty("user.home");
}
/**
* Returns a {@link File} representing the user's home directory.
*
* @return the user's home directory.
*
* @since Commons IO 2.0
*/
public static File getUserDirectory() {
return new File(getUserDirectoryPath());
}
//-----------------------------------------------------------------------
/**
* Opens a {@link FileInputStream} for the specified file, providing better
* error messages than simply calling <code>new FileInputStream(file)</code>.
* <p>
* At the end of the method either the stream will be successfully opened,
* or an exception will have been thrown.
* <p>
* An exception is thrown if the file does not exist.
* An exception is thrown if the file object exists but is a directory.
* An exception is thrown if the file exists but cannot be read.
*
* @param file the file to open for input, must not be <code>null</code>
* @return a new {@link FileInputStream} for the specified file
* @throws FileNotFoundException if the file does not exist
* @throws IOException if the file object is a directory
* @throws IOException if the file cannot be read
* @since Commons IO 1.3
*/
public static FileInputStream openInputStream(File file) throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file + "' exists but is a directory");
}
if (file.canRead() == false) {
throw new IOException("File '" + file + "' cannot be read");
}
} else {
throw new FileNotFoundException("File '" + file + "' does not exist");
}
return new FileInputStream(file);
}
//-----------------------------------------------------------------------
/**
* Opens a {@link FileOutputStream} for the specified file, checking and
* creating the parent directory if it does not exist.
* <p>
* At the end of the method either the stream will be successfully opened,
* or an exception will have been thrown.
* <p>
* The parent directory will be created if it does not exist.
* The file will be created if it does not exist.
* An exception is thrown if the file object exists but is a directory.
* An exception is thrown if the file exists but cannot be written to.
* An exception is thrown if the parent directory cannot be created.
*
* @param file the file to open for output, must not be <code>null</code>
* @return a new {@link FileOutputStream} for the specified file
* @throws IOException if the file object is a directory
* @throws IOException if the file cannot be written to
* @throws IOException if a parent directory needs creating but that fails
* @since Commons IO 1.3
*/
public static FileOutputStream openOutputStream(File file) throws IOException {
return openOutputStream(file, false);
}
/**
* Opens a {@link FileOutputStream} for the specified file, checking and
* creating the parent directory if it does not exist.
* <p>
* At the end of the method either the stream will be successfully opened,
* or an exception will have been thrown.
* <p>
* The parent directory will be created if it does not exist.
* The file will be created if it does not exist.
* An exception is thrown if the file object exists but is a directory.
* An exception is thrown if the file exists but cannot be written to.
* An exception is thrown if the parent directory cannot be created.
*
* @param file the file to open for output, must not be <code>null</code>
* @param append if <code>true</code>, then bytes will be added to the
* end of the file rather than overwriting
* @return a new {@link FileOutputStream} for the specified file
* @throws IOException if the file object is a directory
* @throws IOException if the file cannot be written to
* @throws IOException if a parent directory needs creating but that fails
* @since Commons IO 2.1
*/
public static FileOutputStream openOutputStream(File file, boolean append) throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file + "' exists but is a directory");
}
if (file.canWrite() == false) {
throw new IOException("File '" + file + "' cannot be written to");
}
} else {
File parent = file.getParentFile();
if (parent != null && parent.exists() == false) {
if (parent.mkdirs() == false) {
throw new IOException("File '" + file + "' could not be created");
}
}
}
return new FileOutputStream(file, append);
}
//-----------------------------------------------------------------------
/**
* Returns a human-readable version of the file size, where the input
* represents a specific number of bytes.
*
* If the size is over 1GB, the size is returned as the number of whole GB,
* i.e. the size is rounded down to the nearest GB boundary.
*
* Similarly for the 1MB and 1KB boundaries.
*
* @param size the number of bytes
* @return a human-readable display value (includes units - GB, MB, KB or bytes)
*/
// See https://issues.apache.org/jira/browse/IO-226 - should the rounding be changed?
public static String byteCountToDisplaySize(long size) {
String displaySize;
// if (size / ONE_EB > 0) {
// displaySize = String.valueOf(size / ONE_EB) + " EB";
// } else if (size / ONE_PB > 0) {
// displaySize = String.valueOf(size / ONE_PB) + " PB";
// } else if (size / ONE_TB > 0) {
// displaySize = String.valueOf(size / ONE_TB) + " TB";
// } else
if (size / ONE_GB > 0) {
displaySize = String.valueOf(size / ONE_GB) + " GB";
} else if (size / ONE_MB > 0) {
displaySize = String.valueOf(size / ONE_MB) + " MB";
} else if (size / ONE_KB > 0) {
displaySize = String.valueOf(size / ONE_KB) + " KB";
} else {
displaySize = String.valueOf(size) + " bytes";
}
return displaySize;
}
//-----------------------------------------------------------------------
/**
* Implements the same behaviour as the "touch" utility on Unix. It creates
* a new file with size 0 or, if the file exists already, it is opened and
* closed without modifying it, but updating the file date and time.
* <p>
* NOTE: As from v1.3, this method throws an IOException if the last
* modified date of the file cannot be set. Also, as from v1.3 this method
* creates parent directories if they do not exist.
*
* @param file the File to touch
* @throws IOException If an I/O problem occurs
*/
public static void touch(File file) throws IOException {
if (!file.exists()) {
OutputStream out = openOutputStream(file);
IOUtils.closeQuietly(out);
}
boolean success = file.setLastModified(System.currentTimeMillis());
if (!success) {
throw new IOException("Unable to set the last modification time for " + file);
}
}
//-----------------------------------------------------------------------
/**
* Converts a Collection containing java.io.File instanced into array
* representation. This is to account for the difference between
* File.listFiles() and FileUtils.listFiles().
*
* @param files a Collection containing java.io.File instances
* @return an array of java.io.File
*/
public static File[] convertFileCollectionToFileArray(Collection<File> files) {
return files.toArray(new File[files.size()]);
}
//-----------------------------------------------------------------------
/**
* Finds files within a given directory (and optionally its
* subdirectories). All files found are filtered by an IOFileFilter.
*
* @param files the collection of files found.
* @param directory the directory to search in.
* @param filter the filter to apply to files and directories.
*/
private static void innerListFiles(Collection<File> files, File directory,
IOFileFilter filter) {
File[] found = directory.listFiles((FileFilter) filter);
if (found != null) {
for (File file : found) {
if (file.isDirectory()) {
innerListFiles(files, file, filter);
} else {
files.add(file);
}
}
}
}
/**
* Finds files within a given directory (and optionally its
* subdirectories). All files found are filtered by an IOFileFilter.
* <p>
* If your search should recurse into subdirectories you can pass in
* an IOFileFilter for directories. You don't need to bind a
* DirectoryFileFilter (via logical AND) to this filter. This method does
* that for you.
* <p>
* An example: If you want to search through all directories called
* "temp" you pass in <code>FileFilterUtils.NameFileFilter("temp")</code>
* <p>
* Another common usage of this method is find files in a directory
* tree but ignoring the directories generated CVS. You can simply pass
* in <code>FileFilterUtils.makeCVSAware(null)</code>.
*
* @param directory the directory to search in
* @param fileFilter filter to apply when finding files.
* @param dirFilter optional filter to apply when finding subdirectories.
* If this parameter is <code>null</code>, subdirectories will not be included in the
* search. Use TrueFileFilter.INSTANCE to match all directories.
* @return an collection of java.io.File with the matching files
* @see org.apache.commons.io.filefilter.FileFilterUtils
* @see org.apache.commons.io.filefilter.NameFileFilter
*/
/* public static Collection<File> listFiles(
File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) {
if (!directory.isDirectory()) {
throw new IllegalArgumentException(
"Parameter 'directory' is not a directory");
}
if (fileFilter == null) {
throw new NullPointerException("Parameter 'fileFilter' is null");
}
//Setup effective file filter
IOFileFilter effFileFilter = FileFilterUtils.and(fileFilter,
FileFilterUtils.notFileFilter(DirectoryFileFilter.INSTANCE));
//Setup effective directory filter
IOFileFilter effDirFilter;
if (dirFilter == null) {
effDirFilter = FalseFileFilter.INSTANCE;
} else {
effDirFilter = FileFilterUtils.and(dirFilter,
DirectoryFileFilter.INSTANCE);
}
//Find files
Collection<File> files = new java.util.LinkedList<File>();
innerListFiles(files, directory,
FileFilterUtils.or(effFileFilter, effDirFilter));
return files;
}*/
/**
* Allows iteration over the files in given directory (and optionally
* its subdirectories).
* <p>
* All files found are filtered by an IOFileFilter. This method is
* based on {@link #listFiles(File, IOFileFilter, IOFileFilter)},
* which supports Iterable ('foreach' loop).
* <p>
* @param directory the directory to search in
* @param fileFilter filter to apply when finding files.
* @param dirFilter optional filter to apply when finding subdirectories.
* If this parameter is <code>null</code>, subdirectories will not be included in the
* search. Use TrueFileFilter.INSTANCE to match all directories.
* @return an iterator of java.io.File for the matching files
* @see org.apache.commons.io.filefilter.FileFilterUtils
* @see org.apache.commons.io.filefilter.NameFileFilter
* @since Commons IO 1.2
*/
// public static Iterator<File> iterateFiles(
// File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) {
// return listFiles(directory, fileFilter, dirFilter).iterator();
// }
//-----------------------------------------------------------------------
/**
* Converts an array of file extensions to suffixes for use
* with IOFileFilters.
*
* @param extensions an array of extensions. Format: {"java", "xml"}
* @return an array of suffixes. Format: {".java", ".xml"}
*/
private static String[] toSuffixes(String[] extensions) {
String[] suffixes = new String[extensions.length];
for (int i = 0; i < extensions.length; i++) {
suffixes[i] = "." + extensions[i];
}
return suffixes;
}
/**
* Finds files within a given directory (and optionally its subdirectories)
* which match an array of extensions.
*
* @param directory the directory to search in
* @param extensions an array of extensions, ex. {"java","xml"}. If this
* parameter is <code>null</code>, all files are returned.
* @param recursive if true all subdirectories are searched as well
* @return an collection of java.io.File with the matching files
*/
// public static Collection<File> listFiles(
// File directory, String[] extensions, boolean recursive) {
// IOFileFilter filter;
// if (extensions == null) {
// filter = TrueFileFilter.INSTANCE;
// } else {
// String[] suffixes = toSuffixes(extensions);
// filter = new SuffixFileFilter(suffixes);
// }
// return listFiles(directory, filter,
// (recursive ? TrueFileFilter.INSTANCE : FalseFileFilter.INSTANCE));
// }
/**
* Allows iteration over the files in a given directory (and optionally
* its subdirectories) which match an array of extensions. This method
* is based on {@link #listFiles(File, String[], boolean)},
* which supports Iterable ('foreach' loop).
*
* @param directory the directory to search in
* @param extensions an array of extensions, ex. {"java","xml"}. If this
* parameter is <code>null</code>, all files are returned.
* @param recursive if true all subdirectories are searched as well
* @return an iterator of java.io.File with the matching files
* @since Commons IO 1.2
*/
// public static Iterator<File> iterateFiles(
// File directory, String[] extensions, boolean recursive) {
// return listFiles(directory, extensions, recursive).iterator();
// }
//-----------------------------------------------------------------------
/**
* Compares the contents of two files to determine if they are equal or not.
* <p>
* This method checks to see if the two files are different lengths
* or if they point to the same file, before resorting to byte-by-byte
* comparison of the contents.
* <p>
* Code origin: Avalon
*
* @param file1 the first file
* @param file2 the second file
* @return true if the content of the files are equal or they both don't
* exist, false otherwise
* @throws IOException in case of an I/O error
*/
public static boolean contentEquals(File file1, File file2) throws IOException {
boolean file1Exists = file1.exists();
if (file1Exists != file2.exists()) {
return false;
}
if (!file1Exists) {
// two not existing files are equal
return true;
}
if (file1.isDirectory() || file2.isDirectory()) {
// don't want to compare directory contents
throw new IOException("Can't compare directories, only files");
}
if (file1.length() != file2.length()) {
// lengths differ, cannot be equal
return false;
}
if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) {
// same file
return true;
}
InputStream input1 = null;
InputStream input2 = null;
try {
input1 = new FileInputStream(file1);
input2 = new FileInputStream(file2);
return IOUtils.contentEquals(input1, input2);
} finally {
IOUtils.closeQuietly(input1);
IOUtils.closeQuietly(input2);
}
}
//-----------------------------------------------------------------------
/**
* Convert from a <code>URL</code> to a <code>File</code>.
* <p>
* From version 1.1 this method will decode the URL.
* Syntax such as <code>file:///my%20docs/file.txt</code> will be
* correctly decoded to <code>/my docs/file.txt</code>. Starting with version
* 1.5, this method uses UTF-8 to decode percent-encoded octets to characters.
* Additionally, malformed percent-encoded octets are handled leniently by
* passing them through literally.
*
* @param url the file URL to convert, <code>null</code> returns <code>null</code>
* @return the equivalent <code>File</code> object, or <code>null</code>
* if the URL's protocol is not <code>file</code>
*/
public static File toFile(URL url) {
if (url == null || !"file".equalsIgnoreCase(url.getProtocol())) {
return null;
} else {
String filename = url.getFile().replace('/', File.separatorChar);
filename = decodeUrl(filename);
return new File(filename);
}
}
/**
* Decodes the specified URL as per RFC 3986, i.e. transforms
* percent-encoded octets to characters by decoding with the UTF-8 character
* set. This function is primarily intended for usage with
* {@link java.net.URL} which unfortunately does not enforce proper URLs. As
* such, this method will leniently accept invalid characters or malformed
* percent-encoded octets and simply pass them literally through to the
* result string. Except for rare edge cases, this will make unencoded URLs
* pass through unaltered.
*
* @param url The URL to decode, may be <code>null</code>.
* @return The decoded URL or <code>null</code> if the input was
* <code>null</code>.
*/
static String decodeUrl(String url) {
String decoded = url;
if (url != null && url.indexOf('%') >= 0) {
int n = url.length();
StringBuffer buffer = new StringBuffer();
ByteBuffer bytes = ByteBuffer.allocate(n);
for (int i = 0; i < n;) {
if (url.charAt(i) == '%') {
try {
do {
byte octet = (byte) Integer.parseInt(url.substring(i + 1, i + 3), 16);
bytes.put(octet);
i += 3;
} while (i < n && url.charAt(i) == '%');
continue;
} catch (RuntimeException e) {
// malformed percent-encoded octet, fall through and
// append characters literally
} finally {
if (bytes.position() > 0) {
bytes.flip();
buffer.append(UTF8.decode(bytes).toString());
bytes.clear();
}
}
}
buffer.append(url.charAt(i++));
}
decoded = buffer.toString();
}
return decoded;
}
/**
* Converts each of an array of <code>URL</code> to a <code>File</code>.
* <p>
* Returns an array of the same size as the input.
* If the input is <code>null</code>, an empty array is returned.
* If the input contains <code>null</code>, the output array contains <code>null</code> at the same
* index.
* <p>
* This method will decode the URL.
* Syntax such as <code>file:///my%20docs/file.txt</code> will be
* correctly decoded to <code>/my docs/file.txt</code>.
*
* @param urls the file URLs to convert, <code>null</code> returns empty array
* @return a non-<code>null</code> array of Files matching the input, with a <code>null</code> item
* if there was a <code>null</code> at that index in the input array
* @throws IllegalArgumentException if any file is not a URL file
* @throws IllegalArgumentException if any file is incorrectly encoded
* @since Commons IO 1.1
*/
public static File[] toFiles(URL[] urls) {
if (urls == null || urls.length == 0) {
return EMPTY_FILE_ARRAY;
}
File[] files = new File[urls.length];
for (int i = 0; i < urls.length; i++) {
URL url = urls[i];
if (url != null) {
if (url.getProtocol().equals("file") == false) {
throw new IllegalArgumentException(
"URL could not be converted to a File: " + url);
}
files[i] = toFile(url);
}
}
return files;
}
/**
* Converts each of an array of <code>File</code> to a <code>URL</code>.
* <p>
* Returns an array of the same size as the input.
*
* @param files the files to convert
* @return an array of URLs matching the input
* @throws IOException if a file cannot be converted
*/
public static URL[] toURLs(File[] files) throws IOException {
URL[] urls = new URL[files.length];
for (int i = 0; i < urls.length; i++) {
urls[i] = files[i].toURI().toURL();
}
return urls;
}
//-----------------------------------------------------------------------
/**
* Copies a file to a directory preserving the file date.
* <p>
* This method copies the contents of the specified source file
* to a file of the same name in the specified destination directory.
* The destination directory is created if it does not exist.
* If the destination file exists, then this method will overwrite it.
* <p>
* <strong>Note:</strong> This method tries to preserve the file's last
* modified date/times using {@link File#setLastModified(long)}, however
* it is not guaranteed that the operation will succeed.
* If the modification operation fails, no indication is provided.
*
* @param srcFile an existing file to copy, must not be <code>null</code>
* @param destDir the directory to place the copy in, must not be <code>null</code>
*
* @throws NullPointerException if source or destination is null
* @throws IOException if source or destination is invalid
* @throws IOException if an IO error occurs during copying
* @see #copyFile(File, File, boolean)
*/
public static void copyFileToDirectory(File srcFile, File destDir) throws IOException {
copyFileToDirectory(srcFile, destDir, true);
}
/**
* Copies a file to a directory optionally preserving the file date.
* <p>
* This method copies the contents of the specified source file
* to a file of the same name in the specified destination directory.
* The destination directory is created if it does not exist.
* If the destination file exists, then this method will overwrite it.
* <p>
* <strong>Note:</strong> Setting <code>preserveFileDate</code> to
* <code>true</code> tries to preserve the file's last modified
* date/times using {@link File#setLastModified(long)}, however it is
* not guaranteed that the operation will succeed.
* If the modification operation fails, no indication is provided.
*
* @param srcFile an existing file to copy, must not be <code>null</code>
* @param destDir the directory to place the copy in, must not be <code>null</code>
* @param preserveFileDate true if the file date of the copy
* should be the same as the original
*
* @throws NullPointerException if source or destination is <code>null</code>
* @throws IOException if source or destination is invalid
* @throws IOException if an IO error occurs during copying
* @see #copyFile(File, File, boolean)
* @since Commons IO 1.3
*/
public static void copyFileToDirectory(File srcFile, File destDir, boolean preserveFileDate) throws IOException {
if (destDir == null) {
throw new NullPointerException("Destination must not be null");
}
if (destDir.exists() && destDir.isDirectory() == false) {
throw new IllegalArgumentException("Destination '" + destDir + "' is not a directory");
}
File destFile = new File(destDir, srcFile.getName());
copyFile(srcFile, destFile, preserveFileDate);
}
/**
* Copies a file to a new location preserving the file date.
* <p>
* This method copies the contents of the specified source file to the
* specified destination file. The directory holding the destination file is
* created if it does not exist. If the destination file exists, then this
* method will overwrite it.
* <p>
* <strong>Note:</strong> This method tries to preserve the file's last
* modified date/times using {@link File#setLastModified(long)}, however
* it is not guaranteed that the operation will succeed.
* If the modification operation fails, no indication is provided.
*
* @param srcFile an existing file to copy, must not be <code>null</code>
* @param destFile the new file, must not be <code>null</code>
*
* @throws NullPointerException if source or destination is <code>null</code>
* @throws IOException if source or destination is invalid
* @throws IOException if an IO error occurs during copying
* @see #copyFileToDirectory(File, File)
*/
public static void copyFile(File srcFile, File destFile) throws IOException {
copyFile(srcFile, destFile, true);
}
/**
* Copies a file to a new location.
* <p>
* This method copies the contents of the specified source file
* to the specified destination file.
* The directory holding the destination file is created if it does not exist.
* If the destination file exists, then this method will overwrite it.
* <p>
* <strong>Note:</strong> Setting <code>preserveFileDate</code> to
* <code>true</code> tries to preserve the file's last modified
* date/times using {@link File#setLastModified(long)}, however it is
* not guaranteed that the operation will succeed.
* If the modification operation fails, no indication is provided.
*
* @param srcFile an existing file to copy, must not be <code>null</code>
* @param destFile the new file, must not be <code>null</code>
* @param preserveFileDate true if the file date of the copy
* should be the same as the original
*
* @throws NullPointerException if source or destination is <code>null</code>
* @throws IOException if source or destination is invalid
* @throws IOException if an IO error occurs during copying
* @see #copyFileToDirectory(File, File, boolean)
*/
public static void copyFile(File srcFile, File destFile,
boolean preserveFileDate) throws IOException {
if (srcFile == null) {
throw new NullPointerException("Source must not be null");
}
if (destFile == null) {
throw new NullPointerException("Destination must not be null");
}
if (srcFile.exists() == false) {
throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
}
if (srcFile.isDirectory()) {
throw new IOException("Source '" + srcFile + "' exists but is a directory");
}
if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {
throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");
}
if (destFile.getParentFile() != null && destFile.getParentFile().exists() == false) {
if (destFile.getParentFile().mkdirs() == false) {
throw new IOException("Destination '" + destFile + "' directory cannot be created");
}
}
if (destFile.exists() && destFile.canWrite() == false) {
throw new IOException("Destination '" + destFile + "' exists but is read-only");
}
doCopyFile(srcFile, destFile, preserveFileDate);
}
/**
* Internal copy file method.
*
* @param srcFile the validated source file, must not be <code>null</code>
* @param destFile the validated destination file, must not be <code>null</code>
* @param preserveFileDate whether to preserve the file date
* @throws IOException if an error occurs
*/
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
if (destFile.exists() && destFile.isDirectory()) {
throw new IOException("Destination '" + destFile + "' exists but is a directory");
}
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel input = null;
FileChannel output = null;
try {
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
input = fis.getChannel();
output = fos.getChannel();
long size = input.size();
long pos = 0;
long count = 0;
while (pos < size) {
count = (size - pos) > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : (size - pos);
pos += output.transferFrom(input, pos, count);
}
} finally {
IOUtils.closeQuietly(output);
IOUtils.closeQuietly(fos);
IOUtils.closeQuietly(input);
IOUtils.closeQuietly(fis);
}
if (srcFile.length() != destFile.length()) {
throw new IOException("Failed to copy full contents from '" +
srcFile + "' to '" + destFile + "'");
}
if (preserveFileDate) {
destFile.setLastModified(srcFile.lastModified());
}
}
//-----------------------------------------------------------------------
/**
* Copies a directory to within another directory preserving the file dates.
* <p>
* This method copies the source directory and all its contents to a
* directory of the same name in the specified destination directory.
* <p>
* The destination directory is created if it does not exist.
* If the destination directory did exist, then this method merges
* the source with the destination, with the source taking precedence.
* <p>
* <strong>Note:</strong> This method tries to preserve the files' last
* modified date/times using {@link File#setLastModified(long)}, however
* it is not guaranteed that those operations will succeed.
* If the modification operation fails, no indication is provided.
*
* @param srcDir an existing directory to copy, must not be <code>null</code>
* @param destDir the directory to place the copy in, must not be <code>null</code>
*
* @throws NullPointerException if source or destination is <code>null</code>
* @throws IOException if source or destination is invalid
* @throws IOException if an IO error occurs during copying
* @since Commons IO 1.2
*/
public static void copyDirectoryToDirectory(File srcDir, File destDir) throws IOException {
if (srcDir == null) {
throw new NullPointerException("Source must not be null");
}
if (srcDir.exists() && srcDir.isDirectory() == false) {
throw new IllegalArgumentException("Source '" + destDir + "' is not a directory");
}
if (destDir == null) {
throw new NullPointerException("Destination must not be null");
}
if (destDir.exists() && destDir.isDirectory() == false) {
throw new IllegalArgumentException("Destination '" + destDir + "' is not a directory");
}
copyDirectory(srcDir, new File(destDir, srcDir.getName()), true);
}
/**
* Copies a whole directory to a new location preserving the file dates.
* <p>
* This method copies the specified directory and all its child
* directories and files to the specified destination.
* The destination is the new location and name of the directory.
* <p>
* The destination directory is created if it does not exist.
* If the destination directory did exist, then this method merges
* the source with the destination, with the source taking precedence.
* <p>
* <strong>Note:</strong> This method tries to preserve the files' last
* modified date/times using {@link File#setLastModified(long)}, however
* it is not guaranteed that those operations will succeed.
* If the modification operation fails, no indication is provided.
*
* @param srcDir an existing directory to copy, must not be <code>null</code>
* @param destDir the new directory, must not be <code>null</code>
*
* @throws NullPointerException if source or destination is <code>null</code>
* @throws IOException if source or destination is invalid
* @throws IOException if an IO error occurs during copying
* @since Commons IO 1.1
*/
public static void copyDirectory(File srcDir, File destDir) throws IOException {
copyDirectory(srcDir, destDir, true);
}
/**
* Copies a whole directory to a new location.
* <p>
* This method copies the contents of the specified source directory
* to within the specified destination directory.
* <p>
* The destination directory is created if it does not exist.
* If the destination directory did exist, then this method merges
* the source with the destination, with the source taking precedence.
* <p>
* <strong>Note:</strong> Setting <code>preserveFileDate</code> to
* <code>true</code> tries to preserve the files' last modified
* date/times using {@link File#setLastModified(long)}, however it is
* not guaranteed that those operations will succeed.
* If the modification operation fails, no indication is provided.
*
* @param srcDir an existing directory to copy, must not be <code>null</code>
* @param destDir the new directory, must not be <code>null</code>
* @param preserveFileDate true if the file date of the copy
* should be the same as the original
*
* @throws NullPointerException if source or destination is <code>null</code>
* @throws IOException if source or destination is invalid
* @throws IOException if an IO error occurs during copying
* @since Commons IO 1.1
*/
public static void copyDirectory(File srcDir, File destDir,
boolean preserveFileDate) throws IOException {
copyDirectory(srcDir, destDir, null, preserveFileDate);
}
/**
* Copies a filtered directory to a new location preserving the file dates.
* <p>
* This method copies the contents of the specified source directory
* to within the specified destination directory.
* <p>
* The destination directory is created if it does not exist.
* If the destination directory did exist, then this method merges
* the source with the destination, with the source taking precedence.
* <p>
* <strong>Note:</strong> This method tries to preserve the files' last
* modified date/times using {@link File#setLastModified(long)}, however
* it is not guaranteed that those operations will succeed.
* If the modification operation fails, no indication is provided.
*
* <h4>Example: Copy directories only</h4>
* <pre>
* // only copy the directory structure
* FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY);
* </pre>
*
* <h4>Example: Copy directories and txt files</h4>
* <pre>
* // Create a filter for ".txt" files
* IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt");
* IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter);
*
* // Create a filter for either directories or ".txt" files
* FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles);
*
* // Copy using the filter
* FileUtils.copyDirectory(srcDir, destDir, filter);
* </pre>
*
* @param srcDir an existing directory to copy, must not be <code>null</code>
* @param destDir the new directory, must not be <code>null</code>
* @param filter the filter to apply, null means copy all directories and files
* should be the same as the original
*
* @throws NullPointerException if source or destination is <code>null</code>
* @throws IOException if source or destination is invalid
* @throws IOException if an IO error occurs during copying
* @since Commons IO 1.4
*/
public static void copyDirectory(File srcDir, File destDir,
FileFilter filter) throws IOException {
copyDirectory(srcDir, destDir, filter, true);
}
/**
* Copies a filtered directory to a new location.
* <p>
* This method copies the contents of the specified source directory
* to within the specified destination directory.
* <p>
* The destination directory is created if it does not exist.
* If the destination directory did exist, then this method merges
* the source with the destination, with the source taking precedence.
* <p>
* <strong>Note:</strong> Setting <code>preserveFileDate</code> to
* <code>true</code> tries to preserve the files' last modified
* date/times using {@link File#setLastModified(long)}, however it is
* not guaranteed that those operations will succeed.
* If the modification operation fails, no indication is provided.
*
* <h4>Example: Copy directories only</h4>
* <pre>
* // only copy the directory structure
* FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY, false);
* </pre>
*
* <h4>Example: Copy directories and txt files</h4>
* <pre>
* // Create a filter for ".txt" files
* IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt");
* IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter);
*
* // Create a filter for either directories or ".txt" files
* FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles);
*
* // Copy using the filter
* FileUtils.copyDirectory(srcDir, destDir, filter, false);
* </pre>
*
* @param srcDir an existing directory to copy, must not be <code>null</code>
* @param destDir the new directory, must not be <code>null</code>
* @param filter the filter to apply, null means copy all directories and files
* @param preserveFileDate true if the file date of the copy
* should be the same as the original
*
* @throws NullPointerException if source or destination is <code>null</code>
* @throws IOException if source or destination is invalid
* @throws IOException if an IO error occurs during copying
* @since Commons IO 1.4
*/
public static void copyDirectory(File srcDir, File destDir,
FileFilter filter, boolean preserveFileDate) throws IOException {
if (srcDir == null) {
throw new NullPointerException("Source must not be null");
}
if (destDir == null) {
throw new NullPointerException("Destination must not be null");
}
if (srcDir.exists() == false) {
throw new FileNotFoundException("Source '" + srcDir + "' does not exist");
}
if (srcDir.isDirectory() == false) {
throw new IOException("Source '" + srcDir + "' exists but is not a directory");
}
if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) {
throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same");
}
// Cater for destination being directory within the source directory (see IO-141)
List<String> exclusionList = null;
if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) {
File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
if (srcFiles != null && srcFiles.length > 0) {
exclusionList = new ArrayList<String>(srcFiles.length);
for (File srcFile : srcFiles) {
File copiedFile = new File(destDir, srcFile.getName());
exclusionList.add(copiedFile.getCanonicalPath());
}
}
}
doCopyDirectory(srcDir, destDir, filter, preserveFileDate, exclusionList);
}
/**
* Internal copy directory method.
*
* @param srcDir the validated source directory, must not be <code>null</code>
* @param destDir the validated destination directory, must not be <code>null</code>
* @param filter the filter to apply, null means copy all directories and files
* @param preserveFileDate whether to preserve the file date
* @param exclusionList List of files and directories to exclude from the copy, may be null
* @throws IOException if an error occurs
* @since Commons IO 1.1
*/
private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter,
boolean preserveFileDate, List<String> exclusionList) throws IOException {
// recurse
File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
if (srcFiles == null) { // null if abstract pathname does not denote a directory, or if an I/O error occurs
throw new IOException("Failed to list contents of " + srcDir);
}
if (destDir.exists()) {
if (destDir.isDirectory() == false) {
throw new IOException("Destination '" + destDir + "' exists but is not a directory");
}
} else {
if (destDir.mkdirs() == false) {
throw new IOException("Destination '" + destDir + "' directory cannot be created");
}
}
if (destDir.canWrite() == false) {
throw new IOException("Destination '" + destDir + "' cannot be written to");
}
for (File srcFile : srcFiles) {
File dstFile = new File(destDir, srcFile.getName());
if (exclusionList == null || !exclusionList.contains(srcFile.getCanonicalPath())) {
if (srcFile.isDirectory()) {
doCopyDirectory(srcFile, dstFile, filter, preserveFileDate, exclusionList);
} else {
doCopyFile(srcFile, dstFile, preserveFileDate);
}
}
}
// Do this last, as the above has probably affected directory metadata
if (preserveFileDate) {
destDir.setLastModified(srcDir.lastModified());
}
}
//-----------------------------------------------------------------------
/**
* Copies bytes from the URL <code>source</code> to a file
* <code>destination</code>. The directories up to <code>destination</code>
* will be created if they don't already exist. <code>destination</code>
* will be overwritten if it already exists.
* <p>
* Warning: this method does not set a connection or read timeout and thus
* might block forever. Use {@link #copyURLToFile(URL, File, int, int)}
* with reasonable timeouts to prevent this.
*
* @param source the <code>URL</code> to copy bytes from, must not be <code>null</code>
* @param destination the non-directory <code>File</code> to write bytes to
* (possibly overwriting), must not be <code>null</code>
* @throws IOException if <code>source</code> URL cannot be opened
* @throws IOException if <code>destination</code> is a directory
* @throws IOException if <code>destination</code> cannot be written
* @throws IOException if <code>destination</code> needs creating but can't be
* @throws IOException if an IO error occurs during copying
*/
public static void copyURLToFile(URL source, File destination) throws IOException {
InputStream input = source.openStream();
copyInputStreamToFile(input, destination);
}
/**
* Copies bytes from the URL <code>source</code> to a file
* <code>destination</code>. The directories up to <code>destination</code>
* will be created if they don't already exist. <code>destination</code>
* will be overwritten if it already exists.
*
* @param source the <code>URL</code> to copy bytes from, must not be <code>null</code>
* @param destination the non-directory <code>File</code> to write bytes to
* (possibly overwriting), must not be <code>null</code>
* @param connectionTimeout the number of milliseconds until this method
* will timeout if no connection could be established to the <code>source</code>
* @param readTimeout the number of milliseconds until this method will
* timeout if no data could be read from the <code>source</code>
* @throws IOException if <code>source</code> URL cannot be opened
* @throws IOException if <code>destination</code> is a directory
* @throws IOException if <code>destination</code> cannot be written
* @throws IOException if <code>destination</code> needs creating but can't be
* @throws IOException if an IO error occurs during copying
* @since Commons IO 2.0
*/
public static void copyURLToFile(URL source, File destination,
int connectionTimeout, int readTimeout) throws IOException {
URLConnection connection = source.openConnection();
connection.setConnectTimeout(connectionTimeout);
connection.setReadTimeout(readTimeout);
InputStream input = connection.getInputStream();
copyInputStreamToFile(input, destination);
}
/**
* Copies bytes from an {@link InputStream} <code>source</code> to a file
* <code>destination</code>. The directories up to <code>destination</code>
* will be created if they don't already exist. <code>destination</code>
* will be overwritten if it already exists.
*
* @param source the <code>InputStream</code> to copy bytes from, must not be <code>null</code>
* @param destination the non-directory <code>File</code> to write bytes to
* (possibly overwriting), must not be <code>null</code>
* @throws IOException if <code>destination</code> is a directory
* @throws IOException if <code>destination</code> cannot be written
* @throws IOException if <code>destination</code> needs creating but can't be
* @throws IOException if an IO error occurs during copying
* @since Commons IO 2.0
*/
public static void copyInputStreamToFile(InputStream source, File destination) throws IOException {
try {
FileOutputStream output = openOutputStream(destination);
try {
IOUtils.copy(source, output);
} finally {
IOUtils.closeQuietly(output);
}
} finally {
IOUtils.closeQuietly(source);
}
}
//-----------------------------------------------------------------------
/**
* Deletes a directory recursively.
*
* @param directory directory to delete
* @throws IOException in case deletion is unsuccessful
*/
public static void deleteDirectory(File directory) throws IOException {
if (!directory.exists()) {
return;
}
if (!isSymlink(directory)) {
cleanDirectory(directory);
}
if (!directory.delete()) {
String message =
"Unable to delete directory " + directory + ".";
throw new IOException(message);
}
}
/**
* Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories.
* <p>
* The difference between File.delete() and this method are:
* <ul>
* <li>A directory to be deleted does not have to be empty.</li>
* <li>No exceptions are thrown when a file or directory cannot be deleted.</li>
* </ul>
*
* @param file file or directory to delete, can be <code>null</code>
* @return <code>true</code> if the file or directory was deleted, otherwise
* <code>false</code>
*
* @since Commons IO 1.4
*/
public static boolean deleteQuietly(File file) {
if (file == null) {
return false;
}
try {
if (file.isDirectory()) {
cleanDirectory(file);
}
} catch (Exception ignored) {
}
try {
return file.delete();
} catch (Exception ignored) {
return false;
}
}
/**
* Cleans a directory without deleting it.
*
* @param directory directory to clean
* @throws IOException in case cleaning is unsuccessful
*/
public static void cleanDirectory(File directory) throws IOException {
if (!directory.exists()) {
String message = directory + " does not exist";
throw new IllegalArgumentException(message);
}
if (!directory.isDirectory()) {
String message = directory + " is not a directory";
throw new IllegalArgumentException(message);
}
File[] files = directory.listFiles();
if (files == null) { // null if security restricted
throw new IOException("Failed to list contents of " + directory);
}
IOException exception = null;
for (File file : files) {
try {
forceDelete(file);
} catch (IOException ioe) {
exception = ioe;
}
}
if (null != exception) {
throw exception;
}
}
//-----------------------------------------------------------------------
/**
* Waits for NFS to propagate a file creation, imposing a timeout.
* <p>
* This method repeatedly tests {@link File#exists()} until it returns
* true up to the maximum time specified in seconds.
*
* @param file the file to check, must not be <code>null</code>
* @param seconds the maximum time in seconds to wait
* @return true if file exists
* @throws NullPointerException if the file is <code>null</code>
*/
public static boolean waitFor(File file, int seconds) {
int timeout = 0;
int tick = 0;
while (!file.exists()) {
if (tick++ >= 10) {
tick = 0;
if (timeout++ > seconds) {
return false;
}
}
try {
Thread.sleep(100);
} catch (InterruptedException ignore) {
// ignore exception
} catch (Exception ex) {
break;
}
}
return true;
}
//-----------------------------------------------------------------------
/**
* Reads the contents of a file into a String.
* The file is always closed.
*
* @param file the file to read, must not be <code>null</code>
* @param encoding the encoding to use, <code>null</code> means platform default
* @return the file contents, never <code>null</code>
* @throws IOException in case of an I/O error
* @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
*/
public static String readFileToString(File file, String encoding) throws IOException {
InputStream in = null;
try {
in = openInputStream(file);
return IOUtils.toString(in, encoding);
} finally {
IOUtils.closeQuietly(in);
}
}
/**
* Reads the contents of a file into a String using the default encoding for the VM.
* The file is always closed.
*
* @param file the file to read, must not be <code>null</code>
* @return the file contents, never <code>null</code>
* @throws IOException in case of an I/O error
* @since Commons IO 1.3.1
*/
public static String readFileToString(File file) throws IOException {
return readFileToString(file, null);
}
/**
* Reads the contents of a file into a byte array.
* The file is always closed.
*
* @param file the file to read, must not be <code>null</code>
* @return the file contents, never <code>null</code>
* @throws IOException in case of an I/O error
* @since Commons IO 1.1
*/
public static byte[] readFileToByteArray(File file) throws IOException {
InputStream in = null;
try {
in = openInputStream(file);
return IOUtils.toByteArray(in, file.length());
} finally {
IOUtils.closeQuietly(in);
}
}
/**
* Reads the contents of a file line by line to a List of Strings.
* The file is always closed.
*
* @param file the file to read, must not be <code>null</code>
* @param encoding the encoding to use, <code>null</code> means platform default
* @return the list of Strings representing each line in the file, never <code>null</code>
* @throws IOException in case of an I/O error
* @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
* @since Commons IO 1.1
*/
public static List<String> readLines(File file, String encoding) throws IOException {
InputStream in = null;
try {
in = openInputStream(file);
return IOUtils.readLines(in, encoding);
} finally {
IOUtils.closeQuietly(in);
}
}
/**
* Reads the contents of a file line by line to a List of Strings using the default encoding for the VM.
* The file is always closed.
*
* @param file the file to read, must not be <code>null</code>
* @return the list of Strings representing each line in the file, never <code>null</code>
* @throws IOException in case of an I/O error
* @since Commons IO 1.3
*/
public static List<String> readLines(File file) throws IOException {
return readLines(file, null);
}
/**
* Returns an Iterator for the lines in a <code>File</code>.
* <p>
* This method opens an <code>InputStream</code> for the file.
* When you have finished with the iterator you should close the stream
* to free internal resources. This can be done by calling the
* {@link LineIterator#close()} or
* {@link LineIterator#closeQuietly(LineIterator)} method.
* <p>
* The recommended usage pattern is:
* <pre>
* LineIterator it = FileUtils.lineIterator(file, "UTF-8");
* try {
* while (it.hasNext()) {
* String line = it.nextLine();
* /// do something with line
* }
* } finally {
* LineIterator.closeQuietly(iterator);
* }
* </pre>
* <p>
* If an exception occurs during the creation of the iterator, the
* underlying stream is closed.
*
* @param file the file to open for input, must not be <code>null</code>
* @param encoding the encoding to use, <code>null</code> means platform default
* @return an Iterator of the lines in the file, never <code>null</code>
* @throws IOException in case of an I/O error (file closed)
* @since Commons IO 1.2
*/
public static LineIterator lineIterator(File file, String encoding) throws IOException {
InputStream in = null;
try {
in = openInputStream(file);
return IOUtils.lineIterator(in, encoding);
} catch (IOException ex) {
IOUtils.closeQuietly(in);
throw ex;
} catch (RuntimeException ex) {
IOUtils.closeQuietly(in);
throw ex;
}
}
/**
* Returns an Iterator for the lines in a <code>File</code> using the default encoding for the VM.
*
* @param file the file to open for input, must not be <code>null</code>
* @return an Iterator of the lines in the file, never <code>null</code>
* @throws IOException in case of an I/O error (file closed)
* @since Commons IO 1.3
* @see #lineIterator(File, String)
*/
public static LineIterator lineIterator(File file) throws IOException {
return lineIterator(file, null);
}
//-----------------------------------------------------------------------
/**
* Writes a String to a file creating the file if it does not exist.
*
* NOTE: As from v1.3, the parent directories of the file will be created
* if they do not exist.
*
* @param file the file to write
* @param data the content to write to the file
* @param encoding the encoding to use, <code>null</code> means platform default
* @throws IOException in case of an I/O error
* @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
*/
public static void writeStringToFile(File file, String data, String encoding) throws IOException {
writeStringToFile(file, data, encoding, false);
}
/**
* Writes a String to a file creating the file if it does not exist.
*
* @param file the file to write
* @param data the content to write to the file
* @param encoding the encoding to use, <code>null</code> means platform default
* @param append if <code>true</code>, then the String will be added to the
* end of the file rather than overwriting
* @throws IOException in case of an I/O error
* @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
* @since Commons IO 2.1
*/
public static void writeStringToFile(File file, String data, String encoding, boolean append) throws IOException {
OutputStream out = null;
try {
out = openOutputStream(file, append);
IOUtils.write(data, out, encoding);
} finally {
IOUtils.closeQuietly(out);
}
}
/**
* Writes a String to a file creating the file if it does not exist using the default encoding for the VM.
*
* @param file the file to write
* @param data the content to write to the file
* @throws IOException in case of an I/O error
*/
public static void writeStringToFile(File file, String data) throws IOException {
writeStringToFile(file, data, null, false);
}
/**
* Writes a String to a file creating the file if it does not exist using the default encoding for the VM.
*
* @param file the file to write
* @param data the content to write to the file
* @param append if <code>true</code>, then the String will be added to the
* end of the file rather than overwriting
* @throws IOException in case of an I/O error
* @since Commons IO 2.1
*/
public static void writeStringToFile(File file, String data, boolean append) throws IOException {
writeStringToFile(file, data, null, append);
}
/**
* Writes a CharSequence to a file creating the file if it does not exist using the default encoding for the VM.
*
* @param file the file to write
* @param data the content to write to the file
* @throws IOException in case of an I/O error
* @since Commons IO 2.0
*/
public static void write(File file, CharSequence data) throws IOException {
write(file, data, null, false);
}
/**
* Writes a CharSequence to a file creating the file if it does not exist using the default encoding for the VM.
*
* @param file the file to write
* @param data the content to write to the file
* @param append if <code>true</code>, then the data will be added to the
* end of the file rather than overwriting
* @throws IOException in case of an I/O error
* @since Commons IO 2.1
*/
public static void write(File file, CharSequence data, boolean append) throws IOException {
write(file, data, null, append);
}
/**
* Writes a CharSequence to a file creating the file if it does not exist.
*
* @param file the file to write
* @param data the content to write to the file
* @param encoding the encoding to use, <code>null</code> means platform default
* @throws IOException in case of an I/O error
* @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
* @since Commons IO 2.0
*/
public static void write(File file, CharSequence data, String encoding) throws IOException {
write(file, data, encoding, false);
}
/**
* Writes a CharSequence to a file creating the file if it does not exist.
*
* @param file the file to write
* @param data the content to write to the file
* @param encoding the encoding to use, <code>null</code> means platform default
* @param append if <code>true</code>, then the data will be added to the
* end of the file rather than overwriting
* @throws IOException in case of an I/O error
* @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
* @since IO 2.1
*/
public static void write(File file, CharSequence data, String encoding, boolean append) throws IOException {
String str = data == null ? null : data.toString();
writeStringToFile(file, str, encoding, append);
}
/**
* Writes a byte array to a file creating the file if it does not exist.
* <p>
* NOTE: As from v1.3, the parent directories of the file will be created
* if they do not exist.
*
* @param file the file to write to
* @param data the content to write to the file
* @throws IOException in case of an I/O error
* @since Commons IO 1.1
*/
public static void writeByteArrayToFile(File file, byte[] data) throws IOException {
writeByteArrayToFile(file, data, false);
}
/**
* Writes a byte array to a file creating the file if it does not exist.
*
* @param file the file to write to
* @param data the content to write to the file
* @param append if <code>true</code>, then bytes will be added to the
* end of the file rather than overwriting
* @throws IOException in case of an I/O error
* @since IO 2.1
*/
public static void writeByteArrayToFile(File file, byte[] data, boolean append) throws IOException {
OutputStream out = null;
try {
out = openOutputStream(file, append);
out.write(data);
} finally {
IOUtils.closeQuietly(out);
}
}
/**
* Writes the <code>toString()</code> value of each item in a collection to
* the specified <code>File</code> line by line.
* The specified character encoding and the default line ending will be used.
* <p>
* NOTE: As from v1.3, the parent directories of the file will be created
* if they do not exist.
*
* @param file the file to write to
* @param encoding the encoding to use, <code>null</code> means platform default
* @param lines the lines to write, <code>null</code> entries produce blank lines
* @throws IOException in case of an I/O error
* @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
* @since Commons IO 1.1
*/
public static void writeLines(File file, String encoding, Collection<?> lines) throws IOException {
writeLines(file, encoding, lines, null, false);
}
/**
* Writes the <code>toString()</code> value of each item in a collection to
* the specified <code>File</code> line by line, optionally appending.
* The specified character encoding and the default line ending will be used.
*
* @param file the file to write to
* @param encoding the encoding to use, <code>null</code> means platform default
* @param lines the lines to write, <code>null</code> entries produce blank lines
* @param append if <code>true</code>, then the lines will be added to the
* end of the file rather than overwriting
* @throws IOException in case of an I/O error
* @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
* @since Commons IO 2.1
*/
public static void writeLines(File file, String encoding, Collection<?> lines, boolean append) throws IOException {
writeLines(file, encoding, lines, null, append);
}
/**
* Writes the <code>toString()</code> value of each item in a collection to
* the specified <code>File</code> line by line.
* The default VM encoding and the default line ending will be used.
*
* @param file the file to write to
* @param lines the lines to write, <code>null</code> entries produce blank lines
* @throws IOException in case of an I/O error
* @since Commons IO 1.3
*/
public static void writeLines(File file, Collection<?> lines) throws IOException {
writeLines(file, null, lines, null, false);
}
/**
* Writes the <code>toString()</code> value of each item in a collection to
* the specified <code>File</code> line by line.
* The default VM encoding and the default line ending will be used.
*
* @param file the file to write to
* @param lines the lines to write, <code>null</code> entries produce blank lines
* @param append if <code>true</code>, then the lines will be added to the
* end of the file rather than overwriting
* @throws IOException in case of an I/O error
* @since Commons IO 2.1
*/
public static void writeLines(File file, Collection<?> lines, boolean append) throws IOException {
writeLines(file, null, lines, null, append);
}
/**
* Writes the <code>toString()</code> value of each item in a collection to
* the specified <code>File</code> line by line.
* The specified character encoding and the line ending will be used.
* <p>
* NOTE: As from v1.3, the parent directories of the file will be created
* if they do not exist.
*
* @param file the file to write to
* @param encoding the encoding to use, <code>null</code> means platform default
* @param lines the lines to write, <code>null</code> entries produce blank lines
* @param lineEnding the line separator to use, <code>null</code> is system default
* @throws IOException in case of an I/O error
* @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
* @since Commons IO 1.1
*/
public static void writeLines(File file, String encoding, Collection<?> lines, String lineEnding)
throws IOException {
writeLines(file, encoding, lines, lineEnding, false);
}
/**
* Writes the <code>toString()</code> value of each item in a collection to
* the specified <code>File</code> line by line.
* The specified character encoding and the line ending will be used.
*
* @param file the file to write to
* @param encoding the encoding to use, <code>null</code> means platform default
* @param lines the lines to write, <code>null</code> entries produce blank lines
* @param lineEnding the line separator to use, <code>null</code> is system default
* @param append if <code>true</code>, then the lines will be added to the
* end of the file rather than overwriting
* @throws IOException in case of an I/O error
* @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
* @since Commons IO 2.1
*/
public static void writeLines(File file, String encoding, Collection<?> lines, String lineEnding, boolean append)
throws IOException {
OutputStream out = null;
try {
out = openOutputStream(file, append);
IOUtils.writeLines(lines, lineEnding, out, encoding);
} finally {
IOUtils.closeQuietly(out);
}
}
/**
* Writes the <code>toString()</code> value of each item in a collection to
* the specified <code>File</code> line by line.
* The default VM encoding and the specified line ending will be used.
*
* @param file the file to write to
* @param lines the lines to write, <code>null</code> entries produce blank lines
* @param lineEnding the line separator to use, <code>null</code> is system default
* @throws IOException in case of an I/O error
* @since Commons IO 1.3
*/
public static void writeLines(File file, Collection<?> lines, String lineEnding) throws IOException {
writeLines(file, null, lines, lineEnding, false);
}
/**
* Writes the <code>toString()</code> value of each item in a collection to
* the specified <code>File</code> line by line.
* The default VM encoding and the specified line ending will be used.
*
* @param file the file to write to
* @param lines the lines to write, <code>null</code> entries produce blank lines
* @param lineEnding the line separator to use, <code>null</code> is system default
* @param append if <code>true</code>, then the lines will be added to the
* end of the file rather than overwriting
* @throws IOException in case of an I/O error
* @since Commons IO 2.1
*/
public static void writeLines(File file, Collection<?> lines, String lineEnding, boolean append)
throws IOException {
writeLines(file, null, lines, lineEnding, append);
}
//-----------------------------------------------------------------------
/**
* Deletes a file. If file is a directory, delete it and all sub-directories.
* <p>
* The difference between File.delete() and this method are:
* <ul>
* <li>A directory to be deleted does not have to be empty.</li>
* <li>You get exceptions when a file or directory cannot be deleted.
* (java.io.File methods returns a boolean)</li>
* </ul>
*
* @param file file or directory to delete, must not be <code>null</code>
* @throws NullPointerException if the directory is <code>null</code>
* @throws FileNotFoundException if the file was not found
* @throws IOException in case deletion is unsuccessful
*/
public static void forceDelete(File file) throws IOException {
if (file.isDirectory()) {
deleteDirectory(file);
} else {
boolean filePresent = file.exists();
if (!file.delete()) {
if (!filePresent){
throw new FileNotFoundException("File does not exist: " + file);
}
String message =
"Unable to delete file: " + file;
throw new IOException(message);
}
}
}
/**
* Schedules a file to be deleted when JVM exits.
* If file is directory delete it and all sub-directories.
*
* @param file file or directory to delete, must not be <code>null</code>
* @throws NullPointerException if the file is <code>null</code>
* @throws IOException in case deletion is unsuccessful
*/
public static void forceDeleteOnExit(File file) throws IOException {
if (file.isDirectory()) {
deleteDirectoryOnExit(file);
} else {
file.deleteOnExit();
}
}
/**
* Schedules a directory recursively for deletion on JVM exit.
*
* @param directory directory to delete, must not be <code>null</code>
* @throws NullPointerException if the directory is <code>null</code>
* @throws IOException in case deletion is unsuccessful
*/
private static void deleteDirectoryOnExit(File directory) throws IOException {
if (!directory.exists()) {
return;
}
if (!isSymlink(directory)) {
cleanDirectoryOnExit(directory);
}
directory.deleteOnExit();
}
/**
* Cleans a directory without deleting it.
*
* @param directory directory to clean, must not be <code>null</code>
* @throws NullPointerException if the directory is <code>null</code>
* @throws IOException in case cleaning is unsuccessful
*/
private static void cleanDirectoryOnExit(File directory) throws IOException {
if (!directory.exists()) {
String message = directory + " does not exist";
throw new IllegalArgumentException(message);
}
if (!directory.isDirectory()) {
String message = directory + " is not a directory";
throw new IllegalArgumentException(message);
}
File[] files = directory.listFiles();
if (files == null) { // null if security restricted
throw new IOException("Failed to list contents of " + directory);
}
IOException exception = null;
for (File file : files) {
try {
forceDeleteOnExit(file);
} catch (IOException ioe) {
exception = ioe;
}
}
if (null != exception) {
throw exception;
}
}
/**
* Makes a directory, including any necessary but nonexistent parent
* directories. If a file already exists with specified name but it is
* not a directory then an IOException is thrown.
* If the directory cannot be created (or does not already exist)
* then an IOException is thrown.
*
* @param directory directory to create, must not be <code>null</code>
* @throws NullPointerException if the directory is <code>null</code>
* @throws IOException if the directory cannot be created or the file already exists but is not a directory
*/
public static void forceMkdir(File directory) throws IOException {
if (directory.exists()) {
if (!directory.isDirectory()) {
String message =
"File "
+ directory
+ " exists and is "
+ "not a directory. Unable to create directory.";
throw new IOException(message);
}
} else {
if (!directory.mkdirs()) {
// Double-check that some other thread or process hasn't made
// the directory in the background
if (!directory.isDirectory())
{
String message =
"Unable to create directory " + directory;
throw new IOException(message);
}
}
}
}
//-----------------------------------------------------------------------
/**
* Returns the size of the specified file or directory. If the provided
* {@link File} is a regular file, then the file's length is returned.
* If the argument is a directory, then the size of the directory is
* calculated recursively. If a directory or subdirectory is security
* restricted, its size will not be included.
*
* @param file the regular file or directory to return the size
* of (must not be <code>null</code>).
*
* @return the length of the file, or recursive size of the directory,
* provided (in bytes).
*
* @throws NullPointerException if the file is <code>null</code>
* @throws IllegalArgumentException if the file does not exist.
*
* @since Commons IO 2.0
*/
public static long sizeOf(File file) {
if (!file.exists()) {
String message = file + " does not exist";
throw new IllegalArgumentException(message);
}
if (file.isDirectory()) {
return sizeOfDirectory(file);
} else {
return file.length();
}
}
/**
* Counts the size of a directory recursively (sum of the length of all files).
*
* @param directory directory to inspect, must not be <code>null</code>
* @return size of directory in bytes, 0 if directory is security restricted
* @throws NullPointerException if the directory is <code>null</code>
*/
public static long sizeOfDirectory(File directory) {
if (!directory.exists()) {
String message = directory + " does not exist";
throw new IllegalArgumentException(message);
}
if (!directory.isDirectory()) {
String message = directory + " is not a directory";
throw new IllegalArgumentException(message);
}
long size = 0;
File[] files = directory.listFiles();
if (files == null) { // null if security restricted
return 0L;
}
for (File file : files) {
size += sizeOf(file);
}
return size;
}
//-----------------------------------------------------------------------
/**
* Tests if the specified <code>File</code> is newer than the reference
* <code>File</code>.
*
* @param file the <code>File</code> of which the modification date must
* be compared, must not be <code>null</code>
* @param reference the <code>File</code> of which the modification date
* is used, must not be <code>null</code>
* @return true if the <code>File</code> exists and has been modified more
* recently than the reference <code>File</code>
* @throws IllegalArgumentException if the file is <code>null</code>
* @throws IllegalArgumentException if the reference file is <code>null</code> or doesn't exist
*/
public static boolean isFileNewer(File file, File reference) {
if (reference == null) {
throw new IllegalArgumentException("No specified reference file");
}
if (!reference.exists()) {
throw new IllegalArgumentException("The reference file '"
+ reference + "' doesn't exist");
}
return isFileNewer(file, reference.lastModified());
}
/**
* Tests if the specified <code>File</code> is newer than the specified
* <code>Date</code>.
*
* @param file the <code>File</code> of which the modification date
* must be compared, must not be <code>null</code>
* @param date the date reference, must not be <code>null</code>
* @return true if the <code>File</code> exists and has been modified
* after the given <code>Date</code>.
* @throws IllegalArgumentException if the file is <code>null</code>
* @throws IllegalArgumentException if the date is <code>null</code>
*/
public static boolean isFileNewer(File file, Date date) {
if (date == null) {
throw new IllegalArgumentException("No specified date");
}
return isFileNewer(file, date.getTime());
}
/**
* Tests if the specified <code>File</code> is newer than the specified
* time reference.
*
* @param file the <code>File</code> of which the modification date must
* be compared, must not be <code>null</code>
* @param timeMillis the time reference measured in milliseconds since the
* epoch (00:00:00 GMT, January 1, 1970)
* @return true if the <code>File</code> exists and has been modified after
* the given time reference.
* @throws IllegalArgumentException if the file is <code>null</code>
*/
public static boolean isFileNewer(File file, long timeMillis) {
if (file == null) {
throw new IllegalArgumentException("No specified file");
}
if (!file.exists()) {
return false;
}
return file.lastModified() > timeMillis;
}
//-----------------------------------------------------------------------
/**
* Tests if the specified <code>File</code> is older than the reference
* <code>File</code>.
*
* @param file the <code>File</code> of which the modification date must
* be compared, must not be <code>null</code>
* @param reference the <code>File</code> of which the modification date
* is used, must not be <code>null</code>
* @return true if the <code>File</code> exists and has been modified before
* the reference <code>File</code>
* @throws IllegalArgumentException if the file is <code>null</code>
* @throws IllegalArgumentException if the reference file is <code>null</code> or doesn't exist
*/
public static boolean isFileOlder(File file, File reference) {
if (reference == null) {
throw new IllegalArgumentException("No specified reference file");
}
if (!reference.exists()) {
throw new IllegalArgumentException("The reference file '"
+ reference + "' doesn't exist");
}
return isFileOlder(file, reference.lastModified());
}
/**
* Tests if the specified <code>File</code> is older than the specified
* <code>Date</code>.
*
* @param file the <code>File</code> of which the modification date
* must be compared, must not be <code>null</code>
* @param date the date reference, must not be <code>null</code>
* @return true if the <code>File</code> exists and has been modified
* before the given <code>Date</code>.
* @throws IllegalArgumentException if the file is <code>null</code>
* @throws IllegalArgumentException if the date is <code>null</code>
*/
public static boolean isFileOlder(File file, Date date) {
if (date == null) {
throw new IllegalArgumentException("No specified date");
}
return isFileOlder(file, date.getTime());
}
/**
* Tests if the specified <code>File</code> is older than the specified
* time reference.
*
* @param file the <code>File</code> of which the modification date must
* be compared, must not be <code>null</code>
* @param timeMillis the time reference measured in milliseconds since the
* epoch (00:00:00 GMT, January 1, 1970)
* @return true if the <code>File</code> exists and has been modified before
* the given time reference.
* @throws IllegalArgumentException if the file is <code>null</code>
*/
public static boolean isFileOlder(File file, long timeMillis) {
if (file == null) {
throw new IllegalArgumentException("No specified file");
}
if (!file.exists()) {
return false;
}
return file.lastModified() < timeMillis;
}
//-----------------------------------------------------------------------
/**
* Computes the checksum of a file using the CRC32 checksum routine.
* The value of the checksum is returned.
*
* @param file the file to checksum, must not be <code>null</code>
* @return the checksum value
* @throws NullPointerException if the file or checksum is <code>null</code>
* @throws IllegalArgumentException if the file is a directory
* @throws IOException if an IO error occurs reading the file
* @since Commons IO 1.3
*/
public static long checksumCRC32(File file) throws IOException {
CRC32 crc = new CRC32();
checksum(file, crc);
return crc.getValue();
}
/**
* Computes the checksum of a file using the specified checksum object.
* Multiple files may be checked using one <code>Checksum</code> instance
* if desired simply by reusing the same checksum object.
* For example:
* <pre>
* long csum = FileUtils.checksum(file, new CRC32()).getValue();
* </pre>
*
* @param file the file to checksum, must not be <code>null</code>
* @param checksum the checksum object to be used, must not be <code>null</code>
* @return the checksum specified, updated with the content of the file
* @throws NullPointerException if the file or checksum is <code>null</code>
* @throws IllegalArgumentException if the file is a directory
* @throws IOException if an IO error occurs reading the file
* @since Commons IO 1.3
*/
public static Checksum checksum(File file, Checksum checksum) throws IOException {
if (file.isDirectory()) {
throw new IllegalArgumentException("Checksums can't be computed on directories");
}
InputStream in = null;
try {
in = new CheckedInputStream(new FileInputStream(file), checksum);
IOUtils.copy(in, new NullOutputStream());
} finally {
IOUtils.closeQuietly(in);
}
return checksum;
}
/**
* Moves a directory.
* <p>
* When the destination directory is on another file system, do a "copy and delete".
*
* @param srcDir the directory to be moved
* @param destDir the destination directory
* @throws NullPointerException if source or destination is <code>null</code>
* @throws FileExistsException if the destination directory exists
* @throws IOException if source or destination is invalid
* @throws IOException if an IO error occurs moving the file
* @since Commons IO 1.4
*/
public static void moveDirectory(File srcDir, File destDir) throws IOException {
if (srcDir == null) {
throw new NullPointerException("Source must not be null");
}
if (destDir == null) {
throw new NullPointerException("Destination must not be null");
}
if (!srcDir.exists()) {
throw new FileNotFoundException("Source '" + srcDir + "' does not exist");
}
if (!srcDir.isDirectory()) {
throw new IOException("Source '" + srcDir + "' is not a directory");
}
if (destDir.exists()) {
throw new FileExistsException("Destination '" + destDir + "' already exists");
}
boolean rename = srcDir.renameTo(destDir);
if (!rename) {
copyDirectory( srcDir, destDir );
deleteDirectory( srcDir );
if (srcDir.exists()) {
throw new IOException("Failed to delete original directory '" + srcDir +
"' after copy to '" + destDir + "'");
}
}
}
/**
* Moves a directory to another directory.
*
* @param src the file to be moved
* @param destDir the destination file
* @param createDestDir If <code>true</code> create the destination directory,
* otherwise if <code>false</code> throw an IOException
* @throws NullPointerException if source or destination is <code>null</code>
* @throws FileExistsException if the directory exists in the destination directory
* @throws IOException if source or destination is invalid
* @throws IOException if an IO error occurs moving the file
* @since Commons IO 1.4
*/
public static void moveDirectoryToDirectory(File src, File destDir, boolean createDestDir) throws IOException {
if (src == null) {
throw new NullPointerException("Source must not be null");
}
if (destDir == null) {
throw new NullPointerException("Destination directory must not be null");
}
if (!destDir.exists() && createDestDir) {
destDir.mkdirs();
}
if (!destDir.exists()) {
throw new FileNotFoundException("Destination directory '" + destDir +
"' does not exist [createDestDir=" + createDestDir +"]");
}
if (!destDir.isDirectory()) {
throw new IOException("Destination '" + destDir + "' is not a directory");
}
moveDirectory(src, new File(destDir, src.getName()));
}
/**
* Moves a file.
* <p>
* When the destination file is on another file system, do a "copy and delete".
*
* @param srcFile the file to be moved
* @param destFile the destination file
* @throws NullPointerException if source or destination is <code>null</code>
* @throws FileExistsException if the destination file exists
* @throws IOException if source or destination is invalid
* @throws IOException if an IO error occurs moving the file
* @since Commons IO 1.4
*/
public static void moveFile(File srcFile, File destFile) throws IOException {
if (srcFile == null) {
throw new NullPointerException("Source must not be null");
}
if (destFile == null) {
throw new NullPointerException("Destination must not be null");
}
if (!srcFile.exists()) {
throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
}
if (srcFile.isDirectory()) {
throw new IOException("Source '" + srcFile + "' is a directory");
}
if (destFile.exists()) {
throw new FileExistsException("Destination '" + destFile + "' already exists");
}
if (destFile.isDirectory()) {
throw new IOException("Destination '" + destFile + "' is a directory");
}
boolean rename = srcFile.renameTo(destFile);
if (!rename) {
copyFile( srcFile, destFile );
if (!srcFile.delete()) {
FileUtils.deleteQuietly(destFile);
throw new IOException("Failed to delete original file '" + srcFile +
"' after copy to '" + destFile + "'");
}
}
}
/**
* Moves a file to a directory.
*
* @param srcFile the file to be moved
* @param destDir the destination file
* @param createDestDir If <code>true</code> create the destination directory,
* otherwise if <code>false</code> throw an IOException
* @throws NullPointerException if source or destination is <code>null</code>
* @throws FileExistsException if the destination file exists
* @throws IOException if source or destination is invalid
* @throws IOException if an IO error occurs moving the file
* @since Commons IO 1.4
*/
public static void moveFileToDirectory(File srcFile, File destDir, boolean createDestDir) throws IOException {
if (srcFile == null) {
throw new NullPointerException("Source must not be null");
}
if (destDir == null) {
throw new NullPointerException("Destination directory must not be null");
}
if (!destDir.exists() && createDestDir) {
destDir.mkdirs();
}
if (!destDir.exists()) {
throw new FileNotFoundException("Destination directory '" + destDir +
"' does not exist [createDestDir=" + createDestDir +"]");
}
if (!destDir.isDirectory()) {
throw new IOException("Destination '" + destDir + "' is not a directory");
}
moveFile(srcFile, new File(destDir, srcFile.getName()));
}
/**
* Moves a file or directory to the destination directory.
* <p>
* When the destination is on another file system, do a "copy and delete".
*
* @param src the file or directory to be moved
* @param destDir the destination directory
* @param createDestDir If <code>true</code> create the destination directory,
* otherwise if <code>false</code> throw an IOException
* @throws NullPointerException if source or destination is <code>null</code>
* @throws FileExistsException if the directory or file exists in the destination directory
* @throws IOException if source or destination is invalid
* @throws IOException if an IO error occurs moving the file
* @since Commons IO 1.4
*/
public static void moveToDirectory(File src, File destDir, boolean createDestDir) throws IOException {
if (src == null) {
throw new NullPointerException("Source must not be null");
}
if (destDir == null) {
throw new NullPointerException("Destination must not be null");
}
if (!src.exists()) {
throw new FileNotFoundException("Source '" + src + "' does not exist");
}
if (src.isDirectory()) {
moveDirectoryToDirectory(src, destDir, createDestDir);
} else {
moveFileToDirectory(src, destDir, createDestDir);
}
}
/**
* Determines whether the specified file is a Symbolic Link rather than an actual file.
* <p>
* Will not return true if there is a Symbolic Link anywhere in the path,
* only if the specific file is.
*
* @param file the file to check
* @return true if the file is a Symbolic Link
* @throws IOException if an IO error occurs while checking the file
* @since Commons IO 2.0
*/
public static boolean isSymlink(File file) throws IOException {
if (file == null) {
throw new NullPointerException("File must not be null");
}
File fileInCanonicalDir = null;
if (file.getParent() == null) {
fileInCanonicalDir = file;
} else {
File canonicalDir = file.getParentFile().getCanonicalFile();
fileInCanonicalDir = new File(canonicalDir, file.getName());
}
if (fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile())) {
return false;
} else {
return true;
}
}
}
| {'content_hash': 'e3b76282991909de0a86b772e80f6d24', 'timestamp': '', 'source': 'github', 'line_count': 2446, 'max_line_length': 119, 'avg_line_length': 41.27187244480785, 'alnum_prop': 0.6118611999881131, 'repo_name': 'touchlab/commons-io-mini', 'id': '6decb8da85ef71a24c27d7c79e206f44e0f9f013', 'size': '101755', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/apache/commons/io/FileUtils.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1095449'}]} |
package com.dci.intellij.dbn.data.export.processor;
import com.dci.intellij.dbn.common.locale.Formatter;
import com.dci.intellij.dbn.common.locale.options.RegionalSettings;
import com.dci.intellij.dbn.common.util.StringUtil;
import com.dci.intellij.dbn.connection.ConnectionHandler;
import com.dci.intellij.dbn.data.export.DataExportException;
import com.dci.intellij.dbn.data.export.DataExportFormat;
import com.dci.intellij.dbn.data.export.DataExportInstructions;
import com.dci.intellij.dbn.data.export.DataExportModel;
import com.dci.intellij.dbn.data.type.BasicDataType;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.Date;
public class XMLDataExportProcessor extends DataExportProcessor{
protected DataExportFormat getFormat() {
return DataExportFormat.XML;
}
@Override
public String getFileExtension() {
return "xml";
}
@Override
public String adjustFileName(String fileName) {
if (!fileName.contains(".xml")) {
fileName = fileName + ".xml";
}
return fileName;
}
public boolean canCreateHeader() {
return false;
}
public boolean canExportToClipboard() {
return true;
}
public boolean canQuoteValues() {
return false;
}
@Override
public Transferable createClipboardContent(String content) {
return new XmlContent(content);
}
public class XmlContent implements Transferable {
private DataFlavor[] dataFlavors;
private String content;
public XmlContent(String htmlText) {
content = htmlText;
try {
dataFlavors = new DataFlavor[3];
dataFlavors[0] = new DataFlavor("text/xml;class=java.lang.String");
dataFlavors[1] = new DataFlavor("text/rtf;class=java.lang.String");
dataFlavors[2] = new DataFlavor("text/plain;class=java.lang.String");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public DataFlavor[] getTransferDataFlavors() {
return dataFlavors;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return
"text/xml".equals(flavor.getMimeType()) ||
"text/rtf".equals(flavor.getMimeType()) ||
"text/plain".equals(flavor.getMimeType());
}
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException{
return content;
}
}
public void performExport(DataExportModel model, DataExportInstructions instructions, ConnectionHandler connectionHandler) throws DataExportException {
StringBuilder buffer = new StringBuilder();
buffer.append("<table name=\"");
buffer.append(model.getTableName());
buffer.append("\">\n");
RegionalSettings regionalSettings = RegionalSettings.getInstance(connectionHandler.getProject());
for (int rowIndex=0; rowIndex < model.getRowCount(); rowIndex++) {
buffer.append(" <row index=\"");
buffer.append(rowIndex);
buffer.append("\">\n");
for (int columnIndex=0; columnIndex < model.getColumnCount(); columnIndex++){
String columnName = model.getColumnName(columnIndex);
BasicDataType basicDataType = model.getBasicDataType(columnIndex);
String value = null;
if (basicDataType == BasicDataType.LITERAL ||
basicDataType == BasicDataType.NUMERIC ||
basicDataType == BasicDataType.DATE_TIME) {
Object object = model.getValue(rowIndex, columnIndex);
if (object != null) {
Formatter formatter = regionalSettings.getFormatter();
if (object instanceof Number) {
Number number = (Number) object;
value = formatter.formatNumber(number);
} else if (object instanceof Date) {
Date date = (Date) object;
value = hasTimeComponent(date) ?
formatter.formatDateTime(date) :
formatter.formatDate(date);
} else {
value = object.toString();
}
}
}
if (value == null) value = "";
boolean isCDATA = StringUtil.containsOneOf(value, "\n", "<", ">");
boolean isWrap = value.length() > 100 || isCDATA;
buffer.append(" <column name=\"");
buffer.append(columnName);
buffer.append("\">");
if (isWrap) {
value = ("\n" + value);//.replace("\n", "\n ");
}
if (isCDATA) {
buffer.append("\n <![CDATA[");
buffer.append(value);
buffer.append("\n ]]>");
} else {
buffer.append(value);
}
buffer.append(isWrap ? "\n </column>\n" : "</column>\n");
}
buffer.append(" </row>\n");
}
buffer.append("</table>\n");
writeContent(instructions, buffer.toString());
}
}
| {'content_hash': 'edeb4431fcf750ab81a5da5deba06fe2', 'timestamp': '', 'source': 'github', 'line_count': 157, 'max_line_length': 155, 'avg_line_length': 37.10828025477707, 'alnum_prop': 0.5441125986955029, 'repo_name': 'consulo/consulo-sql', 'id': 'b159e89656c4b43c26a0578317afb4d6b8d12a4f', 'size': '6433', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/com/dci/intellij/dbn/data/export/processor/XMLDataExportProcessor.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '18945'}, {'name': 'HTML', 'bytes': '29057'}, {'name': 'Haskell', 'bytes': '544'}, {'name': 'Java', 'bytes': '6674168'}, {'name': 'Lex', 'bytes': '199690'}]} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ip::address_v4::operator<<</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../ip__address_v4.html" title="ip::address_v4">
<link rel="prev" href="operator_lt_.html" title="ip::address_v4::operator<">
<link rel="next" href="operator_lt__lt_/overload1.html" title="ip::address_v4::operator<< (1 of 2 overloads)">
</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="operator_lt_.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../ip__address_v4.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="operator_lt__lt_/overload1.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_asio.reference.ip__address_v4.operator_lt__lt_"></a><a class="link" href="operator_lt__lt_.html" title="ip::address_v4::operator<<">ip::address_v4::operator<<</a>
</h4></div></div></div>
<p>
<a class="indexterm" name="boost_asio.indexterm.ip__address_v4.operator_lt__lt_"></a>
Output
an address as a string.
</p>
<pre class="programlisting">template<
typename Elem,
typename Traits>
std::basic_ostream< Elem, Traits > & <a class="link" href="operator_lt__lt_/overload1.html" title="ip::address_v4::operator<< (1 of 2 overloads)">operator<<</a>(
std::basic_ostream< Elem, Traits > & os,
const address_v4 & addr);
<span class="emphasis"><em>» <a class="link" href="operator_lt__lt_/overload1.html" title="ip::address_v4::operator<< (1 of 2 overloads)">more...</a></em></span>
</pre>
<p>
Output a network as a string.
</p>
<pre class="programlisting">template<
typename Elem,
typename Traits>
std::basic_ostream< Elem, Traits > & <a class="link" href="operator_lt__lt_/overload2.html" title="ip::address_v4::operator<< (2 of 2 overloads)">operator<<</a>(
std::basic_ostream< Elem, Traits > & os,
const network_v4 & net);
<span class="emphasis"><em>» <a class="link" href="operator_lt__lt_/overload2.html" title="ip::address_v4::operator<< (2 of 2 overloads)">more...</a></em></span>
</pre>
</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 © 2003-2021 Christopher
M. Kohlhoff<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="operator_lt_.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../ip__address_v4.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="operator_lt__lt_/overload1.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {'content_hash': '859df82aeca193f16cfd1fe4dffb3646', 'timestamp': '', 'source': 'github', 'line_count': 68, 'max_line_length': 450, 'avg_line_length': 63.30882352941177, 'alnum_prop': 0.6239256678281069, 'repo_name': 'davehorton/drachtio-server', 'id': '54f6499d3bd68f08b58c4cd46fba95e140d2d169', 'size': '4308', 'binary': False, 'copies': '2', 'ref': 'refs/heads/main', 'path': 'deps/boost_1_77_0/doc/html/boost_asio/reference/ip__address_v4/operator_lt__lt_.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '662596'}, {'name': 'Dockerfile', 'bytes': '1330'}, {'name': 'JavaScript', 'bytes': '60639'}, {'name': 'M4', 'bytes': '35273'}, {'name': 'Makefile', 'bytes': '5960'}, {'name': 'Shell', 'bytes': '47298'}]} |
#ifndef _VIA_DRV_H_
#define _VIA_DRV_H_
#include <drm/drm_mm.h>
#define DRIVER_AUTHOR "Various"
#define DRIVER_NAME "via"
#define DRIVER_DESC "VIA Unichrome / Pro"
#define DRIVER_DATE "20070202"
#define DRIVER_MAJOR 2
#define DRIVER_MINOR 11
#define DRIVER_PATCHLEVEL 1
#include "via_verifier.h"
#include "via_dmablit.h"
#define VIA_PCI_BUF_SIZE 60000
#define VIA_FIRE_BUF_SIZE 1024
#define VIA_NUM_IRQS 4
typedef struct drm_via_ring_buffer {
drm_local_map_t map;
char *virtual_start;
} drm_via_ring_buffer_t;
typedef uint32_t maskarray_t[5];
typedef struct drm_via_irq {
#ifdef __NetBSD__
spinlock_t irq_lock;
unsigned irq_received;
#else
atomic_t irq_received;
#endif
uint32_t pending_mask;
uint32_t enable_mask;
#ifdef __NetBSD__
drm_waitqueue_t irq_queue;
#else
wait_queue_head_t irq_queue;
#endif
} drm_via_irq_t;
typedef struct drm_via_private {
drm_via_sarea_t *sarea_priv;
drm_local_map_t *sarea;
drm_local_map_t *fb;
drm_local_map_t *mmio;
unsigned long agpAddr;
#ifdef __NetBSD__
spinlock_t decoder_lock[VIA_NR_XVMC_LOCKS];
drm_waitqueue_t decoder_queue[VIA_NR_XVMC_LOCKS];
#else
wait_queue_head_t decoder_queue[VIA_NR_XVMC_LOCKS];
#endif
char *dma_ptr;
unsigned int dma_low;
unsigned int dma_high;
unsigned int dma_offset;
uint32_t dma_wrap;
volatile uint32_t *last_pause_ptr;
volatile uint32_t *hw_addr_ptr;
drm_via_ring_buffer_t ring;
struct timeval last_vblank;
int last_vblank_valid;
unsigned usec_per_vblank;
atomic_t vbl_received;
drm_via_state_t hc_state;
char pci_buf[VIA_PCI_BUF_SIZE];
const uint32_t *fire_offsets[VIA_FIRE_BUF_SIZE];
uint32_t num_fire_offsets;
int chipset;
drm_via_irq_t via_irqs[VIA_NUM_IRQS];
unsigned num_irqs;
maskarray_t *irq_masks;
uint32_t irq_enable_mask;
uint32_t irq_pending_mask;
int *irq_map;
unsigned int idle_fault;
int vram_initialized;
struct drm_mm vram_mm;
int agp_initialized;
struct drm_mm agp_mm;
/** Mapping of userspace keys to mm objects */
struct idr object_idr;
unsigned long vram_offset;
unsigned long agp_offset;
drm_via_blitq_t blit_queues[VIA_NUM_BLIT_ENGINES];
uint32_t dma_diff;
} drm_via_private_t;
enum via_family {
VIA_OTHER = 0, /* Baseline */
VIA_PRO_GROUP_A, /* Another video engine and DMA commands */
VIA_DX9_0 /* Same video as pro_group_a, but 3D is unsupported */
};
/* VIA MMIO register access */
#define VIA_BASE ((dev_priv->mmio))
#define VIA_READ(reg) DRM_READ32(VIA_BASE, reg)
#define VIA_WRITE(reg, val) DRM_WRITE32(VIA_BASE, reg, val)
#define VIA_READ8(reg) DRM_READ8(VIA_BASE, reg)
#define VIA_WRITE8(reg, val) DRM_WRITE8(VIA_BASE, reg, val)
extern const struct drm_ioctl_desc via_ioctls[];
extern int via_max_ioctl;
extern int via_fb_init(struct drm_device *dev, void *data, struct drm_file *file_priv);
extern int via_mem_alloc(struct drm_device *dev, void *data, struct drm_file *file_priv);
extern int via_mem_free(struct drm_device *dev, void *data, struct drm_file *file_priv);
extern int via_agp_init(struct drm_device *dev, void *data, struct drm_file *file_priv);
extern int via_map_init(struct drm_device *dev, void *data, struct drm_file *file_priv);
extern int via_decoder_futex(struct drm_device *dev, void *data, struct drm_file *file_priv);
extern int via_wait_irq(struct drm_device *dev, void *data, struct drm_file *file_priv);
extern int via_dma_blit_sync(struct drm_device *dev, void *data, struct drm_file *file_priv);
extern int via_dma_blit(struct drm_device *dev, void *data, struct drm_file *file_priv);
extern int via_driver_load(struct drm_device *dev, unsigned long chipset);
extern int via_driver_unload(struct drm_device *dev);
extern int via_init_context(struct drm_device *dev, int context);
extern int via_final_context(struct drm_device *dev, int context);
extern int via_do_cleanup_map(struct drm_device *dev);
extern u32 via_get_vblank_counter(struct drm_device *dev, int crtc);
extern int via_enable_vblank(struct drm_device *dev, int crtc);
extern void via_disable_vblank(struct drm_device *dev, int crtc);
extern irqreturn_t via_driver_irq_handler(int irq, void *arg);
extern void via_driver_irq_preinstall(struct drm_device *dev);
extern int via_driver_irq_postinstall(struct drm_device *dev);
extern void via_driver_irq_uninstall(struct drm_device *dev);
extern int via_dma_cleanup(struct drm_device *dev);
extern void via_init_command_verifier(void);
extern int via_driver_dma_quiescent(struct drm_device *dev);
extern void via_init_futex(drm_via_private_t *dev_priv);
extern void via_cleanup_futex(drm_via_private_t *dev_priv);
extern void via_release_futex(drm_via_private_t *dev_priv, int context);
extern void via_reclaim_buffers_locked(struct drm_device *dev,
struct drm_file *file_priv);
extern void via_lastclose(struct drm_device *dev);
extern void via_dmablit_handler(struct drm_device *dev, int engine, int from_irq);
extern void via_init_dmablit(struct drm_device *dev);
#endif
| {'content_hash': '1b58141dc8acb77487067268706adab3', 'timestamp': '', 'source': 'github', 'line_count': 152, 'max_line_length': 93, 'avg_line_length': 32.453947368421055, 'alnum_prop': 0.7344415163186702, 'repo_name': 'execunix/vinos', 'id': 'ca486d52f3b9a4ecce0c87521da4e80cbeceb4ad', 'size': '6185', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'sys/external/bsd/drm2/dist/drm/via/via_drv.h', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
package system
import (
"os"
"syscall"
"testing"
"github.com/takama/k8sapp/pkg/logger"
"github.com/takama/k8sapp/pkg/logger/standard"
)
const (
testSignal = syscall.SIGUSR2
customSignalType SignalType = 777
customSignalTypeString = "777"
)
// testHandling implement simplest Operator interface
type testHandling struct {
ch chan SignalType
}
// Reload implementation
func (th testHandling) Reload() error {
th.ch <- Reload
return ErrNotImplemented
}
// Maintenance implementation
func (th testHandling) Maintenance() error {
th.ch <- Maintenance
return ErrNotImplemented
}
// Shutdown implementation
func (th testHandling) Shutdown() error {
th.ch <- Shutdown
return ErrNotImplemented
}
func TestSignals(t *testing.T) {
// Setup logger
log := standard.New(&logger.Config{
Level: logger.LevelDebug,
})
pid := os.Getpid()
proc, err := os.FindProcess(pid)
if err != nil {
t.Error("Finding process:", err)
}
signals := NewSignals()
shutdownSignals := signals.Get(Shutdown)
verifySignal(t, syscall.SIGTERM, shutdownSignals, Shutdown)
verifySignal(t, syscall.SIGINT, shutdownSignals, Shutdown)
reloadSignals := signals.Get(Reload)
verifySignal(t, syscall.SIGHUP, reloadSignals, Reload)
maintenanceSignals := signals.Get(Maintenance)
verifySignal(t, syscall.SIGUSR1, maintenanceSignals, Maintenance)
handling := &testHandling{ch: make(chan SignalType, 1)}
go signals.Wait(log, handling)
// Prepare and send reload signal
signals.Add(testSignal, Reload)
sendSignal(t, handling.ch, proc, Reload)
signals.Remove(testSignal, Reload)
// Prepare and send maintenance signal
signals.Add(testSignal, Maintenance)
sendSignal(t, handling.ch, proc, Maintenance)
signals.Remove(testSignal, Maintenance)
// Prepare and send shutdown signal
signals.Add(testSignal, Shutdown)
sendSignal(t, handling.ch, proc, Shutdown)
signals.Remove(testSignal, Shutdown)
}
func sendSignal(t *testing.T, ch <-chan SignalType, proc *os.Process, signal SignalType) {
err := proc.Signal(testSignal)
if err != nil {
t.Error("Sending signal:", err)
return
}
if sig := <-ch; sig != signal {
t.Error("Expected signal:", signal, "got", sig)
}
return
}
func verifySignal(t *testing.T, signal os.Signal, signals []os.Signal, sigType SignalType) {
if !isSignalAvailable(signal, signals) {
t.Error("Absent of the signal:", signal, "among", sigType, "signal type")
}
}
func TestSignalStringer(t *testing.T) {
var s SignalType
s = Shutdown
if s.String() != "SHUTDOWN" {
t.Error("Expected signal type SHUTDOWN, got", s.String())
}
s = Reload
if s.String() != "RELOAD" {
t.Error("Expected signal type RELOAD, got", s.String())
}
s = Maintenance
if s.String() != "MAINTENANCE" {
t.Error("Expected signal type MAINTENANCE, got", s.String())
}
s = customSignalType
if s.String() != customSignalTypeString {
t.Error("Expected signal type ", customSignalTypeString, "got", s.String())
}
}
func TestRemoveNotExistingSignal(t *testing.T) {
s := NewSignals()
count := len(s.maintenance)
s.Remove(syscall.SIGUSR2, Maintenance)
if len(s.maintenance) != count {
t.Error("Expected count of signals", count, "got", len(s.maintenance))
}
}
| {'content_hash': '7f0620e2dc4ac42a002a79577cff84fd', 'timestamp': '', 'source': 'github', 'line_count': 126, 'max_line_length': 92, 'avg_line_length': 25.571428571428573, 'alnum_prop': 0.7132216014897579, 'repo_name': 'takama/k8sapp', 'id': 'f27d72bde90630ab2b1be741634eb73bdbaadade', 'size': '3222', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'pkg/system/signal_test.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '44516'}, {'name': 'Makefile', 'bytes': '3821'}, {'name': 'Shell', 'bytes': '1646'}, {'name': 'Smarty', 'bytes': '784'}]} |
<div style='visibility: hidden'>
<div #popup class='panel panel-default map-popup'>
<div ng-bind-html='model.tooltip.content | sanitize'></div>
</div>
<div class='arrow_box'></div>
</div>
<div #tooltip class='tooltip' style="display: none"></div>
| {'content_hash': 'df150704aaee89efaa28190fd77ac04c', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 67, 'avg_line_length': 33.5, 'alnum_prop': 0.6380597014925373, 'repo_name': 'intersystems-ru/DeepSeeWeb', 'id': '9e5bf0ac7bc6639cf00aa6ab7be339ca53a3fa80', 'size': '268', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/app/components/widgets/map-widget/map-widget.component.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '128547'}, {'name': 'HTML', 'bytes': '53069'}, {'name': 'JavaScript', 'bytes': '8867095'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="BookmarkManager">
<bookmark url="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/RNN.java" line="36" />
</component>
<component name="ChangeListManager">
<list default="true" id="b3002d8f-4db3-46d6-8600-99affd2dacdf" name="Default" comment="">
<change type="DELETED" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/Algorithm.java" afterPath="" />
<change type="DELETED" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/AlgorithmDriver.java" afterPath="" />
<change type="DELETED" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/MindType.java" afterPath="" />
<change type="DELETED" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/algorithm/BarAnalysis.java" afterPath="" />
<change type="DELETED" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/algorithm/DoubleDifference.java" afterPath="" />
<change type="DELETED" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/algorithm/MAVGReverseDiff.java" afterPath="" />
<change type="DELETED" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/algorithm/MavgDifference.java" afterPath="" />
<change type="DELETED" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/algorithm/TrendHedge.java" afterPath="" />
<change type="DELETED" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/app/AlgorithmManager.java" afterPath="" />
<change type="DELETED" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/app/AlgorithmPanel.java" afterPath="" />
<change type="DELETED" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/order/BaseOrder.java" afterPath="" />
<change type="DELETED" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/order/IOrder.java" afterPath="" />
<change type="DELETED" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/order/MockOrder.java" afterPath="" />
<change type="DELETED" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/order/RealOrder.java" afterPath="" />
<change type="DELETED" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/push/Pusher.java" afterPath="" />
<change type="DELETED" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/push/PusherHandler.java" afterPath="" />
<change type="DELETED" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/push/PusherInitializer.java" afterPath="" />
<change type="MODIFICATION" beforePath="$PROJECT_DIR$/lib/common-0.0.1-SNAPSHOT.jar" afterPath="$PROJECT_DIR$/lib/common-0.0.1-SNAPSHOT.jar" />
<change type="MODIFICATION" beforePath="$PROJECT_DIR$/.idea/workspace.xml" afterPath="$PROJECT_DIR$/.idea/workspace.xml" />
<change type="MODIFICATION" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/func/GeneralUtilizer.java" afterPath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/func/GeneralUtilizer.java" />
<change type="MODIFICATION" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/LearnDirection.java" afterPath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/LearnDirection.java" />
<change type="MODIFICATION" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/BarIterator.java" afterPath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/BarIterator.java" />
<change type="MODIFICATION" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/util/MeanVar.java" afterPath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/util/MeanVar.java" />
<change type="MODIFICATION" beforePath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/util/ModelUtil.java" afterPath="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/util/ModelUtil.java" />
</list>
<ignored path="wisdom.iws" />
<ignored path=".idea/workspace.xml" />
<ignored path="$PROJECT_DIR$/target/" />
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
<option name="TRACKING_ENABLED" value="true" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="ChangesViewManager" flattened_view="true" show_ignored="false" />
<component name="CoverageDataManager">
<SUITE FILE_PATH="coverage/wisdom$AlgorithmDriver.coverage" NAME="AlgorithmDriver Coverage Results" MODIFIED="1456566656987" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="idea" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false">
<FILTER>tongtong.qiangqiang.mind.*</FILTER>
</SUITE>
</component>
<component name="CreatePatchCommitExecutor">
<option name="PATCH_PATH" value="" />
</component>
<component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
<component name="FavoritesManager">
<favorites_list name="wisdom" />
</component>
<component name="FileEditorManager">
<leaf SIDE_TABS_SIZE_LIMIT_KEY="300">
<file leaf-file-name="RNN.java" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/RNN.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="44" column="35" selection-start-line="44" selection-start-column="35" selection-end-line="44" selection-end-column="35" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="ModelUtil.java" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/util/ModelUtil.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="143" column="43" selection-start-line="143" selection-start-column="43" selection-end-line="143" selection-end-column="43" />
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="BarIterator.java" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/BarIterator.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="1" column="0" selection-start-line="1" selection-start-column="0" selection-end-line="1" selection-end-column="0" />
<folding>
<element signature="e#2759#2760#0" expanded="false" />
<element signature="e#2793#2794#0" expanded="false" />
<element signature="e#2840#2841#0" expanded="false" />
<element signature="e#2874#2875#0" expanded="false" />
<element signature="e#2922#2923#0" expanded="false" />
<element signature="e#2956#2957#0" expanded="false" />
<element signature="e#3237#3238#0" expanded="false" />
<element signature="e#3273#3274#0" expanded="false" />
<element signature="e#3314#3315#0" expanded="false" />
<element signature="e#3381#3382#0" expanded="false" />
<element signature="e#3427#3428#0" expanded="false" />
<element signature="e#3465#3466#0" expanded="false" />
<element signature="e#3682#3683#0" expanded="false" />
<element signature="e#3756#3757#0" expanded="false" />
<element signature="e#3802#3803#0" expanded="false" />
<element signature="e#3855#3856#0" expanded="false" />
<element signature="e#3898#3899#0" expanded="false" />
<element signature="e#3940#3941#0" expanded="false" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="KernelSmoothing.java" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/trend/KernelSmoothing.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="48" column="44" selection-start-line="48" selection-start-column="44" selection-end-line="48" selection-end-column="44" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="BarIterator.java" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/trend/BarIterator.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="14" column="47" selection-start-line="14" selection-start-column="47" selection-end-line="14" selection-end-column="47" />
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="RNN.java" pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/trend/RNN.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.47619048">
<caret line="38" column="45" selection-start-line="38" selection-start-column="45" selection-end-line="38" selection-end-column="45" />
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="LearnDirection.java" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/LearnDirection.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="54" column="40" selection-start-line="54" selection-start-column="40" selection-end-line="54" selection-end-column="40" />
<folding>
<element signature="imports" expanded="true" />
<element signature="e#1553#1554#0" expanded="true" />
<element signature="e#1595#1596#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="MeanVar.java" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/util/MeanVar.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="44" column="42" selection-start-line="44" selection-start-column="42" selection-end-line="44" selection-end-column="42" />
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="GeneralUtilizer.java" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/func/GeneralUtilizer.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="172" column="55" selection-start-line="172" selection-start-column="55" selection-end-line="172" selection-end-column="55" />
<folding>
<element signature="e#1657#1658#0" expanded="false" />
<element signature="e#1682#1683#0" expanded="false" />
<element signature="e#2148#2149#0" expanded="false" />
<element signature="e#2200#2201#0" expanded="false" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="TimeSeriesChart.java" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/vis/TimeSeriesChart.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="71" column="0" selection-start-line="71" selection-start-column="0" selection-end-line="71" selection-end-column="0" />
<folding>
<element signature="imports" expanded="false" />
<element signature="e#1163#1164#0" expanded="false" />
<element signature="e#1191#1192#0" expanded="false" />
</folding>
</state>
</provider>
</entry>
</file>
</leaf>
</component>
<component name="FileTemplateManagerImpl">
<option name="RECENT_TEMPLATES">
<list>
<option value="Class" />
</list>
</option>
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="GradleLocalSettings">
<option name="externalProjectsViewState">
<projects_view />
</option>
</component>
<component name="IdeDocumentHistory">
<option name="CHANGED_PATHS">
<list>
<option value="$PROJECT_DIR$/.idea/workspace.xml" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/algorithm/MavgDifference.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/app/AlgorithmManager.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/order/IOrder.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/order/BaseOrder.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/order/MockOrder.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/order/RealOrder.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/app/AlgorithmPanel.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/push/PusherHandler.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/algorithm/MavgReverseDiff.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/algorithm/DoubleDifference.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/RNN.java" />
<option value="$PROJECT_DIR$/pom.xml" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/ModelUtil.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/MeanVar.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/util/MathUtil.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/RNN.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/trend/KernelSmoothing.kt" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/vis/TimeSeriesChart.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/algorithm/BarAnalysis.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/Algorithm.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/push/Pusher.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/util/ModelUtil.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/mind/algorithm/TrendHedge.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/BarIterator.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/util/MeanVar.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/func/GeneralUtilizer.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/trend/KernelSmoothing.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/LearnDirection.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/trend/BarIterator.java" />
<option value="$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/trend/RNN.java" />
</list>
</option>
</component>
<component name="MavenImportPreferences">
<option name="generalSettings">
<MavenGeneralSettings>
<option name="mavenHome" value="Bundled (Maven 3)" />
</MavenGeneralSettings>
</option>
</component>
<component name="MavenProjectNavigator">
<treeState>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="" />
<option name="myItemType" value="org.jetbrains.idea.maven.navigator.MavenProjectsStructure$RootNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="love" />
<option name="myItemType" value="org.jetbrains.idea.maven.navigator.MavenProjectsStructure$ProjectNode" />
</PATH_ELEMENT>
</PATH>
</treeState>
</component>
<component name="ProjectFrameBounds">
<option name="x" value="-8" />
<option name="y" value="-8" />
<option name="width" value="1936" />
<option name="height" value="1096" />
</component>
<component name="ProjectLevelVcsManager" settingsEditedManually="false">
<OptionsSetting value="true" id="Add" />
<OptionsSetting value="true" id="Remove" />
<OptionsSetting value="true" id="Checkout" />
<OptionsSetting value="true" id="Update" />
<OptionsSetting value="true" id="Status" />
<OptionsSetting value="true" id="Edit" />
<ConfirmationsSetting value="1" id="Add" />
<ConfirmationsSetting value="0" id="Remove" />
</component>
<component name="ProjectView">
<navigator currentView="ProjectPane" proportions="" version="1">
<flattenPackages />
<showMembers />
<showModules />
<showLibraryContents />
<hideEmptyPackages />
<abbreviatePackageNames />
<autoscrollToSource />
<autoscrollFromSource />
<sortByType />
<manualOrder />
<foldersAlwaysOnTop value="true" />
</navigator>
<panes>
<pane id="Scratches" />
<pane id="ProjectPane">
<subPane>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="wisdom" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="wisdom" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="Hunter" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="wisdom" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="Hunter" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="src" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="wisdom" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="Hunter" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="src" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="main" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="java" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="qiangqiang" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="wisdom" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="Hunter" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="src" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="main" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="java" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="qiangqiang" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="hunt" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="wisdom" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="Hunter" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="src" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="main" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="java" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="qiangqiang" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="hunt" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="trend" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="wisdom" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="Hunter" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="src" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="main" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="java" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="qiangqiang" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="hunt" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="rnn" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="wisdom" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="Hunter" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="src" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="main" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="java" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="qiangqiang" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="func" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="wisdom" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="Hunter" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="net" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
</subPane>
</pane>
<pane id="PackagesPane" />
<pane id="Scope" />
</panes>
</component>
<component name="RecentsManager">
<key name="CopyClassDialog.RECENTS_KEY">
<recent name="tongtong.qiangqiang.hunt.trend" />
</key>
</component>
<component name="RunManager" selected="Application.KernelSmoothing">
<configuration default="false" name="MavgReverseDiff" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea">
<pattern>
<option name="PATTERN" value="tongtong.qiangqiang.mind.algorithm.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<option name="MAIN_CLASS_NAME" value="tongtong.qiangqiang.mind.algorithm.MavgReverseDiff" />
<option name="VM_PARAMETERS" />
<option name="PROGRAM_PARAMETERS" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="ENABLE_SWING_INSPECTOR" value="false" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<module name="wisdom" />
<envs />
<method />
</configuration>
<configuration default="false" name="DoubleDifference" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea">
<pattern>
<option name="PATTERN" value="tongtong.qiangqiang.mind.algorithm.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<option name="MAIN_CLASS_NAME" value="tongtong.qiangqiang.mind.algorithm.DoubleDifference" />
<option name="VM_PARAMETERS" />
<option name="PROGRAM_PARAMETERS" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="ENABLE_SWING_INSPECTOR" value="false" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<module name="wisdom" />
<envs />
<method />
</configuration>
<configuration default="false" name="RNN" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea">
<pattern>
<option name="PATTERN" value="tongtong.qiangqiang.hunt.rnn.util.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<option name="MAIN_CLASS_NAME" value="tongtong.qiangqiang.hunt.rnn.RNN" />
<option name="VM_PARAMETERS" />
<option name="PROGRAM_PARAMETERS" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="ENABLE_SWING_INSPECTOR" value="false" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<module name="wisdom" />
<envs />
<method />
</configuration>
<configuration default="false" name="MeanVar" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea">
<pattern>
<option name="PATTERN" value="tongtong.qiangqiang.hunt.rnn.util.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<option name="MAIN_CLASS_NAME" value="tongtong.qiangqiang.hunt.rnn.util.MeanVar" />
<option name="VM_PARAMETERS" />
<option name="PROGRAM_PARAMETERS" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="ENABLE_SWING_INSPECTOR" value="false" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<module name="wisdom" />
<envs />
<method />
</configuration>
<configuration default="false" name="KernelSmoothing" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea">
<pattern>
<option name="PATTERN" value="tongtong.qiangqiang.hunt.trend.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<option name="MAIN_CLASS_NAME" value="tongtong.qiangqiang.hunt.trend.KernelSmoothing" />
<option name="VM_PARAMETERS" />
<option name="PROGRAM_PARAMETERS" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="ENABLE_SWING_INSPECTOR" value="false" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<module name="wisdom" />
<envs />
<method />
</configuration>
<configuration default="true" type="AndroidRunConfigurationType" factoryName="Android Application">
<module name="" />
<option name="ACTIVITY_CLASS" value="" />
<option name="MODE" value="default_activity" />
<option name="DEPLOY" value="true" />
<option name="ARTIFACT_NAME" value="" />
<option name="TARGET_SELECTION_MODE" value="EMULATOR" />
<option name="USE_LAST_SELECTED_DEVICE" value="false" />
<option name="PREFERRED_AVD" value="" />
<option name="USE_COMMAND_LINE" value="true" />
<option name="COMMAND_LINE" value="" />
<option name="WIPE_USER_DATA" value="false" />
<option name="DISABLE_BOOT_ANIMATION" value="false" />
<option name="NETWORK_SPEED" value="full" />
<option name="NETWORK_LATENCY" value="none" />
<option name="CLEAR_LOGCAT" value="false" />
<option name="SHOW_LOGCAT_AUTOMATICALLY" value="true" />
<option name="FILTER_LOGCAT_AUTOMATICALLY" value="true" />
<option name="SELECTED_CLOUD_MATRIX_CONFIGURATION_ID" value="0" />
<option name="SELECTED_CLOUD_MATRIX_PROJECT_ID" value="" />
<option name="SELECTED_CLOUD_DEVICE_CONFIGURATION_ID" value="0" />
<option name="SELECTED_CLOUD_DEVICE_PROJECT_ID" value="" />
<option name="IS_VALID_CLOUD_MATRIX_SELECTION" value="false" />
<option name="INVALID_CLOUD_MATRIX_SELECTION_ERROR" value="" />
<option name="IS_VALID_CLOUD_DEVICE_SELECTION" value="false" />
<option name="INVALID_CLOUD_DEVICE_SELECTION_ERROR" value="" />
<option name="CLOUD_DEVICE_SERIAL_NUMBER" value="" />
<method />
</configuration>
<configuration default="true" type="AndroidTestRunConfigurationType" factoryName="Android Tests">
<module name="" />
<option name="TESTING_TYPE" value="0" />
<option name="INSTRUMENTATION_RUNNER_CLASS" value="" />
<option name="METHOD_NAME" value="" />
<option name="CLASS_NAME" value="" />
<option name="PACKAGE_NAME" value="" />
<option name="TARGET_SELECTION_MODE" value="EMULATOR" />
<option name="USE_LAST_SELECTED_DEVICE" value="false" />
<option name="PREFERRED_AVD" value="" />
<option name="USE_COMMAND_LINE" value="true" />
<option name="COMMAND_LINE" value="" />
<option name="WIPE_USER_DATA" value="false" />
<option name="DISABLE_BOOT_ANIMATION" value="false" />
<option name="NETWORK_SPEED" value="full" />
<option name="NETWORK_LATENCY" value="none" />
<option name="CLEAR_LOGCAT" value="false" />
<option name="SHOW_LOGCAT_AUTOMATICALLY" value="true" />
<option name="FILTER_LOGCAT_AUTOMATICALLY" value="true" />
<option name="SELECTED_CLOUD_MATRIX_CONFIGURATION_ID" value="0" />
<option name="SELECTED_CLOUD_MATRIX_PROJECT_ID" value="" />
<option name="SELECTED_CLOUD_DEVICE_CONFIGURATION_ID" value="0" />
<option name="SELECTED_CLOUD_DEVICE_PROJECT_ID" value="" />
<option name="IS_VALID_CLOUD_MATRIX_SELECTION" value="false" />
<option name="INVALID_CLOUD_MATRIX_SELECTION_ERROR" value="" />
<option name="IS_VALID_CLOUD_DEVICE_SELECTION" value="false" />
<option name="INVALID_CLOUD_DEVICE_SELECTION_ERROR" value="" />
<option name="CLOUD_DEVICE_SERIAL_NUMBER" value="" />
<method />
</configuration>
<configuration default="true" type="Applet" factoryName="Applet">
<option name="HTML_USED" value="false" />
<option name="WIDTH" value="400" />
<option name="HEIGHT" value="300" />
<option name="POLICY_FILE" value="$APPLICATION_HOME_DIR$/bin/appletviewer.policy" />
<module />
<method />
</configuration>
<configuration default="true" type="Application" factoryName="Application">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<option name="MAIN_CLASS_NAME" />
<option name="VM_PARAMETERS" />
<option name="PROGRAM_PARAMETERS" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="ENABLE_SWING_INSPECTOR" value="false" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<module name="" />
<envs />
<method />
</configuration>
<configuration default="true" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list />
</option>
<option name="vmOptions" />
</ExternalSystemSettings>
<method />
</configuration>
<configuration default="true" type="JUnit" factoryName="JUnit">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<module name="" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="PACKAGE_NAME" />
<option name="MAIN_CLASS_NAME" />
<option name="METHOD_NAME" />
<option name="TEST_OBJECT" value="class" />
<option name="VM_PARAMETERS" value="-ea" />
<option name="PARAMETERS" />
<option name="WORKING_DIRECTORY" value="$MODULE_DIR$" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<envs />
<patterns />
<method />
</configuration>
<configuration default="true" type="JUnitTestDiscovery" factoryName="JUnit Test Discovery" changeList="All">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<module name="" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="PACKAGE_NAME" />
<option name="MAIN_CLASS_NAME" />
<option name="METHOD_NAME" />
<option name="TEST_OBJECT" value="class" />
<option name="VM_PARAMETERS" />
<option name="PARAMETERS" />
<option name="WORKING_DIRECTORY" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<envs />
<patterns />
<method />
</configuration>
<configuration default="true" type="JarApplication" factoryName="JAR Application">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<envs />
<method />
</configuration>
<configuration default="true" type="Java Scratch" factoryName="Java Scratch">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<option name="SCRATCH_FILE_ID" value="0" />
<option name="MAIN_CLASS_NAME" />
<option name="VM_PARAMETERS" />
<option name="PROGRAM_PARAMETERS" />
<option name="WORKING_DIRECTORY" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="ENABLE_SWING_INSPECTOR" value="false" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<module name="" />
<envs />
<method />
</configuration>
<configuration default="true" type="JetRunConfigurationType" factoryName="Kotlin">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<option name="MAIN_CLASS_NAME" />
<option name="VM_PARAMETERS" />
<option name="PROGRAM_PARAMETERS" />
<option name="WORKING_DIRECTORY" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="PASS_PARENT_ENVS" value="true" />
<module name="wisdom" />
<envs />
<method />
</configuration>
<configuration default="true" type="KotlinStandaloneScriptRunConfigurationType" factoryName="Kotlin script">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<option name="filePath" />
<option name="vmParameters" />
<option name="alternativeJrePath" />
<option name="programParameters" />
<option name="passParentEnvs" value="true" />
<option name="workingDirectory" />
<option name="isAlternativeJrePathEnabled" value="false" />
<envs />
<method />
</configuration>
<configuration default="true" type="PythonConfigurationType" factoryName="Python">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="wisdom" />
<option name="SCRIPT_NAME" value="" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<method />
</configuration>
<configuration default="true" type="Remote" factoryName="Remote">
<option name="USE_SOCKET_TRANSPORT" value="true" />
<option name="SERVER_MODE" value="false" />
<option name="SHMEM_ADDRESS" value="javadebug" />
<option name="HOST" value="localhost" />
<option name="PORT" value="5005" />
<method />
</configuration>
<configuration default="true" type="ScalaTestRunConfiguration" factoryName="ScalaTest">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<module name="" />
<setting name="path" value="" />
<setting name="package" value="" />
<setting name="vmparams" value="" />
<setting name="params" value="" />
<setting name="workingDirectory" value="" />
<setting name="searchForTest" value="Across module dependencies" />
<setting name="testName" value="" />
<setting name="testKind" value="Class" />
<setting name="showProgressMessages" value="true" />
<envs />
<method />
</configuration>
<configuration default="true" type="Specs2RunConfiguration" factoryName="Specs2">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<module name="" />
<setting name="path" value="" />
<setting name="package" value="" />
<setting name="vmparams" value="" />
<setting name="params" value="" />
<setting name="workingDirectory" value="" />
<setting name="searchForTest" value="Across module dependencies" />
<setting name="testName" value="" />
<setting name="testKind" value="Class" />
<setting name="showProgressMessages" value="true" />
<envs />
<method />
</configuration>
<configuration default="true" type="TestNG" factoryName="TestNG">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<module name="" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="SUITE_NAME" />
<option name="PACKAGE_NAME" />
<option name="MAIN_CLASS_NAME" />
<option name="METHOD_NAME" />
<option name="GROUP_NAME" />
<option name="TEST_OBJECT" value="CLASS" />
<option name="VM_PARAMETERS" value="-ea" />
<option name="PARAMETERS" />
<option name="WORKING_DIRECTORY" value="$MODULE_DIR$" />
<option name="OUTPUT_DIRECTORY" />
<option name="ANNOTATION_TYPE" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<option name="USE_DEFAULT_REPORTERS" value="false" />
<option name="PROPERTIES_FILE" />
<envs />
<properties />
<listeners />
<method />
</configuration>
<configuration default="true" type="TestNGTestDiscovery" factoryName="TestNG Test Discovery" changeList="All">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<module name="" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="SUITE_NAME" />
<option name="PACKAGE_NAME" />
<option name="MAIN_CLASS_NAME" />
<option name="METHOD_NAME" />
<option name="GROUP_NAME" />
<option name="TEST_OBJECT" value="CLASS" />
<option name="VM_PARAMETERS" />
<option name="PARAMETERS" />
<option name="WORKING_DIRECTORY" />
<option name="OUTPUT_DIRECTORY" />
<option name="ANNOTATION_TYPE" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<option name="USE_DEFAULT_REPORTERS" value="false" />
<option name="PROPERTIES_FILE" />
<envs />
<properties />
<listeners />
<method />
</configuration>
<configuration default="true" type="tests" factoryName="Attests">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs />
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="wisdom" />
<option name="SCRIPT_NAME" value="" />
<option name="CLASS_NAME" value="" />
<option name="METHOD_NAME" value="" />
<option name="FOLDER_NAME" value="" />
<option name="TEST_TYPE" value="TEST_SCRIPT" />
<option name="PATTERN" value="" />
<option name="USE_PATTERN" value="false" />
<method />
</configuration>
<configuration default="true" type="tests" factoryName="Doctests">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs />
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="wisdom" />
<option name="SCRIPT_NAME" value="" />
<option name="CLASS_NAME" value="" />
<option name="METHOD_NAME" value="" />
<option name="FOLDER_NAME" value="" />
<option name="TEST_TYPE" value="TEST_SCRIPT" />
<option name="PATTERN" value="" />
<option name="USE_PATTERN" value="false" />
<method />
</configuration>
<configuration default="true" type="tests" factoryName="Nosetests">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs />
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="wisdom" />
<option name="SCRIPT_NAME" value="" />
<option name="CLASS_NAME" value="" />
<option name="METHOD_NAME" value="" />
<option name="FOLDER_NAME" value="" />
<option name="TEST_TYPE" value="TEST_SCRIPT" />
<option name="PATTERN" value="" />
<option name="USE_PATTERN" value="false" />
<option name="PARAMS" value="" />
<option name="USE_PARAM" value="false" />
<method />
</configuration>
<configuration default="true" type="tests" factoryName="Unittests">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs />
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="wisdom" />
<option name="SCRIPT_NAME" value="" />
<option name="CLASS_NAME" value="" />
<option name="METHOD_NAME" value="" />
<option name="FOLDER_NAME" value="" />
<option name="TEST_TYPE" value="TEST_SCRIPT" />
<option name="PATTERN" value="" />
<option name="USE_PATTERN" value="false" />
<option name="PUREUNITTEST" value="true" />
<option name="PARAMS" value="" />
<option name="USE_PARAM" value="false" />
<method />
</configuration>
<configuration default="true" type="tests" factoryName="py.test">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs />
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<module name="wisdom" />
<option name="SCRIPT_NAME" value="" />
<option name="CLASS_NAME" value="" />
<option name="METHOD_NAME" value="" />
<option name="FOLDER_NAME" value="" />
<option name="TEST_TYPE" value="TEST_SCRIPT" />
<option name="PATTERN" value="" />
<option name="USE_PATTERN" value="false" />
<option name="testToRun" value="" />
<option name="keywords" value="" />
<option name="params" value="" />
<option name="USE_PARAM" value="false" />
<option name="USE_KEYWORD" value="false" />
<method />
</configuration>
<configuration default="true" type="uTestRunConfiguration" factoryName="utest">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<module name="" />
<setting name="path" value="" />
<setting name="package" value="" />
<setting name="vmparams" value="" />
<setting name="params" value="" />
<setting name="workingDirectory" value="" />
<setting name="searchForTest" value="Across module dependencies" />
<setting name="testName" value="" />
<setting name="testKind" value="Class" />
<setting name="showProgressMessages" value="true" />
<envs />
<method />
</configuration>
<list size="5">
<item index="0" class="java.lang.String" itemvalue="Application.MavgReverseDiff" />
<item index="1" class="java.lang.String" itemvalue="Application.DoubleDifference" />
<item index="2" class="java.lang.String" itemvalue="Application.RNN" />
<item index="3" class="java.lang.String" itemvalue="Application.MeanVar" />
<item index="4" class="java.lang.String" itemvalue="Application.KernelSmoothing" />
</list>
<recent_temporary>
<list size="5">
<item index="0" class="java.lang.String" itemvalue="Application.KernelSmoothing" />
<item index="1" class="java.lang.String" itemvalue="Application.RNN" />
<item index="2" class="java.lang.String" itemvalue="Application.MeanVar" />
<item index="3" class="java.lang.String" itemvalue="Application.MavgReverseDiff" />
<item index="4" class="java.lang.String" itemvalue="Application.DoubleDifference" />
</list>
</recent_temporary>
</component>
<component name="SbtLocalSettings">
<option name="externalProjectsViewState">
<projects_view />
</option>
</component>
<component name="ShelveChangesManager" show_recycled="false" />
<component name="SvnConfiguration">
<configuration />
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="b3002d8f-4db3-46d6-8600-99affd2dacdf" name="Default" comment="" />
<created>1458971116507</created>
<option name="number" value="Default" />
<updated>1458971116507</updated>
</task>
<servers />
</component>
<component name="ToolWindowManager">
<frame x="-8" y="-8" width="1936" height="1096" extended-state="6" />
<editor active="true" />
<layout>
<window_info id="Palette" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
<window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
<window_info id="Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.3692946" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
<window_info id="Palette	" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
<window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.1762918" sideWeight="0.50208336" order="7" side_tool="true" content_ui="tabs" />
<window_info id="Maven Projects" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.15351813" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
<window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
<window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.22925311" sideWeight="0.49791667" order="2" side_tool="false" content_ui="tabs" />
<window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
<window_info id="Designer" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
<window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.17750533" sideWeight="0.49585062" order="0" side_tool="false" content_ui="combo" />
<window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.3347548" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="UI Designer" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
<window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.1924307" sideWeight="0.5041494" order="2" side_tool="true" content_ui="tabs" />
<window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.32987553" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
<window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
<window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
<window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
<window_info id="Application Servers" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="8" side_tool="false" content_ui="tabs" />
<window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
<window_info id="Coverage" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.32959402" sideWeight="0.5" order="4" side_tool="true" content_ui="tabs" />
<window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
<window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.32780084" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
</layout>
<layout-to-restore>
<window_info id="Palette" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
<window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
<window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
<window_info id="Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.17531121" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
<window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
<window_info id="Palette	" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
<window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
<window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.1762918" sideWeight="0.50208336" order="8" side_tool="true" content_ui="tabs" />
<window_info id="Application Servers" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="11" side_tool="false" content_ui="tabs" />
<window_info id="Maven Projects" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.32995737" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
<window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
<window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="9" side_tool="false" content_ui="tabs" />
<window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.34232366" sideWeight="0.49791667" order="2" side_tool="false" content_ui="tabs" />
<window_info id="Coverage" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.32959402" sideWeight="0.5" order="6" side_tool="true" content_ui="tabs" />
<window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="10" side_tool="false" content_ui="tabs" />
<window_info id="Designer" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
<window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.24253732" sideWeight="0.49585062" order="0" side_tool="false" content_ui="combo" />
<window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
<window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.32826748" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.3347548" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="UI Designer" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
<window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.1924307" sideWeight="0.5041494" order="4" side_tool="true" content_ui="tabs" />
<window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.3039419" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
</layout-to-restore>
</component>
<component name="Vcs.Log.UiProperties">
<option name="RECENTLY_FILTERED_USER_GROUPS">
<collection />
</option>
<option name="RECENTLY_FILTERED_BRANCH_GROUPS">
<collection />
</option>
</component>
<component name="VcsContentAnnotationSettings">
<option name="myLimit" value="2678400000" />
</component>
<component name="XDebuggerManager">
<breakpoint-manager>
<breakpoints>
<line-breakpoint enabled="true" type="java-line">
<url>file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/Filter.java</url>
<line>145</line>
<properties />
<option name="timeStamp" value="2" />
</line-breakpoint>
<line-breakpoint enabled="true" type="java-line">
<url>file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/Filter.java</url>
<line>160</line>
<properties />
<option name="timeStamp" value="4" />
</line-breakpoint>
<line-breakpoint enabled="true" type="java-line">
<url>file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/Filter.java</url>
<line>60</line>
<properties />
<option name="timeStamp" value="11" />
</line-breakpoint>
<line-breakpoint enabled="true" type="java-line">
<url>file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/RNN.java</url>
<line>35</line>
<properties />
<option name="timeStamp" value="109" />
</line-breakpoint>
<line-breakpoint enabled="true" type="java-line">
<url>file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/RNN.java</url>
<line>45</line>
<properties />
<option name="timeStamp" value="124" />
</line-breakpoint>
<line-breakpoint enabled="true" type="java-line">
<url>file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/util/MeanVar.java</url>
<line>68</line>
<properties />
<option name="timeStamp" value="133" />
</line-breakpoint>
<line-breakpoint enabled="true" type="java-line">
<url>file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/RNN.java</url>
<line>103</line>
<properties />
<option name="timeStamp" value="138" />
</line-breakpoint>
<line-breakpoint enabled="true" type="java-line">
<url>file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/RNN.java</url>
<line>102</line>
<properties />
<option name="timeStamp" value="140" />
</line-breakpoint>
<line-breakpoint enabled="true" type="java-line">
<url>file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/util/ModelUtil.java</url>
<line>139</line>
<properties />
<option name="timeStamp" value="141" />
</line-breakpoint>
<line-breakpoint enabled="true" type="java-line">
<url>file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/trend/KernelSmoothing.java</url>
<line>48</line>
<properties />
<option name="timeStamp" value="143" />
</line-breakpoint>
<line-breakpoint enabled="true" type="java-line">
<url>file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/trend/KernelSmoothing.java</url>
<line>51</line>
<properties />
<option name="timeStamp" value="144" />
</line-breakpoint>
</breakpoints>
<breakpoints-dialog>
<breakpoints-dialog />
</breakpoints-dialog>
<option name="time" value="145" />
</breakpoint-manager>
<watches-manager>
<configuration name="Application">
<watch expression="HEAD" language="JAVA" custom="" />
<watch expression="i" language="JAVA" custom="" />
<watch expression="j" language="JAVA" custom="" />
<watch expression="ind" language="JAVA" custom="" />
<watch expression="algorithms" language="JAVA" custom="" />
<watch expression="index" language="JAVA" custom="" />
</configuration>
</watches-manager>
</component>
<component name="antWorkspaceConfiguration">
<option name="IS_AUTOSCROLL_TO_SOURCE" value="false" />
<option name="FILTER_TARGETS" value="false" />
</component>
<component name="editorHistoryManager">
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/RNN.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="44" column="35" selection-start-line="44" selection-start-column="35" selection-end-line="44" selection-end-column="35" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/util/ModelUtil.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="143" column="43" selection-start-line="143" selection-start-column="43" selection-end-line="143" selection-end-column="43" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/BarIterator.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="1" column="0" selection-start-line="1" selection-start-column="0" selection-end-line="1" selection-end-column="0" />
<folding>
<element signature="e#2759#2760#0" expanded="false" />
<element signature="e#2793#2794#0" expanded="false" />
<element signature="e#2840#2841#0" expanded="false" />
<element signature="e#2874#2875#0" expanded="false" />
<element signature="e#2922#2923#0" expanded="false" />
<element signature="e#2956#2957#0" expanded="false" />
<element signature="e#3237#3238#0" expanded="false" />
<element signature="e#3273#3274#0" expanded="false" />
<element signature="e#3314#3315#0" expanded="false" />
<element signature="e#3381#3382#0" expanded="false" />
<element signature="e#3427#3428#0" expanded="false" />
<element signature="e#3465#3466#0" expanded="false" />
<element signature="e#3682#3683#0" expanded="false" />
<element signature="e#3756#3757#0" expanded="false" />
<element signature="e#3802#3803#0" expanded="false" />
<element signature="e#3855#3856#0" expanded="false" />
<element signature="e#3898#3899#0" expanded="false" />
<element signature="e#3940#3941#0" expanded="false" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/trend/KernelSmoothing.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/Filter.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="41" column="9" selection-start-line="41" selection-start-column="9" selection-end-line="41" selection-end-column="9" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/LearnDirection.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="312" column="0" selection-start-line="312" selection-start-column="0" selection-end-line="312" selection-end-column="0" />
<folding>
<element signature="imports" expanded="true" />
<element signature="e#1553#1554#0" expanded="true" />
<element signature="e#1595#1596#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/util/MeanVar.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="44" column="42" selection-start-line="44" selection-start-column="42" selection-end-line="44" selection-end-column="42" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/func/GeneralUtilizer.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="172" column="55" selection-start-line="172" selection-start-column="55" selection-end-line="172" selection-end-column="55" />
<folding>
<element signature="e#1657#1658#0" expanded="false" />
<element signature="e#1682#1683#0" expanded="false" />
<element signature="e#2148#2149#0" expanded="false" />
<element signature="e#2200#2201#0" expanded="false" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/vis/TimeSeriesChart.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="71" column="0" selection-start-line="71" selection-start-column="0" selection-end-line="71" selection-end-column="0" />
<folding>
<element signature="imports" expanded="false" />
<element signature="e#1163#1164#0" expanded="false" />
<element signature="e#1191#1192#0" expanded="false" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/func/GeneralUtilizer.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="169" column="37" selection-start-line="169" selection-start-column="37" selection-end-line="169" selection-end-column="37" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/func/GeneralUtilizer.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="169" column="37" selection-start-line="169" selection-start-column="37" selection-end-line="169" selection-end-column="37" />
</state>
</provider>
</entry>
<entry file="jar://$MAVEN_REPOSITORY$/io/netty/netty-all/4.0.29.Final/netty-all-4.0.29.Final.jar!/io/netty/channel/SimpleChannelInboundHandler.class">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.20743035">
<caret line="38" column="16" selection-start-line="38" selection-start-column="16" selection-end-line="38" selection-end-column="16" />
</state>
</provider>
</entry>
<entry file="jar://$PROJECT_DIR$/lib/common-0.0.1-SNAPSHOT.jar!/cn/quanttech/quantera/common/datacenter/DataCenter.class">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.34664765">
<caret line="74" column="25" selection-start-line="74" selection-start-column="25" selection-end-line="74" selection-end-column="25" />
</state>
</provider>
</entry>
<entry file="jar://$PROJECT_DIR$/lib/common-0.0.1-SNAPSHOT.jar!/cn/quanttech/quantera/common/datacenter/HistoricalData.class">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.31383738">
<caret line="23" column="54" selection-start-line="23" selection-start-column="54" selection-end-line="23" selection-end-column="54" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/LICENSE">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="28" column="0" selection-start-line="28" selection-start-column="0" selection-end-line="28" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/.gitignore">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="12" column="0" selection-start-line="12" selection-start-column="0" selection-end-line="12" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/README.md">
<provider editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="jar://$PROJECT_DIR$/lib/common-0.0.1-SNAPSHOT.jar!/cn/quanttech/quantera/common/datacenter/source/QuandisSource.class">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="56" column="0" selection-start-line="56" selection-start-column="0" selection-end-line="56" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="jar://$PROJECT_DIR$/lib/common-0.0.1-SNAPSHOT.jar!/cn/quanttech/quantera/common/type/query/QuotationQuery.class">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="25" column="0" selection-start-line="25" selection-start-column="0" selection-end-line="25" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/pom.xml">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="82" column="20" selection-start-line="82" selection-start-column="20" selection-end-line="82" selection-end-column="20" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/net/conf.json">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="49" column="15" selection-start-line="49" selection-start-column="15" selection-end-line="49" selection-end-column="15" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/util/MathUtil.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="27" column="50" selection-start-line="27" selection-start-column="50" selection-end-line="27" selection-end-column="50" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/Filter.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="41" column="9" selection-start-line="41" selection-start-column="9" selection-end-line="41" selection-end-column="9" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/RNN.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="44" column="35" selection-start-line="44" selection-start-column="35" selection-end-line="44" selection-end-column="35" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/vis/TimeSeriesChart.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="71" column="0" selection-start-line="71" selection-start-column="0" selection-end-line="71" selection-end-column="0" />
<folding>
<element signature="imports" expanded="false" />
<element signature="e#1163#1164#0" expanded="false" />
<element signature="e#1191#1192#0" expanded="false" />
</folding>
</state>
</provider>
</entry>
<entry file="jar://$PROJECT_DIR$/lib/common-0.0.1-SNAPSHOT.jar!/cn/quanttech/quantera/common/type/data/SecuType.class">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.5925297">
<caret line="50" column="26" selection-start-line="50" selection-start-column="26" selection-end-line="50" selection-end-column="26" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/util/ModelUtil.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="143" column="43" selection-start-line="143" selection-start-column="43" selection-end-line="143" selection-end-column="43" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/BarIterator.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="1" column="0" selection-start-line="1" selection-start-column="0" selection-end-line="1" selection-end-column="0" />
<folding>
<element signature="e#2759#2760#0" expanded="false" />
<element signature="e#2793#2794#0" expanded="false" />
<element signature="e#2840#2841#0" expanded="false" />
<element signature="e#2874#2875#0" expanded="false" />
<element signature="e#2922#2923#0" expanded="false" />
<element signature="e#2956#2957#0" expanded="false" />
<element signature="e#3237#3238#0" expanded="false" />
<element signature="e#3273#3274#0" expanded="false" />
<element signature="e#3314#3315#0" expanded="false" />
<element signature="e#3381#3382#0" expanded="false" />
<element signature="e#3427#3428#0" expanded="false" />
<element signature="e#3465#3466#0" expanded="false" />
<element signature="e#3682#3683#0" expanded="false" />
<element signature="e#3756#3757#0" expanded="false" />
<element signature="e#3802#3803#0" expanded="false" />
<element signature="e#3855#3856#0" expanded="false" />
<element signature="e#3898#3899#0" expanded="false" />
<element signature="e#3940#3941#0" expanded="false" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/rnn/util/MeanVar.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="44" column="42" selection-start-line="44" selection-start-column="42" selection-end-line="44" selection-end-column="42" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/func/GeneralUtilizer.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="172" column="55" selection-start-line="172" selection-start-column="55" selection-end-line="172" selection-end-column="55" />
<folding>
<element signature="e#1657#1658#0" expanded="false" />
<element signature="e#1682#1683#0" expanded="false" />
<element signature="e#2148#2149#0" expanded="false" />
<element signature="e#2200#2201#0" expanded="false" />
</folding>
</state>
</provider>
</entry>
<entry file="jar://$PROJECT_DIR$/lib/common-0.0.1-SNAPSHOT.jar!/cn/quanttech/quantera/common/factor/single/indicators/MTM.class">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.19845645">
<caret line="12" column="11" selection-start-line="12" selection-start-column="11" selection-end-line="12" selection-end-column="11" />
<folding>
<element signature="e#337#338#0" expanded="true" />
<element signature="e#361#362#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="jar://$PROJECT_DIR$/lib/common-0.0.1-SNAPSHOT.jar!/cn/quanttech/quantera/common/factor/single/SingleIndicator.class">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.30871004">
<caret line="22" column="15" selection-start-line="22" selection-start-column="15" selection-end-line="22" selection-end-column="15" />
<folding />
</state>
</provider>
</entry>
<entry file="jar://$PROJECT_DIR$/lib/common-0.0.1-SNAPSHOT.jar!/cn/quanttech/quantera/common/factor/single/indicators/RAW.class">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.1323043">
<caret line="9" column="13" selection-start-line="9" selection-start-column="13" selection-end-line="9" selection-end-column="13" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/trend/KernelSmoothing.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="48" column="44" selection-start-line="48" selection-start-column="44" selection-end-line="48" selection-end-column="44" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/LearnDirection.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="54" column="40" selection-start-line="54" selection-start-column="40" selection-end-line="54" selection-end-column="40" />
<folding>
<element signature="imports" expanded="true" />
<element signature="e#1553#1554#0" expanded="true" />
<element signature="e#1595#1596#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/trend/BarIterator.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="14" column="47" selection-start-line="14" selection-start-column="47" selection-end-line="14" selection-end-column="47" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/tongtong/qiangqiang/hunt/trend/RNN.java">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.47619048">
<caret line="38" column="45" selection-start-line="38" selection-start-column="45" selection-end-line="38" selection-end-column="45" />
<folding />
</state>
</provider>
</entry>
</component>
</project> | {'content_hash': '9b9ab5a3d6e0a6f6870276bb119c3293', 'timestamp': '', 'source': 'github', 'line_count': 1582, 'max_line_length': 277, 'avg_line_length': 57.74841972187105, 'alnum_prop': 0.631274765209396, 'repo_name': 'njucslqq/Wisdom', 'id': 'f39a50229d050eddea9484adcd4a2915c5318954', 'size': '91358', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '.idea/workspace.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '153049'}]} |
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Copyright (C) 2021 Intel Corporation
#ifndef OPENCV_GAPI_CPU_STEREO_API_HPP
#define OPENCV_GAPI_CPU_STEREO_API_HPP
#include <opencv2/gapi/gkernel.hpp> // GKernelPackage
namespace cv {
namespace gapi {
namespace calib3d {
namespace cpu {
GAPI_EXPORTS GKernelPackage kernels();
/** @brief Structure for the Stereo operation initialization parameters.*/
struct GAPI_EXPORTS StereoInitParam {
StereoInitParam(int nD, int bS, double bL, double f):
numDisparities(nD), blockSize(bS), baseline(bL), focus(f) {}
StereoInitParam() = default;
int numDisparities = 0;
int blockSize = 21;
double baseline = 63.5;
double focus = 3.6;
};
} // namespace cpu
} // namespace calib3d
} // namespace gapi
namespace detail {
template<> struct CompileArgTag<cv::gapi::calib3d::cpu::StereoInitParam> {
static const char* tag() {
return "org.opencv.stereoInit";
}
};
} // namespace detail
} // namespace cv
#endif // OPENCV_GAPI_CPU_STEREO_API_HPP
| {'content_hash': '755524f4670f025cd35f23bb152cd997', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 90, 'avg_line_length': 24.791666666666668, 'alnum_prop': 0.7025210084033613, 'repo_name': 'opencv/opencv', 'id': 'e2a2242bd0b8abb66a638745b809869c1bf99934', 'size': '1190', 'binary': False, 'copies': '3', 'ref': 'refs/heads/4.x', 'path': 'modules/gapi/include/opencv2/gapi/cpu/stereo.hpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AIDL', 'bytes': '1986'}, {'name': 'Batchfile', 'bytes': '1498'}, {'name': 'C', 'bytes': '1543870'}, {'name': 'C++', 'bytes': '35975082'}, {'name': 'CMake', 'bytes': '1010867'}, {'name': 'Cuda', 'bytes': '333437'}, {'name': 'Dockerfile', 'bytes': '309'}, {'name': 'HTML', 'bytes': '40027'}, {'name': 'Java', 'bytes': '774232'}, {'name': 'JavaScript', 'bytes': '233673'}, {'name': 'Kotlin', 'bytes': '5204'}, {'name': 'Objective-C', 'bytes': '100731'}, {'name': 'Objective-C++', 'bytes': '392600'}, {'name': 'Perl', 'bytes': '15865'}, {'name': 'PowerShell', 'bytes': '14591'}, {'name': 'Prolog', 'bytes': '843'}, {'name': 'Python', 'bytes': '1038154'}, {'name': 'Shell', 'bytes': '22738'}, {'name': 'Swift', 'bytes': '301765'}, {'name': 'TeX', 'bytes': '3530'}]} |
namespace sol {
namespace detail {
template <>
struct is_speshul<unsafe_function_result> : std::true_type {};
template <>
struct is_speshul<protected_function_result> : std::true_type {};
template <std::size_t I, typename... Args, typename T>
stack_proxy get(types<Args...>, meta::index_value<0>, meta::index_value<I>, const T& fr) {
return stack_proxy(fr.lua_state(), static_cast<int>(fr.stack_index() + I));
}
template <std::size_t I, std::size_t N, typename Arg, typename... Args, typename T, meta::enable<meta::boolean<(N > 0)>> = meta::enabler>
stack_proxy get(types<Arg, Args...>, meta::index_value<N>, meta::index_value<I>, const T& fr) {
return get(types<Args...>(), meta::index_value<N - 1>(), meta::index_value<I + lua_size<Arg>::value>(), fr);
}
} // namespace detail
template <>
struct tie_size<unsafe_function_result> : std::integral_constant<std::size_t, SIZE_MAX> {};
template <>
struct tie_size<protected_function_result> : std::integral_constant<std::size_t, SIZE_MAX> {};
template <std::size_t I>
stack_proxy get(const unsafe_function_result& fr) {
return stack_proxy(fr.lua_state(), static_cast<int>(fr.stack_index() + I));
}
template <std::size_t I, typename... Args>
stack_proxy get(types<Args...> t, const unsafe_function_result& fr) {
return detail::get(t, meta::index_value<I>(), meta::index_value<0>(), fr);
}
template <std::size_t I>
stack_proxy get(const protected_function_result& fr) {
return stack_proxy(fr.lua_state(), static_cast<int>(fr.stack_index() + I));
}
template <std::size_t I, typename... Args>
stack_proxy get(types<Args...> t, const protected_function_result& fr) {
return detail::get(t, meta::index_value<I>(), meta::index_value<0>(), fr);
}
} // namespace sol
#endif // SOL_FUNCTION_RESULT_HPP
| {'content_hash': 'b5719696e52f487728b0097de51d8b6b', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 139, 'avg_line_length': 38.319148936170215, 'alnum_prop': 0.6618545252637423, 'repo_name': 'Siv3D/OpenSiv3D', 'id': '2de353be5fa530eb660ffd62995356cf9e8efe54', 'size': '3136', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'Siv3D/include/ThirdParty/sol/function_result.hpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'AngelScript', 'bytes': '29105'}, {'name': 'Assembly', 'bytes': '147'}, {'name': 'C', 'bytes': '1514971'}, {'name': 'C++', 'bytes': '13315018'}, {'name': 'CMake', 'bytes': '178934'}, {'name': 'GLSL', 'bytes': '370938'}, {'name': 'HLSL', 'bytes': '123042'}, {'name': 'HTML', 'bytes': '32876'}, {'name': 'Inno Setup', 'bytes': '1635'}, {'name': 'JavaScript', 'bytes': '52781'}, {'name': 'Metal', 'bytes': '2383'}, {'name': 'Objective-C', 'bytes': '4914'}, {'name': 'Objective-C++', 'bytes': '139706'}, {'name': 'Shell', 'bytes': '8168'}, {'name': 'Smarty', 'bytes': '20525'}, {'name': 'TypeScript', 'bytes': '19085'}]} |
<p align="center">
<h3 align="center">Bear Quest</h3>
<p align="center"> by <a href="http://www.tek256.com">tek256</a></p>
<p align="center"><a href="http://tek.itch.io/bear-quest">download</a></p>
</p>
<h4>about</h4>
<p>
Bear Quest was made over a weekend in July of 2016. The game was made as part of a community driven game jam. All source code is considered experimental and will likely not be updated.
</p>
| {'content_hash': 'fe2e046d230e2072880cae13dab03012', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 184, 'avg_line_length': 41.9, 'alnum_prop': 0.684964200477327, 'repo_name': 'Tek256/Bear-Quest', 'id': 'c769895a6b8e5ee16fb2db1a0caa354996226a28', 'size': '419', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'GLSL', 'bytes': '406'}, {'name': 'HTML', 'bytes': '485'}, {'name': 'Java', 'bytes': '1604626'}]} |
package com.amazonaws.opensdk;
import com.amazonaws.annotation.Immutable;
import com.amazonaws.annotation.SdkProtectedApi;
import com.amazonaws.http.SdkHttpMetadata;
import java.util.Optional;
/**
* Metadata from the HTTP response. Primarily used for detailed logging or debugging.
*/
@Immutable
public class SdkResponseMetadata {
public static final String HEADER_REQUEST_ID = "x-amzn-RequestId";
private final SdkHttpMetadata httpMetadata;
@SdkProtectedApi
public SdkResponseMetadata(SdkHttpMetadata httpMetadata) {
this.httpMetadata = httpMetadata;
}
/**
* @return x-amzn-RequestId generated by the API Gateway frontend. Uniquely identifies a request
* and can be used for troubleshooting server side issues.
*/
public String requestId() {
return httpMetadata.getHttpHeaders().get(HEADER_REQUEST_ID);
}
/**
* Get a specific header from the HTTP response.
*
* @param headerName Header to retrieve.
* @return Optional of header value.
*/
public Optional<String> header(String headerName) {
return Optional.ofNullable(httpMetadata.getHttpHeaders().get(headerName));
}
/**
* @return HTTP status code of response.
*/
public int httpStatusCode() {
return httpMetadata.getHttpStatusCode();
}
}
| {'content_hash': 'e8bc70276a7550d655df4b56683f366c', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 100, 'avg_line_length': 27.346938775510203, 'alnum_prop': 0.7029850746268657, 'repo_name': 'jentfoo/aws-sdk-java', 'id': '8e610c9d9a6e492e41c2fa61e6f5e4b8b9c41205', 'size': '1924', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'aws-java-sdk-opensdk/src/main/java/com/amazonaws/opensdk/SdkResponseMetadata.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '270'}, {'name': 'FreeMarker', 'bytes': '173637'}, {'name': 'Gherkin', 'bytes': '25063'}, {'name': 'Java', 'bytes': '356214839'}, {'name': 'Scilab', 'bytes': '3924'}, {'name': 'Shell', 'bytes': '295'}]} |
@implementation NSString (Common)
- (BOOL)isEmpty {
return self.length == 0;
}
- (BOOL)validateEmail {
return [self validateWithRegExp: @"^[a-zA-Z0-9]{4,}@[a-z0-9A-Z]{2,}\\.[a-zA-Z]{2,}$"];
}
- (BOOL)validateAuthen{
return [self validateWithRegExp: @"^\\d{5,6}$"];
}
- (BOOL)validatePassword{
NSString * length = @"^\\w{6,18}$"; //长度
NSString * number = @"^\\w*\\d+\\w*$";//数字
NSString * lower = @"^\\w*[a-z]+\\w*$";//小写字母
NSString * upper = @"^\\w*[A-Z]+\\w*$";//大写字母
return [self validateWithRegExp: length] && [self validateWithRegExp: number] && [self validateWithRegExp: lower] && [self validateWithRegExp: upper];
}
- (BOOL)validatePhoneNumber {
NSString * reg = @"^1\\d{10}$";
return [self validateWithRegExp: reg];
}
- (BOOL)validateWithRegExp: (NSString *)regExp {
NSPredicate * predicate = [NSPredicate predicateWithFormat: @"SELF MATCHES %@", regExp];
return [predicate evaluateWithObject: self];
}
@end
| {'content_hash': '09b1789cea83002e1b260ab72506ad30', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 154, 'avg_line_length': 29.393939393939394, 'alnum_prop': 0.6164948453608248, 'repo_name': 'aiwalle/LJAppStandard', 'id': '1a999976ddf9c9ff3ebf7213645f6b0431c517e3', 'size': '1159', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'LJAppStandard/LJAppStandard/Categoties/NSString+Common.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '4555'}, {'name': 'Objective-C', 'bytes': '1581854'}]} |
@interface FlyImageIconRenderer ()
@property (nonatomic, strong) NSURL* iconURL;
@end
@implementation FlyImageIconRenderer {
CGSize _drawSize;
FlyImageDownloadHandlerId* _downloadHandlerId;
}
- (void)dealloc
{
[self cancelDownload];
}
- (void)cancelDownload
{
if (_downloadHandlerId != nil) {
[[FlyImageDownloader sharedInstance] cancelDownloadHandler:_downloadHandlerId];
_downloadHandlerId = nil;
}
}
- (void)setPlaceHolderImageName:(NSString*)imageName
iconURL:(NSURL*)iconURL
drawSize:(CGSize)drawSize
{
if (_iconURL != nil && [_iconURL.absoluteString isEqualToString:iconURL.absoluteString]) {
return;
}
[self cancelDownload];
_iconURL = iconURL;
_drawSize = CGSizeMake(round(drawSize.width), round(drawSize.height));
[self renderWithPlaceHolderImageName:imageName];
}
- (void)renderWithPlaceHolderImageName:(NSString*)imageName
{
NSString* key = _iconURL.absoluteString;
// if has already downloaded image
if (key != nil && [[FlyImageIconCache sharedInstance] isImageExistWithKey:key]) {
__weak __typeof__(self) weakSelf = self;
[[FlyImageIconCache sharedInstance] asyncGetImageWithKey:key
completed:^(NSString* key, UIImage* image) {
[weakSelf renderImage:image key:key ];
}];
return;
}
if (imageName != nil) {
UIImage* placeHolderImage = [UIImage imageNamed:imageName];
[self doRenderImage:placeHolderImage];
} else if (key != nil) {
// clear
[self doRenderImage:nil];
}
if (key == nil) {
return;
}
if ([[FlyImageCache sharedInstance] isImageExistWithKey:key]) {
NSString* imagePath = [[FlyImageCache sharedInstance] imagePathWithKey:key];
if (imagePath != nil) {
NSURL* url = [NSURL fileURLWithPath:imagePath];
[self drawIconWithKey:key url:url];
return;
}
}
[self downloadImage];
}
- (void)downloadImage
{
__weak __typeof__(self) weakSelf = self;
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:_iconURL];
request.timeoutInterval = 30; // Default 30 seconds
_downloadHandlerId = [[FlyImageDownloader sharedInstance]
downloadImageForURLRequest:request
success:^(NSURLRequest* request, NSURL* filePath) {
NSString *downloadedKey = request.URL.absoluteString;
[[FlyImageCache sharedInstance] addImageWithKey:downloadedKey
filename:[filePath lastPathComponent]
completed:nil];
// In case downloaded image is not equal with the new url
if ( ![downloadedKey isEqualToString:weakSelf.iconURL.absoluteString] ) {
return;
}
_downloadHandlerId = nil;
[weakSelf drawIconWithKey:downloadedKey url:filePath];
}
failed:^(NSURLRequest* request, NSError* error) {
_downloadHandlerId = nil;
}];
}
- (void)drawIconWithKey:(NSString*)key url:(NSURL*)url
{
__weak __typeof__(self) weakSelf = self;
[[FlyImageIconCache sharedInstance] addImageWithKey:key
size:_drawSize
drawingBlock:^(CGContextRef context, CGRect contextBounds) {
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
[weakSelf.delegate flyImageIconRenderer:weakSelf
drawImage:image
context:context
bounds:contextBounds];
}
completed:^(NSString* key, UIImage* image) {
[weakSelf renderImage:image key:key];
}];
}
- (void)renderImage:(UIImage*)image key:(NSString*)key
{
dispatch_main_sync_safe(^{
if ( ![_iconURL.absoluteString isEqualToString:key] ) {
return;
}
[self doRenderImage:image];
});
}
- (void)doRenderImage:(UIImage*)image
{
[_delegate flyImageIconRenderer:self willRenderImage:image];
}
@end
| {'content_hash': 'b4ef7eba2082c16b558ae8f5df8ea9c4', 'timestamp': '', 'source': 'github', 'line_count': 146, 'max_line_length': 99, 'avg_line_length': 28.527397260273972, 'alnum_prop': 0.6139255702280912, 'repo_name': 'Bujingxian/UUKit', 'id': '7aa00e880e708404be24401a6f0796bcf8121a5d', 'size': '4419', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'UUKitDemo/Pods/FlyImage/FlyImage/UI/FlyImageIconRenderer.m', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '2347'}, {'name': 'Objective-C', 'bytes': '1209508'}, {'name': 'Ruby', 'bytes': '167'}, {'name': 'Shell', 'bytes': '9073'}]} |
<div id="comm_content">
<div class="heading_top"><?php echo __('Search member');?></div>
<h4><span><?php echo __('There are all %1% members',array('%1%'=>$total_member))?></span></h4>
<?php
$options = array(
//'title' => __('Search Members'),
'url' => url_for('@member_search'),
'button' => __('Search'),
'method' => 'get'
);
/*Form search member*/
op_include_form('comm_search', $filters, $options,'formMember');
?>
<?php if ($pager->getNbResults()): ?>
<?php
$list = array();
foreach ($pager->getResults() as $key => $member)
{
$list[$key] = array();
$list[$key][__('%nickname%', array('%nickname%' => $op_term['nickname']->titleize()))] = $member->getName();
$introduction = $member->getProfile('op_preset_self_introduction', true);
if ($introduction)
{
$list[$key][__('Self Introduction')] = $introduction;
}
$list[$key][__('Last Login')] = op_format_last_login_time($member->getLastLoginTime());
}
$options = array(
// 'title' => __('Search Results'),
'pager' => $pager,
'link_to_page' => '@member_search?page=%d',
'link_to_detail' => '@member_profile?id=%d',
'list' => $list,
'use_op_link_to_member' => true,
);
?>
<div class="heading_top"><?php echo __('Member search result' )?></div>
<?php
op_include_parts('searchResultList1', 'searchCommunityResult', $options);
?>
<?php else: ?>
<?php op_include_box('searchMemberResult', __('Your search queries did not match any members.'), array('title' => __('Search Results'))) ?>
<?php endif; ?>
</div>
| {'content_hash': '36ea77a30d879823b3f23f67bdd5eefd', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 143, 'avg_line_length': 36.234042553191486, 'alnum_prop': 0.5278919553728714, 'repo_name': 'smart-e/lifemap', 'id': '1b530c3155ae7d5ee0d5f05e88703b382f119198', 'size': '1703', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'apps/pc_frontend/modules/member/templates/searchSuccess.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '162665'}, {'name': 'JavaScript', 'bytes': '101422'}, {'name': 'PHP', 'bytes': '3955526'}]} |
require "spec_helper"
describe "Freshbooks users" do
let(:client) { Clockpuncher.client "freshbooks", api_token: "xyz", subdomain: "punch" }
describe "fetching all" do
let(:params) { {} }
subject { client.users.all params }
before do
stub_request(:post, "https://xyz:[email protected]/api/2.1/xml-in").
with(body: request_body("freshbooks/users.xml"))
end
it "should generate the correct API request" do
subject
a_request(:post, "https://xyz:[email protected]/api/2.1/xml-in").
with(
body: request_body("freshbooks/users.xml"),
headers: { "User-Agent" => "Clockpuncher/#{Clockpuncher::VERSION}" }
).
should have_been_made.once
end
context "on a page" do
let(:params) { {page: 1, per_page: 2} }
before do
stub_request(:post, "https://xyz:[email protected]/api/2.1/xml-in").
with(body: request_body("freshbooks/users(page=1&per_page=2).xml"))
end
it "should generate the correct API request" do
subject
a_request(:post, "https://xyz:[email protected]/api/2.1/xml-in").
with(
body: request_body("freshbooks/users(page=1&per_page=2).xml"),
headers: { "User-Agent" => "Clockpuncher/#{Clockpuncher::VERSION}" }
).
should have_been_made.once
end
end
end
describe "fetching one" do
subject { client.users.find 1 }
before do
stub_request(:post, "https://xyz:[email protected]/api/2.1/xml-in").
with(body: request_body("freshbooks/user.xml"))
end
it "should generate the correct API request" do
subject
a_request(:post, "https://xyz:[email protected]/api/2.1/xml-in").
with(
body: request_body("freshbooks/user.xml"),
headers: { "User-Agent" => "Clockpuncher/#{Clockpuncher::VERSION}" }
).
should have_been_made.once
end
end
end
| {'content_hash': '7f40d287c5d039b3a298dff45de3e9a5', 'timestamp': '', 'source': 'github', 'line_count': 66, 'max_line_length': 89, 'avg_line_length': 30.03030303030303, 'alnum_prop': 0.5993945509586277, 'repo_name': 'turingstudio/clockpuncher', 'id': '3b1c5f0212559c52b7d6bf9769fd03ae05430477', 'size': '1982', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/functional/freshbooks/users_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '55641'}]} |
@implementation UINavigationBar (Awesome)
static char overlayKey;
- (UIView *)overlay {
return objc_getAssociatedObject(self, &overlayKey);
}
- (void)setOverlay:(UIView *)overlay {
objc_setAssociatedObject(self, &overlayKey, overlay, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)zw_setBackgroundColor:(UIColor *)backgroundColor {
if (!self.overlay) {
[self setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
self.overlay = [[UIView alloc] initWithFrame:CGRectMake(0, -20, [UIScreen mainScreen].bounds.size.width, CGRectGetHeight(self.bounds) + 20)];
self.overlay.userInteractionEnabled = NO;
self.overlay.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
[self insertSubview:self.overlay atIndex:0];
}
self.overlay.backgroundColor = backgroundColor;
}
- (void)zw_setTranslationY:(CGFloat)translationY {
self.transform = CGAffineTransformMakeTranslation(0, translationY);
}
- (void)zw_setElementsAlpha:(CGFloat)alpha {
[[self valueForKey:@"_leftViews"] enumerateObjectsUsingBlock:^(UIView *view, NSUInteger i, BOOL *stop) {
view.alpha = alpha;
}];
[[self valueForKey:@"_rightViews"] enumerateObjectsUsingBlock:^(UIView *view, NSUInteger i, BOOL *stop) {
view.alpha = alpha;
}];
UIView *titleView = [self valueForKey:@"_titleView"];
titleView.alpha = alpha;
// when viewController first load, the titleView maybe nil
[[self subviews] enumerateObjectsUsingBlock:^(UIView *obj, NSUInteger idx, BOOL *stop) {
if ([obj isKindOfClass:NSClassFromString(@"UINavigationItemView")]) {
obj.alpha = alpha;
*stop = YES;
}
}];
}
- (void)zw_reset {
[self setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
[self.overlay removeFromSuperview];
self.overlay = nil;
}
@end
| {'content_hash': '90fd74bc3a2241d90e288b0990228a43', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 149, 'avg_line_length': 35.18518518518518, 'alnum_prop': 0.6989473684210527, 'repo_name': 'sunnyzw/ZWHeaderView', 'id': '8481a376e3970c00c03a5470ca52d6c5087b04c6', 'size': '2110', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'HeaderViewStyleDemo/ZWHeaderView/UINavigationBar+Awesome.m', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '15072'}]} |
<?php
namespace Nette\DI;
use Nette;
use Nette\PhpGenerator\Helpers as PhpHelpers;
use Nette\Utils\Strings;
use Nette\Utils\Validators;
use ReflectionClass;
/**
* Container builder.
*/
class ContainerBuilder
{
use Nette\SmartObject;
const THIS_SERVICE = 'self',
THIS_CONTAINER = 'container';
/** @var array */
public $parameters = [];
/** @var ServiceDefinition[] */
private $definitions = [];
/** @var array of alias => service */
private $aliases = [];
/** @var array for auto-wiring */
private $classList = [];
/** @var bool */
private $classListNeedsRefresh = TRUE;
/** @var string[] of classes excluded from auto-wiring */
private $excludedClasses = [];
/** @var array */
private $dependencies = [];
/** @var string */
private $currentService;
/**
* Adds new service definition.
* @param string
* @return ServiceDefinition
*/
public function addDefinition($name, ServiceDefinition $definition = NULL)
{
$this->classListNeedsRefresh = TRUE;
if (!is_string($name) || !$name) { // builder is not ready for falsy names such as '0'
throw new Nette\InvalidArgumentException(sprintf('Service name must be a non-empty string, %s given.', gettype($name)));
}
$name = isset($this->aliases[$name]) ? $this->aliases[$name] : $name;
if (isset($this->definitions[$name])) {
throw new Nette\InvalidStateException("Service '$name' has already been added.");
}
if (!$definition) {
$definition = new ServiceDefinition;
}
$definition->setNotifier(function () {
$this->classListNeedsRefresh = TRUE;
});
return $this->definitions[$name] = $definition;
}
/**
* Removes the specified service definition.
* @param string
* @return void
*/
public function removeDefinition($name)
{
$this->classListNeedsRefresh = TRUE;
$name = isset($this->aliases[$name]) ? $this->aliases[$name] : $name;
unset($this->definitions[$name]);
}
/**
* Gets the service definition.
* @param string
* @return ServiceDefinition
*/
public function getDefinition($name)
{
$service = isset($this->aliases[$name]) ? $this->aliases[$name] : $name;
if (!isset($this->definitions[$service])) {
throw new MissingServiceException("Service '$name' not found.");
}
return $this->definitions[$service];
}
/**
* Gets all service definitions.
* @return ServiceDefinition[]
*/
public function getDefinitions()
{
return $this->definitions;
}
/**
* Does the service definition or alias exist?
* @param string
* @return bool
*/
public function hasDefinition($name)
{
$name = isset($this->aliases[$name]) ? $this->aliases[$name] : $name;
return isset($this->definitions[$name]);
}
/**
* @param string
* @param string
*/
public function addAlias($alias, $service)
{
if (!is_string($alias) || !$alias) { // builder is not ready for falsy names such as '0'
throw new Nette\InvalidArgumentException(sprintf('Alias name must be a non-empty string, %s given.', gettype($alias)));
} elseif (!is_string($service) || !$service) { // builder is not ready for falsy names such as '0'
throw new Nette\InvalidArgumentException(sprintf('Service name must be a non-empty string, %s given.', gettype($service)));
} elseif (isset($this->aliases[$alias])) {
throw new Nette\InvalidStateException("Alias '$alias' has already been added.");
} elseif (isset($this->definitions[$alias])) {
throw new Nette\InvalidStateException("Service '$alias' has already been added.");
}
$this->aliases[$alias] = $service;
}
/**
* Removes the specified alias.
* @return void
*/
public function removeAlias($alias)
{
unset($this->aliases[$alias]);
}
/**
* Gets all service aliases.
* @return array
*/
public function getAliases()
{
return $this->aliases;
}
/**
* @param string[]
* @return self
*/
public function addExcludedClasses(array $classes)
{
foreach ($classes as $class) {
if (class_exists($class) || interface_exists($class)) {
self::checkCase($class);
$this->excludedClasses += class_parents($class) + class_implements($class) + [$class => $class];
}
}
return $this;
}
/**
* @deprecated
*/
public function setClassName($name)
{
trigger_error(__METHOD__ . ' has been deprecated', E_USER_DEPRECATED);
return $this;
}
/**
* @deprecated
*/
public function getClassName()
{
trigger_error(__METHOD__ . ' has been deprecated', E_USER_DEPRECATED);
}
/********************* class resolving ****************d*g**/
/**
* Resolves service name by type.
* @param string class or interface
* @return string|NULL service name or NULL
* @throws ServiceCreationException
*/
public function getByType($class)
{
$class = ltrim($class, '\\');
if ($this->currentService !== NULL
&& is_a($this->definitions[$this->currentService]->getClass(), $class, TRUE)
) {
return $this->currentService;
}
$classes = $this->getClassList();
if (empty($classes[$class][TRUE])) {
self::checkCase($class);
return;
} elseif (count($classes[$class][TRUE]) === 1) {
return $classes[$class][TRUE][0];
} else {
$list = $classes[$class][TRUE];
$hint = count($list) === 2 && ($tmp = strpos($list[0], '.') xor strpos($list[1], '.'))
? '. If you want to overwrite service ' . $list[$tmp ? 0 : 1] . ', give it proper name.'
: '';
throw new ServiceCreationException("Multiple services of type $class found: " . implode(', ', $list) . $hint);
}
}
/**
* Gets the service names and definitions of the specified type.
* @param string
* @return ServiceDefinition[]
*/
public function findByType($class)
{
$class = ltrim($class, '\\');
self::checkCase($class);
$found = [];
$classes = $this->getClassList();
if (!empty($classes[$class])) {
foreach (array_merge(...array_values($classes[$class])) as $name) {
$found[$name] = $this->definitions[$name];
}
}
return $found;
}
/**
* Gets the service objects of the specified tag.
* @param string
* @return array of [service name => tag attributes]
*/
public function findByTag($tag)
{
$found = [];
foreach ($this->definitions as $name => $def) {
if (($tmp = $def->getTag($tag)) !== NULL) {
$found[$name] = $tmp;
}
}
return $found;
}
/**
* @internal
*/
public function getClassList()
{
if ($this->classList !== FALSE && $this->classListNeedsRefresh) {
$this->prepareClassList();
$this->classListNeedsRefresh = FALSE;
}
return $this->classList ?: [];
}
/**
* Generates $dependencies, $classes and normalizes class names.
* @return array
* @internal
*/
public function prepareClassList()
{
unset($this->definitions[self::THIS_CONTAINER]);
$this->addDefinition(self::THIS_CONTAINER)->setClass(Container::class);
$this->classList = FALSE;
foreach ($this->definitions as $name => $def) {
// prepare generated factories
if ($def->getImplement()) {
$this->resolveImplement($def, $name);
}
if ($def->isDynamic()) {
if (!$def->getClass()) {
throw new ServiceCreationException("Class is missing in definition of service '$name'.");
}
$def->setFactory(NULL);
continue;
}
// complete class-factory pairs
if (!$def->getEntity()) {
if (!$def->getClass()) {
throw new ServiceCreationException("Class and factory are missing in definition of service '$name'.");
}
$def->setFactory($def->getClass(), ($factory = $def->getFactory()) ? $factory->arguments : []);
}
// auto-disable autowiring for aliases
if (($alias = $this->getServiceName($def->getFactory()->getEntity())) &&
(!$def->getImplement() || (!Strings::contains($alias, '\\') && $this->definitions[$alias]->getImplement()))
) {
$def->setAutowired(FALSE);
}
}
// resolve and check classes
foreach ($this->definitions as $name => $def) {
$this->resolveServiceClass($name);
}
// build auto-wiring list
$this->classList = $preferred = [];
foreach ($this->definitions as $name => $def) {
if ($class = $def->getImplement() ?: $def->getClass()) {
$defAutowired = $def->getAutowired();
if (is_array($defAutowired)) {
foreach ($defAutowired as $k => $aclass) {
if ($aclass === self::THIS_SERVICE) {
$defAutowired[$k] = $class;
} elseif (!is_a($class, $aclass, TRUE)) {
throw new ServiceCreationException("Incompatible class $aclass in autowiring definition of service '$name'.");
}
}
}
foreach (class_parents($class) + class_implements($class) + [$class] as $parent) {
$autowired = $defAutowired && empty($this->excludedClasses[$parent]);
if ($autowired && is_array($defAutowired)) {
$autowired = FALSE;
foreach ($defAutowired as $aclass) {
if (is_a($parent, $aclass, TRUE)) {
if (empty($preferred[$parent]) && isset($this->classList[$parent][TRUE])) {
$this->classList[$parent][FALSE] = array_merge(...$this->classList[$parent]);
$this->classList[$parent][TRUE] = [];
}
$preferred[$parent] = $autowired = TRUE;
break;
}
}
} elseif (isset($preferred[$parent])) {
$autowired = FALSE;
}
$this->classList[$parent][$autowired][] = (string) $name;
}
}
}
}
private function resolveImplement(ServiceDefinition $def, $name)
{
$interface = $def->getImplement();
if (!interface_exists($interface)) {
throw new ServiceCreationException("Interface $interface used in service '$name' not found.");
}
self::checkCase($interface);
$rc = new ReflectionClass($interface);
$this->addDependency($rc);
$method = $rc->hasMethod('create')
? $rc->getMethod('create')
: ($rc->hasMethod('get') ? $rc->getMethod('get') : NULL);
if (count($rc->getMethods()) !== 1 || !$method || $method->isStatic()) {
throw new ServiceCreationException("Interface $interface used in service '$name' must have just one non-static method create() or get().");
}
$def->setImplementMode($methodName = $rc->hasMethod('create') ? $def::IMPLEMENT_MODE_CREATE : $def::IMPLEMENT_MODE_GET);
if (!$def->getClass() && !$def->getEntity()) {
$returnType = PhpReflection::getReturnType($method);
if (!$returnType) {
throw new ServiceCreationException("Method $interface::$methodName() used in service '$name' has no @return annotation.");
} elseif (!class_exists($returnType)) {
throw new ServiceCreationException("Check a @return annotation of the $interface::$methodName() method used in service '$name', class '$returnType' cannot be found.");
}
$def->setClass($returnType);
}
if ($methodName === 'get') {
if ($method->getParameters()) {
throw new ServiceCreationException("Method $interface::get() used in service '$name' must have no arguments.");
}
if (!$def->getEntity()) {
$def->setFactory('@\\' . ltrim($def->getClass(), '\\'));
} elseif (!$this->getServiceName($def->getFactory()->getEntity())) {
throw new ServiceCreationException("Invalid factory in service '$name' definition.");
}
}
if (!$def->parameters) {
$ctorParams = [];
if (!$def->getEntity()) {
$def->setFactory($def->getClass(), $def->getFactory() ? $def->getFactory()->arguments : []);
}
if (($class = $this->resolveEntityClass($def->getFactory(), [$name => 1]))
&& ($ctor = (new ReflectionClass($class))->getConstructor())
) {
foreach ($ctor->getParameters() as $param) {
$ctorParams[$param->getName()] = $param;
}
}
foreach ($method->getParameters() as $param) {
$hint = PhpReflection::getParameterType($param);
if (isset($ctorParams[$param->getName()])) {
$arg = $ctorParams[$param->getName()];
if ($hint !== PhpReflection::getParameterType($arg)) {
throw new ServiceCreationException("Type hint for \${$param->getName()} in $interface::$methodName() doesn't match type hint in $class constructor.");
}
$def->getFactory()->arguments[$arg->getPosition()] = self::literal('$' . $arg->getName());
} elseif (!$def->getSetup()) {
$hint = Nette\Utils\ObjectMixin::getSuggestion(array_keys($ctorParams), $param->getName());
throw new ServiceCreationException("Unused parameter \${$param->getName()} when implementing method $interface::$methodName()" . ($hint ? ", did you mean \${$hint}?" : '.'));
}
$paramDef = $hint . ' ' . $param->getName();
if ($param->isDefaultValueAvailable()) {
$def->parameters[$paramDef] = $param->getDefaultValue();
} else {
$def->parameters[] = $paramDef;
}
}
}
}
/** @return string|NULL */
private function resolveServiceClass($name, $recursive = [])
{
if (isset($recursive[$name])) {
throw new ServiceCreationException(sprintf('Circular reference detected for services: %s.', implode(', ', array_keys($recursive))));
}
$recursive[$name] = TRUE;
$def = $this->definitions[$name];
$factoryClass = $def->getFactory() ? $this->resolveEntityClass($def->getFactory()->getEntity(), $recursive) : NULL; // call always to check entities
if ($class = $def->getClass() ?: $factoryClass) {
if (!class_exists($class) && !interface_exists($class)) {
throw new ServiceCreationException("Class or interface '$class' used in service '$name' not found.");
}
self::checkCase($class);
$def->setClass($class);
if (count($recursive) === 1) {
$this->addDependency(new ReflectionClass($factoryClass ?: $class));
}
} elseif ($def->getAutowired()) {
throw new ServiceCreationException("Unknown type of service '$name', declare return type of factory method (for PHP 5 use annotation @return)");
}
return $class;
}
/** @return string|NULL */
private function resolveEntityClass($entity, $recursive = [])
{
$entity = $this->normalizeEntity($entity instanceof Statement ? $entity->getEntity() : $entity);
$serviceName = current(array_slice(array_keys($recursive), -1));
if (is_array($entity)) {
if (($service = $this->getServiceName($entity[0])) || $entity[0] instanceof Statement) {
$entity[0] = $this->resolveEntityClass($entity[0], $recursive);
if (!$entity[0]) {
return;
} elseif (isset($this->definitions[$service]) && $this->definitions[$service]->getImplement()) { // @Implement::create
return $entity[1] === 'create' ? $this->resolveServiceClass($service, $recursive) : NULL;
}
}
try {
$reflection = Nette\Utils\Callback::toReflection($entity[0] === '' ? $entity[1] : $entity);
$refClass = $reflection instanceof \ReflectionMethod ? $reflection->getDeclaringClass() : NULL;
} catch (\ReflectionException $e) {
}
if (isset($e) || ($refClass && (!$reflection->isPublic()
|| ($refClass->isTrait() && !$reflection->isStatic())
))) {
throw new ServiceCreationException(sprintf("Method %s() used in service '%s' is not callable.", Nette\Utils\Callback::toString($entity), $serviceName));
}
$this->addDependency($reflection);
$type = PhpReflection::getReturnType($reflection);
if ($type && !class_exists($type) && !interface_exists($type)) {
throw new ServiceCreationException(sprintf("Class or interface '%s' not found. Is return type of %s() used in service '%s' correct?", $type, Nette\Utils\Callback::toString($entity), $serviceName));
}
return $type;
} elseif ($service = $this->getServiceName($entity)) { // alias or factory
if (Strings::contains($service, '\\')) { // @\Class
return ltrim($service, '\\');
}
return $this->definitions[$service]->getImplement()
?: $this->definitions[$service]->getClass()
?: $this->resolveServiceClass($service, $recursive);
} elseif (is_string($entity)) { // class
if (!class_exists($entity)) {
throw new ServiceCreationException("Class $entity used in service '$serviceName' not found.");
}
return ltrim($entity, '\\');
}
}
/**
* @return void
*/
public function complete()
{
$this->prepareClassList();
foreach ($this->definitions as $name => $def) {
if ($def->isDynamic()) {
continue;
}
$this->currentService = NULL;
$entity = $def->getFactory()->getEntity();
$serviceRef = $this->getServiceName($entity);
$factory = $serviceRef && !$def->getFactory()->arguments && !$def->getSetup() && $def->getImplementMode() !== $def::IMPLEMENT_MODE_CREATE
? new Statement(['@' . self::THIS_CONTAINER, 'getService'], [$serviceRef])
: $def->getFactory();
try {
$def->setFactory($this->completeStatement($factory));
$this->classListNeedsRefresh = FALSE;
$this->currentService = $name;
$setups = $def->getSetup();
foreach ($setups as & $setup) {
if (is_string($setup->getEntity()) && strpbrk($setup->getEntity(), ':@?\\') === FALSE) { // auto-prepend @self
$setup = new Statement(['@' . $name, $setup->getEntity()], $setup->arguments);
}
$setup = $this->completeStatement($setup);
}
$def->setSetup($setups);
} catch (\Exception $e) {
throw new ServiceCreationException("Service '$name': " . $e->getMessage(), 0, $e);
} finally {
$this->currentService = NULL;
}
}
}
/**
* @return Statement
*/
public function completeStatement(Statement $statement)
{
$entity = $this->normalizeEntity($statement->getEntity());
$arguments = $statement->arguments;
if (is_string($entity) && Strings::contains($entity, '?')) { // PHP literal
} elseif ($service = $this->getServiceName($entity)) { // factory calling
$params = [];
foreach ($this->definitions[$service]->parameters as $k => $v) {
$params[] = preg_replace('#\w+\z#', '\$$0', (is_int($k) ? $v : $k)) . (is_int($k) ? '' : ' = ' . PhpHelpers::dump($v));
}
$rm = new \ReflectionFunction(create_function(implode(', ', $params), ''));
$arguments = Helpers::autowireArguments($rm, $arguments, $this);
$entity = '@' . $service;
} elseif ($entity === 'not') { // operator
} elseif (is_string($entity)) { // class name
if (!class_exists($entity)) {
throw new ServiceCreationException("Class $entity not found.");
} elseif ((new ReflectionClass($entity))->isAbstract()) {
throw new ServiceCreationException("Class $entity is abstract.");
} elseif (($rm = (new ReflectionClass($entity))->getConstructor()) !== NULL && !$rm->isPublic()) {
$visibility = $rm->isProtected() ? 'protected' : 'private';
throw new ServiceCreationException("Class $entity has $visibility constructor.");
} elseif ($constructor = (new ReflectionClass($entity))->getConstructor()) {
$this->addDependency($constructor);
$arguments = Helpers::autowireArguments($constructor, $arguments, $this);
} elseif ($arguments) {
throw new ServiceCreationException("Unable to pass arguments, class $entity has no constructor.");
}
} elseif (!Nette\Utils\Arrays::isList($entity) || count($entity) !== 2) {
throw new ServiceCreationException(sprintf('Expected class, method or property, %s given.', PhpHelpers::dump($entity)));
} elseif (!preg_match('#^\$?' . PhpHelpers::PHP_IDENT . '(\[\])?\z#', $entity[1])) {
throw new ServiceCreationException("Expected function, method or property name, '$entity[1]' given.");
} elseif ($entity[0] === '') { // globalFunc
if (!Nette\Utils\Arrays::isList($arguments)) {
throw new ServiceCreationException("Unable to pass specified arguments to $entity[0].");
} elseif (!function_exists($entity[1])) {
throw new ServiceCreationException("Function $entity[1] doesn't exist.");
}
$rf = new \ReflectionFunction($entity[1]);
$this->addDependency($rf);
$arguments = Helpers::autowireArguments($rf, $arguments, $this);
} else {
if ($entity[0] instanceof Statement) {
$entity[0] = $this->completeStatement($entity[0]);
} elseif ($service = $this->getServiceName($entity[0])) { // service method
$entity[0] = '@' . $service;
}
if ($entity[1][0] === '$') { // property getter, setter or appender
Validators::assert($arguments, 'list:0..1', "setup arguments for '" . Nette\Utils\Callback::toString($entity) . "'");
if (!$arguments && substr($entity[1], -2) === '[]') {
throw new ServiceCreationException("Missing argument for $entity[1].");
}
} else {
$class = empty($service) || $entity[1] === 'create'
? $this->resolveEntityClass($entity[0])
: $this->definitions[$service]->getClass();
$arguments = $this->autowireArguments($class, $entity[1], $arguments);
}
}
array_walk_recursive($arguments, function (& $val) {
if ($val instanceof Statement) {
$val = $this->completeStatement($val);
} elseif ($val === $this) {
trigger_error("Replace object ContainerBuilder in Statement arguments with '@container'.", E_USER_DEPRECATED);
$val = self::literal('$this');
} elseif ($val instanceof ServiceDefinition) {
$val = '@' . current(array_keys($this->getDefinitions(), $val, TRUE));
} elseif (is_string($val) && strlen($val) > 1 && $val[0] === '@' && $val[1] !== '@') {
$pair = explode('::', $val, 2);
$name = $this->getServiceName($pair[0]);
if (!isset($pair[1])) { // @service
$val = '@' . $name;
} elseif (preg_match('#^[A-Z][A-Z0-9_]*\z#', $pair[1], $m)) { // @service::CONSTANT
$val = self::literal($this->getDefinition($name)->getClass() . '::' . $pair[1]);
} else { // @service::property
$val = new Statement(['@' . $name, '$' . $pair[1]]);
}
}
});
return new Statement($entity, $arguments);
}
private function checkCase($class)
{
if ((class_exists($class) || interface_exists($class)) && $class !== ($name = (new ReflectionClass($class))->getName())) {
throw new ServiceCreationException("Case mismatch on class name '$class', correct name is '$name'.");
}
}
/**
* Adds item to the list of dependencies.
* @param ReflectionClass|\ReflectionFunctionAbstract|string
* @return self
* @internal
*/
public function addDependency($dep)
{
$this->dependencies[] = $dep;
return $this;
}
/**
* Returns the list of dependencies.
* @return array
*/
public function getDependencies()
{
return $this->dependencies;
}
/**
* Expands %placeholders% in strings.
* @return mixed
* @deprecated
*/
public function expand($value)
{
return Helpers::expand($value, $this->parameters);
}
/**
* @return Nette\PhpGenerator\PhpLiteral
*/
public static function literal($phpCode)
{
return new Nette\PhpGenerator\PhpLiteral($phpCode);
}
/** @internal */
public function normalizeEntity($entity)
{
if (is_string($entity) && Strings::contains($entity, '::') && !Strings::contains($entity, '?')) { // Class::method -> [Class, method]
$entity = explode('::', $entity);
}
if (is_array($entity) && $entity[0] instanceof ServiceDefinition) { // [ServiceDefinition, ...] -> [@serviceName, ...]
$entity[0] = '@' . current(array_keys($this->definitions, $entity[0], TRUE));
} elseif ($entity instanceof ServiceDefinition) { // ServiceDefinition -> @serviceName
$entity = '@' . current(array_keys($this->definitions, $entity, TRUE));
} elseif (is_array($entity) && $entity[0] === $this) { // [$this, ...] -> [@container, ...]
trigger_error("Replace object ContainerBuilder in Statement entity with '@container'.", E_USER_DEPRECATED);
$entity[0] = '@' . self::THIS_CONTAINER;
}
return $entity; // Class, @service, [Class, member], [@service, member], [, globalFunc], Statement
}
/**
* Converts @service or @\Class -> service name and checks its existence.
* @return string of FALSE, if argument is not service name
* @internal
*/
public function getServiceName($arg)
{
if (!is_string($arg) || !preg_match('#^@[\w\\\\.][^:]*\z#', $arg)) {
return FALSE;
}
$service = substr($arg, 1);
if ($service === self::THIS_SERVICE) {
$service = $this->currentService;
}
if (Strings::contains($service, '\\')) {
if ($this->classList === FALSE) { // may be disabled by prepareClassList
return $service;
}
$res = $this->getByType($service);
if (!$res) {
throw new ServiceCreationException("Reference to missing service of type $service.");
}
return $res;
}
$service = isset($this->aliases[$service]) ? $this->aliases[$service] : $service;
if (!isset($this->definitions[$service])) {
throw new ServiceCreationException("Reference to missing service '$service'.");
}
return $service;
}
/**
* Creates a list of arguments using autowiring.
* @return array
* @internal
*/
public function autowireArguments($class, $method, array $arguments)
{
$rc = new ReflectionClass($class);
if (!$rc->hasMethod($method)) {
if (!Nette\Utils\Arrays::isList($arguments)) {
throw new ServiceCreationException("Unable to pass specified arguments to $class::$method().");
}
return $arguments;
}
$rm = $rc->getMethod($method);
if (!$rm->isPublic()) {
throw new ServiceCreationException("$class::$method() is not callable.");
}
$this->addDependency($rm);
return Helpers::autowireArguments($rm, $arguments, $this);
}
/** @deprecated */
public function generateClasses($className = 'Container', $parentName = NULL)
{
trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
return (new PhpGenerator($this))->generate($className);
}
/** @deprecated */
public function formatStatement(Statement $statement)
{
trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
return (new PhpGenerator($this))->formatStatement($statement);
}
/** @deprecated */
public function formatPhp($statement, $args)
{
array_walk_recursive($args, function (& $val) {
if ($val instanceof Statement) {
$val = $this->completeStatement($val);
} elseif ($val === $this) {
trigger_error("Replace object ContainerBuilder in Statement arguments with '@container'.", E_USER_DEPRECATED);
$val = self::literal('$this');
} elseif ($val instanceof ServiceDefinition) {
$val = '@' . current(array_keys($this->getDefinitions(), $val, TRUE));
}
});
return (new PhpGenerator($this))->formatPhp($statement, $args);
}
}
| {'content_hash': '3f9da1d1f4dd6391c73af3dc784fba79', 'timestamp': '', 'source': 'github', 'line_count': 835, 'max_line_length': 201, 'avg_line_length': 31.144910179640718, 'alnum_prop': 0.6293163116203953, 'repo_name': 'slepic/urc-sn-gen', 'id': '588a02f173689ed577ea3080d49d92fa2aa2882a', 'size': '26136', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'nette-app/vendor/nette/di/src/DI/ContainerBuilder.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ApacheConf', 'bytes': '1098'}, {'name': 'CSS', 'bytes': '2307'}, {'name': 'HTML', 'bytes': '11683'}, {'name': 'JavaScript', 'bytes': '80'}, {'name': 'PHP', 'bytes': '54413'}]} |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Leap Motion Controller Plugin — Leap Motion Python SDK v2.3 documentation</title>
<link rel="stylesheet" href="../../cpp/_static/bootstrap-3.0.0/css/documentation-bundle.1439949735.css" type="text/css" />
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '2.3',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: false
};
</script>
<script type="text/javascript" src="../../cpp/_static/bootstrap-3.0.0/js/documentation-bundle.1439949735.js"></script>
<link rel="top" title="Leap Motion Python SDK v2.3 documentation" href="../index.html" />
<script type="text/javascript" src="/assets/standalone-header.js?r9"></script>
<link rel="stylesheet" href="/assets/standalone-header.css?r9" type="text/css" />
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-31536531-1']);
_gaq.push(['_setDomainName', 'leapmotion.com']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<script>
function getQueryValue(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
var relPath = "../../";
var requestedAPI = getQueryValue("proglang");
if(requestedAPI == "current") requestedAPI = localStorage["currentAPI"];
var pageAPI = 'python';
var hasAPI = {};
hasAPI.unreal = true;
if(requestedAPI && (requestedAPI != pageAPI))
{
if(pageAPI != 'none'){
var redirectedLocation = relPath + 'python/unreal/Unreal.ControllerPlugin.html';
if( requestedAPI == 'cpp' && hasAPI.cpp){
redirectedLocation = relPath + "cpp/unreal/Unreal.ControllerPlugin.html";
}
else if( requestedAPI == 'csharp' && hasAPI.csharp){
redirectedLocation = relPath + "csharp/unreal/Unreal.ControllerPlugin.html";
}
else if( requestedAPI == 'unity' && hasAPI.unity){
redirectedLocation = relPath + "unity/unreal/Unreal.ControllerPlugin.html";
}
else if( requestedAPI == 'objc' && hasAPI.objc){
redirectedLocation = relPath + "objc/unreal/Unreal.ControllerPlugin.html";
}
else if( requestedAPI == 'java' && hasAPI.java) {
redirectedLocation = relPath + "java/unreal/Unreal.ControllerPlugin.html";
}
else if( requestedAPI == 'javascript' && hasAPI.javascript){
redirectedLocation = relPath + "javascript/unreal/Unreal.ControllerPlugin.html";
}
else if( requestedAPI == 'python' && hasAPI.python){
redirectedLocation = relPath + "python/unreal/Unreal.ControllerPlugin.html";
}
else if( requestedAPI == 'unreal' && hasAPI.unreal) {
redirectedLocation = relPath + "unreal/unreal/Unreal.ControllerPlugin.html";
} else {
if( requestedAPI == 'cpp'){
redirectedLocation = relPath + "cpp/index.html?proglang=cpp";
}
else if( requestedAPI == 'csharp'){
redirectedLocation = relPath + "csharp/index.html?proglang=csharp";
}
else if( requestedAPI == 'unity'){
redirectedLocation = relPath + "unity/index.html?proglang=unity";
}
else if( requestedAPI == 'objc'){
redirectedLocation = relPath + "objc/index.html?proglang=objc";
}
else if( requestedAPI == 'java') {
redirectedLocation = relPath + "java/index.html?proglang=java";
}
else if( requestedAPI == 'javascript'){
redirectedLocation = relPath + "javascript/index.html?proglang=javascript";
}
else if( requestedAPI == 'python'){
redirectedLocation = relPath + "python/index.html?proglang=python";
}
else if( requestedAPI == 'unreal') {
redirectedLocation = relPath + "unreal/index.html?proglang=unreal";
} else {
redirectedLocation = relPath + "index.html";
}
}
//Guard against redirecting to the same page (infinitely)
if(relPath + 'python/unreal/Unreal.ControllerPlugin.html' != redirectedLocation) window.location.replace(redirectedLocation);
}
}
</script>
<script>
window.addEventListener('keyup', handleKeyInput);
function handleKeyInput(e)
{
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
if( character == "J" & e.altKey){ }
else if( character == "K" & e.altKey){
}
}
</script>
</head>
<body role="document">
<div class="developer-portal-styles">
<header class="navbar navbar-static-top developer-navbar header beta-header">
<nav class="container pr">
<a class="logo-link pull-left" href="/">
<img alt="Leap Motion Developers" class="media-object pull-left white-background" src="../_static/logo.png" />
</a>
<span class="inline-block hidden-phone developer-logo-text">
<div class="text">
<a href="/">
<span class="more-than-1199">Developer Portal</span>
</a>
</div>
</span>
<button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<!-- Everything within here will be hidden at 940px or less, accessible via a button. -->
<div class="nav-collapse">
<ul class="nav header-navigation developer-links">
<li class="external-link"><a href="https://developer.leapmotion.com/features">What's new</a> </li>
<li class="external-link"><a href="https://developer.leapmotion.com/downloads/skeletal-beta" class="">Getting Started</a></li>
<li><a class="active" href="#" class="">Documentation</a></li>
<li class="external-link"> <a href="https://developer.leapmotion.com/gallery" class="">Examples</a> </li>
<li class="external-link"> <a href="https://www.leapmotion.com/blog/category/labs/" class="" target="_blank">Blog <i class='fa fa-external-link'></i></a> </li>
<li class="external-link"> <a href="https://community.leapmotion.com/category/beta" class="" target="_blank">Community <i class='fa fa-external-link'></i></a> </li>
</ul>
</div>
</nav>
</header>
</div>
<section class="main-wrap">
<div data-swiftype-index="true">
<div class="second_navigation">
<div class="container">
<div class="row">
<div class="col-md-8">
<ul>
<li>
<a href="../../javascript/index.html?proglang=javascript" onclick="localStorage['currentAPI'] = 'javascript'">JavaScript</a>
</li>
<li>
<a href="../../unity/index.html?proglang=unity" onclick="localStorage['currentAPI'] = 'unity'">Unity</a>
</li>
<li>
<a href="../../csharp/index.html?proglang=csharp" onclick="localStorage['currentAPI'] = 'csharp'">C#</a>
</li>
<li>
<a href="../../cpp/index.html?proglang=cpp" onclick="localStorage['currentAPI'] = 'cpp'">C++</a>
</li>
<li>
<a href="../../java/index.html?proglang=java" onclick="localStorage['currentAPI'] = 'java'">Java</a>
</li>
<li>
Python
</li>
<li>
<a href="../../objc/index.html?proglang=objc" onclick="localStorage['currentAPI'] = 'objc'">Objective-C</a>
</li>
<li>
<a href="../../unreal/unreal/Unreal.ControllerPlugin.html?proglang=unreal" onclick="localStorage['currentAPI'] = 'unreal'">Unreal</a>
</li>
</ul>
</div>
<div class="col-md-4 search">
<script>
function storeThisPage(){
sessionStorage["pageBeforeSearch"] = window.location;
return true;
}
function doneWithSearch(){
var storedPage = sessionStorage["pageBeforeSearch"];
if(storedPage){
window.location = storedPage;
} else {
window.location = "index.html"; //fallback
}
return false;
}
</script>
<div style="margin-top:-4px">
<ul style="display:inline; white-space:nowrap"><li>
<form class="navbar-form" action="../search.html" method="get" onsubmit="storeThisPage()">
<div class="form-group">
<input type="search" results="5" name="q" class="form-control" placeholder="Search" />
</div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<script>
//Remove dev portal header and footer when viewing from file system
if(window.location.protocol == 'file:'){
var navNode = document.querySelector(".developer-links");
navNode.parentNode.removeChild(navNode);
}
</script>
<div id="wrap" data-spy="scroll" data-target="#sidebar">
<div class="container">
<div class="row">
<div class="col-md-9 pull-right">
<!--
<span id="breadcrumbs">
<a href="../index.html">Home</a>»
Leap Motion Controller Plugin
</span> -->
<div class="section" id="leap-motion-controller-plugin">
<h1>Leap Motion Controller Plugin<a class="headerlink" href="#leap-motion-controller-plugin" title="Permalink to this headline">¶</a></h1>
<div class="line-block" id="unreala00004">
<div class="line"><em>class</em> <strong>FLeapMotionControllerPlugin</strong></div>
</div>
<blockquote>
<div><p>The public interface to the Leap Motion Controller plugin module. </p>
<p></p>
<em>Public Static Functions</em><blockquote>
<div><p><span class="target" id="unreala00004_1acde7dd5d2d11ab85404c433d6ff37f6a"></span><div class="line-block">
<div class="line"><a class="reference internal" href="#unreala00004"><em>FLeapMotionControllerPlugin</em></a> & <strong>Get</strong>()</div>
</div>
</p>
<blockquote>
<div><p>Singleton-like access to this module’s interface. </p>
<p><p>Beware of calling this during the shutdown phase. The module might have been unloaded already.</p>
<p><dl class="docutils">
<dt><strong>Return</strong></dt>
<dd>Returns singleton instance, loading the module on demand if needed </dd>
</dl>
</p>
</p>
</div></blockquote>
<p><span class="target" id="unreala00004_1aa94c3552ff19802b898400162cd120ea"></span><div class="line-block">
<div class="line"><a class="reference internal" href="Unreal.ControllerDevice.html#unreala00005"><em>FLeapMotionDevice</em></a> * <strong>GetLeapDeviceSafe</strong>()</div>
</div>
</p>
<blockquote>
<div><p>Simple helper function to get the device currently active. </p>
<p><dl class="docutils">
<dt><strong>Return</strong></dt>
<dd>Pointer to the LeapMotionDevice, or nullptr if Device is not available. </dd>
</dl>
</p>
</div></blockquote>
<p><span class="target" id="unreala00004_1acaefcb70f013f534bc63a65c25bd0060"></span><div class="line-block">
<div class="line">bool <strong>IsAvailable</strong>()</div>
</div>
</p>
<blockquote>
<div><p>Checks to see if this module is loaded and ready. </p>
<p><p>It is only valid to call <a class="reference internal" href="#unreala00004_1acde7dd5d2d11ab85404c433d6ff37f6a"><em>Get()</em></a> if <a class="reference internal" href="#unreala00004_1acaefcb70f013f534bc63a65c25bd0060"><em>IsAvailable()</em></a> returns true.</p>
<p><dl class="docutils">
<dt><strong>Return</strong></dt>
<dd>True if the module is loaded and ready to use </dd>
</dl>
</p>
</p>
</div></blockquote>
</div></blockquote>
</div></blockquote>
</div>
<!-- get_disqus_sso -->
</div>
<div id="sidebar" class="col-md-3">
<div class="well-sidebar" data-offset-top="188">
<ul>
<li><a href="../index.html" title="Home">Python Docs (v2.3)</a></li>
</ul><ul>
<li class="toctree-l1"><a class="reference internal" href="../devguide/Intro_Skeleton_API.html">Introducing the Skeletal Tracking Model</a></li>
<li class="toctree-l1"><a class="reference internal" href="../devguide/Leap_Overview.html">API Overview</a></li>
<li class="toctree-l1"><a class="reference internal" href="../practices/Leap_Practices.html">Guidelines</a></li>
<li class="toctree-l1"><a class="reference internal" href="../devguide/Leap_Guides.html">Application Development</a></li>
<li class="toctree-l1"><a class="reference internal" href="../devguide/Leap_Guides2.html">Using the Tracking API</a></li>
<li class="toctree-l1"><a class="reference internal" href="../api/Leap_Classes.html">API Reference</a></li>
<li class="toctree-l1"><a class="reference internal" href="../supplements/Leap_Supplements.html">Appendices</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!--
<div class="ribbon">
<p>Python</p>
</div>
<footer>
<div id="footer" class="container">
<div class="container">
<div class="copyright">
<span>Copyright © 2012 - 2014, Leap Motion, Inc.</span>
</div>
</div>
</div>
</footer>
</body>
</html> | {'content_hash': '1586a16e44c7bf8787dfa49820cc07b7', 'timestamp': '', 'source': 'github', 'line_count': 388, 'max_line_length': 269, 'avg_line_length': 37.43298969072165, 'alnum_prop': 0.6054117323051501, 'repo_name': 'joelbandi/Be-ethoven', 'id': '2f9f04f0f48cee0308038f72d3c487cf8f684206', 'size': '14528', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'LeapSDK/docs/python/unreal/Unreal.ControllerPlugin.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '6722'}, {'name': 'C++', 'bytes': '347503'}, {'name': 'CSS', 'bytes': '101632'}, {'name': 'HTML', 'bytes': '24938147'}, {'name': 'Java', 'bytes': '14109'}, {'name': 'JavaScript', 'bytes': '408159'}, {'name': 'Makefile', 'bytes': '526'}, {'name': 'Python', 'bytes': '96203'}]} |
using UnityEngine;
using System.Collections.Generic;
using GameDataEditor;
#if GDE_PLAYMAKER_SUPPORT
namespace HutongGames.PlayMaker.Actions
{
[ActionCategory(GDMConstants.ActionCategory)]
[Tooltip(GDMConstants.GetColorCustomActionTooltip)]
public class GDEGetCustomColor : GDEActionBase
{
[UIHint(UIHint.FsmString)]
[Tooltip(GDMConstants.ColorCustomFieldTooltip)]
public FsmString CustomField;
[UIHint(UIHint.FsmColor)]
public FsmColor StoreResult;
public override void Reset()
{
base.Reset();
StoreResult = null;
}
public override void OnEnter()
{
try
{
Dictionary<string, object> data;
string customKey;
Color val;
if (GDEDataManager.DataDictionary.ContainsKey(ItemName.Value))
{
GDEDataManager.Get(ItemName.Value, out data);
data.TryGetString(FieldName.Value, out customKey);
customKey = GDEDataManager.GetString(ItemName.Value+"_"+FieldName.Value, customKey);
Dictionary<string, object> customData;
GDEDataManager.Get(customKey, out customData);
customData.TryGetColor(CustomField.Value, out val);
StoreResult.Value = val;
}
else
{
// New item case
customKey = GDEDataManager.GetString(ItemName.Value+"_"+FieldName.Value, string.Empty);
if (GDEDataManager.Get(customKey, out data))
{
data.TryGetColor(CustomField.Value, out val);
StoreResult.Value = val;
}
}
StoreResult.Value = GDEDataManager.GetColor(customKey+"_"+CustomField.Value, StoreResult.Value);
}
catch(UnityException ex)
{
LogError(ex.ToString());
}
finally
{
Finish();
}
}
}
}
#endif
| {'content_hash': '3a04b984cb77d1173f4e1625943068f1', 'timestamp': '', 'source': 'github', 'line_count': 73, 'max_line_length': 100, 'avg_line_length': 27.041095890410958, 'alnum_prop': 0.5835866261398176, 'repo_name': 'yantian001/DeadTarget', 'id': '6abdab7603ac7508b88f175252630b34a964d47f', 'size': '1974', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Assets/GameDataEditor/Playmaker/GDEGetCustomColor.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '2950'}, {'name': 'C#', 'bytes': '5477952'}, {'name': 'GLSL', 'bytes': '391774'}, {'name': 'HTML', 'bytes': '4202869'}, {'name': 'JavaScript', 'bytes': '49979'}, {'name': 'Objective-C', 'bytes': '205606'}, {'name': 'Objective-C++', 'bytes': '10565'}]} |
// Creating a closure to avoid leaking variables into global scope,
// and using the variable undefined to get a X-browser compatible
// way of comparing with undefined, see this stackoverflow answer:
// http://stackoverflow.com/questions/135448/how-do-i-check-to-see-if-an-object-has-a-property-in-javascript#answer-135568
(function (window, undefined) {
// Upgrading to EcmaScript 5, and generating more helpful execptions and errors.
// Even though: http://bugs.jquery.com/ticket/13335, we've decided to go this path
// for now to write better code. We only test in modern browsers right now. If
// this bothers you(you use Firefox < 18 and your debug trace crashes it f.x.),
// poke us and we'll bake a version without it. For now, deal with it, since we
// don't have any legacy browsers to test with ;)
"use strict";
var jStorage = function (config) {
// The jStorage object is actually just the init constructor 'enhanced'
return new jStorage.fn.init(config);
};
var error = function (msg) {
// prepend with our libName to be nice, not everyone has nice debugging tools.
throw "jStorage: " + msg;
};
jStorage.fn = jStorage.prototype = {
init: function (config) {
this._provider = false;
// Do some inital sanity checking of our input.
if(config === undefined || !config) error("No config, please consult the readme ;)");
if(config.name === undefined) error("No name in config.");
if (jStorage.providers[config.name]) {
var provider = jStorage.providers[config.name];
this._provider = provider;
// Calling the callback now becomes the provider
// modules responsibility
provider.init(this, config);
} else {
error('Storage provider "' + config.name + '" was not loaded.');
}
},
get: function (name, callback) {
if (this._provider) {
this._provider.get(name, callback);
}
},
set: function(name, content, callback) {
if (this._provider) {
this._provider.set(name, content, callback);
}
},
move: function (currentName, newName, callback) {
if (this._provider) {
this._provider.move(currentName, newName, callback);
}
},
del: function (name, callback) {
if (this._provider) {
this._provider.del(name, callback);
}
},
list: function (name, callback) {
if (this._provider) {
this._provider.list(name, callback);
}
},
exists: function (name, callback) {
//console.log('exists');
if (this._provider) {
this._provider.exists(name, callback);
}
}
};
// Placeholder for our provider modules.
// Each module will register itself here.
jStorage.providers = {
};
// Give the init function the jStorage prototype for later instantiation
jStorage.fn.init.prototype = jStorage.fn;
window.jStorage = jStorage;
}(window)); | {'content_hash': '4823cc6fa6741bfce3c4c2c66e226815', 'timestamp': '', 'source': 'github', 'line_count': 87, 'max_line_length': 122, 'avg_line_length': 37.5632183908046, 'alnum_prop': 0.5795593635250919, 'repo_name': 'StefanWallin/healthmeasure', 'id': 'c67654a0a1b4e784c3f7f982317f243800bc665e', 'size': '3524', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'js/lib/jStorage.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '15668'}, {'name': 'JavaScript', 'bytes': '51331'}]} |
/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */
(function(w) {
"use strict";
w.matchMedia = w.matchMedia || function(doc, undefined) {
var bool, docElem = doc.documentElement, refNode = docElem.firstElementChild || docElem.firstChild, fakeBody = doc.createElement("body"), div = doc.createElement("div");
div.id = "mq-test-1";
div.style.cssText = "position:absolute;top:-100em";
fakeBody.style.background = "none";
fakeBody.appendChild(div);
return function(q) {
div.innerHTML = '­<style media="' + q + '"> #mq-test-1 { width: 42px; }</style>';
docElem.insertBefore(fakeBody, refNode);
bool = div.offsetWidth === 42;
docElem.removeChild(fakeBody);
return {
matches: bool,
media: q
};
};
}(w.document);
})(this);
/*! matchMedia() polyfill addListener/removeListener extension. Author & copyright (c) 2012: Scott Jehl. Dual MIT/BSD license */
(function(w) {
"use strict";
if (w.matchMedia && w.matchMedia("all").addListener) {
return false;
}
var localMatchMedia = w.matchMedia, hasMediaQueries = localMatchMedia("only all").matches, isListening = false, timeoutID = 0, queries = [], handleChange = function(evt) {
w.clearTimeout(timeoutID);
timeoutID = w.setTimeout(function() {
for (var i = 0, il = queries.length; i < il; i++) {
var mql = queries[i].mql, listeners = queries[i].listeners || [], matches = localMatchMedia(mql.media).matches;
if (matches !== mql.matches) {
mql.matches = matches;
for (var j = 0, jl = listeners.length; j < jl; j++) {
listeners[j].call(w, mql);
}
}
}
}, 30);
};
w.matchMedia = function(media) {
var mql = localMatchMedia(media), listeners = [], index = 0;
mql.addListener = function(listener) {
if (!hasMediaQueries) {
return;
}
if (!isListening) {
isListening = true;
w.addEventListener("resize", handleChange, true);
}
if (index === 0) {
index = queries.push({
mql: mql,
listeners: listeners
});
}
listeners.push(listener);
};
mql.removeListener = function(listener) {
for (var i = 0, il = listeners.length; i < il; i++) {
if (listeners[i] === listener) {
listeners.splice(i, 1);
}
}
};
return mql;
};
})(this);
/*! Respond.js v1.4.0: min/max-width media query polyfill. (c) Scott Jehl. MIT Lic. j.mp/respondjs */
(function(w) {
"use strict";
var respond = {};
w.respond = respond;
respond.update = function() {};
var requestQueue = [], xmlHttp = function() {
var xmlhttpmethod = false;
try {
xmlhttpmethod = new w.XMLHttpRequest();
} catch (e) {
xmlhttpmethod = new w.ActiveXObject("Microsoft.XMLHTTP");
}
return function() {
return xmlhttpmethod;
};
}(), ajax = function(url, callback) {
var req = xmlHttp();
if (!req) {
return;
}
req.open("GET", url, true);
req.onreadystatechange = function() {
if (req.readyState !== 4 || req.status !== 200 && req.status !== 304) {
return;
}
callback(req.responseText);
};
if (req.readyState === 4) {
return;
}
req.send(null);
};
respond.ajax = ajax;
respond.queue = requestQueue;
respond.regex = {
media: /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi,
keyframes: /@.*keyframes[^\{]+\{(?:[^\{\}]*\{[^\}\{]*\})+[^\}]+\}/gi,
urls: /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g,
findStyles: /@media *([^\{]+)\{([\S\s]+?)$/,
only: /(only\s+)?([a-zA-Z]+)\s?/,
minw: /\([\s]*min\-width\s*:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/,
maxw: /\([\s]*max\-width\s*:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/
};
respond.mediaQueriesSupported = w.matchMedia && w.matchMedia("only all") !== null && w.matchMedia("only all").matches;
if (respond.mediaQueriesSupported) {
return;
}
var doc = w.document, docElem = doc.documentElement, mediastyles = [], rules = [], appendedEls = [], parsedSheets = {}, resizeThrottle = 30, head = doc.getElementsByTagName("head")[0] || docElem, base = doc.getElementsByTagName("base")[0], links = head.getElementsByTagName("link"), lastCall, resizeDefer, eminpx, getEmValue = function() {
var ret, div = doc.createElement("div"), body = doc.body, originalHTMLFontSize = docElem.style.fontSize, originalBodyFontSize = body && body.style.fontSize, fakeUsed = false;
div.style.cssText = "position:absolute;font-size:1em;width:1em";
if (!body) {
body = fakeUsed = doc.createElement("body");
body.style.background = "none";
}
docElem.style.fontSize = "100%";
body.style.fontSize = "100%";
body.appendChild(div);
docElem.insertBefore(body, docElem.firstChild);
ret = div.offsetWidth;
if (fakeUsed) {
docElem.removeChild(body);
} else {
body.removeChild(div);
}
docElem.style.fontSize = originalHTMLFontSize;
if (originalBodyFontSize) {
body.style.fontSize = originalBodyFontSize;
}
ret = eminpx = parseFloat(ret);
return ret;
}, applyMedia = function(fromResize) {
var name = "clientWidth", docElemProp = docElem[name], currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[name] || docElemProp, styleBlocks = {}, lastLink = links[links.length - 1], now = new Date().getTime();
if (fromResize && lastCall && now - lastCall < resizeThrottle) {
w.clearTimeout(resizeDefer);
resizeDefer = w.setTimeout(applyMedia, resizeThrottle);
return;
} else {
lastCall = now;
}
for (var i in mediastyles) {
if (mediastyles.hasOwnProperty(i)) {
var thisstyle = mediastyles[i], min = thisstyle.minw, max = thisstyle.maxw, minnull = min === null, maxnull = max === null, em = "em";
if (!!min) {
min = parseFloat(min) * (min.indexOf(em) > -1 ? eminpx || getEmValue() : 1);
}
if (!!max) {
max = parseFloat(max) * (max.indexOf(em) > -1 ? eminpx || getEmValue() : 1);
}
if (!thisstyle.hasquery || (!minnull || !maxnull) && (minnull || currWidth >= min) && (maxnull || currWidth <= max)) {
if (!styleBlocks[thisstyle.media]) {
styleBlocks[thisstyle.media] = [];
}
styleBlocks[thisstyle.media].push(rules[thisstyle.rules]);
}
}
}
for (var j in appendedEls) {
if (appendedEls.hasOwnProperty(j)) {
if (appendedEls[j] && appendedEls[j].parentNode === head) {
head.removeChild(appendedEls[j]);
}
}
}
for (var k in styleBlocks) {
if (styleBlocks.hasOwnProperty(k)) {
var ss = doc.createElement("style"), css = styleBlocks[k].join("\n");
ss.type = "text/css";
ss.media = k;
head.insertBefore(ss, lastLink.nextSibling);
if (ss.styleSheet) {
ss.styleSheet.cssText = css;
} else {
ss.appendChild(doc.createTextNode(css));
}
appendedEls.push(ss);
}
}
}, translate = function(styles, href, media) {
var qs = styles.replace(respond.regex.keyframes, "").match(respond.regex.media), ql = qs && qs.length || 0;
href = href.substring(0, href.lastIndexOf("/"));
var repUrls = function(css) {
return css.replace(respond.regex.urls, "$1" + href + "$2$3");
}, useMedia = !ql && media;
if (href.length) {
href += "/";
}
if (useMedia) {
ql = 1;
}
for (var i = 0; i < ql; i++) {
var fullq, thisq, eachq, eql;
if (useMedia) {
fullq = media;
rules.push(repUrls(styles));
} else {
fullq = qs[i].match(respond.regex.findStyles) && RegExp.$1;
rules.push(RegExp.$2 && repUrls(RegExp.$2));
}
eachq = fullq.split(",");
eql = eachq.length;
for (var j = 0; j < eql; j++) {
thisq = eachq[j];
mediastyles.push({
media: thisq.split("(")[0].match(respond.regex.only) && RegExp.$2 || "all",
rules: rules.length - 1,
hasquery: thisq.indexOf("(") > -1,
minw: thisq.match(respond.regex.minw) && parseFloat(RegExp.$1) + (RegExp.$2 || ""),
maxw: thisq.match(respond.regex.maxw) && parseFloat(RegExp.$1) + (RegExp.$2 || "")
});
}
}
applyMedia();
}, makeRequests = function() {
if (requestQueue.length) {
var thisRequest = requestQueue.shift();
ajax(thisRequest.href, function(styles) {
translate(styles, thisRequest.href, thisRequest.media);
parsedSheets[thisRequest.href] = true;
w.setTimeout(function() {
makeRequests();
}, 0);
});
}
}, ripCSS = function() {
for (var i = 0; i < links.length; i++) {
var sheet = links[i], href = sheet.href, media = sheet.media, isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet";
if (!!href && isCSS && !parsedSheets[href]) {
if (sheet.styleSheet && sheet.styleSheet.rawCssText) {
translate(sheet.styleSheet.rawCssText, href, media);
parsedSheets[href] = true;
} else {
if (!/^([a-zA-Z:]*\/\/)/.test(href) && !base || href.replace(RegExp.$1, "").split("/")[0] === w.location.host) {
if (href.substring(0, 2) === "//") {
href = w.location.protocol + href;
}
requestQueue.push({
href: href,
media: media
});
}
}
}
}
makeRequests();
};
ripCSS();
respond.update = ripCSS;
respond.getEmValue = getEmValue;
function callMedia() {
applyMedia(true);
}
if (w.addEventListener) {
w.addEventListener("resize", callMedia, false);
} else if (w.attachEvent) {
w.attachEvent("onresize", callMedia);
}
})(this); | {'content_hash': '59a38c24f020e81f4d1727ca80ec622e', 'timestamp': '', 'source': 'github', 'line_count': 270, 'max_line_length': 341, 'avg_line_length': 36.696296296296296, 'alnum_prop': 0.5646951958013726, 'repo_name': 'aMadReason/Epub3Maker', 'id': '77a81e7556da41de0150d0d0fc7e7e38e548e64d', 'size': '10064', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'view/_dep/Respond/dest/respond.matchmedia.addListener.src.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '105290'}, {'name': 'HTML', 'bytes': '169927'}, {'name': 'JavaScript', 'bytes': '102990'}, {'name': 'PHP', 'bytes': '1013136'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" type="text/css" href="public/components/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="public/components/bootstrap-datepicker/dist/css/bootstrap-datepicker3.css">
<link rel="stylesheet" type="text/css" href="public/css/spending_monitor.css">
<title>Index - SpendingMonitor</title>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="spendings.html">SpendingMonitor</a>
</div> <!-- .navbar-header -->
<ul class="nav navbar-nav">
<li class="active"><a href="spendings.html">Spendings</a></li>
<li><a href="statements.html">Statements</a></li>
</ul>
<form class="navbar-form navbar-right" method="GET" action="login.html">
<button class="btn btn-default" type="submit">
<span class="glyphicon glyphicon-log-out"></span>
Log Out
</button>
</form>
<div class="navbar-text navbar-right">
<span class="glyphicon glyphicon-user"></span>
username
</div> <!-- .navbar-text .navbar-right -->
</div> <!-- .container --->
</nav>
<div class="container">
<form class="form-group">
<div class="row">
<div class="col-xs-12 col-sm-2">
<div class="input-group">
<input id="datepicker" class="form-control" type="text" name="datepicker" readonly>
<label class="input-group-addon btn" for="datepicker">
<span class="glyphicon glyphicon-calendar"></span>
</label>
</div> <!-- .input-group -->
</div> <!-- .col-xs-12 .col-sm-2 -->
<div class="col-xs-12 col-sm-4">
<input class="form-control" type="text" placeholder="Add new item">
</div> <!-- .col-xs-12 .col-sm-4 -->
<div class="col-xs-12 col-sm-3">
<select class="form-control">
<option value="food" >Food</option>
<option value="medical">Medical</option>
<option value="entertainment">Entertainment</option>
<option value="other" selected>Other</option>
</select>
</div> <!-- .col-xs-12 .col-sm-3 -->
<div class="col-xs-12 col-sm-3">
<div class="input-group">
<input class="form-control" type="number" placeholder="Amount">
<div class="input-group-btn">
<button class="btn btn-primary" type="submit">
Add
<span class="glyphicon glyphicon-pencil"></span>
</button>
</div> <!-- .input-group-btn -->
</div> <!-- .input-group -->
</div> <!-- .col-xs-12 .col-sm-6 -->
</div> <!-- .row -->
</form>
<div class="panel panel-default">
<div class="panel-body">
<div class="text-center">
<form class="form form-inline">
<label for="monthpicker">Choose a month: </label>
<div class="input-group">
<input id="monthpicker" class="form-control" type="text" readonly>
<label class="input-group-addon btn" for="monthpicker">
<span class="glyphicon glyphicon-calendar"></span>
</label>
</div> <!-- .input-group -->
</form>
</div> <!-- .text-center -->
</div> <!-- .panel-body -->
<table class="table table-striped table-hover table-condensed table-responsive">
<thead class="thead thead-inverse">
<tr>
<th>Date</th>
<th>Item</th>
<th>Category</th>
<th>Amount</th>
<th></th>
</tr>
</thead>
<tbody>
<tr><td>2015.10.01</td> <td>Dinner</td> <td>Food</td> <td>10</td>
<td>
<div class="btn-group" role="group">
<button class="btn btn-sm btn-default" type="button">
<span class="glyphicon glyphicon-pencil"></span>
</button>
<button class="btn btn-sm btn-default" type="button">
<span class="glyphicon glyphicon-remove"></span>
</button>
</div> <!-- .btn-group -->
</td>
</tr>
<tr><td>2015.10.01</td> <td>Automobile</td> <td>Other</td> <td>1234</td>
<td>
<div class="btn-group" role="group">
<button class="btn btn-sm btn-default" type="button">
<span class="glyphicon glyphicon-pencil"></span>
</button>
<button class="btn btn-sm btn-default" type="button">
<span class="glyphicon glyphicon-remove"></span>
</button>
</div> <!-- .btn-group -->
</td>
</tr>
<tr><td>2015.10.02</td> <td>Lunch</td> <td>Food</td> <td>10</td>
<td>
<div class="btn-group" role="group">
<button class="btn btn-sm btn-default" type="button">
<span class="glyphicon glyphicon-pencil"></span>
</button>
<button class="btn btn-sm btn-default" type="button">
<span class="glyphicon glyphicon-remove"></span>
</button>
</div> <!-- .btn-group -->
</td>
</tr>
<tr><td>2015.10.02</td> <td>Books</td> <td>Entertainment</td> <td>567</td>
<td>
<div class="btn-group" role="group">
<button class="btn btn-sm btn-default" type="button">
<span class="glyphicon glyphicon-pencil"></span>
</button>
<button class="btn btn-sm btn-default" type="button">
<span class="glyphicon glyphicon-remove"></span>
</button>
</div> <!-- .btn-group -->
</td>
</tr>
<tr><td>2015.10.03</td> <td>Medicine</td> <td>Medical</td> <td>89</td>
<td>
<div class="btn-group" role="group">
<button class="btn btn-sm btn-default" type="button">
<span class="glyphicon glyphicon-pencil"></span>
</button>
<button class="btn btn-sm btn-default" type="button">
<span class="glyphicon glyphicon-remove"></span>
</button>
</div> <!-- .btn-group -->
</td>
</tr>
<tr><td>2015.10.04</td> <td>Dinner</td> <td>Food</td> <td>10</td>
<td>
<div class="btn-group" role="group">
<button class="btn btn-sm btn-default" type="button">
<span class="glyphicon glyphicon-pencil"></span>
</button>
<button class="btn btn-sm btn-default" type="button">
<span class="glyphicon glyphicon-remove"></span>
</button>
</div> <!-- .btn-group -->
</td>
</tr>
<tr><td>2015.10.05</td> <td>Groceries</td> <td>Food</td> <td>567</td>
<td>
<div class="btn-group" role="group">
<button class="btn btn-sm btn-default" type="button">
<span class="glyphicon glyphicon-pencil"></span>
</button>
<button class="btn btn-sm btn-default" type="button">
<span class="glyphicon glyphicon-remove"></span>
</button>
</div> <!-- .btn-group -->
</td>
</tr>
</tbody>
</table>
<div class="panel-footer">
<div class="text-center">
<b>Total amount of spending: 121924</b>
</div> <!-- .text-center -->
</div> <!-- .panel-footer -->
</div> <!-- .panel .panel-default -->
</div> <!-- .container --->
<script type="text/javascript" src="public/components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="public/components/bootstrap-datepicker/dist/js/bootstrap-datepicker.js"></script>
<script type="text/javascript">
$("document").ready(function() {
var datePicker = $('#datepicker');
var monthPicker = $('#monthpicker');
datePicker.datepicker({
autoclose: true,
format: "yyyy.mm.dd",
orientation: 'auto top'
});
datePicker.datepicker("setDate", new Date());
monthPicker.datepicker({
autoclose: true,
format: "yyyy.mm",
orientation: 'auto top',
viewMode: "months",
minViewMode: "months"
});
monthPicker.datepicker("setDate", new Date());
});
</script>
</body>
</html>
| {'content_hash': '8726abfd139f8766a6ff81d596139130', 'timestamp': '', 'source': 'github', 'line_count': 214, 'max_line_length': 124, 'avg_line_length': 51.64485981308411, 'alnum_prop': 0.40635179153094464, 'repo_name': 'kocsob/spending-monitor', 'id': 'cc7da79dce1e56d15f941ae1c3c26a0b9fecf9f9', 'size': '11052', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'static/spendings.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '680'}, {'name': 'HTML', 'bytes': '20589'}, {'name': 'JavaScript', 'bytes': '32490'}]} |
from webdav.common import rfc1123_date
from AccessControl import ClassSecurityInfo
from Products.CMFCore import permissions as CMFCorePermissions
from Products.CMFCore.utils import getToolByName
from Products.Archetypes.public import *
from bika.lims.content.bikaschema import BikaSchema
from Products.ATExtensions.ateapi import RecordWidget
from bika.lims.browser.widgets import AddressWidget
from archetypes.referencebrowserwidget import ReferenceBrowserWidget
from bika.lims.config import GENDERS, PROJECTNAME
from bika.lims.browser.fields import AddressField
from bika.lims import PMF, bikaMessageFactory as _
schema = BikaSchema.copy() + Schema((
StringField('Salutation',
widget = StringWidget(
label = _("Salutation",
"Title"),
description=_("Greeting title eg. Mr, Mrs, Dr"),
),
),
StringField('Firstname',
required = 1,
widget = StringWidget(
label=_("Firstname"),
),
),
StringField('Middleinitial',
required = 0,
widget = StringWidget(
label=_("Middle initial"),
),
),
StringField('Middlename',
required = 0,
widget = StringWidget(
label=_("Middle name"),
),
),
StringField('Surname',
required = 1,
widget = StringWidget(
label=_("Surname"),
),
),
ComputedField('Fullname',
expression = 'context.getFullname()',
searchable = 1,
widget = ComputedWidget(
label=_("Full Name"),
visible = {'edit': 'invisible', 'view': 'invisible'},
),
),
StringField('Username',
widget = StringWidget(
visible = False
),
),
StringField('EmailAddress',
schemata = 'Email Telephone Fax',
searchable = 1,
widget = StringWidget(
label=_("Email Address"),
),
),
StringField('BusinessPhone',
schemata = 'Email Telephone Fax',
widget = StringWidget(
label=_("Phone (business)"),
),
),
StringField('BusinessFax',
schemata = 'Email Telephone Fax',
widget = StringWidget(
label=_("Fax (business)"),
),
),
StringField('HomePhone',
schemata = 'Email Telephone Fax',
widget = StringWidget(
label=_("Phone (home)"),
),
),
StringField('MobilePhone',
schemata = 'Email Telephone Fax',
widget = StringWidget(
label=_("Phone (mobile)"),
),
),
StringField('JobTitle',
widget = StringWidget(
label=_("Job title"),
),
),
StringField('Department',
widget = StringWidget(
label=_("Department"),
),
),
AddressField('PhysicalAddress',
schemata = 'Address',
widget = AddressWidget(
label=_("Physical address"),
),
),
AddressField('PostalAddress',
schemata = 'Address',
widget = AddressWidget(
label=_("Postal address"),
),
),
),
)
class Person(BaseFolder):
security = ClassSecurityInfo()
displayContentsTab = False
schema = schema
security.declareProtected(CMFCorePermissions.View, 'getSchema')
def getSchema(self):
return self.schema
def getPossibleAddresses(self):
return ['PhysicalAddress', 'PostalAddress']
def getFullname(self):
""" return Person's Fullname """
fn = self.getFirstname()
mi = self.getMiddleinitial()
md = self.getMiddlename()
sn = self.getSurname()
fullname = ''
if fn or sn:
if mi and md:
fullname = '%s %s %s %s' % (self.getFirstname(),
self.getMiddleinitial(),
self.getMiddlename(),
self.getSurname())
elif mi:
fullname = '%s %s %s' % (self.getFirstname(),
self.getMiddleinitial(),
self.getSurname())
elif md:
fullname = '%s %s %s' % (self.getFirstname(),
self.getMiddlename(),
self.getSurname())
else:
fullname = '%s %s' % (self.getFirstname(), self.getSurname())
return fullname.strip()
def getListingname(self):
""" return Person's Fullname as Surname, Firstname """
fn = self.getFirstname()
mi = self.getMiddleinitial()
md = self.getMiddlename()
sn = self.getSurname()
fullname = ''
if fn and sn:
fullname = '%s, %s' % (self.getSurname(), self.getFirstname())
elif fn or sn:
fullname = '%s %s' % (self.getSurname(), self.getFirstname())
else:
fullname = ''
if fullname != '':
if mi and md:
fullname = '%s %s %s' % (fullname, self.getMiddleinitial(),
self.getMiddlename())
elif mi:
fullname = '%s %s' % (fullname, self.getMiddleinitial())
elif md:
fullname = '%s %s' % (fullname, self.getMiddlename())
return fullname.strip()
Title = getFullname
security.declareProtected(CMFCorePermissions.ManagePortal, 'hasUser')
def hasUser(self):
""" check if contact has user """
return self.portal_membership.getMemberById(
self.getUsername()) is not None
### Removed these accessors to prevent confusion when LDAP is used
# def getEmailAddress(self, **kw):
# """ Return the email address stored in member data if the
# person is a Plone user, else return the one stored on the
# person.
# """
# member = self.portal_membership.getMemberById(self.getUsername())
# if member:
# return member.getProperty('email')
# else:
# return self.Schema()['EmailAddress'].get(self)
# def setEmailAddress(self, value, **kw):
# """ Set email in member data if the person is a Plone user, else
# store it on the Person instance.
# """
# self.Schema()['EmailAddress'].set(self, value, **kw)
# username = self.getUsername()
# if username:
# member = self.portal_membership.getMemberById(username)
# if member:
# member.setMemberProperties({'email': value})
registerType(Person, PROJECTNAME)
| {'content_hash': 'fcf2aa41708e8e78ce10b8fce2cc63eb', 'timestamp': '', 'source': 'github', 'line_count': 207, 'max_line_length': 77, 'avg_line_length': 32.29951690821256, 'alnum_prop': 0.537989829494466, 'repo_name': 'hocinebendou/bika.gsoc', 'id': '82c70f04b5fc878e5d90b318df80f502592480a2', 'size': '6686', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'bika/lims/content/person.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '403'}, {'name': 'COBOL', 'bytes': '5987'}, {'name': 'CSS', 'bytes': '29758'}, {'name': 'JavaScript', 'bytes': '411425'}, {'name': 'Python', 'bytes': '4330980'}, {'name': 'RobotFramework', 'bytes': '239735'}, {'name': 'Shell', 'bytes': '11201'}]} |
static void* my_thread_entry(void * param){
unsigned* ret = (unsigned*)malloc(sizeof(unsigned));
*ret = 1;
if (param == NULL) return ret;
IRunnable* r = (IRunnable*)param;
try{
*ret = (unsigned)r->svc();
} catch (std::exception& ex){
MYERROR("thread exited,%s", ex.what());
} catch (const char* msg){
MYERROR("thread exited,%s", msg);
} catch (...){
MYERROR("thread exited with unknown error");
}
return ret;
}
PosixThread::PosixThread(std::shared_ptr<IRunnable> r):runnable_(r),state(INIT){
pthread_attr_init(&attr);
}
PosixThread::~PosixThread()
{
}
void PosixThread::run(){
if(state!=INIT) return;
int err=pthread_create(&threadID, &attr, my_thread_entry, runnable_.get());
if(err)
return;
state=RUNNING;
}
unsigned PosixThread::wait(){
if(state!=RUNNING) return 1;
void *res;
int joinret = pthread_join(threadID, &res);
if (joinret)
throw std::runtime_error("pthread_join error");
unsigned int ret = *(unsigned*)res;
free(res);
state=DEAD;
return ret;
}
| {'content_hash': 'aa2765406d79b9eaf4fbbe809f361d76', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 80, 'avg_line_length': 22.5, 'alnum_prop': 0.642512077294686, 'repo_name': 'chenbaihu/proxy', 'id': '7041ad644afe992e5a69d074e9f42b836ab26ee8', 'size': '1145', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/PosixThread.cpp', 'mode': '33188', 'license': 'bsd-2-clause', 'language': []} |
package org.apache.hadoop.mapred;
import java.io.IOException;
import java.io.InputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.*;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.CompressionCodecFactory;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import org.apache.hadoop.mapreduce.security.TokenCache;
import org.apache.hadoop.net.NetworkTopology;
import org.apache.hadoop.net.Node;
import org.apache.hadoop.net.NodeBase;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.StringUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.hadoop.io.NetCDFArrayWritable;
import java.util.List;
import ucar.nc2.*;
import ucar.nc2.iosp.*;
import ucar.nc2.iosp.netcdf3.*;
import ucar.unidata.io.*;
import ucar.nc2.dataset.*;
import ucar.ma2.Array;
import ucar.ma2.ArrayFloat;
import java.util.Arrays;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.NetCDFReaderWithMeta;
/**
* Treats keys as offset in fil`e and value as line.
*/
public class NetCDFInputFormatPartToMemoryNoMultiSplit extends FileInputFormat<Text, NetCDFArrayWritable> {
private static final Log LOG
= LogFactory.getLog(NetCDFInputFormatPartToMemoryNoMultiSplit.class.getName());
public static final String HIVE_QUERY = "hadoop.netcdf.hivequery.raw";
public enum QueryType { TIME, LAT, LON, NOLIMIT }
private NetCDFInfo getNetCDFInfo(Path file, FileSystem fs, JobConf job)
{
//traverse header and return chunk start and size arrays
NetCDFInfo result = new NetCDFInfo();//library call
NetcdfFile ncFile;
Variable v;
Variable time;
Variable lat;
Variable lon;
ncFile = null;
try {
//if( file == null ){
//System.out.println( "[SAMAN] NetCDFInputFormat.getNetCDFInfo file is null" );
//LOG.info( "[SAMAN] NetCDFInputFormat.getNetCDFInfo file is null" );
//}else{
//System.out.println( "[SAMAN] NetCDFInputFormat.getNetCDFInfo file is " + file.toString() );
//LOG.info( "[SAMAN] NetCDFInputFormat.getNetCDFInfo file is null" );
//}
ncFile = NetcdfDataset.openFile(file.toString(), null);
v = ncFile.findVariable("rsut");
time = ncFile.findVariable("time");
lat = ncFile.findVariable("lat");
lon = ncFile.findVariable("lon");
//List<Variable> vs = ncFile.getVariables();
//v = vs.get(vs.size()-1);
//LOG.info("Variable is "+ v.getFullName());
result.fileSize = ncFile.vfileSize;
result.recStart = ncFile.vrecStart;
Long[] metaArray = v.reallyReadMeta().toArray(new Long[(int)(ncFile.vnumRecs)]);
result.chunkStarts =ArrayUtils.toPrimitive(metaArray);
//result.chunkSizes = nc.chunkSizes;
result.numRecs = ncFile.vnumRecs;
result.recSize = ncFile.vrecSize;
result.smallRecSize = ncFile.vsmallRecSize;
result.timeLength = (int)(time.getSize());
result.latLength = (int)(lat.getSize());
result.lonLength = (int)(lon.getSize());
//result.shape = v.shape;
} catch (Exception e)
{
LOG.info( "Bad... "+ e );
System.out.println("Bad... "+ e);
}
try{if (ncFile!=null)ncFile.close();}catch (Exception e) { LOG.info( "Bad2... "+e ); System.out.println("Bad2... "+e);}
return result;
}
@Override
public InputSplit[] getSplits(JobConf job, int numSplits)
throws IOException {
FileStatus[] files = listStatus(job);
//LOG.info("[SAMAN][NetCDFInputFormatPruner][getSplits] hive query is: " + job.get(HIVE_QUERY, "Kossher"));
System.out.println("[SAMAN][NetCDFInputFormatPartToMemoryNoMultiSplit][getSplits] hive query is: " + job.get(HIVE_QUERY, "Kossher"));
/* Analyzing Query here */
String hiveQuery = job.get(HIVE_QUERY, "Kossher");
QueryType queryType = QueryType.NOLIMIT; // default mode
if(hiveQuery.contains("where") || hiveQuery.contains("WHERE")) {
if (hiveQuery.contains("time") || hiveQuery.contains("TIME")) {
queryType = QueryType.TIME;
} else if (hiveQuery.contains("lat") || hiveQuery.contains("LAT")) {
queryType = QueryType.LAT;
} else if (hiveQuery.contains("lon") || hiveQuery.contains("LON")) {
queryType = QueryType.LON;
}
}
float topLimit = -1;
float bottomLimit = -1;
if( queryType != QueryType.NOLIMIT ) {
if (hiveQuery.contains("<")) {
String[] querySplitted = hiveQuery.split(" ");
int i = Arrays.asList(querySplitted).indexOf("<");
topLimit = Float.valueOf(querySplitted[i+1]);
}
if (hiveQuery.contains(">")) {
String[] querySplitted = hiveQuery.split(" ");
int i = Arrays.asList(querySplitted).indexOf(">");
bottomLimit = Float.valueOf(querySplitted[i+1]);
}
}
//System.out.println( "[SAMAN][NetCDFInputFormatPruner] QueryType = " + queryType.toString()
// +", topLimit = " + topLimit + ", bottomLimit = " + bottomLimit );
//LOG.info("[SAMAN][NetCDFInputFormatPruner] QueryType = " + queryType.toString()
// + ", topLimit = " + topLimit + ", bottomLimit = " + bottomLimit);
/* End Analyzing Query here */
//System.out.println( "[SAMANPruner] beginning of getSplits" );
//LOG.info( "[SAMANPruner] beginning of getSplits" );
//System.out.println( "[SAMAN] " + files.length );
//LOG.info( "[SAMAN] " + files.length );
// Save the number of input files in the job-conf
job.setLong(NUM_INPUT_FILES, files.length);
long totalSize = 0; // compute total size
for (FileStatus file: files) { // check we have valid files
if (file.isDir()) {
throw new IOException("Not a file: " + file.getPath());
}
totalSize += file.getLen();
}
//long minSize = Math.max(job.getLong("mapred.min.split.size", 1),
// minSplitSize);
// generate splits
ArrayList<FileSplit> splits = new ArrayList<FileSplit>(numSplits);
NetworkTopology clusterMap = new NetworkTopology();
for (FileStatus file: files) {
Path path = file.getPath();
/*
if( queryType == QueryType.TIME || queryType == QueryType.NOLIMIT){
if( path.getName().contains("lat") || path.getName().contains("lon") )
continue;
}else if( queryType == QueryType.LAT ){
if( !path.getName().contains("lat") )
continue;
}else if( queryType == QueryType.LON ){
if( !path.getName().contains("lon") )
continue;
}
*/
LOG.info("[SAMAN][NetCDFInputFormatPruner][getSplits] File name is : " + path.getName());
System.out.println("[SAMAN][NetCDFInputFormatPruner][getSplits] File name is : " + path.getName());
FileSystem fs = path.getFileSystem(job);
long length = file.getLen();
BlockLocation[] blkLocations = fs.getFileBlockLocations(file, 0, length);
if ((length != 0) && isSplitable(fs, path)) {
long blockSize = file.getBlockSize();
NetCDFInfo netInfo = getNetCDFInfo(path, fs, job);
long recStart = netInfo.recStart;
long[] chunkStarts = netInfo.chunkStarts;
long smallSize = netInfo.smallRecSize;
long recSize = netInfo.recSize;
long splitSize = 0;
int chunkIndex = 0;
long bytesRemaining = chunkStarts[chunkStarts.length-1] + recSize - recStart - 2*smallSize;
long thisStart = recStart; // file position
long thisChunk = 0;
long blockNo = 1;
//LOG.info( "[SAMAN] NetCDFInputFormatPruner.getSplits => recStart = " + recStart + ", chunkStarts = " + chunkStarts +
// ", smallSize = " + smallSize + ", recSize = " + recSize + ", bytesRemaining = " + bytesRemaining +
// ", thisStart = " + thisStart);
//System.out.println( "[SAMAN] NetCDFInputFormatPruner.getSplits => recStart = " + recStart + ", chunkStarts = " + chunkStarts +
// ", smallSize = " + smallSize + ", recSize = " + recSize + ", bytesRemaining = " + bytesRemaining +
// ", thisStart = " + thisStart);
while ( bytesRemaining > 0) {
while ( chunkIndex < chunkStarts.length && chunkStarts[chunkIndex] < blockNo * blockSize ) {
chunkIndex++;
}
long tempStart = thisStart;
long endChunk;
if (chunkIndex >= chunkStarts.length) {
splitSize = chunkStarts[chunkStarts.length-1] + recSize - thisStart - smallSize;
//bytesRemaining should be 0 after this round
}
else {
splitSize = chunkStarts[chunkIndex] - thisStart - smallSize;
thisStart = chunkStarts[chunkIndex];
}
endChunk = chunkIndex;
blockNo++;
//LOG.info( "[SAMAN] NetCDFInputFormatPruner.getSplits => splitSize="+splitSize+", thisStart="+thisStart+
// ", endChunk="+endChunk+", blockNo="+blockNo);
//System.out.println( "[SAMAN] NetCDFInputFormatPruner.getSplits => splitSize="+splitSize+", thisStart="+thisStart+
// ", endChunk="+endChunk+", blockNo="+blockNo);
String[] splitHosts = getSplitHosts(blkLocations, tempStart, splitSize, clusterMap);
FileSplit split = new FileSplit(path, tempStart, splitSize, splitHosts);
split.getFileSplit().startChunk = thisChunk;
split.getFileSplit().endChunk = endChunk;
if( queryType == QueryType.TIME ){
split.getFileSplit().timeStartLimit = (long)bottomLimit;
split.getFileSplit().timeEndLimit = (long)topLimit;
split.getFileSplit().latStartLimit = -1;
split.getFileSplit().latEndLimit = -1;
split.getFileSplit().lonStartLimit = -1;
split.getFileSplit().lonEndLimit = -1;
}else if( queryType == QueryType.LAT ){
split.getFileSplit().timeStartLimit = -1;
split.getFileSplit().timeEndLimit = -1;
split.getFileSplit().latStartLimit = (long)bottomLimit;
split.getFileSplit().latEndLimit = (long)topLimit;
split.getFileSplit().lonStartLimit = -1;
split.getFileSplit().lonEndLimit = -1;
}else if( queryType == QueryType.LON ){
split.getFileSplit().timeStartLimit = -1;
split.getFileSplit().timeEndLimit = -1;
split.getFileSplit().latStartLimit = -1;
split.getFileSplit().latEndLimit = -1;
split.getFileSplit().lonStartLimit = (long)bottomLimit;
split.getFileSplit().lonEndLimit = (long)topLimit;
}
/*
if( (topLimit < thisChunk) && (topLimit != -1)) {
bytesRemaining -= splitSize;
thisChunk = endChunk;
continue;
}
if( (bottomLimit > endChunk) && (bottomLimit != -1) ) {
bytesRemaining -= splitSize;
thisChunk = endChunk;
continue;
}
*/
splits.add(split);
bytesRemaining -= splitSize;
thisChunk = endChunk;
//LOG.info( "[SAMAN] NetCDFInputFormatPruner.getSplits => bytesRemaining="+bytesRemaining+", thisChunk="+thisChunk );
//System.out.println( "[SAMAN] NetCDFInputFormatPruner.getSplits => bytesRemaining="+bytesRemaining+", thisChunk="+thisChunk );
}
} else if (length != 0) {
String[] splitHosts = getSplitHosts(blkLocations,0,length,clusterMap);
splits.add(new FileSplit(path, 0, length, splitHosts));
} else {
//Create empty hosts array for zero length files
splits.add(new FileSplit(path, 0, length, new String[0]));
}
}
return splits.toArray(new FileSplit[splits.size()]);
}
@Override
public RecordReader<Text, NetCDFArrayWritable> getRecordReader(
InputSplit genericSplit, JobConf job,
Reporter reporter)
throws IOException {
reporter.setStatus(genericSplit.toString());
//LOG.info( "[SAMAN] return getRecordReader" );
//System.out.println( "[SAMAN] return getRecordReader" );
return new NetCDFReaderWithMetaPartToMemoryNoMultiSplit(job, (FileSplit) genericSplit);
}
}
| {'content_hash': '258e9fdcfb0d9fdec1498b34808923c1', 'timestamp': '', 'source': 'github', 'line_count': 319, 'max_line_length': 147, 'avg_line_length': 46.73040752351097, 'alnum_prop': 0.5697323405111693, 'repo_name': 'saman-aghazadeh/hadoop-2.5.2-netcdf', 'id': '6fa56829ab96f787e34cb7a2cdfea8af0461691b', 'size': '15713', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/NetCDFInputFormatPartToMemoryNoMultiSplit.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AspectJ', 'bytes': '31146'}, {'name': 'Batchfile', 'bytes': '60698'}, {'name': 'C', 'bytes': '1132512'}, {'name': 'C++', 'bytes': '83915'}, {'name': 'CMake', 'bytes': '33672'}, {'name': 'CSS', 'bytes': '43086'}, {'name': 'HTML', 'bytes': '146191'}, {'name': 'Java', 'bytes': '42738526'}, {'name': 'JavaScript', 'bytes': '22405'}, {'name': 'Perl', 'bytes': '18992'}, {'name': 'Protocol Buffer', 'bytes': '196305'}, {'name': 'Python', 'bytes': '11309'}, {'name': 'Shell', 'bytes': '169162'}, {'name': 'TeX', 'bytes': '19322'}, {'name': 'XSLT', 'bytes': '34239'}]} |
package com.github.gv2011.helloworld.impl;
/*-
* %---license-start---
* helloworld-impl
* %
* Copyright (C) 2014 - 2017 Vinz (https://github.com/gv2011)
* %
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* %---license-end---
*/
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.gv2011.helloworld.Greeting;
import com.github.gv2011.helloworld.GreetingService;
public class GreetingServiceImpl implements GreetingService{
private static final Logger LOG = LoggerFactory.getLogger(GreetingServiceImpl.class);
private final ExecutorService executor = Executors.newCachedThreadPool();
final Map<GreetingType,String> greetingTexts;
public GreetingServiceImpl() {
Map<GreetingType,String> greetingTexts = new EnumMap<>(GreetingType.class);
greetingTexts.put(GreetingType.HELLO, "Hello world!");
greetingTexts.put(GreetingType.GOODBYE, "Goodbye, world!");
this.greetingTexts = Collections.unmodifiableMap(greetingTexts);
LOG.info("Created {}.", this);
}
@Override
public Greeting getGreeting(GreetingType greetingType) {
Future<Greeting> result = executor.submit(()->createGreeting(greetingType));
try {
return result.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
private Greeting createGreeting(GreetingType greetingType) throws InterruptedException{
String text = getText(greetingType);
GreetingImpl greeting = new GreetingImpl(text);
LOG.info("Created greeting of type {}.", greetingType);
return greeting;
}
private String getText(GreetingType greetingType) {
return greetingTexts.get(greetingType);
}
@Override
public void close() throws Exception {
LOG.info("Closing {}.", this);
executor.shutdown();
final int timeout = 1;
while(!executor.awaitTermination(timeout, TimeUnit.SECONDS)){
LOG.warn("Executor of {} did not shutdown after {} second, forcing shutdown.", this, timeout);
executor.shutdownNow();
};
LOG.info("Closed {}.", this);
}
}
| {'content_hash': '1a00fc9af94887cff1b03d43a526a4a4', 'timestamp': '', 'source': 'github', 'line_count': 96, 'max_line_length': 97, 'avg_line_length': 35.614583333333336, 'alnum_prop': 0.7361801696402457, 'repo_name': 'gv2011/helloworld', 'id': '31c06f1a9c73fc9f52d6aacbd5596fb1a6b1ef81', 'size': '4631', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'impl/src/main/java/com/github/gv2011/helloworld/impl/GreetingServiceImpl.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'FreeMarker', 'bytes': '105'}, {'name': 'Java', 'bytes': '31721'}]} |
package org.sagebionetworks.repo.manager;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.sagebionetworks.repo.manager.dataaccess.AccessApprovalManager;
import org.sagebionetworks.repo.manager.entity.EntityAuthorizationManager;
import org.sagebionetworks.repo.manager.file.FileHandleAuthorizationManager;
import org.sagebionetworks.repo.model.ACCESS_TYPE;
import org.sagebionetworks.repo.model.AccessControlListDAO;
import org.sagebionetworks.repo.model.AuthorizationConstants.ACL_SCHEME;
import org.sagebionetworks.repo.model.ConflictingUpdateException;
import org.sagebionetworks.repo.model.DatastoreException;
import org.sagebionetworks.repo.model.EntityType;
import org.sagebionetworks.repo.model.InvalidModelException;
import org.sagebionetworks.repo.model.Node;
import org.sagebionetworks.repo.model.NodeDAO;
import org.sagebionetworks.repo.model.UnauthorizedException;
import org.sagebionetworks.repo.model.UserGroup;
import org.sagebionetworks.repo.model.UserInfo;
import org.sagebionetworks.repo.model.annotation.v2.Annotations;
import org.sagebionetworks.repo.model.auth.AuthorizationStatus;
import org.sagebionetworks.repo.model.bootstrap.EntityBootstrapper;
import org.sagebionetworks.repo.web.NotFoundException;
/**
* Validate that authorization checks are in place.
*
*/
@RunWith(MockitoJUnitRunner.class)
public class NodeManagerAuthorizationTest {
@Mock
private NodeDAO mockNodeDao;
@Mock
private EntityAuthorizationManager mockAuthDao;
@Mock
private AccessControlListDAO mockAclDao;
@Mock
private Node mockNode;
@Mock
private Annotations mockUserAnnotations;
@Mock
private org.sagebionetworks.repo.model.Annotations mockEntityPropertyAnnotations;
@Mock
private UserGroup mockUserGroup;
@Mock
private UserInfo mockUserInfo;
@Mock
private EntityBootstrapper mockEntityBootstrapper;
@Mock
private ActivityManager mockActivityManager;
@Mock
private ProjectSettingsManager mockProjectSettingsManager;
@Mock
private FileHandleAuthorizationManager mockfilehandleAuthorizationManager;
@Mock
private AccessApprovalManager mockAccessApprovalManager;
@Mock
private AccessControlListManager mockAclManager;
@InjectMocks
private NodeManagerImpl nodeManager;
@Before
public void before() throws NotFoundException, DatastoreException{
String startEtag = "startEtag";
// The mocks user for tests
when(mockNode.getNodeType()).thenReturn(EntityType.project);
when(mockNode.getName()).thenReturn("BobTheNode");
when(mockNode.getETag()).thenReturn(startEtag);
when(mockUserAnnotations.getEtag()).thenReturn(startEtag);
when(mockNode.getParentId()).thenReturn("syn456");
// UserGroup
when(mockUserGroup.getId()).thenReturn("123");
mockUserInfo = new UserInfo(false, 123L);
when(mockNodeDao.lockNode(any(String.class))).thenReturn(startEtag);
when(mockNodeDao.isNodeAvailable(any(String.class))).thenReturn(true);
}
@Test (expected=UnauthorizedException.class)
public void testUnauthorizedCreateNewNode() throws DatastoreException, InvalidModelException, NotFoundException, UnauthorizedException{
when(mockAuthDao.canCreate(mockNode.getParentId(), mockNode.getNodeType(), mockUserInfo)).thenReturn(AuthorizationStatus.accessDenied(""));
// Should fail
nodeManager.createNewNode(mockNode, mockUserInfo);
}
@Test (expected=UnauthorizedException.class)
public void testUnauthorizedCreateNewNodeFileHandle() throws DatastoreException, InvalidModelException, NotFoundException, UnauthorizedException{
// The user is allowed to create the file handle but not allowed to use the file handle.
String fileHandleId = "123456";
when(mockAuthDao.canCreate(mockNode.getParentId(), mockNode.getNodeType(), mockUserInfo)).thenReturn(AuthorizationStatus.authorized());
when(mockfilehandleAuthorizationManager.canAccessRawFileHandleById(mockUserInfo, fileHandleId)).thenReturn(AuthorizationStatus.accessDenied(""));
when(mockNode.getFileHandleId()).thenReturn(fileHandleId);
// Should fail
nodeManager.createNewNode(mockNode, mockUserInfo);
}
@Test
public void testAuthorizedCreateNewNodeFileHandle() throws DatastoreException, InvalidModelException, NotFoundException, UnauthorizedException{
// The user is allowed to create the file handle but not allowed to use the file handle.
String fileHandleId = "123456";
when(mockAuthDao.canCreate(mockNode.getParentId(), mockNode.getNodeType(), mockUserInfo)).thenReturn(AuthorizationStatus.authorized());
when(mockfilehandleAuthorizationManager.canAccessRawFileHandleById(mockUserInfo, fileHandleId)).thenReturn(AuthorizationStatus.authorized());
when(mockNode.getFileHandleId()).thenReturn(fileHandleId);
when(mockEntityBootstrapper.getChildAclSchemeForPath(any(String.class))).thenReturn(ACL_SCHEME.INHERIT_FROM_PARENT);
when(mockNodeDao.createNewNode(mockNode)).thenReturn(mockNode);
// Should fail
nodeManager.createNewNode(mockNode, mockUserInfo);
verify(mockNodeDao).createNewNode(mockNode);
}
/**
* Test the case where the user has update permission on the node but they did not create the file handle so they cannot
* assign it to the node.
* @throws DatastoreException
* @throws NotFoundException
*/
@Test
public void testUnauthorizedUpdateNodeFileHandle() throws DatastoreException, NotFoundException{
String fileHandleId = "123456";
String oldFileHandleId = "9876";
String parentId = "123";
String nodeId = "456";
when(mockNode.getId()).thenReturn(nodeId);
// The user can update the node.
when(mockAuthDao.hasAccess(mockUserInfo, nodeId, ACCESS_TYPE.UPDATE)).thenReturn(AuthorizationStatus.authorized());
// The old file handle does not match the new file handle.
when(mockNodeDao.getFileHandleIdForVersion(mockNode.getId(), null)).thenReturn(oldFileHandleId);
// The user did not create the file handle.
when(mockfilehandleAuthorizationManager.canAccessRawFileHandleById(mockUserInfo, fileHandleId)).thenReturn(
AuthorizationStatus.accessDenied(mockUserInfo.getId().toString()+" cannot access "+fileHandleId));
when(mockNode.getFileHandleId()).thenReturn(fileHandleId);
when(mockNode.getParentId()).thenReturn(parentId);
when(mockAccessApprovalManager.canUserMoveRestrictedEntity(eq(mockUserInfo), eq(parentId), eq(parentId))).thenReturn(AuthorizationStatus.authorized());
Node oldMockNode = mock(Node.class);
when(oldMockNode.getParentId()).thenReturn(parentId);
when(mockNodeDao.getNode(nodeId)).thenReturn(oldMockNode);
// Should fail
try{
nodeManager.update(mockUserInfo, mockNode, null, false);
fail("Should have failed");
}catch(UnauthorizedException e){
assertTrue("The exception message should contain the file handle id: "+e.getMessage(), e.getMessage().contains(fileHandleId));
assertTrue("The exception message should contain the user's id: "+e.getMessage(), e.getMessage().contains(mockUserInfo.getId().toString()));
}
}
/**
* Test the case where the user has update permission on a node that already had an file handle.
* In this case the file handle currently on the node was created by someone else so the current user would not
* be able to set it. However, since the file handle is not changing, the user should be allowed to proceed with the update.
* @throws DatastoreException
* @throws NotFoundException
*/
@Test
public void testAuthorizedUpdateNodeFileHandleNotChanged() throws DatastoreException, NotFoundException{
String parentId = "123";
String nodeId = "456";
when(mockNode.getId()).thenReturn(nodeId);
String fileHandleId = "123456";
// The user can update the node.
when(mockAuthDao.hasAccess(mockUserInfo, mockNode.getId(), ACCESS_TYPE.UPDATE)).thenReturn(AuthorizationStatus.authorized());
when(mockAuthDao.hasAccess(mockUserInfo, mockNode.getId(), ACCESS_TYPE.READ)).thenReturn(AuthorizationStatus.authorized());
// The file handle was already set on this node so it is not changing with this update.
when(mockNodeDao.getFileHandleIdForVersion(mockNode.getId(), null)).thenReturn(fileHandleId);
// If the user were to set this file handle it would fail as they are not the creator of the file handle.
when(mockfilehandleAuthorizationManager.canAccessRawFileHandleById(mockUserInfo, fileHandleId)).thenReturn(AuthorizationStatus.accessDenied(""));
when(mockNode.getFileHandleId()).thenReturn(fileHandleId);
when(mockNode.getParentId()).thenReturn(parentId);
when(mockAccessApprovalManager.canUserMoveRestrictedEntity(eq(mockUserInfo), eq(parentId), eq(parentId))).thenReturn(AuthorizationStatus.authorized());
Node oldMockNode = mock(Node.class);
when(oldMockNode.getParentId()).thenReturn(parentId);
when(mockNodeDao.getNode(nodeId)).thenReturn(oldMockNode);
// Should fail
nodeManager.update(mockUserInfo, mockNode, null, false);
// The change should make it to the dao
verify(mockNodeDao).updateNode(mockNode);
}
/**
* For this case the user has update permission on the node. This update is changing the file handle
* and the user has permission to use the new file handle, so the update should succeed.
* @throws DatastoreException
* @throws NotFoundException
*/
@Test
public void testAuthorizedUpdateNodeFileHandleChanged() throws DatastoreException, NotFoundException{
String fileHandleId = "123456";
String oldFileHandleId = "9876";
String parentId = "123";
String nodeId = "456";
when(mockNode.getId()).thenReturn(nodeId);
// The user can update the node.
when(mockAuthDao.hasAccess(mockUserInfo, mockNode.getId(), ACCESS_TYPE.UPDATE)).thenReturn(AuthorizationStatus.authorized());
when(mockAuthDao.hasAccess(mockUserInfo, mockNode.getId(), ACCESS_TYPE.READ)).thenReturn(AuthorizationStatus.authorized());
// The current file handle on the node does not match the new handle.
when(mockNodeDao.getFileHandleIdForVersion(mockNode.getId(), null)).thenReturn(oldFileHandleId);
// The user can access the new file handle.
when(mockfilehandleAuthorizationManager.canAccessRawFileHandleById(mockUserInfo, fileHandleId)).thenReturn(AuthorizationStatus.authorized());
when(mockNode.getFileHandleId()).thenReturn(fileHandleId);
when(mockNode.getParentId()).thenReturn(parentId);
when(mockAccessApprovalManager.canUserMoveRestrictedEntity(eq(mockUserInfo), eq(parentId), eq(parentId))).thenReturn(AuthorizationStatus.authorized());
Node oldMockNode = mock(Node.class);
when(oldMockNode.getParentId()).thenReturn(parentId);
when(mockNodeDao.getNode(nodeId)).thenReturn(oldMockNode);
// Should fail
nodeManager.update(mockUserInfo, mockNode, null, false);
// The change should make it to the dao
verify(mockNodeDao).updateNode(mockNode);
}
/**
* For this case the user has read access on the node but not download access.
*
* @throws DatastoreException
* @throws NotFoundException
*/
@Test (expected=UnauthorizedException.class)
public void testUnauthorizedGetFileHandle1() throws DatastoreException, NotFoundException{
// The user has access to read the node
when(mockAuthDao.hasAccess(mockUserInfo, mockNode.getId(), ACCESS_TYPE.READ)).thenReturn(AuthorizationStatus.authorized());
// The user does not have permission to dowload the file
when(mockAuthDao.hasAccess(mockUserInfo, mockNode.getId(), ACCESS_TYPE.DOWNLOAD)).thenReturn(AuthorizationStatus.accessDenied(""));
nodeManager.getFileHandleIdForVersion(mockUserInfo, mockNode.getId(), null);
}
/**
* Not found when there is not file handle id.
*
* @throws DatastoreException
* @throws NotFoundException
*/
@Test (expected=NotFoundException.class)
public void testNotFoundGetFileHandle() throws DatastoreException, NotFoundException{
when(mockAuthDao.hasAccess(mockUserInfo, mockNode.getId(), ACCESS_TYPE.READ)).thenReturn(AuthorizationStatus.authorized());
when(mockAuthDao.hasAccess(mockUserInfo, mockNode.getId(), ACCESS_TYPE.DOWNLOAD)).thenReturn(AuthorizationStatus.authorized());
when(mockNodeDao.getFileHandleIdForVersion(mockNode.getId(), null)).thenReturn(null);
nodeManager.getFileHandleIdForVersion(mockUserInfo, mockNode.getId(), null);
}
@Test
public void testGetFileHandleIdForCurrentVersion() throws DatastoreException, NotFoundException{
when(mockAuthDao.hasAccess(mockUserInfo, mockNode.getId(), ACCESS_TYPE.READ)).thenReturn(AuthorizationStatus.authorized());
when(mockAuthDao.hasAccess(mockUserInfo, mockNode.getId(), ACCESS_TYPE.DOWNLOAD)).thenReturn(AuthorizationStatus.authorized());
String expectedFileHandleId = "999999";
when(mockNodeDao.getFileHandleIdForVersion(mockNode.getId(), null)).thenReturn(expectedFileHandleId);
String handleId = nodeManager.getFileHandleIdForVersion(mockUserInfo, mockNode.getId(), null);
assertEquals(expectedFileHandleId, handleId);
}
/**
* For this case the user has download access to the node but not read.
*
* @throws DatastoreException
* @throws NotFoundException
*/
@Test (expected=UnauthorizedException.class)
public void testUnauthorizedGetFileHandle2() throws DatastoreException, NotFoundException{
// The user does not have access to read the node
when(mockAuthDao.hasAccess(mockUserInfo, mockNode.getId(), ACCESS_TYPE.READ)).thenReturn(AuthorizationStatus.accessDenied(""));
// The user does have permission to dowload the file
when(mockAuthDao.hasAccess(mockUserInfo, mockNode.getId(), ACCESS_TYPE.DOWNLOAD)).thenReturn(AuthorizationStatus.accessDenied(""));
nodeManager.getFileHandleIdForVersion(mockUserInfo, mockNode.getId(), null);
}
@Test (expected=UnauthorizedException.class)
public void testUnauthorizedDeleteNode() throws DatastoreException, InvalidModelException, NotFoundException, UnauthorizedException{
String id = "22";
when(mockAuthDao.hasAccess(mockUserInfo, id, ACCESS_TYPE.DELETE)).thenReturn(AuthorizationStatus.accessDenied(""));
// Should fail
nodeManager.delete(mockUserInfo, id);
}
@Test (expected=UnauthorizedException.class)
public void testUnauthorizedGetNode() throws DatastoreException, InvalidModelException, NotFoundException, UnauthorizedException{
String id = "22";
when(mockAuthDao.hasAccess(mockUserInfo, id, ACCESS_TYPE.READ)).thenReturn(AuthorizationStatus.accessDenied(""));
// Should fail
nodeManager.getNode(mockUserInfo, id);
}
@Test (expected=UnauthorizedException.class)
public void testUnauthorizedGetNodeForVersionNumber() throws DatastoreException, InvalidModelException, NotFoundException, UnauthorizedException{
String id = "22";
when(mockAuthDao.hasAccess(mockUserInfo, id, ACCESS_TYPE.READ)).thenReturn(AuthorizationStatus.accessDenied(""));
// Should fail
nodeManager.getNodeForVersionNumber(mockUserInfo, id, 1L);
}
@Test (expected=UnauthorizedException.class)
public void testUnauthorizedUpdate() throws DatastoreException, InvalidModelException, NotFoundException, UnauthorizedException, ConflictingUpdateException{
String id = "22";
when(mockNode.getId()).thenReturn(id);
when(mockAuthDao.hasAccess(mockUserInfo, id, ACCESS_TYPE.UPDATE)).thenReturn(AuthorizationStatus.accessDenied(""));
// Should fail
nodeManager.update(mockUserInfo, mockNode, null, false);
}
@Test (expected=UnauthorizedException.class)
public void testUnauthorizedUpdate2() throws DatastoreException, InvalidModelException, NotFoundException, UnauthorizedException, ConflictingUpdateException{
String id = "22";
when(mockNode.getId()).thenReturn(id);
when(mockAuthDao.hasAccess(mockUserInfo, id, ACCESS_TYPE.UPDATE)).thenReturn(AuthorizationStatus.accessDenied(""));
// Should fail
nodeManager.update(mockUserInfo, mockNode, mockEntityPropertyAnnotations, true);
}
@Test
public void testUnauthorizedUpdateDueToAccessRequirements() throws DatastoreException, InvalidModelException, NotFoundException, UnauthorizedException, ConflictingUpdateException{
String id = "22";
String parentId = "123";
when(mockNode.getId()).thenReturn(id);
when(mockAuthDao.hasAccess(mockUserInfo, id, ACCESS_TYPE.READ)).thenReturn(AuthorizationStatus.authorized());
when(mockAuthDao.hasAccess(mockUserInfo, id, ACCESS_TYPE.UPDATE)).thenReturn(AuthorizationStatus.authorized());
when(mockNode.getParentId()).thenReturn(parentId);
// can't move due to access restrictions
when(mockAccessApprovalManager.canUserMoveRestrictedEntity(eq(mockUserInfo), eq(parentId), eq(parentId))).thenReturn(AuthorizationStatus.authorized());
Node oldMockNode = mock(Node.class);
when(oldMockNode.getParentId()).thenReturn(parentId);
when(mockNodeDao.getNode(id)).thenReturn(oldMockNode);
// OK!
nodeManager.update(mockUserInfo, mockNode, null, true);
// can't move due to access restrictions
when(mockAccessApprovalManager.canUserMoveRestrictedEntity(eq(mockUserInfo), eq(parentId), eq(parentId))).thenReturn(AuthorizationStatus.accessDenied(""));
try {
// Should fail
nodeManager.update(mockUserInfo, mockNode, null, true);
fail("Excpected unauthorized exception");
} catch (UnauthorizedException e) {
// as expected
}
verify(mockAccessApprovalManager, times(2)).canUserMoveRestrictedEntity(eq(mockUserInfo), eq(parentId), eq(parentId));
}
@Test
public void testUnauthorizedUpdateDueToAliasChange() throws DatastoreException, InvalidModelException, NotFoundException,
UnauthorizedException, ConflictingUpdateException {
String id = "22";
String parentId = "123";
when(mockNode.getId()).thenReturn(id);
when(mockAuthDao.hasAccess(mockUserInfo, id, ACCESS_TYPE.READ)).thenReturn(AuthorizationStatus.authorized());
when(mockAuthDao.hasAccess(mockUserInfo, id, ACCESS_TYPE.UPDATE)).thenReturn(AuthorizationStatus.authorized());
when(mockNode.getParentId()).thenReturn(parentId);
// can't move due to access restrictions
when(mockAccessApprovalManager.canUserMoveRestrictedEntity(eq(mockUserInfo), eq(parentId), eq(parentId))).thenReturn(
AuthorizationStatus.authorized());
Node oldMockNode = mock(Node.class);
when(oldMockNode.getParentId()).thenReturn(parentId);
when(oldMockNode.getAlias()).thenReturn("alias2");
when(mockNodeDao.getNode(id)).thenReturn(oldMockNode);
when(mockAuthDao.hasAccess(mockUserInfo, id, ACCESS_TYPE.CHANGE_SETTINGS)).thenReturn(AuthorizationStatus.authorized());
// OK!
nodeManager.update(mockUserInfo, mockNode, null, true);
// can't change alias due to access restrictions
when(mockAuthDao.hasAccess(mockUserInfo, id, ACCESS_TYPE.CHANGE_SETTINGS)).thenReturn(AuthorizationStatus.accessDenied(""));
try {
// Should fail
nodeManager.update(mockUserInfo, mockNode, null, true);
fail("Expected unauthorized exception");
} catch (UnauthorizedException e) {
// as expected
}
verify(mockAuthDao, times(2)).hasAccess(mockUserInfo, id, ACCESS_TYPE.CHANGE_SETTINGS);
}
@Test (expected=UnauthorizedException.class)
public void testUnauthorizedGetUserAnnotations() throws DatastoreException, InvalidModelException, NotFoundException, UnauthorizedException, ConflictingUpdateException{
String id = "22";
when(mockAuthDao.hasAccess(mockUserInfo, id, ACCESS_TYPE.READ)).thenReturn(AuthorizationStatus.accessDenied(""));
// Should fail
nodeManager.getUserAnnotations(mockUserInfo, id);
}
@Test (expected=UnauthorizedException.class)
public void testUnauthorizedetGetUserAnnotationsForVersion() throws DatastoreException, InvalidModelException, NotFoundException, UnauthorizedException, ConflictingUpdateException{
String id = "22";
when(mockAuthDao.hasAccess(mockUserInfo, id, ACCESS_TYPE.READ)).thenReturn(AuthorizationStatus.accessDenied(""));
// Should fail
nodeManager.getUserAnnotationsForVersion(mockUserInfo, id, 2L);
}
@Test (expected=UnauthorizedException.class)
public void testUnauthorizedGetEntityPropertyAnnotations() throws DatastoreException, InvalidModelException, NotFoundException, UnauthorizedException, ConflictingUpdateException{
String id = "22";
when(mockAuthDao.hasAccess(mockUserInfo, id, ACCESS_TYPE.READ)).thenReturn(AuthorizationStatus.accessDenied(""));
// Should fail
nodeManager.getEntityPropertyAnnotations(mockUserInfo, id);
}
@Test (expected=UnauthorizedException.class)
public void testUnauthorizedetGetEntityPropertyAnnotationsForVersion() throws DatastoreException, InvalidModelException, NotFoundException, UnauthorizedException, ConflictingUpdateException{
String id = "22";
when(mockAuthDao.hasAccess(mockUserInfo, id, ACCESS_TYPE.READ)).thenReturn(AuthorizationStatus.accessDenied(""));
// Should fail
nodeManager.getEntityPropertyForVersion(mockUserInfo, id, 2L);
}
@Test (expected=UnauthorizedException.class)
public void testUnauthorizedetUpdateAnnotations() throws DatastoreException, InvalidModelException, NotFoundException, UnauthorizedException, ConflictingUpdateException{
String id = "22";
when(mockAuthDao.hasAccess(mockUserInfo, id, ACCESS_TYPE.UPDATE)).thenReturn(AuthorizationStatus.accessDenied(""));
// Should fail
nodeManager.updateUserAnnotations(mockUserInfo, id, mockUserAnnotations);
}
@Test (expected=UnauthorizedException.class)
public void testUnauthorizedetGetNodeType() throws DatastoreException, InvalidModelException, NotFoundException, UnauthorizedException, ConflictingUpdateException{
String id = "22";
when(mockAuthDao.hasAccess(mockUserInfo, id, ACCESS_TYPE.READ)).thenReturn(AuthorizationStatus.accessDenied(""));
// Should fail
nodeManager.getNodeType(mockUserInfo, id);
}
@Test (expected=UnauthorizedException.class)
public void testUnauthorizedetDeleteVersion() throws DatastoreException, InvalidModelException, NotFoundException, UnauthorizedException, ConflictingUpdateException{
String id = "22";
when(mockAuthDao.hasAccess(mockUserInfo, id, ACCESS_TYPE.DELETE)).thenReturn(AuthorizationStatus.accessDenied(""));
// Should fail
nodeManager.deleteVersion(mockUserInfo, id, 12L);
}
}
| {'content_hash': '9dbf35a854c642e2f5a30a2c46fd62ff', 'timestamp': '', 'source': 'github', 'line_count': 439, 'max_line_length': 191, 'avg_line_length': 51.735763097949885, 'alnum_prop': 0.7824498062698133, 'repo_name': 'Sage-Bionetworks/Synapse-Repository-Services', 'id': '498ad60d6d5ff2caecb0e859f2a1c305bf7f9882', 'size': '22712', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'services/repository-managers/src/test/java/org/sagebionetworks/repo/manager/NodeManagerAuthorizationTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '47960'}, {'name': 'Java', 'bytes': '21087205'}, {'name': 'Python', 'bytes': '2379'}, {'name': 'Rich Text Format', 'bytes': '31728'}, {'name': 'Roff', 'bytes': '54'}, {'name': 'Shell', 'bytes': '32205'}, {'name': 'Velocity Template Language', 'bytes': '3416'}]} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Cats.TemplateEditor.TemplateService;
namespace Cats.TemplateEditor
{
public class DocumentProcessorService:IDocumentProcessorService
{
public void UploadDocument(int templateType, string filepath)
{
if (!string.IsNullOrEmpty(filepath))
{
string virtualPath = AppendToFileName(templateType, Path.GetFileName(filepath));
using (Stream uploadStream = new FileStream(filepath, FileMode.Open))
{
using (var client = new TemplateManagerClient())
{
client.PutFile(new FileUploadMessage() { VirtualPath = virtualPath, DataStream = uploadStream }.VirtualPath, uploadStream);
}
}
}
}
public string DownloadDocument(ListView fileList)
{
var filePath = string.Empty;
ListViewItem item = fileList.SelectedItems[0];
// Strip off 'Root' from the full path
var path = item.SubItems[1].Text;
filePath = Properties.Settings.Default.DefaultPath.ToString() + path;
if (!string.IsNullOrEmpty(filePath))
{
// Get the file from the server
using (var output = new FileStream(filePath, FileMode.Create))
{
Stream downloadStream;
using (var client = new TemplateManagerClient())
{
downloadStream = client.GetFile(path);
}
downloadStream.CopyTo(output);
}
return filePath;
}
return string.Empty;
}
public void DeleteDocument(string path)
{
if (File.Exists(path))
{
File.Delete(path);
}
}
private static string AppendToFileName(int templateType, string fileName)
{
switch (templateType)
{
case 1:
if (fileName.StartsWith("TRANS-"))
return fileName;
return "TRANS-" + fileName;
case 2:
if (fileName.StartsWith("GIFT-"))
return fileName;
return "GIFT-" + fileName;
default:
return fileName;
}
}
}
}
| {'content_hash': '236a418fdb768d46037020fca325b758', 'timestamp': '', 'source': 'github', 'line_count': 97, 'max_line_length': 145, 'avg_line_length': 27.896907216494846, 'alnum_prop': 0.49741315594974134, 'repo_name': 'ndrmc/cats', 'id': 'd1ba1a66da5e60f0b03072c2b901846e13ce59a7', 'size': '2708', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Servers/Cats.TemplateEditor/DocumentProcessorService.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '23179'}, {'name': 'Batchfile', 'bytes': '220'}, {'name': 'C#', 'bytes': '17077194'}, {'name': 'CSS', 'bytes': '1272649'}, {'name': 'HTML', 'bytes': '1205906'}, {'name': 'JavaScript', 'bytes': '4300261'}, {'name': 'PLpgSQL', 'bytes': '10605'}, {'name': 'SQLPL', 'bytes': '11550'}, {'name': 'Smalltalk', 'bytes': '10'}]} |
from django.views.decorators.csrf import csrf_exempt
try:
from django.utils.functional import update_wrapper
except ImportError:
from functools import update_wrapper
from django.utils.cache import patch_vary_headers
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.importlib import import_module
from oauth.oauth import build_authenticate_header
import sys
def trim_indent(docstring):
"""
Helps in formatting document strings for display within the project's developers' section.
"""
if not docstring:
return ''
lines = docstring.expandtabs().splitlines()
indent = sys.maxint
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
trimmed = [lines[0].strip()]
if indent < sys.maxint:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
return '\n'.join(trimmed)
def form_initial_data(form_class, obj = None, **kwargs):
"""
Creates a dictionary of data to be passed as 'initial data' to a form.
"""
initial = {}
for (name, field) in form_class.base_fields.items():
initial[name] = field.prepare_value(getattr(obj, name, field.initial))
for (key, value) in kwargs.items():
if not '__' in key:
initial[key] = value
return initial
def wrap_api_function(site, view, detail_level, allowed_methods, processor, verbose_name = None):
"""
A decorator which wraps certain functions, so that a number of checks can be run before the function
is called (ie: checking that the HTTP method is allowed).
"""
def wrapper(request, format, *args, **kwargs):
if not request.method in allowed_methods:
return HttpResponse('')
response = site.api_view(
view, request, format, *args,
detail_level = detail_level + (request.method == 'POST' and 1 or 0),
processor = processor,
**kwargs
)
if isinstance(response, HttpResponse):
patch_vary_headers(response,
getattr(settings, 'API_CACHE_VARY_HEADERS', ('Cookie',))
)
return response
wrapped = csrf_exempt(
update_wrapper(wrapper, view)
)
wrapped.api_verbose_name = verbose_name
wrapped.api_call_type = 'view'
return wrapped
def wrap_api_page(site, view, allowed_methods):
"""
A decorator which wraps certain functions, so that a number of checks can be run before the function
is called (ie: checking that the HTTP method is allowed).
"""
def wrapper(request, *args, **kwargs):
if not request.method in allowed_methods:
return HttpResponse('')
response = site.api_page(
view, request, *args, **kwargs
)
if isinstance(response, HttpResponse):
patch_vary_headers(response,
('X-Platform', 'X-Device', 'Cookie')
)
return response
wrapped = update_wrapper(wrapper, view)
wrapped.api_call_type = 'page'
return wrapped
def generate_random_key(length = 32):
"""
Generates a random password for a user. This is purely for display purposes, from within the project's
developers' section.
"""
return User.objects.make_random_password(length = length)
def send_oauth_error(err):
"""
Send an OAuth error to the HTTP client.
"""
response = HttpResponse(err.message.encode('utf-8'))
response.status_code = 401
realm = 'OAuth'
header = build_authenticate_header(realm=realm)
for k, v in header.iteritems():
response[k] = v
return response
def get_request_logger():
logger = getattr(settings, 'API_REQUEST_LOGGER', 'bambu_api.requestlogging.DatabaseRequestLogger')
module, dot, klass = logger.rpartition('.')
module = import_module(module)
klass = getattr(module, klass)
return klass()
| {'content_hash': '38abaeb70050dc3f1a43b1a0b0bef86f', 'timestamp': '', 'source': 'github', 'line_count': 148, 'max_line_length': 103, 'avg_line_length': 25.155405405405407, 'alnum_prop': 0.7155519742143432, 'repo_name': 'iamsteadman/bambu-api', 'id': '097e56b42e6deeef4ae33190ff94582c30bb25d8', 'size': '3723', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'bambu_api/helpers.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '16424'}, {'name': 'JavaScript', 'bytes': '54587'}, {'name': 'Python', 'bytes': '133026'}]} |
using System.Collections.Generic;
using System.Linq;
namespace OrionLib.CommonContracts
{
public class ContextElementDto
{
public string Type { get; set; }
public string IsPattern { get; set; }
public string Id { get; set; }
public List<GetAttributeDto> Attributes { get; set; }
}
public static class ContextElementDtoExtensions
{
public static OrionEntity ToEntity(this ContextElementDto contextElement)
{
var entityAttributes = contextElement.Attributes.Select(attribute => attribute.ToEntityAttribute());
return new OrionEntity(contextElement.Type, contextElement.Id, entityAttributes);
}
}
} | {'content_hash': '8a4f0a7bcf78af8747b2e088852cc61a', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 112, 'avg_line_length': 30.565217391304348, 'alnum_prop': 0.6799431009957326, 'repo_name': 'bt-skyrise/OrionLib', 'id': 'd143a36bdb0cd3e63f48ab00a146e77064771937', 'size': '705', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Source/OrionLib/CommonContracts/ContextElementDto.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '120009'}, {'name': 'PowerShell', 'bytes': '4203'}]} |
// Copyright 2020 The TensorFlow Runtime Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Thin wrapper around the HIP API adding llvm::Error and explicit context.
#include "tfrt/gpu/wrapper/hip_wrapper.h"
#include <cstddef>
#include "llvm/Support/FormatVariadic.h"
#include "tfrt/gpu/wrapper/hip_stub.h"
#include "wrapper_detail.h"
namespace tfrt {
namespace gpu {
namespace wrapper {
llvm::raw_ostream& Print(llvm::raw_ostream& os, hipError_t error) {
const char* msg = hipGetErrorName(error);
if (msg != nullptr) {
os << msg;
} else {
os << llvm::formatv("hipError_t({0})", static_cast<int>(error));
}
msg = hipGetErrorString(error);
if (msg != nullptr) os << " (" << msg << ")";
return os;
}
// Convert wrapper types to HIP types.
static hipDevice_t ToRocm(Device device) { return device.id(Platform::ROCm); }
llvm::Error HipInit() { return TO_ERROR(hipInit(/*flags=*/0)); }
llvm::Error HipFree(std::nullptr_t) { return TO_ERROR(hipFree(nullptr)); }
llvm::Expected<int> HipDriverGetVersion() {
int version = -1;
RETURN_IF_ERROR(hipDriverGetVersion(&version));
return version;
}
llvm::Expected<int> HipRuntimeGetVersion() {
int version = -1;
RETURN_IF_ERROR(hipRuntimeGetVersion(&version));
return version;
}
llvm::Error HipGetLastError(CurrentContext current) {
CheckHipContext(current);
return TO_ERROR(hipGetLastError());
}
llvm::Error HipPeekAtLastError(CurrentContext current) {
CheckHipContext(current);
return TO_ERROR(hipPeekAtLastError());
}
llvm::Expected<hipDeviceProp_t> HipGetDeviceProperties(CurrentContext current) {
CheckHipContext(current);
int deviceId;
RETURN_IF_ERROR(hipGetDevice(&deviceId));
hipDeviceProp_t properties;
RETURN_IF_ERROR(hipGetDeviceProperties(&properties, deviceId));
return properties;
}
llvm::Expected<int> HipDeviceGetCount() {
int count;
RETURN_IF_ERROR(hipGetDeviceCount(&count));
return count;
}
llvm::Expected<Device> HipDeviceGet(int ordinal) {
hipDevice_t device;
RETURN_IF_ERROR(hipDeviceGet(&device, ordinal));
return Device(device, Platform::ROCm);
}
llvm::Expected<std::string> HipDeviceGetName(Device device) {
char name[100];
RETURN_IF_ERROR(hipDeviceGetName(name, sizeof(name), ToRocm(device)));
return std::string(name);
}
llvm::Expected<size_t> HipDeviceTotalMem(Device device) {
size_t size_bytes;
RETURN_IF_ERROR(hipDeviceTotalMem(&size_bytes, ToRocm(device)));
return size_bytes;
}
llvm::Expected<int> HipDeviceGetAttribute(hipDeviceAttribute_t attribute,
Device device) {
int value;
RETURN_IF_ERROR(hipDeviceGetAttribute(&value, attribute, ToRocm(device)));
return value;
}
llvm::Expected<std::string> HipDeviceGetPCIBusId(Device device) {
char bus_id[100];
RETURN_IF_ERROR(hipDeviceGetPCIBusId(bus_id, sizeof(bus_id), ToRocm(device)));
return std::string(bus_id);
}
llvm::Expected<size_t> HipDeviceGetLimit(CurrentContext current,
hipLimit_t limit) {
CheckHipContext(current);
size_t value;
RETURN_IF_ERROR(hipDeviceGetLimit(&value, limit));
return value;
}
llvm::Expected<StreamPriorityRange> HipDeviceGetStreamPriorityRange(
CurrentContext current) {
CheckHipContext(current);
StreamPriorityRange priority_range;
RETURN_IF_ERROR(hipDeviceGetStreamPriorityRange(&priority_range.least,
&priority_range.greatest));
return priority_range;
}
llvm::Error HipDeviceSynchronize(CurrentContext current) {
CheckHipContext(current);
return TO_ERROR(hipDeviceSynchronize());
}
llvm::Expected<int> HipDeviceCanAccessPeer(Device src_dev, Device dst_dev) {
int result;
RETURN_IF_ERROR(
hipDeviceCanAccessPeer(&result, ToRocm(src_dev), ToRocm(dst_dev)));
return result;
}
llvm::Error HipDeviceEnablePeerAccess(CurrentContext current,
Device peer_device) {
CheckHipContext(current);
return TO_ERROR(hipDeviceEnablePeerAccess(ToRocm(peer_device), /*flags=*/0));
}
llvm::Error HipDeviceDisablePeerAccess(CurrentContext current,
Device peer_device) {
CheckHipContext(current);
return TO_ERROR(hipDeviceDisablePeerAccess(peer_device.id(Platform::ROCm)));
}
llvm::Expected<OwningContext> HipDevicePrimaryCtxRetain(Device device) {
hipCtx_t hip_ctx;
RETURN_IF_ERROR(hipDevicePrimaryCtxRetain(&hip_ctx, ToRocm(device)));
kContextTls.hip_may_skip_set_ctx = true;
return OwningContext(hip_ctx);
}
llvm::Error HipDevicePrimaryCtxRelease(Device device) {
if (auto has_instance = CheckNoCurrentContext()) return has_instance;
RETURN_IF_ERROR(hipDevicePrimaryCtxRelease(ToRocm(device)));
// Releasing the primary context does not change the current context, but
// decrements the internal reference count and deactivates it iff zero.
kContextTls.hip_may_skip_set_ctx = false;
#ifndef NDEBUG
auto state = HipDevicePrimaryCtxGetState(device);
if (!state) return state.takeError();
if (!state->active) {
auto context = HipDevicePrimaryCtxRetain(device);
if (!context) return context.takeError();
RETURN_IF_ERROR(hipDevicePrimaryCtxRelease(ToRocm(device)));
return CheckNoDanglingResources(context->release());
}
#endif
return llvm::Error::success();
}
llvm::Error HipDevicePrimaryCtxReset(Device device) {
if (kContextTls.platform == Platform::ROCm) {
if (auto has_instance = CheckNoCurrentContext()) {
// There is a CurrentContext instance, check that primary is not current.
hipCtx_t context;
RETURN_IF_ERROR(hipCtxGetCurrent(&context));
if (kContextTls.hip_ctx == context) return has_instance;
}
}
Context context;
#ifndef NDEBUG
auto context_or = HipDevicePrimaryCtxRetain(device);
if (!context_or) return context_or.takeError();
context = context_or->release();
RETURN_IF_ERROR(hipDevicePrimaryCtxRelease(ToRocm(device)));
#endif
RETURN_IF_ERROR(hipDevicePrimaryCtxReset(ToRocm(device)));
return CheckNoDanglingResources(context);
}
llvm::Expected<ContextState> HipDevicePrimaryCtxGetState(Device device) {
unsigned flags;
int active;
RETURN_IF_ERROR(hipDevicePrimaryCtxGetState(ToRocm(device), &flags, &active));
return ContextState{static_cast<hipDeviceFlags_t>(flags), active};
}
llvm::Error HipDevicePrimaryCtxSetFlags(Device device, hipDeviceFlags_t flags) {
return TO_ERROR(hipDevicePrimaryCtxSetFlags(ToRocm(device), flags));
}
llvm::Expected<OwningContext> HipCtxCreate(hipDeviceFlags_t flags,
Device device) {
// Check no instance of CurrentContext exists in this thread.
if (auto has_instance = CheckNoCurrentContext())
return std::move(has_instance);
RETURN_IF_ERROR(hipCtxCreate(&kContextTls.hip_ctx, flags, ToRocm(device)));
kContextTls.platform = Platform::ROCm;
kContextTls.hip_may_skip_set_ctx = true;
return OwningContext(kContextTls.hip_ctx);
}
llvm::Error HipCtxDestroy(hipCtx_t context) {
if (context == nullptr) return llvm::Error::success();
if (kContextTls.hip_ctx == context &&
kContextTls.platform == Platform::ROCm) {
// Check that there is no CurrentContext instance.
if (auto has_instance = CheckNoCurrentContext()) return has_instance;
}
RETURN_IF_ERROR(hipCtxDestroy(context));
if (kContextTls.hip_ctx == context) {
// Destroying the current context makes the primary context current if there
// is one for the same device. The primary context may be inactive.
RETURN_IF_ERROR(hipCtxGetCurrent(&kContextTls.hip_ctx));
kContextTls.hip_may_skip_set_ctx = false;
}
return CheckNoDanglingResources(context);
}
llvm::Expected<CurrentContext> HipCtxGetCurrent() {
return CreateCurrentContext();
}
llvm::Expected<CurrentContext> HipCtxSetCurrent(hipCtx_t context) {
// Check no instance of CurrentContext exists in this thread.
if (auto has_instance = CheckNoCurrentContext())
return std::move(has_instance);
// Skip setting context if it's already current. This is an optimization
// that requires users to not change the current context through the HIP
// API. This is validated through calls to CheckHipContext().
if (kContextTls.hip_ctx != context || !kContextTls.hip_may_skip_set_ctx) {
RETURN_IF_ERROR(hipCtxSetCurrent(context));
if (context != nullptr) {
kContextTls.hip_may_skip_set_ctx = true;
} else {
// Setting the null context makes the primary context current if there
// is one for the current device. The primary context may be inactive.
RETURN_IF_ERROR(hipCtxGetCurrent(&context));
kContextTls.hip_may_skip_set_ctx = (context == nullptr);
}
kContextTls.hip_ctx = context;
}
kContextTls.platform = Platform::ROCm;
auto current = CreateCurrentContext();
// Catch false skipping of setting context above.
CheckHipContext(current);
return current;
}
llvm::Expected<unsigned> HipCtxGetApiVersion(hipCtx_t context) {
int version;
RETURN_IF_ERROR(hipCtxGetApiVersion(context, &version));
return version;
}
llvm::Expected<Device> HipCtxGetDevice(CurrentContext current) {
CheckHipContext(current);
hipDevice_t device;
RETURN_IF_ERROR(hipCtxGetDevice(&device));
return Device(device, Platform::ROCm);
}
llvm::Expected<hipDeviceFlags_t> HipCtxGetFlags(CurrentContext current) {
CheckHipContext(current);
unsigned flags;
RETURN_IF_ERROR(hipCtxGetFlags(&flags));
return static_cast<hipDeviceFlags_t>(flags);
}
llvm::Expected<OwningStream> HipStreamCreate(CurrentContext current,
hipStreamFlags_t flags) {
CheckHipContext(current);
hipStream_t stream;
RETURN_IF_ERROR(hipStreamCreateWithFlags(&stream, flags));
NotifyResourceCreated(ResourceType::kStream, stream);
return OwningStream(stream);
}
llvm::Expected<OwningStream> HipStreamCreate(CurrentContext current,
hipStreamFlags_t flags,
int priority) {
CheckHipContext(current);
hipStream_t stream;
RETURN_IF_ERROR(hipStreamCreateWithPriority(&stream, flags, priority));
NotifyResourceCreated(ResourceType::kStream, stream);
return OwningStream(stream);
}
llvm::Error HipStreamDestroy(hipStream_t stream) {
if (stream == nullptr) return llvm::Error::success();
RETURN_IF_ERROR(hipStreamDestroy(stream));
NotifyResourceDestroyed(stream);
return llvm::Error::success();
}
llvm::Expected<int> HipStreamGetPriority(hipStream_t stream) {
int priority;
RETURN_IF_ERROR(hipStreamGetPriority(stream, &priority));
return priority;
}
llvm::Expected<hipStreamFlags_t> HipStreamGetFlags(hipStream_t stream) {
unsigned flags;
RETURN_IF_ERROR(hipStreamGetFlags(stream, &flags));
return static_cast<hipStreamFlags_t>(flags);
}
llvm::Error HipStreamSynchronize(hipStream_t stream) {
return TO_ERROR(hipStreamSynchronize(stream));
}
llvm::Expected<bool> HipStreamQuery(hipStream_t stream) {
auto result = hipStreamQuery(stream);
if (result == hipErrorNotReady) {
return false;
}
RETURN_IF_ERROR(result);
return true;
}
llvm::Error HipStreamWaitEvent(hipStream_t stream, hipEvent_t event) {
return TO_ERROR(hipStreamWaitEvent(stream, event, /*flags=*/0));
}
llvm::Expected<OwningEvent> HipEventCreate(CurrentContext current,
hipEventFlags_t flags) {
CheckHipContext(current);
hipEvent_t event;
RETURN_IF_ERROR(hipEventCreateWithFlags(&event, flags));
NotifyResourceCreated(ResourceType::kEvent, event);
return OwningEvent(event);
}
llvm::Error HipEventDestroy(hipEvent_t event) {
if (event == nullptr) return llvm::Error::success();
RETURN_IF_ERROR(hipEventDestroy(event));
NotifyResourceDestroyed(event);
return llvm::Error::success();
}
llvm::Error HipEventRecord(hipEvent_t event, hipStream_t stream) {
return TO_ERROR(hipEventRecord(event, stream));
}
llvm::Error HipEventSynchronize(hipEvent_t event) {
return TO_ERROR(hipEventSynchronize(event));
}
llvm::Expected<bool> HipEventQuery(hipEvent_t event) {
auto result = hipEventQuery(event);
if (result == hipErrorNotReady) {
return false;
}
RETURN_IF_ERROR(result);
return true;
}
llvm::Expected<float> HipEventElapsedTime(hipEvent_t start, hipEvent_t end) {
float time_ms;
RETURN_IF_ERROR(hipEventElapsedTime(&time_ms, start, end));
return time_ms;
}
llvm::Expected<DeviceMemory<void>> HipMemAlloc(CurrentContext current,
size_t size_bytes) {
CheckHipContext(current);
hipDeviceptr_t ptr;
if (auto error = TO_ERROR(hipMalloc(&ptr, size_bytes))) {
return llvm::handleErrors(std::move(error),
[&](std::unique_ptr<ErrorInfo<hipError_t>> info) {
return GetResult(*info) == hipErrorOutOfMemory
? MakeOomError(current, size_bytes)
: llvm::Error(std::move(info));
});
}
NotifyResourceCreated(ResourceType::kDeviceMemory, ptr);
return DeviceMemory<void>({ptr, Platform::ROCm});
}
llvm::Error HipMemFree(Pointer<void> pointer) {
RETURN_IF_ERROR(hipFree(ToRocm(pointer)));
NotifyResourceDestroyed(ToRocm(pointer));
return llvm::Error::success();
}
llvm::Expected<HostMemory<void>> HipMemHostAlloc(CurrentContext current,
size_t size_bytes,
hipHostMallocFlags_t flags) {
CheckHipContext(current);
void* ptr;
RETURN_IF_ERROR(hipHostMalloc(&ptr, size_bytes, flags));
NotifyResourceCreated(ResourceType::kHostMemory, ptr);
return HostMemory<void>({ptr, Platform::ROCm});
}
llvm::Error HipMemHostFree(Pointer<void> pointer) {
RETURN_IF_ERROR(hipHostFree(ToRocm(pointer)));
NotifyResourceDestroyed(ToRocm(pointer));
return llvm::Error::success();
}
llvm::Expected<RegisteredMemory<void>> HipMemHostRegister(
CurrentContext current, void* ptr, size_t size_bytes,
hipHostRegisterFlags_t flags) {
CheckHipContext(current);
RETURN_IF_ERROR(hipHostRegister(ptr, size_bytes, flags));
NotifyResourceCreated(ResourceType::kRegisteredMemory, ptr);
return RegisteredMemory<void>({ptr, Platform::ROCm});
}
llvm::Error HipMemHostUnregister(Pointer<void> pointer) {
RETURN_IF_ERROR(hipHostUnregister(ToRocm(pointer)));
NotifyResourceDestroyed(ToRocm(pointer));
return llvm::Error::success();
}
llvm::Expected<DeviceMemory<void>> HipMemAllocManaged(
CurrentContext current, size_t size_bytes, hipMemAttachFlags_t flags) {
CheckHipContext(current);
hipDeviceptr_t ptr;
RETURN_IF_ERROR(hipMallocManaged(&ptr, size_bytes, flags));
NotifyResourceCreated(ResourceType::kDeviceMemory, ptr);
return DeviceMemory<void>({ptr, Platform::ROCm});
}
llvm::Expected<Pointer<void>> HipMemHostGetDevicePointer(
Pointer<void> host_ptr) {
hipDeviceptr_t device_ptr;
RETURN_IF_ERROR(
hipHostGetDevicePointer(&device_ptr, ToRocm(host_ptr), /*flags=*/0));
return Pointer<void>(device_ptr, Platform::ROCm);
}
llvm::Expected<MemoryRange<void>> HipMemGetAddressRange(CurrentContext current,
Pointer<void> ptr) {
CheckHipContext(current);
hipDeviceptr_t base;
size_t size_bytes;
RETURN_IF_ERROR(hipMemGetAddressRange(&base, &size_bytes, ToRocm(ptr)));
return MemoryRange<void>{{base, Platform::ROCm}, size_bytes};
}
llvm::Expected<MemoryInfo> HipMemGetInfo(CurrentContext current) {
CheckHipContext(current);
MemoryInfo info;
RETURN_IF_ERROR(hipMemGetInfo(&info.free_bytes, &info.total_bytes));
return info;
}
llvm::Expected<hipPointerAttribute_t> HipPointerGetAttributes(
Pointer<const void> ptr) {
hipPointerAttribute_t attributes;
RETURN_IF_ERROR(hipPointerGetAttributes(&attributes, ToRocm(ptr)));
return attributes;
}
llvm::Error HipMemcpy(CurrentContext current, Pointer<void> dst,
Pointer<const void> src, size_t count_bytes) {
CheckHipContext(current);
return TO_ERROR(
hipMemcpy(ToRocm(dst), ToRocm(src), count_bytes, hipMemcpyDefault));
}
llvm::Error HipMemcpyAsync(CurrentContext current, Pointer<void> dst,
Pointer<const void> src, size_t count_bytes,
hipStream_t stream) {
CheckHipContext(current);
return TO_ERROR(hipMemcpyAsync(ToRocm(dst), ToRocm(src), count_bytes,
hipMemcpyDefault, stream));
}
llvm::Error HipMemcpyPeer(Pointer<void> dst_ptr, Device dst_dev,
Pointer<const void> src_ptr, Device src_dev,
size_t count_bytes) {
return TO_ERROR(hipMemcpyPeer(ToRocm(dst_ptr), ToRocm(dst_dev),
ToRocm(src_ptr), ToRocm(src_dev), count_bytes));
}
llvm::Error HipMemcpyPeerAsync(Pointer<void> dst_ptr, Device dst_dev,
Pointer<const void> src_ptr, Device src_dev,
size_t count_bytes, hipStream_t stream) {
return TO_ERROR(hipMemcpyPeerAsync(ToRocm(dst_ptr), ToRocm(dst_dev),
ToRocm(src_ptr), ToRocm(src_dev),
count_bytes, stream));
}
llvm::Error HipMemsetD8(CurrentContext current, Pointer<void> dst,
std::uint8_t value, size_t count) {
CheckHipContext(current);
return TO_ERROR(hipMemset(ToRocm(dst), value, count));
}
llvm::Error HipMemsetD32(CurrentContext current, Pointer<void> dst,
std::uint32_t value, size_t count) {
CheckHipContext(current);
return TO_ERROR(hipMemsetD32(ToRocm(dst), value, count));
}
llvm::Error HipMemsetD8Async(CurrentContext current, Pointer<void> dst,
std::uint8_t value, size_t count,
hipStream_t stream) {
CheckHipContext(current);
return TO_ERROR(hipMemsetAsync(ToRocm(dst), value, count, stream));
}
llvm::Error HipMemsetD32Async(CurrentContext current, Pointer<void> dst,
std::uint32_t value, size_t count,
hipStream_t stream) {
CheckHipContext(current);
return TO_ERROR(hipMemsetD32Async(ToRocm(dst), value, count, stream));
}
llvm::Expected<OwningModule> HipModuleLoadData(CurrentContext current,
const void* image) {
CheckHipContext(current);
hipModule_t module;
RETURN_IF_ERROR(hipModuleLoadData(&module, image));
NotifyResourceCreated(ResourceType::kModule, module);
return OwningModule(module);
}
llvm::Expected<OwningModule> HipModuleLoadDataEx(
CurrentContext current, const void* image,
llvm::ArrayRef<hipJitOption> options, llvm::ArrayRef<void*> option_values) {
CheckHipContext(current);
hipModule_t module;
RETURN_IF_ERROR(hipModuleLoadDataEx(
&module, image, options.size(), const_cast<hipJitOption*>(options.data()),
const_cast<void**>(option_values.data())));
NotifyResourceCreated(ResourceType::kModule, module);
return OwningModule(module);
}
llvm::Error HipModuleUnload(hipModule_t module) {
if (module == nullptr) return llvm::Error::success();
RETURN_IF_ERROR(hipModuleUnload(module));
NotifyResourceDestroyed(module);
return llvm::Error::success();
}
llvm::Expected<Function> HipModuleGetFunction(hipModule_t module,
const char* name) {
hipFunction_t function;
RETURN_IF_ERROR(hipModuleGetFunction(&function, module, name));
return function;
}
llvm::Expected<MemoryRange<void>> HipModuleGetGlobal(hipModule_t module,
const char* name) {
void* ptr;
size_t size;
RETURN_IF_ERROR(hipModuleGetGlobal(&ptr, &size, module, name));
return MemoryRange<void>{{ptr, Platform::ROCm}, size};
}
llvm::Expected<hipFuncAttributes> HipFuncGetAttributes(CurrentContext current,
hipFunction_t function) {
CheckHipContext(current);
hipFuncAttributes attributes;
RETURN_IF_ERROR(hipFuncGetAttributes(&attributes, function));
return attributes;
}
llvm::Error HipLaunchKernel(CurrentContext current, hipFunction_t function,
unsigned grid_dim_x, unsigned grid_dim_y,
unsigned grid_dim_z, unsigned block_dim_x,
unsigned block_dim_y, unsigned block_dim_z,
unsigned shared_memory_size_bytes,
hipStream_t stream, llvm::ArrayRef<void*> arguments,
llvm::ArrayRef<void*> extras) {
CheckHipContext(current);
return TO_ERROR(hipModuleLaunchKernel(
function, grid_dim_x, grid_dim_y, grid_dim_z, block_dim_x, block_dim_y,
block_dim_z, shared_memory_size_bytes, stream,
const_cast<void**>(arguments.data()), const_cast<void**>(extras.data())));
}
llvm::Error HipLaunchCooperativeKernel(
CurrentContext current, hipFunction_t function, unsigned grid_dim_x,
unsigned grid_dim_y, unsigned grid_dim_z, unsigned block_dim_x,
unsigned block_dim_y, unsigned block_dim_z,
unsigned shared_memory_size_bytes, hipStream_t stream,
llvm::ArrayRef<void*> arguments) {
CheckHipContext(current);
hipDim3_t grid_dim = {grid_dim_x, grid_dim_y, grid_dim_z};
hipDim3_t block_dim = {block_dim_x, block_dim_y, block_dim_z};
return TO_ERROR(hipLaunchCooperativeKernel(
function, grid_dim, block_dim, const_cast<void**>(arguments.data()),
shared_memory_size_bytes, stream));
}
llvm::Expected<int> HipOccupancyMaxActiveBlocksPerMultiprocessor(
CurrentContext current, hipFunction_t function, int block_size,
size_t dynamic_shared_memory_size) {
CheckHipContext(current);
int32_t num_blocks;
RETURN_IF_ERROR(hipOccupancyMaxActiveBlocksPerMultiprocessor(
&num_blocks, function, block_size, dynamic_shared_memory_size));
return num_blocks;
}
llvm::Expected<MaxPotentialBlockSize> HipOccupancyMaxPotentialBlockSize(
CurrentContext current, hipFunction_t function,
size_t dynamic_shared_memory_size, int block_size_limit) {
CheckHipContext(current);
int32_t min_num_blocks, block_size;
RETURN_IF_ERROR(hipOccupancyMaxPotentialBlockSize(
&min_num_blocks, &block_size, function, dynamic_shared_memory_size,
block_size_limit));
return MaxPotentialBlockSize{min_num_blocks, block_size};
}
// Definitions from wrapper_detail.h.
llvm::Expected<hipDevice_t> HipCtxGetDevice(hipCtx_t context) {
hipDevice_t device;
if (kContextTls.hip_ctx == context) {
RETURN_IF_ERROR(hipCtxGetDevice(&device));
} else {
RETURN_IF_ERROR(hipCtxPushCurrent(context));
auto result = hipCtxGetDevice(&device);
RETURN_IF_ERROR(hipCtxPopCurrent(nullptr));
RETURN_IF_ERROR(result);
}
return device;
}
void CheckHipContext(CurrentContext) {
#ifndef NDEBUG
DieIfError([&]() -> llvm::Error {
if (auto error = CheckPlatform(kContextTls.platform, Platform::ROCm))
return error;
hipCtx_t hip_ctx;
RETURN_IF_ERROR(hipCtxGetCurrent(&hip_ctx));
if (kContextTls.hip_ctx != hip_ctx) {
std::string msg = llvm::formatv("Expected context to be {0}, but got {1}",
kContextTls.hip_ctx, hip_ctx);
return llvm::createStringError(llvm::inconvertibleErrorCode(), msg);
}
return llvm::Error::success();
}());
#endif
}
} // namespace wrapper
} // namespace gpu
} // namespace tfrt
| {'content_hash': '44a0767416c29e779b251410b1220d70', 'timestamp': '', 'source': 'github', 'line_count': 668, 'max_line_length': 80, 'avg_line_length': 36.01796407185629, 'alnum_prop': 0.691978387364921, 'repo_name': 'tensorflow/runtime', 'id': '052c06f1f754ce70b7fce91b29142d5a0c7f0afe', 'size': '24060', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'backends/gpu/lib/wrapper/hip_wrapper.cc', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '177969'}, {'name': 'C++', 'bytes': '4047908'}, {'name': 'MLIR', 'bytes': '4176420'}, {'name': 'Python', 'bytes': '29147'}, {'name': 'Shell', 'bytes': '2389'}, {'name': 'Starlark', 'bytes': '183378'}]} |
title: 使用JAXP以SAX解析xml实例
tags: [xml]
---
### 创建解析器(方式一)
通过XMLReaderFactory、XMLReader完成
```
//通过XMLReaderFactory创建XMLReader对象
XMLReader reader = XMLReaderFactory.createXMLReader();
//设置事件处理器对象:
//这里的MyDefaultHandler是自定义的处理器
reader.setContentHandler(new MyDefaultHandler());
//读取要解析的xml文件:
FileReader fileReader = new FileReader(
new File( "src\\sax\\startelement\\web.xml"));
//指定解析的xml文件:
reader.parse(new InputSource(fileReader));
```
### 创建解析器(方式二)
通过SAXParserFactory、SAXParser、XMLReader完成
```
//使用SAXParserFactory创建SAX解析工厂:
SAXParserFactory spFactory = SAXParserFactory.newInstance();
//通过SAX解析工厂得到解析器对象:
SAXParser sParser = spFactory.newSAXParser();
//通过解析器对象得到一个XML的读取器:
XMLReader xmlReader = sp.getXMLReader();
//设置读取器的事件处理器:
xmlReader.setContentHandler(new MyDefaultHandler());
//解析xml文件:
reader.parse(new InputSource(fileReader));
```
### 创建解析器(方式三)
通过SAXParserFactory,SAXParser完成
```
//获取sax解析器的工厂对象:
SAXParserFactory factory = SAXParserFactory.newInstance();
//通过工厂对象 SAXParser创建解析器对象:
SAXParser saxParser = factory.newSAXParser();
//通过解析saxParser的parse方法设定解析的文件和自己定义的事件处理器对象:
saxParser.parse(new File("src//sax//sida.xml"), new MyDefaultHandler());
``` | {'content_hash': '71f9322c242c4d1274dde1fe9769b48c', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 72, 'avg_line_length': 23.098039215686274, 'alnum_prop': 0.7809847198641766, 'repo_name': 'yutian1012/yutian1012.github.io', 'id': '17c55f278abb9cdbde8ef18cdcfc556206fd080a', 'size': '1590', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '_posts/language/java/高级应用/xml/jaxp/2017-05-19-xml-jaxp-sax-example.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '7162'}, {'name': 'CoffeeScript', 'bytes': '4590'}, {'name': 'HTML', 'bytes': '77617'}]} |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using org.ohdsi.cdm.framework.core.CommonVocabulary;
using org.ohdsi.cdm.framework.core.Definitions;
using org.ohdsi.cdm.framework.core.Savers;
using org.ohdsi.cdm.framework.entities.Builder;
using org.ohdsi.cdm.framework.entities.Omop;
using org.ohdsi.cdm.framework.shared.Enums;
using org.ohdsi.cdm.framework.shared.Helpers;
namespace org.ohdsi.cdm.framework.core.Base
{
public class ChunkBuilder : IChunkBuilder
{
#region Variables
private readonly ConcurrentDictionary<long, IPersonBuilder> personBuilders =
new ConcurrentDictionary<long, IPersonBuilder>();
private readonly ConcurrentDictionary<string, long> providerKeys =
new ConcurrentDictionary<string, long>(StringComparer.OrdinalIgnoreCase);
private readonly ChunkData chunk;
private readonly Type builderType;
#endregion
#region Properties
public Vocabulary Vocabulary { get; set; }
public ChunkData Chunk
{
get { return chunk; }
}
public ConcurrentDictionary<string, long> ProviderKeys
{
get { return providerKeys; }
}
#endregion
#region Constructors
public ChunkBuilder(ChunkData chunkData, Type builderType)
{
this.chunk = chunkData;
this.builderType = builderType;
}
#endregion
#region Methods
private IPersonBuilder CreatePersonBuilder()
{
return (IPersonBuilder)Activator.CreateInstance(builderType, this);
}
private void AddEntity(IEntity entity)
{
personBuilders.GetOrAdd(entity.PersonId, CreatePersonBuilder()).AddData(entity);
if (!string.IsNullOrEmpty(entity.ProviderKey))
{
providerKeys.GetOrAdd(entity.ProviderKey, 0);
}
}
private void AddChildData(IEntity parent, IEntity child)
{
personBuilders[parent.PersonId].AddChildData(parent, child);
}
private void AddEntity(QueryDefinition queryDefinition, IEnumerable<EntityDefinition> definitions,
IDataReader reader, Guid recordGuid)
{
if (definitions == null) return;
foreach (var d in queryDefinition.FindDefinition(definitions, reader))
{
Concept conceptDef = null;
if (d.Concepts != null && d.Concepts.Any())
conceptDef = d.Concepts[0];
if (this.Vocabulary == null)
this.Vocabulary = d.Vocabulary;
foreach (var entity in d.GetConcepts(conceptDef, reader, chunk.KeyMasterOffset))
{
if (entity == null) continue;
entity.SourceRecordGuid = recordGuid;
AddEntity(entity);
if (entity is DrugExposure)
{
if (queryDefinition.DrugCost != null)
AddChildData(entity, queryDefinition.DrugCost[0].CreateEnity((DrugExposure) entity, reader));
}
else if (entity is ProcedureOccurrence)
{
if (queryDefinition.ProcedureCost != null)
AddChildData(entity,
queryDefinition.ProcedureCost[0].CreateEnity((ProcedureOccurrence) entity, reader));
}
}
}
}
public ChunkBuilder Load()
{
var timer = new Stopwatch();
timer.Start();
foreach (var queryDefinition in Settings.Current.Building.SourceQueryDefinitions)
{
if (queryDefinition.Providers != null) continue;
if (queryDefinition.Locations != null) continue;
if (queryDefinition.CareSites != null) continue;
using (var conn = SqlConnectionHelper.OpenConnection(Settings.Current.Building.SourceConnectionString))
{
var queryFormat = queryDefinition.Query;
var query = string.Format(queryFormat, chunk.Id);
foreach (var q in query.Split(new[] {"go;"}, StringSplitOptions.RemoveEmptyEntries))
{
using (var c = new SqlCommand(q, conn))
{
c.CommandTimeout = 999999999;
using (var reader = c.ExecuteReader())
{
do
{
while (reader.Read())
{
var recordGuid = Guid.NewGuid();
AddEntity(queryDefinition, queryDefinition.Persons, reader, recordGuid);
AddEntity(queryDefinition, queryDefinition.PayerPlanPeriods, reader, recordGuid);
AddEntity(queryDefinition, queryDefinition.Death, reader, recordGuid);
AddEntity(queryDefinition, queryDefinition.VisitOccurrence, reader, recordGuid);
AddEntity(queryDefinition, queryDefinition.Observation, reader, recordGuid);
AddEntity(queryDefinition, queryDefinition.ConditionOccurrence, reader, recordGuid);
AddEntity(queryDefinition, queryDefinition.ProcedureOccurrence, reader, recordGuid);
AddEntity(queryDefinition, queryDefinition.DrugExposure, reader, recordGuid);
AddEntity(queryDefinition, queryDefinition.Cohort, reader, recordGuid);
}
} while (reader.NextResult());
}
}
}
}
}
timer.Stop();
Logger.Write(chunk.Id, LogMessageTypes.Info, string.Format("Loaded - {0} ms", timer.ElapsedMilliseconds));
Logger.Write(chunk.Id, LogMessageTypes.Info, string.Format("Loaded - {0} Mb", (GC.GetTotalMemory(false) / 1024f) / 1024f));
return this;
}
public ChunkBuilder Build()
{
var timer = new Stopwatch();
timer.Start();
if (providerKeys.Count > 0)
{
var providerIds = VocabularyManager.GetProviderIds(providerKeys.Keys.ToArray());
foreach (var keyValuePair in providerIds)
{
if (keyValuePair.Value != -1)
{
providerKeys[keyValuePair.Key] = keyValuePair.Value;
}
else
Logger.Write(chunk.Id, LogMessageTypes.Warning,
string.Format("ProviderIds does not contains key = '{0}'", keyValuePair.Key));
}
}
var opt = new ParallelOptions {MaxDegreeOfParallelism = 1};
Parallel.ForEach(personBuilders, opt, cd => cd.Value.Build());
timer.Stop();
Logger.Write(chunk.Id, LogMessageTypes.Info, string.Format("Built - {0} ms", timer.ElapsedMilliseconds));
Logger.Write(chunk.Id, LogMessageTypes.Info, string.Format("Built - {0} Mb", (GC.GetTotalMemory(false) / 1024f) / 1024f));
return this;
}
private void SaveData()
{
ISaver saver;
if (Settings.Current.Building.SaveType == SaveType.Db)
{
saver = new DbSaver();
}
else
{
saver = new FileSaver();
}
using (saver)
{
saver.Create().Save(chunk);
}
}
public Task Save()
{
return Task.Factory.StartNew(SaveData);
}
#endregion
}
}
| {'content_hash': '29e58766d6fc053c57741dfda93ab6da', 'timestamp': '', 'source': 'github', 'line_count': 222, 'max_line_length': 132, 'avg_line_length': 35.5, 'alnum_prop': 0.5641416063951276, 'repo_name': 'OHDSI/ETL-CDMBuilder', 'id': '64659f16085a34a6d7dc38d32cf0aed9dff125f8', 'size': '7883', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'CDMv4/source/Framework/org.ohdsi.cdm.framework.core/Base/ChunkBuilder.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '2469354'}, {'name': 'Dockerfile', 'bytes': '2077'}, {'name': 'Perl', 'bytes': '11421'}, {'name': 'TSQL', 'bytes': '140218'}]} |
<?php
namespace common\modules\admin;
class Module extends \common\modules\admin\BaseModule
{
public $controllerNamespace = 'common\modules\admin\controllers';
}
| {'content_hash': '3f6d59e94046b3ee932a000d720bfbb1', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 69, 'avg_line_length': 23.857142857142858, 'alnum_prop': 0.7784431137724551, 'repo_name': 'jump2/easycms', 'id': 'ee9d3858e84ce7a008f63b7a44d086a313868c64', 'size': '167', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'common/modules/admin/Module.php', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'ApacheConf', 'bytes': '482'}, {'name': 'Batchfile', 'bytes': '1541'}, {'name': 'CSS', 'bytes': '7655'}, {'name': 'JavaScript', 'bytes': '3026'}, {'name': 'PHP', 'bytes': '521014'}, {'name': 'Shell', 'bytes': '3257'}]} |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using Moq;
using System.Data.Entity;
using RoboBraille.WebApi.Models;
using System.Collections.Generic;
using System.Text;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net.Http;
using RoboBraille.WebApi.Controllers;
namespace RoboBraille.WebApi.Test
{
[TestClass]
public class TestEBook
{
[TestMethod]
public async Task TestPostEBook()
{
//init
var mockJobs = new Mock<DbSet<Job>>();
var mockServiceUsers = new Mock<DbSet<ServiceUser>>();
var mockContext = new Mock<RoboBrailleDataContext>();
// arrange
var users = new List<ServiceUser> {
new ServiceUser
{
EmailAddress = "[email protected]",
UserId = Guid.Parse("d2b97532-e8c5-e411-8270-f0def103cfd0"),
ApiKey = Encoding.UTF8.GetBytes("7b76ae41-def3-e411-8030-0c8bfd2336cd"),
FromDate = new DateTime(2015, 1, 1),
ToDate = new DateTime(2020, 1, 1),
UserName = "TestUser",
Jobs = null
}
}.AsQueryable();
EBookJob acj = new EBookJob()
{
Id = Guid.NewGuid(),
FileContent = new byte[512],
UserId = Guid.Parse("d2b97532-e8c5-e411-8270-f0def103cfd0"),
FileExtension = ".pdf",
FileName = "test",
MimeType = "application/pdf",
Status = JobStatus.Started,
SubmitTime = DateTime.Now,
DownloadCounter = 0,
InputFileHash = new byte[8]
};
EBookJob acj2 = new EBookJob()
{
Id = Guid.NewGuid(),
FileContent = new byte[256],
UserId = Guid.Parse("d2b87532-e8c5-e411-8270-f0def103cfd0"),
FileExtension = ".txt",
FileName = "test2",
MimeType = "text/plain",
Status = JobStatus.Done,
SubmitTime = DateTime.Now,
DownloadCounter = 2,
InputFileHash = new byte[2]
};
var jobs = new List<Job> { acj2 }.AsQueryable();
mockJobs.As<IDbAsyncEnumerable<Job>>().Setup(m => m.GetAsyncEnumerator()).Returns(new TestDbAsyncEnumerator<Job>(jobs.GetEnumerator()));
mockJobs.As<IQueryable<Job>>().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider<Job>(jobs.Provider));
mockJobs.As<IQueryable<Job>>().Setup(m => m.Expression).Returns(jobs.Expression);
mockJobs.As<IQueryable<Job>>().Setup(m => m.ElementType).Returns(jobs.ElementType);
mockJobs.As<IQueryable<Job>>().Setup(m => m.GetEnumerator()).Returns(jobs.GetEnumerator());
mockServiceUsers.As<IDbAsyncEnumerable<ServiceUser>>().Setup(m => m.GetAsyncEnumerator()).Returns(new TestDbAsyncEnumerator<ServiceUser>(users.GetEnumerator()));
mockServiceUsers.As<IQueryable<ServiceUser>>().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider<ServiceUser>(users.Provider));
mockServiceUsers.As<IQueryable<ServiceUser>>().Setup(m => m.Expression).Returns(users.Expression);
mockServiceUsers.As<IQueryable<ServiceUser>>().Setup(m => m.ElementType).Returns(users.ElementType);
mockServiceUsers.As<IQueryable<ServiceUser>>().Setup(m => m.GetEnumerator()).Returns(users.GetEnumerator());
mockContext.Setup(m => m.Jobs).Returns(mockJobs.Object);
mockContext.Setup(m => m.ServiceUsers).Returns(mockServiceUsers.Object);
var repo = new EBookRepository(mockContext.Object);
var request = new HttpRequestMessage();
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Authorization", "Hawk id=\"d2b97532-e8c5-e411-8270-f0def103cfd0\", ts=\"1470657024\", nonce=\"VkcMGB\", mac=\"hXW+BLRoqwlUaQZQtpPToOWnVAh5KbAXGGT5f8dLMVk=\"");
var serviceController = new EBookController(repo);
serviceController.Request = request;
//call
await serviceController.Post(acj);
//test
mockJobs.Verify(m => m.Add(It.IsAny<Job>()), Times.Once());
mockContext.Verify(m => m.SaveChanges(), Times.Once());
}
}
}
| {'content_hash': 'eabbb008ffe7b0e6b9cfdf9376d6362d', 'timestamp': '', 'source': 'github', 'line_count': 97, 'max_line_length': 258, 'avg_line_length': 46.154639175257735, 'alnum_prop': 0.5968282331918695, 'repo_name': 'sensusaps/RoboBraille.Web.API', 'id': 'aab27dcaa4057b58166e5c71b79c8b04abad8f01', 'size': '4479', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'RoboBraille.WebApi.Test/PostTests/TestEBook.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '109'}, {'name': 'Batchfile', 'bytes': '300'}, {'name': 'C#', 'bytes': '1239445'}, {'name': 'CSS', 'bytes': '67060'}, {'name': 'HTML', 'bytes': '1830352'}, {'name': 'JavaScript', 'bytes': '848822'}, {'name': 'Python', 'bytes': '867517'}, {'name': 'Shell', 'bytes': '1422'}, {'name': 'Smalltalk', 'bytes': '3'}, {'name': 'TeX', 'bytes': '462500'}, {'name': 'XSLT', 'bytes': '555256'}]} |
<?php
require_once '../conf.php';
$page = 'services';
$title = 'M.B. Driveways Services - Paths and Paving Services';
$desc = 'MB Driveways can install any kind of path wide or thin, straight or curved made from blocks, flags, cobble or gravel. For our paving we use tried and tested materials from trusted companies such as Thomas Armstrong, Brett, Marshalls, Bradstone and Lakeland.';
$keyw = 'paths, path, paving, consett, hexham, gateshead, durham, newcastle, dewentside, block paving, paved, thomas armstrong, brett, marshalls, bradstone, lakeland';
include_once '../head.php';
?>
<section id="services-paving">
<div class="container">
<div class="row">
<div class="col-lg-12">
<h2 class="section-heading text-center">Paths and Paving</h2>
<p class="text-muted">
One of the main aspects of work we provide along side our driveways are paths. We can install any kind of path wide or thin, straight or
curved made from blocks, flags, cobble or gravel. For our paving we use tried and tested materials from trusted companies such as Thomas
Armstrong, Brett, Marshalls, Bradstone and Lakeland.
<br><br>
If you have any questions about patios or would like us to give you a quote, please <a href="/contact.html">get in touch</a>.
</p>
</div>
</div>
</div>
</section>
<section id="gallery" style="margin-top: -80px">
<div class="container">
<div class="row">
<?php
$usedpics = '';
$sql = "SELECT filename, job_type, job_area, description FROM gallery where `keywords` LIKE '%path%' order by rand() desc limit 0,12";
if (!$result = $mysqli->query($sql)) {
echo "Sorry, the website is experiencing problems.";
exit;
}
while ($gallery = $result->fetch_assoc()) {
if (!$gallery['job_type'] && !$gallery['job_area']) {
$gallery_title = $titles[rand(0,count($titles)-1)];
} else {
$gallery_title = $gallery['job_type'];
if ($gallery['job_area']) {
$gallery_title .= ' in ';
}
$gallery_title .= $gallery['job_area'];
}
$usedpics .= " and `filename` != '" . $gallery['filename'] . "'";
echo '<div class="col-md-4 col-sm-6 gallery-item">
<a href="/gallery/' . $gallery['filename'] . '.html" class="gallery-link" data-toggle="modal">
<div class="gallery-hover">
<div class="gallery-hover-content">
<i class="fa fa-plus fa-3x"></i>
</div>
</div>
<img src="/images/gallery/' . $gallery['filename'] . '.jpg" class="img-responsive" alt="' . $gallery_title . '">
</a>
<div class="gallery-caption">
<p class="text-muted"><a href="/gallery/' . $gallery['filename'] . '.html">' . $gallery_title . '</a></p>
</div>
</div>';
}
?>
</div>
<div class="row">
<div class="col-lg-12" style="margin-top: -30px">
<p class="text-muted">
View more of our <a href="/gallery/">paving in our gallery</a>.
</p>
</div>
</div>
</div>
</section>
<section id="services-all" class="bg-light-gray" style="margin-top: -30px">
<div class="container">
<div class="row">
<div class="col-lg-12" style="margin-top: -20px">
<h3 class="section-subheading">Paths and Paving in your area</h3>
</div>
</div>
<div class="row" style="line-height: 1.8">
<div class="col-md-4 col-sm-6">
<a href="/areas/consett.html">Paving in Consett</a><br>
<a href="/areas/chester-le-street.html">Paving in Chester-Le-Street</a><br>
<a href="/areas/newcastle.html">Paving in Newcastle</a><br>
<a href="/areas/waldridge.html">Paving in Waldridge</a><br>
<a href="/areas/rowlands-gill.html">Paving in Rowlands Gill</a><br>
<a href="/areas/stocksfield.html">Paving in Stocksfield</a><br>
</div>
<div class="col-md-4 col-sm-6">
<a href="/areas/stanley.html">Paving in Stanley</a><br>
<a href="/areas/derwentside.html">Paving in Derwentside</a><br>
<a href="/areas/weardale.html">Paving in Weardale</a><br>
<a href="/areas/whickham.html">Paving in Whickham</a><br>
<a href="/areas/high-spen.html">Paving in High Spen</a><br>
</div>
<div class="col-md-4 col-sm-6">
<a href="/areas/durham.html">Paving in Durham</a><br>
<a href="/areas/gateshead.html">Paving in Gateshead</a><br>
<a href="/areas/hexham.html">Paving in Hexham</a><br>
<a href="/areas/lanchester.html">Paving in Lanchester</a><br>
<a href="/areas/prudhoe.html">Paving in Prudhoe</a><br>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<p class="text-muted">
Please don't hesitate to <a href="/contact.html">contact us</a> if you have any questions or would like a quote.
</p>
</div>
</div>
</div>
</section>
<?php
include_once '../foot.php';
?> | {'content_hash': '58dbb07f3a3938e1e870ec47846f96e5', 'timestamp': '', 'source': 'github', 'line_count': 130, 'max_line_length': 273, 'avg_line_length': 47.46153846153846, 'alnum_prop': 0.480064829821718, 'repo_name': 'neilnem/mbdriveways', 'id': '2b4aa8f0848d42a155652ce79db98d61820bc351', 'size': '6170', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'services/paving.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '1297'}, {'name': 'CSS', 'bytes': '75899'}, {'name': 'HTML', 'bytes': '53'}, {'name': 'JavaScript', 'bytes': '44441'}, {'name': 'PHP', 'bytes': '156922'}]} |
require 'spec_helper'
describe 'lma_collector::logs::openstack_decoder_splitter' do
let(:facts) do
{:kernel => 'Linux', :operatingsystem => 'Ubuntu',
:osfamily => 'Debian'}
end
describe 'without file_match' do
it { is_expected.to contain_heka__decoder__sandbox('openstack') }
it { is_expected.to contain_heka__splitter__token('openstack') \
.with_delimiter('\n') }
end
end
| {'content_hash': 'ff8db20b072e751b369330da0309006b', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 73, 'avg_line_length': 31.142857142857142, 'alnum_prop': 0.6123853211009175, 'repo_name': 'TAJaroszewski/lma_contrail_monitoring', 'id': '1021425dc60d5ebed1595e05ae4b44c3864ae77a', 'size': '1048', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'deployment_scripts/puppet/modules/lma_collector/spec/classes/lma_collector_logs_openstack_decoder_splitter_spec.rb', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '338021'}, {'name': 'Lua', 'bytes': '225189'}, {'name': 'Pascal', 'bytes': '5775'}, {'name': 'Puppet', 'bytes': '222517'}, {'name': 'Python', 'bytes': '200210'}, {'name': 'Ruby', 'bytes': '119983'}, {'name': 'Shell', 'bytes': '39325'}]} |
This is a sample app for Google App Engine that demonstrates the [Images Python
API](https://cloud.google.com/appengine/docs/python/images/usingimages).
<!-- auto-doc-link -->
These samples are used on the following documentation page:
> https://cloud.google.com/appengine/docs/python/images/usingimages
<!-- end-auto-doc-link -->
Refer to the [App Engine Samples README](../README.md) for information on how to run and deploy this sample.
| {'content_hash': '78ddc2e2ae9c307f587e2acf5b5e3423', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 108, 'avg_line_length': 40.36363636363637, 'alnum_prop': 0.7567567567567568, 'repo_name': 'marcomaccio/python-docs-samples', 'id': 'f4164204c542d7c8fa3d442b310d57fa00c77ce0', 'size': '472', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'appengine/images/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '58'}, {'name': 'HTML', 'bytes': '1490'}, {'name': 'JavaScript', 'bytes': '148'}, {'name': 'Python', 'bytes': '225894'}, {'name': 'Shell', 'bytes': '3961'}]} |
import sys
from time import sleep
from datetime import datetime
from courtutils.databases.postgres import PostgresDatabase
from courtreader import readers
from courtutils.logger import get_logger
log = get_logger()
reader = readers.DistrictCourtReader()
db = PostgresDatabase('district')
def update_case(fips):
cases_to_fix = db.get_cases_with_no_past_due(fips, 'criminal')
for case_to_fix in cases_to_fix:
time_cap_1 = datetime.now()
case = {
'fips': fips,
'case_number': case_to_fix[0],
'details_fetched_for_hearing_date': case_to_fix[1],
'collected': datetime.now()
}
case['details'] = reader.get_case_details_by_number(
fips, 'criminal', case_to_fix[0],
case['details_url'] if 'details_url' in case else None)
time_cap_2 = datetime.now()
if 'error' in case['details']:
log.warn('Could not collect case details for %s in %s',
case_to_fix[0], case['fips'])
else:
log.info('%s %s', fips, case['details']['CaseNumber'])
last_case_collected = datetime.now()
db.replace_case_details(case, 'criminal')
log.info('%s %s',
int((time_cap_2 - time_cap_1).total_seconds()),
int((datetime.now() - time_cap_2).total_seconds()))
while True:
try:
reader.connect()
if len(sys.argv) > 1:
update_case(sys.argv[1])
else:
courts = list(db.get_courts())
for court in courts:
update_case(court['fips'])
except Exception:
print 'Exception. Starting over.'
except KeyboardInterrupt:
raise
try:
reader.log_off()
except Exception:
print 'Could not log off'
except KeyboardInterrupt:
raise
sleep(10)
| {'content_hash': '3939a74ebfb555a45099453a12900a2b', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 68, 'avg_line_length': 32.258620689655174, 'alnum_prop': 0.5740245857830037, 'repo_name': 'bschoenfeld/va-court-scraper', 'id': 'efea981257cfba36e85994d3221889cb924530fe', 'size': '1871', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'archived/fix_past_due_issue.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '43814'}, {'name': 'Python', 'bytes': '189578'}]} |
<?php
namespace App\Http\Controllers;
use Intervention\Image\ImageManagerStatic as Image;
use Illuminate\Support\Facades\File;
class ImageController extends Controller
{
public function getImageThumbnail($path, $width = null, $height = null, $school_code = "ys", $type = "fit", $file_ext = "")
{
$images_path = config('definitions.images_path') . "/" . $school_code;
$path = ltrim($path, "/");
//returns the original image if isn't passed width and height
if (is_null($width) && is_null($height)) {
return url("{$images_path}/" . $path);
}
//if thumbnail exist returns it
if (File::exists(public_path("{$images_path}/thumbs/" . "{$width}x{$height}/" . $path))) {
return url("{$images_path}/thumbs/" . "{$width}x{$height}/" . $path);
}
//If original image doesn't exists returns a default image which shows that original image doesn't exist.
if (!File::exists(public_path("{$images_path}/" . $path))) {
/*
* 2 ways
*/
//1. recursive call for the default image
//return $this->getImageThumbnail("error/no-image.png", $width, $height, $type);
//2. returns an image placeholder generated from placehold.it
return "http://placehold.it/{$width}x{$height}";
}
$allowedMimeTypes = ['image/gif', 'image/png', 'image/jpeg', 'image/bmp', 'image/x-ms-bmp', 'image/webp'];
$picFileExt = ['gif', 'png', 'jpeg', 'bmp', 'jpg'];
// $contentType = mime_content_type("{$images_path}/" . $path);
// $finfo = finfo_open(FILEINFO_MIME_TYPE);
// dd (finfo_file($finfo, "{$images_path}/" . $path));
// finfo_close($finfo);
$contentType = mime_content_type("{$images_path}/" . $path);
// var_dump($allowedMimeTypes);
// dd($file_ext);
if (in_array($file_ext, $picFileExt)) { //Checks if is an image
Image::configure(array('driver' => 'imagick'));
$image = Image::make(public_path("{$images_path}/" . $path));
switch ($type) {
case "fit": {
$image->fit($width, $height, function ($constraint) {
$constraint->upsize();
});
break;
}
case "resize": {
//stretched
$image->resize($width, $height);
}
case "background": {
$image->resize($width, $height, function ($constraint) {
//keeps aspect ratio and sets black background
$constraint->aspectRatio();
$constraint->upsize();
});
}
case "resizeCanvas": {
$image->resizeCanvas($width, $height, 'center', false, 'rgba(0, 0, 0, 0)'); //gets the center part
}
}
//relative directory path starting from main directory of images
$dir_path = (dirname($path) == '.') ? "" : dirname($path);
//Create the directory if it doesn't exist
if (!File::exists(public_path("{$images_path}/thumbs/" . "{$width}x{$height}/" . $dir_path))) {
File::makeDirectory(public_path("{$images_path}/thumbs/" . "{$width}x{$height}/" . $dir_path), 0775, true);
}
//Save the thumbnail
$image->save(public_path("{$images_path}/thumbs/" . "{$width}x{$height}/" . $path));
//return the url of the thumbnail
return url("{$images_path}/thumbs/" . "{$width}x{$height}/" . $path);
} else { //Checks if is an document
$docFileExt = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'];
$docMimeType = ["application/msword", 'application/x-xls', 'application/vnd.ms-excel', 'application/x-ppt', 'application/vnd.ms-powerpoint'];
if (in_array($file_ext, ["doc", "docx"])) {
return url("images/doc.png");
// return "http://10.63.7.189/op/embed.aspx?src=http%3A%2F%2Fwww.oic.com%3A8001%2Fposts%2F%E5%91%B3%E9%81%93.docx-5b96766db52f2.docx";
} elseif (in_array($file_ext, ["xls", 'xlsx'])) {
return url("images/xls.png");
} elseif (in_array($file_ext, ["ppt", "pptx"])) {
return url("images/ppt.png");
} elseif (in_array($file_ext, ["sb2"])) {
return url("images/scratch.png");
} else {
return "http://placehold.it/{$width}x{$height}";
}
}
}
} | {'content_hash': '8e96f5b6fa03387d6799d7e64fdbff1b', 'timestamp': '', 'source': 'github', 'line_count': 108, 'max_line_length': 153, 'avg_line_length': 43.351851851851855, 'alnum_prop': 0.5081161896625374, 'repo_name': 'huanhuashengling/our-information-class', 'id': 'cea1e78a975a2ca93d8dd64e440502e36e55d2cb', 'size': '4682', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/Http/Controllers/ImageController.php', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'HTML', 'bytes': '220199'}, {'name': 'PHP', 'bytes': '3216938'}, {'name': 'TSQL', 'bytes': '33290'}, {'name': 'Vue', 'bytes': '561'}]} |
package pgx_test
import (
"errors"
"fmt"
"github.com/jackc/pgx"
"sync"
"testing"
)
func createConnPool(t *testing.T, maxConnections int) *pgx.ConnPool {
config := pgx.ConnPoolConfig{ConnConfig: *defaultConnConfig, MaxConnections: maxConnections}
pool, err := pgx.NewConnPool(config)
if err != nil {
t.Fatalf("Unable to create connection pool: %v", err)
}
return pool
}
func TestNewConnPool(t *testing.T) {
t.Parallel()
var numCallbacks int
afterConnect := func(c *pgx.Conn) error {
numCallbacks++
return nil
}
config := pgx.ConnPoolConfig{ConnConfig: *defaultConnConfig, MaxConnections: 2, AfterConnect: afterConnect}
pool, err := pgx.NewConnPool(config)
if err != nil {
t.Fatal("Unable to establish connection pool")
}
defer pool.Close()
// It initially connects once
stat := pool.Stat()
if stat.CurrentConnections != 1 {
t.Errorf("Expected 1 connection to be established immediately, but %v were", numCallbacks)
}
// Pool creation returns an error if any AfterConnect callback does
errAfterConnect := errors.New("Some error")
afterConnect = func(c *pgx.Conn) error {
return errAfterConnect
}
config = pgx.ConnPoolConfig{ConnConfig: *defaultConnConfig, MaxConnections: 2, AfterConnect: afterConnect}
pool, err = pgx.NewConnPool(config)
if err != errAfterConnect {
t.Errorf("Expected errAfterConnect but received unexpected: %v", err)
}
}
func TestNewConnPoolDefaultsTo5MaxConnections(t *testing.T) {
t.Parallel()
config := pgx.ConnPoolConfig{ConnConfig: *defaultConnConfig}
pool, err := pgx.NewConnPool(config)
if err != nil {
t.Fatal("Unable to establish connection pool")
}
defer pool.Close()
if n := pool.Stat().MaxConnections; n != 5 {
t.Fatalf("Expected pool to default to 5 max connections, but it was %d", n)
}
}
func TestPoolAcquireAndReleaseCycle(t *testing.T) {
t.Parallel()
maxConnections := 2
incrementCount := int32(100)
completeSync := make(chan int)
pool := createConnPool(t, maxConnections)
defer pool.Close()
acquireAll := func() (connections []*pgx.Conn) {
connections = make([]*pgx.Conn, maxConnections)
for i := 0; i < maxConnections; i++ {
var err error
if connections[i], err = pool.Acquire(); err != nil {
t.Fatalf("Unable to acquire connection: %v", err)
}
}
return
}
allConnections := acquireAll()
for _, c := range allConnections {
mustExec(t, c, "create temporary table t(counter integer not null)")
mustExec(t, c, "insert into t(counter) values(0);")
}
for _, c := range allConnections {
pool.Release(c)
}
f := func() {
conn, err := pool.Acquire()
if err != nil {
t.Fatal("Unable to acquire connection")
}
defer pool.Release(conn)
// Increment counter...
mustExec(t, conn, "update t set counter = counter + 1")
completeSync <- 0
}
for i := int32(0); i < incrementCount; i++ {
go f()
}
// Wait for all f() to complete
for i := int32(0); i < incrementCount; i++ {
<-completeSync
}
// Check that temp table in each connection has been incremented some number of times
actualCount := int32(0)
allConnections = acquireAll()
for _, c := range allConnections {
var n int32
c.QueryRow("select counter from t").Scan(&n)
if n == 0 {
t.Error("A connection was never used")
}
actualCount += n
}
if actualCount != incrementCount {
fmt.Println(actualCount)
t.Error("Wrong number of increments")
}
for _, c := range allConnections {
pool.Release(c)
}
}
func TestPoolReleaseWithTransactions(t *testing.T) {
t.Parallel()
pool := createConnPool(t, 2)
defer pool.Close()
conn, err := pool.Acquire()
if err != nil {
t.Fatalf("Unable to acquire connection: %v", err)
}
mustExec(t, conn, "begin")
if _, err = conn.Exec("selct"); err == nil {
t.Fatal("Did not receive expected error")
}
if conn.TxStatus != 'E' {
t.Fatalf("Expected TxStatus to be 'E', instead it was '%c'", conn.TxStatus)
}
pool.Release(conn)
if conn.TxStatus != 'I' {
t.Fatalf("Expected release to rollback errored transaction, but it did not: '%c'", conn.TxStatus)
}
conn, err = pool.Acquire()
if err != nil {
t.Fatalf("Unable to acquire connection: %v", err)
}
mustExec(t, conn, "begin")
if conn.TxStatus != 'T' {
t.Fatalf("Expected txStatus to be 'T', instead it was '%c'", conn.TxStatus)
}
pool.Release(conn)
if conn.TxStatus != 'I' {
t.Fatalf("Expected release to rollback uncommitted transaction, but it did not: '%c'", conn.TxStatus)
}
}
func TestPoolAcquireAndReleaseCycleAutoConnect(t *testing.T) {
t.Parallel()
maxConnections := 3
pool := createConnPool(t, maxConnections)
defer pool.Close()
doSomething := func() {
c, err := pool.Acquire()
if err != nil {
t.Fatalf("Unable to Acquire: %v", err)
}
rows, _ := c.Query("select 1")
rows.Close()
pool.Release(c)
}
for i := 0; i < 1000; i++ {
doSomething()
}
stat := pool.Stat()
if stat.CurrentConnections != 1 {
t.Fatalf("Pool shouldn't have established more connections when no contention: %v", stat.CurrentConnections)
}
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
doSomething()
}()
}
wg.Wait()
stat = pool.Stat()
if stat.CurrentConnections != stat.MaxConnections {
t.Fatalf("Pool should have used all possible connections: %v", stat.CurrentConnections)
}
}
func TestPoolReleaseDiscardsDeadConnections(t *testing.T) {
t.Parallel()
// Run timing sensitive test many times
for i := 0; i < 50; i++ {
func() {
maxConnections := 3
pool := createConnPool(t, maxConnections)
defer pool.Close()
var c1, c2 *pgx.Conn
var err error
var stat pgx.ConnPoolStat
if c1, err = pool.Acquire(); err != nil {
t.Fatalf("Unexpected error acquiring connection: %v", err)
}
defer func() {
if c1 != nil {
pool.Release(c1)
}
}()
if c2, err = pool.Acquire(); err != nil {
t.Fatalf("Unexpected error acquiring connection: %v", err)
}
defer func() {
if c2 != nil {
pool.Release(c2)
}
}()
if _, err = c2.Exec("select pg_terminate_backend($1)", c1.Pid); err != nil {
t.Fatalf("Unable to kill backend PostgreSQL process: %v", err)
}
// do something with the connection so it knows it's dead
rows, _ := c1.Query("select 1")
rows.Close()
if rows.Err() == nil {
t.Fatal("Expected error but none occurred")
}
if c1.IsAlive() {
t.Fatal("Expected connection to be dead but it wasn't")
}
stat = pool.Stat()
if stat.CurrentConnections != 2 {
t.Fatalf("Unexpected CurrentConnections: %v", stat.CurrentConnections)
}
if stat.AvailableConnections != 0 {
t.Fatalf("Unexpected AvailableConnections: %v", stat.CurrentConnections)
}
pool.Release(c1)
c1 = nil // so it doesn't get released again by the defer
stat = pool.Stat()
if stat.CurrentConnections != 1 {
t.Fatalf("Unexpected CurrentConnections: %v", stat.CurrentConnections)
}
if stat.AvailableConnections != 0 {
t.Fatalf("Unexpected AvailableConnections: %v", stat.CurrentConnections)
}
}()
}
}
func TestConnPoolTransaction(t *testing.T) {
t.Parallel()
pool := createConnPool(t, 2)
defer pool.Close()
stats := pool.Stat()
if stats.CurrentConnections != 1 || stats.AvailableConnections != 1 {
t.Fatalf("Unexpected connection pool stats: %v", stats)
}
tx, err := pool.Begin()
if err != nil {
t.Fatalf("pool.Begin failed: %v", err)
}
defer tx.Rollback()
var n int32
err = tx.QueryRow("select 40+$1", 2).Scan(&n)
if err != nil {
t.Fatalf("tx.QueryRow Scan failed: %v", err)
}
if n != 42 {
t.Errorf("Expected 42, got %d", n)
}
stats = pool.Stat()
if stats.CurrentConnections != 1 || stats.AvailableConnections != 0 {
t.Fatalf("Unexpected connection pool stats: %v", stats)
}
err = tx.Rollback()
if err != nil {
t.Fatalf("tx.Rollback failed: %v", err)
}
stats = pool.Stat()
if stats.CurrentConnections != 1 || stats.AvailableConnections != 1 {
t.Fatalf("Unexpected connection pool stats: %v", stats)
}
}
func TestConnPoolTransactionIso(t *testing.T) {
t.Parallel()
pool := createConnPool(t, 2)
defer pool.Close()
tx, err := pool.BeginIso(pgx.Serializable)
if err != nil {
t.Fatalf("pool.Begin failed: %v", err)
}
defer tx.Rollback()
var level string
err = tx.QueryRow("select current_setting('transaction_isolation')").Scan(&level)
if err != nil {
t.Fatalf("tx.QueryRow failed: %v", level)
}
if level != "serializable" {
t.Errorf("Expected to be in isolation level %v but was %v", "serializable", level)
}
}
func TestConnPoolBeginRetry(t *testing.T) {
t.Parallel()
// Run timing sensitive test many times
for i := 0; i < 50; i++ {
func() {
pool := createConnPool(t, 2)
defer pool.Close()
killerConn, err := pool.Acquire()
if err != nil {
t.Fatal(err)
}
defer pool.Release(killerConn)
victimConn, err := pool.Acquire()
if err != nil {
t.Fatal(err)
}
pool.Release(victimConn)
// Terminate connection that was released to pool
if _, err = killerConn.Exec("select pg_terminate_backend($1)", victimConn.Pid); err != nil {
t.Fatalf("Unable to kill backend PostgreSQL process: %v", err)
}
// Since victimConn is the only available connection in the pool, pool.Begin should
// try to use it, fail, and allocate another connection
tx, err := pool.Begin()
if err != nil {
t.Fatalf("pool.Begin failed: %v", err)
}
defer tx.Rollback()
var txPid int32
err = tx.QueryRow("select pg_backend_pid()").Scan(&txPid)
if err != nil {
t.Fatalf("tx.QueryRow Scan failed: %v", err)
}
if txPid == victimConn.Pid {
t.Error("Expected txPid to defer from killed conn pid, but it didn't")
}
}()
}
}
func TestConnPoolQuery(t *testing.T) {
t.Parallel()
pool := createConnPool(t, 2)
defer pool.Close()
var sum, rowCount int32
rows, err := pool.Query("select generate_series(1,$1)", 10)
if err != nil {
t.Fatalf("pool.Query failed: %v", err)
}
stats := pool.Stat()
if stats.CurrentConnections != 1 || stats.AvailableConnections != 0 {
t.Fatalf("Unexpected connection pool stats: %v", stats)
}
for rows.Next() {
var n int32
rows.Scan(&n)
sum += n
rowCount++
}
if rows.Err() != nil {
t.Fatalf("conn.Query failed: ", err)
}
if rowCount != 10 {
t.Error("Select called onDataRow wrong number of times")
}
if sum != 55 {
t.Error("Wrong values returned")
}
stats = pool.Stat()
if stats.CurrentConnections != 1 || stats.AvailableConnections != 1 {
t.Fatalf("Unexpected connection pool stats: %v", stats)
}
}
func TestConnPoolQueryConcurrentLoad(t *testing.T) {
t.Parallel()
pool := createConnPool(t, 10)
defer pool.Close()
n := 100
done := make(chan bool)
for i := 0; i < n; i++ {
go func() {
defer func() { done <- true }()
var rowCount int32
rows, err := pool.Query("select generate_series(1,$1)", 1000)
if err != nil {
t.Fatalf("pool.Query failed: %v", err)
}
defer rows.Close()
for rows.Next() {
var n int32
err = rows.Scan(&n)
if err != nil {
t.Fatalf("rows.Scan failed: %v", err)
}
if n != rowCount+1 {
t.Fatalf("Expected n to be %d, but it was %d", rowCount+1, n)
}
rowCount++
}
if rows.Err() != nil {
t.Fatalf("conn.Query failed: ", err)
}
if rowCount != 1000 {
t.Error("Select called onDataRow wrong number of times")
}
_, err = pool.Exec("--;")
if err != nil {
t.Fatalf("pool.Exec failed: %v", err)
}
}()
}
for i := 0; i < n; i++ {
<-done
}
}
func TestConnPoolQueryRow(t *testing.T) {
t.Parallel()
pool := createConnPool(t, 2)
defer pool.Close()
var n int32
err := pool.QueryRow("select 40+$1", 2).Scan(&n)
if err != nil {
t.Fatalf("pool.QueryRow Scan failed: %v", err)
}
if n != 42 {
t.Errorf("Expected 42, got %d", n)
}
stats := pool.Stat()
if stats.CurrentConnections != 1 || stats.AvailableConnections != 1 {
t.Fatalf("Unexpected connection pool stats: %v", stats)
}
}
func TestConnPoolExec(t *testing.T) {
t.Parallel()
pool := createConnPool(t, 2)
defer pool.Close()
results, err := pool.Exec("create temporary table foo(id integer primary key);")
if err != nil {
t.Fatalf("Unexpected error from pool.Exec: %v", err)
}
if results != "CREATE TABLE" {
t.Errorf("Unexpected results from Exec: %v", results)
}
results, err = pool.Exec("insert into foo(id) values($1)", 1)
if err != nil {
t.Fatalf("Unexpected error from pool.Exec: %v", err)
}
if results != "INSERT 0 1" {
t.Errorf("Unexpected results from Exec: %v", results)
}
results, err = pool.Exec("drop table foo;")
if err != nil {
t.Fatalf("Unexpected error from pool.Exec: %v", err)
}
if results != "DROP TABLE" {
t.Errorf("Unexpected results from Exec: %v", results)
}
}
| {'content_hash': 'a9fecfaa41280d96f38366570a7b1ea2', 'timestamp': '', 'source': 'github', 'line_count': 554, 'max_line_length': 110, 'avg_line_length': 23.04693140794224, 'alnum_prop': 0.6467731829573935, 'repo_name': 'kelvich/pgx', 'id': '93fea4d46e5f58eaa4436f6a8d227f221509318e', 'size': '12768', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'conn_pool_test.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '267405'}]} |
import {
CHANGE_MONITOR,
CHANGE_POSITION,
CHANGE_SIZE,
TOGGLE_VISIBILITY
} from "./actions";
import { POSITIONS } from "./constants";
import { Children } from "react";
function position(props, state = props.defaultPosition, action) {
return (action.type === CHANGE_POSITION) ?
POSITIONS[(POSITIONS.indexOf(state) + 1) % POSITIONS.length] :
state;
}
function size(props, state = props.defaultSize, action) {
return (action.type === CHANGE_SIZE) ?
action.size :
state;
}
function isVisible(props, state = props.defaultIsVisible, action) {
return (action.type === TOGGLE_VISIBILITY) ?
!state :
state;
}
function childMonitorStates(props, state = [], action) {
return Children.map(props.children, (child: any, index) =>
child.type.update(child.props, state[index], action)
);
}
function childMonitorIndex(props, state = 0, action) {
switch (action.type) {
case CHANGE_MONITOR:
return (state + 1) % Children.count(props.children);
default:
return state;
}
}
export default function reducer(props, state: any = {}, action: any) {
if (!state.childMonitorStates) {
Children.forEach(props.children, (child: any, index) => {
if (typeof child.type.update !== "function") {
console.error(
`Child of <DockMonitor> with the index ${index} ` +
`(${child.type.displayName || child.type.name || child.type}) ` +
"does not appear to be a valid Redux DevTools monitor."
);
}
});
}
return {
position: position(props, state.position, action),
isVisible: isVisible(props, state.isVisible, action),
size: size(props, state.size, action),
childMonitorIndex: childMonitorIndex(
props,
state.childMonitorIndex,
action
),
childMonitorStates: childMonitorStates(
props,
state.childMonitorStates,
action
)
};
} | {'content_hash': '1d5a6f889264181f45adad63135b1734', 'timestamp': '', 'source': 'github', 'line_count': 71, 'max_line_length': 85, 'avg_line_length': 29.633802816901408, 'alnum_prop': 0.5822243346007605, 'repo_name': 'dotnetprofessional/ABusJS', 'id': '1f58143d83cfc13042d1b6ebb350bd3a0dcf6e2f', 'size': '2104', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'packages/abus-devtools/src/reducersOld.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1684'}, {'name': 'HTML', 'bytes': '117'}, {'name': 'JavaScript', 'bytes': '32262'}, {'name': 'TypeScript', 'bytes': '342029'}]} |
using ArchitectNow.Framework.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TypeScript.Demo.Data.Models;
using TypeScript.Demo.Data.Repositories;
namespace TypeScript.Demo.Areas.API.Controllers
{
[AllowAnonymous]
public class PersonController : BaseDataController<Person>
{
public IPersonRepository PersonRepository { get; set; }
public PersonController(IPersonRepository PersonRepository)
{
this.PersonRepository = PersonRepository;
this.Repository = PersonRepository;
}
public Envelope<bool> CheckActive(Guid ID)
{
return new Envelope<bool>() { Content = true };
}
}
}
| {'content_hash': 'f79b4026e1c470d9517c1fb944deb448', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 68, 'avg_line_length': 27.96551724137931, 'alnum_prop': 0.6670776818742293, 'repo_name': 'ArchitectNow/TypeScript.Demo', 'id': 'bd607302c67f4d03e1d0eef50b73c69cb4853363', 'size': '813', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'TypeScript.Demo/Areas/API/Controllers/PersonController.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '107'}, {'name': 'C#', 'bytes': '52191'}, {'name': 'CSS', 'bytes': '731'}, {'name': 'HTML', 'bytes': '5277'}, {'name': 'JavaScript', 'bytes': '12581'}, {'name': 'TypeScript', 'bytes': '7759'}]} |
<?php
namespace Ben\DoctorsBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Httpfoundation\Response;
use JMS\SecurityExtraBundle\Annotation\Secure;
class DefaultController extends Controller
{
/**
* @Secure(roles="ROLE_USER")
*/
public function indexAction()
{
return $this->render('BenDoctorsBundle:Default:index.html.twig');
}
/**
* @Secure(roles="ROLE_USER")
*/
public function statsAction(Request $request)
{
$daterange = $request->get('daterange');
$statsHandler = $this->get('ben.stats_handler')->setDateRange($daterange);
$availableWidgets = ['meds', 'stock', 'cnss', 'consultations_demande', 'consultations_demande_gender', 'consultations_demande_resident',
'consultations_demande_resident_gender', 'consultations_systematique_resident', 'consultations_systematique_resident_gender',
'consultations_visual_issue', 'consultations_special', 'consultations_special_gender', 'consultations_chronic',
'consultations_not_chronic', 'consultations_structures'];
$widgets = $request->get('widgets');
$stats = [];
if (isset($widgets)) {
foreach ($widgets as $key => $val) {
if(in_array($key, $availableWidgets))
$stats[$key] = $statsHandler->setDataColumn($key)->processData();
}
}
return $this->render('BenDoctorsBundle:Default:ajaxStats.html.twig', array(
'stats' => $stats));
}
} | {'content_hash': '4c661800f74490c35ea0b3dc6d8e2d9f', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 150, 'avg_line_length': 38.81395348837209, 'alnum_prop': 0.6249251048532055, 'repo_name': 'umamaheswarib/Doctors', 'id': '48618c71b61c238f8857e76a3bd81ea9a1b4d282', 'size': '1669', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/Ben/DoctorsBundle/Controller/DefaultController.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '2907'}, {'name': 'CSS', 'bytes': '43602'}, {'name': 'HTML', 'bytes': '154970'}, {'name': 'JavaScript', 'bytes': '136875'}, {'name': 'PHP', 'bytes': '236710'}]} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': 'cfa6c1ccfa67f07eb62aa16307349adb', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': '3f2be9972ad8bd52178880afa3db635e7befd839', 'size': '173', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Salvia/Salvia orientalis/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
<?php
declare(strict_types=1);
namespace Lsv\Rejseplan\Utils;
use Lsv\Rejseplan\Response\CoordinateResponse;
use Lsv\Rejseplan\Response\Location\Stop;
class LocationParser
{
/**
* @return array<array-key, string>
*/
public static function supports(bool $coordinates = true): array
{
$supports = ['string', 'int', Stop::class];
if ($coordinates) {
$supports[] = CoordinateResponse::class;
}
return $supports;
}
/**
* @param array<array-key, mixed> $data
*/
public static function parse(array &$data, string $key, bool $addKeys = true): void
{
if (!isset($data[$key])) {
return;
}
if ($data[$key] instanceof Stop) {
$newdata = $data[$key];
$newkey = $key;
if ($addKeys) {
$newkey .= 'Id';
}
unset($data[$key]);
$data[$newkey] = $newdata->id;
return;
}
if ($addKeys && $data[$key] instanceof CoordinateResponse) {
$data[$key.'CoordX'] = self::coordinateToNumber($data[$key]->longitude);
$data[$key.'CoordY'] = self::coordinateToNumber($data[$key]->latitude);
unset($data[$key]);
return;
}
if (is_numeric($data[$key])) {
$newdata = $data[$key];
$newkey = $key;
if ($addKeys) {
$newkey .= 'Id';
}
unset($data[$key]);
$data[$newkey] = $newdata;
return;
}
$data[$key.'CoordName'] = $data[$key];
unset($data[$key]);
}
public static function coordinateToNumber(float $coordinate): string
{
return str_replace('.', '', (string) $coordinate);
}
}
| {'content_hash': '8bbb4f2c162f39484a6acab17c385140', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 87, 'avg_line_length': 24.405405405405407, 'alnum_prop': 0.4955703211517165, 'repo_name': 'lsv/rejseplan-php-api', 'id': 'a5e1e44960d01f2661b466982bc63a40be1b2feb', 'size': '1806', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Utils/LocationParser.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '69755'}]} |
import sys
if sys.version_info < (3, 7):
from ._opacity import OpacityValidator
from ._fillcolor import FillcolorValidator
else:
from _plotly_utils.importers import relative_import
__all__, __getattr__, __dir__ = relative_import(
__name__, [], ["._opacity.OpacityValidator", "._fillcolor.FillcolorValidator"]
)
| {'content_hash': 'c2d6931a64d2cf88e510767cb96e6420', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 86, 'avg_line_length': 31.0, 'alnum_prop': 0.6627565982404692, 'repo_name': 'plotly/python-api', 'id': '92c926891250388a7d1fd6819c47c6ec5266b77a', 'size': '341', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'packages/python/plotly/plotly/validators/layout/activeshape/__init__.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '6870'}, {'name': 'Makefile', 'bytes': '1708'}, {'name': 'Python', 'bytes': '823245'}, {'name': 'Shell', 'bytes': '3238'}]} |
require "coverage.so"
module Coverage
def self.line_stub(file)
lines = File.foreach(file).map { nil }
iseqs = [RubyVM::InstructionSequence.compile_file(file)]
until iseqs.empty?
iseq = iseqs.pop
iseq.trace_points.each {|n, type| lines[n - 1] = 0 if type == :line }
iseq.each_child {|child| iseqs << child }
end
lines
end
end
| {'content_hash': '9e001d4574514db9c264e827844182fa', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 75, 'avg_line_length': 26.285714285714285, 'alnum_prop': 0.6304347826086957, 'repo_name': 'pmq20/ruby-compiler', 'id': 'f1923ef366cbf35abd04b010902abd1cb3813872', 'size': '368', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'ruby/ext/coverage/lib/coverage.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '35'}, {'name': 'Assembly', 'bytes': '545193'}, {'name': 'Awk', 'bytes': '750'}, {'name': 'Batchfile', 'bytes': '10078'}, {'name': 'C', 'bytes': '31431383'}, {'name': 'C++', 'bytes': '170471'}, {'name': 'CSS', 'bytes': '15720'}, {'name': 'Emacs Lisp', 'bytes': '122830'}, {'name': 'GDB', 'bytes': '29782'}, {'name': 'HTML', 'bytes': '22578'}, {'name': 'JavaScript', 'bytes': '18023'}, {'name': 'M4', 'bytes': '74049'}, {'name': 'Makefile', 'bytes': '320959'}, {'name': 'Perl', 'bytes': '302'}, {'name': 'Perl 6', 'bytes': '636'}, {'name': 'Python', 'bytes': '7484'}, {'name': 'Ragel', 'bytes': '24937'}, {'name': 'Roff', 'bytes': '3385688'}, {'name': 'Ruby', 'bytes': '18904964'}, {'name': 'Scheme', 'bytes': '668'}, {'name': 'Scilab', 'bytes': '745'}, {'name': 'Shell', 'bytes': '362849'}, {'name': 'TeX', 'bytes': '323102'}, {'name': 'XSLT', 'bytes': '13913'}, {'name': 'Yacc', 'bytes': '512205'}]} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.