text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInitfb6747cac0a5fc682ced97418fc65bef::getLoader();

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: halifax
description: sad
date: 2017-08-24
---

I've tried to start this a few times.

I'm going to Victoria in the fall.

Please forgive the forthcoming John-Green-teenage-romance-movie language.

I don't know how else to say this: You are my closest group of friends.

I can't pretend like I'm certain about the decision I'm making. There's so much uncertainty in my life right now and nothing really seems absolute about my future. I just know that the program in Victoria is better for me, and I feel like I'll do well there.

For me, this past year was the most defining period of my life and I am so thankful to you for that.

This past year was so much more about people than it was about school, and I'm only realizing that now.

I miss you guys and I will continue to miss you.

I know that you all will get somewhere great in life.

You all deserve so much. You are all so kind. Please realize that you can help sarcastic, boring pricks like me and open them up to things beyond what they can learn on their own.

You guys changed me and I owe you for that.

Sidenote: Also I'm getting a tattoo and I need your input. It's to remember Halifax. I'm thinking like just the letters "UKC" in like handwriting or like the geographical coordinates of Alex Hall or maybe like an anchor?? idk but plz text me before I make a bad decision


text:
<?xml version="1.0" encoding="UTF-8"?>

<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
    id="cordova-plugin-bcplayer"
    version="1.1.6">
    <name>BCPlayerPlugin</name>
    <description>Brightcove Native Player for Cordova</description>
    <license>Apache 2.0</license>
    <keywords>Cordova,Brightcove,Player</keywords>

  <js-module src="www/player.js" name="player">
    <clobbers target="plugins.BCPlayer" />
  </js-module>

  <engines>
    <engine name="cordova-android" version=">=4.0.0-dev" />
  </engines>

  <!-- android -->
  <platform name="android">
    <config-file target="res/xml/config.xml" parent="/*">
      <feature name="BCPlayerPlugin">
        <param name="android-package" value="net.nopattern.cordova.brightcoveplayer.BCPlayerPlugin" />
        <param name="onload" value="true" />
      </feature>
    </config-file>

    <config-file target="AndroidManifest.xml" parent="application">
      <activity
              android:theme="@style/AppThemeTransparent"
              android:name="net.nopattern.cordova.brightcoveplayer.BCPlayerActivity"
              android:configChanges="orientation|screenSize"
              android:launchMode="singleTask"
              android:label="@string/app_name" >
      </activity>
      <service android:name="net.nopattern.cordova.brightcoveplayer.BCPlayerService" android:stopWithTask="true" />
    </config-file>

    <!-- src -->
    <source-file src="src/android/BCPlayerPlugin.java" target-dir="src/net/nopattern/cordova/brightcoveplayer" />
    <source-file src="src/android/BCPlayerActivity.java" target-dir="src/net/nopattern/cordova/brightcoveplayer" />
    <source-file src="src/android/Cmd.java" target-dir="src/net/nopattern/cordova/brightcoveplayer" />
    <source-file src="src/android/BCPlayerService.java" target-dir="src/net/nopattern/cordova/brightcoveplayer" />
    <source-file src="src/android/BCVideoRetriever.java" target-dir="src/net/nopattern/cordova/brightcoveplayer" />

    <!-- libs -->
    <framework src="src/android/brightcove-libs.gradle" custom="true" type="gradleReference" />

    <resource-file src="src/android/libs/android-sdk-4.7.3.aar" target="libs/android-sdk-4.7.3.aar" />

    <!-- layout -->
    <source-file src="src/android/res/layout/bundled_video_activity_brightcove.xml" target-dir="res/layout/" />
    <source-file src="src/android/res/values/style.xml" target-dir="res/values/" />
  </platform>

  <!-- ios -->
  <platform name="ios">
    <config-file target="config.xml" parent="/*">
      <feature name="BCPlayerPlugin">
        <param name="ios-package" value="BCPlayerPlugin" />
      </feature>
    </config-file>

    <!-- src -->
    <header-file src="src/ios/BCPlayerPlugin.h" />
    <source-file src="src/ios/BCPlayerPlugin.m" />

    <header-file src="src/ios/BCPlayerPluginController.h" />
    <source-file src="src/ios/BCPlayerPluginController.m" />

    <framework src="src/ios/BrightcovePlayerSDK.framework" custom="true" />
    <framework src="MediaPlayer.framework" />
    <framework src="CoreMedia.framework" />
    <framework src="AVFoundation.framework" />
    <framework src="SystemConfiguration.framework" />
    <framework src="AdSupport.framework" />
    <framework src="AVKit.framework" />
</platform>

</plugin>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>CheckTypeSize — CMake 3.7.2 Documentation</title>

    <link rel="stylesheet" href="../_static/cmake.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/cmake-favicon.ico"/>
    <link rel="top" title="CMake 3.7.2 Documentation" href="../index.html" />
    <link rel="up" title="cmake-modules(7)" href="../manual/cmake-modules.7.html" />
    <link rel="next" title="CheckVariableExists" href="CheckVariableExists.html" />
    <link rel="prev" title="CheckSymbolExists" href="CheckSymbolExists.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.7.2 Documentation »

cmake-modules(7) »

CheckTypeSize¶

Check sizeof a type

CHECK_TYPE_SIZE(TYPE VARIABLE [BUILTIN_TYPES_ONLY]
                              [LANGUAGE <language>])

Check if the type exists and determine its size.  On return,
“HAVE_${VARIABLE}” holds the existence of the type, and “${VARIABLE}”
holds one of the following:

<size> = type has non-zero size <size>
"0"    = type has arch-dependent size (see below)
""     = type does not exist

Both HAVE_${VARIABLE} and ${VARIABLE} will be created as internal
cache variables.

Furthermore, the variable “${VARIABLE}_CODE” holds C preprocessor code
to define the macro “${VARIABLE}” to the size of the type, or leave
the macro undefined if the type does not exist.

The variable “${VARIABLE}” may be “0” when CMAKE_OSX_ARCHITECTURES has
multiple architectures for building OS X universal binaries.  This
indicates that the type size varies across architectures.  In this
case “${VARIABLE}_CODE” contains C preprocessor tests mapping from
each architecture macro to the corresponding type size.  The list of
architecture macros is stored in “${VARIABLE}_KEYS”, and the value for
each key is stored in “${VARIABLE}-${KEY}”.

If the BUILTIN_TYPES_ONLY option is not given, the macro checks for
headers <sys/types.h>, <stdint.h>, and <stddef.h>, and saves results
in HAVE_SYS_TYPES_H, HAVE_STDINT_H, and HAVE_STDDEF_H.  The type size
check automatically includes the available headers, thus supporting
checks of types defined in the headers.

If LANGUAGE is set, the specified compiler will be used to perform the
check. Acceptable values are C and CXX

Despite the name of the macro you may use it to check the size of more
complex expressions, too.  To check e.g.  for the size of a struct
member you can do something like this:

check_type_size("((struct something*)0)->member" SIZEOF_MEMBER)

The following variables may be set before calling this macro to modify
the way the check is run:

CMAKE_REQUIRED_FLAGS = string of compile command line flags
CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
CMAKE_REQUIRED_INCLUDES = list of include directories
CMAKE_REQUIRED_LIBRARIES = list of libraries to link
CMAKE_REQUIRED_QUIET = execute quietly without messages
CMAKE_EXTRA_INCLUDE_FILES = list of extra headers to include

Previous topic

CheckSymbolExists

Next topic

CheckVariableExists

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          next |

          previous |

    CMake »

    3.7.2 Documentation »

cmake-modules(7) »

        © Copyright 2000-2016 Kitware, Inc. and Contributors.
      Created using Sphinx 1.4a0+.


text:
{% if value %}

{% else %}

{% endif %}
<input type="hidden" name="{{ name }}" value="{{ value }}"/>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Kosmos 36: 295 & 298 (1911)

#### Original name
Aecidium aposeridis Namysl.

### Remarks
null


text:
namespace interfaces {
namespace {

    class LockImpl : public Chain::Lock {};

    class LockingStateImpl : public LockImpl,
                             public UniqueLock<CCriticalSection> {
        using UniqueLock::UniqueLock;
    };

