text:
/**
 * @fileoverview Rule to disallow empty functions.
 * @author Toru Nagashima
 */

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const astUtils = require("./utils/ast-utils");

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

const ALLOW_OPTIONS = Object.freeze([
    "functions",
    "arrowFunctions",
    "generatorFunctions",
    "methods",
    "generatorMethods",
    "getters",
    "setters",
    "constructors",
    "asyncFunctions",
    "asyncMethods"
]);

/**
 * Gets the kind of a given function node.
 * @param {ASTNode} node A function node to get. This is one of
 *      an ArrowFunctionExpression, a FunctionDeclaration, or a
 *      FunctionExpression.
 * @returns {string} The kind of the function. This is one of "functions",
 *      "arrowFunctions", "generatorFunctions", "asyncFunctions", "methods",
 *      "generatorMethods", "asyncMethods", "getters", "setters", and
 *      "constructors".
 */
function getKind(node) {
    const parent = node.parent;
    let kind = "";

    if (node.type === "ArrowFunctionExpression") {
        return "arrowFunctions";
    }

    // Detects main kind.
    if (parent.type === "Property") {
        if (parent.kind === "get") {
            return "getters";
        }
        if (parent.kind === "set") {
            return "setters";
        }
        kind = parent.method ? "methods" : "functions";

    } else if (parent.type === "MethodDefinition") {
        if (parent.kind === "get") {
            return "getters";
        }
        if (parent.kind === "set") {
            return "setters";
        }
        if (parent.kind === "constructor") {
            return "constructors";
        }
        kind = "methods";

    } else {
        kind = "functions";
    }

    // Detects prefix.
    let prefix = "";

    if (node.generator) {
        prefix = "generator";
    } else if (node.async) {
        prefix = "async";
    } else {
        return kind;
    }
    return prefix + kind[0].toUpperCase() + kind.slice(1);
}

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

/** @type {import('../shared/types').Rule} */
module.exports = {
    meta: {
        type: "suggestion",

        docs: {
            description: "disallow empty functions",
            recommended: false,
            url: "https://eslint.org/docs/rules/no-empty-function"
        },

        schema: [
            {
                type: "object",
                properties: {
                    allow: {
                        type: "array",
                        items: { enum: ALLOW_OPTIONS },
                        uniqueItems: true
                    }
                },
                additionalProperties: false
            }
        ],

        messages: {
            unexpected: "Unexpected empty {{name}}."
        }
    },

    create(context) {
        const options = context.options[0] || {};
        const allowed = options.allow || [];

        const sourceCode = context.getSourceCode();

        /**
         * Reports a given function node if the node matches the following patterns.
         *
         * - Not allowed by options.
         * - The body is empty.
         * - The body doesn't have any comments.
         * @param {ASTNode} node A function node to report. This is one of
         *      an ArrowFunctionExpression, a FunctionDeclaration, or a
         *      FunctionExpression.
         * @returns {void}
         */
        function reportIfEmpty(node) {
            const kind = getKind(node);
            const name = astUtils.getFunctionNameWithKind(node);
            const innerComments = sourceCode.getTokens(node.body, {
                includeComments: true,
                filter: astUtils.isCommentToken
            });

            if (allowed.indexOf(kind) === -1 &&
                node.body.type === "BlockStatement" &&
                node.body.body.length === 0 &&
                innerComments.length === 0
            ) {
                context.report({
                    node,
                    loc: node.body.loc,
                    messageId: "unexpected",
                    data: { name }
                });
            }
        }

        return {
            ArrowFunctionExpression: reportIfEmpty,
            FunctionDeclaration: reportIfEmpty,
            FunctionExpression: reportIfEmpty
        };
    }
};


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/menu_item_delete_book"
        android:title="@string/delete_book"
        android:icon="@drawable/ic_action_delete"
        app:showAsAction="never"/>
    <item
        android:id="@+id/menu_item_save_book"
        android:title="@string/save_book"
        android:icon="@drawable/ic_action_tick"
        app:showAsAction="ifRoom|withText"/>
</menu>

redpajama_set_name: RedPajamaGithub


text:
level-set
=========

Saves JSON to your LevelDB. Converting your JSON to LevelDB key-value pair data structure.

### Install
```bash
npm install level-set
```

```js
var LevelUp = require('levelup'),
    LevelSet = require('level-set');

var db = LevelUp('./testdb');

LevelSet(db);
```

### Set JSON object
```js
var person = { name: 'Maiah', occupation: 'Ninja' };
db.set('/', person, function (err) {
  if (!err) console.log('Saved person under root path');
});
```

This will put key-value pairs LevelDB data structure at the `root` path.
```
name = Maiah
occupation = Ninja
```

You can also save any valid JSON structure.
```js
var person = {
  name: 'Maiah',
  occupation: 'Ninja',
  tools: {
    lang: 'js'
  }
};

db.set('/', person, function (err) {
  if (!err) console.log('Saved person under root path');
});

```

This will put key-value pairs LevelDB data structure at the `root` path.
```
name = Maiah
occupation = Ninja
tools/lang = js
```

You can also specify a path other than the `root`.
```js
var person = { name: 'Maiah', occupation: 'Ninja' };
db.set('/person', person, function (err) {
  if (!err) console.log('Saved person object');
});

```

This will put key-value pairs LevelDB data structure at the `person` path.
```
person/name = Maiah
person/occupation = Ninja
```

### License
MIT


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>Apache log4cxx: rollingfileappender.h File Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Namespaces

Classes

Files

File List

File Members

rollingfileappender.h File Reference

Namespaces

namespace  	log4cxx

namespace  	log4cxx::rolling

Classes

class  	RollingFileAppender

 	RollingFileAppender extends log4cxx::FileAppender to backup the log files depending on RollingPolicy and TriggeringPolicy.  More...

Defines

#define 	_LOG4CXX_ROLLING_ROLLING_FILE_APPENDER_H

Functions

 	log4cxx::rolling::LOG4CXX_PTR_DEF (RollingFileAppender)

Define Documentation

          #define _LOG4CXX_ROLLING_ROLLING_FILE_APPENDER_H


text:
param($installPath, $toolsPath, $package, $project)

$analyzersPath = join-path $toolsPath "analyzers"

# Install the language agnostic analyzers.
foreach ($analyzerFilePath in Get-ChildItem $analyzersPath)
{
    $project.Object.AnalyzerReferences.Add($analyzerFilePath.FullName)
}

# Install language specific analyzers.
# $project.Type gives the language name like (C# or VB.NET)
$languageAnalyzersPath = join-path $analyzersPath $project.Type

foreach ($analyzerFilePath in Get-ChildItem $languageAnalyzersPath)
{
    $project.Object.AnalyzerReferences.Add($analyzerFilePath.FullName)
}


text:
#pragma once

#include "fboss/lib/usb/BaseWedgeI2CBus.h"

#include <mutex>
#include <folly/Range.h>

namespace facebook { namespace fboss {

/*
 * A small wrapper around CP2112 which is aware of the topology of wedge's QSFP
 * I2C bus, and can select specific QSFPs to query.
 */
class WedgeI2CBusLock {
 public:
  explicit WedgeI2CBusLock(std::unique_ptr<BaseWedgeI2CBus> wedgeI2CBus);
  void open();
  void close();
  void moduleRead(unsigned int module, uint8_t i2cAddress,
                  int offset, int len, uint8_t* buf);
  void moduleWrite(unsigned int module, uint8_t i2cAddress,
                  int offset, int len, uint8_t* buf);

 private:

  // Forbidden copy constructor and assignment operator
  WedgeI2CBusLock(WedgeI2CBusLock const &) = delete;
  WedgeI2CBusLock& operator=(WedgeI2CBusLock const &) = delete;

  void openLocked();
  void closeLocked();

  std::unique_ptr<BaseWedgeI2CBus> wedgeI2CBus_{nullptr};
  mutable std::mutex busMutex_;
  bool opened_{false};
};

}} // facebook::fboss


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Anal. Soc. cient. argent. 12(4): 187 (1881)

#### Original name
Hysterium ajoense Speg.

### Remarks
null


text:
import {APPLICATION_DATA_SOURCE_EDITOR} from './dataSources/applicationDataSourceEditor.component';
import {CHAOS_MONKEY_CONFIG_COMPONENT} from 'core/chaosMonkey/chaosMonkeyConfig.component';
import {TRAFFIC_GUARD_CONFIG_COMPONENT} from './trafficGuard/trafficGuardConfig.component';
import {SETTINGS} from 'core/config/settings';

const angular = require('angular');

module.exports = angular
  .module('spinnaker.core.application.config.controller', [
    require('@uirouter/angularjs').default,
    require('./applicationAttributes.directive.js'),
    require('./applicationNotifications.directive.js'),
    require('./applicationCacheManagement.directive.js'),
    require('./deleteApplicationSection.directive.js'),
    require('./applicationSnapshotSection.component.js'),
    APPLICATION_DATA_SOURCE_EDITOR,
    CHAOS_MONKEY_CONFIG_COMPONENT,
    TRAFFIC_GUARD_CONFIG_COMPONENT,
    require('./links/applicationLinks.component.js'),
  ])
  .controller('ApplicationConfigController', function ($state, app) {
    this.application = app;
    this.feature = SETTINGS.feature;
    if (app.notFound) {
      $state.go('home.infrastructure', null, {location: 'replace'});
    } else {
      this.application.attributes.instancePort = this.application.attributes.instancePort || SETTINGS.defaultInstancePort || null;
    }
  });


text:
layout: post
title: "Hello world"
quote: This is the very first post of my personal website.
image: /assets/images/cover.jpg
video: false
---

#So what do we do here?

We can stick with the simple and mainstream first post for websites:

```
printf("Hello world.");
```


text:
package org.osgi.test.cases.servlet.junit;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;

import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.servlet.runtime.dto.PreprocessorDTO;
import org.osgi.service.servlet.whiteboard.HttpWhiteboardConstants;
import org.osgi.service.servlet.whiteboard.Preprocessor;
import org.osgi.test.cases.servlet.junit.mock.MockPreprocessor;
import org.osgi.test.cases.servlet.junit.mock.MockServlet;

import jakarta.servlet.FilterChain;
import jakarta.servlet.Servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponseWrapper;

/**
 * Preprocessors are introduced in 1.1
 */
public class PreprocessorTestCase extends BaseHttpWhiteboardTestCase {

	public void testPreprocessorInitParameters() throws Exception {
		Dictionary<String,Object> properties = new Hashtable<>();
		properties
				.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_PREPROCESSOR_INIT_PARAM_PREFIX
						+ "param1", "value1");
		properties
				.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_PREPROCESSOR_INIT_PARAM_PREFIX
						+ "param2", "value2");
		properties
				.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_PREPROCESSOR_INIT_PARAM_PREFIX
						+ "param3", 345l);

		long before = this.getHttpRuntimeChangeCount();
		final ServiceRegistration<Preprocessor> reg = getContext()
				.registerService(Preprocessor.class, new MockPreprocessor(),
						properties);
		this.serviceRegistrations.add(reg);
		this.waitForRegistration(before);

		final PreprocessorDTO[] dtos = this.getHttpServiceRuntime()
				.getRuntimeDTO().preprocessorDTOs;
		assertEquals(1, dtos.length);

		assertTrue(dtos[0].initParams.containsKey("param1"));
		assertTrue(dtos[0].initParams.containsKey("param2"));
		assertFalse(dtos[0].initParams.containsKey("param3"));
		assertEquals(getServiceId(reg), dtos[0].serviceId);
	}

	public void testPreprocessorRanging() throws Exception {
		// register preprocessor with ranking -5
		Dictionary<String,Object> properties = new Hashtable<>();
		properties.put(Constants.SERVICE_RANKING, -5);

		long before = this.getHttpRuntimeChangeCount();
		this.serviceRegistrations
				.add(getContext().registerService(Preprocessor.class.getName(),
						new MockPreprocessor().around("d"), properties));
		before = this.waitForRegistration(before);

		// register preprocessor with ranking 8
		properties = new Hashtable<>();
		properties.put(Constants.SERVICE_RANKING, 8);

		this.serviceRegistrations
				.add(getContext().registerService(Preprocessor.class.getName(),
						new MockPreprocessor().around("a"), properties));
		before = this.waitForRegistration(before);

		// register preprocessor with invalid ranking
		properties = new Hashtable<>();
		properties.put(Constants.SERVICE_RANKING, 3L); // this is invalid ->
														// ranking = 0

		this.serviceRegistrations
				.add(getContext().registerService(Preprocessor.class.getName(),
						new MockPreprocessor().around("b"), properties));
		before = this.waitForRegistration(before);

		// register preprocessor with no ranking
		properties = new Hashtable<>();

		this.serviceRegistrations
				.add(getContext().registerService(Preprocessor.class.getName(),
						new MockPreprocessor().around("c"), properties));
		before = this.waitForRegistration(before);

		// check that we have four preprocessors
		final PreprocessorDTO[] dtos = this.getHttpServiceRuntime()
				.getRuntimeDTO().preprocessorDTOs;
		assertEquals(4, dtos.length);

		// register endpoint
		final String path = "/available";
		properties = new Hashtable<>();
		properties.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN,
				path);
		this.serviceRegistrations.add(getContext().registerService(
				Servlet.class, new MockServlet().content("hello"), properties));

		assertEquals("abcdhellodcba", request(path));
	}

	/**
	 * Test a request with a servlet registered at that url and check if the
	 * preprocessor is invoked. Do the same with a non existing url.
	 */
	public void testPreprocessorInvocation() throws Exception {
		// register preprocessor
		final List<String> filterActions = new ArrayList<>();
		long before = this.getHttpRuntimeChangeCount();
		this.serviceRegistrations.add(getContext().registerService(
				Preprocessor.class.getName(), new MockPreprocessor() {

					@Override
					public void doFilter(ServletRequest request,
							ServletResponse response, FilterChain chain)
							throws IOException, ServletException {
						filterActions.add("a");
						super.doFilter(request, new HttpServletResponseWrapper(
								(HttpServletResponse) response) {

							private boolean hasStatus = false;

							private void addStatus(final int sc) {
								if (!hasStatus) {
									hasStatus = true;
									filterActions.add(String.valueOf(sc));
								}
							}

							@Override
							public void setStatus(int sc) {
								addStatus(sc);
								super.setStatus(sc);
							}

							@Override
							public void sendError(int sc, String msg)
									throws IOException {
								addStatus(sc);
								super.sendError(sc, msg);
							}

							@Override
							public void sendError(int sc) throws IOException {
								addStatus(sc);
								super.sendError(sc);
							}

						}, chain);
						filterActions.add("b");
					}

				}, null));
		before = this.waitForRegistration(before);

		// register endpoint
		final String path = "/available";
		Dictionary<String,Object> properties = new Hashtable<>();
		properties.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN,
				path);
		this.serviceRegistrations.add(getContext().registerService(
				Servlet.class, new MockServlet().content("hello"), properties));

		assertEquals("hello", request(path));
		assertEquals(2, filterActions.size());
		assertEquals("a", filterActions.get(0));
		assertEquals("b", filterActions.get(1));

		// request a non existing pattern - this will somehow set the status
		// code to 404
		filterActions.clear();
		request("/foo");
		assertEquals(3, filterActions.size());
		assertEquals("a", filterActions.get(0));
		assertEquals("404", filterActions.get(1));
		assertEquals("b", filterActions.get(2));
	}
}


text:
package StrgWar.gui;

import StrgWar.core.IPlayerColorProvider;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.Pane;

public interface IDrawable
{
	void Draw(GraphicsContext gc, Pane root, IPlayerColorProvider playerColorProvider, long now);
}


text:
package com.intel.analytics.bigdl.nn

import com.intel.analytics.bigdl.nn.abstractnn.{IdentityOutputShape, TensorModule}
import com.intel.analytics.bigdl.tensor.Tensor
import com.intel.analytics.bigdl.tensor.TensorNumericMath.TensorNumeric

import scala.reflect.ClassTag

/**
 * Apply SoftSign function to an n-dimensional input Tensor.
 *
 * SoftSign function: f_i(x) = x_i / (1+|x_i|)
 */

@SerialVersionUID(- 3936698382129844874L)
class SoftSign[T: ClassTag]()
    (implicit ev: TensorNumeric[T])
  extends TensorModule[T] {

  @transient private var temp: Tensor[T] = null
  @transient private var tempGrad: Tensor[T] = null

  output = Tensor[T]()
  gradInput = Tensor[T]()

  override def updateOutput(input: Tensor[T]): Tensor[T] = {
    if (null == temp) {
      temp = input.clone()
    } else {
      temp.resizeAs(input).copy(input)
    }
    temp.abs().add(ev.fromType[Int](1))
    output.resizeAs(input).copy(input).cdiv(temp)
    output
  }

  override def updateGradInput(input: Tensor[T], gradOutput: Tensor[T]): Tensor[T] = {
    if (null == tempGrad) {
      tempGrad = input.clone()
    } else {
      tempGrad.resizeAs(output).copy(input)
    }
    tempGrad.abs().add(ev.fromType[Int](1)).cmul(tempGrad)
    gradInput.resizeAs(input).copy(gradOutput).cdiv(tempGrad)
    gradInput
  }
}

object SoftSign {
  def apply[@specialized(Float, Double) T: ClassTag]()
      (implicit ev: TensorNumeric[T]) : SoftSign[T] = {
    new SoftSign[T]()
  }
}


text:
#import <Cocoa/Cocoa.h>

//#import "IDEIndexDatabaseDelegate-Protocol.h"

@class DVTDispatchLock, DVTFilePath, IDEIndexDatabase, IDEIndexQPManager, IDEIndexingEngine, IDEIndexingPrebuildController, IDEWorkspace, NSDate, NSMutableDictionary, NSSet, NSString;

@interface IDEIndex : NSObject /*<IDEIndexDatabaseDelegate>*/
{
    IDEWorkspace *_workspace;
    DVTFilePath *_databaseFile;
    IDEIndexingPrebuildController *_prebuildController;
    IDEIndexingEngine *_engine;
    IDEIndexQPManager *_qpManager;
    NSMutableDictionary *_identifiersToIndexables;
    NSMutableDictionary *_indexablesToProductHeaders;
    NSMutableDictionary *_copiedHeadersToSources;
    NSMutableDictionary *_sourceHeadersToIndexables;
    NSSet *_preferredTargets;
    NSSet *_priorityTargets;
    IDEIndexDatabase *_workspaceDatabase;
    long long _purgeCount;
    DVTDispatchLock *_stateLock;
    DVTDispatchLock *_pchCreationLock;
    NSMutableDictionary *_pchFiles;
    NSDate *_lastErrorTime;
    BOOL _isInvalid;
    BOOL _isCancelled;
    BOOL _isInErrorRecoveryMode;
    BOOL _isReadOnly;
    BOOL _cleanedUpOldPCHs;
    BOOL _didSetKeyPathObservers;
    id _indexableFileWasAddedNotificationObservingToken;
    id _indexableFileWillBeRemovedNotificationObservingToken;
    id _indexableDidRenameFileNotificationObservingToken;
    id _buildablesDidChangeNotificationObservingToken;
    id _buildSettingsDidChangeNotificationObservingToken;
    id _buildOperationDidStopNotificationObservingToken;
}