    class ChainImpl : public Chain {
    public:
        std::unique_ptr<Chain::Lock> lock(bool try_lock) override {
            auto result = std::make_unique<LockingStateImpl>(
                ::cs_main, "cs_main", __FILE__, __LINE__, try_lock);
            if (try_lock && result && !*result) {
                return {};
            }
            return result;
        }
        std::unique_ptr<Chain::Lock> assumeLocked() override {
            return std::make_unique<LockImpl>();
        }
    };

} // namespace

std::unique_ptr<Chain> MakeChain() {
    return std::make_unique<ChainImpl>();
}

} // namespace interfaces


text:
/**
 * A tree representing class inheritances, where keys are class names.
 */
export interface IClassInheritance {
    [i: string]: IClassInheritance;
}

/**
 * Properties for each class, keyed by class name.
 */
export interface IClassProperties {
    [i: string]: any;
}

/**
 * Generated classes, keyed by name.
 */
export interface IClassFunctions {
    [i: string]: IClass;
}

/**
 * Parent names for each class.
 */
export interface IClassParentNames {
    [i: string]: string;
}

/**
 * Root abstract definition for generated classes.
 */
export type IClass = new () => any;

/**
 * Member callback for when an output onMake is a Function.
 *
 * @template T   Type of the generated class instance.
 * @param output   Generated class instance.
 * @param name   Name of the class.
 * @param settings   Settings used to instantiate this instance.
 * @param defaults   Defaults for the class.
 */
export type IOnMakeFunction<T> = (this: T, output: T, name: string) => void;

/**
 * Settings to initialize a new IObjectMakr.
 */
export interface IObjectMakrSettings {
    /**
     * A tree representing class inheritances, where keys are class names.
     */
    inheritance?: IClassInheritance;

    /**
     * Properties for each class.
     */
    properties?: IClassProperties;

    /**
     * How properties can be mapped from an Array to indices.
     */
    indexMap?: string[];

    /**
     * Member name for a function on instances to be called upon creation.
     */
    onMake?: string;
}

/**
 * An abstract factory for dynamic attribute-based classes.
 */
export interface IObjectMakr {
    /**
     * Gets the prototype of a class, which contains its base properties.
     *
     * @template T   Type of class properties being retrieved.
     * @param name   Name of a class.
     * @returns Base properties for the class.
     */
    getPrototypeOf<T extends {}>(name: string): T;

    /**
     * Gets whether a class exists.
     *
     * @param name   Name of a class.
     * @returns Whether that class exists.
     */
    hasClass(name: string): boolean;

    /**
     * Creates a new instance of a class.
     *
     * @template T   Type of class being created.
     * @param name   Name of the class.
     * @param settings   Additional attributes to deep copy onto the new instance.
     * @returns A newly created instance of the specified class.
     */
    make<T extends {}>(name: string, settings?: Partial<T>): T;
}


text:
When using `mech_saml_ec`, the value of the `local-login-user` determines which account on the resource an authenticated
user gains access to. Thus, denying a user access is accomplished by not setting a value for that attribute or
filtering a previously set value.