+ (BOOL)languageSupportsSymbolColoring:(id)arg1;
+ (id)resolutionForName:(id)arg1 kind:(id)arg2 containerName:(id)arg3;
+ (id)pathToClang;
+ (id)_dataSourceExtensionForFile:(id)arg1 withLanguage:(id)arg2;
+ (void)createIndexForWorkspace:(id)arg1 withState:(id)arg2;
+ (id)_databaseFolderForWorkspace:(id)arg1;
+ (void)syncPerformBlockOnMainThread:(id)arg1;
+ (void)initialize;
+ (BOOL)includeAutoImportResults;
+ (id)schedulingLogAspect;
+ (id)clangInvocationLogAspect;
+ (id)symbolAdditionLogAspect;
+ (id)deferredMetricLogAspect;
+ (id)metricLogAspect;
+ (id)logAspect;
@property(readonly) IDEIndexingPrebuildController *prebuildController; // @synthesize prebuildController=_prebuildController;
@property(readonly, nonatomic) DVTFilePath *databaseFile; // @synthesize databaseFile=_databaseFile;
@property(readonly, nonatomic) IDEIndexDatabase *database; // @synthesize database=_workspaceDatabase;
@property(readonly, nonatomic) IDEWorkspace *workspace; // @synthesize workspace=_workspace;
//- (void).cxx_destruct;
- (id)symbolDumpForFile:(id)arg1;
- (id)targetIdentifiersForFile:(id)arg1;
- (id)mainFilesForFile:(id)arg1;
- (id)sdkForFile:(id)arg1;
- (id)timestampForFile:(id)arg1;
- (void)_buildOperationDidStop:(id)arg1;
- (void)_buildSettingsDidChange:(id)arg1;
- (void)_activeRunDestinationDidChange:(id)arg1;
- (void)_activeRunContextDidChange:(id)arg1;
- (void)_clearAllCachedBuildSettings;
- (void)_computePreferredTargets;
- (BOOL)isPreferredTarget:(id)arg1 priority:(char *)arg2;
- (BOOL)isPreferredTarget:(id)arg1;
- (id)databaseQueryProvider;
- (id)queryProviderForLocation:(id)arg1 highPriority:(BOOL)arg2;
- (void)dontDeferJobForFile:(id)arg1 indexable:(id)arg2;
- (void)registerHotFile:(id)arg1;
- (id)queryProviderForFile:(id)arg1 highPriority:(BOOL)arg2;
- (id)resolutionForName:(id)arg1 kind:(id)arg2 containerName:(id)arg3;
- (id)indexableForCopiedHeader:(id)arg1;
- (id)originalPathsForPaths:(id)arg1;
- (id)effectivePathForHeader:(id)arg1;
- (void)_initCopiedHeaders;
- (void)indexModuleIfNeeded:(id)arg1 settings:(id)arg2;
- (void)indexModuleIfNeeded:(id)arg1;
- (void)_cleanupOldPCHs;
- (void)didCancelIndexingPCHFile:(id)arg1;
- (BOOL)createPCHFile:(id)arg1 arguments:(id)arg2 hashCriteria:(id)arg3 target:(id)arg4 session:(id)arg5 willIndex:(BOOL)arg6 translationUnit:(id *)arg7;
- (void)database:(id)arg1 reportAutoQueryProgress:(double)arg2;
- (void)clearPCHFailuresForDatabase:(id)arg1;
- (void)databaseDidReportError:(id)arg1;
- (void)databaseDidLoad:(id)arg1;
- (void)databaseDidOpen:(id)arg1;
- (id)databaseProvidersAndVersions:(id)arg1;
- (void)database:(id)arg1 didForgetFiles:(id)arg2;
- (void)database:(id)arg1 didEndImportSession:(id)arg2;
- (void)databaseDidSave:(id)arg1;
- (void)databaseDidIndexHotFile:(id)arg1;
- (void)_respondToFileChangeNotification:(id)arg1;
@property(readonly, nonatomic) DVTFilePath *workspaceFile;
@property(readonly, nonatomic) NSString *workspaceName;
- (id)dataSourceExtensionForFile:(id)arg1 settings:(id)arg2;
- (id)_dataSourceExtensionForFile:(id)arg1 withSettings:(id)arg2;
- (id)settingsForFile:(id)arg1 indexable:(id)arg2;
- (id)_waitForSettingsForFile:(id)arg1 object:(id)arg2;
- (id)_waitForSettingsFromObject:(id)arg1;
- (void)waitForBuildSystem:(id)arg1;
- (id)workspaceHeadersForIndexable:(id)arg1;
- (void)gatherProductHeadersForIndexable:(id)arg1;
- (long long)purgeCount;
- (void)purgeFileCaches;
- (void)close;
- (void)editorWillSaveFile:(id)arg1;
- (void)expediteIndexing;
- (void)_stopIndexing;
- (void)setThrottleFactor:(double)arg1;
- (void)resumeIndexing;
- (void)suspendIndexing;
@property(readonly, nonatomic) BOOL shouldAllowRefactoring;
@property(readonly, nonatomic) BOOL isQuiescent;
- (void)doWhenFilesReady:(id)arg1;
- (void)willRegisterMoreFiles:(BOOL)arg1;
- (void)unregisterFile:(id)arg1;
- (void)registerFile:(id)arg1;
- (id)indexableForIdentifier:(id)arg1;
- (void)unregisterObject:(id)arg1;
- (void)registerObject:(id)arg1;
- (void)postNotificationName:(id)arg1;
- (void)postNotificationName:(id)arg1 userInfo:(id)arg2;
- (id)description;
- (void)setIndexState:(id)arg1;
- (id)indexState;
@property(readonly) DVTFilePath *workspaceBuildProductsDirPath;
@property(readonly) DVTFilePath *headerMapFilePath;
- (void)observeValueForKeyPath:(id)arg1 ofObject:(id)arg2 change:(id)arg3 context:(void *)arg4;
- (void)setKeyPathObservers:(id)arg1;
- (BOOL)isCurrentForWorkspace:(id)arg1;
- (void)beginTextIndexing;
- (id)initWithFolder:(id)arg1;
- (id)initWithFolder:(id)arg1 forWorkspace:(id)arg2 withState:(id)arg3;
- (void)_cleanupOldIndexFoldersForWorkspace:(id)arg1;
- (double)_atime:(struct stat *)arg1;
- (BOOL)_stat:(struct stat *)arg1 filePath:(id)arg2;
- (id)_databaseFileURLForFolder:(id)arg1;
- (id)_databaseFolderForWorkspace:(id)arg1;
- (BOOL)_reopenDatabaseWithRemoval:(BOOL)arg1;
- (BOOL)_createDatabaseFolder;
- (void)_setupObservers;
- (id)allAutoImportItemsMatchingKind:(id)arg1 symbolLanguage:(id)arg2;
- (id)allAutoImportItemsMatchingKind:(id)arg1;
- (id)filesWithSymbolOccurrencesMatchingName:(id)arg1 kind:(id)arg2;
- (id)classesWithReferencesToSymbols:(id)arg1;
- (id)allClassesWithMembers:(id)arg1;
- (id)classesWithMembers:(id)arg1;
- (id)allMethodsMatchingMethod:(id)arg1 forReceiver:(id)arg2;
- (id)membersMatchingName:(id)arg1 kinds:(id)arg2 forInterfaces:(id)arg3;
- (id)membersMatchingKinds:(id)arg1 forInterfaces:(id)arg2;
- (id)symbolsForResolutions:(id)arg1;
- (id)parsedCodeCommentAtLocation:(id)arg1 withCurrentFileContentDictionary:(id)arg2;
- (id)codeDiagnosticsAtLocation:(id)arg1 withCurrentFileContentDictionary:(id)arg2;
- (id)codeCompletionsAtLocation:(id)arg1 withCurrentFileContentDictionary:(id)arg2 completionContext:(id *)arg3;
- (id)allParentsOfSymbols:(id)arg1 cancelWhen:(id)arg2;
- (id)topLevelSymbolsInFile:(id)arg1;
- (unsigned long long)countOfSymbolsMatchingKind:(id)arg1 workspaceOnly:(BOOL)arg2;
- (id)allSymbolsMatchingKind:(id)arg1 workspaceOnly:(BOOL)arg2 cancelWhen:(id)arg3;
- (id)allSymbolsMatchingKind:(id)arg1 workspaceOnly:(BOOL)arg2;
- (id)allSymbolsMatchingKind:(id)arg1;
- (id)testMethodsForClasses:(id)arg1;
- (id)allSubClassesForClasses:(id)arg1;
- (id)allSymbolsMatchingNames:(id)arg1 kind:(id)arg2;
- (id)allSymbolsMatchingName:(id)arg1 kind:(id)arg2;
- (id)allProtocolsMatchingName:(id)arg1;
- (id)allClassesMatchingName:(id)arg1;
- (id)impliedHeadersForModuleImportLocation:(id)arg1 withCurrentFileContentDictionary:(id)arg2;
- (id)importedFileAtDocumentLocation:(id)arg1 withCurrentFileContentDictionary:(id)arg2;
- (id)importedFilesAtDocument:(id)arg1 withCurrentFileContentDictionary:(id)arg2;
- (id)collectionElementTypeSymbolForSymbol:(id)arg1 withCurrentFileContentDictionary:(id)arg2;
- (id)typeSymbolForSymbol:(id)arg1 withCurrentFileContentDictionary:(id)arg2;
- (id)messageReceiverInContext:(id)arg1 withCurrentFileContentDictionary:(id)arg2;
- (id)referencesToSymbolMatchingName:(id)arg1 inContext:(id)arg2 withCurrentFileContentDictionary:(id)arg3;
- (id)referencesToSymbol:(id)arg1 inContext:(id)arg2 withCurrentFileContentDictionary:(id)arg3;
- (id)symbolsUsedInContext:(id)arg1 withCurrentFileContentDictionary:(id)arg2;
- (id)symbolsOccurrencesInContext:(id)arg1 withCurrentFileContentDictionary:(id)arg2;
- (id)symbolsMatchingName:(id)arg1 inContext:(id)arg2 withCurrentFileContentDictionary:(id)arg3;
- (id)symbolsMatchingName:(id)arg1 inContext:(id)arg2;
- (id)symbolsContaining:(id)arg1 anchorStart:(BOOL)arg2 anchorEnd:(BOOL)arg3 subsequence:(BOOL)arg4 ignoreCase:(BOOL)arg5 cancelWhen:(id)arg6;
- (id)symbolsContaining:(id)arg1 anchorStart:(BOOL)arg2 anchorEnd:(BOOL)arg3 subsequence:(BOOL)arg4 ignoreCase:(BOOL)arg5;
- (id)topLevelProtocolsWorkspaceOnly:(BOOL)arg1 cancelWhen:(id)arg2;
- (id)topLevelProtocolsWorkspaceOnly:(BOOL)arg1;
- (id)topLevelProtocols;
- (id)topLevelClassesWorkspaceOnly:(BOOL)arg1 cancelWhen:(id)arg2;
- (id)topLevelClassesWorkspaceOnly:(BOOL)arg1;
- (id)topLevelClasses;
- (id)filesContaining:(id)arg1 anchorStart:(BOOL)arg2 anchorEnd:(BOOL)arg3 subsequence:(BOOL)arg4 ignoreCase:(BOOL)arg5 cancelWhen:(id)arg6;
- (id)filesIncludedByFile:(id)arg1;
- (id)filesIncludingFile:(id)arg1;
- (id)mainFileForSelectionFilePath:(id)arg1 buildSettings:(id *)arg2;
- (id)objCOrCCompilationUnitIndexablesForMainFile:(id)arg1 indexableObjects:(id)arg2;
- (BOOL)isFileObjCCompilationUnitOrHeader:(id)arg1 error:(id *)arg2;
- (id)_localizedPhraseForDependentObjCCompilationUnit:(id)arg1 errorLanguages:(id)arg2 sharedLanguageIdentifier:(id)arg3 sharedIndexableObject:(id)arg4;
- (id)_localizedDescriptionForObjCCompilationUnit:(id)arg1 errorLanguages:(id)arg2;
- (BOOL)_errorLanguages:(id *)arg1 forFilePath:(id)arg2 indexableObjects:(id)arg3;

@end


text:
import json
import logging

from pika import exceptions

from sprockets.mixins import amqp
from tests import base

LOGGER = logging.getLogger(__name__)

class ConfirmationsDisabledMixinTestCase(base.AsyncHTTPTestCase):

    def get_install_kwargs(self):
        return {'enable_confirmations': False}

    def test_mixin_invokes_amqp_publish(self):
        with self.mock_publish() as publish:
            response = self.fetch('/', headers=self.headers)
            parameters = json.loads(response.body.decode('utf-8'))
            self.assertEqual(publish.call_args[0][0], parameters['exchange'])
            self.assertEqual(publish.call_args[0][1],
                             parameters['routing_key'])
            self.assertEqual(publish.call_args[0][2], parameters['body'])
            for key, expectation in parameters['properties'].items():
                self.assertEqual(getattr(publish.call_args[0][3], key),
                                 expectation)

    def test_not_ready_raised(self):
        self.client.state = amqp.Client.STATE_BLOCKED
        with self.mock_publish():
            response = self.fetch('/', headers=self.headers)
            result = json.loads(response.body.decode('utf-8'))
            error_expectation = amqp.NotReadyError.fmt.format(
                self.client.state_description,
                result['parameters']['properties']['message_id'])
            self.assertEqual(result['error'], error_expectation)
            self.assertEqual(result['type'], 'NotReadyError')

class ConfirmationsEnabledMixinTestCase(base.AsyncHTTPTestCase):

    def test_mixin_invokes_amqp_publish(self):
        with self.mock_publish(side_effect=self.send_ack) as publish:
            response = self.fetch('/', headers=self.headers)
            parameters = json.loads(response.body.decode('utf-8'))
            self.assertEqual(publish.call_args[0][0], parameters['exchange'])
            self.assertEqual(publish.call_args[0][1],
                             parameters['routing_key'])
            self.assertEqual(publish.call_args[0][2], parameters['body'])
            for key, expectation in parameters['properties'].items():
                self.assertEqual(getattr(publish.call_args[0][3], key),
                                 expectation)

    def test_mixin_amqp_publish_without_correlation_id(self):
        with self.mock_publish(side_effect=self.send_ack) as publish:
            response = self.fetch('/')
            parameters = json.loads(response.body.decode('utf-8'))
            self.assertEqual(publish.call_args[0][0],
                             parameters['exchange'])
            self.assertEqual(publish.call_args[0][1],
                             parameters['routing_key'])
            self.assertEqual(publish.call_args[0][2], parameters['body'])
            for key, expectation in parameters['properties'].items():
                self.assertEqual(getattr(publish.call_args[0][3], key),
                                 expectation)
            self.assertIsNone(publish.call_args[0][3].correlation_id)

    def test_not_ready_raised(self):
        self.client.state = amqp.Client.STATE_BLOCKED
        with self.mock_publish():
            response = self.fetch('/', headers=self.headers)
            result = json.loads(response.body.decode('utf-8'))
            error_expectation = amqp.NotReadyError.fmt.format(
                self.client.state_description,
                result['parameters']['properties']['message_id'])
            self.assertEqual(result['error'], error_expectation)
            self.assertEqual(result['type'], 'NotReadyError')

    def test_publishing_failure_raised(self):
        with self.mock_publish(side_effect=exceptions.AMQPChannelError()):
            response = self.fetch('/', headers=self.headers)
            result = json.loads(response.body.decode('utf-8'))
            error_expectation = amqp.PublishingFailure.fmt.format(
                result['parameters']['properties']['message_id'],
                result['parameters']['exchange'],
                result['parameters']['routing_key'],
                exceptions.AMQPChannelError.__name__)
            self.assertEqual(result['error'], error_expectation)
            self.assertEqual(result['type'], 'PublishingFailure')


text:
<!DOCTYPE html>

    <title>Problem 3. Occurrences of word</title>

Problem 3. Occurrences of word

Please Press F12 (in Chrome) to see the output in the console

You may want to edit OccurrencesOfWord.js to test different scenarios


text:
api
===
project defining the REST API itself. See api/api.json for a full
description of the API.

www
===
project defining the web application

Generated Code
==============
The .apidoc file lists the specific targets which are generated by
apidoc. To regenerate code, clone github.com/mbryzek/apidoc-cli and

    apidoc update

Database
========

    psql -c "create role api login createdb" postgres
    psql -U api -c "CREATE DATABASE apidoc-test-light" postgres

Database
========

In one screen:

    $ sbt
    sbt> project api
    sbt> run 9001

In another screen:

    $ sbt
    sbt> project www
    sbt> run

Goto http://localhost:9000 in your browser


text:
static std::vector<std::string> list_files(const std::string &directory) {
  std::vector<std::string> result;
  DIR *dir;
  struct dirent *ent;
  dir = opendir(directory.c_str());
  if (dir != NULL) {
    while ((ent = readdir(dir)) != NULL) {
      std::string file = ent->d_name;
      if (file != "." && file != "..")
        result.push_back(ent->d_name);
    }
    closedir(dir);
  }
  return result;
}


text:
  Charly-Oradour est
       un village
       géographiquement positionné dans le département de Moselle en Lorraine. Elle totalisait 632 habitants en 2008.

Charly-Oradour est localisé à seulement 8 Kilomètres de Metz, les élèves qui aurons besoin de se loger à pas cher pourront envisager de prendre un appartement à Charly-Oradour. Charly-Oradour est aussi un bon investissement locatif a cause de sa proximité de Metz et de ses Universités. Il sera facile de trouver un logement à acheter.

À Charly-Oradour, le prix moyen à la vente d'un appartement se situe à 976 € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 700 € du m². À la location le prix moyen se situe à 6,9 € du m² par mois.

La commune offre quelques  équipements, elle propose entre autres un terrain de sport.

Le parc d'habitations, à Charly-Oradour, se décomposait en 2011 en 17 appartements et 238 maisons soit
 un marché relativement équilibré.

À proximité de Charly-Oradour sont positionnées géographiquement les villes de
Vany à 1 km, 338 habitants,
Failly localisée à 2 km, 566 habitants,
Sanry-lès-Vigy à 3 km, 530 habitants,
Servigny-lès-Sainte-Barbe localisée à 3 km, 430 habitants,
Antilly à 2 km, 115 habitants,
Chailly-lès-Ennery localisée à 3 km, 336 habitants,
 entre autres. De plus, Charly-Oradour est située à seulement huit km de Metz.

Si vous envisagez de demenager à Charly-Oradour, vous pourrez facilement trouver une maison à acheter.


text:
package org.codehaus.griffon.runtime.core;

import griffon.core.Context;
import griffon.core.ContextFactory;

import javax.inject.Inject;
import javax.inject.Provider;

/**
 * @author Andres Almiray
 * @since 2.2.0
 */
public class DefaultContextProvider implements Provider<Context> {
    @Inject
    private ContextFactory contextFactory;

    @Override
    public Context get() {
        return contextFactory.create(null);
    }
}


text:
using System;
using System.Data.SqlClient;
using bv.model.BLToolkit;
using eidss.model.Reports;
using eidss.model.Reports.GG;
using EIDSS.Reports.BaseControls.Report;

namespace EIDSS.Reports.Parameterized.Human.GG.Report
{
    [CanWorkWithArchive]
    [NullableAdapters]
    public partial class SerologyResearchCardReport : BaseSampleReport
    {
        public SerologyResearchCardReport()
        {
            InitializeComponent();
        }

        public override void SetParameters(HumanLabSampleModel model, DbManagerProxy manager, DbManagerProxy archiveManager)
        {
            AjustDateBindings(model.Language, "SerologyResearchCard.datSampleReceived", ReceivedMonthCell, ReceivedDayCell);
            AjustDateBindings(model.Language, "SerologyResearchCard.datSampleCollected", CollectedMonthCell, CollectedDayCell);
            AjustDateBindings(model.Language, "SerologyResearchCard.datResultDate", TestMonthCell, TestDayCell);

            base.SetParameters(model, manager, archiveManager);

              Action<SqlConnection, SqlTransaction> action = ((connection, transaction) =>
            {
                m_Adapter.Connection = connection;
                m_Adapter.Transaction = transaction;
                m_Adapter.CommandTimeout = CommandTimeout;

                m_DataSet.EnforceConstraints = false;
                m_Adapter.Fill(
                    m_DataSet.SerologyResearchCard,
                    model.Language,
                    model.SampleId,
                    model.LastName,
                    model.FirstName,
                    model.SiteId);
            });

            const string keyName = "strKey";

            FillDataTableWithArchive(action,
                manager, archiveManager,
                m_DataSet.SerologyResearchCard,
                model.Mode,
                new[] {keyName});

            m_DataSet.SerologyResearchCard.DefaultView.Sort = keyName;
        }
    }
}


text:
package com.alibaba.dubbo.config.spring.context.annotation;

import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;

import java.util.Set;

import static org.springframework.context.annotation.AnnotationConfigUtils.registerAnnotationConfigProcessors;