When only an IdP and SP are involved, access control can be done by configuring the SP's
[attribute filter](https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPAttributeFilter).
However, when the resource provider uses an attribute authority to resolve `local-login-user`, the situation gets
more complicated. The value of `local-login-user` is retrieved from the AA using a
[Simple Aggregation Attribute Resolver](https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPAttributeResolver#NativeSPAttributeResolver-SimpleAggregationAttributeResolver(Version2.2andAbove)).
However:
> After each query is performed, the resolver applies the attribute extractor and filter configured for the
> application before continuing with other queries and eventually returning the resulting attributes. Each filtering
> step will operate on only the attributes extracted as a result of a particular query, and the filter policies can be
> expressed in terms of the actual "issuer" of each set of attributes for fine-grained control.

Thus, the SP cannot filter `local-login-user` based on attribute values obtained from either the user's primary
IdP or a virtual organization's attribute authority.

To get around this, the decision to release a value for `local-login-user` can be done at the resource AA. For this
to work, the resource AA has to be queried with the user's EPPN as well as any other attributes necessary for the
access control decision. Because the [SimpleAggregation AttributeResolver](https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPAttributeResolver#NativeSPAttributeResolver-SimpleAggregationAttributeResolver(Version2.2andAbove))
can only pass one attribute value (the query identifier) to the attribute authority, the user's EPPN and the other
attributes must be first joined into a single attribute. The choice of method for encoding/decoding the attribute
values will affect both SP and resource AA configuration.

## Example

For this example, assume the SP queries a virtual organization's AA with an EPPN and a VO name. The VO's AA releases
an `isMemberOf` attribute with a boolean value indicating whether or not the user is a member of that VO. The SP
should allow access through `mech_saml_ec` if `isMemberOf` is true.

### SP Configuration

The SP needs to query the resource AA with the user's EPPN and the value of the `isMemberOf` attribute.

One way to join the attributes into a single attribute to use for the query is with a Template Attribute Resolver.
From its documentation:

> To use this plugin, the plugins.so shared library must be loaded via the <OutOfProcess> element's
> <Library> element.

`/etc/shibboleth/shibboleth2.xml`
```xml
...

<OutOfProcess>
   <Extensions>
      <Library path="plugins.so" fatal="true"/>
   </Extensions>
</OutOfProcess>

...

<AttributeResolver type="Template" sources="eppn isMemberOf" dest="eppnAndMembership">
   <Template>$eppn:$isMemberOf</Template>
</AttributeResolver>

<AttributeResolver type="SimpleAggregation" attributeId="eppnAndMembership" format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">
   <Entity>https://aa.resourceprovider.com/idp/shibboleth</Entity>
   <MetadataProvider type="XML" validate="true" path="/path/to/resource-aa-metadata.xml" />
</AttributeResolver>

...
```

### Attribute Authority Configuration

At the resource's attribute authority, this joined attribute needs to be split up again. This can be done using a
[Script AttributeDefinition](https://wiki.shibboleth.net/confluence/display/SHIB2/ResolverScriptAttributeDefinition).
(The static data connector is necessary to create attributes if using
[Java 1.8's Nashorn engine](https://wiki.shibboleth.net/confluence/display/SHIB2/IdPJava1.8))

`$IDP_HOME/conf/attribute-resolver.xml`
```xml
...

<!-- Create attributes for script definitions -->
<resolver:DataConnector id="scriptAttrCreation" xsi:type="dc:Static" xmlns="urn:mace:shibboleth:2.0:resolver:dc">
   <Attribute id="eppn">
      <Value>placeholder</Value>
   </Attribute>
   <Attribute id="isAllowed">
      <Value>placeholder</Value>
   </Attribute>
</resolver:DataConnector>

<!-- Extract EPPN from attribute query -->
<resolver:AttributeDefinition id="eppn" xsi:type="ad:Script">
   <resolver:Dependency ref="scriptAttrCreation" />
   <ad:Script>
      <![CDATA[
         eppn.getValues().clear();
         eppn.getValues().add(requestContext.principalName.split(":")[0]);
      ]]>
   </ad:Script>
</resolver:AttributeDefinition>

<!-- Extract isAllowed from attribute query -->
<resolver:AttributeDefinition id="isAllowed" xsi:type="ad:Script">
   <resolver:Dependency ref="scriptAttrCreation" />
   <ad:Script>
      <![CDATA[
         isAllowed.getValues().clear();
         isAllowed.getValues().add(requestContext.principalName.split(":")[1]);
      ]]>
   </ad:Script>
</resolver:AttributeDefinition>

...
```

Now that the user's EPPN and whether or not they are allowed access are determined, those attributes can be used
in an [attribute filter](https://wiki.shibboleth.net/confluence/display/IDP30/AttributeFilterConfiguration) to
clear the value of `local-login-user` if `isAllowed` is not true. For example:

`$IDP_HOME/conf/attribute-filter.xml`
```xml
<afp:AttributeFilterPolicyGroup ...>
   ...

   <!-- Permit local-login-user is isAllowed is true -->
   <afp:AttributeFilterPolicy>
      <afp:PolicyRequirementRule xsi:type="basic:AttributeValueString" attributeID="isAllowed" value="true" />
      <afp:AttributeRule attributeID="local-login-user">
         <afp:PermitValueRule xsi:type="basic:ANY" />
      </afp:AttributeRule>
   </afp:AttributeFilterPolicy>

    <!-- Deny if false-->
   <afp:AttributeFilterPolicy>
      <afp:PolicyRequirementRule xsi:type="basic:AttributeValueString" attributeID="isAllowed" value="false" />
      <afp:AttributeRule attributeID="local-login-user">
         <afp:DenyValueRule xsi:type="basic:ANY" />
      </afp:AttributeRule>
   </afp:AttributeFilterPolicy>

   ...
</afp:AttributeFilterPolicyGroup>
```


text:
bool g_ReplaceMaterials	= false;

static KeyValues *kv			= 0;
static KeyValues *allMapKeys	= 0;
static KeyValues *curMapKeys	= 0;

//-----------------------------------------------------------------------------
// Purpose: Loads the KeyValues file for materials replacements
//-----------------------------------------------------------------------------
void LoadMaterialReplacementKeys( const char *gamedir, const char *mapname )
{
	// Careful with static variables
	if( kv )
	{
		kv->deleteThis();
		kv = 0;
	}
	if( allMapKeys )
		allMapKeys = 0;
	if( curMapKeys )
		curMapKeys = 0;

	Msg( "Loading Replacement Keys\n" );

	// Attach the path to the keyValues file
	char path[1024];
	Q_snprintf( path, sizeof( path ), "%scfg\\materialsub.cfg", gamedir );

	// Load the keyvalues file
	kv = new KeyValues( "MaterialReplacements" );

	Msg( "File path: %s", path );
	if( !kv->LoadFromFile( g_pFileSystem, path ) )
	{
		Msg( "Failed to load KeyValues file!\n" );
		g_ReplaceMaterials = false;
		kv->deleteThis();
		kv = 0;
		return;
	}

	// Load global replace keys
	allMapKeys = kv->FindKey( "AllMaps", true );

	// Load keys for the current map
	curMapKeys = kv->FindKey( mapname );

	allMapKeys->ChainKeyValue( curMapKeys );
}

//-----------------------------------------------------------------------------
// Purpose: Deletes all keys
//-----------------------------------------------------------------------------
void DeleteMaterialReplacementKeys( void )
{
	if( kv )
	{
		kv->deleteThis();
		kv = 0;
	}
}

//-----------------------------------------------------------------------------
// Purpose: Replace the passed-in material name with a replacement name, if one exists
//-----------------------------------------------------------------------------
const char* ReplaceMaterialName( const char *name )
{
	// Look for the material name in the global and map KeyValues
	// If it's not there, just return the original name

	// HACK: This stinks - KeyValues won't take a string with '/' in it.
	// If they did, this could be a simple pointer swap.
	char newName[1024];
	Q_strncpy( newName, name, sizeof( newName ) );
	Q_FixSlashes( newName );
	return allMapKeys->GetString( newName, name );
}


text:
const childProcess = require('child_process');
const electron = require('electron');
const gulp = require('gulp');

gulp.task('start', ['build', 'watch'], () => {
  childProcess.spawn(electron, ['.', '--force-gpu-rasterization'], { stdio: 'inherit' })
  .on('close', () => {
    // User closed the app. Kill the host process.
    process.exit();
  })
  .on('error', spawnError => console.error(spawnError));
});


text:
#ifndef PUSTAK_HPP
#define PUSTAK_HPP

#include "cards/Playable.hpp"
#include "cards/BaseCardImpl.hpp"
namespace Cards{
class Pustak : public Playable, public BaseCardImpl{ //virtual inheritance needs the base class to be inherited normally exactly once so we inherit it non-virtually at the very last step
public:
    string getName() override;
    CardPtr makeNew() override;
    void played(GameServer& game) override;

    inline virtual ~Pustak(){}
};
}

#endif /* PUSTAK_HPP */


text:
RMPCDMD: Reactive MultiParticle Collision Dynamics - Molecular Dynamics
=======================================================================

**Homepage:** [RMPCDMD](http://lab.pdebuyl.be/rmpcdmd/) (includes documentation)
**License:** BSD 3-clause, see [LICENSE](LICENSE).

[![Build Status](https://travis-ci.org/pdebuyl-lab/RMPCDMD.svg?branch=master)](https://travis-ci.org/pdebuyl-lab/RMPCDMD)

RMPCDMD is a collection of Fortran modules and programs for the
mesoscopic modeling of chemically active fluids with embedded colloids.

## Status

RMPCDMD is ready to use for chemically powered dimer nanomotor simulations.
A former version of this code, still available in the branches `trs`
and `trs_two_prod`, was used to obtain the results presented in P. de
Buyl and R. Kapral [Nanoscale 5, 1337-1344
(2013)](http://dx.doi.org/10.1039/C2NR33711H) and P. de Buyl,
A. S. Mikhailov and R. Kapral [EPL 103, 60009
(2013)](http://dx.doi.org/10.1209/0295-5075/103/60009).

The current version has been totally refactored to remove the use of global variables,
enable testing and enable OpenMP multithreaded operation.

## Citation

RMPCDMD is presented in the article *RMPCDMD: Simulations of colloids with
coarse-grained hydrodynamics, chemical reactions and external fields*, Journal
of Open Research Software (JORS) **5**, 3 (2017)
[doi](http://doi.org/10.5334/jors.142) -
[arXiv:1608.04904](https://arxiv.org/abs/1608.04904)

Please cite this paper if you use RMPCDMD in a research work. A bibtex entry is provided in
the [CITATION](CITATION) file.

## Requirements

RMPCDMD has the following requirements:

- A Fortran 2008 compiler (e.g. [gfortran](https://gcc.gnu.org/wiki/GFortran) ≥ 4.7 with support for [OpenMP](https://gcc.gnu.org/wiki/openmp) ≥ 3.1)
- A Fortran enabled [HDF5](https://www.hdfgroup.org/HDF5/) installation
- [CMake](http://cmake.org/)
- [GNU Make](https://www.gnu.org/software/make/)
- [git](http://git-scm.com/)

See the documentation for
[installation instructions](http://lab.pdebuyl.be/rmpcdmd/install.html) for Linux and OS X.

## Contact

- The contact for RMPCDMD is the main author, [Pierre de Buyl](http://pdebuyl.be/).
- Bug reports are welcome either by email or via
  [GitHub issues](https://github.com/pdebuyl-lab/RMPCDMD/issues).

## Contributors

Peter Colberg: general programming improvements, OpenMP, debugging
Laurens Deprez: single colloid setup, gravity field and corresponding bounce-back, shake/rattle for dimers
Mu-Jie Huang: parts of the tutorial


text:
{% extends 'layouts/base.html' %}

{% block nav %}{% endblock %}

{% block footer %}

Powered by {{config.SERVICE_NAME}}. Read more.

{% endblock %}


text:
"""Base classes for type definitions in the STIX2 library."""

import collections
import collections.abc
import copy
import itertools
import re
import uuid

import simplejson as json

import stix2
from stix2.canonicalization.Canonicalize import canonicalize

from .exceptions import (
    AtLeastOnePropertyError, DependentPropertiesError, ExtraPropertiesError,
    ImmutableError, InvalidObjRefError, InvalidValueError,
    MissingPropertiesError, MutuallyExclusivePropertiesError, STIXError,
)
from .markings import _MarkingsMixin
from .markings.utils import validate
from .registry import class_for_type
from .serialization import STIXJSONEncoder, fp_serialize, serialize
from .utils import NOW, PREFIX_21_REGEX, get_timestamp
from .versioning import new_version as _new_version
from .versioning import revoke as _revoke

DEFAULT_ERROR = "{type} must have {property}='{expected}'."
SCO_DET_ID_NAMESPACE = uuid.UUID("00abedb4-aa42-466c-9c01-fed23315a9b7")

def get_required_properties(properties):
    return (k for k, v in properties.items() if v.required)

class _STIXBase(collections.abc.Mapping):
    """Base class for STIX object types"""

    def _check_property(self, prop_name, prop, kwargs, allow_custom):
        if prop_name not in kwargs:
            if hasattr(prop, 'default'):
                value = prop.default()
                if value == NOW:
                    value = self.__now
                kwargs[prop_name] = value

        has_custom = False
        if prop_name in kwargs:
            try:
                kwargs[prop_name], has_custom = prop.clean(
                    kwargs[prop_name], allow_custom,
                )
            except InvalidValueError:
                # No point in wrapping InvalidValueError in another
                # InvalidValueError... so let those propagate.
                raise
            except Exception as exc:
                raise InvalidValueError(
                    self.__class__, prop_name, reason=str(exc),
                ) from exc

        return has_custom

    # inter-property constraint methods

    def _check_mutually_exclusive_properties(self, list_of_properties, at_least_one=True):
        current_properties = self.properties_populated()
        count = len(set(list_of_properties).intersection(current_properties))
        # at_least_one allows for xor to be checked
        if count > 1 or (at_least_one and count == 0):
            raise MutuallyExclusivePropertiesError(self.__class__, list_of_properties)

    def _check_at_least_one_property(self, properties_checked=None):
        """
        Check whether one or more of the given properties are present.

        :param properties_checked: An iterable of the names of the properties
            of interest, or None to check against a default list.  The default
            list includes all properties defined on the object, with some
            hard-coded exceptions.
        :raises AtLeastOnePropertyError: If none of the given properties are
            present.
        """
        if properties_checked is None:
            property_exceptions = {"extensions", "type"}
            if isinstance(self, _Observable):
                property_exceptions |= {"id", "defanged", "spec_version"}

            properties_checked = self._properties.keys() - property_exceptions

        elif not isinstance(properties_checked, set):
            properties_checked = set(properties_checked)

        if properties_checked:
            properties_checked_assigned = properties_checked & self.keys()

            if not properties_checked_assigned:
                raise AtLeastOnePropertyError(
                    self.__class__, properties_checked,
                )

    def _check_properties_dependency(self, list_of_properties, list_of_dependent_properties):
        failed_dependency_pairs = []
        for p in list_of_properties:
            for dp in list_of_dependent_properties:
                if not self.get(p) and self.get(dp):
                    failed_dependency_pairs.append((p, dp))
        if failed_dependency_pairs:
            raise DependentPropertiesError(self.__class__, failed_dependency_pairs)

    def _check_object_constraints(self):
        for m in self.get('granular_markings', []):
            validate(self, m.get('selectors'))

    def __init__(self, allow_custom=False, **kwargs):
        cls = self.__class__

        # Use the same timestamp for any auto-generated datetimes
        self.__now = get_timestamp()

        custom_props = kwargs.pop('custom_properties', {})
        if custom_props and not isinstance(custom_props, dict):
            raise ValueError("'custom_properties' must be a dictionary")

        # Detect any keyword arguments representing customization.
        # In STIX 2.1, this is complicated by "toplevel-property-extension"
        # type extensions, which can add extra properties which are *not*
        # considered custom.
        extensions = kwargs.get("extensions")
        registered_toplevel_extension_props = {}
        has_unregistered_toplevel_extension = False
        if extensions:
            for ext_id, ext in extensions.items():
                if ext.get("extension_type") == "toplevel-property-extension":
                    registered_ext_class = class_for_type(
                        ext_id, "2.1", "extensions",
                    )
                    if registered_ext_class:
                        registered_toplevel_extension_props.update(
                            registered_ext_class._toplevel_properties,
                        )
                    else:
                        has_unregistered_toplevel_extension = True

        if has_unregistered_toplevel_extension:
            # Must assume all extras are extension properties, not custom.
            custom_kwargs = set()

        else:
            # All toplevel property extensions (if any) have been
            # registered.  So we can tell what their properties are and
            # treat only those as not custom.
            custom_kwargs = kwargs.keys() - self._properties.keys() \
                - registered_toplevel_extension_props.keys()

        if custom_kwargs and not allow_custom:
            raise ExtraPropertiesError(cls, custom_kwargs)

        if custom_props:
            # loophole for custom_properties...
            allow_custom = True

        all_custom_prop_names = (custom_kwargs | custom_props.keys()) - \
            self._properties.keys()
        if all_custom_prop_names:
            if not isinstance(self, stix2.v20._STIXBase20):
                for prop_name in all_custom_prop_names:
                    if not re.match(PREFIX_21_REGEX, prop_name):
                        raise InvalidValueError(
                            self.__class__, prop_name,
                            reason="Property name '%s' must begin with an alpha character." % prop_name,
                        )

        # defined_properties = all properties defined on this type, plus all
        # properties defined on this instance as a result of toplevel property
        # extensions.
        defined_properties = collections.ChainMap(
            self._properties, registered_toplevel_extension_props,
        )

        assigned_properties = collections.ChainMap(kwargs, custom_props)

        # Establish property order: spec-defined, toplevel extension, custom.
        toplevel_extension_props = registered_toplevel_extension_props.keys() \
            | (kwargs.keys() - self._properties.keys() - custom_kwargs)
        property_order = itertools.chain(
            self._properties,
            toplevel_extension_props,
            sorted(all_custom_prop_names),
        )

        setting_kwargs = {}

        has_custom = bool(all_custom_prop_names)
        for prop_name in property_order:

            prop_val = assigned_properties.get(prop_name)
            if prop_val not in (None, []):
                setting_kwargs[prop_name] = prop_val

            prop = defined_properties.get(prop_name)
            if prop:
                temp_custom = self._check_property(
                    prop_name, prop, setting_kwargs, allow_custom,
                )

                has_custom = has_custom or temp_custom

        # Detect any missing required properties
        required_properties = set(
            get_required_properties(defined_properties),
        )
        missing_kwargs = required_properties - setting_kwargs.keys()
        if missing_kwargs:
            raise MissingPropertiesError(cls, missing_kwargs)

        # Cache defaulted optional properties for serialization
        defaulted = []
        for name, prop in defined_properties.items():
            try:
                if (
                    not prop.required and not hasattr(prop, '_fixed_value') and
                    prop.default() == setting_kwargs[name]
                ):
                    defaulted.append(name)
            except (AttributeError, KeyError):
                continue
        self._defaulted_optional_properties = defaulted

        self._inner = setting_kwargs

        self._check_object_constraints()

        if allow_custom:
            self.__has_custom = has_custom

        else:
            # The simple case: our property cleaners are supposed to do their
            # job and prevent customizations, so we just set to False.  But
            # this sanity check is helpful for finding bugs in those clean()
            # methods.
            if has_custom:
                raise STIXError(
                    "Internal error: a clean() method did not properly enforce "
                    "allow_custom=False!",
                )

            self.__has_custom = False

    def __getitem__(self, key):
        return self._inner[key]

    def __iter__(self):
        return iter(self._inner)

    def __len__(self):
        return len(self._inner)

    # Handle attribute access just like key access
    def __getattr__(self, name):
        # Pickle-proofing: pickle invokes this on uninitialized instances (i.e.
        # __init__ has not run).  So no "self" attributes are set yet.  The
        # usual behavior of this method reads an __init__-assigned attribute,
        # which would cause infinite recursion.  So this check disables all
        # attribute reads until the instance has been properly initialized.
        unpickling = '_inner' not in self.__dict__
        if not unpickling and name in self:
            return self.__getitem__(name)
        raise AttributeError(
            "'%s' object has no attribute '%s'" %
            (self.__class__.__name__, name),
        )

    def __setattr__(self, name, value):
        if not name.startswith("_"):
            raise ImmutableError(self.__class__, name)
        super(_STIXBase, self).__setattr__(name, value)

    def __str__(self):
        # Note: use .serialize() or fp_serialize() directly if specific formatting options are needed.
        return self.serialize()

    def __repr__(self):
        props = ', '.join([f"{k}={self[k]!r}" for k in self])
        return f'{self.__class__.__name__}({props})'

    def __deepcopy__(self, memo):
        # Assume: we can ignore the memo argument, because no object will ever contain the same sub-object multiple times.
        new_inner = copy.deepcopy(self._inner, memo)
        cls = type(self)
        if isinstance(self, _Observable):
            # Assume: valid references in the original object are still valid in the new version
            new_inner['_valid_refs'] = {'*': '*'}
        return cls(allow_custom=True, **new_inner)

    def properties_populated(self):
        return list(self._inner.keys())

    @property
    def has_custom(self):
        return self.__has_custom

    #  Versioning API

    def new_version(self, **kwargs):
        return _new_version(self, **kwargs)

    def revoke(self):
        return _revoke(self)

    def serialize(self, *args, **kwargs):
        """
        Serialize a STIX object.

        Examples:
            >>> import stix2
            >>> identity = stix2.Identity(name='Example Corp.', identity_class='organization')
            >>> print(identity.serialize(sort_keys=True))
            {"created": "2018-06-08T19:03:54.066Z", ... "name": "Example Corp.", "type": "identity"}
            >>> print(identity.serialize(sort_keys=True, indent=4))
            {
                "created": "2018-06-08T19:03:54.066Z",
                "id": "identity--d7f3e25a-ba1c-447a-ab71-6434b092b05e",
                "identity_class": "organization",
                "modified": "2018-06-08T19:03:54.066Z",
                "name": "Example Corp.",
                "type": "identity"
            }

        Returns:
            str: The serialized JSON object.

        See Also:
            ``stix2.serialization.serialize`` for options.
        """
        return serialize(self, *args, **kwargs)

    def fp_serialize(self, *args, **kwargs):
        """
        Serialize a STIX object to ``fp`` (a text stream file-like supporting object).

        Examples:
            >>> import stix2
            >>> identity = stix2.Identity(name='Example Corp.', identity_class='organization')
            >>> print(identity.serialize(sort_keys=True))
            {"created": "2018-06-08T19:03:54.066Z", ... "name": "Example Corp.", "type": "identity"}
            >>> print(identity.serialize(sort_keys=True, indent=4))
            {
                "created": "2018-06-08T19:03:54.066Z",
                "id": "identity--d7f3e25a-ba1c-447a-ab71-6434b092b05e",
                "identity_class": "organization",
                "modified": "2018-06-08T19:03:54.066Z",
                "name": "Example Corp.",
                "type": "identity"
            }
            >>> with open("example.json", mode="w", encoding="utf-8") as f:
            >>>     identity.fp_serialize(f, pretty=True)

        Returns:
            None

        See Also:
            ``stix2.serialization.fp_serialize`` for options.
        """
        fp_serialize(self, *args, **kwargs)

class _DomainObject(_STIXBase, _MarkingsMixin):
    pass

class _RelationshipObject(_STIXBase, _MarkingsMixin):
    pass

class _Observable(_STIXBase):

    def __init__(self, **kwargs):
        # the constructor might be called independently of an observed data object
        self._STIXBase__valid_refs = kwargs.pop('_valid_refs', [])
        super(_Observable, self).__init__(**kwargs)

    def _check_ref(self, ref, prop, prop_name):
        """
        Only for checking `*_ref` or `*_refs` properties in spec_version 2.0
        STIX Cyber Observables (SCOs)
        """

        if '*' in self._STIXBase__valid_refs:
            return  # don't check if refs are valid

        if ref not in self._STIXBase__valid_refs:
            raise InvalidObjRefError(self.__class__, prop_name, "'%s' is not a valid object in local scope" % ref)

        try:
            allowed_types = prop.contained.valid_types
        except AttributeError:
            allowed_types = prop.valid_types

        try:
            try:
                ref_type = self._STIXBase__valid_refs[ref].type
            except AttributeError:
                ref_type = self._STIXBase__valid_refs[ref]
        except TypeError:
            raise ValueError("'%s' must be created with _valid_refs as a dict, not a list." % self.__class__.__name__)

        if allowed_types:
            if ref_type not in allowed_types:
                raise InvalidObjRefError(self.__class__, prop_name, "object reference '%s' is of an invalid type '%s'" % (ref, ref_type))

    def _check_property(self, prop_name, prop, kwargs, allow_custom):
        has_custom = super(_Observable, self)._check_property(prop_name, prop, kwargs, allow_custom)

        if prop_name in kwargs:
            from .properties import ObjectReferenceProperty
            if prop_name.endswith('_ref'):
                if isinstance(prop, ObjectReferenceProperty):
                    ref = kwargs[prop_name]
                    self._check_ref(ref, prop, prop_name)
            elif prop_name.endswith('_refs'):
                if isinstance(prop.contained, ObjectReferenceProperty):
                    for ref in kwargs[prop_name]:
                        self._check_ref(ref, prop, prop_name)

        return has_custom

    def _generate_id(self):
        """
        Generate a UUIDv5 for this observable, using its "ID contributing
        properties".

        :return: The ID, or None if no ID contributing properties are set
        """

        id_ = None
        json_serializable_object = {}

        for key in self._id_contributing_properties:

            if key in self:
                obj_value = self[key]

                if key == "hashes":
                    serializable_value = _choose_one_hash(obj_value)

                    if serializable_value is None:
                        raise InvalidValueError(
                            self, key, "No hashes given",
                        )

                else:
                    serializable_value = _make_json_serializable(obj_value)

                json_serializable_object[key] = serializable_value

        if json_serializable_object:

            data = canonicalize(json_serializable_object, utf8=False)
            uuid_ = uuid.uuid5(SCO_DET_ID_NAMESPACE, data)
            id_ = "{}--{}".format(self._type, str(uuid_))

        return id_

class _Extension(_STIXBase):

    def _check_object_constraints(self):
        super(_Extension, self)._check_object_constraints()
        self._check_at_least_one_property()

def _choose_one_hash(hash_dict):
    if "MD5" in hash_dict:
        return {"MD5": hash_dict["MD5"]}
    elif "SHA-1" in hash_dict:
        return {"SHA-1": hash_dict["SHA-1"]}
    elif "SHA-256" in hash_dict:
        return {"SHA-256": hash_dict["SHA-256"]}
    elif "SHA-512" in hash_dict:
        return {"SHA-512": hash_dict["SHA-512"]}
    else:
        k = next(iter(hash_dict), None)
        if k is not None:
            return {k: hash_dict[k]}

    return None

def _cls_init(cls, obj, kwargs):
    if getattr(cls, '__init__', object.__init__) is not object.__init__:
        cls.__init__(obj, **kwargs)

def _make_json_serializable(value):
    """
    Make the given value JSON-serializable; required for the JSON canonicalizer
    to work.  This recurses into lists/dicts, converts stix objects to dicts,
    etc.  "Convenience" types this library uses as property values are
    JSON-serialized to produce a JSON-serializable value.  (So you will always
    get strings for those.)

    The conversion will not affect the passed in value.

    :param value: The value to make JSON-serializable.
    :return: The JSON-serializable value.
    :raises ValueError: If value is None (since nulls are not allowed in STIX
        objects).
    """
    if value is None:
        raise ValueError("Illegal null value found in a STIX object")

    json_value = value  # default assumption

    if isinstance(value, collections.abc.Mapping):
        json_value = {
            k: _make_json_serializable(v)
            for k, v in value.items()
        }

    elif isinstance(value, list):
        json_value = [
            _make_json_serializable(v)
            for v in value
        ]

    elif not isinstance(value, (int, float, str, bool)):
        # If a "simple" value which is not already JSON-serializable,
        # JSON-serialize to a string and use that as our JSON-serializable
        # value.  This applies to our datetime objects currently (timestamp
        # properties), and could apply to any other "convenience" types this
        # library uses for property values in the future.
        json_value = json.dumps(value, ensure_ascii=False, cls=STIXJSONEncoder)

        # If it looks like a string literal was output, strip off the quotes.
        # Otherwise, a second pair will be added when it's canonicalized.  Also
        # to be extra safe, we need to unescape.
        if len(json_value) >= 2 and \
                json_value[0] == '"' and json_value[-1] == '"':
            json_value = _un_json_escape(json_value[1:-1])

    return json_value

_JSON_ESCAPE_RE = re.compile(r"\\.")
# I don't think I should need to worry about the unicode escapes (\uXXXX)
# since I use ensure_ascii=False when generating it.  I will just fix all
# the other escapes, e.g. \n, \r, etc.
#
# This list is taken from RFC8259 section 7:
# https://tools.ietf.org/html/rfc8259#section-7
# Maps the second char of a "\X" style escape, to a replacement char
_JSON_ESCAPE_MAP = {
    '"': '"',
    "\\": "\\",
    "/": "/",
    "b": "\b",
    "f": "\f",
    "n": "\n",
    "r": "\r",
    "t": "\t",
}

def _un_json_escape(json_string):
    """
    Removes JSON string literal escapes.  We should undo these things Python's
    serializer does, so we can ensure they're done canonically.  The
    canonicalizer should be in charge of everything, as much as is feasible.

    :param json_string: String literal output of Python's JSON serializer,
        minus the surrounding quotes.
    :return: The unescaped string
    """

    def replace(m):
        replacement = _JSON_ESCAPE_MAP.get(m.group(0)[1])
        if replacement is None:
            raise ValueError("Unrecognized JSON escape: " + m.group(0))

        return replacement

    result = _JSON_ESCAPE_RE.sub(replace, json_string)

    return result


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DisasterReport.DisasterService.Dto;
using Abp.Domain.Repositories;
using DisasterReport.DomainEntities;
using Abp.AutoMapper;
using DisasterReport;
using DisasterReport.DisasterService;
using DisasterReport.DtoTemplate;
using DisasterReport.DisasterService.Event;
using Abp.Events.Bus;
using Abp.UI;

namespace DisasterAppService.DisasterService
{
    public class DisasterAppService : DisasterReportAppServiceBase, IDisasterAppService
    {
        private readonly IRepository<DisasterInfoTb, Guid> _disasterInfoTbRepository;
        private readonly IRepository<UploadsFileTb, Guid> _uploadsFileTbRespository;
        private readonly IRepository<ReporterInfoTb, Guid> _reporterInfoRespository;
        private readonly IRepository<DisasterKindTb, Guid> _disasterKindTbRespository;
        private readonly IRepository<MessageGroupTb, Guid> _messageGroupRespository;
        private readonly IRepository<DisasterRescueTb, Guid> _disasterRescueRepo;

        public IEventBus EventBus { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public DisasterAppService(
                IRepository<DisasterInfoTb, Guid> disasterInfoTbRepository,
                IRepository<UploadsFileTb, Guid> uploadsFileTbRespository,
                IRepository<ReporterInfoTb, Guid> reporterInfoRespository,
                IRepository<DisasterKindTb, Guid> disasterKindTbRespository,
                IRepository<MessageGroupTb, Guid> messageGroupRespository,
                IRepository<DisasterRescueTb, Guid> disasterRescueRepo
            )
        {
            EventBus = NullEventBus.Instance;
            _disasterInfoTbRepository = disasterInfoTbRepository;
            _uploadsFileTbRespository = uploadsFileTbRespository;
            _reporterInfoRespository = reporterInfoRespository;
            _disasterKindTbRespository = disasterKindTbRespository;
            _messageGroupRespository = messageGroupRespository;
            _disasterRescueRepo = disasterRescueRepo;
        }

        /// <summary>
        /// 分页获取灾情
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="type">上报类型 1-移动网络 2-北斗短报文 9-全部</param>
        /// <param name="status">灾情是否已处理 0-没有处理 1-正在处理 2-已处理 9-全部</param>
        /// <returns></returns>
        public RuimapPageResultDto<ReportDisasterOutput> GetPageDisaster(int pageIndex = 1, int pageSize = 9999, int type = 9, int status = 9)
        {
            var count = 0;
            List<DisasterInfoTb> result;
            if (type == 9 && status == 9)
            {
                count = _disasterInfoTbRepository.Count();
                result = _disasterInfoTbRepository.GetAll().OrderByDescending(d => d.ReportDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            } else  if(type == 9 && status != 9)
            {
                count = _disasterInfoTbRepository.Count(d => d.Status == status);
                result = _disasterInfoTbRepository.GetAll().Where(d => d.Status == status).OrderByDescending(d => d.ReportDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            } else if(type != 9 && status == 9)
            {
                count = _disasterInfoTbRepository.Count(d => d.Type == type);
                result = _disasterInfoTbRepository.GetAll().Where(d => d.Type == type).OrderByDescending(d => d.ReportDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            } else
            {
                count = _disasterInfoTbRepository.Count(d => d.Type == type && d.Status == status);
                result = _disasterInfoTbRepository.GetAll().Where(d => d.Type == type && d.Status == status).OrderByDescending(d => d.ReportDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            int currPage = pageIndex;
            int totalPage = (int)Math.Ceiling(count / (pageSize * 1.0));

            return new RuimapPageResultDto<ReportDisasterOutput>(count, currPage, totalPage, result.MapTo<List<ReportDisasterOutput>>());
        }

        /// <summary>
        /// 手持终端上报灾情
        /// </summary>
        /// <param name="input"></param>
        public void ReportDisaster(ReportDisasterInput input)
        {
            var uploads = input.UploadFiles;
            var disaster = input.MapTo<DisasterInfoTb>();
            disaster.Status = 0;    // 没有处理
            disaster.ReportDate = DateTime.Now;
            disaster.DisasterCode = "[DC]-" + Guid.NewGuid();

            var existReporter = _reporterInfoRespository.FirstOrDefault(r => r.Id == input.ReporterId);
            if(existReporter == null)
            {
                throw new UserFriendlyException("没有对应的上报人员");
            }

            disaster.Reporter = existReporter;

            var existDisasterKind = _disasterKindTbRespository.FirstOrDefault(d => d.KindCode == input.DisasterKindCode);
            if(existDisasterKind == null)
            {
                throw new UserFriendlyException("没有对应的灾情类型");
            }

            disaster.DisasterKind = existDisasterKind;

            var id = _disasterInfoTbRepository.InsertAndGetId(disaster);

            for(var i = 0; i < uploads.Count(); i++)
            {
                var fileInsertInfo = new UploadsFileTb
                {
                    OtherRowId = id,
                    FileName = uploads[i].FileName,
                    Path = uploads[i].FilePath
                };
                _uploadsFileTbRespository.Insert(fileInsertInfo);
            }

            // 推送新增灾情Id给web管理终端
            EventBus.Trigger(new DisasterReportEventData() { DisasterInfoId = id });
        }

        public async Task<ReportDisasterOutput> GetDisasterById(Guid id)
        {
            var result = await _disasterInfoTbRepository.FirstOrDefaultAsync(d => d.Id == id);
            if(result == null)
            {
                throw new UserFriendlyException("查询不到相应的灾情");
            }
            return result.MapTo<ReportDisasterOutput>();
        }

        public List<UploadsFileTbOutput> GetDisasterFilePicById(Guid id)
        {
            List<UploadsFileTb> result;

            result = _uploadsFileTbRespository.GetAllList(u=>u.OtherRowId == id);

            return result.MapTo<List<UploadsFileTbOutput>>();
        }

        public RuimapPageResultDto<ReportDisasterOutput> GetPageDisasterByReporterId(Guid id, int pageIndex = 1, int pageSize = 9999, int type = 9, int status = 9)
        {
            var count = 0;
            List<DisasterInfoTb> result;
            if (type == 9 && status == 9)
            {
                count = _disasterInfoTbRepository.Count(d => d.Reporter.Id == id);
                result = _disasterInfoTbRepository.GetAll().Where(d => d.Reporter.Id == id).OrderByDescending(d => d.ReportDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else if (type == 9 && status != 9)
            {
                count = _disasterInfoTbRepository.Count(d => d.Status == status);
                result = _disasterInfoTbRepository.GetAll().Where(d => d.Status == status && d.Reporter.Id == id).OrderByDescending(d => d.ReportDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else if (type != 9 && status == 9)
            {
                count = _disasterInfoTbRepository.Count(d => d.Type == type);
                result = _disasterInfoTbRepository.GetAll().Where(d => d.Type == type && d.Reporter.Id == id).OrderByDescending(d => d.ReportDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                count = _disasterInfoTbRepository.Count(d => d.Type == type && d.Status == status);
                result = _disasterInfoTbRepository.GetAll().Where(d => d.Type == type && d.Status == status && d.Reporter.Id == id).OrderByDescending(d => d.ReportDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            int currPage = pageIndex;
            int totalPage = (int)Math.Ceiling(count / (pageSize * 1.0));

            return new RuimapPageResultDto<ReportDisasterOutput>(count, currPage, totalPage, result.MapTo<List<ReportDisasterOutput>>());
        }

        public List<DisasterKindDetailOutput> GetDisasterKindCount()
        {
            // 先找出有多少个子类灾情种类
            var existKinds = _disasterKindTbRespository.GetAll().Where(d => d.Pid.ToString() != "0").ToList();
            if(existKinds == null)
            {
                throw new UserFriendlyException("没有灾情种类");
            }

            List<DisasterKindDetailOutput> outList = new List<DisasterKindDetailOutput>();
            // 分别查找出对应的灾情个数
            foreach (var i in existKinds)
            {
                var _count = _disasterInfoTbRepository.Count(d => d.DisasterKind.Id == i.Id);
                outList.Add(new DisasterKindDetailOutput()
                {
                    KindName = i.Name,
                    KindCount = _count
                });
            }

            return outList;
        }

        public List<DisasterKindNetWorkOutput> GetDisasterNetworkCount()
        {
            // 上报类型 1-移动网络 2-北斗短报文
            List<DisasterKindNetWorkOutput> outList = new List<DisasterKindNetWorkOutput>();

            // 移动
            var _count = _disasterInfoTbRepository.Count(d => d.Type == 1);
            outList.Add(new DisasterKindNetWorkOutput()
            {
                Type = "移动上报",
                Count = _count
            });

            _count = _disasterInfoTbRepository.Count(d => d.Type == 2);
            outList.Add(new DisasterKindNetWorkOutput()
            {
                Type = "北斗上报",
                Count = _count
            });

            return outList;
        }

        public List<DisasterTrendOutput> GetDisasterTrend(int type = 1)
        {
            // 默认得到1年以内的灾情趋势
            var currDate = DateTime.Today;
            List<DisasterTrendOutput> outList = new List<DisasterTrendOutput>();
            if(type == 1)
            {
                // 获取12个月份的记录
                for (var i = 0; i < 12; i++)
                {
                    // 全部
                    var tempCurrDate = currDate.AddMonths(-i);
                    var _count = _disasterInfoTbRepository.Count(d => d.ReportDate.Month == tempCurrDate.Month && d.ReportDate.Year == tempCurrDate.Year);
                    // 已处理
                    var _solveCount = _disasterInfoTbRepository.Count(d => d.ReportDate.Month == tempCurrDate.Month && d.ReportDate.Year == tempCurrDate.Year && d.Status == 2);
                    outList.Add(new DisasterTrendOutput()
                    {
                        Count = _count,
                        SolveCount = _solveCount,
                        Date = currDate.AddMonths(-i).Year.ToString() + "年" + currDate.AddMonths(-i).Month.ToString() + "月"
                    });
                }
            }
            else if(type == 2)
            {
                // 获取30天以内的记录
                for (var i = 0; i < 30; i++)
                {
                    // 全部
                    var tempCurrDate = currDate.AddDays(-i);
                    var _count = _disasterInfoTbRepository.Count(d => d.ReportDate.Year == tempCurrDate.Year && d.ReportDate.Month == tempCurrDate.Month && d.ReportDate.Day == tempCurrDate.Day);
                    // 已处理
                    var _solveCount = _disasterInfoTbRepository.Count(d => d.ReportDate.Year == tempCurrDate.Year && d.ReportDate.Month == tempCurrDate.Month && d.ReportDate.Day == tempCurrDate.Day && d.Status == 2);
                    outList.Add(new DisasterTrendOutput()
                    {
                        Count = _count,
                        SolveCount = _solveCount,
                        Date = currDate.AddDays(-i).Year.ToString() + "年" + currDate.AddDays(-i).Month.ToString() + "月" + currDate.AddDays(-i).Day.ToString() + "日"
                    });
                }
            }
            return outList;
        }

        public DisasterResultSumOutput GetDisasterResultSum()
        {
            DisasterResultSumOutput outResult = new DisasterResultSumOutput();

            outResult.DisasterCount = _disasterInfoTbRepository.Count();
            outResult.FinishCount = _disasterInfoTbRepository.Count(d => d.Status == 2);
            outResult.RemainderCount = _disasterInfoTbRepository.Count(d => d.Status != 2);
            var tempCurrDate = DateTime.Today;
            outResult.TodayCount = _disasterInfoTbRepository.Count(d => d.ReportDate.Year == tempCurrDate.Year && d.ReportDate.Month == tempCurrDate.Month && d.ReportDate.Day == tempCurrDate.Day);

            outResult.RescueCount = _messageGroupRespository.Count();
            outResult.ReporterCount = _reporterInfoRespository.Count(r => r.Type == 1);

            return outResult;
        }

        public ReportDisasterOutput SetDisasterStatus(SetDisasterStatusInput input)
        {
            var existDisaster = _disasterInfoTbRepository.FirstOrDefault(d => d.Id == input.DisasterId);
            if(existDisaster == null)
            {
                throw new UserFriendlyException("没有相应的灾情");
            }

            existDisaster.Status = input.Status;

            _disasterInfoTbRepository.InsertOrUpdate(existDisaster);

            return existDisaster.MapTo<ReportDisasterOutput>();
        }

        public List<DisasterAreaTotalOutput> GetAreaTotal()
        {
            var result = _disasterInfoTbRepository.GetAll().GroupBy(d => d.AreaCode).ToList();
            var outResult = new List<DisasterAreaTotalOutput>();
            for(var i = 0; i < result.Count; i++)
            {
                var key = result[i].Key;
                var count = _disasterInfoTbRepository.Count(d => d.AreaCode == key);
                var existDisaster = _disasterInfoTbRepository.FirstOrDefault(d => d.AreaCode == key);
                outResult.Add(new DisasterAreaTotalOutput()
                {
                    Count = count,
                    Lat = existDisaster.Lat,
                    Lng = existDisaster.Lng,
                    Name = existDisaster.DisasterAddress
                });
            }
            return outResult;
        }

        public List<DisasterKindOutput> GetDisasterKind()
        {
            var existKind = _disasterKindTbRespository.GetAll().Where(d => d.Pid.ToString() != "0").ToList();

            return existKind.MapTo<List<DisasterKindOutput>>();
        }

        public void UpdateDisasterKindIcon(DisasterKindUpdateInput input)
        {
            var existKind = _disasterKindTbRespository.FirstOrDefault(d => d.Id == input.Id);
            if(existKind == null)
            {
                throw new UserFriendlyException("没有此灾情种类");
            }
            try
            {
                existKind.Photo = input.Photo;
                _disasterKindTbRespository.Update(existKind);
            } catch(Exception e)
            {
                throw new Exception(e.Message);
            }
        }

        public void ResponseDisaster(ResponseDisasterInput input)
        {
            var existReporter = _reporterInfoRespository.FirstOrDefault(r => r.Id == input.ReporterId);
            if(existReporter == null)
            {
                throw new UserFriendlyException("没有此上报人员");
            }
            var existDisaster = _disasterInfoTbRepository.FirstOrDefault(d => d.Id == input.DisasterId);
            if(existDisaster == null)
            {
                throw new UserFriendlyException("没有此灾情");
            }

            // 查询此上报人员是否之前加入过了
            var existAdd = _disasterRescueRepo.FirstOrDefault(d => d.Disaster.Id == input.DisasterId && d.Reporter.Id == input.ReporterId);
            if(existAdd == null)
            {
                DisasterRescueTb newItem = new DisasterRescueTb();
                newItem.Reporter = existReporter;
                newItem.Disaster = existDisaster;
                newItem.StartTime = DateTime.Now;

                // 保存
                _disasterRescueRepo.Insert(newItem);

                // 更新
                existDisaster.Status = 1;   // 变为正在处理
                _disasterInfoTbRepository.InsertOrUpdate(existDisaster);

                // 查询出此上报人员属于哪一个队伍
                // 将队伍与灾情也关联起来
                // 找出之前存在的灾情
                var messageGroup = existReporter.MessageGroup;
                // 如果没有关联此灾情 则增加
                var existbool = messageGroup.Disaster.Any(m => m.Id == input.DisasterId);
                if(existbool == false)
                {
                    messageGroup.Disaster.Add(existDisaster);
                    _messageGroupRespository.InsertOrUpdate(messageGroup);
                }

                // 只有之前没有加入行动的才可以触发通知
                // 触发通知
                EventBus.Trigger(new ResponseDisasterEventData()
                {
                    ReporterId = existReporter.Id,
                    GroupName = existReporter.MessageGroup.GroupName,
                    Name = existReporter.Name,
                    DisasterKindName = existDisaster.DisasterKind.Name,
                    Type = "responseDisaster"
                });
            }
        }

        public void HasJoinDisasterRescue(HasJoinDisasterRescueInput input)
        {
            var hasJoin = _disasterRescueRepo.FirstOrDefault(d => d.Disaster.Id == input.DisasterId && d.Reporter.Id == input.ReporterId);
            if(hasJoin != null)
            {
                throw new UserFriendlyException("已经在此灾情救援行动中");
            }
        }
    }
}


text:
package biz.k11i.xgboost.spark.model

import biz.k11i.xgboost.spark.util.FVecMLVector
import biz.k11i.xgboost.{Predictor => XGBoostPredictor}
import org.apache.spark.ml.linalg.Vector
import org.apache.spark.ml.regression.RegressionModel
import org.apache.spark.ml.util.Identifiable

/**
 * XGBoost prediction model for regression task.
 *
 * @param uid               uid
 * @param _xgboostPredictor [[XGBoostPredictor]] instance
 */
class XGBoostRegressionModel(
  override val uid: String,
  _xgboostPredictor: XGBoostPredictor)
  extends RegressionModel[Vector, XGBoostRegressionModel]
    with XGBoostPredictionModel[XGBoostRegressionModel] {

  def this(xgboostPredictor: XGBoostPredictor) = this(Identifiable.randomUID("XGBoostPredictorRegressionModel"), xgboostPredictor)

  setDefault(xgboostPredictor, _xgboostPredictor)

  override protected def predict(features: Vector): Double = {
    getXGBoostPredictor.predictSingle(toFVec(features))
  }
}

object XGBoostRegression extends XGBoostPrediction[XGBoostRegressionModel] {
  override protected def newXGBoostModel(xgboostPredictor: XGBoostPredictor): XGBoostRegressionModel = new XGBoostRegressionModel(xgboostPredictor)
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
  Module: Nacho::Common

    — Documentation by YARD 0.8.7.6

</title>

  <link rel="stylesheet" href="../css/style.css" type="text/css" charset="utf-8" />

  <link rel="stylesheet" href="../css/common.css" type="text/css" charset="utf-8" />

    Index (C) »
    Nacho
     »
    Common

(no frames)

      Class List

      Method List

      File List

Module: Nacho::Common

Includes:

ActionView::Context

Included in:

ActionView::Helpers::FormHelper, Helper

Defined in:

lib/nacho/common.rb

Overview

The common code module for the FormBuilder helper and the form tag helper.

Author:

Daniel Ward

Constant Summary

HTML5_OPTION_VALUE_KEY =

"data-nacho-option-value-key"

HTML5_OPTION_TEXT_KEY =

"data-nacho-option-text-key"

HTML5_NEW_ITEM_VALUE_KEY =

"data-nacho-new-value-key"

HTML5_MODAL_ID_KEY =

"data-nacho-modal-id"

HTML5_MODAL_HTML_KEY =

"data-nacho-modal"

HTML5_ADD_NEW_VALUE_KEY =

"data-nacho-add-new-value"

  Generated on Wed Feb 24 22:56:32 2016 by
  yard
  0.8.7.6 (ruby-2.3.0).


text:
package com.taobao.tddl.repo.mysql.spi;

import javax.sql.DataSource;

import com.taobao.tddl.common.model.Group;
import com.taobao.tddl.executor.common.ExecutorContext;
import com.taobao.tddl.executor.common.TopologyHandler;
import com.taobao.tddl.executor.spi.IDataSourceGetter;
import com.taobao.tddl.executor.spi.IGroupExecutor;

public class DatasourceMySQLImplement implements IDataSourceGetter {

    public DataSource getDatasourceByGroupNode(TopologyHandler topology, String groupNode) {
        if ("undecided".equals(groupNode)) {
            return null;
        }
        IGroupExecutor matrixExecutor = topology.get(groupNode);

        if (matrixExecutor == null) return null;
        /*
         * 这里做个hack吧。 原因是在构造topologic的时候,默认全部使用mysql作为type了。
         * 这样就造成所有的Datasource都是由RemotingExecutor
         * com.taobao.ustore.jdbc.mysql.My_Reponsitory.buildRemoting(Group
         * group) 创建的,type都是mysql.
         * 但实际上这里的type需要根据实际的DataSource来决定是个oracle还是个mysql.
         * 如果是oracle那么type需要改成oracle..
         */
        Group.GroupType type = matrixExecutor.getGroupInfo().getType();
        DataSource ds = (DataSource) matrixExecutor.getRemotingExecutableObject();

        if (isNotValidateNode(type)) {
            throw new IllegalArgumentException("target node is not a validated Jdbc node");
        }

        if (ds == null) {
            throw new IllegalArgumentException("can't find ds by group name ");
        }
        return ds;
    }

    protected boolean isNotValidateNode(Group.GroupType type) {
        return !Group.GroupType.MYSQL_JDBC.equals(type) && !Group.GroupType.TDHS_CLIENT.equals(type)
               && !Group.GroupType.ORACLE_JDBC.equals(type) && !Group.GroupType.OCEANBASE_JDBC.equals(type);
    }

    @Override
    public DataSource getDataSource(String group) {
        return getDatasourceByGroupNode(ExecutorContext.getContext().getTopologyHandler(), group);
    }

}


text:
<?php

/**
 * Schema for a whole extension
 *
 * @version $ID:$
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License, version 3 or later
 */
class Tx_ExtensionBuilder_Exception extends TYPO3\CMS\Extbase\Exception {

	/**
	 * @var string
	 */
	protected $subKey = null;

	/**
	 * @param string $message
	 * @param integer $code
	 * @param Exception $previous
	 */
	public function __construct($message, $code, Exception $previous = null) {

		$this->findTranslationSubKeyByExceptionClassName();

		// Build the locallang label index
		$translationKey = 'error.';
		if ($this->subKey !== null) {
			$translationKey .= $this->subKey . '.';
		}
		$translationKey .= $code;

		// Get the translated message
		$translated = TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate($translationKey, 'ExtbaseBuilder');
		if (!empty($translated)) {
			$message = $translated;
		}

		parent::__construct($message, $code);
	}

	/**
	 * Find the translation subkey based on the class name of the exception
	 */
	protected function findTranslationSubKeyByExceptionClassName() {
		preg_match("/_([^_]*)Exception$/", get_class($this), $subKey);

		if (!empty($subKey[1])) {
			$this->subKey = \TYPO3\CMS\Core\Utility\GeneralUtility::camelCaseToLowerCaseUnderscored($subKey[1]);
		}
	}
}

?>


text:
'use strict';

import * as nls from 'vs/nls';
import {KeyCode, KeyMod} from 'vs/base/common/keyCodes';
import {TPromise} from 'vs/base/common/winjs.base';
import {INullService} from 'vs/platform/instantiation/common/instantiation';
import {EditorAction} from 'vs/editor/common/editorAction';
import {Behaviour} from 'vs/editor/common/editorActionEnablement';
import {Handler, ICommonCodeEditor, IEditorActionDescriptorData} from 'vs/editor/common/editorCommon';
import {CommonEditorRegistry, ContextKey, EditorActionDescriptor} from 'vs/editor/common/editorCommonExtensions';

class SelectBracketAction extends EditorAction {

	static ID = 'editor.action.jumpToBracket';

	constructor(descriptor:IEditorActionDescriptorData, editor:ICommonCodeEditor, @INullService ns) {
		super(descriptor, editor, Behaviour.TextFocus);
	}

	public run():TPromise<boolean> {

		this.editor.trigger(this.id, Handler.JumpToBracket, {});

		return TPromise.as(true);
	}

}

// register actions
CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(SelectBracketAction, SelectBracketAction.ID, nls.localize('smartSelect.jumpBracket', "Go to Bracket"), {
	context: ContextKey.EditorTextFocus,
	primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.US_BACKSLASH
}));