/**
 * Dubbo {@link ClassPathBeanDefinitionScanner} that exposes some methods to be public.
 *
 * @author Mercy
 * @see #doScan(String...)
 * @see #registerDefaultFilters()
 * @since 2.5.7
 */
public class DubboClassPathBeanDefinitionScanner extends ClassPathBeanDefinitionScanner {

    public DubboClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters, Environment environment,
                                               ResourceLoader resourceLoader) {

        super(registry, useDefaultFilters);

        setEnvironment(environment);

        setResourceLoader(resourceLoader);

        registerAnnotationConfigProcessors(registry);

    }

    public DubboClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, Environment environment,
                                               ResourceLoader resourceLoader) {

        this(registry, false, environment, resourceLoader);

    }

    public Set<BeanDefinitionHolder> doScan(String... basePackages) {
        return super.doScan(basePackages);
    }

}


text:
from __future__ import print_function

import re
import numpy as np
import numpy.testing as npt

import logging
logging.basicConfig(level=logging.DEBUG)

import unittest

# import the module
import tomographer.mhrwtasks
import tomographer

class MHRWTasksStuff(unittest.TestCase):
    def test_fields(self):

        def prg_callback(x):
            print(x.getHumanReport())

        # just run tomorun on some arbitrary data to get some stuff to check
        mhrw_params = tomographer.MHRWParams(
            step_size=0.04,
            n_sweep=25,
            n_run=8192,
            n_therm=500)
        hist_params = tomographer.HistogramParams(0.985, 1, 20)
        binning_num_levels = 7
        r = tomographer.tomorun.tomorun(
            dim=2,
            Emn=[
                np.array([[0.5, -0.5j],
                          [0.5j, 0.5]]),
                np.array([[0.5, 0.5j],
                          [-0.5j, 0.5]])
            ],
            Nm=np.array([ 500, 0 ]),
            fig_of_merit="obs-value",
            observable=np.array([[0.5, -0.5j],
                                [0.5j, 0.5]]),
            num_repeats=2,
            binning_num_levels=binning_num_levels,
            mhrw_params=mhrw_params,
            hist_params=hist_params,
            ctrl_step_size_params={'enable': False},
            progress_interval_ms=500,
            progress_fn=prg_callback,
        )

        # check that all fields are there and display meaningful values

        runres = r['runs_results'][0]
        self.assertAlmostEqual(runres.mhrw_params.mhwalker_params["step_size"],
                               mhrw_params.mhwalker_params["step_size"])
        self.assertEqual(runres.mhrw_params.n_sweep, mhrw_params.n_sweep)
        self.assertEqual(runres.mhrw_params.n_therm, mhrw_params.n_therm)
        self.assertEqual(runres.mhrw_params.n_run, mhrw_params.n_run)

        self.assertGreater(runres.acceptance_ratio, 0.2)
        self.assertLess(runres.acceptance_ratio, 0.4)

        stats_results = runres.stats_results

        self.assertEqual(stats_results.histogram.numBins(), hist_params.num_bins)

        npt.assert_array_equal(stats_results.error_levels.shape,
                               [hist_params.num_bins, binning_num_levels+1])
        # the last error level should be the reported error bar:
        npt.assert_array_almost_equal(stats_results.error_levels[:, binning_num_levels],
                                      stats_results.histogram.delta)

        for c in stats_results.converged_status:
            self.assertIn(c, (tomographer.BinningAnalysis.CONVERGED,
                              tomographer.BinningAnalysis.NOT_CONVERGED,
                              tomographer.BinningAnalysis.UNKNOWN_CONVERGENCE) )

    def test_binningbarssummary(self):

        x = tomographer.BinningErrorBarConvergenceSummary()
        self.assertEqual(x.n_bins, 0)
        self.assertEqual(x.n_converged, 0)
        self.assertEqual(x.n_unknown, 0)
        self.assertEqual(x.n_unknown_isolated, 0)
        self.assertEqual(x.n_not_converged, 0)

        x = tomographer.BinningErrorBarConvergenceSummary(n_bins=1,n_converged=2,n_unknown=3,
                                                          n_unknown_isolated=4,n_not_converged=5)
        self.assertEqual(x.n_bins, 1)
        self.assertEqual(x.n_converged, 2)
        self.assertEqual(x.n_unknown, 3)
        self.assertEqual(x.n_unknown_isolated, 4)
        self.assertEqual(x.n_not_converged, 5)

    def test_pickle(self):
        hist = tomographer.HistogramWithErrorBars(0, 1, 3)
        stats_results = tomographer.ValueHistogramWithBinningMHRWStatsCollectorResult(
            hist,
            np.array([ [ 1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]),
            np.array([tomographer.BinningAnalysis.CONVERGED,
                      tomographer.BinningAnalysis.NOT_CONVERGED,
                      tomographer.BinningAnalysis.UNKNOWN_CONVERGENCE])
        )
        mhrw_task_result = tomographer.mhrwtasks.MHRandomWalkTaskResult(
            stats_results,
            tomographer.MHRWParams(0.03, 37, 400, 65538),
            0.27
        )
        # see http://pybind11.readthedocs.io/en/master/advanced/classes.html#pickling-support
        try:
            import cPickle as pickle
        except:
            import pickle
        s = pickle.dumps(mhrw_task_result,2)
        print("PICKLE:\n"+str(s))
        mhrw_task_result2 = pickle.loads(s)

        m = mhrw_task_result
        m2 = mhrw_task_result2
        self.assertAlmostEqual(m.acceptance_ratio, m2.acceptance_ratio)
        self.assertAlmostEqual(m.mhrw_params.mhwalker_params, m2.mhrw_params.mhwalker_params)
        self.assertEqual(m.mhrw_params.n_sweep, m2.mhrw_params.n_sweep)
        self.assertEqual(m.mhrw_params.n_therm, m2.mhrw_params.n_therm)
        self.assertEqual(m.mhrw_params.n_run, m2.mhrw_params.n_run)
        npt.assert_array_almost_equal(m.stats_results.histogram.bins, m2.stats_results.histogram.bins)
        npt.assert_array_almost_equal(m.stats_results.histogram.delta, m2.stats_results.histogram.delta)
        npt.assert_array_almost_equal(m.stats_results.error_levels, m2.stats_results.error_levels)
        npt.assert_array_equal(m.stats_results.converged_status, m2.stats_results.converged_status)

        summary = m2.stats_results.errorBarConvergenceSummary()
        self.assertEqual(summary.n_bins, m.stats_results.histogram.numBins())
        self.assertEqual(summary.n_converged, 1)
        self.assertEqual(summary.n_unknown, 1)
        self.assertEqual(summary.n_unknown_isolated, 0)
        self.assertEqual(summary.n_not_converged, 1)

        # pickle the summary itself?
        s2 = pickle.dumps(summary,2)
        print("PICKLE OF SUMMARY:\n"+str(s2))
        summary2 = pickle.loads(s2)
        self.assertEqual(summary2.n_bins, m.stats_results.histogram.numBins())
        self.assertEqual(summary2.n_converged, 1)
        self.assertEqual(summary2.n_unknown, 1)
        self.assertEqual(summary2.n_unknown_isolated, 0)
        self.assertEqual(summary2.n_not_converged, 1)

#

# normally, this is not needed as we are being run via pyruntest.py, but it might be
# useful if we want to run individually picked tests
if __name__ == '__main__':
    unittest.main()


text:
/* @flow */

import {
  isPreTag, // <pre>
  mustUseProp,
  isReservedTag,
  getTagNamespace
} from '../util/index'

import modules from './modules/index'
import directives from './directives/index'
import { genStaticKeys } from 'shared/util'
import { isUnaryTag, canBeLeftOpenTag } from './util'

export const baseOptions: CompilerOptions = {
  expectHTML: true,
  modules,
  directives, // 这里包括 model(v-model)、html(v-html)、text(v-text) 三个指令。
  isPreTag, // 函数,判断是否是 pre 标签
  isUnaryTag, // 是否是单标签, 比如 img/input/iframe 等
  mustUseProp, // 函数,判断标签中需要使用 props 绑定的属性, 比如 <option> 的 selected 属性,<input> 的 checked 属性等
  canBeLeftOpenTag, // 可以不闭合的标签, 比如 tr/td 等
  isReservedTag, // 是否是保留标签, html 标签和 SVG 标签
  getTagNamespace, // 获取命名空间, svg 和 math
  staticKeys: genStaticKeys(modules) // 静态关键词, 包括 staticClass, staticStyle
}


text:
import os

BASE_DIR = os.path.dirname(os.path.dirname(__file__))

SECRET_KEY = 'test-key'

DEBUG = True

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
        'OPTIONS': {
            'debug': True,
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.template.context_processors.static',
                'django.template.context_processors.media',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

SITE_ID = 1

INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'invite'
]

MIDDLEWARE = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'tests.urls'

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/static/'


text:
.slidedeck-content-source ul.content-source-fields li input#options-dribbble_username {
	min-width: 200px;
	width: 200px;
}


text:
using Equin.ApplicationFramework;
using KnowledgeBase.DTOs;
using RolePlayCharacter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace IntegratedAuthoringToolWF.Metabeliefs
{
    public partial class MetaBeliefForm : Form
    {
        private RolePlayCharacterAsset rpc;

        public MetaBeliefForm(RolePlayCharacterAsset _rpc)
        {
            InitializeComponent();
            this.rpc = _rpc;
            dataGridViewAgentInspector.DataSource = new BindingListView<DynamicPropertyDTO>(_rpc.GetAllDynamicProperties().ToList());
        }
    }
}


text:
layout: layouts/session/index.njk
title: What's new in DevTools?
speakers:
  - jecelyn-yeen
start: 2020/12/10 09:39
end: 2020/12/10 09:50
description: This session gives an overview of the latest and greatest features in Chrome DevTools.
youtubeId: QsOF9SJJdAA
---

This session gives an overview of the latest and greatest features in Chrome DevTools.


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
	"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

	<title>Fx Demo</title>
	<link rel="stylesheet" href="../Assets/global.css" type="text/css" charset="utf-8">

Fx Demo

		Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididun
		ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
		laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
		voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
		cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


text:
title: What's New in Bolt 1.x?
---

- Docs Improvements
- Code Improvements
- Testing Coverage
- Brand New `@bolt/build-tools`, CLI Tool
- Component Schemas
- Continuous Integration & Publishing Improvements
- Twig Templates & Drupal Integration
- Source of Truth Separate from `Apps`

## Docs Improvements
- Brand new [Bolt site](https://boltdesignsystem.com)!
- [Quick Start Guide](/docs/guides/quick-start-guide.html) now available
- Pattern Lab Docs Reinvented
  - Component-specific docs now baked into Pattern Lab, powered by the component's `README.md`
  - Edit Markdown docs in Github directly from Pattern Lab

## Code Improvements
### Package Consolidation
- Many many many packages merged together: went from around ~130 packages down to around 50
	* Polyfill loader now targets features more closely

### New and updated components:
- Refactored navbar / nav / navlink
- Dropdown
- Tooltip
- Share
- Video component refactored: options for autoplay, loop and hiding controls now added
- Major refactor of the Image component
- Band, button, device viewer, dropdown, nav, navlink, and ratio object components now all powered by the same internal base component class
- Forms

 ### New utility classes
- Opacity
- Display
- Height
- z-index
- Box Shadow

### New Twig extensions added
- Schema validate function (see Schemas)
- Assets (inline and reference assets from Webpack)
- `console_log`
- Bolt maninfest

### Major Refactor of Twig Extensions
- Broken out into separate Bolt Core PHP package
- Twig extensions broken down into PHP Classes
- Pick and choose twig extensions (including overriding) in PL

### Bolt Data
- Global Bolt data is now console logged for debugging
- `get_data` Twig extension added

## Testing Coverage
- 1st set of PHP unit tests added for Bolt Core PHP
- End to End Integration Tests
- Linting v2: starting to programmatically enforce coding standards
- New publishing preflight check for Lerna

## Build Tools, Setup and Bolt CLI
- Significantly faster setup, compile, and build times
- Bolt CLI much less noisy by default; global verbosity setting now available
- No more pre-built Bolt CSS and JS — DIY builds with Bolt Build Tools
- Moved from npm to Yarn

## Component Schemas
- Yaml Schemas + schema validation
- Component defaults and available options now starting to get powered by schema data (button component already using this!)
- Demos in PL showing component variations are now based on component schemas
- Validate schema extension added, allowing for Twig templates to be validated regardless on the backend implementation (currently a PL feature)

## Continuous Integration & Publishing Improvements
- Bolt Bot with Netlify URL
- Faster Travis build times
- Publishing workflow adjusted: release/1.x branch
- Drupal Lab staged instance (coming soon)

## Twig Templates & Drupal Integration
- Twig template paths have a new `@bolt-components-button/file-name.twig` path aunts
- Bolt Connect module released

## Source of Truth Separate from `Apps`
- Static site generator (similar to Jekyll) powered by Twig, Node and Bolt Components
- Drupal Lab
- Decoupled Pattern Lab from Components
  - Components now live on their own.
	- Pattern Lab pulls in components the exact same way as


text:
'use strict';

/*
 * Module dependencies.
 */

var gutil = require('gulp-util');
var through = require('through2');
var Ware = require('ware');

var Adapter = require('./lib/adapter');

module.exports = function (assemble) {

  var ware = new Ware();

  /**
  * ## Metalsmith plugin
  *
  * Assemble plugin to run metalsmith middleware
  */

  function metalsmithPlugin() {
    return through.obj(function (file, encoding, callback) {
      return callback();
    }, function (callback) {

      // keep a reference to the stream
      var stream = this;

      // initialize an adapter for metalsmith
      var adapter = new Adapter(assemble);

      // run all the registered middleware
      ware.run(adapter.files(), adapter, function (err, files) {
        if (err) {
          stream.emit('error', new gutil.PluginError('assemble-metalsmith', err));
          return callback();
        }

        // restore the files and push them through the stream
        adapter.files(files);
        assemble.files.forEach(function (file) {
          stream.push(file);
        });
        return callback();
      })

    });
  };

  /**
   * ## .use
   *
   * Add a middleware or plugin to use.
   *
   * @param  {Function} `middleware` this is the middleware to run.
   * @return {Object} this for chaining
   */

  metalsmithPlugin.use = function (middleware) {
    ware.use(middleware);
    return this;
  };

  return metalsmithPlugin;
};


text:
So, I plan to stay in NYC.

And the logical continuance of that goal is - *you guessed it* - finding a job.

What do I want to be? *A creative technologist!* What exactly qualifies one to do that? *It's up for debate!*

I found this job posting for "Creative Technologist"(what a lot of us call ourselves, but maybe only a select few really deserve to?) from "experiential design" titan and well-known entity, [Fake Love](http://fakelove.tv/).

I'm not even close to qualified for this job. I've just started learning Open Frameworks and I have no experience managing teams. Despite that, I thought I'd share the job post as a study in what the ad world considers a Creative Technologist to be.

Here's the original post, in iPhone screen caps.

![Fake Love Creative Technologist job posting 01](/images/IMG_4246.JPG)
![Fake Love Creative Technologist job posting 01](/images/IMG_4247.JPG)
![Fake Love Creative Technologist job posting 01](/images/IMG_4248.JPG)
![Fake Love Creative Technologist job posting 01](/images/IMG_4249.JPG)

-----

They're asking for a lot, methinks, but what job doesn't nowadays? I hate advertising and working in advertising. I'm not a 9 to 5 guy. Despite all of that, maybe I will apply. It would be really cool to get paid to make interactive, code-based projects for a living, and I wouldn't mind being paid decent money to do so!

Maybe I will see if I can get an introduction, and angle towards securing an entry-level position with them. Notice that this job posting asks for a "senior-level programmer". That's not me, but maybe in a few years?

If I'm going to stay here, I need a job.


text:
(function($angular) {

    "use strict";

    // The truest wisdom is a resolute determination...
    $angular.module('ngDroplet', []).directive('droplet', ['$rootScope', '$window', '$timeout',

    function DropletDirective($rootScope, $window, $timeout) {

        return {

            /**
             * @property restrict
             * @type {String}
             */
            restrict: 'EA',

            /**
             * @property require
             * @type {String}
             */
            require: '?ngModel',

            /**
             * @property scope
             * @type {Object}
             */
            scope: {
                directiveInterface: '=ngModel'
            },

            /**
             * @method controller
             * @param $scope {Object}
             * @return {void}
             */
            controller: ['$scope', function DropletController($scope) {

                /**
                 * @constant FILE_TYPES
                 * @type {Object}
                 */
                $scope.FILE_TYPES = { VALID: 1, INVALID: 2, DELETED: 4, UPLOADED: 8 };

                /**
                 * @property files
                 * @type {Array}
                 */
                $scope.files = [];

                /**
                 * @property isUploading
                 * @type {Boolean}
                 */
                $scope.isUploading = false;

                /**
                 * @property isError
                 * @type {Boolean}
                 */
                $scope.isError = false;

                /**
                 * @property options
                 * @type {Object}
                 */
                $scope.options = {
                    disableXFileSize: false,
                    useArray: true
                };

                /**
                 * @property extensions
                 * @type {Array}
                 */
                $scope.extensions = [];

                /**
                 * @property requestUrl
                 * @type {String}
                 */
                $scope.requestUrl = '';

                /**
                 * @property requestProgress
                 * @type {Object}
                 */
                $scope.requestProgress = { percent: 0, total: 0, loaded: 0 };

                /**
                 * @property requestHeaders
                 * @type {Object}
                 */
                $scope.requestHeaders = {};

                /**
                 * @property requestPostData
                 * @type {Object}
                 */
                $scope.requestPostData = {};

                /**
                 * @property listeners
                 * @type {Object}
                 */
                $scope.listeners = {

                    /**
                     * Invoked once the HTTP request has been successfully completed.
                     *
                     * @method success
                     * @param httpRequest {XMLHttpRequest}
                     * @return {void}
                     */
                    success: function success(httpRequest) {

                        httpRequest.upload.onload = function onLoad() {

                            $scope.$apply(function apply() {

                                $scope.finishedUploading();

                                $scope.forEachFile($scope.FILE_TYPES.VALID, function forEach(model) {

                                    // Advance the status of the file to that of an uploaded file.
                                    model.type = $scope.FILE_TYPES.UPLOADED;

                                });

                            });

                        };

                    },

                    /**
                     * Invoked once everything has been uploaded.
                     *
                     * @method finish
                     * @param httpRequest {XMLHttpRequest}
                     * @param uploadedFiles {Array}
                     * @return {void}
                     */
                    finish: function finish(httpRequest, uploadedFiles) {

                        httpRequest.onreadystatechange = function onReadyStateChange() {

                            if (httpRequest.readyState === 4 && httpRequest.status !== 0) {

                                $scope.$apply(function apply() {

                                    // Parse the response, and then emit the event passing along the response
                                    // and the uploaded files!
                                    var response = $window.JSON.parse(httpRequest.responseText);
                                    $rootScope.$broadcast('$dropletUploaded', response, uploadedFiles);

                                });

                            }

                        };

                    },

                    /**
                     * Invoked when an error is thrown when uploading the files.
                     *
                     * @method error
                     * @param httpRequest {XMLHttpRequest}
                     * @return {void}
                     */
                    error: function error(httpRequest) {

                        httpRequest.upload.onerror = function onError() {

                            $scope.$apply(function apply() {

                                $scope.finishedUploading();
                                $scope.isError = true;

                            });

                        };

                    },

                    /**
                     * Invoked each time there's a progress update on the files being uploaded.
                     *
                     * @method progress
                     * @param httpRequest {XMLHttpRequest}
                     * @param requestLength {Number}
                     * @return {void}
                     */
                    progress: function progress(httpRequest, requestLength) {

                        httpRequest.upload.onprogress = function onProgress(event) {

                            $scope.$apply(function apply() {

                                console.log(event.loaded);

                                if (event.lengthComputable) {

                                    // Update the progress object.
                                    $scope.requestProgress.percent = Math.round((event.loaded / requestLength) * 100);
                                    $scope.requestProgress.loaded  = event.loaded;
                                    $scope.requestProgress.total   = requestLength;

                                }

                            });

                        };

                    }

                };

                /**
                 * @method createModelBlueprint
                 * @return {void}
                 */
                (function createModelBlueprint() {

                    /**
                     * @model DropletModel
                     * @constructor
                     */
                    $scope.DropletModel = function DropletModel() {};

                    /**
                     * @property prototype
                     * @type {Object}
                     */
                    $scope.DropletModel.prototype = {

                        /**
                         * @method file
                         * @param file {File}
                         * @param type {Number}
                         * @return {void}
                         */
                        load: function load(file, type) {

                            this.file      = file;
                            this.type      = type;
                            this.date      = new $window.Date();
                            this.mimeType  = file.type;
                            this.extension = $scope.getExtension(file);

                        },

                        /**
                         * @method deleteFile
                         * @return {void}
                         */
                        deleteFile: function deleteFile() {
                            $scope.deleteFile(this);
                        },

                        /**
                         * @method isImage
                         * @return {Boolean}
                         */
                        isImage: function isImage() {
                            return !!this.file.type.match(/^image\//i);
                        }

                    };

                })();

                /**
                 * @method finishedUploading
                 * @return {void}
                 */
                $scope.finishedUploading = function finishedUploading() {

                    $scope.progress    = { percent: 0, total: 0, loaded: 0 };
                    $scope.isUploading = false;

                };

                /**
                 * Utility method for iterating over files of a given type.
                 *
                 * @method forEachFile
                 * @param type {Number}
                 * @param callbackFn {Function}
                 * @return {void}
                 */
                $scope.forEachFile = function forEachFile(type, callbackFn) {

                    $angular.forEach($scope.filterFiles(type || $scope.FILE_TYPES.VALID), function forEach(model) {
                        callbackFn(model);
                    });

                };

                /**
                 * @method addFile
                 * @param file {File}
                 * @param type {Number}
                 * @return {Object}
                 */
                $scope.addFile = function addFile(file, type) {

                    // If the developer didn't specify the type then we'll assume it's a valid file
                    // that they're adding.
                    type = type || $scope.FILE_TYPES.VALID;

                    // Create the model and then register the file.
                    var model = new $scope.DropletModel();
                    model.load(file, type);

                    $scope.files.push(model);
                    return model;

                };

                /**
                 * @method deleteFile
                 * @throws Exception
                 * @param model {Object}
                 * @return {void}
                 */
                $scope.deleteFile = function deleteFile(model) {

                    if (!(model instanceof $scope.DropletModel)) {
                        $scope.throwException('Method expects an instance of DropletModel');
                    }

                    model.type = $scope.FILE_TYPES.DELETED;

                };

                /**
                 * @method filterFiles
                 * @param type {Number}
                 * @return {Array}
                 */
                $scope.filterFiles = function filterFiles(type) {

                    return $scope.files.filter(function filter(file) {
                        return type & file.type;
                    });

                };

                /**
                 * @method getExtension
                 * @param file {File}
                 * @return {String}
                 */
                $scope.getExtension = function getExtension(file) {
                    return file.name.split('.').pop().trim().toLowerCase();
                };

                /**
                 * @method traverseFiles
                 * @param files {FileList}
                 * @return {void}
                 */
                $scope.traverseFiles = function traverseFiles(files) {

                    $scope.$apply(function apply() {

                        for (var index = 0, numFiles = files.length; index < numFiles; index++) {

                            var file      = files[index],
                                extension = $scope.getExtension(file),
                                type      = $scope.FILE_TYPES.VALID;

                            if ($scope.extensions.indexOf(extension) === -1) {

                                // Invalid extension which we must reject!
                                type = $scope.FILE_TYPES.INVALID

                            }

                            // Finally we'll register the file using the type that has been deduced.
                            $scope.addFile(file, type);

                        }

                    });

                };

                /**
                 * @method uploadFiles
                 * @return {void}
                 */
                $scope.uploadFiles = function uploadFiles() {

                    // Reset...
                    $scope.isError = false;

                    var httpRequest   = new $window.XMLHttpRequest(),
                        formData      = new $window.FormData(),
                        queuedFiles   = $scope.filterFiles($scope.FILE_TYPES.VALID),
                        fileProperty  = $scope.options.useArray ? 'file[]' : 'file',
                        requestLength = $scope.getRequestLength(queuedFiles);

                    // Initiate the HTTP request.
                    httpRequest.open('post', $scope.requestUrl, true);

                    /**
                     * @method appendCustomData
                     * @return {void}
                     */
                    (function appendCustomData() {

                        if (!$scope.options.disableXFileSize) {

                            // Setup the file size of the request.
                            httpRequest.setRequestHeader('X-File-Size', requestLength);

                        }

                        // ...And any other additional HTTP request headers, and POST data.
                        $scope.addRequestHeaders(httpRequest);
                        $scope.addPostData(formData);

                    })();

                    /**
                     * @method attachEventListeners
                     * @return {void}
                     */
                    (function attachEventListeners() {

                        // Configure the event listeners for the impending request.
                        $scope.listeners.finish(httpRequest, queuedFiles);
                        $scope.listeners.success(httpRequest);
                        $scope.listeners.progress(httpRequest, requestLength);
                        $scope.listeners.error(httpRequest);

                    })();

                    // Iterate all of the valid files to append them to the previously created
                    // `formData` object.
                    $angular.forEach(queuedFiles, function forEach(model) {
                        formData.append(fileProperty, model.file);
                    });

                    // Voila...
                    $scope.isUploading = true;
                    httpRequest.send(formData);

                };

                /**
                 * Iterate over any additional headers added by the developer and append to the current
                 * request being generated.
                 *
                 * @method addRequestHeaders
                 * @param httpRequest {XMLHttpRequest}
                 * @return {Array}
                 */
                $scope.addRequestHeaders = function addRequestHeaders(httpRequest) {

                    for (var header in $scope.requestHeaders) {

                        if ($scope.requestHeaders.hasOwnProperty(header)) {
                            httpRequest.setRequestHeader(header, $scope.requestHeaders[header]);
                        }

                    }

                    return Object.keys($scope.requestHeaders);

                };

                /**
                 * Iterate over any additional POST data that must be bundled with the request.
                 *
                 * @method addPostData
                 * @param formData {FormData}
                 * @return {Array}
                 */
                $scope.addPostData = function addPostData(formData) {

                    for (var header in $scope.requestPostData) {

                        if ($scope.requestPostData.hasOwnProperty(header)) {
                            formData.append(header, $scope.requestHeaders[header]);
                        }

                    }

                    return Object.keys($scope.requestPostData);

                };

                /**
                 * Determine the size of the request based on the files preparing to be uploaded.
                 *
                 * @method getRequestLength
                 * @param [files=[]] {Array}
                 * @return {Number}
                 * @private
                 */
                $scope.getRequestLength = function getRequestLength(files) {

                    var size = 0;

                    // Iterate over all of the files to determine the size of all valid files.
                    $angular.forEach(files || $scope.filterFiles($scope.FILE_TYPES.VALID), function forEach(model) {
                        size += model.file.size;
                    });

                    return size;

                };

                /**
                 * @method throwException
                 * @param message {String}
                 * @return {void}
                 */
                $scope.throwException = function throwException(message) {
                    throw "ngDroplet: " + message + ".";
                };

                /**
                 * Responsible for setting up the interface that allows the developer to interact
                 * with the directive from outside.
                 *
                 * @method setupDirectiveInterface
                 * @return {void}
                 */
                (function setupDirectiveInterface() {

                    /**
                     * @property directiveInterface
                     * @type {Object}
                     */
                    $scope.directiveInterface = {

                        /**
                         * @constant FILE_TYPES
                         * @type {Object}
                         */
                        FILE_TYPES: $scope.FILE_TYPES,

                        /**
                         * @method uploadFiles
                         * @return {void}
                         */
                        uploadFiles: $scope.uploadFiles,

                        /**
                         * @property progress
                         * @type {Object}
                         */
                        progress: $scope.requestProgress,

                        /**
                         * @method isUploading
                         * @return {Boolean}
                         */
                        isUploading: function() {
                            return $scope.isUploading;
                        },

                        /**
                         * @property isError
                         * @type {Object}
                         */
                        isError: $scope.isError,

                        /**
                         * Determines if there are files ready and waiting to be uploaded.
                         *
                         * @method isReady
                         * @return {Boolean}
                         */
                        isReady: function isReady() {
                            return !!$scope.filterFiles($scope.FILE_TYPES.VALID).length;
                        },

                        /**
                         * @method addFile
                         * @param file {File}
                         * @param type {Number}
                         * @return {void}
                         */
                        addFile: $scope.addFile,

                        /**
                         * @method disableXFileSize
                         * @return {void}
                         */
                        disableXFileSize: function disableXFileSize() {
                            $scope.options.disableXFileSize = true;
                        },

                        /**
                         * @method useArray
                         * @param value {Boolean}
                         * @return {void}
                         */
                        useArray: function useArray(value) {
                            $scope.options.useArray = !!value;
                        },

                        /**
                         * @method setRequestUrl
                         * @param url {String}
                         * @return {void}
                         */
                        setRequestUrl: function setRequestUrl(url) {
                            $scope.requestUrl = url;
                        },

                        /**
                         * @method setRequestHeaders
                         * @param headers {Object}
                         * @return {void}
                         */
                        setRequestHeaders: function setRequestHeaders(headers) {
                            $scope.requestHeaders = headers;
                        },

                        /**
                         * @method setPostData
                         * @param data {Object}
                         * @return {void}
                         */
                        setPostData: function setPostData(data) {
                            $scope.requestPostData = data;
                        },

                        /**
                         * @method getFiles
                         * @param type {Number}
                         * @return {Array}
                         */
                        getFiles: function getFiles(type) {

                            if (type) {

                                // Apply any necessary filters if a bitwise value has been supplied.
                                return $scope.filterFiles(type);

                            }

                            // Otherwise we'll yield the entire set of files.
                            return $scope.files;

                        },

                        /**
                         * @method allowedExtensions
                         * @param extensions {Array}
                         * @return {void}
                         */
                        allowedExtensions: function allowedExtensions(extensions) {

                            if (!$angular.isArray(extensions)) {

                                // Developer didn't pass an array of extensions!
                                $scope.throwException('Extensions must be an array');

                            }

                            $scope.extensions = extensions;

                        }

                    };

                    $timeout(function timeout() {

                        // Emit the event to notify any listening scopes that the interface has been attached
                        // for communicating with the directive.
                        $rootScope.$broadcast('$dropletReady');

                    });

                })();

            }],

            /**
             * @method link
             * @param scope {Object}
             * @param element {Object}
             * @return {void}
             */
            link: function link(scope, element) {

                /**
                 * @method _preventDefault
                 * @param event {Object}
                 * @return {void}
                 * @private
                 */
                var _preventDefault = function _preventDefault(event) {

                    event.preventDefault();
                    event.stopPropagation();

                };

                // Events that merely need their default behaviour quelling.
                element.bind('dragover dragenter dragleave', _preventDefault);

                // Bind to the "drop" event which will contain the items the user dropped
                // onto the element.
                element.bind('drop', function onDrop(event) {

                    _preventDefault(event);
                    scope.traverseFiles(event.dataTransfer.files);

                });

            }

        }

    }]).directive('dropletPreview', ['$window', function DropletPreviewDirective($window) {

        return {

            /**
             * @property scope
             * @type {Object}
             */
            scope: {
                model: '=ngModel'
            },

            /**
             * @property restrict
             * @type {String}
             */
            restrict: 'E',

            /**
             * @property replace
             * @type {Boolean}
             */
            replace: true,

            /**
             * @property template
             * @type {String}
             */
            template: '<img ng-show="model.isImage()" ng-src="{{imageData}}" class="droplet-preview" />',

            /**
             * @method link
             * @param scope {Object}
             * @return {void}
             */
            link: function link(scope) {

                /**
                 * @property imageData
                 * @type {String}
                 */
                scope.imageData = '';

                // Instantiate the file reader for reading the image data.
                var fileReader = new $window.FileReader();

                /**
                 * @method onload
                 * @return {void}
                 */
                fileReader.onload = function onload(event) {

                    scope.$apply(function apply() {

                        // Voila! Define the image data.
                        scope.imageData = event.target.result;

                    });

                };

                if (scope.model.isImage()) {

                    // Initialise the loading of the image into the file reader.
                    fileReader.readAsDataURL(scope.model.file);

                }

            }

        }

    }]);

})(window.angular);


text:
import mock
from oslo_context import context as o_context
from oslo_context import fixture as o_fixture

from nova import context
from nova import objects
from nova import test

class ContextTestCase(test.NoDBTestCase):

    def setUp(self):
        super(ContextTestCase, self).setUp()
        self.useFixture(o_fixture.ClearRequestContext())

    def test_request_context_elevated(self):
        user_ctxt = context.RequestContext('111',
                                           '222',
                                           admin=False)
        self.assertFalse(user_ctxt.is_admin)
        admin_ctxt = user_ctxt.elevated()
        self.assertTrue(admin_ctxt.is_admin)
        self.assertIn('admin', admin_ctxt.roles)
        self.assertFalse(user_ctxt.is_admin)
        self.assertNotIn('admin', user_ctxt.roles)

    def test_request_context_sets_is_admin(self):
        ctxt = context.RequestContext('111',
                                      '222',
                                      roles=['admin', 'weasel'])
        self.assertTrue(ctxt.is_admin)

    def test_request_context_sets_is_admin_by_role(self):
        ctxt = context.RequestContext('111',
                                      '222',
                                      roles=['administrator'])
        self.assertTrue(ctxt.is_admin)

    def test_request_context_sets_is_admin_upcase(self):
        ctxt = context.RequestContext('111',
                                      '222',
                                      roles=['Admin', 'weasel'])
        self.assertTrue(ctxt.is_admin)

    def test_request_context_read_deleted(self):
        ctxt = context.RequestContext('111',
                                      '222',
                                      read_deleted='yes')
        self.assertEqual('yes', ctxt.read_deleted)

        ctxt.read_deleted = 'no'
        self.assertEqual('no', ctxt.read_deleted)

    def test_request_context_read_deleted_invalid(self):
        self.assertRaises(ValueError,
                          context.RequestContext,
                          '111',
                          '222',
                          read_deleted=True)

        ctxt = context.RequestContext('111', '222')
        self.assertRaises(ValueError,
                          setattr,
                          ctxt,
                          'read_deleted',
                          True)

    def test_extra_args_to_context_get_logged(self):
        info = {}

        def fake_warn(log_msg, *args):
            if args:
                log_msg = log_msg % args
            info['log_msg'] = log_msg

        self.stub_out('nova.context.LOG.warning', fake_warn)

        c = context.RequestContext('user', 'project',
                extra_arg1='meow', extra_arg2='wuff')
        self.assertTrue(c)
        self.assertIn("'extra_arg1': 'meow'", info['log_msg'])
        self.assertIn("'extra_arg2': 'wuff'", info['log_msg'])

    def test_service_catalog_default(self):
        ctxt = context.RequestContext('111', '222')
        self.assertEqual([], ctxt.service_catalog)

        ctxt = context.RequestContext('111', '222',
                service_catalog=[])
        self.assertEqual([], ctxt.service_catalog)

        ctxt = context.RequestContext('111', '222',
                service_catalog=None)
        self.assertEqual([], ctxt.service_catalog)

    def test_service_catalog_cinder_only(self):
        service_catalog = [
                {u'type': u'compute', u'name': u'nova'},
                {u'type': u's3', u'name': u's3'},
                {u'type': u'image', u'name': u'glance'},
                {u'type': u'volume', u'name': u'cinder'},
                {u'type': u'ec2', u'name': u'ec2'},
                {u'type': u'object-store', u'name': u'swift'},
                {u'type': u'identity', u'name': u'keystone'},
                {u'type': None, u'name': u'S_withouttype'},
                {u'type': u'vo', u'name': u'S_partofvolume'}]

        volume_catalog = [{u'type': u'volume', u'name': u'cinder'}]
        ctxt = context.RequestContext('111', '222',
                service_catalog=service_catalog)
        self.assertEqual(volume_catalog, ctxt.service_catalog)

    def test_to_dict_from_dict_no_log(self):
        warns = []

        def stub_warn(msg, *a, **kw):
            if (a and len(a) == 1 and isinstance(a[0], dict) and a[0]):
                a = a[0]
            warns.append(str(msg) % a)

        self.stub_out('nova.context.LOG.warning', stub_warn)

        ctxt = context.RequestContext('111',
                                      '222',
                                      roles=['admin', 'weasel'])

        context.RequestContext.from_dict(ctxt.to_dict())

        self.assertEqual(0, len(warns), warns)

    def test_store_when_no_overwrite(self):
        # If no context exists we store one even if overwrite is false
        # (since we are not overwriting anything).
        ctx = context.RequestContext('111',
                                      '222',
                                      overwrite=False)
        self.assertIs(o_context.get_current(), ctx)

    def test_no_overwrite(self):
        # If there is already a context in the cache a new one will
        # not overwrite it if overwrite=False.
        ctx1 = context.RequestContext('111',
                                      '222',
                                      overwrite=True)
        context.RequestContext('333',
                               '444',
                               overwrite=False)
        self.assertIs(o_context.get_current(), ctx1)

    def test_admin_no_overwrite(self):
        # If there is already a context in the cache creating an admin
        # context will not overwrite it.
        ctx1 = context.RequestContext('111',
                                      '222',
                                      overwrite=True)
        context.get_admin_context()
        self.assertIs(o_context.get_current(), ctx1)

    def test_convert_from_rc_to_dict(self):
        ctx = context.RequestContext(
            111, 222, request_id='req-679033b7-1755-4929-bf85-eb3bfaef7e0b',
            timestamp='2015-03-02T22:31:56.641629')
        values2 = ctx.to_dict()
        expected_values = {'auth_token': None,
                           'domain': None,
                           'instance_lock_checked': False,
                           'is_admin': False,
                           'project_id': 222,
                           'project_domain': None,
                           'project_name': None,
                           'quota_class': None,
                           'read_deleted': 'no',
                           'read_only': False,
                           'remote_address': None,
                           'request_id':
                               'req-679033b7-1755-4929-bf85-eb3bfaef7e0b',
                           'resource_uuid': None,
                           'roles': [],
                           'service_catalog': [],
                           'show_deleted': False,
                           'tenant': 222,
                           'timestamp': '2015-03-02T22:31:56.641629',
                           'user': 111,
                           'user_domain': None,
                           'user_id': 111,
                           'user_identity': '111 222 - - -',
                           'user_name': None}
        self.assertEqual(expected_values, values2)

    def test_convert_from_dict_then_to_dict(self):
        values = {'user': '111',
                  'user_id': '111',
                  'tenant': '222',
                  'project_id': '222',
                  'domain': None, 'project_domain': None,
                  'auth_token': None,
                  'resource_uuid': None, 'read_only': False,
                  'user_identity': '111 222 - - -',
                  'instance_lock_checked': False,
                  'user_name': None, 'project_name': None,
                  'timestamp': '2015-03-02T20:03:59.416299',
                  'remote_address': None, 'quota_class': None,
                  'is_admin': True,
                  'service_catalog': [],
                  'read_deleted': 'no', 'show_deleted': False,
                  'roles': [],
                  'request_id': 'req-956637ad-354a-4bc5-b969-66fd1cc00f50',
                  'user_domain': None}
        ctx = context.RequestContext.from_dict(values)
        self.assertEqual('111', ctx.user)
        self.assertEqual('222', ctx.tenant)
        self.assertEqual('111', ctx.user_id)
        self.assertEqual('222', ctx.project_id)
        values2 = ctx.to_dict()
        self.assertEqual(values, values2)

    @mock.patch('nova.db.create_context_manager')
    def test_target_cell(self, mock_create_ctxt_mgr):
        mock_create_ctxt_mgr.return_value = mock.sentinel.cm
        ctxt = context.RequestContext('111',
                                      '222',
                                      roles=['admin', 'weasel'])
        # Verify the existing db_connection, if any, is restored
        ctxt.db_connection = mock.sentinel.db_conn
        mapping = objects.CellMapping(database_connection='fake://')
        with context.target_cell(ctxt, mapping):
            self.assertEqual(ctxt.db_connection, mock.sentinel.cm)
        self.assertEqual(mock.sentinel.db_conn, ctxt.db_connection)