code
stringlengths
4
1.01M
using System; using System.Collections.Generic; using System.Text; namespace Vino.Core.TimedTask.Attribute { [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)] public class InvokeAttribute : System.Attribute { public string Name { set; get; } public bool IsEnabled { get; set; } = true; /// <summary> /// //设置是执行一次(false)还是一直执行(true),默认为true /// </summary> public bool AutoReset { set; get; } = true; public int Interval { get; set; } = 1000 * 60; // 1分钟 public DateTime BeginTime { set; get; } public DateTime ExpireTime { set; get; } } }
<?php /** * Part of Windwalker project Test files. * * @copyright Copyright (C) 2019 LYRASOFT Taiwan, Inc. * @license LGPL-2.0-or-later */ declare(strict_types=1); namespace Windwalker\Filesystem\Test; use Windwalker\Filesystem\File; use Windwalker\Filesystem\Path; /** * Test class of Path * * @since 2.0 */ class PathTest extends AbstractVfsTestCase { /** * Data provider for testClean() method. * * @return array * * @since 2.0 */ public function cleanProvider(): array { return [ // Input Path, Directory Separator, Expected Output 'Nothing to do.' => ['/var/www/foo/bar/baz', '/', '/var/www/foo/bar/baz'], 'One backslash.' => ['/var/www/foo\\bar/baz', '/', '/var/www/foo/bar/baz'], 'Two and one backslashes.' => ['/var/www\\\\foo\\bar/baz', '/', '/var/www/foo/bar/baz'], 'Mixed backslashes and double forward slashes.' => [ '/var\\/www//foo\\bar/baz', '/', '/var/www/foo/bar/baz', ], 'UNC path.' => ['\\\\www\\docroot', '\\', '\\\\www\\docroot'], 'UNC path with forward slash.' => ['\\\\www/docroot', '\\', '\\\\www\\docroot'], 'UNC path with UNIX directory separator.' => ['\\\\www/docroot', '/', '/www/docroot'], 'Stream URL.' => ['vfs://files//foo\\bar', '/', 'vfs://files/foo/bar'], 'Stream URL empty.' => ['vfs://', '/', 'vfs://'], 'Windows path.' => ['C:\\files\\\\foo//bar', '\\', 'C:\\files\\foo\\bar'], 'Windows path empty.' => ['C:\\', '\\', 'C:\\'], ]; } /** * Method to test setPermissions(). * * @return void * * @covers \Windwalker\Filesystem\Path::setPermissions * @TODO Implement testSetPermissions(). */ public function testSetPermissions() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Method to test getPermissions(). * * @return void * * @covers \Windwalker\Filesystem\Path::getPermissions * @TODO Implement testGetPermissions(). */ public function testGetPermissions() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Method to test clean(). * * @param string $input * @param string $ds * @param string $expected * * @return void * * @covers \Windwalker\Filesystem\Path::clean * * @dataProvider cleanProvider */ public function testClean(string $input, string $ds, string $expected): void { $this->assertEquals( $expected, Path::clean($input, $ds) ); } /** * testExistsInsensitive * * @param string $path * @param bool $sExists * @param bool $iExists * * @return void * @dataProvider existsProvider */ public function testExists(string $path, bool $sExists, bool $iExists): void { self::assertSame($sExists, Path::exists($path, Path::CASE_SENSITIVE)); self::assertSame($iExists, Path::exists($path, Path::CASE_INSENSITIVE)); } /** * existsProvider * * @return array */ public function existsProvider(): array { return [ [ __DIR__ . '/case/Flower/saKura/test.txt', false, true, ], [ __DIR__ . '/case/Flower/saKura/TEST.txt', true, true, ], [ __DIR__ . '/case/Flower/sakura', false, true, ], [ __DIR__ . '/case/Flower/Olive', false, false, ], [ 'vfs://root/files', true, true, ], ]; } /** * testFixCase * * @return void */ public function testFixCase() { $path = __DIR__ . '/case/Flower/saKura/test.txt'; self::assertEquals(Path::clean(__DIR__ . '/case/Flower/saKura/TEST.txt'), Path::fixCase($path)); } /** * Method to test stripExtension(). * * @return void */ public function testStripExtension() { $name = Path::stripExtension('Wu-la.la'); $this->assertEquals('Wu-la', $name); $name = Path::stripExtension(__DIR__ . '/Wu-la.la'); $this->assertEquals(__DIR__ . '/Wu-la', $name); } /** * Method to test getExtension(). * * @return void */ public function testGetExtension() { $ext = Path::getExtension('Wu-la.la'); $this->assertEquals('la', $ext); } /** * Method to test getFilename(). * * @return void */ public function testGetFilename() { $name = Path::getFilename(__DIR__ . '/Wu-la.la'); $this->assertEquals('Wu-la.la', $name); } /** * Provides the data to test the makeSafe method. * * @return array * * @since 2.0 */ public function dataTestMakeSafe() { return [ [ 'windwalker.', ['#^\.#'], 'windwalker', 'There should be no fullstop on the end of a filename', ], [ 'Test w1ndwa1ker_5-1.html', ['#^\.#'], 'Test w1ndwa1ker_5-1.html', 'Alphanumeric symbols, dots, dashes, spaces and underscores should not be filtered', ], [ 'Test w1ndwa1ker_5-1.html', ['#^\.#', '/\s+/'], 'Testw1ndwa1ker_5-1.html', 'Using strip chars parameter here to strip all spaces', ], [ 'windwalker.php!.', ['#^\.#'], 'windwalker.php', 'Non-alphanumeric symbols should be filtered to avoid disguising file extensions', ], [ 'windwalker.php.!', ['#^\.#'], 'windwalker.php', 'Non-alphanumeric symbols should be filtered to avoid disguising file extensions', ], [ '.gitignore', [], '.gitignore', 'Files starting with a fullstop should be allowed when strip chars parameter is empty', ], ]; } /** * Method to test makeSafe(). * * @param string $name The name of the file to test filtering of * @param array $stripChars Whether to filter spaces out the name or not * @param string $expected The expected safe file name * @param string $message The message to show on failure of test * * @return void * * @dataProvider dataTestMakeSafe */ public function testMakeSafe($name, $stripChars, $expected, $message) { $this->assertEquals(Path::makeSafe($name, $stripChars), $expected, $message); } }
package org.newdawn.slick.util.pathfinding.navmesh; import java.util.ArrayList; /** * A nav-mesh is a set of shapes that describe the navigation of a map. These * shapes are linked together allow path finding but without the high * resolution that tile maps require. This leads to fast path finding and * potentially much more accurate map definition. * * @author kevin * */ public class NavMesh { /** The list of spaces that build up this navigation mesh */ private ArrayList spaces = new ArrayList(); /** * Create a new empty mesh */ public NavMesh() { } /** * Create a new mesh with a set of spaces * * @param spaces The spaces included in the mesh */ public NavMesh(ArrayList spaces) { this.spaces.addAll(spaces); } /** * Get the number of spaces that are in the mesh * * @return The spaces in the mesh */ public int getSpaceCount() { return spaces.size(); } /** * Get the space at a given index * * @param index The index of the space to retrieve * @return The space at the given index */ public Space getSpace(int index) { return (Space) spaces.get(index); } /** * Add a single space to the mesh * * @param space The space to be added */ public void addSpace(Space space) { spaces.add(space); } /** * Find the space at a given location * * @param x The x coordinate at which to find the space * @param y The y coordinate at which to find the space * @return The space at the given location */ public Space findSpace(float x, float y) { for (int i=0;i<spaces.size();i++) { Space space = getSpace(i); if (space.contains(x,y)) { return space; } } return null; } /** * Find a path from the source to the target coordinates * * @param sx The x coordinate of the source location * @param sy The y coordinate of the source location * @param tx The x coordinate of the target location * @param ty The y coordinate of the target location * @param optimize True if paths should be optimized * @return The path between the two spaces */ public NavPath findPath(float sx, float sy, float tx, float ty, boolean optimize) { Space source = findSpace(sx,sy); Space target = findSpace(tx,ty); if ((source == null) || (target == null)) { return null; } for (int i=0;i<spaces.size();i++) { ((Space) spaces.get(i)).clearCost(); } target.fill(source,tx, ty, 0); if (target.getCost() == Float.MAX_VALUE) { return null; } if (source.getCost() == Float.MAX_VALUE) { return null; } NavPath path = new NavPath(); path.push(new Link(sx, sy, null)); if (source.pickLowestCost(target, path)) { path.push(new Link(tx, ty, null)); if (optimize) { optimize(path); } return path; } return null; } /** * Check if a particular path is clear * * @param x1 The x coordinate of the starting point * @param y1 The y coordinate of the starting point * @param x2 The x coordinate of the ending point * @param y2 The y coordinate of the ending point * @param step The size of the step between points * @return True if there are no blockages along the path */ private boolean isClear(float x1, float y1, float x2, float y2, float step) { float dx = (x2 - x1); float dy = (y2 - y1); float len = (float) Math.sqrt((dx*dx)+(dy*dy)); dx *= step; dx /= len; dy *= step; dy /= len; int steps = (int) (len / step); for (int i=0;i<steps;i++) { float x = x1 + (dx*i); float y = y1 + (dy*i); if (findSpace(x,y) == null) { return false; } } return true; } /** * Optimize a path by removing segments that arn't required * to reach the end point * * @param path The path to optimize. Redundant segments will be removed */ private void optimize(NavPath path) { int pt = 0; while (pt < path.length()-2) { float sx = path.getX(pt); float sy = path.getY(pt); float nx = path.getX(pt+2); float ny = path.getY(pt+2); if (isClear(sx,sy,nx,ny,0.1f)) { path.remove(pt+1); } else { pt++; } } } }
use strict; use Data::Dumper; use Carp; # # This is a SAS Component # =head1 NAME roles_to_complexes =head1 SYNOPSIS roles_to_complexes [arguments] < input > output =head1 DESCRIPTION roles_to_complexes allows a user to connect Roles to Complexes, from there, the connection exists to Reactions (although in the actual ER-model model, the connection from Complex to Reaction goes through ReactionComplex). Since Roles also connect to fids, the connection between fids and Reactions is induced. Example: roles_to_complexes [arguments] < input > output The standard input should be a tab-separated table (i.e., each line is a tab-separated set of fields). Normally, the last field in each line would contain the identifer. If another column contains the identifier use -c N where N is the column (from 1) that contains the subsystem. This is a pipe command. The input is taken from the standard input, and the output is to the standard output. For each line of input there may be multiple lines of output, one per complex associated with the role. Two columns are appended to the input line, the optional flag, and the complex id. =head1 COMMAND-LINE OPTIONS Usage: roles_to_complexes [arguments] < input > output -c num Select the identifier from column num -i filename Use filename rather than stdin for input =head1 AUTHORS L<The SEED Project|http://www.theseed.org> =cut our $usage = "usage: roles_to_complexes [-c column] < input > output"; use Bio::KBase::CDMI::CDMIClient; use Bio::KBase::Utilities::ScriptThing; my $column; my $input_file; my $kbO = Bio::KBase::CDMI::CDMIClient->new_for_script('c=i' => \$column, 'i=s' => \$input_file); if (! $kbO) { print STDERR $usage; exit } my $ih; if ($input_file) { open $ih, "<", $input_file or die "Cannot open input file $input_file: $!"; } else { $ih = \*STDIN; } while (my @tuples = Bio::KBase::Utilities::ScriptThing::GetBatch($ih, undef, $column)) { my @h = map { $_->[0] } @tuples; my $h = $kbO->roles_to_complexes(\@h); for my $tuple (@tuples) { # # Process output here and print. # my ($id, $line) = @$tuple; my $v = $h->{$id}; if (! defined($v)) { print STDERR $line,"\n"; } else { foreach $_ (@$v) { my($complex,$optional) = @$_; print "$line\t$optional\t$complex\n"; } } } } __DATA__
import aaf import os from optparse import OptionParser parser = OptionParser() (options, args) = parser.parse_args() if not args: parser.error("not enough argements") path = args[0] name, ext = os.path.splitext(path) f = aaf.open(path, 'r') f.save(name + ".xml") f.close()
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import styles from '../../build/styles'; export default class Subtitle extends Component { static propTypes = { children: PropTypes.any, className: PropTypes.string, size: PropTypes.oneOf([ 'is1', 'is2', 'is3', 'is4', 'is5', 'is6', ]), }; static defaultProps = { className: '', }; createClassName() { return [ styles.subtitle, styles[this.props.size], this.props.className, ].join(' ').trim(); } render() { return ( <p {...this.props} className={this.createClassName()}> {this.props.children} </p> ); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>18 --> 19</title> <link href="./../../assets/style.css" rel="stylesheet"> </head> <body> <h2>You have to be fast</h2> <a href="./873af1edd08a980241ee3f9ff4f23ed88f42c05f1e83b3c4e77ebd81e29a8512.html">Teleport</a> <hr> <a href="./../../about.md">About</a> (Spoilers! ) <script src="./../../assets/md5.js"></script> <script> window.currentLevel = 7; </script> <script src="./../../assets/script.js"></script> </body> </html>
# nimna **nim** **n**ucleic **a**cid folding. ## What is nimna? **nimna** is a set of bindings to [ViennaRNA](https://www.tbi.univie.ac.at/RNA/), a library for RNA and DNA folding applications. It consists of a very thin `c2nim` wrapper `RNA.nim`, as well as a high level interface `nimna.nim`, which wraps the many pointers used in the ViennaRNA into garbage collected `ref objects` to make the library easier to use. Furthermore, it provides nucleic acid design functionality in the form of an 'artificial immune-system' algorithm in `design.nim`. ## Installation Installation of `nimna` and its dependencies is automatically handled using `nimble install`. This tries to autodetect, whether a suitable dynamic library version of `libRNA` exists on your computer. If that is not the case, it pulls all files necessary for installation from the web and installs them. In case of Windows, the ViennaRNA installer is started and you may need to complete the some installation steps manually, while for \*nix ViennaRNA is built from source. As such, it suffices for most use-cases to just perform: ``` $ nimble install nimna ``` or ``` $ nimble install <this repository's url> ``` As nimble currently does not allow `uninstall` hooks, `nimna` provides a command to clean up dependencies, should you want to uninstall `nimna`: ``` $ nimnacleanup ``` This removes the dependency folder in the `nimna` package. If this is not done, nimble cannot fully remove `nimna's` package directory, leaving the deps folder to lie around. ## What can I do with it? `nimna` currently provides the functionality implemented in ViennaRNA, as well as some extra bits. As `nimna`'s current status is a *work-in-progress*, the set of available functionality will be steadily growing. You can find more documentation, as well as short examples for every submodule [here](https://mjendrusch.github.io/projects/nimna/nimna) Here's an incomplete list of what can be done with `nimna`: ### Partition function (pf) and minimum free energy (mfe) folding Folding for single molecules: ```nim let sequence = compound"CCCCCAAAGGGGG" mfeResult = sequence.mfe pfResult = sequence.pf echo mfeResult.struc # prints (((((...))))) echo mfeResult.E # prints the free energy # of folding in kcal/mol echo pfResult.struc # prints (((((...))))) echo pfResult.E # prints the ensemble free # energy of folding in kcal/mol ``` Folding for dimers and alignments works analogously after creation of suitable `Compound` objects. ### Free energy evaluation of structures When no full folding prediction is required, `nimna` allows for the computation of free energies of given secondary structures for a `Compound`: ```nim echo sequence.eval("(((((...)))))") # Prints the free # energy of folding # for the given # structure. echo sequence.evalRemove( "(((((...)))))", 0, 12) # Prints the free energy of # removing the base pair of # the first and last # nucleotides echo sequence.evalAdd( ".((((...)))).", 0, 12) # Prints the free energy of # adding a base pair between # the first and last # nucleotides ``` ### Access to base pairing probabilities When using partition function folding (`pf`), base pairing probabilities are set in the `Compound` object, an immutable view of which can be created later: ```nim let probs = sequence.probabilities echo probs[i, j] # prints the probability of bases # i and j in `sequence` forming # a base pair. echo sequence.prob(i, j) # prints the same as above. ``` A `Probabilities` object created from a `Compound` may be iterated over using a set of iterators provided in `nimna`: ```nim for elem in probs.items: echo elem # prints each and every # entry in the probability matrix. for pos, prob in probs.pairs: echo pos.i, " : ", pos.j, " : ", prob # prints the base positions together # with the associated probabilities. for i, j, prob in probs.triples: echo i, " : ", j, " : ", prob # prints the same as above. for pos in probs.positions: for elem in pos: echo elem # for every base in the Compound # prints the base pairing probability # of that base with all other bases. ``` ### Fine tuning of folding parameters Although standard folding parameters are often deemed sufficient for many use cases, tuning of parameters may be required for more specialized analyses. To that end `nimna` provides the means to adjust the folding parameters at will: ```nim # Use the `settings` macro to create a new # set of folding parameters: let settings = settings( temperature = 25.0, # Set the folding # temperature to 25°C noGU = 1 # Disallow G--U base pairs ) # Parameters for mfe folding mfeParams = settings.toParams # Parameters for pf folding pfParams = settings.toScaledParams # Now, update the compound with those parameters: sequence.update(mfeParams) # Update parameters # for mfe folding only. sequence.update(pfParams) # Update parameters # for pf folding only. sequence.update(settings) # Update all parameters. ``` ### Application of soft and hard constraints to compounds For certain applications, for example for working with aptamers protein binding domains, Ag-nanocluster forming sequences and other sequences with strong outside (i.e. non DNA/RNA) influences on folding, it is necessary to inform the folding algorithm about the presence of those structures. This is done using (hard or soft) constraints encoding the outside influence, its free energy of interaction and the resulting secondary structure resulting upon interaction. To that end, `nimna` provides access to the full spectrum of constraints implemented in ViennaRNA. Hard constraints __force__ the nucleic acid to fold in certain ways, regardless of other, perhaps more favourable interactions involved. They are set using `forceX`, where `X` is one of `paired, unpaired`: ```nim # Given a compound `sequence`, constrain its # i'th and j'th base to pair: sequence.forcePaired(i, j) # constrain its k'th base to stay unpaired: sequence.forceUnpaired(k) # constrain it according to a dot-bracket string: sequence.constrain("x((((xxx))))x") # 'x' means: # must not pair # lift all constraints sequence.liftConstraints ``` Soft constraints register base pairs or motifs with a certain __preferred__ free energy of interaction, which are then incorporated into folding prediction. This allows for correct folding, when lower energy interactions outside the constraints are available. They are set using `preferX`, where `X` is one of `paired, unpaired`: ```nim # Given a compound `sequence`, add a beneficial # free energy contribution of -10.0 kcal/mol to # the base pairing of its i'th and j'th base: sequence.preferPaired(i, j, -10.0) # Do the same for its k'th base to stay unpaired: sequence.preferUnpaired(k, -10.0) # Do the same for a motif `CCAA` in `sequence` sequence.preferMotif("CCAA", -10) # Lift all preferences sequence.liftPreferences ``` ### Nucleic acid design `nimna` provides an 'artificial immune system'-based nucleic acid design algorithm for automatic design of nucleic acids according to a user-specified fitness function: ```nim # Define a fitness function: proc fitness(c: Compound): float = c.eval("(((((((...))))..)))") # create a new `DesignEngine`: let design = newEngine(20, fitness) # constrain the sequence space to be searched: design.pattern = "NNNNNNNATGCNNNYHGNN" # specify a structure for structure-consistent mutation. # this ensures, that the three base pairs around the # three-nucleotide-loop are mutated together, such that # they form Watson-Crick base pairs: design.structure = "....(((...)))......" # set the folding parameters: design.settings = settings(temperature = 25.0) # set the mutation probability: design.mutationProbability = 0.6 # run the algorithm for 100 steps: design.step(100) # print the best sequence according to # the fitness function: echo design.best.sequence ``` ### A more complete list of available functionality * Folding: * Partition function folding for one or more molecules, as well as alignments. * Minimum free energy folding for one or more molecules, as well as alignments.. * Centroid structure folding for one or more molecules. * 2DFold (MFE and partition function). * Maximum expected accuracy folding. * Generation of suboptimal structures and energies. * Constraints: * Hard constraints are fully supported. * Soft constraints are fully supported. * Structured ligand binding constraints are fully supported. * Model Details: * Updating of model details associated with a molecule. * Generating MFE and PF parameters from model details. * Macro for easily generating model details. * Parameters: * Updating of parameters associated with a molecule. * Probability Matrix: * Probability matrix exposed as `Probabilities = ref object`. * Extracting values from the probability matrix of partition function folding. * Generating a Density Plot of the base pairing probability in a terminal emulator. * Nucleic acid design: * Generating nucleic acid sequences corresponding to local minima in user-defined fitness functions. * Miscellaneous: * Generating reasonably random DNA/RNA sequences. * Evaluating energies of secondary structures. * Sampling secondary structures from ensembles computed with `pf` and `pf2D`. * Iterators for all types which can be iterated over. * Reading and writing parameter files. ## A short example: ```nim # We want to fold a sequence at multiple temperatures, # and see how the base pairing probabilities change: import nimna import strutils let rna = compound"GGGGGAGGAAACCTTCCCC" for deltaT in 0..200: let T = 20.0 + deltaT.float / 10.0 discard rna.update(settings(temperature = T)).pf if deltaT != 0: # This makes use of ANSI-escapes to move the cursor # up to the beginning of the plot, to write over it # again, so we can have a nice animation. echo "\e[$1A" % $(rna.length + 2) rna.densityPlot ``` ## iGEM disclaimer `nimna` is not a project of a Heidelberg iGEM team, future or past. Certainly, it was inspired by the work of the [Heidelberg iGEM team 2015](http://2015.igem.org/Team:Heidelberg) but it is its own project, which I work on, on my own time and which **will be maintained and supported**, in contrast to some iGEM code out there.
""" telemetry full tests. """ import platform import sys from unittest import mock import pytest import wandb def test_telemetry_finish(runner, live_mock_server, parse_ctx): with runner.isolated_filesystem(): run = wandb.init() run.finish() ctx_util = parse_ctx(live_mock_server.get_ctx()) telemetry = ctx_util.telemetry assert telemetry and 2 in telemetry.get("3", []) def test_telemetry_imports_hf(runner, live_mock_server, parse_ctx): with runner.isolated_filesystem(): run = wandb.init() with mock.patch.dict("sys.modules", {"transformers": mock.Mock()}): import transformers run.finish() ctx_util = parse_ctx(live_mock_server.get_ctx()) telemetry = ctx_util.telemetry # hf in finish modules but not in init modules assert telemetry and 11 not in telemetry.get("1", []) assert telemetry and 11 in telemetry.get("2", []) def test_telemetry_imports_catboost(runner, live_mock_server, parse_ctx): with runner.isolated_filesystem(): with mock.patch.dict("sys.modules", {"catboost": mock.Mock()}): import catboost run = wandb.init() run.finish() ctx_util = parse_ctx(live_mock_server.get_ctx()) telemetry = ctx_util.telemetry # catboost in both init and finish modules assert telemetry and 7 in telemetry.get("1", []) assert telemetry and 7 in telemetry.get("2", []) @pytest.mark.skipif( platform.system() == "Windows", reason="test suite does not build jaxlib on windows" ) @pytest.mark.skipif(sys.version_info >= (3, 10), reason="jax has no py3.10 wheel") def test_telemetry_imports_jax(runner, live_mock_server, parse_ctx): with runner.isolated_filesystem(): import jax wandb.init() wandb.finish() ctx_util = parse_ctx(live_mock_server.get_ctx()) telemetry = ctx_util.telemetry # jax in finish modules but not in init modules assert telemetry and 12 in telemetry.get("1", []) assert telemetry and 12 in telemetry.get("2", []) def test_telemetry_run_organizing_init(runner, live_mock_server, parse_ctx): with runner.isolated_filesystem(): wandb.init(name="test_name", tags=["my-tag"], config={"abc": 123}, id="mynewid") wandb.finish() ctx_util = parse_ctx(live_mock_server.get_ctx()) telemetry = ctx_util.telemetry assert telemetry and 13 in telemetry.get("3", []) # name assert telemetry and 14 in telemetry.get("3", []) # id assert telemetry and 15 in telemetry.get("3", []) # tags assert telemetry and 16 in telemetry.get("3", []) # config def test_telemetry_run_organizing_set(runner, live_mock_server, parse_ctx): with runner.isolated_filesystem(): run = wandb.init() run.name = "test-name" run.tags = ["tag1"] wandb.config.update = True run.finish() ctx_util = parse_ctx(live_mock_server.get_ctx()) telemetry = ctx_util.telemetry assert telemetry and 17 in telemetry.get("3", []) # name assert telemetry and 18 in telemetry.get("3", []) # tags assert telemetry and 19 in telemetry.get("3", []) # config update
# Last.fm user track analysis ## Description Program that retrieves data from the Last.fm service API and provides the user with information on their listening habits. ## How to run it You can start it either by executing module with `python` command ```bash python user_tracks user_name api_key ``` Or by starting app it self: ```bash ./user_tracks/user_tracks.py user_name api_key ``` It can be run for multiple users in any order. For more details please run app with `--help`: ```bash python user_tracks --help ``` *Note:* Please see **Requirements** section to install necessary libraries ## How to run tests Application has number of tests that can be executed with helper script: ```bash ./runtests.py ``` *Note:* Please see **Requirements** section to install necessary libraries ## Requirements To run app you need external library. To install it please run standard `pip`command: ```bash pip install -r requirements.txt ``` Tests depends on some more requirements, listed in `test_requirements.txt` and can be installed in similar way: ```bash pip install -r test_requirements.txt ``` ## To remove history of tracks This has to happen manually by removing either whole `dbs` folder (that will be created after first run) or specific file in this folder (named after user name). ## Assumptions When writing this small app I had some assumptions: * User has it's own API key for Last.fm service * Application can write to directory from where was executed (to store the state between runs) * API call to "user.getRecentTracks" always returns tracks from newest to oldest * Application will not try to recover from most of exceptions (ie. when network error will occur it will fail fast and laud). It can be rerun to start from where it left off * Currently running track will not be included in history (it will get in with of of next runs) * State of app is preserved using SQLite db ## Final note Tested on Ubuntu with Python 2.7.5 and virtualenv ## Example of output ``` Stats for user 'mrfuxi': - listened to a total of 554 tracks. - top 5 favorite artists: Chris Rea, Dire Straits, Evanescence, Formacja Nieżywych Schabuff, The Doors. - listen to an average of 22 tracks a day. - most active day is Saturday. ```
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>You Are Statistically</title> <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Source+Sans+Pro:300,300i,600"> <link rel="stylesheet" href="/style.css"> <link rel="stylesheet" href="/custom.css"> <link rel="shortcut icon" href="https://micro.blog/curt/favicon.png" type="image/x-icon" /> <link rel="alternate" type="application/rss+xml" title="Curt Clifton" href="http://microblog.curtclifton.net/feed.xml" /> <link rel="alternate" type="application/json" title="Curt Clifton" href="http://microblog.curtclifton.net/feed.json" /> <link rel="EditURI" type="application/rsd+xml" href="/rsd.xml" /> <link rel="me" href="https://micro.blog/curt" /> <link rel="me" href="https://twitter.com/curtclifton" /> <link rel="authorization_endpoint" href="https://micro.blog/indieauth/auth" /> <link rel="token_endpoint" href="https://micro.blog/indieauth/token" /> <link rel="micropub" href="https://micro.blog/micropub" /> <link rel="webmention" href="https://micro.blog/webmention" /> <link rel="subscribe" href="https://micro.blog/users/follow" /> </head> <body> <div class="container"> <header class="masthead"> <h1 class="masthead-title--small"> <a href="/">Curt Clifton</a> </h1> </header> <div class="content post h-entry"> <div class="post-date"> <time class="dt-published" datetime="2017-05-15 22:30:36 -0700">15 May 2017</time> </div> <div class="e-content"> <p>“you are statistically more likely to get mauled by a hungry timeshare salesman than be bitten by a shark” <a href="https://itun.es/us/1DhO_.l">Maui Revealed</a></p> </div> </div> </div> </body> </html>
using MinMaxFilter using Base.Test using MAT # ####### # # 1 dimension # # Compare to matlab slowminmaxfilt_algo.m # # t = [1:1024] ./1024; d = sin(2*pi*4*t); # [minval, maxval] = slowminmaxfilt_algo(d, 100) # dlmwrite('minmax_output.txt',[minval; maxval], 'delimiter', '\t', 'precision', '%.12f') # # ###### matlab = readdlm(joinpath(dirname(@__FILE__), "data", "minmax_output.txt"),'\t') t = (1:1024)./1024 d = sin(2*pi*4*t) minval, maxval = minmax_filter(d, 100) @test_approx_eq minval matlab[1,:] @test_approx_eq maxval matlab[2,:] # ####### # # 2 dimension # # Compare to matlab minmaxfilt.m # # [X,Y,Z] = peaks(100); # smax = minmaxfilt(Z, 11, 'max') # # ###### filen = matopen(joinpath(dirname(@__FILE__), "data", "2d_array.mat")) A = read(filen, "Z") A = convert(Array{AbstractFloat}, A) close(filen) filen = matopen(joinpath(dirname(@__FILE__), "data", "2d_array_max11.mat")) max_matlab = read(filen, "smax") max_matlab = convert(Array{AbstractFloat}, max_matlab) close(filen) filen = matopen(joinpath(dirname(@__FILE__), "data", "2d_array_min11.mat")) min_matlab = read(filen, "smin") min_matlab = convert(Array{AbstractFloat}, min_matlab) close(filen) minval, maxval = minmax_filter(A, [11, 11]) @test_approx_eq maxval max_matlab @test_approx_eq minval min_matlab # ####### # # 3 dimension # # Compare to matlab minmaxfilt.m # # amax=minmaxfilt(image,5,'max','valid'); # # ###### filen = matopen(joinpath(dirname(@__FILE__), "data", "3d_array.mat")) A = read(filen, "image") A = convert(Array{AbstractFloat}, A) close(filen) filen = matopen(joinpath(dirname(@__FILE__), "data", "3d_array_max5.mat")) max_matlab = read(filen, "amax") max_matlab = convert(Array{AbstractFloat}, max_matlab) close(filen) filen = matopen(joinpath(dirname(@__FILE__), "data", "3d_array_min5.mat")) min_matlab = read(filen, "amin") min_matlab = convert(Array{AbstractFloat}, min_matlab) close(filen) minval, maxval = minmax_filter(A, [5,5,5]) @test_approx_eq maxval max_matlab @test_approx_eq minval min_matlab
\documentclass[11pt,english]{article} \usepackage[a4paper,bindingoffset=0mm,left=20mm,right=18mm,top=17mm,bottom=12mm]{geometry} \usepackage{blindtext} \usepackage[T1]{fontenc} \usepackage[colorlinks=true, linkcolor=red, urlcolor=blue, citecolor=gray]{hyperref} \usepackage{hyperref,url} \usepackage{xcolor,longtable} \usepackage{fancyhdr}\pagestyle{fancy}\usepackage{lastpage} \fancyhf{}\renewcommand{\headrulewidth}{0pt} %\rfoot{ %\fboxsep0pt %\vspace{-10mm}\colorbox{maincolor}{\begin{minipage}[b][9mm][b]{11mm} %\begin{center} \color{white} \thepage /\pageref*{LastPage} \end{center} %\end{minipage}} %\vspace{6mm} %} \usepackage{enumitem}\setlist{nolistsep} \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}\setlength{\parsep}{0pt} \setlength\parindent{0pt}\setlength{\topskip}{0pt} \usepackage{titlesec} \titleformat*{\section}{\huge} \usepackage{hyphenat}\hyphenation{Mathematica} \renewcommand{\familydefault}{lmss} \begin{document} %main color \definecolor{maincolor}{RGB}{109,0,3} %light grey for HR-appreciated but otherwise not-so-fucking-important information \definecolor{maingrey}{RGB}{150,150,150} \begin{center} \huge\bf\color{maincolor} KEITH T. BUTLER \\ \small\color{black} \href{mailto: keith.butler@stfc.ac.uk }{keith.butler@stfc.ac.uk } \end{center} \begin{flushright} \vspace{3.5mm} \end{flushright} \vspace{-18mm} \medskip \fontfamily{lmss}\selectfont %\newgeometry{left=0mm,right=135mm} \fboxsep0pt \hspace{-20mm}\colorbox{maincolor}{\begin{minipage}[t][8mm][c]{75mm} \hspace{20mm}\bfseries \color{white} PUBLICATIONS \end{minipage}} \vspace{6mm} %to restore old margins, use %\restoregeometry \begin{minipage}{\textwidth} \begin{tabular}{ @{} p{32mm} p{135mm} @{} } &I have published over 70 peer-reviewed research papers throughout top journals in materials chemistry, condensed matter physics and machine learning. In all cases author listing is by contribution, i.e. lead author first. In some instances I was joined lead author, or lead author of the computational section in a collaboration with experiment. I have indicated all lead author papers with an asterisk. \href{https://scholar.google.co.uk/citations?user=eruLmgUAAAAJ&hl=en}{[H-index: 26; total citations: 3952]}. \\ \end{tabular} \vspace{1mm} \end{minipage} \medskip \fontfamily{lmss}\selectfont %\bibliography{citations.bib} % Created using bibliographystyle ieeetr \begin{thebibliography}{10} \bibitem{davies2019data} D.~Davies, K.~Butler, and A.~Walsh, ``Data-driven discovery of photoactive quaternary oxides using first-principles machine learning,'' {\em ChemRxiv}, 2019. \bibitem{butler2019designing} * K.~T. Butler, G.~S. Gautam, and P.~Canepa, ``Designing interfaces in energy materials applications with first-principles calculations,'' {\em npj Comp. Mater.}, vol.~5, no.~1, p.~19, 2019. \bibitem{wahila2019accelerated} * M.~J. Wahila, Z.~W. Lebens-Higgins, K.~T. Butler, D.~Fritsch, R.~E. Treharne, R.~G. Palgrave, J.~C. Woicik, B.~J. Morgan, A.~Walsh, and L.~F. Piper, ``Accelerated optimization of transparent, amorphous zinc-tin-oxide thin films for optoelectronic applications,'' {\em APL Mater.}, vol.~7, no.~2, p.~022509, 2019. \bibitem{wallace2019finding} S.~K. Wallace, K.~T. Butler, Y.~Hinuma, and A.~Walsh, ``Finding a junction partner for candidate solar cell absorbers enargite and bournonite from electronic band and lattice matching,'' {\em J. Appl. Phys.}, vol.~125, no.~5, p.~055703, 2019. \bibitem{butler2018machine} K.~T. Butler, D.~W. Davies, H.~Cartwright, O.~Isayev, and A.~Walsh, ``Machine learning for molecular and materials science,'' {\em Nature}, vol.~559, no.~7715, p.~547, 2018. \bibitem{collins2018subwavelength} S.~M. Collins, D.~M. Kepaptsoglou, K.~T. Butler, L.~Longley, T.~D. Bennett, Q.~M. Ramasse, and P.~A. Midgley, ``Subwavelength spatially resolved coordination chemistry of metal--organic framework glass blends,'' {\em J. Am. Chem. Soc.}, vol.~140, no.~51, pp.~17862--17866, 2018. \bibitem{kieslich2018hydrogen} G.~Kieslich, J.~M. Skelton, J.~Armstrong, Y.~Wu, F.~Wei, K.~L. Svane, A.~Walsh, and K.~T. Butler, ``Hydrogen bonding versus entropy: Revealing the underlying thermodynamics of the hybrid organic--inorganic perovskite [ch3nh3] pbbr3,'' {\em Chem. Mater.}, vol.~30, no.~24, pp.~8782--8788, 2018. \bibitem{butler2018chemical} K.~T. Butler, ``The chemical forces underlying octahedral tilting in halide perovskites,'' {\em J. Mater. Chem. C}, vol.~6, no.~44, pp.~12045--12051, 2018. \bibitem{davies2018computer} D.~W. Davies, K.~T. Butler, J.~M. Skelton, C.~Xie, A.~R. Oganov, and A.~Walsh, ``Computer-aided design of metal chalcohalide semiconductors: from chemical composition to crystal structure,'' {\em Chem. Sci.}, vol.~9, no.~4, pp.~1022--1030, 2018. \bibitem{davies2018materials} D.~W. Davies, K.~T. Butler, O.~Isayev, and A.~Walsh, ``Materials discovery by chemical analogy: role of oxidation states in structure prediction,'' {\em Faraday Dissc.}, vol.~211, pp.~553--568, 2018. \bibitem{makaremi2018band} M.~Makaremi, S.~Grixti, K.~T. Butler, G.~A. Ozin, and C.~V. Singh, ``Band engineering of carbon nitride monolayers by n-type, p-type, and isoelectronic doping for photocatalytic applications,'' {\em ACS Appl. Mater. Inter.}, vol.~10, no.~13, pp.~11143--11151, 2018. \bibitem{wei2018unusual} W.~Wei, W.~Li, K.~T. Butler, G.~Feng, C.~J. Howard, M.~A. Carpenter, P.~Lu, A.~Walsh, and A.~K. Cheetham, ``An unusual phase transition driven by vibrational entropy changes in a hybrid organic--inorganic perovskite,'' {\em Angew. Chem.}, vol.~130, no.~29, pp.~9070--9074, 2018. \bibitem{park2018quick} J.-S. Park, Y.-K. Jung, K.~T. Butler, and A.~Walsh, ``Quick-start guide for first-principles modelling of semiconductor interfaces,'' {\em J. Phys.: Energy}, vol.~1, no.~1, p.~016001, 2018. \bibitem{svane2017strong} K.~L. Svane, A.~C. Forse, C.~P. Grey, G.~Kieslich, A.~K. Cheetham, A.~Walsh, and K.~T. Butler, ``How strong is the hydrogen bond in hybrid perovskites?,'' {\em J. Phys. Chem. Lett.}, vol.~8, no.~24, pp.~6154--6159, 2017. \bibitem{jia2017heterogeneous} J.~Jia, C.~Qian, Y.~Dong, Y.~F. Li, H.~Wang, M.~Ghoussoub, K.~T. Butler, A.~Walsh, and G.~A. Ozin, ``Heterogeneous catalytic hydrogenation of co 2 by metal oxides: defect engineering--perfecting imperfection,'' {\em Chem. Soc. Rev.}, vol.~46, no.~15, pp.~4631--4644, 2017. \bibitem{butler2017designing} K.~T. Butler, C.~H. Hendon, and A.~Walsh, ``Designing porous electronic thin-film devices: band offsets and heteroepitaxy,'' {\em Faraday disc.}, vol.~201, pp.~207--219, 2017. \bibitem{jung2017halide} Y.-K. Jung, K.~T. Butler, and A.~Walsh, ``Halide perovskite heteroepitaxy: Bond formation and carrier confinement at the pbs--cspbbr3 interface,'' {\em The J. Phys. Chem. C}, vol.~121, no.~49, pp.~27351--27356, 2017. \bibitem{hendon2017a} { * K.~T. Butler, S.~D. Worrall, C.~D. Molloy, C.~H. Hendon, M.~P. Attfield, R.~A.~W. Dryfe and A. Walsh, ``Electronic structure design for nanoporous, electrically conductive zeolitic imidazolate frameworks'' {\em J. Mater. Chem. C}, vol.~5,pp.~7726, 2017} \bibitem{hendon2017a} { C. H. Hendon, K.~T. Butler, A.~M. Ganose, Y. Roman-Leshkov, D.~O. Scanlon, G.~A. Ozin, and A. Walsh, ``Electroactive Nanoporous Metal Oxides and Chalcogenides by Chemical Design'' {\em Chem. Mater.}, vol.~29,pp.~3663, 2017} \bibitem{kumagai2017prb} { Y. Kumagai, K.~T. Butler, A. Walsh, and F. Oba, ``Theory of ionization potentials of nonmetallic solids'' {\em Phys. Rev. B}, vol.~95,pp.~125309, 2017} \bibitem{plug2017a} { N. Plugaru, G.~A. Nemnes, L. Filip, I. Pintille, L. Pintille, K.~T. Butler, A. Manolescu ``Atomistic simulations of methylammonium lead halide layers on PbTiO$_3$ (001) Surfaces'' {\em J. Phys. Chem. C} vol.~121, pp.~9096, 2017} \bibitem{Amin2017a} {H. Sepehri-Amin, H. Iwama, G. Hrkac, K.~T. Butler, T. Shima, K. Hono ``Pt surface segregation in L1$_0$-FePt nano-grains'' {\em Scr. Mater.} vol.~135, pp.~88, 2017} \bibitem{bristow2017jmca} { J. ~K. Bristow, K.~T. Butler, K.~L. Svane, J.~D. Gale and A. Walsh, ``Chemical bonding at the metal-organic framework / metal oxide interface: simulated epitaxial growth of MOF-5 on rutile TiO$_2$'' {\em J. Mater. Chem. A}, vol.~5,pp.~6226, 2017.} \bibitem{butler2017faraday} * K.~T. Butler, C.~H. Hendon, and A. Walsh, ``Designing porous electronic thin-film devices: Band offsets and heteroepitaxy,'' {\em Faraday Diss.}, In press, 2017. \bibitem{walsh2016chemical} { A.~Walsh, K.~T. Butler, and C.~H. Hendon, ``Chemical principles for electroactive metal--organic frameworks,'' {\em MRS Bull.}, vol.~41, no.~11, pp.~870--876, 2016.} \bibitem{butler2016ultrafast} * K.~T. Butler, B.~J. Dringoli, L.~Zhou, P.~M. Rao, A.~Walsh, and L.~Titova, ``Ultrafast carrier dynamics in BiVO4 thin film photoanode material: interplay between free carriers, trapped carriers and low-frequency lattice vibrations,'' {\em J. Mater. Chem. A} vol.~4, no.~47, pp.~18516-18523, 2016. \bibitem{davies2016computational} * D.~W. Davies, K.~T. Butler, A.~J. Jackson, A.~Morris, J.~M. Frost, J.~M. Skelton, and A.~Walsh, ``Computational screening of all stoichiometric inorganic materials'' {\em Chem} vol.~1 pp.~617--627, 2016 \bibitem{hendon2016realistic} C.~H. Hendon, S.~T. Hunt, M.~Milina, K.~T. Butler, A.~Walsh, and Y.~Roman-Leshkov, ``Realistic surface descriptions of heterometallic interfaces: The case of TiWC coated in noble metals,'' {\em J. Phys. Chem. Lett.} vol.~7, no.~22, pp.~4475-4482, 2016. \bibitem{butler2016microscopic} * K.~T. Butler, K.~Svane, G.~Kieslich, A.~K. Cheetham, and A.~Walsh, ``Microscopic origin of entropy-driven polymorphism in hybrid organic-inorganic perovskite materials,'' {\em Phys. Rev. B}, vol.~94, no.~18, p.~180103, 2016. \bibitem{butler2016organised} * K.~T. Butler, A.~Walsh, A.~K. Cheetham, and G.~Kieslich, ``Organised chaos: entropy in hybrid inorganic--organic systems and other materials,'' {\em Chem. Sci.}, vol.~7, no.~10, pp.~6316--6324, 2016. \bibitem{wahila2016lone} * M.~J. Wahila, K.~T. Butler, Z.~W. Lebens-Higgins, C.~H. Hendon, A.~S. Nandur, R.~E. Treharne, N.~F. Quackenbush, S.~Sallis, K.~Mason, H.~Paik, {\em et~al.}, ``Lone-pair stabilization in transparent amorphous tin oxides: A potential route to p-type conduction pathways,'' {\em Chem. Mater.} vol.~28, no.~13, pp.~4706-4713, 2016. \bibitem{uman2016effect} E.~Uman, M.~Colonna-Dashwood, L.~Colonna-Dashwood, M.~Perger, C.~Klatt, S.~Leighton, B.~Miller, K.~T. Butler, B.~C. Melot, R.~W. Speirs, {\em et~al.}, ``The effect of bean origin and temperature on grinding roasted coffee,'' {\em Sci. Rep.}, vol.~6, p.~24483, 2016. \bibitem{caetano2016analysis} C.~Caetano, K.~T. Butler, and A.~Walsh, ``Analysis of electrostatic stability and ordering in quaternary perovskite solid solutions,'' {\em Phys. Rev. B}, vol.~93, no.~14, p.~144205, 2016. \bibitem{butler2016computational} * K.~T. Butler, J.~M. Frost, J.~M. Skelton, K.~L. Svane, and A.~Walsh, ``Computational materials design of crystalline solids,'' {\em Chem. Soc. Rev.}, 2016. \bibitem{butler2016quasi} * K.~T. Butler, S.~McKechnie, P.~Azarhoosh, M.~Van~Schilfgaarde, D.~O. Scanlon, and A.~Walsh, ``Quasi-particle electronic band structure and alignment of the V-VI-VII semiconductors SbSI, SbSBr, and SbSeI for solar cells,'' {\em Appl. Phys. Lett.}, vol.~108, no.~11, p.~112103, 2016. \bibitem{ganose2016interplay} A.~M. Ganose, M.~Cuff, K.~T. Butler, A.~Walsh, and D.~O. Scanlon, ``Interplay of orbital and relativistic effects in bismuth oxyhalides: BiOF, BiOCl, BiOBr, and BiOI,'' {\em Chem. Mater.}, vol.~28, no.~7, pp.~1980--1984, 2016. \bibitem{ganose2016relativistic} A.~M. Ganose, K.~T. Butler, A.~Walsh, and D.~O. Scanlon, ``Relativistic electronic structure and band alignment of BiSI and BiSeI: candidate photovoltaic materials,'' {\em J. Mater. Chem. A}, vol.~4, no.~6, pp.~2060--2068, 2016. \bibitem{butler2016screening} { * K.~T. Butler, Y.~Kumagai, F.~Oba, and A.~Walsh, ``Screening procedure for structurally and electronically matched contact layers for high-performance solar cells: hybrid perovskites,'' {\em J. Mater. Chem. C}, vol.~4, no.~6, pp.~1149--1158, 2016.} \bibitem{butler2015band} { * K.~T. Butler, J.~M. Frost, and A.~Walsh, ``Band alignment of the hybrid halide perovskites CH$_3$NH$_3$PbSl$_3$, CH$_3$NH$_3$PbBr$_3$ and CH$_3$NH$_3$PbI$_3$,'' {\em Materials Horizons}, vol.~2, no.~2, pp.~228--231, 2015.} \bibitem{yang2015assessment} R.~X. Yang, K.~T. Butler, and A.~Walsh, ``Assessment of hybrid organic--inorganic antimony sulfides for earth-abundant photovoltaic applications,'' {\em J. Phys. Chem. Lett.}, vol.~6, no.~24, pp.~5009--5014, 2015. \bibitem{kieslich2015role} * G.~Kieslich, S.~Kumagai, K.~T. Butler, T.~Okamura, C.~H. Hendon, S.~Sun, M.~Yamashita, A.~Walsh, and A.~K. Cheetham, ``Role of entropic effects in controlling the polymorphism in formate ABX$_3$ metal--organic frameworks,'' {\em Chem. Comm.}, vol.~51, no.~85, pp.~15538--15541, 2015. \bibitem{hrkac2015magnetic} G.~Hrkac, P.~S. Keatley, M.~T. Bryan, and K.~Butler, ``Magnetic vortex oscillators,'' {\em J. Phys. D: Appl. Phys.}, vol.~48, no.~45, p.~453001, 2015. \bibitem{jackson2015crystal} A.~J. Jackson, J.~M. Skelton, C.~H. Hendon, K.~T. Butler, and A.~Walsh, ``Crystal structure optimisation using an auxiliary equation of state,'' {\em J. Chem. Phys.}, vol.~143, no.~18, p.~184101, 2015. \bibitem{isherwood2015tunable} * P.~J. Isherwood, K.~T. Butler, A.~Walsh, and J.~M. Walls, ``A tunable amorphous p-type ternary oxide system: The highly mismatched alloy of copper tin oxide,'' {\em J. Appl. Phys.}, vol.~118, no.~10, p.~105702, 2015. \bibitem{buckeridge2015polymorph} J.~Buckeridge, K.~T. Butler, C.~R.~A. Catlow, A.~J. Logsdail, D.~O. Scanlon, S.~A. Shevlin, S.~M. Woodley, A.~A. Sokol, and A.~Walsh, ``Polymorph engineering of TiO$_2$: Demonstrating how absolute reference potentials are determined by local coordination,'' {\em Chem. Mater.}, vol.~27, no.~11, pp.~3844--3851, 2015. \bibitem{butler2015morphological} * K.~T. Butler, ``Morphological control of band offsets for transparent bipolar heterojunctions: The B{\"a}deker diode,'' {\em Phys. Stat. Sol. (a)}, vol.~212, no.~7, pp.~1461--1465, 2015. \bibitem{hendon2015absorbate} C.~H. Hendon, K.~E. Wittering, T.-H. Chen, W.~Kaveevivitchai, I.~Popov, K.~T. Butler, C.~C. Wilson, D.~L. Cruickshank, O.~S. Miljani\'{c}, and A.~Walsh, ``Absorbate-induced piezochromism in a porous molecular crystal,'' {\em Nano Lett.}, vol.~15, no.~3, pp.~2149--2154, 2015. \bibitem{kim2015lattice} C.-E. Kim, Y.-J. Tak, K.~T. Butler, A.~Walsh, and A.~Soon, ``Lattice-mismatched heteroepitaxy of iv-vi thin films on PbTe (001): An ab initio study,'' {\em Phys. Rev. B}, vol.~91, no.~8, p.~085307, 2015. \bibitem{butler2015ferroelectric} { * K.~T. Butler, J.~M. Frost, and A.~Walsh, ``Ferroelectric materials for solar energy conversion: photoferroics revisited,'' {\em Energy \& Environmental Science}, vol.~8, no.~3, pp.~838--848, 2015.} \bibitem{butler2014electronic} { * K.~T. Butler, C.~H. Hendon, and A.~Walsh, ``Electronic chemical potentials of porous metal--organic frameworks,'' {\em J. Am. Chem. Soc.}, vol.~136, no.~7, pp.~2703--2706, 2014.} \bibitem{yoo2014identification} S.-H. Yoo, K.~T. Butler, A.~Soon, A.~Abbas, J.~M. Walls, and A.~Walsh, ``Identification of critical stacking faults in thin-film CdTe solar cells,'' {\em Appl. Phys. Lett.}, vol.~105, no.~6, p.~062104, 2014. \bibitem{sallis2014origin} * S.~Sallis, K.~Butler, N.~Quackenbush, D.~Williams, M.~Junda, D.~Fischer, J.~Woicik, N.~Podraza, B.~White~Jr, A.~Walsh, {\em et~al.}, ``Origin of deep subgap states in amorphous indium gallium zinc oxide: Chemically disordered coordination of oxygen,'' {\em Appl. Phys. Lett.}, vol.~104, no.~23, p.~232108, 2014. \bibitem{hrkac2014modeling} G.~Hrkac, K.~Butler, T.~Woodcock, L.~Saharan, T.~Schrefl, and O.~Gutfleisch, ``Modeling of Nd-oxide grain boundary phases in Nd-Fe-B sintered magnets,'' {\em JOM}, vol.~66, no.~7, pp.~1138--1143, 2014. \bibitem{frost2014molecular} J.~M. Frost, K.~T. Butler, and A.~Walsh, ``Molecular ferroelectric contributions to anomalous hysteresis in hybrid perovskite solar cells,'' {\em Apl Materials}, vol.~2, no.~8, p.~081506, 2014. \bibitem{svensson2014contact} A.~M. Svensson, S.~Olibet, D.~Rudolph, E.~Cabrera, J.~Friis, K.~Butler, and J.~Harding, ``Contact resistance of screen printed Ag-contacts to Si emitters: Mathematical modeling and microstructural characterization,'' {\em Journal of The Electrochemical Society}, vol.~161, no.~8, pp.~E3180--E3187, 2014. \bibitem{butler2014crystal} { * K.~T. Butler, J.~Buckeridge, C.~R.~A. Catlow, and A.~Walsh, ``Crystal electron binding energy and surface work function control of tin dioxide,'' {\em Phys. Rev. B}, vol.~89, no.~11, p.~115320, 2014.} \bibitem{frost2014atomistic} { J.~M. Frost, K.~T. Butler, F.~Brivio, C.~H. Hendon, M.~Van~Schilfgaarde, and A.~Walsh, ``Atomistic origins of high-performance in hybrid halide perovskite solar cells,'' {\em Nano Lett.}, vol.~14, no.~5, pp.~2584--2590, 2014.} \bibitem{brivio2014relativistic} F.~Brivio, K.~T. Butler, A.~Walsh, and M.~Van~Schilfgaarde, ``Relativistic quasiparticle self-consistent electronic structure of hybrid halide perovskite photovoltaic absorbers,'' {\em Phys. Rev. B}, vol.~89, no.~15, p.~155204, 2014. \bibitem{lamers2014interface} M.~Lamers, L.~E. Hintzsche, K.~T. Butler, P.~E. Vullum, C.-M. Fang, M.~Marsman, G.~Jordan, J.~H. Harding, G.~Kresse, and A.~Weeber, ``The interface of a-SiN x: H and Si: Linking the nano-scale structure to passivation quality,'' {\em Sol. Ene. Mater. Solar Cells}, vol.~120, pp.~311--316, 2014. \bibitem{butler2014ultra} * K.~T. Butler and A.~Walsh, ``Ultra-thin oxide films for band engineering: design principles and numerical experiments,'' {\em Thin Solid Films}, vol.~559, pp.~64--68, 2014. \bibitem{walsh2013prediction} A.~Walsh and K.~T. Butler, ``Prediction of electron energies in metal oxides,'' {\em Accounts of chemical research}, vol.~47, no.~2, pp.~364--372, 2013. \bibitem{hrkac2014impact} G.~Hrkac, T.~Woodcock, K.~Butler, L.~Saharan, M.~Bryan, T.~Schrefl, and O.~Gutfleisch, ``Impact of different Nd-rich crystal-phases on the coercivity of Nd--Fe--B grain ensembles,'' {\em Scripta Materialia}, vol.~70, pp.~35--38, 2014. \bibitem{butler2013computational} * K.~T. Butler and J.~Harding, ``A computational investigation of nickel (silicides) as potential contact layers for silicon photovoltaic cells,'' {\em Journal of Physics: Condensed Matter}, vol.~25, pp.~395003--395012, 2013. \bibitem{butler200829} * K.~Butler, B.~Slater, and D.~W. Lewis, ``29 Si NMR chemical shifts from density functional theory incorporating solvent effects,'' {\em Studies in Surface Science and Catalysis}, vol.~174, pp.~725--728, 2008. \bibitem{lamers2013characterization} * M.~Lamers, K.~Butler, P.~E. Vullum, J.~Harding, and A.~Weeber, ``Characterization of a-SiNx: H layer: Bulk properties, interface with Si and solar cell efficiency,'' {\em Phys. Stat. Sol. (a)}, vol.~210, no.~4, pp.~658--668, 2013. \bibitem{green2013tuning} A.~P. Green, K.~T. Butler, and A.~R. Buckley, ``Tuning of the emission energy of fluorophores using solid state solvation for efficient luminescent solar concentrators,'' {\em Appl. Phys. Lett.}, vol.~102, no.~13, p.~133501, 2013. \bibitem{butler2012calculation} * K.~T. Butler and D.~W. Lewis, ``Calculation of the 29Si NMR chemical shifts of aqueous silicate species,'' {\em The Journal of Physical Chemistry A}, vol.~116, no.~34, pp.~8786--8791, 2012. \bibitem{butler2012atomistic} * K.~T. Butler and J.~H. Harding, ``Atomistic simulation of doping effects on growth and charge transport in Si/Ag interfaces in high-performance solar cells,'' {\em Phys. Rev. B}, vol.~86, no.~24, p.~245319, 2012. \bibitem{butler2012stoichiometrically} * K.~T. Butler, J.~H. Harding, M.~P. Lamers, and A.~W. Weeber, ``Stoichiometrically graded SiNx for improved surface passivation in high performance solar cells,'' {\em J. Appl. Phys.}, vol.~112, no.~9, p.~094303, 2012. \bibitem{lamers2012interface} * M.~W. Lamers, K.~T. Butler, J.~H. Harding, and A.~Weeber, ``Interface properties of a-SiNx: H/Si to improve surface passivation,'' {\em Sol. Ene. Mater. Solar Cells}, vol.~106, pp.~17--21, 2012. \bibitem{butler2011molecular} * K.~T. Butler, M.~P. Lamers, A.~W. Weeber, and J.~H. Harding, ``Molecular dynamics studies of the bonding properties of amorphous silicon nitride coatings on crystalline silicon,'' {\em J. Appl. Phys.}, vol.~110, no.~12, p.~124905, 2011. \bibitem{butler2011structural} * K.~T. Butler, P.~E. Vullum, A.~M. Muggerud, E.~Cabrera, and J.~H. Harding, ``Structural and electronic properties of silver/silicon interfaces and implications for solar cell performance,'' {\em Phys. Rev. B}, vol.~83, no.~23, p.~235307, 2011. \bibitem{butler2009toward} * K.~T. Butler, F.~J. Luque, and X.~Barril, ``Toward accurate relative energy predictions of the bioactive conformation of drugs,'' {\em J. Comp. Chem.}, vol.~30, no.~4, pp.~601--610, 2009. \end{thebibliography} \end{document}
define(function(require, exports, module) { var Notify = require('common/bootstrap-notify'); exports.run = function() { var $form = $("#user-roles-form"), isTeacher = $form.find('input[value=ROLE_TEACHER]').prop('checked'), currentUser = $form.data('currentuser'), editUser = $form.data('edituser'); if (currentUser == editUser) { $form.find('input[value=ROLE_SUPER_ADMIN]').attr('disabled', 'disabled'); }; $form.find('input[value=ROLE_USER]').on('change', function(){ if ($(this).prop('checked') === false) { $(this).prop('checked', true); var user_name = $('#change-user-roles-btn').data('user') ; Notify.info('用户必须拥有'+user_name+'角色'); } }); $form.on('submit', function() { var roles = []; var $modal = $('#modal'); $form.find('input[name="roles[]"]:checked').each(function(){ roles.push($(this).val()); }); if ($.inArray('ROLE_USER', roles) < 0) { var user_name = $('#change-user-roles-btn').data('user') ; Notify.danger('用户必须拥有'+user_name+'角色'); return false; } if (isTeacher && $.inArray('ROLE_TEACHER', roles) < 0) { if (!confirm('取消该用户的教师角色,同时将收回该用户所有教授的课程的教师权限。您真的要这么做吗?')) { return false; } } $form.find('input[value=ROLE_SUPER_ADMIN]').removeAttr('disabled'); $('#change-user-roles-btn').button('submiting').addClass('disabled'); $.post($form.attr('action'), $form.serialize(), function(html) { $modal.modal('hide'); Notify.success('用户组保存成功'); var $tr = $(html); $('#' + $tr.attr('id')).replaceWith($tr); }).error(function(){ Notify.danger('操作失败'); }); return false; }); }; });
#!/bin/sh echo 'todo!'
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Newtonsoft.Json; namespace Microsoft.AspNetCore.SignalR.Hubs { /// <summary> /// The response returned from an incoming hub request. /// </summary> public class HubResponse { /// <summary> /// The changes made the the round tripped state. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Type is used for serialization")] [JsonProperty("S", NullValueHandling = NullValueHandling.Ignore)] public IDictionary<string, object> State { get; set; } /// <summary> /// The result of the invocation. /// </summary> [JsonProperty("R", NullValueHandling = NullValueHandling.Ignore)] public object Result { get; set; } /// <summary> /// The id of the operation. /// </summary> [JsonProperty("I")] public string Id { get; set; } /// <summary> /// The progress update of the invocation. /// </summary> [JsonProperty("P", NullValueHandling = NullValueHandling.Ignore)] public object Progress { get; set; } /// <summary> /// Indicates whether the Error is a see <see cref="HubException"/>. /// </summary> [JsonProperty("H", NullValueHandling = NullValueHandling.Ignore)] public bool? IsHubException { get; set; } /// <summary> /// The exception that occurs as a result of invoking the hub method. /// </summary> [JsonProperty("E", NullValueHandling = NullValueHandling.Ignore)] public string Error { get; set; } /// <summary> /// The stack logger of the exception that occurs as a result of invoking the hub method. /// </summary> [JsonProperty("T", NullValueHandling = NullValueHandling.Ignore)] public string StackTrace { get; set; } /// <summary> /// Extra error data contained in the <see cref="HubException"/> /// </summary> [JsonProperty("D", NullValueHandling = NullValueHandling.Ignore)] public object ErrorData { get; set; } } }
import * as Cookies from 'js-cookie' import AppSettings from '../appSettings' import { IFetchResult } from '../interfaces' import History from './history' export class HttpUtils { parseJSON<T> (response: Response): Promise<IFetchResult<T>> { return new Promise((resolve, reject) => { if (response.status === 401) { const location = window.location History.push(`/account/logout?returnUrl=${encodeURIComponent(location.pathname + location.search)}&logout=true`) return } else if (response.status === 403) { History.push('/account/login?returnUrl=/') throw { message: 'Access Denied', status: response.status, response } } response.text() .then((text) => { if (text.length > 0) { if (!response.ok && response.status === 500) { try { const data = JSON.parse(text) as T resolve({ status: response.status, ok: response.ok, data: data }) } catch { reject({ ok: false, status: response.status, data: { errorMessage: 'Something has gone wrong on the server!', configurationData: undefined, contentData: undefined, errorMessages: ['Something has gone wrong on the server!'], errors: {}, rulesExceptionListContainers: [] } }) } } else { resolve({ status: response.status, ok: response.ok, data: JSON.parse(text) as T }) } } else { resolve({ status: response.status, ok: response.ok, data: {} as T }) } }) .catch(err => { reject(err) }) }) } get<T> (url: string): Promise<IFetchResult<T>> { return this.futchGet(url) } post<T, R> (url: string, postData: T): Promise<IFetchResult<R>> { return this.futch<T, R>(url, 'POST', postData) } put<T, R> (url: string, postData: T): Promise<IFetchResult<R>> { return this.futch<T, R>(url, 'PUT', postData) } delete<T, R> (url: string, postData: T): Promise<IFetchResult<R>> { return this.futch<T, R>(url, 'DELETE', postData) } postXhr = (url: string, opts: any, onProgress: any, onComplete: any) => { return new Promise((res, rej) => { let xhr = new XMLHttpRequest() xhr.open(opts.method || 'get', url) for (let k in opts.headers || {}) { xhr.setRequestHeader(k, opts.headers[k]) } xhr.onload = res xhr.onerror = rej xhr.onreadystatechange = onComplete xhr.setRequestHeader('X-CSRF-TOKEN-ARRAGROCMS', this.getCSRFCookie()) if (xhr.upload && onProgress) { xhr.upload.onprogress = onProgress // event.loaded / event.total * 100 //event.lengthComputable } xhr.send(opts.body) }) } private getCSRFCookie (): string { const csrf = Cookies.get('ARRAGROCMSCSRF') return csrf === undefined ? '' : csrf } private futchGet<T> (url: string): Promise<IFetchResult<T>> { return fetch(url, { credentials: 'same-origin' }) .then((response: Response) => this.parseJSON<T>(response)) .catch((error) => { if (url !== '/api/user/current') { if (error.data && error.data.errorMessage) { AppSettings.error(`${error.data.errorMessage} - ${url}`, AppSettings.AlertSettings) } else if (error.message) { AppSettings.error(`${error.message} - ${url}`, AppSettings.AlertSettings) } } throw error }) } private futch<T, R> (url: string, verb: string, postData: T): Promise<IFetchResult<R>> { return fetch(url, { credentials: 'same-origin', method: verb, headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN-ARRAGROCMS': this.getCSRFCookie() }, body: JSON.stringify(postData) }) .then((response: Response) => this.parseJSON<R>(response)) .catch((error) => { if (error.data && error.data.errorMessage) { AppSettings.error(`${error.data.errorMessage} - ${url}`, AppSettings.AlertSettings) } else if (error.message) { AppSettings.error(`${error.message} - ${url}`, AppSettings.AlertSettings) } throw error }) } } const httpUtils = new HttpUtils() export default httpUtils
using Abp.Configuration.Startup; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Abp { public class AbpRedisCacheConfig { private string connectionStringKey = "Abp.Redis.Cache"; public string ConnectionStringKey { get { return connectionStringKey; } set { connectionStringKey = value; } } } public static class AbpRedisCacheConfigEctensions { public static AbpRedisCacheConfig AbpRedisCacheModule(this IModuleConfigurations moduleConfigurations) { return moduleConfigurations.AbpConfiguration .GetOrCreate("AbpRedisCacheModule", () => moduleConfigurations.AbpConfiguration.IocManager.Resolve<AbpRedisCacheConfig>() ); } } }
using System; namespace System.Windows.Automation { /// public static class AutomationProperties { #region AutomationId /// <summary> /// AutomationId Property /// </summary> public static readonly DependencyProperty AutomationIdProperty = DependencyProperty.RegisterAttached( "AutomationId", typeof(string), typeof(AutomationProperties), new UIPropertyMetadata(string.Empty), new ValidateValueCallback(IsNotNull)); /// <summary> /// Helper for setting AutomationId property on a DependencyObject. /// </summary> public static void SetAutomationId(DependencyObject element, string value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(AutomationIdProperty, value); } /// <summary> /// Helper for reading AutomationId property from a DependencyObject. /// </summary> public static string GetAutomationId(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return ((string)element.GetValue(AutomationIdProperty)); } #endregion AutomationId #region Name /// <summary> /// Name Property /// </summary> public static readonly DependencyProperty NameProperty = DependencyProperty.RegisterAttached( "Name", typeof(string), typeof(AutomationProperties), new UIPropertyMetadata(string.Empty), new ValidateValueCallback(IsNotNull)); /// <summary> /// Helper for setting Name property on a DependencyObject. /// </summary> public static void SetName(DependencyObject element, string value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(NameProperty, value); } /// <summary> /// Helper for reading Name property from a DependencyObject. /// </summary> public static string GetName(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return ((string)element.GetValue(NameProperty)); } #endregion Name #region HelpText /// <summary> /// HelpText Property /// </summary> public static readonly DependencyProperty HelpTextProperty = DependencyProperty.RegisterAttached( "HelpText", typeof(string), typeof(AutomationProperties), new UIPropertyMetadata(string.Empty), new ValidateValueCallback(IsNotNull)); /// <summary> /// Helper for setting HelpText property on a DependencyObject. /// </summary> public static void SetHelpText(DependencyObject element, string value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(HelpTextProperty, value); } /// <summary> /// Helper for reading HelpText property from a DependencyObject. /// </summary> public static string GetHelpText(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return ((string)element.GetValue(HelpTextProperty)); } #endregion HelpText #region AcceleratorKey /// <summary> /// AcceleratorKey Property /// </summary> public static readonly DependencyProperty AcceleratorKeyProperty = DependencyProperty.RegisterAttached( "AcceleratorKey", typeof(string), typeof(AutomationProperties), new UIPropertyMetadata(string.Empty), new ValidateValueCallback(IsNotNull)); /// <summary> /// Helper for setting AcceleratorKey property on a DependencyObject. /// </summary> public static void SetAcceleratorKey(DependencyObject element, string value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(AcceleratorKeyProperty, value); } /// <summary> /// Helper for reading AcceleratorKey property from a DependencyObject. /// </summary> public static string GetAcceleratorKey(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return ((string)element.GetValue(AcceleratorKeyProperty)); } #endregion AcceleratorKey #region AccessKey /// <summary> /// AccessKey Property /// </summary> public static readonly DependencyProperty AccessKeyProperty = DependencyProperty.RegisterAttached( "AccessKey", typeof(string), typeof(AutomationProperties), new UIPropertyMetadata(string.Empty), new ValidateValueCallback(IsNotNull)); /// <summary> /// Helper for setting AccessKey property on a DependencyObject. /// </summary> public static void SetAccessKey(DependencyObject element, string value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(AccessKeyProperty, value); } /// <summary> /// Helper for reading AccessKey property from a DependencyObject. /// </summary> public static string GetAccessKey(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return ((string)element.GetValue(AccessKeyProperty)); } #endregion AccessKey #region ItemStatus /// <summary> /// ItemStatus Property /// </summary> public static readonly DependencyProperty ItemStatusProperty = DependencyProperty.RegisterAttached( "ItemStatus", typeof(string), typeof(AutomationProperties), new UIPropertyMetadata(string.Empty), new ValidateValueCallback(IsNotNull)); /// <summary> /// Helper for setting ItemStatus property on a DependencyObject. /// </summary> public static void SetItemStatus(DependencyObject element, string value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(ItemStatusProperty, value); } /// <summary> /// Helper for reading ItemStatus property from a DependencyObject. /// </summary> public static string GetItemStatus(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return ((string)element.GetValue(ItemStatusProperty)); } #endregion ItemStatus #region ItemType /// <summary> /// ItemType Property /// </summary> public static readonly DependencyProperty ItemTypeProperty = DependencyProperty.RegisterAttached( "ItemType", typeof(string), typeof(AutomationProperties), new UIPropertyMetadata(string.Empty), new ValidateValueCallback(IsNotNull)); /// <summary> /// Helper for setting ItemType property on a DependencyObject. /// </summary> public static void SetItemType(DependencyObject element, string value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(ItemTypeProperty, value); } /// <summary> /// Helper for reading ItemType property from a DependencyObject. /// </summary> public static string GetItemType(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return ((string)element.GetValue(ItemTypeProperty)); } #endregion ItemType #region IsColumnHeader /// <summary> /// IsColumnHeader Property /// </summary> public static readonly DependencyProperty IsColumnHeaderProperty = DependencyProperty.RegisterAttached( "IsColumnHeader", typeof(bool), typeof(AutomationProperties), new UIPropertyMetadata(MS.Internal.KnownBoxes.BooleanBoxes.FalseBox)); /// <summary> /// Helper for setting IsColumnHeader property on a DependencyObject. /// </summary> public static void SetIsColumnHeader(DependencyObject element, bool value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(IsColumnHeaderProperty, value); } /// <summary> /// Helper for reading IsColumnHeader property from a DependencyObject. /// </summary> public static bool GetIsColumnHeader(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return ((bool)element.GetValue(IsColumnHeaderProperty)); } #endregion IsColumnHeader #region IsRowHeader /// <summary> /// IsRowHeader Property /// </summary> public static readonly DependencyProperty IsRowHeaderProperty = DependencyProperty.RegisterAttached( "IsRowHeader", typeof(bool), typeof(AutomationProperties), new UIPropertyMetadata(MS.Internal.KnownBoxes.BooleanBoxes.FalseBox)); /// <summary> /// Helper for setting IsRowHeader property on a DependencyObject. /// </summary> public static void SetIsRowHeader(DependencyObject element, bool value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(IsRowHeaderProperty, value); } /// <summary> /// Helper for reading IsRowHeader property from a DependencyObject. /// </summary> public static bool GetIsRowHeader(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return ((bool)element.GetValue(IsRowHeaderProperty)); } #endregion IsRowHeader #region IsRequiredForForm /// <summary> /// IsRequiredForForm Property /// </summary> public static readonly DependencyProperty IsRequiredForFormProperty = DependencyProperty.RegisterAttached( "IsRequiredForForm", typeof(bool), typeof(AutomationProperties), new UIPropertyMetadata(MS.Internal.KnownBoxes.BooleanBoxes.FalseBox)); /// <summary> /// Helper for setting IsRequiredForForm property on a DependencyObject. /// </summary> public static void SetIsRequiredForForm(DependencyObject element, bool value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(IsRequiredForFormProperty, value); } /// <summary> /// Helper for reading IsRequiredForForm property from a DependencyObject. /// </summary> public static bool GetIsRequiredForForm(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return ((bool)element.GetValue(IsRequiredForFormProperty)); } #endregion IsRequiredForForm #region LabeledBy /// <summary> /// LabeledBy Property /// </summary> public static readonly DependencyProperty LabeledByProperty = DependencyProperty.RegisterAttached( "LabeledBy", typeof(UIElement), typeof(AutomationProperties), new UIPropertyMetadata((UIElement)null)); /// <summary> /// Helper for setting LabeledBy property on a DependencyObject. /// </summary> public static void SetLabeledBy(DependencyObject element, UIElement value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(LabeledByProperty, value); } /// <summary> /// Helper for reading LabeledBy property from a DependencyObject. /// </summary> public static UIElement GetLabeledBy(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return ((UIElement)element.GetValue(LabeledByProperty)); } #endregion LabeledBy #region IsOffscreenBehavior /// <summary> /// IsOffscreenBehavior Property /// </summary> public static readonly DependencyProperty IsOffscreenBehaviorProperty = DependencyProperty.RegisterAttached( "IsOffscreenBehavior", typeof(IsOffscreenBehavior), typeof(AutomationProperties), new UIPropertyMetadata(IsOffscreenBehavior.Default)); /// <summary> /// Helper for setting IsOffscreenBehavior property on a DependencyObject. /// </summary> public static void SetIsOffscreenBehavior(DependencyObject element, IsOffscreenBehavior value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(IsOffscreenBehaviorProperty, value); } /// <summary> /// Helper for reading IsOffscreenBehavior property from a DependencyObject. /// </summary> public static IsOffscreenBehavior GetIsOffscreenBehavior(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } return ((IsOffscreenBehavior)element.GetValue(IsOffscreenBehaviorProperty)); } #endregion IsOffscreenBehavior #region private implementation // Validation callback for string properties private static bool IsNotNull(object value) { return (value != null); } #endregion } }
package org.sm.jdsa.graph.algorithm.coloring; import java.util.stream.IntStream; import org.sm.jdsa.graph.GraphAdjacencyListImpl; import org.sm.jdsa.list.LinkedList; import org.sm.jdsa.list.Iterator; /** * * Counts number of colors upper bound for graph (vertex) * coloring problem using greedy algorithm. * * @author Stanislav Markov * */ public class ColoringAdjacentListStrategyImpl implements ColoringStrategy { private final GraphAdjacencyListImpl graph; private final int graphSize; private int colorsUsed; private final int[] vertexColors; private final boolean[] adjecentsColors; int numberOfColors = -1; public ColoringAdjacentListStrategyImpl(GraphAdjacencyListImpl graph) { this.graph = graph; this.graphSize = graph.getGraphSize(); this.colorsUsed = 0; this.vertexColors = new int[graphSize]; this.adjecentsColors = new boolean[graphSize]; initVertexColors(); } /** * Main Method, in charge of counting number of different colors. * In case it is already calculated it just passes the value * * @return */ @Override public int getNumberOfColors() { if (numberOfColors < 0 && graphSize > 0) { vertexColors[0] = colorsUsed; IntStream.range(0, graphSize).forEach(vertex -> { int leastAvailableColor = getLeastAvailableColor(vertex); vertexColors[vertex] = leastAvailableColor; colorsUsed = Math.max(colorsUsed, leastAvailableColor); }); numberOfColors = colorsUsed + 1; } return numberOfColors; } /** * Finds the least available color from vertex's adjacents * * @param vertex * @return */ private int getLeastAvailableColor(int vertex) { loadAdjecentsColors(vertex); int leastAvailableColor = -1; int i = 0; while (leastAvailableColor < 0 && i < adjecentsColors.length) { if (!adjecentsColors[i]) leastAvailableColor = i; i++; } return leastAvailableColor; } /** * Loads helper array with already taken color by vertex's adjacents * * @param vertex */ private void loadAdjecentsColors(int vertex) { resetAdjecentsColors(); LinkedList<Integer> vertexAdjecents = graph.getDataStructure()[vertex]; for (int i = 0; i < adjecentsColors.length; i++) { } for(Iterator<Integer> iterator = vertexAdjecents.iterator(); iterator.hasNext();) { int adjacent = iterator.next(); if (adjacent > -1) { adjecentsColors[vertexColors[adjacent]] = true; } } } /* * Resets helper array used for recording colors * assigned to the vertex's adjecents for next vertex */ private void resetAdjecentsColors() { IntStream.range(0, graphSize).forEach(color -> adjecentsColors[color] = false); } /* * Initialization of the array which holds colors assigned to verticies */ private void initVertexColors() { IntStream.range(0, graphSize).forEach(vertex -> vertexColors[vertex] = -1); } }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Publications &#9679; ghost in the computer</title> <link rel="stylesheet" type="text/css" href="/css/style.css" > <link rel="alternate" type="application/atom+xml" href="/feed.xml" title="News Feed"> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,600&amp;subset=cyrillic" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=PT+Sans:400,700&amp;subset=cyrillic" rel="stylesheet"> </head> <body> <div class="container"> <header class="masthead"> <h3 class="masthead-title"> <a href="/">ghost in the computer</a> <!-- <small> &nbsp;&nbsp;&nbsp;<a href="/projects">Projects</a> </small> <small> &nbsp;&nbsp;&nbsp;<a href="/publications">Publications</a> </small> --> <!-- <small> &nbsp;&nbsp;&nbsp;<a href="/feed.xml">Feed</a> </small> --> </h3> </header> <div id="content"> <p>Some words I put online:</p> <ul> <li>Short <a href="https://medium.com/@szvsk/spelunky-8b04c20dbf8">review</a> for Spelunky book (ru);</li> </ul> </div> </div><!-- .container --> </body> </html>
import { ModuleWithProviders } from '@angular/core' import { Routes, RouterModule } from '@angular/router' //anything not maching a registered URL will go to the login page const routes: Routes = [ { path: '**', redirectTo: '/login', pathMatch: 'full' } ] export const routing: ModuleWithProviders = RouterModule.forRoot(routes)
--- layout: micropubpost date: '2018-05-28T18:33:41.488Z' title: '' mf-like-of: - 'https://aaronparecki.com/2018/05/27/10/indieauth-twitter' slug: '66821' category: social ---
--- layout: default --- <h1> <!-- https://allejo.io/blog/a-jekyll-toc-in-liquid-only/ --> <!-- preserve <code/> in titles --> {% capture title %}{% include toc_pure_liquid.html html=content h_min=1 h_max=1 %}{% endcapture %} {{ title | replace: '<code class="highlighter-rouge">', '`' | replace: '</code>', '`' | strip_html | markdownify }} </h1> <nav> <!-- https://allejo.io/blog/a-jekyll-toc-in-liquid-only/ --> {% assign my_min = page.toc_min | default: site.toc_min | default: 2 %} {% assign my_max = page.toc_max | default: site.toc_max | default: 6 %} {% include toc_pure_liquid.html html=content sanitize=true h_min=my_min h_max=my_max %} </nav> {{ content }}
module Ecm module UserArea module Generators class InstallGenerator < Rails::Generators::Base desc "Generates the intializer" source_root File.expand_path('../templates', __FILE__) def generate_intializer copy_file "initializer.rb", "config/initializers/ecm_user_area.rb" end end end end end
/** * Test async injectors */ import { memoryHistory } from 'react-router'; import { put } from 'redux-saga/effects'; import { fromJS } from 'immutable'; import configureStore from 'store'; import { injectAsyncReducer, injectAsyncSagas, getAsyncInjectors, } from '../asyncInjectors'; // Fixtures const initialState = fromJS({ reduced: 'soon' }); const reducer = (state = initialState, action) => { switch (action.type) { case 'TEST': return state.set('reduced', action.payload); default: return state; } }; function* testSaga() { yield put({ type: 'TEST', payload: 'yup' }); } const sagas = [ testSaga, ]; describe('asyncInjectors', () => { let store; describe('getAsyncInjectors', () => { beforeAll(() => { store = configureStore({}, memoryHistory); }); it('given a store, should return all async injectors', () => { const { injectReducer, injectSagas } = getAsyncInjectors(store); injectReducer('test', reducer); injectSagas(sagas); const actual = store.getState().get('test'); const expected = initialState.merge({ reduced: 'yup' }); expect(actual.toJS()).toEqual(expected.toJS()); }); it('should throw if passed invalid store shape', () => { let result = false; Reflect.deleteProperty(store, 'dispatch'); try { getAsyncInjectors(store); } catch (err) { result = err.name === 'Invariant Violation'; } expect(result).toEqual(true); }); }); describe('helpers', () => { beforeAll(() => { store = configureStore({}, memoryHistory); }); describe('injectAsyncReducer', () => { it('given a store, it should provide a function to inject a reducer', () => { const injectReducer = injectAsyncReducer(store); injectReducer('test', reducer); const actual = store.getState().get('test'); const expected = initialState; expect(actual.toJS()).toEqual(expected.toJS()); }); it('should not assign reducer if already existing', () => { const injectReducer = injectAsyncReducer(store); injectReducer('test', reducer); injectReducer('test', () => {}); expect(store.asyncReducers.test.toString()).toEqual(reducer.toString()); }); it('should throw if passed invalid name', () => { let result = false; const injectReducer = injectAsyncReducer(store); try { injectReducer('', reducer); } catch (err) { result = err.name === 'Invariant Violation'; } try { injectReducer(999, reducer); } catch (err) { result = err.name === 'Invariant Violation'; } expect(result).toEqual(true); }); it('should throw if passed invalid reducer', () => { let result = false; const injectReducer = injectAsyncReducer(store); try { injectReducer('bad', 'nope'); } catch (err) { result = err.name === 'Invariant Violation'; } try { injectReducer('coolio', 12345); } catch (err) { result = err.name === 'Invariant Violation'; } expect(result).toEqual(true); }); }); describe('injectAsyncSagas', () => { it('given a store, it should provide a function to inject a saga', () => { const injectSagas = injectAsyncSagas(store); injectSagas(sagas); const actual = store.getState().get('test'); const expected = initialState.merge({ reduced: 'yup' }); expect(actual.toJS()).toEqual(expected.toJS()); }); it('should throw if passed invalid saga', () => { let result = false; const injectSagas = injectAsyncSagas(store); try { injectSagas({ testSaga }); } catch (err) { result = err.name === 'Invariant Violation'; } try { injectSagas(testSaga); } catch (err) { result = err.name === 'Invariant Violation'; } expect(result).toEqual(true); }); }); }); });
# -*- coding: utf-8 -*- ' 检查扩展名是否合法 ' __author__ = 'Ellery' from app import app import datetime, random from PIL import Image import os def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in app.config.get('ALLOWED_EXTENSIONS') def unique_name(): now_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S") random_num = random.randint(0, 100) if random_num <= 10: random_num = str(0) + str(random_num) unique_num = str(now_time) + str(random_num) return unique_num def image_thumbnail(filename): filepath = os.path.join(app.config.get('UPLOAD_FOLDER'), filename) im = Image.open(filepath) w, h = im.size if w > h: im.thumbnail((106, 106*h/w)) else: im.thumbnail((106*w/h, 106)) im.save(os.path.join(app.config.get('UPLOAD_FOLDER'), os.path.splitext(filename)[0] + '_thumbnail' + os.path.splitext(filename)[1])) def image_delete(filename): thumbnail_filepath = os.path.join(app.config.get('UPLOAD_FOLDER'), filename) filepath = thumbnail_filepath.replace('_thumbnail', '') os.remove(filepath) os.remove(thumbnail_filepath) def cut_image(filename, box): filepath = os.path.join(app.config.get('UPLOAD_AVATAR_FOLDER'), filename) im = Image.open(filepath) new_im = im.crop(box) new_im.save(os.path.join(app.config.get('UPLOAD_AVATAR_FOLDER'), filename))
module.exports = function (grunt) { "use strict"; grunt.initConfig({ pkg: grunt.file.readJSON("package.json"), // grunt-contrib-clean clean: { instrument: "<%= instrument.options.basePath %>" }, // grunt-contrib-jshint jshint: { files: [ "<%= instrument.files %>", "<%= mochaTest.test.src %>", "bin/**.js", "gruntfile.js", "node_tests/**/*.js" ], options: grunt.file.readJSON(".jshintrc") }, // grunt-mocha-test mochaTest: { test: { options: { reporter: "spec" }, src: "node_tests/**/*.test.js" } }, // grunt-contrib-watch watch: { files: ["<%= jshint.files %>"], tasks: ["beautify", "test"] }, // grunt-istanbul instrument: { files: "node_libs/**/*.js", options: { basePath: "coverage/instrument/" } }, storeCoverage: { options: { dir: "coverage/reports/<%= pkg.version %>" } }, makeReport: { src: "<%= storeCoverage.options.dir %>/*.json", options: { type: "lcov", dir: "<%= storeCoverage.options.dir %>", print: "detail" } }, // grunt-jsbeautifier jsbeautifier: { files: ["<%= jshint.files %>"], options: { js: grunt.file.readJSON(".jsbeautifyrc") } } }); grunt.loadNpmTasks("grunt-contrib-clean"); grunt.loadNpmTasks("grunt-contrib-jshint"); grunt.loadNpmTasks("grunt-contrib-watch"); grunt.loadNpmTasks("grunt-istanbul"); grunt.loadNpmTasks("grunt-jsbeautifier"); grunt.loadNpmTasks("grunt-mocha-test"); grunt.registerTask("register_globals", function (task) { var moduleRoot; if ("coverage" === task) { moduleRoot = __dirname + "/" + grunt.template.process("<%= instrument.options.basePath %>"); } else if ("test" === task) { moduleRoot = __dirname; } global.MODULE_ROOT = moduleRoot; global.MODULE_ROOT_TESTS = __dirname + "/node_tests"; }); grunt.registerTask("beautify", ["jsbeautifier"]); grunt.registerTask("cover", ["register_globals:coverage", "clean:instrument", "instrument", "lint", "mochaTest", "storeCoverage", "makeReport"]); grunt.registerTask("lint", ["jshint"]); grunt.registerTask("test", ["register_globals:test", "clean:instrument", "lint", "mochaTest"]); grunt.registerTask("default", ["jsbeautifier", "test"]); };
class ConcernBox include BlackBox::Concern subject Hash accept :a, :b, :c, :d expose :[], :size end
const EventEmitter = require('events'); /** * Ends the session. Uses session protocol command. * * @example * this.demoTest = function (browser) { * browser.end(); * }; * * @method end * @syntax .end([callback]) * @param {function} [callback] Optional callback function to be called when the command finishes. * @see session * @api protocol.sessions */ class End extends EventEmitter { command(callback) { const client = this.client; if (this.api.sessionId) { this.api.session('delete', result => { client.session.clearSession(); client.setApiProperty('sessionId', null); this.complete(callback, result); }); } else { setImmediate(() => { this.complete(callback, null); }); } return this.client.api; } complete(callback, result) { if (typeof callback === 'function') { callback.call(this.api, result); } this.emit('complete'); } } module.exports = End;
--- --- <div class="block block-headline"> <a href="{{ url }}"> <h2 class="headline">Headline: Lorem ipsum dolor sit amet, consectetur adipiscing elit</h2> </a> </div>
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GettTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GettTest")] [assembly: AssemblyCopyright("Copyright © 2016 Togocoder")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("91610e04-b20e-4350-b4c6-52d21ff78322")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore //go:generate go run gen.go // This program generates internet protocol constants and tables by // reading IANA protocol registries. package main import ( "bytes" "encoding/xml" "fmt" "go/format" "io" "io/ioutil" "net/http" "os" "strconv" "strings" ) var registries = []struct { url string parse func(io.Writer, io.Reader) error }{ { "http://www.iana.org/assignments/dscp-registry/dscp-registry.xml", parseDSCPRegistry, }, { "http://www.iana.org/assignments/ipv4-tos-byte/ipv4-tos-byte.xml", parseTOSTCByte, }, { "http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xml", parseProtocolNumbers, }, } func main() { var bb bytes.Buffer fmt.Fprintf(&bb, "// go generate gen.go\n") fmt.Fprintf(&bb, "// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT\n\n") fmt.Fprintf(&bb, "// Package iana provides protocol number resources managed by the Internet Assigned Numbers Authority (IANA).\n") fmt.Fprintf(&bb, `package iana // import "golang.org/x/net/internal/iana"` + "\n\n") for _, r := range registries { resp, err := http.Get(r.url) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { fmt.Fprintf(os.Stderr, "got HTTP status code %v for %v\n", resp.StatusCode, r.url) os.Exit(1) } if err := r.parse(&bb, resp.Body); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } fmt.Fprintf(&bb, "\n") } b, err := format.Source(bb.Bytes()) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } if err := ioutil.WriteFile("const.go", b, 0644); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func parseDSCPRegistry(w io.Writer, r io.Reader) error { dec := xml.NewDecoder(r) var dr dscpRegistry if err := dec.Decode(&dr); err != nil { return err } drs := dr.escape() fmt.Fprintf(w, "// %s, Updated: %s\n", dr.Title, dr.Updated) fmt.Fprintf(w, "const (\n") for _, dr := range drs { fmt.Fprintf(w, "DiffServ%s = %#x", dr.Name, dr.Value) fmt.Fprintf(w, "// %s\n", dr.OrigName) } fmt.Fprintf(w, ")\n") return nil } type dscpRegistry struct { XMLName xml.Name `xml:"registry"` Title string `xml:"title"` Updated string `xml:"updated"` Note string `xml:"note"` RegTitle string `xml:"registry>title"` PoolRecords []struct { Name string `xml:"name"` Space string `xml:"space"` } `xml:"registry>record"` Records []struct { Name string `xml:"name"` Space string `xml:"space"` } `xml:"registry>registry>record"` } type canonDSCPRecord struct { OrigName string Name string Value int } func (drr *dscpRegistry) escape() []canonDSCPRecord { drs := make([]canonDSCPRecord, len(drr.Records)) sr := strings.NewReplacer( "+", "", "-", "", "/", "", ".", "", " ", "", ) for i, dr := range drr.Records { s := strings.TrimSpace(dr.Name) drs[i].OrigName = s drs[i].Name = sr.Replace(s) n, err := strconv.ParseUint(dr.Space, 2, 8) if err != nil { continue } drs[i].Value = int(n) << 2 } return drs } func parseTOSTCByte(w io.Writer, r io.Reader) error { dec := xml.NewDecoder(r) var ttb tosTCByte if err := dec.Decode(&ttb); err != nil { return err } trs := ttb.escape() fmt.Fprintf(w, "// %s, Updated: %s\n", ttb.Title, ttb.Updated) fmt.Fprintf(w, "const (\n") for _, tr := range trs { fmt.Fprintf(w, "%s = %#x", tr.Keyword, tr.Value) fmt.Fprintf(w, "// %s\n", tr.OrigKeyword) } fmt.Fprintf(w, ")\n") return nil } type tosTCByte struct { XMLName xml.Name `xml:"registry"` Title string `xml:"title"` Updated string `xml:"updated"` Note string `xml:"note"` RegTitle string `xml:"registry>title"` Records []struct { Binary string `xml:"binary"` Keyword string `xml:"keyword"` } `xml:"registry>record"` } type canonTOSTCByteRecord struct { OrigKeyword string Keyword string Value int } func (ttb *tosTCByte) escape() []canonTOSTCByteRecord { trs := make([]canonTOSTCByteRecord, len(ttb.Records)) sr := strings.NewReplacer( "Capable", "", "(", "", ")", "", "+", "", "-", "", "/", "", ".", "", " ", "", ) for i, tr := range ttb.Records { s := strings.TrimSpace(tr.Keyword) trs[i].OrigKeyword = s ss := strings.Split(s, " ") if len(ss) > 1 { trs[i].Keyword = strings.Join(ss[1:], " ") } else { trs[i].Keyword = ss[0] } trs[i].Keyword = sr.Replace(trs[i].Keyword) n, err := strconv.ParseUint(tr.Binary, 2, 8) if err != nil { continue } trs[i].Value = int(n) } return trs } func parseProtocolNumbers(w io.Writer, r io.Reader) error { dec := xml.NewDecoder(r) var pn protocolNumbers if err := dec.Decode(&pn); err != nil { return err } prs := pn.escape() prs = append([]canonProtocolRecord{{ Name: "IP", Descr: "IPv4 encapsulation, pseudo protocol number", Value: 0, }}, prs...) fmt.Fprintf(w, "// %s, Updated: %s\n", pn.Title, pn.Updated) fmt.Fprintf(w, "const (\n") for _, pr := range prs { if pr.Name == "" { continue } fmt.Fprintf(w, "Protocol%s = %d", pr.Name, pr.Value) s := pr.Descr if s == "" { s = pr.OrigName } fmt.Fprintf(w, "// %s\n", s) } fmt.Fprintf(w, ")\n") return nil } type protocolNumbers struct { XMLName xml.Name `xml:"registry"` Title string `xml:"title"` Updated string `xml:"updated"` RegTitle string `xml:"registry>title"` Note string `xml:"registry>note"` Records []struct { Value string `xml:"value"` Name string `xml:"name"` Descr string `xml:"description"` } `xml:"registry>record"` } type canonProtocolRecord struct { OrigName string Name string Descr string Value int } func (pn *protocolNumbers) escape() []canonProtocolRecord { prs := make([]canonProtocolRecord, len(pn.Records)) sr := strings.NewReplacer( "-in-", "in", "-within-", "within", "-over-", "over", "+", "P", "-", "", "/", "", ".", "", " ", "", ) for i, pr := range pn.Records { if strings.Contains(pr.Name, "Deprecated") || strings.Contains(pr.Name, "deprecated") { continue } prs[i].OrigName = pr.Name s := strings.TrimSpace(pr.Name) switch pr.Name { case "ISIS over IPv4": prs[i].Name = "ISIS" case "manet": prs[i].Name = "MANET" default: prs[i].Name = sr.Replace(s) } ss := strings.Split(pr.Descr, "\n") for i := range ss { ss[i] = strings.TrimSpace(ss[i]) } if len(ss) > 1 { prs[i].Descr = strings.Join(ss, " ") } else { prs[i].Descr = ss[0] } prs[i].Value, _ = strconv.Atoi(pr.Value) } return prs }
[System.Serializable] public class Objectives { public bool isDone; public string Requirement; Objectives() { isDone = false; Requirement = "Objective Display"; } } //Possibly split into //TimedObjective //ResourceObjective //BonusObjective
from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals from SimPEG import Mesh, Utils import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches from scipy.sparse import spdiags,csr_matrix, eye,kron,hstack,vstack,eye,diags import copy from scipy.constants import mu_0 from SimPEG import SolverLU from scipy.sparse.linalg import spsolve,splu from SimPEG.EM import TDEM from SimPEG.EM.Analytics.TDEM import hzAnalyticDipoleT,hzAnalyticCentLoopT from scipy.interpolate import interp2d,LinearNDInterpolator from scipy.special import ellipk,ellipe def rectangular_plane_layout(mesh,corner, closed = False,I=1.): """ corner: sorted list of four corners (x,y,z) 2--3 | | 1--4 y | |--> x Output: Js """ Jx = np.zeros(mesh.nEx) Jy = np.zeros(mesh.nEy) Jz = np.zeros(mesh.nEz) indy1 = np.logical_and( \ np.logical_and( \ np.logical_and(mesh.gridEy[:,0]>=corner[0,0],mesh.gridEy[:,0]<=corner[1,0]), \ np.logical_and(mesh.gridEy[:,1] >=corner[0,1] , mesh.gridEy[:,1]<=corner[1,1] )), (mesh.gridEy[:,2] == corner[0,2] ) ) indx1 = np.logical_and( \ np.logical_and( \ np.logical_and(mesh.gridEx[:,0]>=corner[1,0],mesh.gridEx[:,0]<=corner[2,0]), \ np.logical_and(mesh.gridEx[:,1] >=corner[1,1] , mesh.gridEx[:,1]<=corner[2,1] )), (mesh.gridEx[:,2] == corner[1,2] ) ) indy2 = np.logical_and( \ np.logical_and( \ np.logical_and(mesh.gridEy[:,0]>=corner[2,0],mesh.gridEy[:,0]<=corner[3,0]), \ np.logical_and(mesh.gridEy[:,1] <=corner[2,1] , mesh.gridEy[:,1]>=corner[3,1] )), (mesh.gridEy[:,2] == corner[2,2] ) ) if closed: indx2 = np.logical_and( \ np.logical_and( \ np.logical_and(mesh.gridEx[:,0]>=corner[0,0],mesh.gridEx[:,0]<=corner[3,0]), \ np.logical_and(mesh.gridEx[:,1] >=corner[0,1] , mesh.gridEx[:,1]<=corner[3,1] )), (mesh.gridEx[:,2] == corner[0,2] ) ) else: indx2 = [] Jy[indy1] = -I Jx[indx1] = -I Jy[indy2] = I Jx[indx2] = I J = np.hstack((Jx,Jy,Jz)) J = J*mesh.edge return J def BiotSavart(locs,mesh,Js): """ Compute the magnetic field generated by current discretized on a mesh using Biot-Savart law Input: locs: observation locations mesh: mesh on which the current J is discretized Js: discretized source current in A-m (Finite Volume formulation) Output: B: magnetic field [Bx,By,Bz] """ c = mu_0/(4*np.pi) nwire = np.sum(Js!=0.) ind= np.where(Js!=0.) ind = ind[0] B = np.zeros([locs.shape[0],3]) gridE = np.vstack([mesh.gridEx,mesh.gridEy,mesh.gridEz]) for i in range(nwire): # x wire if ind[i]<mesh.nEx: r = locs-gridE[ind[i]] I = Js[ind[i]]*np.hstack([np.ones([locs.shape[0],1]),np.zeros([locs.shape[0],1]),np.zeros([locs.shape[0],1])]) cr = np.cross(I,r) rsq = np.linalg.norm(r,axis=1)**3. B = B + c*cr/rsq[:,None] # y wire elif ind[i]<mesh.nEx+mesh.nEy: r = locs-gridE[ind[i]] I = Js[ind[i]]*np.hstack([np.zeros([locs.shape[0],1]),np.ones([locs.shape[0],1]),np.zeros([locs.shape[0],1])]) cr = np.cross(I,r) rsq = np.linalg.norm(r,axis=1)**3. B = B + c*cr/rsq[:,None] # z wire elif ind[i]<mesh.nEx+mesh.nEy+mesh.nEz: r = locs-gridE[ind[i]] I = Js[ind[i]]*np.hstack([np.zeros([locs.shape[0],1]),np.zeros([locs.shape[0],1]),np.ones([locs.shape[0],1])]) cr = np.cross(I,r) rsq = np.linalg.norm(r,axis=1)**3. B = B + c*cr/rsq[:,None] else: print('error: index of J out of bounds (number of edges in the mesh)') return B def analytic_infinite_wire(obsloc,wireloc,orientation,I=1.): """ Compute the response of an infinite wire with orientation 'orientation' and current I at the obsvervation locations obsloc Output: B: magnetic field [Bx,By,Bz] """ n,d = obsloc.shape t,d = wireloc.shape d = np.sqrt(np.dot(obsloc**2.,np.ones([d,t]))+np.dot(np.ones([n,d]),(wireloc.T)**2.) - 2.*np.dot(obsloc,wireloc.T)) distr = np.amin(d, axis=1, keepdims = True) idxmind = d.argmin(axis=1) r = obsloc - wireloc[idxmind] orient = np.c_[[orientation for i in range(obsloc.shape[0])]] B = (mu_0*I)/(2*np.pi*(distr**2.))*np.cross(orientation,r) return B def mag_dipole(m,obsloc): """ Compute the response of an infinitesimal mag dipole at location (0,0,0) with orientation X and magnetic moment 'm' at the obsvervation locations obsloc Output: B: magnetic field [Bx,By,Bz] """ loc = np.r_[[[0.,0.,0.]]] n,d = obsloc.shape t,d = loc.shape d = np.sqrt(np.dot(obsloc**2.,np.ones([d,t]))+np.dot(np.ones([n,d]),(loc.T)**2.) - 2.*np.dot(obsloc,loc.T)) d = d.flatten() ind = np.where(d==0.) d[ind] = 1e6 x = obsloc[:,0] y = obsloc[:,1] z = obsloc[:,2] #orient = np.c_[[orientation for i in range(obsloc.shape[0])]] Bz = (mu_0*m)/(4*np.pi*(d**3.))*(3.*((z**2.)/(d**2.))-1.) By = (mu_0*m)/(4*np.pi*(d**3.))*(3.*(z*y)/(d**2.)) Bx = (mu_0*m)/(4*np.pi*(d**3.))*(3.*(x*z)/(d**2.)) B = np.vstack([Bx,By,Bz]).T return B def circularloop(a,obsloc,I=1.): """ From Simpson, Lane, Immer, Youngquist 2001 Compute the magnetic field B response of a current loop of radius 'a' with intensity 'I'. input: a: radius in m obsloc: obsvervation locations Output: B: magnetic field [Bx,By,Bz] """ x = np.atleast_2d(obsloc[:,0]).T y = np.atleast_2d(obsloc[:,1]).T z = np.atleast_2d(obsloc[:,2]).T r = np.linalg.norm(obsloc,axis=1) loc = np.r_[[[0.,0.,0.]]] n,d = obsloc.shape r2 = x**2.+y**2.+z**2. rho2 = x**2.+y**2. alpha2 = a**2.+r2-2*a*np.sqrt(rho2) beta2 = a**2.+r2+2*a*np.sqrt(rho2) k2 = 1-(alpha2/beta2) lbda = x**2.-y**2. C = mu_0*I/np.pi Bx = ((C*x*z)/(2*alpha2*np.sqrt(beta2)*rho2))*\ ((a**2.+r2)*ellipe(k2)-alpha2*ellipk(k2)) Bx[np.isnan(Bx)] = 0. By = ((C*y*z)/(2*alpha2*np.sqrt(beta2)*rho2))*\ ((a**2.+r2)*ellipe(k2)-alpha2*ellipk(k2)) By[np.isnan(By)] = 0. Bz = (C/(2.*alpha2*np.sqrt(beta2)))*\ ((a**2.-r2)*ellipe(k2)+alpha2*ellipk(k2)) Bz[np.isnan(Bz)] = 0. #print(Bx.shape) #print(By.shape) #print(Bz.shape) B = np.hstack([Bx,By,Bz]) return B
--- --- <!doctype html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Photo - A History of UCSF</title> <link href='https://fonts.googleapis.com/css?family=Gilda+Display%7CPT+Sans+Narrow:300' rel='stylesheet' type='text/css'> <link href="ucsf_history.css" rel="stylesheet" type="text/css" media="all" /> {% include google_analytics.html %} </head> <body> <div id="mainbody"> {% include ucsf_banner.html %} <div class="banner"><h1><a href="/">A History of UCSF</a></h1></div> <div id="insidebody"> <div id="photocopy"> <div id="photocopy_text"><h2 class="title"><span class="title-primary">Photos</span></h2> <div id="subhead">Aerial View of the UCSF Campus in 1958 </div> <br /> <img src="images/pictures/ucsf_ariel_view_1958.jpg"/><br/> <br/> <br/> </div> </div> <div id="sidebar"> <div id="sidenav_inside">{% include search_include.html %}<br /> <div id="sidenavtype"> <a href="story.html" class="sidenavtype"><strong>THE STORY</strong></a><br/> <br/> <a href="special_topics.html" class="sidenavtype"><strong>SPECIAL TOPICS</strong></a><br/><br/> <a href="people.html" class="sidenavtype"><strong>PEOPLE</strong></a><br/> <br/> <div id="sidenav_subnav_header"><strong><a href="photos.html" class="sidenav_subnav_type_visited">PHOTOS</a></strong></div> <br/> <a href="buildings.html" class="sidenavtype"><strong>BUILDINGS</strong></a><br/> <br/> <a href="index.html" class="sidenavtype"><strong>HOME</strong></a><br/> </div> </div> </div> </div> {% include footer.html %} </div> {% include bottom_js.html %} </body> </html>
/* * */ #include <stdint.h> #include "unix/constant.h" #include "encode.h" #include "invoke.h" #include "poll.h" #define ONCE_PER_SECOND 100 enum { ENABLED = (1 << 0), /* else disabled */ STARTED = (1 << 1), /* else stopped */ }; static uint8_t flag = 0; void poll_init () { flag = 0; } void poll_enable () { return; flag |= ENABLED; } void poll_disable () { return; flag &= ~ENABLED; poll_stop (); } /* static void poll_callback () */ /* { */ /* return; */ /* encode_msg_0 (MSG_ID_POLL, SERIAL_ID_TO_IGNORE); */ /* } */ void poll_start () { return; if ((flag & STARTED) != 0) return; flag |= STARTED; /* invoke_enable (INVOKE_ID_POLL, ONCE_PER_SECOND, poll_callback); */ } void poll_stop () { return; if ((flag & STARTED) == 0) return; flag &= ~STARTED; /* invoke_disable (INVOKE_ID_POLL); */ }
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Injectable} from '@angular/core'; import {Observable, of} from 'rxjs'; import {concatMap, filter, map} from 'rxjs/operators'; import {HttpHandler} from './backend'; import {HttpContext} from './context'; import {HttpHeaders} from './headers'; import {HttpParams, HttpParamsOptions} from './params'; import {HttpRequest} from './request'; import {HttpEvent, HttpResponse} from './response'; /** * Constructs an instance of `HttpRequestOptions<T>` from a source `HttpMethodOptions` and * the given `body`. This function clones the object and adds the body. * * Note that the `responseType` *options* value is a String that identifies the * single data type of the response. * A single overload version of the method handles each response type. * The value of `responseType` cannot be a union, as the combined signature could imply. * */ function addBody<T>( options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body'|'events'|'response', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'arraybuffer'|'blob'|'json'|'text', withCredentials?: boolean, }, body: T|null): any { return { body, headers: options.headers, context: options.context, observe: options.observe, params: options.params, reportProgress: options.reportProgress, responseType: options.responseType, withCredentials: options.withCredentials, }; } /** * Performs HTTP requests. * This service is available as an injectable class, with methods to perform HTTP requests. * Each request method has multiple signatures, and the return type varies based on * the signature that is called (mainly the values of `observe` and `responseType`). * * Note that the `responseType` *options* value is a String that identifies the * single data type of the response. * A single overload version of the method handles each response type. * The value of `responseType` cannot be a union, as the combined signature could imply. * * @usageNotes * Sample HTTP requests for the [Tour of Heroes](/tutorial/toh-pt0) application. * * ### HTTP Request Example * * ``` * // GET heroes whose name contains search term * searchHeroes(term: string): observable<Hero[]>{ * * const params = new HttpParams({fromString: 'name=term'}); * return this.httpClient.request('GET', this.heroesUrl, {responseType:'json', params}); * } * ``` * * Alternatively, the parameter string can be used without invoking HttpParams * by directly joining to the URL. * ``` * this.httpClient.request('GET', this.heroesUrl + '?' + 'name=term', {responseType:'json'}); * ``` * * * ### JSONP Example * ``` * requestJsonp(url, callback = 'callback') { * return this.httpClient.jsonp(this.heroesURL, callback); * } * ``` * * ### PATCH Example * ``` * // PATCH one of the heroes' name * patchHero (id: number, heroName: string): Observable<{}> { * const url = `${this.heroesUrl}/${id}`; // PATCH api/heroes/42 * return this.httpClient.patch(url, {name: heroName}, httpOptions) * .pipe(catchError(this.handleError('patchHero'))); * } * ``` * * @see [HTTP Guide](guide/http) * @see [HTTP Request](api/common/http/HttpRequest) * * @publicApi */ @Injectable() export class HttpClient { constructor(private handler: HttpHandler) {} /** * Sends an `HttpRequest` and returns a stream of `HttpEvent`s. * * @return An `Observable` of the response, with the response body as a stream of `HttpEvent`s. */ request<R>(req: HttpRequest<any>): Observable<HttpEvent<R>>; /** * Constructs a request that interprets the body as an `ArrayBuffer` and returns the response in * an `ArrayBuffer`. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * * @return An `Observable` of the response, with the response body as an `ArrayBuffer`. */ request(method: string, url: string, options: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<ArrayBuffer>; /** * Constructs a request that interprets the body as a blob and returns * the response as a blob. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body of type `Blob`. */ request(method: string, url: string, options: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<Blob>; /** * Constructs a request that interprets the body as a text string and * returns a string value. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body of type string. */ request(method: string, url: string, options: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<string>; /** * Constructs a request that interprets the body as an `ArrayBuffer` and returns the * the full event stream. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body as an array of `HttpEvent`s for * the request. */ request(method: string, url: string, options: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, observe: 'events', reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<HttpEvent<ArrayBuffer>>; /** * Constructs a request that interprets the body as a `Blob` and returns * the full event stream. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body of type `Blob`. */ request(method: string, url: string, options: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<HttpEvent<Blob>>; /** * Constructs a request which interprets the body as a text string and returns the full event * stream. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body of type string. */ request(method: string, url: string, options: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<HttpEvent<string>>; /** * Constructs a request which interprets the body as a JSON object and returns the full event * stream. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body of type `Object`. */ request(method: string, url: string, options: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, reportProgress?: boolean, observe: 'events', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpEvent<any>>; /** * Constructs a request which interprets the body as a JSON object and returns the full event * stream. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body of type `R`. */ request<R>(method: string, url: string, options: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, reportProgress?: boolean, observe: 'events', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpEvent<R>>; /** * Constructs a request which interprets the body as an `ArrayBuffer` * and returns the full `HttpResponse`. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse`, with the response body as an `ArrayBuffer`. */ request(method: string, url: string, options: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<HttpResponse<ArrayBuffer>>; /** * Constructs a request which interprets the body as a `Blob` and returns the full `HttpResponse`. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse`, with the response body of type `Blob`. */ request(method: string, url: string, options: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<HttpResponse<Blob>>; /** * Constructs a request which interprets the body as a text stream and returns the full * `HttpResponse`. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the HTTP response, with the response body of type string. */ request(method: string, url: string, options: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<HttpResponse<string>>; /** * Constructs a request which interprets the body as a JSON object and returns the full * `HttpResponse`. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the full `HttpResponse`, * with the response body of type `Object`. */ request(method: string, url: string, options: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, reportProgress?: boolean, observe: 'response', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpResponse<Object>>; /** * Constructs a request which interprets the body as a JSON object and returns * the full `HttpResponse` with the response body in the requested type. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the full `HttpResponse`, with the response body of type `R`. */ request<R>(method: string, url: string, options: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, reportProgress?: boolean, observe: 'response', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpResponse<R>>; /** * Constructs a request which interprets the body as a JSON object and returns the full * `HttpResponse` as a JSON object. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse`, with the response body of type `Object`. */ request(method: string, url: string, options?: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, responseType?: 'json', reportProgress?: boolean, withCredentials?: boolean, }): Observable<Object>; /** * Constructs a request which interprets the body as a JSON object * with the response body of the requested type. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse`, with the response body of type `R`. */ request<R>(method: string, url: string, options?: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, responseType?: 'json', reportProgress?: boolean, withCredentials?: boolean, }): Observable<R>; /** * Constructs a request where response type and requested observable are not known statically. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the reuested response, wuth body of type `any`. */ request(method: string, url: string, options?: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, observe?: 'body'|'events'|'response', reportProgress?: boolean, responseType?: 'arraybuffer'|'blob'|'json'|'text', withCredentials?: boolean, }): Observable<any>; /** * Constructs an observable for a generic HTTP request that, when subscribed, * fires the request through the chain of registered interceptors and on to the * server. * * You can pass an `HttpRequest` directly as the only parameter. In this case, * the call returns an observable of the raw `HttpEvent` stream. * * Alternatively you can pass an HTTP method as the first parameter, * a URL string as the second, and an options hash containing the request body as the third. * See `addBody()`. In this case, the specified `responseType` and `observe` options determine the * type of returned observable. * * The `responseType` value determines how a successful response body is parsed. * * If `responseType` is the default `json`, you can pass a type interface for the resulting * object as a type parameter to the call. * * The `observe` value determines the return type, according to what you are interested in * observing. * * An `observe` value of events returns an observable of the raw `HttpEvent` stream, including * progress events by default. * * An `observe` value of response returns an observable of `HttpResponse<T>`, * where the `T` parameter depends on the `responseType` and any optionally provided type * parameter. * * An `observe` value of body returns an observable of `<T>` with the same `T` body type. * */ request(first: string|HttpRequest<any>, url?: string, options: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body'|'events'|'response', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'arraybuffer'|'blob'|'json'|'text', withCredentials?: boolean, } = {}): Observable<any> { let req: HttpRequest<any>; // First, check whether the primary argument is an instance of `HttpRequest`. if (first instanceof HttpRequest) { // It is. The other arguments must be undefined (per the signatures) and can be // ignored. req = first; } else { // It's a string, so it represents a URL. Construct a request based on it, // and incorporate the remaining arguments (assuming `GET` unless a method is // provided. // Figure out the headers. let headers: HttpHeaders|undefined = undefined; if (options.headers instanceof HttpHeaders) { headers = options.headers; } else { headers = new HttpHeaders(options.headers); } // Sort out parameters. let params: HttpParams|undefined = undefined; if (!!options.params) { if (options.params instanceof HttpParams) { params = options.params; } else { params = new HttpParams({fromObject: options.params} as HttpParamsOptions); } } // Construct the request. req = new HttpRequest(first, url!, (options.body !== undefined ? options.body : null), { headers, context: options.context, params, reportProgress: options.reportProgress, // By default, JSON is assumed to be returned for all calls. responseType: options.responseType || 'json', withCredentials: options.withCredentials, }); } // Start with an Observable.of() the initial request, and run the handler (which // includes all interceptors) inside a concatMap(). This way, the handler runs // inside an Observable chain, which causes interceptors to be re-run on every // subscription (this also makes retries re-run the handler, including interceptors). const events$: Observable<HttpEvent<any>> = of(req).pipe(concatMap((req: HttpRequest<any>) => this.handler.handle(req))); // If coming via the API signature which accepts a previously constructed HttpRequest, // the only option is to get the event stream. Otherwise, return the event stream if // that is what was requested. if (first instanceof HttpRequest || options.observe === 'events') { return events$; } // The requested stream contains either the full response or the body. In either // case, the first step is to filter the event stream to extract a stream of // responses(s). const res$: Observable<HttpResponse<any>> = <Observable<HttpResponse<any>>>events$.pipe( filter((event: HttpEvent<any>) => event instanceof HttpResponse)); // Decide which stream to return. switch (options.observe || 'body') { case 'body': // The requested stream is the body. Map the response stream to the response // body. This could be done more simply, but a misbehaving interceptor might // transform the response body into a different format and ignore the requested // responseType. Guard against this by validating that the response is of the // requested type. switch (req.responseType) { case 'arraybuffer': return res$.pipe(map((res: HttpResponse<any>) => { // Validate that the body is an ArrayBuffer. if (res.body !== null && !(res.body instanceof ArrayBuffer)) { throw new Error('Response is not an ArrayBuffer.'); } return res.body; })); case 'blob': return res$.pipe(map((res: HttpResponse<any>) => { // Validate that the body is a Blob. if (res.body !== null && !(res.body instanceof Blob)) { throw new Error('Response is not a Blob.'); } return res.body; })); case 'text': return res$.pipe(map((res: HttpResponse<any>) => { // Validate that the body is a string. if (res.body !== null && typeof res.body !== 'string') { throw new Error('Response is not a string.'); } return res.body; })); case 'json': default: // No validation needed for JSON responses, as they can be of any type. return res$.pipe(map((res: HttpResponse<any>) => res.body)); } case 'response': // The response stream was requested directly, so return it. return res$; default: // Guard against new future observe types being added. throw new Error(`Unreachable: unhandled observe type ${options.observe}}`); } } /** * Constructs a `DELETE` request that interprets the body as an `ArrayBuffer` * and returns the response as an `ArrayBuffer`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response body as an `ArrayBuffer`. */ delete(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, body?: any|null, }): Observable<ArrayBuffer>; /** * Constructs a `DELETE` request that interprets the body as a `Blob` and returns * the response as a `Blob`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response body as a `Blob`. */ delete(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, body?: any|null, }): Observable<Blob>; /** * Constructs a `DELETE` request that interprets the body as a text string and returns * a string. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body of type string. */ delete(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, body?: any|null, }): Observable<string>; /** * Constructs a `DELETE` request that interprets the body as an `ArrayBuffer` * and returns the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, * with response body as an `ArrayBuffer`. */ delete(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, body?: any|null }): Observable<HttpEvent<ArrayBuffer>>; /** * Constructs a `DELETE` request that interprets the body as a `Blob` * and returns the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all the `HttpEvent`s for the request, with the response body as a * `Blob`. */ delete(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, body?: any|null, }): Observable<HttpEvent<Blob>>; /** * Constructs a `DELETE` request that interprets the body as a text string * and returns the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, with the response * body of type string. */ delete(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, body?: any|null, }): Observable<HttpEvent<string>>; /** * Constructs a `DELETE` request that interprets the body as a JSON object * and returns the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, with response body of * type `Object`. */ delete(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, body?: any|null, }): Observable<HttpEvent<Object>>; /** * Constructs a `DELETE`request that interprets the body as a JSON object * and returns the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all the `HttpEvent`s for the request, with a response * body in the requested type. */ delete<T>(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | (string | number | boolean)[]}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, body?: any|null, }): Observable<HttpEvent<T>>; /** * Constructs a `DELETE` request that interprets the body as an `ArrayBuffer` and returns * the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the full `HttpResponse`, with the response body as an `ArrayBuffer`. */ delete(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, body?: any|null, }): Observable<HttpResponse<ArrayBuffer>>; /** * Constructs a `DELETE` request that interprets the body as a `Blob` and returns the full * `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse`, with the response body of type `Blob`. */ delete(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, body?: any|null, }): Observable<HttpResponse<Blob>>; /** * Constructs a `DELETE` request that interprets the body as a text stream and * returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the full `HttpResponse`, with the response body of type string. */ delete(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, body?: any|null, }): Observable<HttpResponse<string>>; /** * Constructs a `DELETE` request the interprets the body as a JSON object and returns * the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse`, with the response body of type `Object`. * */ delete(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, body?: any|null, }): Observable<HttpResponse<Object>>; /** * Constructs a `DELETE` request that interprets the body as a JSON object * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse`, with the response body of the requested type. */ delete<T>(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, body?: any|null, }): Observable<HttpResponse<T>>; /** * Constructs a `DELETE` request that interprets the body as a JSON object and * returns the response body as a JSON object. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body of type `Object`. */ delete(url: string, options?: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, body?: any|null, }): Observable<Object>; /** * Constructs a DELETE request that interprets the body as a JSON object and returns * the response in a given type. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse`, with response body in the requested type. */ delete<T>(url: string, options?: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, body?: any|null, }): Observable<T>; /** * Constructs an observable that, when subscribed, causes the configured * `DELETE` request to execute on the server. See the individual overloads for * details on the return type. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * */ delete(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body'|'events'|'response', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'arraybuffer'|'blob'|'json'|'text', withCredentials?: boolean, body?: any|null, } = {}): Observable<any> { return this.request<any>('DELETE', url, options as any); } /** * Constructs a `GET` request that interprets the body as an `ArrayBuffer` and returns the * response in an `ArrayBuffer`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body as an `ArrayBuffer`. */ get(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<ArrayBuffer>; /** * Constructs a `GET` request that interprets the body as a `Blob` * and returns the response as a `Blob`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body as a `Blob`. */ get(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<Blob>; /** * Constructs a `GET` request that interprets the body as a text string * and returns the response as a string value. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body of type string. */ get(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<string>; /** * Constructs a `GET` request that interprets the body as an `ArrayBuffer` and returns * the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, with the response * body as an `ArrayBuffer`. */ get(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<HttpEvent<ArrayBuffer>>; /** * Constructs a `GET` request that interprets the body as a `Blob` and * returns the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body as a `Blob`. */ get(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<HttpEvent<Blob>>; /** * Constructs a `GET` request that interprets the body as a text string and returns * the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body of type string. */ get(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<HttpEvent<string>>; /** * Constructs a `GET` request that interprets the body as a JSON object * and returns the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body of type `Object`. */ get(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpEvent<Object>>; /** * Constructs a `GET` request that interprets the body as a JSON object and returns the full event * stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with a response body in the requested type. */ get<T>(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpEvent<T>>; /** * Constructs a `GET` request that interprets the body as an `ArrayBuffer` and * returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body as an `ArrayBuffer`. */ get(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<HttpResponse<ArrayBuffer>>; /** * Constructs a `GET` request that interprets the body as a `Blob` and * returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body as a `Blob`. */ get(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<HttpResponse<Blob>>; /** * Constructs a `GET` request that interprets the body as a text stream and * returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body of type string. */ get(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<HttpResponse<string>>; /** * Constructs a `GET` request that interprets the body as a JSON object and * returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the full `HttpResponse`, * with the response body of type `Object`. */ get(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpResponse<Object>>; /** * Constructs a `GET` request that interprets the body as a JSON object and * returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the full `HttpResponse` for the request, * with a response body in the requested type. */ get<T>(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpResponse<T>>; /** * Constructs a `GET` request that interprets the body as a JSON object and * returns the response body as a JSON object. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * * @return An `Observable` of the response body as a JSON object. */ get(url: string, options?: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<Object>; /** * Constructs a `GET` request that interprets the body as a JSON object and returns * the response body in a given type. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse`, with a response body in the requested type. */ get<T>(url: string, options?: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<T>; /** * Constructs an observable that, when subscribed, causes the configured * `GET` request to execute on the server. See the individual overloads for * details on the return type. */ get(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body'|'events'|'response', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'arraybuffer'|'blob'|'json'|'text', withCredentials?: boolean, } = {}): Observable<any> { return this.request<any>('GET', url, options as any); } /** * Constructs a `HEAD` request that interprets the body as an `ArrayBuffer` and * returns the response as an `ArrayBuffer`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body as an `ArrayBuffer`. */ head(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<ArrayBuffer>; /** * Constructs a `HEAD` request that interprets the body as a `Blob` and returns * the response as a `Blob`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body as a `Blob`. */ head(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<Blob>; /** * Constructs a `HEAD` request that interprets the body as a text string and returns the response * as a string value. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body of type string. */ head(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<string>; /** * Constructs a `HEAD` request that interprets the body as an `ArrayBuffer` * and returns the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body as an `ArrayBuffer`. */ head(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<HttpEvent<ArrayBuffer>>; /** * Constructs a `HEAD` request that interprets the body as a `Blob` and * returns the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body as a `Blob`. */ head(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<HttpEvent<Blob>>; /** * Constructs a `HEAD` request that interprets the body as a text string * and returns the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, with the response body of type * string. */ head(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<HttpEvent<string>>; /** * Constructs a `HEAD` request that interprets the body as a JSON object * and returns the full HTTP event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, with a response body of * type `Object`. */ head(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpEvent<Object>>; /** * Constructs a `HEAD` request that interprets the body as a JSON object and * returns the full event stream. * * @return An `Observable` of all the `HttpEvent`s for the request, * with a response body in the requested type. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. */ head<T>(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpEvent<T>>; /** * Constructs a `HEAD` request that interprets the body as an `ArrayBuffer` * and returns the full HTTP response. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body as an `ArrayBuffer`. */ head(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<HttpResponse<ArrayBuffer>>; /** * Constructs a `HEAD` request that interprets the body as a `Blob` and returns * the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body as a blob. */ head(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<HttpResponse<Blob>>; /** * Constructs a `HEAD` request that interprets the body as text stream * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body of type string. */ head(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<HttpResponse<string>>; /** * Constructs a `HEAD` request that interprets the body as a JSON object and * returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body of type `Object`. */ head(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpResponse<Object>>; /** * Constructs a `HEAD` request that interprets the body as a JSON object * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse` for the request, * with a responmse body of the requested type. */ head<T>(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpResponse<T>>; /** * Constructs a `HEAD` request that interprets the body as a JSON object and * returns the response body as a JSON object. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body as a JSON object. */ head(url: string, options?: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<Object>; /** * Constructs a `HEAD` request that interprets the body as a JSON object and returns * the response in a given type. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse` for the request, * with a response body of the given type. */ head<T>(url: string, options?: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<T>; /** * Constructs an observable that, when subscribed, causes the configured * `HEAD` request to execute on the server. The `HEAD` method returns * meta information about the resource without transferring the * resource itself. See the individual overloads for * details on the return type. */ head(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body'|'events'|'response', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'arraybuffer'|'blob'|'json'|'text', withCredentials?: boolean, } = {}): Observable<any> { return this.request<any>('HEAD', url, options as any); } /** * Constructs a `JSONP` request for the given URL and name of the callback parameter. * * @param url The resource URL. * @param callbackParam The callback function name. * * @return An `Observable` of the response object, with response body as an object. */ jsonp(url: string, callbackParam: string): Observable<Object>; /** * Constructs a `JSONP` request for the given URL and name of the callback parameter. * * @param url The resource URL. * @param callbackParam The callback function name. * * You must install a suitable interceptor, such as one provided by `HttpClientJsonpModule`. * If no such interceptor is reached, * then the `JSONP` request can be rejected by the configured backend. * * @return An `Observable` of the response object, with response body in the requested type. */ jsonp<T>(url: string, callbackParam: string): Observable<T>; /** * Constructs an `Observable` that, when subscribed, causes a request with the special method * `JSONP` to be dispatched via the interceptor pipeline. * The [JSONP pattern](https://en.wikipedia.org/wiki/JSONP) works around limitations of certain * API endpoints that don't support newer, * and preferable [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) protocol. * JSONP treats the endpoint API as a JavaScript file and tricks the browser to process the * requests even if the API endpoint is not located on the same domain (origin) as the client-side * application making the request. * The endpoint API must support JSONP callback for JSONP requests to work. * The resource API returns the JSON response wrapped in a callback function. * You can pass the callback function name as one of the query parameters. * Note that JSONP requests can only be used with `GET` requests. * * @param url The resource URL. * @param callbackParam The callback function name. * */ jsonp<T>(url: string, callbackParam: string): Observable<T> { return this.request<any>('JSONP', url, { params: new HttpParams().append(callbackParam, 'JSONP_CALLBACK'), observe: 'body', responseType: 'json', }); } /** * Constructs an `OPTIONS` request that interprets the body as an * `ArrayBuffer` and returns the response as an `ArrayBuffer`. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of the response, with the response body as an `ArrayBuffer`. */ options(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<ArrayBuffer>; /** * Constructs an `OPTIONS` request that interprets the body as a `Blob` and returns * the response as a `Blob`. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of the response, with the response body as a `Blob`. */ options(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<Blob>; /** * Constructs an `OPTIONS` request that interprets the body as a text string and * returns a string value. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of the response, with the response body of type string. */ options(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<string>; /** * Constructs an `OPTIONS` request that interprets the body as an `ArrayBuffer` * and returns the full event stream. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body as an `ArrayBuffer`. */ options(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<HttpEvent<ArrayBuffer>>; /** * Constructs an `OPTIONS` request that interprets the body as a `Blob` and * returns the full event stream. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body as a `Blob`. */ options(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<HttpEvent<Blob>>; /** * Constructs an `OPTIONS` request that interprets the body as a text string * and returns the full event stream. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of all the `HttpEvent`s for the request, * with the response body of type string. */ options(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<HttpEvent<string>>; /** * Constructs an `OPTIONS` request that interprets the body as a JSON object * and returns the full event stream. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of all the `HttpEvent`s for the request with the response * body of type `Object`. */ options(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpEvent<Object>>; /** * Constructs an `OPTIONS` request that interprets the body as a JSON object and * returns the full event stream. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of all the `HttpEvent`s for the request, * with a response body in the requested type. */ options<T>(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpEvent<T>>; /** * Constructs an `OPTIONS` request that interprets the body as an `ArrayBuffer` * and returns the full HTTP response. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body as an `ArrayBuffer`. */ options(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<HttpResponse<ArrayBuffer>>; /** * Constructs an `OPTIONS` request that interprets the body as a `Blob` * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body as a `Blob`. */ options(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<HttpResponse<Blob>>; /** * Constructs an `OPTIONS` request that interprets the body as text stream * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body of type string. */ options(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<HttpResponse<string>>; /** * Constructs an `OPTIONS` request that interprets the body as a JSON object * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body of type `Object`. */ options(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpResponse<Object>>; /** * Constructs an `OPTIONS` request that interprets the body as a JSON object and * returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with a response body in the requested type. */ options<T>(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpResponse<T>>; /** * Constructs an `OPTIONS` request that interprets the body as a JSON object and returns the * response body as a JSON object. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of the response, with the response body as a JSON object. */ options(url: string, options?: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<Object>; /** * Constructs an `OPTIONS` request that interprets the body as a JSON object and returns the * response in a given type. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse`, with a response body of the given type. */ options<T>(url: string, options?: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<T>; /** * Constructs an `Observable` that, when subscribed, causes the configured * `OPTIONS` request to execute on the server. This method allows the client * to determine the supported HTTP methods and other capabilites of an endpoint, * without implying a resource action. See the individual overloads for * details on the return type. */ options(url: string, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body'|'events'|'response', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'arraybuffer'|'blob'|'json'|'text', withCredentials?: boolean, } = {}): Observable<any> { return this.request<any>('OPTIONS', url, options as any); } /** * Constructs a `PATCH` request that interprets the body as an `ArrayBuffer` and returns * the response as an `ArrayBuffer`. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of the response, with the response body as an `ArrayBuffer`. */ patch(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<ArrayBuffer>; /** * Constructs a `PATCH` request that interprets the body as a `Blob` and returns the response * as a `Blob`. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of the response, with the response body as a `Blob`. */ patch(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<Blob>; /** * Constructs a `PATCH` request that interprets the body as a text string and * returns the response as a string value. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of the response, with a response body of type string. */ patch(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<string>; /** * Constructs a `PATCH` request that interprets the body as an `ArrayBuffer` and * returns the full event stream. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of all the `HttpEvent`s for the request, * with the response body as an `ArrayBuffer`. */ patch(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<HttpEvent<ArrayBuffer>>; /** * Constructs a `PATCH` request that interprets the body as a `Blob` * and returns the full event stream. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of all the `HttpEvent`s for the request, with the * response body as `Blob`. */ patch(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<HttpEvent<Blob>>; /** * Constructs a `PATCH` request that interprets the body as a text string and * returns the full event stream. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of all the `HttpEvent`s for the request, with a * response body of type string. */ patch(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<HttpEvent<string>>; /** * Constructs a `PATCH` request that interprets the body as a JSON object * and returns the full event stream. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of all the `HttpEvent`s for the request, * with a response body of type `Object`. */ patch(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpEvent<Object>>; /** * Constructs a `PATCH` request that interprets the body as a JSON object * and returns the full event stream. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of all the `HttpEvent`s for the request, * with a response body in the requested type. */ patch<T>(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpEvent<T>>; /** * Constructs a `PATCH` request that interprets the body as an `ArrayBuffer` * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body as an `ArrayBuffer`. */ patch(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<HttpResponse<ArrayBuffer>>; /** * Constructs a `PATCH` request that interprets the body as a `Blob` and returns the full * `HttpResponse`. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body as a `Blob`. */ patch(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<HttpResponse<Blob>>; /** * Constructs a `PATCH` request that interprets the body as a text stream and returns the * full `HttpResponse`. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with a response body of type string. */ patch(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<HttpResponse<string>>; /** * Constructs a `PATCH` request that interprets the body as a JSON object * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with a response body in the requested type. */ patch(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpResponse<Object>>; /** * Constructs a `PATCH` request that interprets the body as a JSON object * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with a response body in the given type. */ patch<T>(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpResponse<T>>; /** * Constructs a `PATCH` request that interprets the body as a JSON object and * returns the response body as a JSON object. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of the response, with the response body as a JSON object. */ patch(url: string, body: any|null, options?: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<Object>; /** * Constructs a `PATCH` request that interprets the body as a JSON object * and returns the response in a given type. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with a response body in the given type. */ patch<T>(url: string, body: any|null, options?: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<T>; /** * Constructs an observable that, when subscribed, causes the configured * `PATCH` request to execute on the server. See the individual overloads for * details on the return type. */ patch(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body'|'events'|'response', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'arraybuffer'|'blob'|'json'|'text', withCredentials?: boolean, } = {}): Observable<any> { return this.request<any>('PATCH', url, addBody(options, body)); } /** * Constructs a `POST` request that interprets the body as an `ArrayBuffer` and returns * an `ArrayBuffer`. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options. * * @return An `Observable` of the response, with the response body as an `ArrayBuffer`. */ post(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<ArrayBuffer>; /** * Constructs a `POST` request that interprets the body as a `Blob` and returns the * response as a `Blob`. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of the response, with the response body as a `Blob`. */ post(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<Blob>; /** * Constructs a `POST` request that interprets the body as a text string and * returns the response as a string value. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of the response, with a response body of type string. */ post(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<string>; /** * Constructs a `POST` request that interprets the body as an `ArrayBuffer` and * returns the full event stream. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body as an `ArrayBuffer`. */ post(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<HttpEvent<ArrayBuffer>>; /** * Constructs a `POST` request that interprets the body as a `Blob` * and returns the response in an observable of the full event stream. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of all `HttpEvent`s for the request, with the response body as `Blob`. */ post(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<HttpEvent<Blob>>; /** * Constructs a `POST` request that interprets the body as a text string and returns the full * event stream. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of all `HttpEvent`s for the request, * with a response body of type string. */ post(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<HttpEvent<string>>; /** * Constructs a POST request that interprets the body as a JSON object and returns the full event * stream. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of all `HttpEvent`s for the request, * with a response body of type `Object`. */ post(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpEvent<Object>>; /** * Constructs a POST request that interprets the body as a JSON object and returns the full event * stream. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of all `HttpEvent`s for the request, * with a response body in the requested type. */ post<T>(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpEvent<T>>; /** * Constructs a POST request that interprets the body as an `ArrayBuffer` * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, with the response body as an * `ArrayBuffer`. */ post(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<HttpResponse<ArrayBuffer>>; /** * Constructs a `POST` request that interprets the body as a `Blob` and returns the full * `HttpResponse`. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, * with the response body as a `Blob`. */ post(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<HttpResponse<Blob>>; /** * Constructs a `POST` request that interprets the body as a text stream and returns * the full `HttpResponse`. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, * with a response body of type string. */ post(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<HttpResponse<string>>; /** * Constructs a `POST` request that interprets the body as a JSON object * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, with a response body of type * `Object`. */ post(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpResponse<Object>>; /** * Constructs a `POST` request that interprets the body as a JSON object and returns the full * `HttpResponse`. * * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, with a response body in the * requested type. */ post<T>(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpResponse<T>>; /** * Constructs a `POST` request that interprets the body as a * JSON object and returns the response body as a JSON object. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of the response, with the response body as a JSON object. */ post(url: string, body: any|null, options?: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<Object>; /** * Constructs a `POST` request that interprets the body as a JSON object * and returns an observable of the response. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, with a response body in the * requested type. */ post<T>(url: string, body: any|null, options?: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<T>; /** * Constructs an observable that, when subscribed, causes the configured * `POST` request to execute on the server. The server responds with the location of * the replaced resource. See the individual overloads for * details on the return type. */ post(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body'|'events'|'response', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'arraybuffer'|'blob'|'json'|'text', withCredentials?: boolean, } = {}): Observable<any> { return this.request<any>('POST', url, addBody(options, body)); } /** * Constructs a `PUT` request that interprets the body as an `ArrayBuffer` and returns the * response as an `ArrayBuffer`. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of the response, with the response body as an `ArrayBuffer`. */ put(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<ArrayBuffer>; /** * Constructs a `PUT` request that interprets the body as a `Blob` and returns * the response as a `Blob`. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of the response, with the response body as a `Blob`. */ put(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<Blob>; /** * Constructs a `PUT` request that interprets the body as a text string and * returns the response as a string value. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of the response, with a response body of type string. */ put(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<string>; /** * Constructs a `PUT` request that interprets the body as an `ArrayBuffer` and * returns the full event stream. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body as an `ArrayBuffer`. */ put(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<HttpEvent<ArrayBuffer>>; /** * Constructs a `PUT` request that interprets the body as a `Blob` and returns the full event * stream. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body as a `Blob`. */ put(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<HttpEvent<Blob>>; /** * Constructs a `PUT` request that interprets the body as a text string and returns the full event * stream. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of all `HttpEvent`s for the request, with a response body * of type string. */ put(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<HttpEvent<string>>; /** * Constructs a `PUT` request that interprets the body as a JSON object and returns the full event * stream. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of all `HttpEvent`s for the request, with a response body of * type `Object`. */ put(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpEvent<Object>>; /** * Constructs a `PUT` request that interprets the body as a JSON object and returns the * full event stream. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of all `HttpEvent`s for the request, * with a response body in the requested type. */ put<T>(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpEvent<T>>; /** * Constructs a `PUT` request that interprets the body as an * `ArrayBuffer` and returns an observable of the full HTTP response. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, with the response body as an * `ArrayBuffer`. */ put(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'arraybuffer', withCredentials?: boolean, }): Observable<HttpResponse<ArrayBuffer>>; /** * Constructs a `PUT` request that interprets the body as a `Blob` and returns the * full HTTP response. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, * with the response body as a `Blob`. */ put(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'blob', withCredentials?: boolean, }): Observable<HttpResponse<Blob>>; /** * Constructs a `PUT` request that interprets the body as a text stream and returns the * full HTTP response. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, with a response body of type * string. */ put(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType: 'text', withCredentials?: boolean, }): Observable<HttpResponse<string>>; /** * Constructs a `PUT` request that interprets the body as a JSON object and returns the full HTTP * response. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, with a response body * of type 'Object`. */ put(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpResponse<Object>>; /** * Constructs a `PUT` request that interprets the body as an instance of the requested type and * returns the full HTTP response. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, * with a response body in the requested type. */ put<T>(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', context?: HttpContext, params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<HttpResponse<T>>; /** * Constructs a `PUT` request that interprets the body as a JSON object * and returns an observable of JSON object. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of the response as a JSON object. */ put(url: string, body: any|null, options?: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<Object>; /** * Constructs a `PUT` request that interprets the body as an instance of the requested type * and returns an observable of the requested type. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of the requested type. */ put<T>(url: string, body: any|null, options?: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean, }): Observable<T>; /** * Constructs an observable that, when subscribed, causes the configured * `PUT` request to execute on the server. The `PUT` method replaces an existing resource * with a new set of values. * See the individual overloads for details on the return type. */ put(url: string, body: any|null, options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body'|'events'|'response', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'arraybuffer'|'blob'|'json'|'text', withCredentials?: boolean, } = {}): Observable<any> { return this.request<any>('PUT', url, addBody(options, body)); } }
import Botkit from 'botkit'; import os from 'os'; import Wit from 'botkit-middleware-witai'; import moment from 'moment-timezone'; import models from '../../app/models'; import storageCreator from '../lib/storage'; import setupReceiveMiddleware from '../middleware/receiveMiddleware'; import notWitController from './notWit'; import miscController from './misc'; import sessionsController from './sessions'; import pingsController from './pings'; import slashController from './slash'; import dashboardController from './dashboard'; import { seedAndUpdateUsers } from '../../app/scripts'; require('dotenv').config(); var env = process.env.NODE_ENV || 'development'; if (env == 'development') { process.env.SLACK_ID = process.env.DEV_SLACK_ID; process.env.SLACK_SECRET = process.env.DEV_SLACK_SECRET; } // actions import { firstInstallInitiateConversation, loginInitiateConversation } from '../actions'; // Wit Brain if (process.env.WIT_TOKEN) { var wit = Wit({ token: process.env.WIT_TOKEN, minimum_confidence: 0.55 }); } else { console.log('Error: Specify WIT_TOKEN in environment'); process.exit(1); } export { wit }; /** * *** CONFIG **** */ var config = {}; const storage = storageCreator(config); var controller = Botkit.slackbot({ interactive_replies: true, storage }); export { controller }; /** * User has joined slack channel ==> make connection * then onboard! */ controller.on('team_join', function (bot, message) { console.log("\n\n\n ~~ joined the team ~~ \n\n\n"); const SlackUserId = message.user.id; console.log(message.user.id); bot.api.users.info({ user: SlackUserId }, (err, response) => { if (!err) { const { user, user: { id, team_id, name, tz } } = response; const email = user.profile && user.profile.email ? user.profile.email : ''; models.User.find({ where: { SlackUserId }, }) .then((user) => { if (!user) { models.User.create({ TeamId: team_id, email, tz, SlackUserId, SlackName: name }); } else { user.update({ TeamId: team_id, SlackName: name }) } }); } }); }); /** * User has updated data ==> update our DB! */ controller.on('user_change', function (bot, message) { console.log("\n\n\n ~~ user updated profile ~~ \n\n\n"); if (message && message.user) { const { user, user: { name, id, team_id, tz } } = message; const SlackUserId = id; const email = user.profile && user.profile.email ? user.profile.email : ''; models.User.find({ where: { SlackUserId }, }) .then((user) => { if (!user) { models.User.create({ TeamId: team_id, email, tz, SlackUserId, SlackName: name }); } else { user.update({ TeamId: team_id, SlackName: name }) } }); } }); // simple way to keep track of bots export var bots = {}; if (!process.env.SLACK_ID || !process.env.SLACK_SECRET || !process.env.HTTP_PORT) { console.log('Error: Specify SLACK_ID SLACK_SECRET and HTTP_PORT in environment'); process.exit(1); } // Custom Toki Config export function customConfigBot(controller) { // beef up the bot setupReceiveMiddleware(controller); notWitController(controller); dashboardController(controller); pingsController(controller); sessionsController(controller); slashController(controller); miscController(controller); } // try to avoid repeat RTM's export function trackBot(bot) { bots[bot.config.token] = bot; } /** * *** TURN ON THE BOT **** * VIA SIGNUP OR LOGIN */ export function connectOnInstall(team_config) { console.log(`\n\n\n\n CONNECTING ON INSTALL \n\n\n\n`); let bot = controller.spawn(team_config); controller.trigger('create_bot', [bot, team_config]); } export function connectOnLogin(identity) { // bot already exists, get bot token for this users team var SlackUserId = identity.user_id; var TeamId = identity.team_id; models.Team.find({ where: { TeamId } }) .then((team) => { const { token } = team; if (token) { var bot = controller.spawn({ token }); controller.trigger('login_bot', [bot, identity]); } }) } controller.on('rtm_open',function(bot) { console.log(`\n\n\n\n** The RTM api just connected! for bot token: ${bot.config.token}\n\n\n`); }); // upon install controller.on('create_bot', (bot,team) => { const { id, url, name, bot: { token, user_id, createdBy, accessToken, scopes } } = team; // this is what is used to save team data const teamConfig = { TeamId: id, createdBy, url, name, token, scopes, accessToken } if (bots[bot.config.token]) { // already online! do nothing. console.log("already online! restarting bot due to re-install"); // restart the bot bots[bot.config.token].closeRTM(); } bot.startRTM((err) => { if (!err) { console.log("\n\n RTM on with team install and listening \n\n"); trackBot(bot); controller.saveTeam(teamConfig, (err, id) => { if (err) { console.log("Error saving team") } else { console.log("Team " + team.name + " saved"); console.log(`\n\n installing users... \n\n`); bot.api.users.list({}, (err, response) => { if (!err) { const { members } = response; seedAndUpdateUsers(members); } firstInstallInitiateConversation(bot, team); }); } }); } else { console.log("RTM failed") } }); }); // subsequent logins controller.on('login_bot', (bot,identity) => { if (bots[bot.config.token]) { // already online! do nothing. console.log("already online! do nothing."); loginInitiateConversation(bot, identity); } else { bot.startRTM((err) => { if (!err) { console.log("RTM on and listening"); trackBot(bot); loginInitiateConversation(bot, identity); } else { console.log("RTM failed") console.log(err); } }); } });
<?php include("../core/init.php"); require_once("../class/Mail.php"); $flag=true; $id_user = addslashes($_POST['id_user']); $res = $mysqli->query("SELECT nom, prenom, identifiant, id_classe FROM fc_user WHERE id_user = '$id_user'"); if(mysqli_num_rows($res) > 0){ $tab=$res->fetch_assoc(); $nom = stripslashes($tab['nom']); $prenom = stripslashes($tab['prenom']); $identifiant = stripslashes($tab['identifiant']); $id_classe = stripslashes($tab['id_classe']); mysqli_free_result($res); $res_classe= $mysqli->query("SELECT referent, identifiant, niveau, barette, classe FROM fc_classe, fc_user WHERE fc_classe.id_classe = '$id_classe' AND id_user = referent"); if(mysqli_num_rows($res_classe) > 0){ $tab_classe=$res_classe->fetch_assoc(); mysqli_free_result($res_classe); $identifiant_ref = $tab_classe['identifiant']; $id_user_ref = $tab_classe['referent']; $niveau=$tab_classe['niveau']; $barette=$tab_classe['barette']; $classe=$tab_classe['classe']; $classe = $niveau." ".$barette." ".$classe; $date_message=time(); $message = "L'utilisateur n°".$id_user." souhaite supprimer son compte.<br>Veuillez vous rendre dans l'espace d'administration de FreeCademy afin de procéder à l'opération."; $message= addslashes(str_replace("<br>", "\n\r", utf8_decode($message))); $insert = $mysqli->query("INSERT INTO fc_user_message VALUES ('', 2, '$id_user_ref', 1, '$message', '$date_message')"); $bcc=''; $cc=''; $to="Freecademy Contact utilisateurs <$identifiant_ref>"; $tab_banished_IP=array("222.77.83.226","222.77.83.231"); if(!preg_match("#http#",$email) && !in_array($_SERVER['REMOTE_ADDR'],$tab_banished_IP)){ $message="Identité du contact : Nom : ".utf8_decode($nom)." Prénom : ".utf8_decode($prenom)." Classe : ".utf8_decode($classe)." Email : ".utf8_decode($identifiant)." Message : ".utf8_decode($message); $file_name=array(); $object="=?iso-8859-1?B?".base64_encode((stripslashes("[Freecademy] ".$objet)))."?="; $sendMe=send_mail($email,$to,$cc,$bcc,$message,$objet,$file_name,$path_dep=""); if($insert && $sendMe){ $flag=true; } }else{ $flag=false; } }else { $flag=false; } } if($flag){ echo "1"; }else{ echo "0"; } $mysqli->close(); ?>
namespace MealsToday.MVC.Providers.DBModels { public class UserInserted { public int UserId { get; set; } public string Email { get; set; } } }
#!/bin/bash -x # # Generated - do not edit! # # Macros TOP=`pwd` CND_PLATFORM=Cygwin_4.x-Windows CND_CONF=Debug CND_DISTDIR=dist CND_BUILDDIR=build CND_DLIB_EXT=dll NBTMPDIR=${CND_BUILDDIR}/${CND_CONF}/${CND_PLATFORM}/tmp-packaging TMPDIRNAME=tmp-packaging OUTPUT_PATH=${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cs501kruskal OUTPUT_BASENAME=cs501kruskal PACKAGE_TOP_DIR=cs501kruskal/ # Functions function checkReturnCode { rc=$? if [ $rc != 0 ] then exit $rc fi } function makeDirectory # $1 directory path # $2 permission (optional) { mkdir -p "$1" checkReturnCode if [ "$2" != "" ] then chmod $2 "$1" checkReturnCode fi } function copyFileToTmpDir # $1 from-file path # $2 to-file path # $3 permission { cp "$1" "$2" checkReturnCode if [ "$3" != "" ] then chmod $3 "$2" checkReturnCode fi } # Setup cd "${TOP}" mkdir -p ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package rm -rf ${NBTMPDIR} mkdir -p ${NBTMPDIR} # Copy files and create directories and links cd "${TOP}" makeDirectory "${NBTMPDIR}/cs501kruskal/bin" copyFileToTmpDir "${OUTPUT_PATH}.exe" "${NBTMPDIR}/${PACKAGE_TOP_DIR}bin/${OUTPUT_BASENAME}.exe" 0755 # Generate tar file cd "${TOP}" rm -f ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/cs501kruskal.tar cd ${NBTMPDIR} tar -vcf ../../../../${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/cs501kruskal.tar * checkReturnCode # Cleanup cd "${TOP}" rm -rf ${NBTMPDIR}
<?php /* * This file is part of Sulu. * * (c) MASSIVE ART WebServices GmbH * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Sulu\Bundle\SecurityBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Sulu\Bundle\SecurityBundle\Entity\SecurityType; use Symfony\Component\DependencyInjection\ContainerAware; class LoadSecurityTypes extends ContainerAware implements FixtureInterface, OrderedFixtureInterface { /** * {@inheritdoc} */ public function load(ObjectManager $manager) { // force id = 1 $metadata = $manager->getClassMetaData(get_class(new SecurityType())); $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE); $file = $this->container->getParameter('sulu_security.security_types.fixture'); $doc = new \DOMDocument(); $doc->load($file); $xpath = new \DOMXpath($doc); $elements = $xpath->query('/security-types/security-type'); if (!is_null($elements)) { /** @var $element \DOMNode */ foreach ($elements as $element) { $securityType = new SecurityType(); $children = $element->childNodes; /** @var $child \DOMNode */ foreach ($children as $child) { if (isset($child->nodeName)) { if ($child->nodeName == 'id') { $securityType->setId($child->nodeValue); } if ($child->nodeName == 'name') { $securityType->setName($child->nodeValue); } } } $manager->persist($securityType); } } $manager->flush(); } /** * {@inheritdoc} */ public function getOrder() { return 5; } }
--- layout: default title: Account title_label: hide post_scripts: - js/account.js startup_functions: - redirectIfNotLoggedIn() --- <div class="header"> {% include small-banner.html %} {% include header.html %} </div> <div class="wrapper container"> <div class="row"> <div class="col-md-6"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Update User Password</h3> </div> <div class="panel-body"> <div class="col-md-10 col-md-offset-1"> <form role="form" id="password-update-form"> <div class="form-group"> <label for="current-password" class="control-label">Current Password</label> <input name="current-password" id="current-password" class="form-control" type="password" placeholder="Current Password"> </div> <div class="form-group"> <label for="new-password" class="control-label">New Password</label> <input name="new-password" id="new-password" class="form-control" type="password" placeholder="New Password"> </div> <div class="form-group"> <label for="new-password-confirmation" class="control-label">Repeat New Password</label> <input name="new-password-confirmation" id="new-password-confirmation" class="form-control" type="password" placeholder="Repeat New Password"> </div> <div class="form-group"> <button id="password-update-button" class="btn btn-primary" type="submit">Update Password</button> </div> </form> </div> </div> </div> </div> <div class="col-md-6"> <div class="panel panel-danger"> <div class="panel-heading"> <h3 class="panel-title">Leave Team and Disable Account</h3> <em>This is permanent action; you can not undo this.</em> </div> <div class="panel-body"> <div class="col-md-10 col-md-offset-1"> <form role="form" id="disable-account-form"> <p>Disabling your account will remove you from your team, freeing up a slot for another member. You will not be able to log in once you disable your account. Disabled accounts cannot be re-enabled.</p> <div class="form-group"> <label for="current-password" class="control-label">Current Password</label> <input name="current-password" id="current-password-disable" class="form-control" type="password" placeholder="Current Password"> </div> <div class="form-group"> <button id="disable-account-button" class="btn btn-danger" type="submit">Disable Account</button> </div> </form> </div> </div> </div> </div> </div> </div>
package com.voxelgameslib.voxelgameslib.api.feature.features; import com.google.gson.annotations.Expose; import java.util.Arrays; import javax.annotation.Nonnull; import com.voxelgameslib.voxelgameslib.api.event.GameEvent; import com.voxelgameslib.voxelgameslib.api.feature.AbstractFeature; import com.voxelgameslib.voxelgameslib.api.feature.FeatureInfo; import org.bukkit.Material; import org.bukkit.event.block.BlockBreakEvent; @FeatureInfo(name = "NoBlockBreakFeature", author = "MiniDigger", version = "1.0", description = "Small feature that blocks block breaking if active") public class NoBlockBreakFeature extends AbstractFeature { @Expose private Material[] whitelist = new Material[0]; @Expose private Material[] blacklist = new Material[0]; /** * Sets the list with whitelisted materials. Enabling the whitelist means that ppl are allowed to break only * materials which are on the whitelist. to disabled the whitelist, pass an empty array. * * @param whitelist the new whitelist */ public void setWhitelist(@Nonnull Material[] whitelist) { this.whitelist = whitelist; } /** * Sets the list with blacklisted materials. Enabling the blacklist means that ppl are allowed to break every * material other than those on the blacklist. to disabled the blacklist, pass an empty array * * @param blacklist the new blacklist */ public void setBlacklist(@Nonnull Material[] blacklist) { this.blacklist = blacklist; } @SuppressWarnings({"JavaDoc", "Duplicates"}) @GameEvent public void onBlockBreak(@Nonnull BlockBreakEvent event) { if (blacklist.length != 0) { if (Arrays.stream(blacklist).anyMatch(m -> m.equals(event.getBlock().getType()))) { event.setCancelled(true); } } else if (whitelist.length != 0) { if (Arrays.stream(whitelist).noneMatch(m -> m.equals(event.getBlock().getType()))) { event.setCancelled(true); } } else { event.setCancelled(true); } } }
<?php class Gestor_Tiendas_Model extends CI_Model { private $fileName; private $xmlProductos; public function __construct() { parent::__construct(); } /** * Carga los datos de la tienda seleccionada * @param type $nombreTienda */ public function Load($nombreTienda) { // Guardaremos la información en un fichero en formato JSON $this->fileName=__DIR__.'/'.$nombreTienda.'.xml'; $this->xmlProductos= new SimpleXMLElement(file_get_contents($this->fileName)); } public function Total() { return count($this->xmlProductos); } /** * Devuelve la lista de productos, desde la posición indicada * @param type $offset Desplazamiento desde el inicio * @param type $limit Nº de productos a devolver * @return type */ public function Lista($offset, $limit) { $offset=(int)$offset; $limit=(int) $limit; $listaProductosDevolver=array(); for($idx=$offset; $idx<count($this->xmlProductos) && $idx-$offset<$limit; $idx++) { $producto=$this->xmlProductos->producto[$idx]; $listaProductosDevolver[]=array( 'nombre'=>(string) $producto->nombre, 'descripcion'=>(string) $producto->descripcion, 'precio'=>(string) $producto->precio, 'img'=>(string) $producto->img, 'url'=>site_url('service/tienda01/producto/'. (string) $producto->id) ); } // foreach($this->xmlProductos->producto as $p) // { // $listaProductosDevolver[]=array( // 'nombre'=>(string) $p->nombre, // 'descripcion'=>(string) $p->descripcion, // 'precio'=>(string) $p->precio, // 'img'=>(string) $p->img, // 'url'=>site_url('service/tienda01/'. (string) $p->id) // ); // } return $listaProductosDevolver; //$listaProductosDevolver; } }
/** Create by Huy: codocmm@gmail.com ~ nqhuy2k6@gmail.com 07/31/2015 */ define(["durandal/app", "knockout", "bootstrap", "viewmodels/component-4"], function (app, ko, bootstrap, Component4) { return function () { var me = this; var dashboardViewModel = this; dashboardViewModel.compoment4 = ko.observable(); dashboardViewModel.activate = function () { me.compoment4(new Component4(0)) } } });
@font-face { font-family: "Material Icons"; font-style: normal; font-weight: 400; src: local("Material Icons"), local("MaterialIcons-Regular"), url(/static/fonts/MaterialIcons-Regular.woff2) format('woff2'), url(/static/fonts/MaterialIcons-Regular.woff) format('woff'), url(/static/fonts/MaterialIcons-Regular.ttf) format('truetype'); } .material-icons { display: inline-block; font: normal normal 24px/24px "Material Icons"; text-transform: none; letter-spacing: normal; word-wrap: normal; white-space: nowrap; direction: ltr; /* Support for all WebKit browsers. */ -webkit-font-smoothing: antialiased; /* Support for Safari and Chrome. */ text-rendering: optimizeLegibility; /* Support for Firefox. */ -moz-osx-font-smoothing: grayscale; /* Support for IE. */ font-feature-settings: "liga"; }
extern int js_add(int, int); int add(int a, int b) { return js_add(a, b); }
module Instructions where import Text.ParserCombinators.Parsec import Control.Applicative hiding (many, (<|>)) type Coordinate = (Integer, Integer) type Region = (Coordinate, Coordinate) data Instruction = Instruction Task Region deriving (Show) data Task = TurnOn | Toggle | TurnOff deriving (Show) instructions = many instruction <* eof instruction :: GenParser Char st Instruction instruction = Instruction <$> task <* space <*> region <* eol task = try (TurnOn <$ string "turn on") <|> try (TurnOff <$ string "turn off") <|> (Toggle <$ string "toggle") region = (,) <$> coord <* string " through " <*> coord coord = (,) <$> integer <* char ',' <*> integer integer = rd <$> many1 digit where rd = read :: String -> Integer eol = (char '\n' <|> (char '\r' >> option '\n' (char '\n'))) >> return ()
# DAY19 ## 20171109 # TIL ## #1. 2차원 배열 - 배열안에 배열이 들어있는 것으로, 2차원, 3차원까지 주로 사용한다. ```javascript var arr = []; arr.push([1,2,3]); arr.push([4,5,6]); ``` - 배열 주소의 의미 : arr[0] = [arr의 주소 + 0번째]를 읽으라는 의미이다. - n*m행렬에서 a(ij) = m * i + j로 표현할 수 있다. - 2차원 배열의 순회 n * m ```javascript var arr = [[1,2,3],[4,5,6]]; for (var i = 0; i < arr.length; i++) { for (var j = 0; j < arr[i].length; j++) { console.log(arr[i][j]); } } for (var i = 0; i < 6; i++) { console.log(); } ``` # My Coding ## 연습문제#1 - 5 * 10배열에 1부터 50까지 채우세요 루프는 두 개 사용할 것. push사용하지말 것. ```javascript var arr = []; for (var i = 0; i < 5; i++) { arr[i] = []; for (var j = 0; j < 10; j++) { arr[i][j] = i * 10 + (j + 1); } } console.log(arr); ``` - 위 배열을 1차원 행렬로 바꾸기. ```javascript var arr2 = []; for (var i = 0; i < 5; i++) { for (var j = 0; j < 10; j++) { arr2[i * 10 + j] = arr[i][j]; } } console.log("arr2 : " + arr2); ``` ## 연습문제#2 - 특정 원소의 주변값 읽기 - 2차원 배열과 값을 인자로 입력받아서 해당 값이 존재하면, 상하좌우값을 출력하는 함수를 구현! - (1) 배열에 값이 있는지 검색, (2) 값이 없으면 리턴 (3) 값이 있다면 위쪽 값 검색 (4)좌,우,하 검색 및 출력 ```javascript var norarr = []; var mkNum = function() { return Math.floor(Math.random() * 1000 + 1); }; var mkArr = function() { var temp = []; for (var i = 0; i < 4; i++) { temp[i] = []; for (var j = 0; j < 4; j++) { temp[i][j] = mkNum(); } } return temp; }; var findNum = function(val, arr) { for (var i = 0; i < 4; i++) { for (var j = 0; j < 4; j++) { if (val === arr[i][j]) { console.log("찾는 값 : " + val + "이 있습니다!"); if (!!arr[i - 1][j]) { //위 console.log("찾으려는 원소의 위 값 : " + arr[i - 1][j]); } if (!!arr[i][j - 1]) { //왼쪽 console.log("찾으려는 원소의 왼쪽 값 : " + arr[i][j - 1]); } if (!!arr[i][j + 1]) { //오른쪽 console.log("찾으려는 원소의 오른쪽 값 : " + arr[i][j + 1]); } if (!!arr[i + 1][j]) { //아래 console.log("찾으려는 원소의 아래 값 : " + arr[i + 1][j]); } return; } } } console.log("찾는 값이 없습니다."); }; norarr = mkArr(); console.log(norarr); ``` ## 연습문제#3 - 배열의 스왑 구현하기. ```javascript var arr = [[1,2,3],[4,5,6]]; var arraySwap = function(arr, x1, y1, x2, y2) { var temp; temp = arr[x1][y1]; arr[x1][y1] = arr[x2][y2]; arr[x2][y2] = temp; }; arraySwap(arr, 0, 1, 1, 1); console.log(arr); ``` ## 연습문제#4. - 2차원 배열의 원소 한 칸 옮기기 ```javascript //position : "left", "right", "up", "down" function arrayMove(arr, x1, y1, position) { if(position === "left" && y1 > 0) { arraySwap(arr, x1, y1, x1, y1 - 1); return true; } else if(position === "right" && y1 < 3) { arraySwap(arr, x1, y1, x1, y1 + 1); return true; } else if(position === "up" && x1 > 0) { arraySwap(arr, x1, y1, x1 - 1, y1); return true; } else if(position === "down" && x1 < 3) { arraySwap(arr, x1, y1, x1 + 1, y1); return true; } else { return false; } } ``` ## 연습문제#5. - x 주변의 값 찾기 : 4*4배열에 1부터 15까지 숫자와 x가 들어있을 때, x주변의 숫자를 return! ```javascript var arr = [[1,2,3,4],[5,6,7,8],['x',9,10,11],[12,13,14,15]]; var findNum = function(val, arr) { for (var i = 0; i < 4; i++) { for (var j = 0; j < 4; j++) { if (val === arr[i][j]) { console.log("찾는 값 : " + val + "이 있습니다!"); if (!!arr[i - 1][j]) { //위 console.log("찾으려는 원소의 위 값 : " + arr[i - 1][j]); } if (!!arr[i][j - 1]) { //왼쪽 console.log("찾으려는 원소의 왼쪽 값 : " + arr[i][j - 1]); } if (!!arr[i][j + 1]) { //오른쪽 console.log("찾으려는 원소의 오른쪽 값 : " + arr[i][j + 1]); } if (!!arr[i + 1][j]) { //아래 console.log("찾으려는 원소의 아래 값 : " + arr[i + 1][j]); } return; } } } console.log("찾는 값이 없습니다."); }; console.log(arr); findNum('x',arr); ``` ## 숫자퍼즐 구현하기. 1. html + js 만들기 ```html <div id = "puzzle"> <div><span id = "n00"> .....<\span> <span id = "n01"><\span> <\div> <div><span id "n10">...... <\span> <\div> <\div> ``` 2. css로 span을 적당히 키워줍니다. 3. js구현하기 - div에 버튼 이벤트 리스너 추가 - 어떤 span이 눌렸는지 체크 - 움직일 수 있다면, 스왑 - 반복 4. 추가 구현 - 섞기 : 무작위 스왑을 여러번 수행하는 것이 제일 좋다. - 움직인 횟수 체크 - 다 정리했으면 성공! 메세지 출력!
all: linux linux: main tresmeios rostorobo movimentos curvas help headers/debug.h g++ -o trabalho1compgraf_linux -fwhole-program -O2 -Wall -Wextra main.o tresmeios.o movimentos.o rostorobo.o curvas.o help.o -lglui -lglut -lGLU -lGL -lm #Compilação para Windows NAO FOI TESTADA pois nenhum dos membros utilizava ambiente Windows durante o desenvolvimento do projeto win: main tresmeios rostorobo movimentos curvas help headers/debug.h g++ -o trabalho1compgraf_win.exe -O2 -Wall -Wextra main.o tresmeios.o movimentos.o rostorobo.o curvas.o help.o -lglui32 -lglut32 -lglu32 -lopengl32 -lm main: src/main.c headers/main.h g++ -c -o main.o -O2 -Wall -Wextra src/main.c tresmeios: src/tresmeios.c headers/tresmeios.h g++ -c -o tresmeios.o -O2 -Wall -Wextra src/tresmeios.c rostorobo: src/rostorobo.c headers/rostorobo.h g++ -c -o movimentos.o -O2 -Wall -Wextra src/movimentos.c movimentos: src/movimentos.c headers/movimentos.h g++ -c -o rostorobo.o -O2 -Wall -Wextra src/rostorobo.c curvas: src/curvas.c headers/curvas.h g++ -c -o curvas.o -O2 -Wall -Wextra src/curvas.c help: src/help.c headers/help.h g++ -c -o help.o -O2 -Wall -Wextra src/help.c clean: rm trabalho1compgraf_linux rm main.o rm tresmeios.o rm movimentos.o rm rostorobo.o rm curvas.o rm help.o
/* ************************************************************************ Copyright (c) 2013 UBINITY SAS Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************* */ var ChromeapiPlugupCardTerminalFactory = Class.extend(CardTerminalFactory, { /** @lends ChromeapiPlugupCardTerminalFactory.prototype */ /** * @class Implementation of the {@link CardTerminalFactory} using the Chrome API for Plug-up Dongle * @constructs * @augments CardTerminalFactory */ initialize: function(pid, usagePage, ledgerTransport, vid) { this.pid = pid; this.vid = vid; this.usagePage = usagePage; this.ledgerTransport = ledgerTransport; }, list_async: function(pid, usagePage) { if (typeof chromeDevice == "undefined") { throw "Content script is not available"; } return chromeDevice.enumerateDongles_async(this.pid, this.usagePage, this.vid) .then(function(result) { return result.deviceList; }); }, waitInserted: function() { throw "Not implemented" }, getCardTerminal: function(device) { return new ChromeapiPlugupCardTerminal(device, undefined, this.ledgerTransport); } });
using System; namespace work.bacome.imapclient { public partial class cIMAPClient { private partial class cSession { public enum eGreetingType { ok, preauth, bye } public struct sGreeting { public readonly eGreetingType Type; public readonly cResponseText ResponseText; public sGreeting(eGreetingType pType, cResponseText pResponseText) { Type = pType; ResponseText = pResponseText; } } } } }
# Module Smith ![](https://i.cloudup.com/YjjosQY66o-3000x3000.png) A simple extensible `npm` build bot that works on Linux, SmartOS, and Windows. ## Example Given a small script for building a specific module: ``` js var assert = require('assert'), tmp = require('tmp'), ModuleSmith = require('module-smith'); var buildbot = ModuleSmith.createModuleSmith(); // // Grab a temporary directory to build in // tmp.dir(function (err, tmpdir) { assert.ifError(err); // // Start our build // buildbot.build({ repository: { type: 'git', url: 'git@github.com:bmeck/bcrypt-example.git' }, directories: { root: tmpdir } }, function (err, stream) { assert.ifError(err); // // Pipe out the data to stdio // stream.pipe(process.stdout); }); }); ``` We can dump it to a file via: ```bash node build.js > built.tgz ``` ## API ### ModuleSmith.createModuleSmith(options) * `Array` _options.versions_: List of the versions supported with absolute version numbers like ie. '0.8.12' * `BuildDescription` _options.defaults_: The defaults for a build run using this ModuleSmith. ### ModuleSmith.build(buildDescription, callback(err, tgzStream)) Runs a build ### BuildDescription ``` js { uid: 'nobody', gid: 'nobody', command: 'install', env: { 'npm_config_registry': 'http://registry.npmjs.org', 'npm_config_nodedir': path.join(process.env.HOME, '.node-gyp') }, repository: { type: 'git', url: 'git@github.com:bmeck/bcrypt-example.git' }, directories: { root: '/path/to/build/output/root' } } ``` A build description enumerates a number of values #### BuildDescription.command The `npm` command that you wish to execute for the build. Can be: * `install`: Installs all module dependencies. * `build`: Runs `node-gyp` to build any binary dependencies. #### BuildDescription.env Optional environmental variables to spawn `npm` with. Some interesting fields are: * npm_config_registry - registry to download from * npm_config_nodedir - location of node-gyp's include directory #### BuildDescription.uid = 'nobody' Optional user to spawn `npm` as. #### BuildDescription.gid = undefined Optional group to spawn `npm` under. #### BuildDescription.package Optional package.json overrides. Can be extended easily from the repository during `npm.configure`. Some interesting fields are: * engines.node - version to spawn as #### BuildDescription.repository A `checkout` npm module repository to download before building. #### BuildDescription.directories.root The place to use for creating the build. ## Understudy Actions Extensibility for complex actions can be done via Understudy based actions, only `before` actions are supported. * build.configure (buildDescription) * npm.configure (buildDescription) * npm.package (buildDescription, package) * build.output (buildDescription, tgzStream) ## Events Notifications of actions that have been completed are available via the EventEmitter APIs. * npm.spawned (buildDescription, npmProcess) <hr> #### Copyright (C) Charlie Robbins, Bradley Meck and the Contributors #### Authors: [Bradley Meck](https://github.com/bmeck), [Charlie Robbins](https://github.com/indexzero) #### License: MIT _Hammer Icon by Edward Boatman from The Noun Project_
# Rails 3.2 Integration for Redactor (Devise Edition) and for ActiveAdmin! # Only for AciveAdmin The redactor-rails gem integrates the [Redactor](http://redactorjs.com/) editor with the Rails 3.2 asset pipeline. This gem bundles Redactor version 8.2.2 which is the most recent version as of January 20, 2013. Check [Redactor's changelog](http://imperavi.com/redactor/log/) for further updates. ## Installation Add this line to your application's Gemfile: gem 'redactor-rails', :git => 'git://github.com/eddiefisher/redactor-rails.git' And then execute: $ bundle install ### Now generate models for store uploading files #### ActiveRecord + carrierwave gem "carrierwave" gem "mini_magick" $ rails generate redactor:install or $ rails generate redactor:install --devise # --devise option generate user_id attribute for asset(Picture, Document) models. For more details show Devise gem. # Now, Pictures and Documents uploading available only for signed in users # All uploaded files will stored with current user_id # User will choose only own uploaded Pictures and Documents $ rake db:migrate #### Mongoid + carrierwave gem "carrierwave" gem "carrierwave-mongoid", :require => "carrierwave/mongoid" gem "mini_magick" $ rails generate redactor:install ### Include the Redactor assets Add to your `application.js`: //= require redactor-rails Add to your `application.css`: *= require redactor-rails ### Initialize Redactor For each textarea that you want to use with Redactor, add the "redactor" class and ensure it has a unique ID: <%= text_area_tag :editor, "", :class => "redactor", :rows => 40, :cols => 120 %> ### Custom Your redactor If you need change some config in redactor, you can $ rails generate redactor:config Then generate `app\assets\redactor-rails\config.js`. See the [Redactor Documentation](http://redactorjs.com/docs/settings/) for a full list of configuration options. If You Want To setup a new language in Redactor you should do two things: In you file `app\assets\redactor-rails\config.js` set option "lang":'zh_tw' and Add to your layout <%= redactor_lang('zh_tw') %> ## Contributing 1. Fork it 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Added some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request ## Special Thanks [wildjcrt (Jerry Lee)](https://github.com/wildjcrt/) ## Statement `redactor-rails` part of reference [galetahub/ckeditor](https://github.com/galetahub/ckeditor) project. `redactor-rails` uses MIT-LICENSE. Rock!!!!! ## License the `redactor-rails` project is MIT-LICENSE. You may use `Redactor` for non-commercial websites for free, however, we do not guarantee any technical support. Redactor has [3 different licenses](http://redactorjs.com/download/) for commercial use. For details please see [License Agreement](http://redactorjs.com/download/).
#ifndef TECH_UI_WINDOWSYSTEM_H #define TECH_UI_WINDOWSYSTEM_H #include <tech/pimpl.h> #include <tech/string.h> #include <tech/types.h> #include <tech/ui/rect.h> #include <tech/ui/timer.h> #include <tech/ui/widget.h> namespace Tech { class WindowSystemPrivate; class WindowSystem final : public Interface<WindowSystemPrivate> { public: static WindowSystem* instance(); void processEvents(); void stopEventProcessing(); void sync(); Widget::Handle createWindow(Widget* widget, Widget::Handle parent = Widget::kInvalidHandle); void destroyWindow(Widget::Handle handle); Widget* findWindow(Widget::Handle handle) const; void setWindowSizeLimits(Widget::Handle handle, const Size<int>& minSize, const Size<int>& maxSize); void moveWindow(Widget::Handle handle, const Point<int>& pos); void resizeWindow(Widget::Handle handle, const Size<int>& size); void setWindowVisible(Widget::Handle handle, bool visible); void setWindowFrameless(Widget::Handle handle, bool enabled); void setWindowTaskbarButton(Widget::Handle handle, bool enabled); void setWindowTitle(Widget::Handle handle, const String& title); void repaintWindow(Widget::Handle handle, const Rect<int>& rect); void enqueueWidgetRepaint(Widget* widget); void enqueueWidgetDeletion(Widget* widget); Timer::Handle createTimer(Timer* timer); void destroyTimer(Timer::Handle handle); void startTimer(Timer::Handle handle, Duration timeout, bool periodic); void stopTimer(Timer::Handle handle); bool isTimerActive(Timer::Handle handle) const; Duration timerInterval(Timer::Handle handle) const; private: WindowSystem(); }; } // namespace Tech #endif // TECH_UI_WINDOWSYSTEM_H
import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import org.junit.*; public class ScoreCollectionTest { @Test public void answersArithmeticMeanOfTwoNumbers() { // arrange ScoreCollection collection = new ScoreCollection(); collection.add(() -> 5); collection.add(() -> 7); // act int actualResult = collection.arithmeticMean(); // assert assertThat(actualResult, equalTo(6)); } }
export { Button, ButtonFactory } from './Button';
clean-obj ========= Clean objects recursively, deleting undefined & null or falsy properties. ## Installation ```bash npm i clean-obj --save ``` ## Usage `cleanObj(obj [,strict])` The usage of this module is very straightforward, as you can see in the example below. ```javascript var cleanObj = require('clean-obj') var obj = { key: 'value', undf: undefined, nullz: null, falsy: 0, bool: false } cleanObj(obj) // { set: 'value', falsy: 0, bool: false } cleanObj(obj, true) // { set: 'value' } ``` ## License MIT
namespace System.Text.RegularExpressions { using System; using System.Globalization; internal sealed class RegexFC { internal bool _caseInsensitive; internal RegexCharClass _cc; internal bool _nullable; internal RegexFC(bool nullable) { this._cc = new RegexCharClass(); this._nullable = nullable; } internal RegexFC(string set, bool nullable, bool caseInsensitive) { this._cc = new RegexCharClass(); this._cc.AddSet(set); this._nullable = nullable; this._caseInsensitive = caseInsensitive; } internal RegexFC(char ch, bool not, bool nullable, bool caseInsensitive) { this._cc = new RegexCharClass(); if (not) { if (ch > '\0') { this._cc.AddRange('\0', (char) (ch - '\x0001')); } if (ch < 0xffff) { this._cc.AddRange((char) (ch + '\x0001'), (char)0xffff); } } else { this._cc.AddRange(ch, ch); } this._caseInsensitive = caseInsensitive; this._nullable = nullable; } internal void AddFC(RegexFC fc, bool concatenate) { if (concatenate) { if (!this._nullable) { return; } if (!fc._nullable) { this._nullable = false; } } else if (fc._nullable) { this._nullable = true; } this._caseInsensitive |= fc._caseInsensitive; this._cc.AddCharClass(fc._cc); } internal string GetFirstChars(CultureInfo culture) { return this._cc.ToSetCi(this._caseInsensitive, culture); } internal bool IsCaseInsensitive() { return this._caseInsensitive; } } }
@setlocal @ECHO off SET CONFIGURATION=Release SET CMDHOME=%~dp0 @REM Remove trailing backslash \ set CMDHOME=%CMDHOME:~0,-1% pushd "%CMDHOME%" @cd SET OutDir=%CMDHOME%\..\Binaries\%CONFIGURATION% set TESTS=%OutDir%\Tester.dll %OutDir%\TesterInternal.dll if []==[%TEST_FILTERS%] set TEST_FILTERS=-trait "Category=BVT" @Echo Test assemblies = %TESTS% @Echo Test filters = %TEST_FILTERS% @echo on call "%CMDHOME%\SetupTestScript.cmd" "%OutDir%" packages\xunit.runner.console.2.1.0\tools\xunit.console %TESTS% %TEST_FILTERS% -xml "%OutDir%/xUnit-Results.xml" -parallel none -noshadow set testresult=%errorlevel% popd endlocal&set testresult=%testresult% exit /B %testresult%
'use strict'; /** * Created by Alex Levshin on 26/11/16. */ var RootFolder = process.env.ROOT_FOLDER; if (!global.rootRequire) { global.rootRequire = function (name) { return require(RootFolder + '/' + name); }; } var restify = require('restify'); var _ = require('lodash'); var fs = require('fs'); var expect = require('chai').expect; var ApiPrefix = '/api/v1'; var Promise = require('promise'); var config = rootRequire('config'); var util = require('util'); var WorktyRepositoryCodePath = RootFolder + '/workties-repository'; var SubVersion = config.restapi.getLatestVersion().sub; // YYYY.M.D // Init the test client using supervisor account (all acl permissions) var adminClient = restify.createJsonClient({ version: SubVersion, url: config.restapi.getConnectionString(), headers: { 'Authorization': config.supervisor.getAuthorizationBasic() // supervisor }, rejectUnauthorized: false }); describe('Workflow Rest API', function () { var WorkflowsPerPage = 3; var Workflows = []; var WorktiesPerPage = 2; var Workties = []; var WorktiesInstances = []; var WORKTIES_FILENAMES = ['unsorted/nodejs/unit-tests/without-delay.zip']; console.log('Run Workflow API tests for version ' + ApiPrefix + '/' + SubVersion); function _createPromises(callback, count) { var promises = []; for (var idx = 0; idx < count; idx++) { promises.push(callback(idx)); } return promises; } function _createWorkty(idx) { return new Promise(function (resolve, reject) { try { var compressedCode = fs.readFileSync(WorktyRepositoryCodePath + '/' + WORKTIES_FILENAMES[0]); adminClient.post(ApiPrefix + '/workties', { name: 'myworkty' + idx, desc: 'worktydesc' + idx, compressedCode: compressedCode, template: true }, function (err, req, res, data) { var workty = data; adminClient.post(ApiPrefix + '/workties/' + data._id + '/properties', { property: { name: 'PropertyName', value: 'PropertyValue' } }, function (err, req, res, data) { workty.propertiesIds = [data]; resolve({res: res, data: workty}); }); }); } catch (ex) { reject(ex); } }); } function _createWorkflow(idx) { return new Promise(function (resolve, reject) { try { adminClient.post(ApiPrefix + '/workflows', { name: 'myworkflow' + idx, desc: 'workflowdesc' + idx }, function (err, req, res, data) { resolve({res: res, data: data}); }); } catch (ex) { reject(ex); } }); } function _createWorktyInstance(idx) { return new Promise(function (resolve, reject) { try { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances', { name: 'worktyinstance' + idx, desc: 'worktyinstance' + idx, worktyId: Workties[idx]._id, embed: 'properties' }, function (err, req, res, data) { resolve({res: res, data: data}); }); } catch (ex) { reject(ex); } }); } // Delete workflows and workties function _deleteWorkty(idx) { return new Promise(function (resolve, reject) { try { adminClient.del(ApiPrefix + '/workties/' + Workties[idx]._id, function (err, req, res, data) { resolve({res: res}); }); } catch (ex) { reject(ex); } }); } function _deleteWorkflow(idx) { return new Promise(function (resolve, reject) { try { adminClient.del(ApiPrefix + '/workflows/' + Workflows[idx]._id, function (err, req, res, data) { resolve({res: res}); }); } catch (ex) { reject(ex); } }); } // Run once before the first test case before(function (done) { Promise.all(_createPromises(_createWorkty, WorktiesPerPage)).then(function (results) { // Create workties for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; var data = results[idx].data; expect(res.statusCode).to.equals(201); expect(data).to.not.be.empty; Workties.push(data); } return Promise.all(_createPromises(_createWorkflow, WorkflowsPerPage)); }).then(function (results) { // Create workflows for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; var data = results[idx].data; expect(res.statusCode).to.equals(201); expect(data).to.not.be.empty; Workflows.push(data); } return Promise.all(_createPromises(_createWorktyInstance, WorktiesPerPage)); }).then(function (results) { // Create workties instances for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; var data = results[idx].data; expect(res.statusCode).to.equals(201); expect(data).to.not.be.empty; WorktiesInstances.push(data); } }).done(function (err) { expect(err).to.be.undefined; done(); }); }); // Run once after the last test case after(function (done) { Promise.all(_createPromises(_deleteWorkty, WorktiesPerPage)).then(function (results) { // Delete workties for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; expect(res.statusCode).to.equals(204); } return Promise.all(_createPromises(_deleteWorkflow, WorkflowsPerPage)); }).then(function (results) { // Delete workflows for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; expect(res.statusCode).to.equals(204); } }).done(function (err) { expect(err).to.be.undefined; done(); }); }); describe('.getAll()', function () { it('should get a 200 response', function (done) { adminClient.get(ApiPrefix + '/workflows', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length.above(1); done(); }); }); it('should get 3', function (done) { adminClient.get(ApiPrefix + '/workflows?page_num=1&per_page=3', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(3); done(); }); }); it('should get 2', function (done) { adminClient.get(ApiPrefix + '/workflows?per_page=2', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(2); done(); }); }); it('should get records-count', function (done) { adminClient.get(ApiPrefix + '/workflows?per_page=3&count=true', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(3); expect(res.headers).to.contain.keys('records-count'); expect(res.headers['records-count']).equals('3'); done(); }); }); it('should get sorted', function (done) { adminClient.get(ApiPrefix + '/workflows?per_page=3&sort=_id', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(3); expect(data).to.satisfy(function (workflows) { var currentValue = null; _.each(workflows, function (workflow) { if (!currentValue) { currentValue = workflow._id; } else { if (workflow._id <= currentValue) expect(true).to.be.false(); currentValue = workflow._id; } }); return true; }); done(); }); }); it('should get fields', function (done) { adminClient.get(ApiPrefix + '/workflows?per_page=3&fields=_id,name,desc', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(3); expect(data).to.satisfy(function (workflows) { _.each(workflows, function (workflow) { expect(workflow).to.have.keys(['_id', 'name', 'desc']); }); return true; }); done(); }); }); it('should get embed fields', function (done) { adminClient.get(ApiPrefix + '/workflows?per_page=3&embed=worktiesInstances,account', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(3); expect(data).to.satisfy(function (workflows) { _.each(workflows, function (workflow) { expect(workflow).to.contain.keys('accountId', 'worktiesInstancesIds'); expect(workflow.accountId).to.contain.keys('_id'); if (workflow.worktiesInstancesIds.length > 0) { expect(workflow.worktiesInstancesIds[0]).to.contain.keys('_id'); } }); return true; }); done(); }); }); }); describe('.getById()', function () { it('should get a 200 response', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; done(); }); }); it('should get a 500 response not found', function (done) { adminClient.get(ApiPrefix + '/workflows/' + 'N', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.not.be.empty; expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.equals(1); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); it('should get records-count', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '?count=true', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(res.headers).to.contain.keys('records-count'); expect(res.headers['records-count']).equals('1'); done(); }); }); it('should get fields', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '?fields=_id,name,desc', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data).to.have.keys(['_id', 'name', 'desc']); done(); }); }); it('should get embed fields', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '?embed=worktiesInstances,account', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data).to.contain.keys('accountId', 'worktiesInstancesIds'); expect(data.accountId).to.contain.keys('_id'); if (data.worktiesInstancesIds.length > 0) { expect(data.worktiesInstancesIds[0]).to.contain.keys('_id'); } done(); }); }); }); describe('.add()', function () { it('should get a 409 response', function (done) { adminClient.post(ApiPrefix + '/workflows', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(409); var error = JSON.parse(err.message).error; expect(error.message).to.equals("Validation Error"); expect(error.errors).to.have.length(1); expect(error.errors[0].message).to.equals("Path `name` is required."); done(); }); }); it('should get a 201 response', function (done) { // Create workflow adminClient.post(ApiPrefix + '/workflows', { name: 'mytestworkflow', desc: 'testworkflow' }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var workflowId = data._id; expect(res.headers.location).to.have.string('/' + workflowId); expect(data.name).to.be.equal('mytestworkflow'); expect(data.desc).to.be.equal('testworkflow'); // Delete workflow adminClient.del(res.headers.location, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(204); done(); }); }); }); }); describe('.update()', function () { it('should get a 400 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(400); var error = JSON.parse(err.message).error; expect(error.errors).is.empty; done(); }); }); it('should get a 409 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id, {name: ''}, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(409); var error = JSON.parse(err.message).error; expect(error.errors).to.have.length(1); expect(error.errors[0].message).to.equals("Path `name` is required."); done(); }); }); it('should get a 200 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id, { name: 'mytestworkflow', desc: 'testworkflow' }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.null; var workflowId = data._id; expect(workflowId).to.equals(Workflows[0]._id); expect(data.name).to.be.equal('mytestworkflow'); expect(data.desc).to.be.equal('testworkflow'); done(); }); }); }); describe('.del()', function () { it('should get a 500 response not found', function (done) { // Delete workflow adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + 'N', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); done(); }); }); it('should get a 204 response', function (done) { // Create workflow adminClient.post(ApiPrefix + '/workflows', { name: 'mytestworkflow', desc: 'testworkflow' }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var workflowId = data._id; expect(res.headers.location).to.have.string('/' + workflowId); // Delete workflow adminClient.del(ApiPrefix + '/workflows/' + workflowId, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); }); describe('.run()', function () { it('should get a 200 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; done(); }); }); it('should get a 500 response not found', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + 'N' + '/running', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.not.be.empty; expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.be.equals(1); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); describe('multiple workflows', function () { var WorkflowExtraPerPage = 2; var WorkflowExtraIds = []; function _deleteExtraWorkflow(idx) { return new Promise(function (resolve, reject) { try { adminClient.del(ApiPrefix + '/workflows/' + WorkflowExtraIds[idx], function (err, req, res, data) { resolve({res: res}); }); } catch (ex) { reject(ex); } }); } // Run once before the first test case before(function (done) { Promise.all(_createPromises(_createWorkflow, WorkflowExtraPerPage)).then(function (results) { // Create workflows for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; var data = results[idx].data; expect(res.statusCode).to.equals(201); expect(data).to.not.be.empty; WorkflowExtraIds.push(data._id); } }).done(function (err) { expect(err).to.be.undefined; done(); }); }); // Run once after the last test case after(function (done) { Promise.all(_createPromises(_deleteExtraWorkflow, WorkflowExtraPerPage)).then(function (results) { // Delete workflows for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; expect(res.statusCode).to.equals(204); } }).done(function (err) { expect(err).to.be.undefined; done(); }); }); }); }); describe('.stop()', function () { it('should get a 200 response', function (done) { // Run workflow adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); done(); }); }); it('should get a 500 response not found', function (done) { adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + 'N' + '/running', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.not.be.empty; expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.be.equals(1); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); it('should get a 200 response after two stops', function (done) { // Run workflow adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; // Stop workflow twice adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); done(); }); }); }); }); }); describe('.resume()', function () { it('should get a 200 response', function (done) { // Resume workflow adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; done(); }); }); it('should get a 500 response not found', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + 'N' + '/running', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.not.be.empty; expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.be.equals(1); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); }); describe('Workties instances', function () { describe('.getAllWorktiesInstances()', function () { it('should get a 200 response', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length.above(0); expect(data[0].workflowId).to.equals(Workflows[0]._id); done(); }); }); it('should get 2', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?per_page=2', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(2); done(); }); }); it('should get records-count', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?per_page=2&count=true', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(2); expect(res.headers).to.contain.keys('records-count'); expect(res.headers['records-count']).equals('2'); done(); }); }); it('should get fields', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?per_page=2&fields=_id,desc,created', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(2); expect(data).to.satisfy(function (workflowInstances) { _.each(workflowInstances, function (workflowInstance) { expect(workflowInstance).to.have.keys(['_id', 'desc', 'created']); }); return true; }); done(); }); }); it('should get embed fields', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?per_page=2&embed=workflow,state', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(2); expect(data).to.satisfy(function (workflowInstances) { _.each(workflowInstances, function (workflowInstance) { expect(workflowInstance).to.contain.keys('stateId', 'workflowId'); expect(workflowInstance.workflowId).to.contain.keys('_id'); if (workflowInstance.stateId.length > 0) { expect(workflowInstance.stateId[0]).to.contain.keys('_id'); } }); return true; }); done(); }); }); }); describe('.getWorktyInstanceById()', function () { it('should get a 200 response', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; done(); }); }); it('should get a 500 response not found', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + 'N', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.not.be.empty; expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.equals(1); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); it('should get records-count', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + '?count=true', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(res.headers).to.contain.keys('records-count'); expect(res.headers['records-count']).equals('1'); done(); }); }); it('should get fields', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + '?fields=_id,desc', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data).to.have.keys(['_id', 'desc']); done(); }); }); it('should get embed fields', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + '?embed=workflow,state', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data).to.contain.keys('stateId', 'workflowId'); expect(data.stateId).to.contain.keys('_id'); expect(data.workflowId).to.contain.keys('_id'); expect(data.workflowId._id).to.equals(Workflows[0]._id); done(); }); }); }); describe('.addWorktyInstance()', function () { it('should get a 201 response', function (done) { // Create workty instance adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances', { desc: 'descworktyinstance4', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; expect(data.worktyId).to.be.equal(Workties[0]._id); expect(data.desc).to.be.equal('descworktyinstance4'); // Delete workty instance adminClient.del(res.headers.location, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); it('should get a 500 response with code 12 position type is unknown', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_type=unknown', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.equals(12); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); it('should get a 201 response for position type is last', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_type=last', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var worktyInstanceId = data._id; expect(res.headers.location).to.have.string('worktiesInstances/' + worktyInstanceId); expect(data.desc).to.be.equal('testworkty'); var headerLocation = res.headers.location; // Get workflow to check workty instance added in last position adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data.worktiesInstancesIds).to.satisfy(function (worktiesInstancesIds) { if (worktiesInstancesIds.length !== 3) { return false; } return worktyInstanceId === worktiesInstancesIds[worktiesInstancesIds.length - 1]; }); // Delete workty instance adminClient.del(headerLocation, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); }); it('should get a 201 response for position type is first', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_type=first', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var worktyInstanceId = data._id; expect(res.headers.location).to.have.string('worktiesInstances/' + worktyInstanceId); expect(data.desc).to.be.equal('testworkty'); var headerLocation = res.headers.location; // Get workflow to check workty instance added in first position adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data.worktiesInstancesIds).to.satisfy(function (worktiesInstancesIds) { if (worktiesInstancesIds.length !== 3) { return false; } return worktyInstanceId === worktiesInstancesIds[0]; }); // Delete workty instance adminClient.del(headerLocation, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); }); it('should get a 201 response for position index is 0 among 4 values', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_index=0', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var worktyInstanceId = data._id; expect(res.headers.location).to.have.string('worktiesInstances/' + worktyInstanceId); expect(data.desc).to.be.equal('testworkty'); var headerLocation = res.headers.location; // Get workflow to check workty instance added by index 1 adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data.worktiesInstancesIds).to.satisfy(function (worktiesInstancesIds) { if (worktiesInstancesIds.length !== 3) { return false; } return _.indexOf(worktiesInstancesIds, worktyInstanceId) === 0; }); // Delete workty instance adminClient.del(headerLocation, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); }); it('should get a 500 response with code 10 for position index is -1', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_index=-1', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.equals(10); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); it('should get a 500 response with code 11 for missing position id', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_id=N', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.equals(11); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); it('should get a 201 response for position id', function (done) { // Insert workty by index 0 adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_index=0', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var worktyInstanceId = data._id; expect(res.headers.location).to.have.string('worktiesInstances/' + worktyInstanceId); expect(data.desc).to.be.equal('testworkty'); var headerLocationFirst = res.headers.location; // Get workflow to check workty instance added by index 1 adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data.worktiesInstancesIds).to.satisfy(function (worktiesInstancesIds) { if (worktiesInstancesIds.length !== 3) { return false; } return _.indexOf(worktiesInstancesIds, worktyInstanceId) === 0; }); // Insert workty instance before worktyInstanceId adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_id=' + worktyInstanceId, { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; worktyInstanceId = data._id; expect(res.headers.location).to.have.string('worktiesInstances/' + worktyInstanceId); expect(data.desc).to.be.equal('testworkty'); var headerLocation = res.headers.location; // Get workflow to check workty instance added by index 1 adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data.worktiesInstancesIds).to.satisfy(function (worktiesInstancesIds) { if (worktiesInstancesIds.length !== 4) { return false; } return _.indexOf(worktiesInstancesIds, worktyInstanceId) === 0; }); // Delete first workty instance adminClient.del(headerLocationFirst, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); // Delete second workty instance adminClient.del(headerLocation, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); }); }); }); }); it('should get a 500 response with code 1 for missing worktyId', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_index=-1', {desc: 'testworkty'}, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(409); expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'errors', 'inputParameters']); expect(data.error.code).is.empty; expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); }); describe('.updateWorktyInstance()', function () { it('should get a 400 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(400); var error = JSON.parse(err.message).error; expect(error.errors).is.empty; done(); }); }); it('should get a 200 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id, {desc: 'updateddesc'}, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.null; expect(data.desc).to.be.equal('updateddesc'); done(); }); }); }); describe('.delWorktyInstance()', function () { it('should get a 500 response not found', function (done) { // Delete workty instance adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + 'N', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); done(); }); }); it('should get a 204 response', function (done) { // Create workty instance adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var workflowId = data.workflowId; var worktyInstanceId = data._id; expect(res.headers.location).to.have.string('/' + workflowId); // Delete workty instance adminClient.del(ApiPrefix + '/workflows/' + workflowId + '/worktiesInstances/' + worktyInstanceId, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); }); describe('.updateWorktyInstanceProperty()', function () { it('should get a 400 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + '/properties/' + WorktiesInstances[0].propertiesIds[0]._id, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(400); var error = JSON.parse(err.message).error; expect(error.errors).is.empty; done(); }); }); it('should get a 200 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + '/properties/' + WorktiesInstances[0].propertiesIds[0]._id, { name: 'NewPropertyName', value: 'NewPropertyValue' }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data.name).to.be.equal('NewPropertyName'); expect(data.value).to.be.equal('NewPropertyValue'); done(); }); }); }); }); });
""" Test the Multinet Class. """ import multinet as mn import networkx as nx class TestMultinet(object): def test_build_multinet(self): """ Test building Multinet objects. """ mg = mn.Multinet() assert mg.is_directed() == False mg.add_edge(0, 1, 'L1') mg.add_edge(0, 1, 'L2') mg.add_edge(1, 0, 'L2') mg.add_edge(1, 2, 'L2') assert 'L1' in mg.layers() assert 'L2' in mg.layers() assert len(mg.edgelets) == 3 assert mg.number_of_nodes() == 3 assert mg.number_of_edges() == 2 assert mg.number_of_layers() == 2 assert mg.number_of_edgelets() == 3 # Remove non-existed edge. mg.remove_edgelet(2, 3, 'L3') mg.remove_edgelet(0, 1, 'L2') assert mg.number_of_nodes() == 3 assert mg.number_of_edges() == 2 assert mg.number_of_layers() == 2 assert mg.number_of_edgelets() == 2 mg.remove_edgelet(0, 1, 'L1') assert mg.number_of_nodes() == 3 assert mg.number_of_edges() == 1 assert mg.number_of_layers() == 2 assert mg.number_of_edgelets() == 1 assert len(mg.empty_layers()) == 1 mg.remove_empty_layers() assert mg.number_of_layers() == 1 def test_aggregate_edge(self): mg = mn.Multinet() mg.add_edge(0, 1, 'L1', weight=5) mg.add_edge(1, 2, 'L2', weight=6) assert mg[0][1][mg.cid]['L1'] == 5 assert mg[1][2][mg.cid]['L2'] == 6 mg.add_edge(0, 1, 'L1', weight=10) assert mg[0][1][mg.cid]['L1'] == 10 mg.aggregate_edge(0, 1, 'L1', weight=5) assert mg[0][1][mg.cid]['L1'] == 15 mg.aggregate_edge(2, 3, 'L2', weight=7) assert mg[2][3][mg.cid]['L2'] == 7 def test_sub_layer(self): mg = mn.Multinet() mg.add_edge(0, 1, 'L1', weight=5) mg.add_edge(1, 2, 'L2', weight=6) sg = mg.sub_layer('L1') assert type(sg) == nx.Graph assert sg.number_of_nodes() == 3 assert sg.number_of_edges() == 1 sg = mg.sub_layer('L2', remove_isolates=True) assert type(sg) == nx.Graph assert sg.number_of_nodes() == 2 assert sg.number_of_edges() == 1 def test_sub_layers(self): mg = mn.Multinet() mg.add_edge(0, 1, 'L1', weight=5) mg.add_edge(1, 2, 'L2', weight=6) mg.add_edge(1, 2, 'L3', weight=2) sg = mg.sub_layers(['L1', 'L2']) assert type(sg) == mn.Multinet assert sg.number_of_nodes() == 3 assert sg.number_of_edges() == 2 assert sg.number_of_layers() == 2 sg = mg.sub_layers(['L2', 'L3'], remove_isolates=True) assert type(sg) == mn.Multinet assert sg.number_of_nodes() == 2 assert sg.number_of_edges() == 1 assert sg.number_of_layers() == 2 def test_aggregated(self): mg = mn.Multinet() mg.add_edge(0, 1, 'L1', weight=5) mg.add_edge(1, 2, 'L2', weight=6) mg.add_edge(1, 2, 'L3', weight=2) ag = mg.aggregated() assert type(ag) == nx.Graph assert ag.number_of_nodes() == 3 assert ag.number_of_edges() == 2 assert ag[1][2]['weight'] == 8 assert ag[1][2]['nlayer'] == 2 def test_merge_layers(self): mg = mn.Multinet() mg.add_edge(0, 1, 'L1', weight=5) mg.add_edge(1, 2, 'L2', weight=6) mg.add_edge(1, 2, 'L3', weight=2) mg.merge_layers(['L1', 'L2']) assert 'L1' not in mg.layers() assert 'L2' not in mg.layers() assert 'L1_L2' in mg.layers() assert mg.number_of_layers() == 2 assert mg.number_of_nodes() == 3 assert mg.number_of_edges() == 2 assert mg[0][1][mg.cid]['L1_L2'] == 5 assert mg[1][2][mg.cid]['L1_L2'] == 6 mg = mn.Multinet() mg.add_edge(0, 1, 'L1', weight=5) mg.add_edge(1, 2, 'L2', weight=6) mg.add_edge(1, 2, 'L3', weight=2) mg.merge_layers(['L2', 'L3'], new_name='LN') assert 'L2' not in mg.layers() assert 'L3' not in mg.layers() assert 'LN' in mg.layers() assert mg.number_of_layers() == 2 assert mg.number_of_nodes() == 3 assert mg.number_of_edges() == 2 assert mg[0][1][mg.cid]['L1'] == 5 assert mg[1][2][mg.cid]['LN'] == 8 def test_add_layer(self): mg = mn.Multinet() mg.add_edge(0, 1, 'L1', weight=5) mg.add_edge(1, 2, 'L2', weight=6) sg = nx.Graph() sg.add_edge(1, 2, weight=7) sg.add_edge(2, 3) mg.add_layer(sg, 'L3') assert mg.number_of_nodes() == 4 assert mg.number_of_edges() == 3 assert mg.number_of_layers() == 3 assert mg[1][2][mg.cid]['L2'] == 6 assert mg[1][2][mg.cid]['L3'] == 7 assert mg[2][3][mg.cid]['L3'] == 1 def test_remove_layer(self): mg = mn.Multinet() mg.add_edge(0, 1, 'L1', weight=5) mg.add_edge(1, 2, 'L2', weight=6) mg.add_edge(1, 2, 'L3', weight=2) mg.remove_layer('L3') assert mg.number_of_nodes() == 3 assert mg.number_of_edges() == 2 assert mg.number_of_layers() == 2 mg = mn.Multinet() mg.add_edge(0, 1, 'L1', weight=5) mg.add_edge(1, 2, 'L2', weight=6) mg.add_edge(1, 2, 'L3', weight=2) mg.remove_layer('L1') assert mg.number_of_nodes() == 3 assert mg.number_of_edges() == 1 assert mg.number_of_layers() == 2 class TestDiMultinet(object): def test_build_dimultinet(self): """ Test building Multinet objects. """ mg = mn.DiMultinet() assert mg.is_directed() == True mg.add_edge(0, 1, 'L1') mg.add_edge(0, 1, 'L2') mg.add_edge(1, 0, 'L2') mg.add_edge(1, 2, 'L2') assert 'L1' in mg.layers() assert 'L2' in mg.layers() assert len(mg.edgelets) == 4 assert mg.number_of_nodes() == 3 assert mg.number_of_edges() == 3 assert mg.number_of_layers() == 2 assert mg.number_of_edgelets() == 4 # Remove non-existed edge. mg.remove_edgelet(2, 3, 'L3') mg.remove_edgelet(0, 1, 'L2') assert mg.number_of_nodes() == 3 assert mg.number_of_edges() == 3 assert mg.number_of_layers() == 2 assert mg.number_of_edgelets() == 3 mg.remove_edgelet(0, 1, 'L1') assert mg.number_of_nodes() == 3 assert mg.number_of_edges() == 2 assert mg.number_of_layers() == 2 assert mg.number_of_edgelets() == 2 assert len(mg.empty_layers()) == 1 mg.remove_empty_layers() assert mg.number_of_layers() == 1 def test_aggregate_edge(self): mg = mn.DiMultinet() mg.add_edge(0, 1, 'L1', weight=5) mg.add_edge(1, 2, 'L2', weight=6) assert mg[0][1][mg.cid]['L1'] == 5 assert mg[1][2][mg.cid]['L2'] == 6 mg.add_edge(0, 1, 'L1', weight=10) assert mg[0][1][mg.cid]['L1'] == 10 mg.aggregate_edge(0, 1, 'L1', weight=5) assert mg[0][1][mg.cid]['L1'] == 15 mg.aggregate_edge(2, 3, 'L2', weight=7) assert mg[2][3][mg.cid]['L2'] == 7 def test_sub_layer(self): mg = mn.DiMultinet() mg.add_edge(0, 1, 'L1', weight=5) mg.add_edge(1, 2, 'L2', weight=6) sg = mg.sub_layer('L1') assert type(sg) == nx.DiGraph assert sg.number_of_nodes() == 3 assert sg.number_of_edges() == 1 sg = mg.sub_layer('L2', remove_isolates=True) assert type(sg) == nx.DiGraph assert sg.number_of_nodes() == 2 assert sg.number_of_edges() == 1 def test_sub_layers(self): mg = mn.DiMultinet() mg.add_edge(0, 1, 'L1', weight=5) mg.add_edge(1, 2, 'L2', weight=6) mg.add_edge(1, 2, 'L3', weight=2) sg = mg.sub_layers(['L1', 'L2']) assert type(sg) == mn.DiMultinet assert sg.number_of_nodes() == 3 assert sg.number_of_edges() == 2 assert sg.number_of_layers() == 2 sg = mg.sub_layers(['L2', 'L3'], remove_isolates=True) assert type(sg) == mn.DiMultinet assert sg.number_of_nodes() == 2 assert sg.number_of_edges() == 1 assert sg.number_of_layers() == 2 def test_aggregated(self): mg = mn.DiMultinet() mg.add_edge(0, 1, 'L1', weight=5) mg.add_edge(1, 2, 'L2', weight=6) mg.add_edge(1, 2, 'L3', weight=2) ag = mg.aggregated() assert type(ag) == nx.DiGraph assert ag.number_of_nodes() == 3 assert ag.number_of_edges() == 2 assert ag[1][2]['weight'] == 8 assert ag[1][2]['nlayer'] == 2 def test_merge_layers(self): mg = mn.DiMultinet() mg.add_edge(0, 1, 'L1', weight=5) mg.add_edge(1, 2, 'L2', weight=6) mg.add_edge(1, 2, 'L3', weight=2) mg.merge_layers(['L1', 'L2']) assert 'L1' not in mg.layers() assert 'L2' not in mg.layers() assert 'L1_L2' in mg.layers() assert mg.number_of_layers() == 2 assert mg.number_of_nodes() == 3 assert mg.number_of_edges() == 2 assert mg[0][1][mg.cid]['L1_L2'] == 5 assert mg[1][2][mg.cid]['L1_L2'] == 6 mg = mn.DiMultinet() mg.add_edge(0, 1, 'L1', weight=5) mg.add_edge(1, 2, 'L2', weight=6) mg.add_edge(1, 2, 'L3', weight=2) mg.merge_layers(['L2', 'L3'], new_name='LN') assert 'L2' not in mg.layers() assert 'L3' not in mg.layers() assert 'LN' in mg.layers() assert mg.number_of_layers() == 2 assert mg.number_of_nodes() == 3 assert mg.number_of_edges() == 2 assert mg[0][1][mg.cid]['L1'] == 5 assert mg[1][2][mg.cid]['LN'] == 8 def test_add_layer(self): mg = mn.DiMultinet() mg.add_edge(0, 1, 'L1', weight=5) mg.add_edge(1, 2, 'L2', weight=6) sg = nx.Graph() sg.add_edge(1, 2, weight=7) sg.add_edge(2, 3) mg.add_layer(sg, 'L3') assert mg.number_of_nodes() == 4 assert mg.number_of_edges() == 3 assert mg.number_of_layers() == 3 assert mg[1][2][mg.cid]['L2'] == 6 assert mg[1][2][mg.cid]['L3'] == 7 assert mg[2][3][mg.cid]['L3'] == 1 def test_remove_layer(self): mg = mn.DiMultinet() mg.add_edge(0, 1, 'L1', weight=5) mg.add_edge(1, 2, 'L2', weight=6) mg.add_edge(1, 2, 'L3', weight=2) mg.remove_layer('L3') assert mg.number_of_nodes() == 3 assert mg.number_of_edges() == 2 assert mg.number_of_layers() == 2 mg = mn.DiMultinet() mg.add_edge(0, 1, 'L1', weight=5) mg.add_edge(1, 2, 'L2', weight=6) mg.add_edge(1, 2, 'L3', weight=2) mg.remove_layer('L1') assert mg.number_of_nodes() == 3 assert mg.number_of_edges() == 1 assert mg.number_of_layers() == 2 def test_to_undirected(self): mg = mn.DiMultinet() mg.add_edge(0, 1, 'L1', weight=5) mg.add_edge(1, 2, 'L2', weight=6) mg.add_edge(2, 1, 'L3', weight=2) assert mg.number_of_nodes() == 3 assert mg.number_of_edges() == 3 assert mg.number_of_layers() == 3 nmg = mg.to_undirected() assert nmg.number_of_nodes() == 3 assert nmg.number_of_edges() == 2 assert nmg.number_of_layers() == 3
using System; using System.Collections.Immutable; using System.IO; using System.Xml; using Xunit; namespace WarHub.ArmouryModel.Source.CodeGeneration.Tests { public class SerializationTests { [Fact] public void CheckEmptyDeserialization() { const string ContainerXml = "<container/>"; var serializer = new XmlFormat.ContainerCoreXmlSerializer(); using var reader = XmlReader.Create(new StringReader(ContainerXml)); var container = (ContainerCore)serializer.Deserialize(reader)!; Assert.Null(container.Id); Assert.Null(container.Name); Assert.Empty(container.Items); Assert.True(container.Items.IsEmpty); } [Fact] public void ContainerSerializesAndDeserializes() { var emptyGuid = Guid.Empty.ToString(); const string ContainerName = "Container0"; const string Item1Name = "Item1"; const string Item2Name = "Item2"; const string Item3Name = "Item3"; var profileType = new ContainerCore { Id = emptyGuid, Name = ContainerName, Items = ImmutableArray.Create( new ItemCore { Id = emptyGuid, Name = Item1Name }, new ItemCore { Id = emptyGuid, Name = Item2Name }, new ItemCore { Id = emptyGuid, Name = Item3Name }) }; var serializer = new XmlFormat.ContainerCoreXmlSerializer(); using var stream = new MemoryStream(); serializer.Serialize(stream, profileType); stream.Position = 0; using var reader = XmlReader.Create(stream); var deserialized = (ContainerCore)serializer.Deserialize(reader)!; Assert.NotNull(deserialized); Assert.Equal(ContainerName, deserialized.Name); Assert.Collection( deserialized.Items, x => Assert.Equal(Item1Name, x.Name), x => Assert.Equal(Item2Name, x.Name), x => Assert.Equal(Item3Name, x.Name)); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Xml.Linq; using System.Windows.Forms; namespace NetOffice.DeveloperToolbox.ToolboxControls.OfficeCompatibility { /// <summary> /// Shows a detailed usage report for an analyzed assembly /// </summary> [ResourceTable("ToolboxControls.OfficeCompatibility.Report.txt")] public partial class ReportControl : UserControl { #region Fields private AnalyzerResult _report; #endregion #region Construction /// <summary> /// Creates an instance of the class /// </summary> public ReportControl() { InitializeComponent(); pictureBoxField.Image = imageList1.Images[3]; pictureBoxProperty.Image = imageList1.Images[7]; pictureBoxMethod.Image = imageList1.Images[5]; } /// <summary> /// Creates an instance of the class /// </summary> /// <param name="report">detailed report</param> public ReportControl(AnalyzerResult report) { InitializeComponent(); if (null == report.Report) return; _report = report; comboBoxFilter.SelectedIndex = 0; pictureBoxField.Image = imageList1.Images[3]; pictureBoxProperty.Image = imageList1.Images[7]; pictureBoxMethod.Image = imageList1.Images[5]; if (treeViewReport.Nodes.Count > 0) treeViewReport.SelectedNode = treeViewReport.Nodes[0]; } #endregion #region Methods private int GetPercent(int value, int percent) { return value / 100 * percent; } private int GetImageClassIndex(XElement itemClass) { if (itemClass.Attribute("IsPublic").Value.Equals("true", StringComparison.InvariantCultureIgnoreCase)) return 1; else return 2; } private int GetImageFieldIndex(XElement itemField) { if (itemField.Attribute("IsPublic").Value.Equals("true", StringComparison.InvariantCultureIgnoreCase)) return 3; else return 4; } private int GetImageMethodIndex(XElement itemMethod) { if (itemMethod.Attribute("IsProperty").Value.Equals("true", StringComparison.InvariantCultureIgnoreCase)) { if (itemMethod.Attribute("IsPublic").Value.Equals("true", StringComparison.InvariantCultureIgnoreCase)) return 7; else return 8; } else { if (itemMethod.Attribute("IsPublic").Value.Equals("true", StringComparison.InvariantCultureIgnoreCase)) return 5; else return 6; } } private void ShowAssembly() { treeViewReport.Nodes.Clear(); foreach (XElement item in _report.Report.Document.Root.Elements("Assembly")) { string name = item.Attribute("Name").Value; if (name.IndexOf(",", StringComparison.InvariantCultureIgnoreCase) > 0) name = name.Substring(0, name.IndexOf(",", StringComparison.InvariantCultureIgnoreCase)); TreeNode node = treeViewReport.Nodes.Add(name); node.ImageIndex = 0; node.SelectedImageIndex = 0; node.Tag = item; foreach (XElement itemClass in item.Element("Classes").Elements("Class")) { TreeNode classNode = node.Nodes.Add(itemClass.Attribute("Name").Value); classNode.ImageIndex = GetImageClassIndex(itemClass); classNode.SelectedImageIndex = GetImageClassIndex(itemClass); classNode.Tag = itemClass; foreach (XElement itemField in itemClass.Element("Fields").Elements("Entity")) { if (FilterPassed(itemField.Element("SupportByLibrary"))) { TreeNode fieldNode = classNode.Nodes.Add(itemField.Attribute("Name").Value); fieldNode.ImageIndex = GetImageFieldIndex(itemField); fieldNode.SelectedImageIndex = GetImageFieldIndex(itemField); fieldNode.Tag = itemField; } } foreach (XElement itemMethod in itemClass.Element("Methods").Elements("Method")) { bool filterPassed = false; foreach (XElement itemFilterNode in itemMethod.Descendants("SupportByLibrary")) { if (FilterPassed(itemFilterNode)) { filterPassed = true; break; } } if (filterPassed) { string methodName = itemMethod.Attribute("Name").Value; if(methodName.StartsWith("get_")) { methodName = methodName.Substring(4); TreeNode methodNode = classNode.Nodes.Add(methodName, methodName); methodNode.ImageIndex = GetImageMethodIndex(itemMethod); methodNode.SelectedImageIndex = GetImageMethodIndex(itemMethod); methodNode.Tag = itemMethod; } else if( methodName.StartsWith("set_")) { methodName = methodName.Substring(4); List<XElement> list = new List<XElement>(); TreeNode getNode = classNode.Nodes[methodName]; list.Add(getNode.Tag as XElement); list.Add(itemMethod); getNode.Tag = list; } else { TreeNode methodNode = classNode.Nodes.Add(methodName); methodNode.ImageIndex = GetImageMethodIndex(itemMethod); methodNode.SelectedImageIndex = GetImageMethodIndex(itemMethod); methodNode.Tag = itemMethod; } } } } } panelView.Dock = DockStyle.Fill; panelNativeView.Dock = DockStyle.Fill; if (treeViewReport.Nodes.Count > 0) treeViewReport.Nodes[0].Expand(); } private void SetMethodCalls(XElement element) { XElement parametersNode = element.Element("Calls"); if ((null != parametersNode) && (parametersNode.Elements("Entity").Count() > 0)) { foreach (XElement item in parametersNode.Elements("Entity")) { string name = item.Attribute("Name").Value; if (name.IndexOf("::", StringComparison.InvariantCultureIgnoreCase) > -1) name = name.Substring(0,name.IndexOf("::", StringComparison.InvariantCultureIgnoreCase)); string type = item.Element("SupportByLibrary").Attribute("Name").Value; if (type.IndexOf("::", StringComparison.InvariantCultureIgnoreCase) > -1) type = type.Substring(type.IndexOf("::", StringComparison.InvariantCultureIgnoreCase) + 2); if (FilterPassed(item.Element("SupportByLibrary"))) { ListViewItem paramViewItem = listViewDetail.Items.Add("Call Method: " + name); paramViewItem.SubItems.Add(type); string supportText = item.Element("SupportByLibrary").Attribute("Api").Value + " "; foreach (XElement itemVersion in item.Element("SupportByLibrary").Elements("Version")) supportText += itemVersion.Value + " "; paramViewItem.SubItems.Add(supportText); } XElement itemParameters = item.Element("Parameters"); if (null != itemParameters) { foreach (XElement paramItem in itemParameters.Elements("Parameter")) { if (!FilterPassed(paramItem.Element("SupportByLibrary"))) continue; ListViewItem paramViewItem2 = listViewDetail.Items.Add(" Parameter"); paramViewItem2.SubItems.Add(paramItem.Element("SupportByLibrary").Attribute("Name").Value); string supportText = paramItem.Element("SupportByLibrary").Attribute("Api").Value + " "; foreach (XElement itemVersionParam in paramItem.Element("SupportByLibrary").Elements("Version")) supportText += itemVersionParam.Value + " "; paramViewItem2.SubItems.Add(supportText); } } } listViewDetail.Items.Add(""); } } private void SetMethodLocalFieldSets(XElement element) { XElement parametersNode = element.Element("LocalFieldSets"); if ((null != parametersNode) && (parametersNode.Elements("Field").Count() > 0)) { foreach (XElement item in parametersNode.Elements("Field")) { if (!FilterPassed(item.Element("SupportByLibrary"))) continue; ListViewItem paramViewItem = listViewDetail.Items.Add("Set Local Variable " + item.Attribute("Name").Value); paramViewItem.SubItems.Add(item.Element("SupportByLibrary").Attribute("Name").Value); string supportText = item.Element("SupportByLibrary").Attribute("Api").Value + " "; foreach (XElement itemVersion in item.Element("SupportByLibrary").Elements("Version")) supportText += itemVersion.Value + " "; paramViewItem.SubItems.Add(supportText); } listViewDetail.Items.Add(""); } } private void SetMethodFieldSets(XElement element) { XElement parametersNode = element.Element("FieldSets"); if ((null != parametersNode) && (parametersNode.Elements("Field").Count() > 0)) { foreach (XElement item in parametersNode.Elements("Field")) { if (!FilterPassed(item.Element("SupportByLibrary"))) continue; ListViewItem paramViewItem = listViewDetail.Items.Add("Set Class Field " + item.Attribute("Name").Value); paramViewItem.SubItems.Add(item.Element("SupportByLibrary").Attribute("Name").Value); string supportText = item.Element("SupportByLibrary").Attribute("Api").Value + " "; foreach (XElement itemVersion in item.Element("SupportByLibrary").Elements("Version")) supportText += itemVersion.Value + " "; paramViewItem.SubItems.Add(supportText); } listViewDetail.Items.Add(""); } } private void SetNewObjects(XElement element) { XElement parametersNode = element.Element("NewObjects"); if ((null != parametersNode) && (parametersNode.Elements("Entity").Count() > 0)) { foreach (XElement item in parametersNode.Elements("Entity")) { if (!FilterPassed(item.Element("SupportByLibrary"))) continue; ListViewItem paramViewItem = listViewDetail.Items.Add("new " + item.Attribute("Type").Value + "()"); paramViewItem.SubItems.Add(item.Attribute("Type").Value); string supportText = item.Element("SupportByLibrary").Attribute("Api").Value + " "; foreach (XElement itemVersion in item.Element("SupportByLibrary").Elements("Version")) supportText += itemVersion.Value + " "; paramViewItem.SubItems.Add(supportText); } listViewDetail.Items.Add(""); } } private void SetMethodVariables(XElement element) { XElement parametersNode = element.Element("Variables"); if ((null != parametersNode) && (parametersNode.Elements("Entity").Count() > 0)) { foreach (XElement item in parametersNode.Elements("Entity")) { if (!FilterPassed(item.Element("SupportByLibrary"))) continue; ListViewItem paramViewItem = listViewDetail.Items.Add("Locale Variable " + item.Attribute("Name").Value); paramViewItem.SubItems.Add(item.Attribute("Type").Value); string supportText = item.Element("SupportByLibrary").Attribute("Api").Value + " "; foreach (XElement itemVersion in item.Element("SupportByLibrary").Elements("Version")) supportText += itemVersion.Value + " "; paramViewItem.SubItems.Add(supportText); } listViewDetail.Items.Add(""); } } private void SetMethodParameters(XElement element) { XElement parametersNode = element.Element("Parameters"); if ((null != parametersNode) && (parametersNode.Elements("Entity").Count() > 0)) { foreach (XElement item in parametersNode.Elements("Entity")) { if (!FilterPassed(item.Element("SupportByLibrary"))) continue; ListViewItem paramViewItem = listViewDetail.Items.Add("Parameter " + item.Attribute("Name").Value); paramViewItem.SubItems.Add(item.Attribute("Type").Value); string supportText = item.Element("SupportByLibrary").Attribute("Api").Value + " "; foreach (XElement itemVersion in item.Element("SupportByLibrary").Elements("Version")) supportText += itemVersion.Value + " "; paramViewItem.SubItems.Add(supportText); } listViewDetail.Items.Add(""); } } private void SetMethodReturnValue(XElement element) { XElement returnValueNode = element.Element("ReturnValue"); if (null != returnValueNode) { if (!FilterPassed(returnValueNode.Element("Entity").Element("SupportByLibrary"))) return; string valType = returnValueNode.Element("Entity").Attribute("FullType").Value; ListViewItem viewItem = listViewDetail.Items.Add("Return Value"); viewItem.SubItems.Add(valType); string supportText = returnValueNode.Element("Entity").Element("SupportByLibrary").Attribute("Api").Value + " "; foreach (XElement versionItem in returnValueNode.Element("Entity").Element("SupportByLibrary").Elements("Version")) supportText += versionItem.Value + " "; viewItem.SubItems.Add(supportText); listViewDetail.Items.Add(""); } } private bool FilterPassed(XElement supportNode) { if (0 == comboBoxFilter.SelectedIndex) return true; bool found09 = false; bool found10 = false; bool found11 = false; bool found12 = false; bool found14 = false; bool found15 = false; bool found16 = false; foreach (XElement itemVersion in supportNode.Elements("Version")) { switch (itemVersion.Value) { case "9": found09 = true; break; case "10": found10 = true; break; case "11": found11 = true; break; case "12": found12 = true; break; case "14": found14 = true; break; case "15": found15 = true; break; case "16": found16 = true; break; default: break; } } switch (comboBoxFilter.SelectedIndex) { case 1: // 09 if (found09) return false; break; case 2: // 10 if (found10) return false; break; case 3: // 11 if (found11) return false; break; case 4: // 12 if (found12) return false; break; case 5: // 14 if (found14) return false; break; case 6: // 15 if (found15) return false; break; case 7: // 16 if (found16) return false; break; } return true; } private string GetLogFileContent() { return _report.Report.ToString(); } #endregion #region Trigger private void buttonClose_Click(object sender, EventArgs e) { this.Hide(); } private void ShowDetails(List<XElement> elements) { listViewDetail.Items.Clear(); foreach (XElement element in elements) ShowDetails(element, false); } private void ShowDetails(XElement element, bool clearOldItems) { switch (element.Name.ToString()) { case "Assembly": listViewDetail.Columns.Clear(); listViewDetail.Columns.Add(""); listViewDetail.Columns[0].Width = listViewDetail.Width - 50; listViewDetail.Columns[0].Text = "Assenbly"; listViewDetail.Items.Add(element.Attribute("Name").Value); break; case "Class": listViewDetail.Items.Clear(); listViewDetail.Columns.Clear(); listViewDetail.Columns.Add(""); listViewDetail.Columns[0].Width = listViewDetail.Width - 50; listViewDetail.Columns[0].Text = "Class"; listViewDetail.Items.Add(element.Attribute("Name").Value); break; case "Entity": listViewDetail.Items.Clear(); listViewDetail.Columns.Clear(); listViewDetail.Columns.Add("Name"); listViewDetail.Columns.Add("Type"); listViewDetail.Columns.Add("Support"); listViewDetail.Columns[0].Width = GetPercent(listViewDetail.Width, 25); listViewDetail.Columns[0].Tag = 25; listViewDetail.Columns[1].Width = GetPercent(listViewDetail.Width, 50); listViewDetail.Columns[1].Tag = 50; listViewDetail.Columns[2].Width = GetPercent(listViewDetail.Width, 25); listViewDetail.Columns[2].Tag = 25; if (!FilterPassed(element.Element("SupportByLibrary"))) break; listViewDetail.Items.Add(element.Attribute("Name").Value); listViewDetail.Items[0].SubItems.Add(element.Attribute("Type").Value); string supportText = element.Element("SupportByLibrary").Attribute("Api").Value + " "; foreach (XElement item in element.Element("SupportByLibrary").Elements("Version")) supportText += item.Value + " "; listViewDetail.Items[0].SubItems.Add(supportText); break; case "Method": if (clearOldItems) listViewDetail.Items.Clear(); listViewDetail.Columns.Clear(); listViewDetail.Columns.Add("Instance"); listViewDetail.Columns.Add("Target"); listViewDetail.Columns.Add("Support"); listViewDetail.Columns[0].Width = GetPercent(listViewDetail.Width, 25); listViewDetail.Columns[0].Tag = 25; listViewDetail.Columns[1].Width = GetPercent(listViewDetail.Width, 50); listViewDetail.Columns[1].Tag = 50; listViewDetail.Columns[2].Width = GetPercent(listViewDetail.Width, 25); listViewDetail.Columns[2].Tag = 25; SetMethodReturnValue(element); SetMethodParameters(element); SetMethodVariables(element); SetMethodLocalFieldSets(element); SetMethodFieldSets(element); SetNewObjects(element); SetMethodCalls(element); break; default: listViewDetail.Items.Clear(); listViewDetail.Columns.Clear(); break; } textBoxReport.Text = element.ToString(); } private void treeViewReport_AfterSelect(object sender, TreeViewEventArgs e) { if (null == treeViewReport.SelectedNode) { textBoxReport.Text = ""; return; } XElement element = treeViewReport.SelectedNode.Tag as XElement; if (null != element) { ShowDetails(element, true); } else { List<XElement> elements = treeViewReport.SelectedNode.Tag as List<XElement>; ShowDetails(elements); } } private void checkBoxNativeView_CheckedChanged(object sender, EventArgs e) { try { panelView.Visible = !checkBoxNativeView.Checked; panelNativeView.Visible = checkBoxNativeView.Checked; } catch (Exception exception) { Forms.ErrorForm.ShowError(this, exception,ErrorCategory.NonCritical); } } private void comboBoxFilter_SelectedIndexChanged(object sender, EventArgs e) { try { ShowAssembly(); } catch (Exception exception) { Forms.ErrorForm.ShowError(this, exception, ErrorCategory.NonCritical); } } private void listViewDetail_Resize(object sender, EventArgs e) { foreach (ColumnHeader item in listViewDetail.Columns) { if (item.Tag != null) { int percentValue = Convert.ToInt32(item.Tag); item.Width = GetPercent(listViewDetail.Width, percentValue); } } } private void buttonSaveReport_Click(object sender, EventArgs e) { try { SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = "*.txt|*.txt"; if(DialogResult.OK == dialog.ShowDialog(this)) { if (File.Exists(dialog.FileName)) File.Delete(dialog.FileName); string logFileContent = GetLogFileContent(); File.AppendAllText(dialog.FileName, logFileContent); } } catch (Exception exception) { Forms.ErrorForm.ShowError(this, exception, ErrorCategory.NonCritical); } } #endregion } }
<h1 id="test">Test</h1> <pre><code class="lang-javascript"><span class="hljs-variable"><span class="hljs-keyword">var</span> a</span> = <span class="hljs-number">10</span>; </code></pre> <h2 id="hello-helinjiang">Hello grunt-md-html</h2>
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace Window { public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; // ƒ^ƒCƒgƒ‹‚̕ύX Window.Title = "Ookumaneko"; // ƒ}ƒEƒXƒJ[ƒ\ƒ‹‚ð•\ަ‚·‚é IsMouseVisible = true; // ‹N“®’†‚ɃTƒCƒY‚ð•ύX‚Å‚«‚邿‚¤‚É‚·‚é Window.AllowUserResizing = true; } protected override void Initialize() { base.Initialize(); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); } protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); base.Draw(gameTime); } } }
require.register("scripts/product", function(exports, require, module) { var req = require('scripts/req'); AddStyleTagToItemVM = function(user, styletag_repo) { // this is very similar to AddItemToCollectionVM - yet different. var self = this; self.styletags = styletag_repo.create_filter(); self.styletags.load_until_entry(100); self.target_item = ko.observable(null); self.selected_styletag = ko.observable(); self.show_select_styletag = ko.computed(function() { return self.target_item(); }); self.show_must_login = ko.observable(false); var request_add_styletag_to_item = function(item, styletag, success, error) { req.post("/api/styletag-item/create/", JSON.stringify({'item': item.id, 'styletag': styletag.name}), success, error); }; self.confirmed_must_login = function() { self.show_must_login(false); }; self.confirmed_add_styletag = function() { if (!self.selected_styletag()) { // user selected "Choose..." in the drop-down return; } if (!_.contains(self.target_item().styletags(), self.selected_styletag())) { var success = function() { self.target_item().styletags.push(self.selected_styletag().name); self.target_item(null); }; var error = function() { self.target_item(null); /* TODO: display something to user. */ }; request_add_styletag_to_item(self.target_item(), self.selected_styletag(), success, error); }; }; self.add_to_item = function(item) { if (!user()) { self.show_must_login(true); return; } console.log("lets go add styletag"); self.target_item(item); }; }; ProductVM = function(template_name, item_repo, add_to_collection_vm, favorites_vm, add_styletag_to_item_vm) { var self = this; self.template_name = template_name; self.product = ko.observable(null); self.add_to_collection_vm = add_to_collection_vm; self.favorites_vm = favorites_vm; self.add_styletag_to_item_vm = add_styletag_to_item_vm self.load = function(params) { item_repo.fetch(params.product_id, self.product); } }; exports.ProductVM = ProductVM; exports.AddStyleTagToItemVM = AddStyleTagToItemVM; });
module SifttterRedux # DropboxUploader Class # Wrapper class for the Dropbox Uploader project class DropboxUploader # Stores the local filepath. # @return [String] attr_accessor :local_target # Stores the remote filepath. # @return [String] attr_accessor :remote_target # Stores the message to display. # @return [String] attr_accessor :message # Stores the verbosity level. # @return [Boolean] attr_accessor :verbose # Loads the location of dropbox_uploader.sh. # @param [String] dbu_path The local filepath to the script # @param [Logger] A Logger to use # @return [void] def initialize(dbu_path, logger = nil) @dbu = dbu_path @logger = logger end # Downloads files from Dropbox (assumes that both # local_target and remote_target have been set). # @return [void] def download if !@local_target.nil? && !@remote_target.nil? if @verbose system "#{ @dbu } download #{ @remote_target } #{ @local_target }" else exec = `#{ @dbu } download #{ @remote_target } #{ @local_target }` end else error_msg = 'Local and remote targets cannot be nil' @logger.error(error_msg) if @logger fail StandardError, error_msg end end # Uploads files tro Dropbox (assumes that both # local_target and remote_target have been set). # @return [void] def upload if !@local_target.nil? && !@remote_target.nil? if @verbose system "#{ @dbu } upload #{ @local_target } #{ @remote_target }" else exec = `#{ @dbu } upload #{ @local_target } #{ @remote_target }` end else error_msg = 'Local and remote targets cannot be nil' @logger.error(error_msg) if @logger fail StandardError, error_msg end end end end
using AppKit; using Foundation; namespace ChipmunkSharp.Example.Cocoa { [Register ("AppDelegate")] public class AppDelegate : NSApplicationDelegate { public AppDelegate () { } public override void DidFinishLaunching (NSNotification notification) { // Insert code here to initialize your application } public override void WillTerminate (NSNotification notification) { // Insert code here to tear down your application } } }
--- layout: post title: "via显卡驱动" date: 2007-05-20 17:02:31 categories: 默认分类 tags: --- * content {:toc} http://forum.ubuntu.org.cn/about48065.html&sid=0076348367b759485c5f40f3f7b54d91
<?php // Connection Component Binding Doctrine_Manager::getInstance()->bindComponent('Spdevalm', 'profit'); /** * BaseSpdevalm * * This class has been auto-generated by the Doctrine ORM Framework * * @property integer $dev_num * @property timestamp $fecha * @property string $alm_orig * @property string $alm_dest * @property string $motivo_glo * @property boolean $confirma * @property timestamp $fec_conf * @property boolean $inactivo * @property string $campo1 * @property string $campo2 * @property string $campo3 * @property string $campo4 * @property string $campo5 * @property string $campo6 * @property string $campo7 * @property string $campo8 * @property string $co_us_in * @property timestamp $fe_us_in * @property string $co_us_mo * @property timestamp $fe_us_mo * @property string $co_us_el * @property timestamp $fe_us_el * @property string $revisado * @property string $reqnfe * @property integer $seriales * @property string $co_sucu * @property boolean $anulada * @property string $dis_cen * @property timestamp $feccom * @property integer $numcom * @property integer $odp_num * @property string $comentario * @property integer $tras_num * @property string $rowguid * @property string $trasnfe * * @method integer getDevNum() Returns the current record's "dev_num" value * @method timestamp getFecha() Returns the current record's "fecha" value * @method string getAlmOrig() Returns the current record's "alm_orig" value * @method string getAlmDest() Returns the current record's "alm_dest" value * @method string getMotivoGlo() Returns the current record's "motivo_glo" value * @method boolean getConfirma() Returns the current record's "confirma" value * @method timestamp getFecConf() Returns the current record's "fec_conf" value * @method boolean getInactivo() Returns the current record's "inactivo" value * @method string getCampo1() Returns the current record's "campo1" value * @method string getCampo2() Returns the current record's "campo2" value * @method string getCampo3() Returns the current record's "campo3" value * @method string getCampo4() Returns the current record's "campo4" value * @method string getCampo5() Returns the current record's "campo5" value * @method string getCampo6() Returns the current record's "campo6" value * @method string getCampo7() Returns the current record's "campo7" value * @method string getCampo8() Returns the current record's "campo8" value * @method string getCoUsIn() Returns the current record's "co_us_in" value * @method timestamp getFeUsIn() Returns the current record's "fe_us_in" value * @method string getCoUsMo() Returns the current record's "co_us_mo" value * @method timestamp getFeUsMo() Returns the current record's "fe_us_mo" value * @method string getCoUsEl() Returns the current record's "co_us_el" value * @method timestamp getFeUsEl() Returns the current record's "fe_us_el" value * @method string getRevisado() Returns the current record's "revisado" value * @method string getReqnfe() Returns the current record's "reqnfe" value * @method integer getSeriales() Returns the current record's "seriales" value * @method string getCoSucu() Returns the current record's "co_sucu" value * @method boolean getAnulada() Returns the current record's "anulada" value * @method string getDisCen() Returns the current record's "dis_cen" value * @method timestamp getFeccom() Returns the current record's "feccom" value * @method integer getNumcom() Returns the current record's "numcom" value * @method integer getOdpNum() Returns the current record's "odp_num" value * @method string getComentario() Returns the current record's "comentario" value * @method integer getTrasNum() Returns the current record's "tras_num" value * @method string getRowguid() Returns the current record's "rowguid" value * @method string getTrasnfe() Returns the current record's "trasnfe" value * @method Spdevalm setDevNum() Sets the current record's "dev_num" value * @method Spdevalm setFecha() Sets the current record's "fecha" value * @method Spdevalm setAlmOrig() Sets the current record's "alm_orig" value * @method Spdevalm setAlmDest() Sets the current record's "alm_dest" value * @method Spdevalm setMotivoGlo() Sets the current record's "motivo_glo" value * @method Spdevalm setConfirma() Sets the current record's "confirma" value * @method Spdevalm setFecConf() Sets the current record's "fec_conf" value * @method Spdevalm setInactivo() Sets the current record's "inactivo" value * @method Spdevalm setCampo1() Sets the current record's "campo1" value * @method Spdevalm setCampo2() Sets the current record's "campo2" value * @method Spdevalm setCampo3() Sets the current record's "campo3" value * @method Spdevalm setCampo4() Sets the current record's "campo4" value * @method Spdevalm setCampo5() Sets the current record's "campo5" value * @method Spdevalm setCampo6() Sets the current record's "campo6" value * @method Spdevalm setCampo7() Sets the current record's "campo7" value * @method Spdevalm setCampo8() Sets the current record's "campo8" value * @method Spdevalm setCoUsIn() Sets the current record's "co_us_in" value * @method Spdevalm setFeUsIn() Sets the current record's "fe_us_in" value * @method Spdevalm setCoUsMo() Sets the current record's "co_us_mo" value * @method Spdevalm setFeUsMo() Sets the current record's "fe_us_mo" value * @method Spdevalm setCoUsEl() Sets the current record's "co_us_el" value * @method Spdevalm setFeUsEl() Sets the current record's "fe_us_el" value * @method Spdevalm setRevisado() Sets the current record's "revisado" value * @method Spdevalm setReqnfe() Sets the current record's "reqnfe" value * @method Spdevalm setSeriales() Sets the current record's "seriales" value * @method Spdevalm setCoSucu() Sets the current record's "co_sucu" value * @method Spdevalm setAnulada() Sets the current record's "anulada" value * @method Spdevalm setDisCen() Sets the current record's "dis_cen" value * @method Spdevalm setFeccom() Sets the current record's "feccom" value * @method Spdevalm setNumcom() Sets the current record's "numcom" value * @method Spdevalm setOdpNum() Sets the current record's "odp_num" value * @method Spdevalm setComentario() Sets the current record's "comentario" value * @method Spdevalm setTrasNum() Sets the current record's "tras_num" value * @method Spdevalm setRowguid() Sets the current record's "rowguid" value * @method Spdevalm setTrasnfe() Sets the current record's "trasnfe" value * * @package gesser * @subpackage model * @author Luis Hernández * @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $ */ abstract class BaseSpdevalm extends sfDoctrineRecord { public function setTableDefinition() { $this->setTableName('spdevalm'); $this->hasColumn('dev_num', 'integer', 4, array( 'type' => 'integer', 'fixed' => 0, 'unsigned' => false, 'primary' => true, 'autoincrement' => false, 'length' => 4, )); $this->hasColumn('fecha', 'timestamp', 16, array( 'type' => 'timestamp', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(convert(varchar(10),getdate(),104))', 'primary' => false, 'autoincrement' => false, 'length' => 16, )); $this->hasColumn('alm_orig', 'string', 6, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 6, )); $this->hasColumn('alm_dest', 'string', 6, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 6, )); $this->hasColumn('motivo_glo', 'string', 60, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 60, )); $this->hasColumn('confirma', 'boolean', 1, array( 'type' => 'boolean', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(0)', 'primary' => false, 'autoincrement' => false, 'length' => 1, )); $this->hasColumn('fec_conf', 'timestamp', 16, array( 'type' => 'timestamp', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(convert(varchar(10),getdate(),104))', 'primary' => false, 'autoincrement' => false, 'length' => 16, )); $this->hasColumn('inactivo', 'boolean', 1, array( 'type' => 'boolean', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(0)', 'primary' => false, 'autoincrement' => false, 'length' => 1, )); $this->hasColumn('campo1', 'string', 60, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 60, )); $this->hasColumn('campo2', 'string', 60, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 60, )); $this->hasColumn('campo3', 'string', 60, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 60, )); $this->hasColumn('campo4', 'string', 60, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 60, )); $this->hasColumn('campo5', 'string', 60, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 60, )); $this->hasColumn('campo6', 'string', 60, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 60, )); $this->hasColumn('campo7', 'string', 60, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 60, )); $this->hasColumn('campo8', 'string', 60, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 60, )); $this->hasColumn('co_us_in', 'string', 4, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 4, )); $this->hasColumn('fe_us_in', 'timestamp', 16, array( 'type' => 'timestamp', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(dateadd(millisecond,(((-datepart(millisecond,getdate())))),getdate()))', 'primary' => false, 'autoincrement' => false, 'length' => 16, )); $this->hasColumn('co_us_mo', 'string', 4, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 4, )); $this->hasColumn('fe_us_mo', 'timestamp', 16, array( 'type' => 'timestamp', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(dateadd(millisecond,(((-datepart(millisecond,getdate())))),getdate()))', 'primary' => false, 'autoincrement' => false, 'length' => 16, )); $this->hasColumn('co_us_el', 'string', 4, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 4, )); $this->hasColumn('fe_us_el', 'timestamp', 16, array( 'type' => 'timestamp', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(dateadd(millisecond,(((-datepart(millisecond,getdate())))),getdate()))', 'primary' => false, 'autoincrement' => false, 'length' => 16, )); $this->hasColumn('revisado', 'string', 1, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 1, )); $this->hasColumn('reqnfe', 'string', 1, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 1, )); $this->hasColumn('seriales', 'integer', 4, array( 'type' => 'integer', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(0)', 'primary' => false, 'autoincrement' => false, 'length' => 4, )); $this->hasColumn('co_sucu', 'string', 6, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 6, )); $this->hasColumn('anulada', 'boolean', 1, array( 'type' => 'boolean', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(0)', 'primary' => false, 'autoincrement' => false, 'length' => 1, )); $this->hasColumn('dis_cen', 'string', 2147483647, array( 'type' => 'string', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 2147483647, )); $this->hasColumn('feccom', 'timestamp', 16, array( 'type' => 'timestamp', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(convert(varchar(10),getdate(),104))', 'primary' => false, 'autoincrement' => false, 'length' => 16, )); $this->hasColumn('numcom', 'integer', 4, array( 'type' => 'integer', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(0)', 'primary' => false, 'autoincrement' => false, 'length' => 4, )); $this->hasColumn('odp_num', 'integer', 4, array( 'type' => 'integer', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(0)', 'primary' => false, 'autoincrement' => false, 'length' => 4, )); $this->hasColumn('comentario', 'string', 2147483647, array( 'type' => 'string', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(space(1))', 'primary' => false, 'autoincrement' => false, 'length' => 2147483647, )); $this->hasColumn('tras_num', 'integer', 4, array( 'type' => 'integer', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(0)', 'primary' => false, 'autoincrement' => false, 'length' => 4, )); $this->hasColumn('rowguid', 'string', 36, array( 'type' => 'string', 'fixed' => 0, 'unsigned' => false, 'notnull' => true, 'default' => '(newid())', 'primary' => false, 'autoincrement' => false, 'length' => 36, )); $this->hasColumn('trasnfe', 'string', 1, array( 'type' => 'string', 'fixed' => 1, 'unsigned' => false, 'notnull' => true, 'primary' => false, 'autoincrement' => false, 'length' => 1, )); } public function setUp() { parent::setUp(); } }
using System.Web; using System.Web.Optimization; namespace MvcOther { public class BundleConfig { // バンドルの詳細については、http://go.microsoft.com/fwlink/?LinkId=301862 を参照してください public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // 開発と学習には、Modernizr の開発バージョンを使用します。次に、実稼働の準備が // できたら、http://modernizr.com にあるビルド ツールを使用して、必要なテストのみを選択します。 bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); // デバッグを行うには EnableOptimizations を false に設定します。詳細については、 // http://go.microsoft.com/fwlink/?LinkId=301862 を参照してください BundleTable.EnableOptimizations = true; } } }
<?php /** * Class for performing HTTP requests * * PHP versions 4 and 5 * * LICENSE: * * Copyright (c) 2002-2007, Richard Heyes * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * o Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * o Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * o The names of the authors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @category HTTP * @package HTTP_Request * @author Richard Heyes <richard@phpguru.org> * @author Alexey Borzov <avb@php.net> * @copyright 2002-2007 Richard Heyes * @license http://opensource.org/licenses/bsd-license.php New BSD License * @version CVS: $Id: Request.php,v 1.58 2007/10/26 13:45:56 avb Exp $ * @link http://pear.php.net/package/HTTP_Request/ */ /** * PEAR and PEAR_Error classes (for error handling) */ require_once 'PEAR.php'; /** * Socket class */ require_once 'Socket.php'; /** * URL handling class */ require_once 'URL.php'; /**#@+ * Constants for HTTP request methods */ define('HTTP_REQUEST_METHOD_GET', 'GET', true); define('HTTP_REQUEST_METHOD_HEAD', 'HEAD', true); define('HTTP_REQUEST_METHOD_POST', 'POST', true); define('HTTP_REQUEST_METHOD_PUT', 'PUT', true); define('HTTP_REQUEST_METHOD_DELETE', 'DELETE', true); define('HTTP_REQUEST_METHOD_OPTIONS', 'OPTIONS', true); define('HTTP_REQUEST_METHOD_TRACE', 'TRACE', true); /**#@-*/ /**#@+ * Constants for HTTP request error codes */ define('HTTP_REQUEST_ERROR_FILE', 1); define('HTTP_REQUEST_ERROR_URL', 2); define('HTTP_REQUEST_ERROR_PROXY', 4); define('HTTP_REQUEST_ERROR_REDIRECTS', 8); define('HTTP_REQUEST_ERROR_RESPONSE', 16); define('HTTP_REQUEST_ERROR_GZIP_METHOD', 32); define('HTTP_REQUEST_ERROR_GZIP_READ', 64); define('HTTP_REQUEST_ERROR_GZIP_DATA', 128); define('HTTP_REQUEST_ERROR_GZIP_CRC', 256); /**#@-*/ /**#@+ * Constants for HTTP protocol versions */ define('HTTP_REQUEST_HTTP_VER_1_0', '1.0', true); define('HTTP_REQUEST_HTTP_VER_1_1', '1.1', true); /**#@-*/ if (extension_loaded('mbstring') && (2 & ini_get('mbstring.func_overload'))) { /** * Whether string functions are overloaded by their mbstring equivalents */ define('HTTP_REQUEST_MBSTRING', true); } else { /** * @ignore */ define('HTTP_REQUEST_MBSTRING', false); } /** * Class for performing HTTP requests * * Simple example (fetches yahoo.com and displays it): * <code> * $a = &new HTTP_Request('http://www.yahoo.com/'); * $a->sendRequest(); * echo $a->getResponseBody(); * </code> * * @category HTTP * @package HTTP_Request * @author Richard Heyes <richard@phpguru.org> * @author Alexey Borzov <avb@php.net> * @version Release: 1.4.2 */ class HTTP_Request { /**#@+ * @access private */ /** * Instance of Net_URL * @var Net_URL */ var $_url; /** * Type of request * @var string */ var $_method; /** * HTTP Version * @var string */ var $_http; /** * Request headers * @var array */ var $_requestHeaders; /** * Basic Auth Username * @var string */ var $_user; /** * Basic Auth Password * @var string */ var $_pass; /** * Socket object * @var Net_Socket */ var $_sock; /** * Proxy server * @var string */ var $_proxy_host; /** * Proxy port * @var integer */ var $_proxy_port; /** * Proxy username * @var string */ var $_proxy_user; /** * Proxy password * @var string */ var $_proxy_pass; /** * Post data * @var array */ var $_postData; /** * Request body * @var string */ var $_body; /** * A list of methods that MUST NOT have a request body, per RFC 2616 * @var array */ var $_bodyDisallowed = array('TRACE'); /** * Files to post * @var array */ var $_postFiles = array(); /** * Connection timeout. * @var float */ var $_timeout; /** * HTTP_Response object * @var HTTP_Response */ var $_response; /** * Whether to allow redirects * @var boolean */ var $_allowRedirects; /** * Maximum redirects allowed * @var integer */ var $_maxRedirects; /** * Current number of redirects * @var integer */ var $_redirects; /** * Whether to append brackets [] to array variables * @var bool */ var $_useBrackets = true; /** * Attached listeners * @var array */ var $_listeners = array(); /** * Whether to save response body in response object property * @var bool */ var $_saveBody = true; /** * Timeout for reading from socket (array(seconds, microseconds)) * @var array */ var $_readTimeout = null; /** * Options to pass to Net_Socket::connect. See stream_context_create * @var array */ var $_socketOptions = null; /**#@-*/ /** * Constructor * * Sets up the object * @param string The url to fetch/access * @param array Associative array of parameters which can have the following keys: * <ul> * <li>method - Method to use, GET, POST etc (string)</li> * <li>http - HTTP Version to use, 1.0 or 1.1 (string)</li> * <li>user - Basic Auth username (string)</li> * <li>pass - Basic Auth password (string)</li> * <li>proxy_host - Proxy server host (string)</li> * <li>proxy_port - Proxy server port (integer)</li> * <li>proxy_user - Proxy auth username (string)</li> * <li>proxy_pass - Proxy auth password (string)</li> * <li>timeout - Connection timeout in seconds (float)</li> * <li>allowRedirects - Whether to follow redirects or not (bool)</li> * <li>maxRedirects - Max number of redirects to follow (integer)</li> * <li>useBrackets - Whether to append [] to array variable names (bool)</li> * <li>saveBody - Whether to save response body in response object property (bool)</li> * <li>readTimeout - Timeout for reading / writing data over the socket (array (seconds, microseconds))</li> * <li>socketOptions - Options to pass to Net_Socket object (array)</li> * </ul> * @access public */ function HTTP_Request($url = '', $params = array()) { $this->_method = HTTP_REQUEST_METHOD_GET; $this->_http = HTTP_REQUEST_HTTP_VER_1_1; $this->_requestHeaders = array(); $this->_postData = array(); $this->_body = null; $this->_user = null; $this->_pass = null; $this->_proxy_host = null; $this->_proxy_port = null; $this->_proxy_user = null; $this->_proxy_pass = null; $this->_allowRedirects = false; $this->_maxRedirects = 3; $this->_redirects = 0; $this->_timeout = null; $this->_response = null; foreach ($params as $key => $value) { $this->{'_' . $key} = $value; } if (!empty($url)) { $this->setURL($url); } // Default useragent $this->addHeader('User-Agent', 'PEAR HTTP_Request class ( http://pear.php.net/ )'); // We don't do keep-alives by default $this->addHeader('Connection', 'close'); // Basic authentication if (!empty($this->_user)) { $this->addHeader('Authorization', 'Basic ' . base64_encode($this->_user . ':' . $this->_pass)); } // Proxy authentication (see bug #5913) if (!empty($this->_proxy_user)) { $this->addHeader('Proxy-Authorization', 'Basic ' . base64_encode($this->_proxy_user . ':' . $this->_proxy_pass)); } // Use gzip encoding if possible if (HTTP_REQUEST_HTTP_VER_1_1 == $this->_http && extension_loaded('zlib')) { $this->addHeader('Accept-Encoding', 'gzip'); } } /** * Generates a Host header for HTTP/1.1 requests * * @access private * @return string */ function _generateHostHeader() { if ($this->_url->port != 80 AND strcasecmp($this->_url->protocol, 'http') == 0) { $host = $this->_url->host . ':' . $this->_url->port; } elseif ($this->_url->port != 443 AND strcasecmp($this->_url->protocol, 'https') == 0) { $host = $this->_url->host . ':' . $this->_url->port; } elseif ($this->_url->port == 443 AND strcasecmp($this->_url->protocol, 'https') == 0 AND strpos($this->_url->url, ':443') !== false) { $host = $this->_url->host . ':' . $this->_url->port; } else { $host = $this->_url->host; } return $host; } /** * Resets the object to its initial state (DEPRECATED). * Takes the same parameters as the constructor. * * @param string $url The url to be requested * @param array $params Associative array of parameters * (see constructor for details) * @access public * @deprecated deprecated since 1.2, call the constructor if this is necessary */ function reset($url, $params = array()) { $this->HTTP_Request($url, $params); } /** * Sets the URL to be requested * * @param string The url to be requested * @access public */ function setURL($url) { $this->_url = &new Net_URL($url, $this->_useBrackets); if (!empty($this->_url->user) || !empty($this->_url->pass)) { $this->setBasicAuth($this->_url->user, $this->_url->pass); } if (HTTP_REQUEST_HTTP_VER_1_1 == $this->_http) { $this->addHeader('Host', $this->_generateHostHeader()); } // set '/' instead of empty path rather than check later (see bug #8662) if (empty($this->_url->path)) { $this->_url->path = '/'; } } /** * Returns the current request URL * * @return string Current request URL * @access public */ function getUrl() { return empty($this->_url)? '': $this->_url->getUrl(); } /** * Sets a proxy to be used * * @param string Proxy host * @param int Proxy port * @param string Proxy username * @param string Proxy password * @access public */ function setProxy($host, $port = 8080, $user = null, $pass = null) { $this->_proxy_host = $host; $this->_proxy_port = $port; $this->_proxy_user = $user; $this->_proxy_pass = $pass; if (!empty($user)) { $this->addHeader('Proxy-Authorization', 'Basic ' . base64_encode($user . ':' . $pass)); } } /** * Sets basic authentication parameters * * @param string Username * @param string Password */ function setBasicAuth($user, $pass) { $this->_user = $user; $this->_pass = $pass; $this->addHeader('Authorization', 'Basic ' . base64_encode($user . ':' . $pass)); } /** * Sets the method to be used, GET, POST etc. * * @param string Method to use. Use the defined constants for this * @access public */ function setMethod($method) { $this->_method = $method; } /** * Sets the HTTP version to use, 1.0 or 1.1 * * @param string Version to use. Use the defined constants for this * @access public */ function setHttpVer($http) { $this->_http = $http; } /** * Adds a request header * * @param string Header name * @param string Header value * @access public */ function addHeader($name, $value) { $this->_requestHeaders[strtolower($name)] = $value; } /** * Removes a request header * * @param string Header name to remove * @access public */ function removeHeader($name) { if (isset($this->_requestHeaders[strtolower($name)])) { unset($this->_requestHeaders[strtolower($name)]); } } /** * Adds a querystring parameter * * @param string Querystring parameter name * @param string Querystring parameter value * @param bool Whether the value is already urlencoded or not, default = not * @access public */ function addQueryString($name, $value, $preencoded = false) { $this->_url->addQueryString($name, $value, $preencoded); } /** * Sets the querystring to literally what you supply * * @param string The querystring data. Should be of the format foo=bar&x=y etc * @param bool Whether data is already urlencoded or not, default = already encoded * @access public */ function addRawQueryString($querystring, $preencoded = true) { $this->_url->addRawQueryString($querystring, $preencoded); } /** * Adds postdata items * * @param string Post data name * @param string Post data value * @param bool Whether data is already urlencoded or not, default = not * @access public */ function addPostData($name, $value, $preencoded = false) { if ($preencoded) { $this->_postData[$name] = $value; } else { $this->_postData[$name] = $this->_arrayMapRecursive('urlencode', $value); } } /** * Recursively applies the callback function to the value * * @param mixed Callback function * @param mixed Value to process * @access private * @return mixed Processed value */ function _arrayMapRecursive($callback, $value) { if (!is_array($value)) { return call_user_func($callback, $value); } else { $map = array(); foreach ($value as $k => $v) { $map[$k] = $this->_arrayMapRecursive($callback, $v); } return $map; } } /** * Adds a file to upload * * This also changes content-type to 'multipart/form-data' for proper upload * * @access public * @param string name of file-upload field * @param mixed file name(s) * @param mixed content-type(s) of file(s) being uploaded * @return bool true on success * @throws PEAR_Error */ function addFile($inputName, $fileName, $contentType = 'application/octet-stream') { if (!is_array($fileName) && !is_readable($fileName)) { return PEAR::raiseError("File '{$fileName}' is not readable", HTTP_REQUEST_ERROR_FILE); } elseif (is_array($fileName)) { foreach ($fileName as $name) { if (!is_readable($name)) { return PEAR::raiseError("File '{$name}' is not readable", HTTP_REQUEST_ERROR_FILE); } } } $this->addHeader('Content-Type', 'multipart/form-data'); $this->_postFiles[$inputName] = array( 'name' => $fileName, 'type' => $contentType ); return true; } /** * Adds raw postdata (DEPRECATED) * * @param string The data * @param bool Whether data is preencoded or not, default = already encoded * @access public * @deprecated deprecated since 1.3.0, method setBody() should be used instead */ function addRawPostData($postdata, $preencoded = true) { $this->_body = $preencoded ? $postdata : urlencode($postdata); } /** * Sets the request body (for POST, PUT and similar requests) * * @param string Request body * @access public */ function setBody($body) { $this->_body = $body; } /** * Clears any postdata that has been added (DEPRECATED). * * Useful for multiple request scenarios. * * @access public * @deprecated deprecated since 1.2 */ function clearPostData() { $this->_postData = null; } /** * Appends a cookie to "Cookie:" header * * @param string $name cookie name * @param string $value cookie value * @access public */ function addCookie($name, $value) { $cookies = isset($this->_requestHeaders['cookie']) ? $this->_requestHeaders['cookie']. '; ' : ''; $this->addHeader('Cookie', $cookies . $name . '=' . $value); } /** * Clears any cookies that have been added (DEPRECATED). * * Useful for multiple request scenarios * * @access public * @deprecated deprecated since 1.2 */ function clearCookies() { $this->removeHeader('Cookie'); } /** * Sends the request * * @access public * @param bool Whether to store response body in Response object property, * set this to false if downloading a LARGE file and using a Listener * @return mixed PEAR error on error, true otherwise */ function sendRequest($saveBody = true) { if (!is_a($this->_url, 'Net_URL')) { return PEAR::raiseError('No URL given', HTTP_REQUEST_ERROR_URL); } $host = isset($this->_proxy_host) ? $this->_proxy_host : $this->_url->host; $port = isset($this->_proxy_port) ? $this->_proxy_port : $this->_url->port; // 4.3.0 supports SSL connections using OpenSSL. The function test determines // we running on at least 4.3.0 if (strcasecmp($this->_url->protocol, 'https') == 0 AND function_exists('file_get_contents') AND extension_loaded('openssl')) { if (isset($this->_proxy_host)) { return PEAR::raiseError('HTTPS proxies are not supported', HTTP_REQUEST_ERROR_PROXY); } $host = 'ssl://' . $host; } // magic quotes may fuck up file uploads and chunked response processing $magicQuotes = ini_get('magic_quotes_runtime'); ini_set('magic_quotes_runtime', false); // RFC 2068, section 19.7.1: A client MUST NOT send the Keep-Alive // connection token to a proxy server... if (isset($this->_proxy_host) && !empty($this->_requestHeaders['connection']) && 'Keep-Alive' == $this->_requestHeaders['connection']) { $this->removeHeader('connection'); } $keepAlive = (HTTP_REQUEST_HTTP_VER_1_1 == $this->_http && empty($this->_requestHeaders['connection'])) || (!empty($this->_requestHeaders['connection']) && 'Keep-Alive' == $this->_requestHeaders['connection']); $sockets = &PEAR::getStaticProperty('HTTP_Request', 'sockets'); $sockKey = $host . ':' . $port; unset($this->_sock); // There is a connected socket in the "static" property? if ($keepAlive && !empty($sockets[$sockKey]) && !empty($sockets[$sockKey]->fp)) { $this->_sock =& $sockets[$sockKey]; $err = null; } else { $this->_notify('connect'); $this->_sock =& new Net_Socket(); $err = $this->_sock->connect($host, $port, null, $this->_timeout, $this->_socketOptions); } PEAR::isError($err) or $err = $this->_sock->write($this->_buildRequest()); if (!PEAR::isError($err)) { if (!empty($this->_readTimeout)) { $this->_sock->setTimeout($this->_readTimeout[0], $this->_readTimeout[1]); } $this->_notify('sentRequest'); // Read the response $this->_response = &new HTTP_Response($this->_sock, $this->_listeners); $err = $this->_response->process( $this->_saveBody && $saveBody, HTTP_REQUEST_METHOD_HEAD != $this->_method ); if ($keepAlive) { $keepAlive = (isset($this->_response->_headers['content-length']) || (isset($this->_response->_headers['transfer-encoding']) && strtolower($this->_response->_headers['transfer-encoding']) == 'chunked')); if ($keepAlive) { if (isset($this->_response->_headers['connection'])) { $keepAlive = strtolower($this->_response->_headers['connection']) == 'keep-alive'; } else { $keepAlive = 'HTTP/'.HTTP_REQUEST_HTTP_VER_1_1 == $this->_response->_protocol; } } } } ini_set('magic_quotes_runtime', $magicQuotes); if (PEAR::isError($err)) { return $err; } if (!$keepAlive) { $this->disconnect(); // Store the connected socket in "static" property } elseif (empty($sockets[$sockKey]) || empty($sockets[$sockKey]->fp)) { $sockets[$sockKey] =& $this->_sock; } // Check for redirection if ( $this->_allowRedirects AND $this->_redirects <= $this->_maxRedirects AND $this->getResponseCode() > 300 AND $this->getResponseCode() < 399 AND !empty($this->_response->_headers['location'])) { $redirect = $this->_response->_headers['location']; // Absolute URL if (preg_match('/^https?:\/\//i', $redirect)) { $this->_url = &new Net_URL($redirect); $this->addHeader('Host', $this->_generateHostHeader()); // Absolute path } elseif ($redirect{0} == '/') { $this->_url->path = $redirect; // Relative path } elseif (substr($redirect, 0, 3) == '../' OR substr($redirect, 0, 2) == './') { if (substr($this->_url->path, -1) == '/') { $redirect = $this->_url->path . $redirect; } else { $redirect = dirname($this->_url->path) . '/' . $redirect; } $redirect = Net_URL::resolvePath($redirect); $this->_url->path = $redirect; // Filename, no path } else { if (substr($this->_url->path, -1) == '/') { $redirect = $this->_url->path . $redirect; } else { $redirect = dirname($this->_url->path) . '/' . $redirect; } $this->_url->path = $redirect; } $this->_redirects++; return $this->sendRequest($saveBody); // Too many redirects } elseif ($this->_allowRedirects AND $this->_redirects > $this->_maxRedirects) { return PEAR::raiseError('Too many redirects', HTTP_REQUEST_ERROR_REDIRECTS); } return true; } /** * Disconnect the socket, if connected. Only useful if using Keep-Alive. * * @access public */ function disconnect() { if (!empty($this->_sock) && !empty($this->_sock->fp)) { $this->_notify('disconnect'); $this->_sock->disconnect(); } } /** * Returns the response code * * @access public * @return mixed Response code, false if not set */ function getResponseCode() { return isset($this->_response->_code) ? $this->_response->_code : false; } /** * Returns either the named header or all if no name given * * @access public * @param string The header name to return, do not set to get all headers * @return mixed either the value of $headername (false if header is not present) * or an array of all headers */ function getResponseHeader($headername = null) { if (!isset($headername)) { return isset($this->_response->_headers)? $this->_response->_headers: array(); } else { $headername = strtolower($headername); return isset($this->_response->_headers[$headername]) ? $this->_response->_headers[$headername] : false; } } /** * Returns the body of the response * * @access public * @return mixed response body, false if not set */ function getResponseBody() { return isset($this->_response->_body) ? $this->_response->_body : false; } /** * Returns cookies set in response * * @access public * @return mixed array of response cookies, false if none are present */ function getResponseCookies() { return isset($this->_response->_cookies) ? $this->_response->_cookies : false; } /** * Builds the request string * * @access private * @return string The request string */ function _buildRequest() { $separator = ini_get('arg_separator.output'); ini_set('arg_separator.output', '&'); $querystring = ($querystring = $this->_url->getQueryString()) ? '?' . $querystring : ''; ini_set('arg_separator.output', $separator); $host = isset($this->_proxy_host) ? $this->_url->protocol . '://' . $this->_url->host : ''; $port = (isset($this->_proxy_host) AND $this->_url->port != 80) ? ':' . $this->_url->port : ''; $path = $this->_url->path . $querystring; $url = $host . $port . $path; if (!strlen($url)) { $url = '/'; } $request = $this->_method . ' ' . $url . ' HTTP/' . $this->_http . "\r\n"; if (in_array($this->_method, $this->_bodyDisallowed) || (0 == strlen($this->_body) && (HTTP_REQUEST_METHOD_POST != $this->_method || (empty($this->_postData) && empty($this->_postFiles))))) { $this->removeHeader('Content-Type'); } else { if (empty($this->_requestHeaders['content-type'])) { // Add default content-type $this->addHeader('Content-Type', 'application/x-www-form-urlencoded'); } elseif ('multipart/form-data' == $this->_requestHeaders['content-type']) { $boundary = 'HTTP_Request_' . md5(uniqid('request') . microtime()); $this->addHeader('Content-Type', 'multipart/form-data; boundary=' . $boundary); } } // Request Headers if (!empty($this->_requestHeaders)) { foreach ($this->_requestHeaders as $name => $value) { $canonicalName = implode('-', array_map('ucfirst', explode('-', $name))); $request .= $canonicalName . ': ' . $value . "\r\n"; } } // No post data or wrong method, so simply add a final CRLF if (in_array($this->_method, $this->_bodyDisallowed) || (HTTP_REQUEST_METHOD_POST != $this->_method && 0 == strlen($this->_body))) { $request .= "\r\n"; // Post data if it's an array } elseif (HTTP_REQUEST_METHOD_POST == $this->_method && (!empty($this->_postData) || !empty($this->_postFiles))) { // "normal" POST request if (!isset($boundary)) { $postdata = implode('&', array_map( create_function('$a', 'return $a[0] . \'=\' . $a[1];'), $this->_flattenArray('', $this->_postData) )); // multipart request, probably with file uploads } else { $postdata = ''; if (!empty($this->_postData)) { $flatData = $this->_flattenArray('', $this->_postData); foreach ($flatData as $item) { $postdata .= '--' . $boundary . "\r\n"; $postdata .= 'Content-Disposition: form-data; name="' . $item[0] . '"'; $postdata .= "\r\n\r\n" . urldecode($item[1]) . "\r\n"; } } foreach ($this->_postFiles as $name => $value) { if (is_array($value['name'])) { $varname = $name . ($this->_useBrackets? '[]': ''); } else { $varname = $name; $value['name'] = array($value['name']); } foreach ($value['name'] as $key => $filename) { $fp = fopen($filename, 'r'); $data = fread($fp, filesize($filename)); fclose($fp); $basename = basename($filename); $type = is_array($value['type'])? @$value['type'][$key]: $value['type']; $postdata .= '--' . $boundary . "\r\n"; $postdata .= 'Content-Disposition: form-data; name="' . $varname . '"; filename="' . $basename . '"'; $postdata .= "\r\nContent-Type: " . $type; $postdata .= "\r\n\r\n" . $data . "\r\n"; } } $postdata .= '--' . $boundary . "--\r\n"; } $request .= 'Content-Length: ' . (HTTP_REQUEST_MBSTRING? mb_strlen($postdata, 'iso-8859-1'): strlen($postdata)) . "\r\n\r\n"; $request .= $postdata; // Explicitly set request body } elseif (0 < strlen($this->_body)) { $request .= 'Content-Length: ' . (HTTP_REQUEST_MBSTRING? mb_strlen($this->_body, 'iso-8859-1'): strlen($this->_body)) . "\r\n\r\n"; $request .= $this->_body; // Terminate headers with CRLF on POST request with no body, too } else { $request .= "\r\n"; } return $request; } /** * Helper function to change the (probably multidimensional) associative array * into the simple one. * * @param string name for item * @param mixed item's values * @return array array with the following items: array('item name', 'item value'); * @access private */ function _flattenArray($name, $values) { if (!is_array($values)) { return array(array($name, $values)); } else { $ret = array(); foreach ($values as $k => $v) { if (empty($name)) { $newName = $k; } elseif ($this->_useBrackets) { $newName = $name . '[' . $k . ']'; } else { $newName = $name; } $ret = array_merge($ret, $this->_flattenArray($newName, $v)); } return $ret; } } /** * Adds a Listener to the list of listeners that are notified of * the object's events * * Events sent by HTTP_Request object * - 'connect': on connection to server * - 'sentRequest': after the request was sent * - 'disconnect': on disconnection from server * * Events sent by HTTP_Response object * - 'gotHeaders': after receiving response headers (headers are passed in $data) * - 'tick': on receiving a part of response body (the part is passed in $data) * - 'gzTick': on receiving a gzip-encoded part of response body (ditto) * - 'gotBody': after receiving the response body (passes the decoded body in $data if it was gzipped) * * @param HTTP_Request_Listener listener to attach * @return boolean whether the listener was successfully attached * @access public */ function attach(&$listener) { if (!is_a($listener, 'HTTP_Request_Listener')) { return false; } $this->_listeners[$listener->getId()] =& $listener; return true; } /** * Removes a Listener from the list of listeners * * @param HTTP_Request_Listener listener to detach * @return boolean whether the listener was successfully detached * @access public */ function detach(&$listener) { if (!is_a($listener, 'HTTP_Request_Listener') || !isset($this->_listeners[$listener->getId()])) { return false; } unset($this->_listeners[$listener->getId()]); return true; } /** * Notifies all registered listeners of an event. * * @param string Event name * @param mixed Additional data * @access private * @see HTTP_Request::attach() */ function _notify($event, $data = null) { foreach (array_keys($this->_listeners) as $id) { $this->_listeners[$id]->update($this, $event, $data); } } } /** * Response class to complement the Request class * * @category HTTP * @package HTTP_Request * @author Richard Heyes <richard@phpguru.org> * @author Alexey Borzov <avb@php.net> * @version Release: 1.4.2 */ class HTTP_Response { /** * Socket object * @var Net_Socket */ var $_sock; /** * Protocol * @var string */ var $_protocol; /** * Return code * @var string */ var $_code; /** * Response headers * @var array */ var $_headers; /** * Cookies set in response * @var array */ var $_cookies; /** * Response body * @var string */ var $_body = ''; /** * Used by _readChunked(): remaining length of the current chunk * @var string */ var $_chunkLength = 0; /** * Attached listeners * @var array */ var $_listeners = array(); /** * Bytes left to read from message-body * @var null|int */ var $_toRead; /** * Constructor * * @param Net_Socket socket to read the response from * @param array listeners attached to request */ function HTTP_Response(&$sock, &$listeners) { $this->_sock =& $sock; $this->_listeners =& $listeners; } /** * Processes a HTTP response * * This extracts response code, headers, cookies and decodes body if it * was encoded in some way * * @access public * @param bool Whether to store response body in object property, set * this to false if downloading a LARGE file and using a Listener. * This is assumed to be true if body is gzip-encoded. * @param bool Whether the response can actually have a message-body. * Will be set to false for HEAD requests. * @throws PEAR_Error * @return mixed true on success, PEAR_Error in case of malformed response */ function process($saveBody = true, $canHaveBody = true) { do { $line = $this->_sock->readLine(); if (sscanf($line, 'HTTP/%s %s', $http_version, $returncode) != 2) { return PEAR::raiseError('Malformed response', HTTP_REQUEST_ERROR_RESPONSE); } else { $this->_protocol = 'HTTP/' . $http_version; $this->_code = intval($returncode); } while ('' !== ($header = $this->_sock->readLine())) { $this->_processHeader($header); } } while (100 == $this->_code); $this->_notify('gotHeaders', $this->_headers); // RFC 2616, section 4.4: // 1. Any response message which "MUST NOT" include a message-body ... // is always terminated by the first empty line after the header fields // 3. ... If a message is received with both a // Transfer-Encoding header field and a Content-Length header field, // the latter MUST be ignored. $canHaveBody = $canHaveBody && $this->_code >= 200 && $this->_code != 204 && $this->_code != 304; // If response body is present, read it and decode $chunked = isset($this->_headers['transfer-encoding']) && ('chunked' == $this->_headers['transfer-encoding']); $gzipped = isset($this->_headers['content-encoding']) && ('gzip' == $this->_headers['content-encoding']); $hasBody = false; if ($canHaveBody && ($chunked || !isset($this->_headers['content-length']) || 0 != $this->_headers['content-length'])) { if ($chunked || !isset($this->_headers['content-length'])) { $this->_toRead = null; } else { $this->_toRead = $this->_headers['content-length']; } while (!$this->_sock->eof() && (is_null($this->_toRead) || 0 < $this->_toRead)) { if ($chunked) { $data = $this->_readChunked(); } elseif (is_null($this->_toRead)) { $data = $this->_sock->read(4096); } else { $data = $this->_sock->read(min(4096, $this->_toRead)); $this->_toRead -= HTTP_REQUEST_MBSTRING? mb_strlen($data, 'iso-8859-1'): strlen($data); } if ('' == $data) { break; } else { $hasBody = true; if ($saveBody || $gzipped) { $this->_body .= $data; } $this->_notify($gzipped? 'gzTick': 'tick', $data); } } } if ($hasBody) { // Uncompress the body if needed if ($gzipped) { $body = $this->_decodeGzip($this->_body); if (PEAR::isError($body)) { return $body; } $this->_body = $body; $this->_notify('gotBody', $this->_body); } else { $this->_notify('gotBody'); } } return true; } /** * Processes the response header * * @access private * @param string HTTP header */ function _processHeader($header) { if (false === strpos($header, ':')) { return; } list($headername, $headervalue) = explode(':', $header, 2); $headername = strtolower($headername); $headervalue = ltrim($headervalue); if ('set-cookie' != $headername) { if (isset($this->_headers[$headername])) { $this->_headers[$headername] .= ',' . $headervalue; } else { $this->_headers[$headername] = $headervalue; } } else { $this->_parseCookie($headervalue); } } /** * Parse a Set-Cookie header to fill $_cookies array * * @access private * @param string value of Set-Cookie header */ function _parseCookie($headervalue) { $cookie = array( 'expires' => null, 'domain' => null, 'path' => null, 'secure' => false ); // Only a name=value pair if (!strpos($headervalue, ';')) { $pos = strpos($headervalue, '='); $cookie['name'] = trim(substr($headervalue, 0, $pos)); $cookie['value'] = trim(substr($headervalue, $pos + 1)); // Some optional parameters are supplied } else { $elements = explode(';', $headervalue); $pos = strpos($elements[0], '='); $cookie['name'] = trim(substr($elements[0], 0, $pos)); $cookie['value'] = trim(substr($elements[0], $pos + 1)); for ($i = 1; $i < count($elements); $i++) { if (false === strpos($elements[$i], '=')) { $elName = trim($elements[$i]); $elValue = null; } else { list ($elName, $elValue) = array_map('trim', explode('=', $elements[$i])); } $elName = strtolower($elName); if ('secure' == $elName) { $cookie['secure'] = true; } elseif ('expires' == $elName) { $cookie['expires'] = str_replace('"', '', $elValue); } elseif ('path' == $elName || 'domain' == $elName) { $cookie[$elName] = urldecode($elValue); } else { $cookie[$elName] = $elValue; } } } $this->_cookies[] = $cookie; } /** * Read a part of response body encoded with chunked Transfer-Encoding * * @access private * @return string */ function _readChunked() { // at start of the next chunk? if (0 == $this->_chunkLength) { $line = $this->_sock->readLine(); if (preg_match('/^([0-9a-f]+)/i', $line, $matches)) { $this->_chunkLength = hexdec($matches[1]); // Chunk with zero length indicates the end if (0 == $this->_chunkLength) { $this->_sock->readLine(); // make this an eof() return ''; } } else { return ''; } } $data = $this->_sock->read($this->_chunkLength); $this->_chunkLength -= HTTP_REQUEST_MBSTRING? mb_strlen($data, 'iso-8859-1'): strlen($data); if (0 == $this->_chunkLength) { $this->_sock->readLine(); // Trailing CRLF } return $data; } /** * Notifies all registered listeners of an event. * * @param string Event name * @param mixed Additional data * @access private * @see HTTP_Request::_notify() */ function _notify($event, $data = null) { foreach (array_keys($this->_listeners) as $id) { $this->_listeners[$id]->update($this, $event, $data); } } /** * Decodes the message-body encoded by gzip * * The real decoding work is done by gzinflate() built-in function, this * method only parses the header and checks data for compliance with * RFC 1952 * * @access private * @param string gzip-encoded data * @return string decoded data */ function _decodeGzip($data) { if (HTTP_REQUEST_MBSTRING) { $oldEncoding = mb_internal_encoding(); mb_internal_encoding('iso-8859-1'); } $length = strlen($data); // If it doesn't look like gzip-encoded data, don't bother if (18 > $length || strcmp(substr($data, 0, 2), "\x1f\x8b")) { return $data; } $method = ord(substr($data, 2, 1)); if (8 != $method) { return PEAR::raiseError('_decodeGzip(): unknown compression method', HTTP_REQUEST_ERROR_GZIP_METHOD); } $flags = ord(substr($data, 3, 1)); if ($flags & 224) { return PEAR::raiseError('_decodeGzip(): reserved bits are set', HTTP_REQUEST_ERROR_GZIP_DATA); } // header is 10 bytes minimum. may be longer, though. $headerLength = 10; // extra fields, need to skip 'em if ($flags & 4) { if ($length - $headerLength - 2 < 8) { return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA); } $extraLength = unpack('v', substr($data, 10, 2)); if ($length - $headerLength - 2 - $extraLength[1] < 8) { return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA); } $headerLength += $extraLength[1] + 2; } // file name, need to skip that if ($flags & 8) { if ($length - $headerLength - 1 < 8) { return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA); } $filenameLength = strpos(substr($data, $headerLength), chr(0)); if (false === $filenameLength || $length - $headerLength - $filenameLength - 1 < 8) { return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA); } $headerLength += $filenameLength + 1; } // comment, need to skip that also if ($flags & 16) { if ($length - $headerLength - 1 < 8) { return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA); } $commentLength = strpos(substr($data, $headerLength), chr(0)); if (false === $commentLength || $length - $headerLength - $commentLength - 1 < 8) { return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA); } $headerLength += $commentLength + 1; } // have a CRC for header. let's check if ($flags & 1) { if ($length - $headerLength - 2 < 8) { return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA); } $crcReal = 0xffff & crc32(substr($data, 0, $headerLength)); $crcStored = unpack('v', substr($data, $headerLength, 2)); if ($crcReal != $crcStored[1]) { return PEAR::raiseError('_decodeGzip(): header CRC check failed', HTTP_REQUEST_ERROR_GZIP_CRC); } $headerLength += 2; } // unpacked data CRC and size at the end of encoded data $tmp = unpack('V2', substr($data, -8)); $dataCrc = $tmp[1]; $dataSize = $tmp[2]; // finally, call the gzinflate() function $unpacked = @gzinflate(substr($data, $headerLength, -8), $dataSize); if (false === $unpacked) { return PEAR::raiseError('_decodeGzip(): gzinflate() call failed', HTTP_REQUEST_ERROR_GZIP_READ); } elseif ($dataSize != strlen($unpacked)) { return PEAR::raiseError('_decodeGzip(): data size check failed', HTTP_REQUEST_ERROR_GZIP_READ); } elseif ((0xffffffff & $dataCrc) != (0xffffffff & crc32($unpacked))) { return PEAR::raiseError('_decodeGzip(): data CRC check failed', HTTP_REQUEST_ERROR_GZIP_CRC); } if (HTTP_REQUEST_MBSTRING) { mb_internal_encoding($oldEncoding); } return $unpacked; } } // End class HTTP_Response ?>
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require("react"); var _react2 = _interopRequireDefault(_react); var _propTypes = require("prop-types"); var _propTypes2 = _interopRequireDefault(_propTypes); var _textInput = require("./text-input"); var _textInput2 = _interopRequireDefault(_textInput); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function validateEmail(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } var EmailInput = function (_TextInput) { _inherits(EmailInput, _TextInput); function EmailInput(props) { _classCallCheck(this, EmailInput); return _possibleConstructorReturn(this, (EmailInput.__proto__ || Object.getPrototypeOf(EmailInput)).call(this, props)); } _createClass(EmailInput, [{ key: "onValid", value: function onValid(e) { if (!!this.props.onValid) { this.props.onValid(validateEmail(e.target.value), e); } } }]); return EmailInput; }(_textInput2.default); exports.default = EmailInput; EmailInput.propTypes = { type: _propTypes2.default.string.isRequired }; EmailInput.defaultProps = { type: "email" };
import React, { Component } from 'react'; import List from 'react-toolbox/lib/list/List'; import ListSubHeader from 'react-toolbox/lib/list/ListSubHeader'; import ListCheckbox from 'react-toolbox/lib/list/ListCheckbox'; import ListItem from 'react-toolbox/lib/list/ListItem'; import Dropdown from 'react-toolbox/lib/dropdown/Dropdown'; import ConnectedStoreHOC from '../utils/connect.store.hoc'; import * as Actions from '../utils/actions'; import { NEW_PHOTO_DURATIONS } from '../configs/constants'; const NEW_PHOTO_INTERVAL_OPTIONS = [ { value: NEW_PHOTO_DURATIONS.ALWAYS, label: 'Always' }, { value: NEW_PHOTO_DURATIONS.HOURLY, label: 'Hourly' }, { value: NEW_PHOTO_DURATIONS.DAILY, label: 'Daily' }, ]; const handleFetchFromServerChange = (value, ev) => Actions.setSetting({ fetchFromServer: value }); const handleNewPhotoIntervalChange = (value, ev) => Actions.setSetting({ newPhotoDuration: parseInt(value, 10) }); const NewPhotoIntervalDropdown = ({ refreshInterval, className }) => ( <Dropdown label="Duration" className={className} value={refreshInterval} source={NEW_PHOTO_INTERVAL_OPTIONS} onChange={handleNewPhotoIntervalChange} /> ); class SettingsContainer extends Component { componentDidMount() { // lazy initialize the state object setTimeout(() => Actions.refresh(false), 0); } render() { const { fetchFromServer, newPhotoDuration } = this.props; return ( <List selectable ripple> <ListSubHeader caption="Background Photos" /> <ListCheckbox caption="Load Fresh" legend="If disabled, it will cycle through a list of locally stored wallpapers only." checked={fetchFromServer} onChange={handleFetchFromServerChange} /> <ListItem itemContent={ <div> <p className="settings__inlineItem">Show new photo</p> <NewPhotoIntervalDropdown className="settings__inlineItem" refreshInterval={newPhotoDuration} /> </div> } ripple={false} selectable={false} /> </List>); } } export default ConnectedStoreHOC(SettingsContainer);
require "simple_selector/version" require "simple_selector/specificity" require "simple_selector/segment" class SimpleSelector def initialize(string=nil) @segments = [] @specificity = Specificity.new concat(string) unless string.nil? end attr_reader :specificity def concat(string) string.scan(/[\w.#]+/).map { |s| Segment.new(s) }.each do |segment| @segments << segment @specificity += segment.specificity end self end def +(string) duplicate.concat(string) end def match?(tag) return true if @segments.none? return false unless @segments.last.match?(tag) index = @segments.size - 2 current_tag = tag while index >= 0 && current_tag = current_tag.parent if @segments[index].match?(current_tag) index -= 1 next end end index == -1 end def empty? @segments.none? end def to_s @segments.map { |segment| segment.to_s }.join(" ") end def inspect "#<#{self.class} #{to_s.inspect}>" end def ==(other) to_s == other.to_s end def duplicate d = dup d.instance_variable_set( "@segments", @segments.dup) d.instance_variable_set("@specificity", @specificity.dup) d end end
<?php namespace thgs\Olographos; class Olographos { /* | Olographos class |-=-=-=-=-=-=-=-=-=- | | I wrote this a while ago, now went through it all wrapping it in a class. | Has some introspective comments :) | | | Limitations: max number is 999,999.99 | | Version: 0.1b - Improved comments and whitespace :) */ const STR_EURO = 'ΕΥΡΩ'; const STR_AND = 'ΚΑΙ'; const STR_CENTS = 'ΛΕΠΤΑ'; const STR_THOUSANDS = 'ΧΙΛΙΑΔΕΣ'; protected static $representations = [ '0' => '', '1' => 'ΕΝΑ', '2' => 'ΔΥΟ', '3' => 'ΤΡΙΑ', '4' => 'ΤΕΣΣΕΡΑ', '5' => 'ΠΕΝΤΕ', '6' => 'ΕΞΙ', '7' => 'ΕΠΤΑ', '8' => 'ΟΚΤΩ', '9' => 'ΕΝΝΙΑ', '10' => 'ΔΕΚΑ', '11' => 'ΕΝΤΕΚΑ', '12' => 'ΔΩΔΕΚΑ', '13' => 'ΔΕΚΑ ΤΡΙΑ', '14' => 'ΔΕΚΑ ΤΕΣΣΕΡΑ', '15' => 'ΔΕΚΑ ΠΕΝΤΕ', '16' => 'ΔΕΚΑ ΕΞΙ', '17' => 'ΔΕΚΑ ΕΠΤΑ', '18' => 'ΔΕΚΑ ΟΚΤΩ', '19' => 'ΔΕΚΑ ΕΝΝΙΑ', '20' => 'ΕΙΚΟΣΙ', '30' => 'ΤΡΙΑΝΤΑ', '40' => 'ΣΑΡΑΝΤΑ', '50' => 'ΠΕΝΗΝΤΑ', '60' => 'ΕΞΗΝΤΑ', '70' => 'ΕΒΔΟΜΗΝΤΑ', '80' => 'ΟΓΔΟΝΤΑ', '90' => 'ΕΝΕΝΗΝΤΑ', '100' => 'ΕΚΑΤΟ', '200' => 'ΔΙΑΚΟΣΙΑ', '300' => 'ΤΡΙΑΚΟΣΙΑ', '400' => 'ΤΕΤΡΑΚΟΣΙΑ', '500' => 'ΠΕΝΤΑΚΟΣΙΑ', '600' => 'ΕΞΑΚΟΣΙΑ', '700' => 'ΕΠΤΑΚΟΣΙΑ', '800' => 'ΟΚΤΑΚΟΣΙΑ', '900' => 'ΕΝΝΙΑΚΟΣΙΑ', '1000' => 'ΧΙΛΙΑ', ]; protected static $thousand_corrections = [ 'ΔΙΑΚΟΣΙΑ' => 'ΔΙΑΚΟΣΙΕΣ', 'ΤΡΙΑΚΟΣΙΑ' => 'ΤΡΙΑΚΟΣΙΕΣ', 'ΤΕΤΡΑΚΟΣΙΑ' => 'ΤΕΤΡΑΚΟΣΙΕΣ', 'ΠΕΝΤΑΚΟΣΙΑ' => 'ΠΕΝΤΑΚΟΣΙΕΣ', 'ΕΞΑΚΟΣΙΑ' => 'ΕΞΑΚΟΣΙΕΣ', 'ΕΠΤΑΚΟΣΙΑ' => 'ΕΠΤΑΚΟΣΙΕΣ', 'ΟΚΤΑΚΟΣΙΑ' => 'ΟΚΤΑΚΟΣΙΕΣ', 'ΕΝΝΙΑΚΟΣΙΑ' => 'ΕΝΝΙΑΚΟΣΙΕΣ', ]; protected static $grammar_corrections = [ 'ΕΝΑ ΧΙΛΙΑΔΕΣ' => 'ΧΙΛΙΑ', ' ΕΝΑ ΧΙΛΙΑΔΕΣ' => ' ΜΙΑ ΧΙΛΙΑΔΕΣ', 'ΕΚΑΤΟ ' => 'ΕΚΑΤΟΝ ', 'ΤΡΙΑ ΧΙΛΙΑΔΕΣ' => 'ΤΡΕΙΣ ΧΙΛΙΑΔΕΣ', 'ΤΕΣΣΕΡΑ ΧΙΛΙΑΔΕΣ' => 'ΤΕΣΣΕΡΙΣ ΧΙΛΙΑΔΕΣ', ]; public static function nt_prim($n, $append = false) { // if $n is not a number return false and exit function if (!is_numeric($n)) { return false; } // case $n contains thousands if ($n > 1000) { // process thousands recursively and correct any mistakes in representation // due to thousands word in greek (xiliades) $tnum = (int) ($n / 1000); $pretext = strtr( self::number_text($tnum).' '.self::STR_THOUSANDS.' ', self::$thousand_corrections ); // remove thousands from number // 0.1-old code: while ($n >= 1000) $n -= 1000; $n = $n % 1000; } // case $n is exactly 1000 if ($n == 1000) { $pretext = self::$representations['1000']; $n -= 1000; // not sure if we need this line // why not return here ? } $text = (isset($pretext)) ? $pretext : ''; // look for the closest representation, performing one iteration // over all representations $plimit = 0; foreach (self::$representations as $limit => $desc) { $ilimit = (int) $limit; if ($ilimit <= $n) { // store current limit, to be used as last found representation $plimit = $limit; continue; } else { // store last found representation $text .= self::$representations[$plimit]; // subtract the amount of last used representation from the number $n -= $plimit; break; } } // return return [$n, $text]; // that is a weird return value, regarding $n, which should be 0 ?? } /** * Returns a textual representation for a number $n in Greek. * * @param float $n * @returns string */ public static function number_text($n) { // dup $n to start getting textual representations $new = $n; // get all textual representations do { list($new, $txt) = self::nt_prim($new); $text[] = $txt; } while ($new > 0); // store into one string $ret = implode(' ', $text); // final grammar corrections $ret = strtr($ret, self::$grammar_corrections); // remove STR_AND from the end of the string, if there is there $length = (2 + strlen(self::STR_AND)) * (-1); if (substr($ret, $length) == ' '.self::STR_AND.' ') { $ret = substr($ret, 0, $length); } // return textual representation of $n return $ret; } /** * Returns the textual representation of an amount in Greek. * * @param float $amount * @returns string */ public static function str_greek_amount($amount) { // explode decimal part list($int, $dec) = explode('.', number_format($amount, 2, '.', '')); // get textual representation of integer part $txt = self::number_text($int).' '.self::STR_EURO; // add cents part if there is any if ($dec > 0) { $txt .= ' '.self::STR_AND.' ' .self::number_text($dec).' '.self::STR_CENTS; } // return return $txt; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LambdastylePrototype; using LambdastylePrototype.Interpreter; using LambdastylePrototype.Interpreter.Predicates; using LambdastylePrototype.Interpreter.Subjects; namespace Test.input5.json._5_remove_keys_with_values_containing_two_upper_letters { class Style { void Build(Builder builder) { builder.Add( new Sentence(new Subject(new Equals(new Any(), new RegExp("[A-Z].*[A-Z]"))), new Predicate()), Consts.CopyAny); } } }
package jp.co.rakuten.checkout.lite.model; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import jp.co.rakuten.checkout.lite.RpayLite; import jp.co.rakuten.checkout.lite.RpayLiteTest; import jp.co.rakuten.checkout.lite.exception.UnexpectedValueException; import jp.co.rakuten.checkout.lite.net.Webhook; import jp.co.rakuten.checkout.lite.net.Webhook.SignatureVerificationException; public class EventTest extends RpayLiteTest { String payload = ""; @Before public void setUpAll() { payload += "{\"object\": \"event\",\"id\": \"evt_ace3a9e65ad548a8b5c8de7965efa160\",\"livemode\": false,\"type\": \"charge.check\",\"synchronous\": true,\"data\": {\"object\": {\"object\": \"charge\","; payload += "\"open_id\": \"https://myid.rakuten.co.jp/openid/user/h65MxxxxxxxQxn0wJENoHHsalseDD==\", \"id\": null,\"cipher\": null,\"livemode\": false,\"currency\": \"jpy\",\"amount\": 5000,\"point\": 1000,"; payload += "\"cart_id\": \"cart_id1\",\"paid\": false,\"captured\": false,\"status\": null,\"refunded\": false,"; payload += "\"items\": [{\"id\": \"item_id1\",\"name\": \"item1\",\"quantity\": 10,\"unit_price\": 1000},{\"id\": \"item_id2\",\"name\": \"item2\",\"quantity\": 20,\"unit_price\": 2000}],"; payload += "\"address\": null,\"created\": null,\"updated\": null}},\"pending_webhooks\":0,\"created\":1433862000}"; } @Test public void testConstruct() throws UnexpectedValueException, SignatureVerificationException { RpayLite.setWebhookSignature("123"); Event ev = Webhook.constructEvent(payload, "123", "123"); assertEquals(ev.getId(), "evt_ace3a9e65ad548a8b5c8de7965efa160"); assertEquals(ev.getData().getObject().getPoint(), 1000); } @Test(expected = SignatureVerificationException.class) public void testNullSigHeader() throws SignatureVerificationException, UnexpectedValueException { Webhook.constructEvent(payload, null, "123"); } @Test(expected = SignatureVerificationException.class) public void testSignatureNotEqual() throws SignatureVerificationException, UnexpectedValueException { RpayLite.setWebhookSignature("123"); Webhook.constructEvent(payload, "188", "123"); } @Test(expected = UnexpectedValueException.class) public void testInvalidJson() throws SignatureVerificationException, UnexpectedValueException { String payloadError = "{\"object\" \"event\",\"id\": \"evt_0a28558a912043d7bb82ba0702afda7f\",\"livemode\": false,\"type\": \"ping\",\"synchronous\": true,\"data\": null,\"pending_webhooks\": 0,\"created\": 1499068723}"; Webhook.constructEvent(payloadError, "188", "123"); } @Test(expected = SignatureVerificationException.class) public void testNullSignature() throws SignatureVerificationException, UnexpectedValueException { Webhook.constructEvent(payload, "188", null); } @Test public void testExceptionSigHeader() throws UnexpectedValueException { try { Webhook.constructEvent(payload, "188", "123"); } catch (SignatureVerificationException e) { assertEquals("188", e.getSigHeader()); } } }
using System; using System.Windows.Forms; using BizHawk.Emulation.Common; using BizHawk.Client.Common; using BizHawk.Common.NumberExtensions; namespace BizHawk.Client.EmuHawk { public partial class StateHistorySettingsForm : Form { public IStatable Statable { get; set; } private readonly TasStateManagerSettings _settings; private decimal _stateSizeMb; public StateHistorySettingsForm(TasStateManagerSettings settings) { _settings = settings; InitializeComponent(); } private void StateHistorySettings_Load(object sender, EventArgs e) { _stateSizeMb = Statable.SaveStateBinary().Length / (decimal)1024 / (decimal)1024; MemCapacityNumeric.Maximum = 1024 * 8; MemCapacityNumeric.Minimum = _stateSizeMb + 1; MemStateGapDividerNumeric.Maximum = Statable.SaveStateBinary().Length / 1024 / 2 + 1; MemStateGapDividerNumeric.Minimum = Math.Max(Statable.SaveStateBinary().Length / 1024 / 16, 1); MemCapacityNumeric.Value = NumberExtensions.Clamp(_settings.Capacitymb, MemCapacityNumeric.Minimum, MemCapacityNumeric.Maximum); DiskCapacityNumeric.Value = NumberExtensions.Clamp(_settings.DiskCapacitymb, MemCapacityNumeric.Minimum, MemCapacityNumeric.Maximum); FileCapacityNumeric.Value = NumberExtensions.Clamp(_settings.DiskSaveCapacitymb, MemCapacityNumeric.Minimum, MemCapacityNumeric.Maximum); MemStateGapDividerNumeric.Value = NumberExtensions.Clamp(_settings.MemStateGapDivider, MemStateGapDividerNumeric.Minimum, MemStateGapDividerNumeric.Maximum); FileStateGapNumeric.Value = _settings.FileStateGap; SavestateSizeLabel.Text = $"{Math.Round(_stateSizeMb, 2)} MB"; CapacityNumeric_ValueChanged(null, null); SaveCapacityNumeric_ValueChanged(null, null); } private int MaxStatesInCapacity => (int)Math.Floor(MemCapacityNumeric.Value / _stateSizeMb) + (int)Math.Floor(DiskCapacityNumeric.Value / _stateSizeMb); private void OkBtn_Click(object sender, EventArgs e) { _settings.Capacitymb = (int)MemCapacityNumeric.Value; _settings.DiskCapacitymb = (int)DiskCapacityNumeric.Value; _settings.DiskSaveCapacitymb = (int)FileCapacityNumeric.Value; _settings.MemStateGapDivider = (int)MemStateGapDividerNumeric.Value; _settings.FileStateGap = (int)FileStateGapNumeric.Value; DialogResult = DialogResult.OK; Close(); } private void CancelBtn_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } private void CapacityNumeric_ValueChanged(object sender, EventArgs e) { // TODO: Setting space for 2.6 (2) states in memory and 2.6 (2) on disk results in 5 total. // Easy to fix the display, but the way TasStateManager works the total used actually is 5. NumStatesLabel.Text = MaxStatesInCapacity.ToString(); } private void SaveCapacityNumeric_ValueChanged(object sender, EventArgs e) { NumSaveStatesLabel.Text = ((int)Math.Floor(FileCapacityNumeric.Value / _stateSizeMb)).ToString(); } private void FileStateGap_ValueChanged(object sender, EventArgs e) { FileNumFramesLabel.Text = FileStateGapNumeric.Value == 0 ? "frame" : $"{1 << (int)FileStateGapNumeric.Value} frames"; } private void MemStateGapDivider_ValueChanged(object sender, EventArgs e) { int val = (int)(Statable.SaveStateBinary().Length / MemStateGapDividerNumeric.Value / 1024); if (val <= 1) MemStateGapDividerNumeric.Maximum = MemStateGapDividerNumeric.Value; MemFramesLabel.Text = val <= 1 ? "frame" : $"{val} frames"; } } }
<?php // autoload_real.php @generated by Composer class ComposerAutoloaderInit54de4412c901abf97506a041edca18c7 { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } public static function getLoader() { if (null !== self::$loader) { return self::$loader; } spl_autoload_register(array('ComposerAutoloaderInit54de4412c901abf97506a041edca18c7', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(); spl_autoload_unregister(array('ComposerAutoloaderInit54de4412c901abf97506a041edca18c7', 'loadClassLoader')); $useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION'); if ($useStaticLoader) { require_once __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\ComposerStaticInit54de4412c901abf97506a041edca18c7::getInitializer($loader)); } else { $map = require __DIR__ . '/autoload_namespaces.php'; foreach ($map as $namespace => $path) { $loader->set($namespace, $path); } $map = require __DIR__ . '/autoload_psr4.php'; foreach ($map as $namespace => $path) { $loader->setPsr4($namespace, $path); } $classMap = require __DIR__ . '/autoload_classmap.php'; if ($classMap) { $loader->addClassMap($classMap); } } $loader->register(true); return $loader; } }
<!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>Iglesia Calle Brasil</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="apple-touch-icon" href="apple-touch-icon.png"> <!-- Place favicon.ico in the root directory --> <link rel="stylesheet" href="css/vendor.css"> <!-- Theme initialization --> <link rel="stylesheet" id="theme-style" href="css/app.css"> <link rel="stylesheet" href="css/site.css"> </head> <body> <div class="main-wrapper"> <div class="app no-sidebar" id="app"> <header class="header no-sidebar"> <div class="sidebar-header"> <div class="brand brand-header"> <div class="logo"><img class="logo-header" src="assets/logo.png" alt="logo" /></div> <div class="pull-right">Iglesia Calle Brasil</div> </div> </div> <div class="header-block header-block-nav"> <ul class="nav-profile"> <li class="profile dropdown"> <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false"> <div class="img" style="background-image: url('https://avatars3.githubusercontent.com/u/3959008?v=3&s=40')"> </div> <span class="name"> Bienvenido, Rubén Gomez </span> </a> <div class="dropdown-menu profile-dropdown-menu" aria-labelledby="dropdownMenu1"> <a class="dropdown-item" href="actualizarDomicilio.html"> <i class="fa fa-user icon"></i> Mis datos </a> <a class="dropdown-item" href="listarPedidosHechosMiembro.html"> <i class="fa fa-shopping-cart icon"></i> Mis pedidos </a> <a class="dropdown-item" href="iniciarSesion.html"> <i class="fa fa-power-off icon"></i> Cerrar sesión </a> </div> </li> </ul> </div> </header> <article class="content items-list-page"> <div class="title-search-block"> <div class="title-block"> <div class="row"> <div class="col-md-6"> <h3 class="title"> Listado de pedidos </h3> </div> </div> </div> </div> <div class="card items"> <ul class="item-list striped"> <li class="item item-list-header hidden-sm-down"> <div class="item-row"> <div class="item-col item-col-header item-col-title"> <div> <span>TEMA</span> </div> </div> <div class="item-col item-col-header item-col-sales"> <div> <span>CANT</span> </div> </div> <div class="item-col item-col-header item-col-date"> <div> <span>FECHA PEDIDO</span> </div> </div> <div class="item-col item-col-header item-col-date"> <div> <span>FECHA ENTREGA</span> </div> </div> <div class="item-col item-col-header item-col-sales"> <div> <span>ESTADO</span> </div> </div> </div> </li> <li class="item"> <div class="item-row"> <div class="item-col item-col-title"> <div>Predicación</div> </div> <div class="item-col item-col-sales"> <div>1</div> </div> <div class="item-col item-col-date"> <div>12/04/2016</div> </div> <div class="item-col item-col-date"> <div>-</div> </div> <div class="item-col item-col-sales"> <div>Listo</div> </div> </div> </li> <li class="item"> <div class="item-row"> <div class="item-col item-col-title"> <div>Predicación</div> </div> <div class="item-col item-col-sales"> <div>1</div> </div> <div class="item-col item-col-date"> <div>12/04/2016</div> </div> <div class="item-col item-col-date"> <div>-</div> </div> <div class="item-col item-col-sales"> <div>Listo</div> </div> </div> </li> <li class="item"> <div class="item-row"> <div class="item-col item-col-title"> <div>Predicación</div> </div> <div class="item-col item-col-sales"> <div>1</div> </div> <div class="item-col item-col-date"> <div>12/04/2016</div> </div> <div class="item-col item-col-date"> <div>-</div> </div> <div class="item-col item-col-sales"> <div>Listo</div> </div> </div> </li> </ul> </div> <nav class="text-xs-right"> <ul class="pagination"> <li class="page-item"> <a class="page-link" href=""> Anterior </a> </li> <li class="page-item active"> <a class="page-link" href=""> 1 </a> </li> <li class="page-item"> <a class="page-link" href=""> 2 </a> </li> <li class="page-item"> <a class="page-link" href=""> 3 </a> </li> <li class="page-item"> <a class="page-link" href=""> 4 </a> </li> <li class="page-item"> <a class="page-link" href=""> 5 </a> </li> <li class="page-item"> <a class="page-link" href=""> Siguiente </a> </li> </ul> </nav> </article> <footer class="footer no-sidebar"> <div class="footer-block author"> <ul> <li> Iglesia Calle Brasil </li> <li> 2017 </li> </ul> </div> </footer> </div> </div> <!-- Reference block for JS --> <div class="ref" id="ref"> <div class="color-primary"></div> <div class="chart"> <div class="color-primary"></div> <div class="color-secondary"></div> </div> </div> <script src="js/vendor.js"></script> <script src="js/app.js"></script> </body> </html>
//----------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // The MIT License (MIT) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // --------------------------------------------------------------------------------- using System; namespace PhotoSharingApp.Universal.Models { /// <summary> /// Represents an annotation for a photo. /// </summary> public class Annotation { /// <summary> /// Gets or sets the date and time when the /// notification was created. /// </summary> public DateTime CreatedTime { get; set; } /// <summary> /// Gets or sets the user who is the originator /// or the annotion. /// </summary> public User From { get; set; } /// <summary> /// Gets or sets the gold count which represents how /// much gold the annotation's originator gives to /// the photo. /// </summary> public int GoldCount { get; set; } /// <summary> /// Gets or sets the Id. /// </summary> public string Id { get; set; } /// <summary> /// Gets or sets the Photo Id. /// </summary> public string PhotoId { get; set; } /// <summary> /// Gets or sets the comment. /// </summary> public string Text { get; set; } } }
using System; using Android.App; using Android.Content; using Android.Content.PM; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using GlobalTouch; using Xamarin.Forms; namespace GlobalTouch.Droid { [Activity(Label = "GlobalTouch.Droid", Icon = "@drawable/icon", Theme = "@style/MyTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App()); } public EventHandler globalTouchHandler; public override bool DispatchTouchEvent(MotionEvent ev) { globalTouchHandler?.Invoke(null, new TouchEventArgs<Point>(new Point(ev.GetX(), ev.GetY()))); return base.DispatchTouchEvent(ev); } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class OVRSceneLoader : MonoBehaviour { public const string externalStoragePath = "/sdcard/Android/data"; public const string sceneLoadDataName = "SceneLoadData.txt"; public const string resourceBundleName = "asset_resources"; public float sceneCheckIntervalSeconds = 1f; public float logCloseTime = 5.0f; public Canvas mainCanvas; public Text logTextBox; private AsyncOperation loadSceneOperation; private string formattedLogText; private float closeLogTimer; private bool closeLogDialogue; private bool canvasPosUpdated; private struct SceneInfo { public List<string> scenes; public long version; public SceneInfo(List<string> sceneList, long currentSceneEpochVersion) { scenes = sceneList; version = currentSceneEpochVersion; } } private string scenePath = ""; private string sceneLoadDataPath = ""; private List<AssetBundle> loadedAssetBundles = new List<AssetBundle>(); private SceneInfo currentSceneInfo; private void Awake() { // Make it presist across scene to continue checking for changes DontDestroyOnLoad(this.gameObject); } void Start() { string applicationPath = Path.Combine(externalStoragePath, Application.identifier); scenePath = Path.Combine(applicationPath, "cache/scenes"); sceneLoadDataPath = Path.Combine(scenePath, sceneLoadDataName); closeLogDialogue = false; StartCoroutine(DelayCanvasPosUpdate()); currentSceneInfo = GetSceneInfo(); // Check valid scene info has been fetched, and load the scenes if (currentSceneInfo.version != 0 && !string.IsNullOrEmpty(currentSceneInfo.scenes[0])) { LoadScene(currentSceneInfo); } } private void LoadScene(SceneInfo sceneInfo) { AssetBundle mainSceneBundle = null; Debug.Log("[OVRSceneLoader] Loading main scene: " + sceneInfo.scenes[0] + " with version " + sceneInfo.version.ToString()); logTextBox.text += "Target Scene: " + sceneInfo.scenes[0] + "\n"; logTextBox.text += "Version: " + sceneInfo.version.ToString() + "\n"; // Load main scene and dependent additive scenes (if any) Debug.Log("[OVRSceneLoader] Loading scene bundle files."); // Fetch all files under scene cache path, excluding unnecessary files such as scene metadata file string[] bundles = Directory.GetFiles(scenePath, "*_*"); logTextBox.text += "Loading " + bundles.Length + " bundle(s) . . . "; string mainSceneBundleFileName = "scene_" + sceneInfo.scenes[0].ToLower(); try { foreach (string b in bundles) { var assetBundle = AssetBundle.LoadFromFile(b); if (assetBundle != null) { Debug.Log("[OVRSceneLoader] Loading file bundle: " + assetBundle.name == null ? "null" : assetBundle.name); loadedAssetBundles.Add(assetBundle); } else { Debug.LogError("[OVRSceneLoader] Loading file bundle failed"); } if (assetBundle.name == mainSceneBundleFileName) { mainSceneBundle = assetBundle; } if (assetBundle.name == resourceBundleName) { OVRResources.SetResourceBundle(assetBundle); } } } catch(Exception e) { logTextBox.text += "<color=red>" + e.Message + "</color>"; return; } logTextBox.text += "<color=green>DONE\n</color>"; if (mainSceneBundle != null) { logTextBox.text += "Loading Scene: {0:P0}\n"; formattedLogText = logTextBox.text; string[] scenePaths = mainSceneBundle.GetAllScenePaths(); string sceneName = Path.GetFileNameWithoutExtension(scenePaths[0]); loadSceneOperation = SceneManager.LoadSceneAsync(sceneName); loadSceneOperation.completed += LoadSceneOperation_completed; } else { logTextBox.text += "<color=red>Failed to get main scene bundle.\n</color>"; } } private void LoadSceneOperation_completed(AsyncOperation obj) { StartCoroutine(onCheckSceneCoroutine()); StartCoroutine(DelayCanvasPosUpdate()); closeLogTimer = 0; closeLogDialogue = true; logTextBox.text += "Log closing in {0} seconds.\n"; formattedLogText = logTextBox.text; } public void Update() { // Display scene load percentage if (loadSceneOperation != null) { if (!loadSceneOperation.isDone) { logTextBox.text = string.Format(formattedLogText, loadSceneOperation.progress + 0.1f); if (loadSceneOperation.progress >= 0.9f) { logTextBox.text = formattedLogText.Replace("{0:P0}", "<color=green>DONE</color>"); logTextBox.text += "Transitioning to new scene.\nLoad times will vary depending on scene complexity.\n"; } } } UpdateCanvasPosition(); // Wait a certain time before closing the log dialogue after the scene has transitioned if (closeLogDialogue) { if (closeLogTimer < logCloseTime) { closeLogTimer += Time.deltaTime; logTextBox.text = string.Format(formattedLogText, (int)(logCloseTime - closeLogTimer)); } else { mainCanvas.gameObject.SetActive(false); closeLogDialogue = false; } } } private void UpdateCanvasPosition() { // Update canvas camera reference and position if the main camera has changed if (mainCanvas.worldCamera != Camera.main) { mainCanvas.worldCamera = Camera.main; if (Camera.main != null) { Vector3 newPosition = Camera.main.transform.position + Camera.main.transform.forward * 0.3f; gameObject.transform.position = newPosition; gameObject.transform.rotation = Camera.main.transform.rotation; } } } private SceneInfo GetSceneInfo() { SceneInfo sceneInfo = new SceneInfo(); try { StreamReader reader = new StreamReader(sceneLoadDataPath); sceneInfo.version = System.Convert.ToInt64(reader.ReadLine()); List<string> sceneList = new List<string>(); while (!reader.EndOfStream) { sceneList.Add(reader.ReadLine()); } sceneInfo.scenes = sceneList; } catch { logTextBox.text += "<color=red>Failed to get scene info data.\n</color>"; } return sceneInfo; } // Update canvas position after a slight delay to get accurate headset position after scene transitions IEnumerator DelayCanvasPosUpdate() { yield return new WaitForSeconds(0.1f); UpdateCanvasPosition(); } IEnumerator onCheckSceneCoroutine() { SceneInfo newSceneInfo; while (true) { newSceneInfo = GetSceneInfo(); if (newSceneInfo.version != currentSceneInfo.version) { Debug.Log("[OVRSceneLoader] Scene change detected."); // Unload all asset bundles foreach (var b in loadedAssetBundles) { if (b != null) { b.Unload(true); } } loadedAssetBundles.Clear(); // Unload all scenes in the hierarchy including main scene and // its dependent additive scenes. int activeScenes = SceneManager.sceneCount; for (int i = 0; i < activeScenes; i++) { SceneManager.UnloadSceneAsync(SceneManager.GetSceneAt(i)); } DestroyAllGameObjects(); SceneManager.LoadSceneAsync("OVRTransitionScene"); break; } yield return new WaitForSeconds(sceneCheckIntervalSeconds); } } void DestroyAllGameObjects() { foreach (GameObject go in Resources.FindObjectsOfTypeAll(typeof(GameObject)) as GameObject[]) { Destroy(go); } } }
<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta name="description"> <meta name="keywords" content="static content generator,static site generator,static site,HTML,web development,.NET,C#,Razor,Markdown,YAML"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="shortcut icon" href="/StrideToolkit/assets/img/favicon.ico" type="image/x-icon"> <link rel="icon" href="/StrideToolkit/assets/img/favicon.ico" type="image/x-icon"> <title>StrideToolkit - API - MathUtilEx.Interpolate(Vector2, Vector2, float, EasingFunction, Vector2) Method</title> <link href="/StrideToolkit/assets/css/highlight.css" rel="stylesheet"> <link href="/StrideToolkit/assets/css/bootstrap/bootstrap.css" rel="stylesheet"> <link href="/StrideToolkit/assets/css/adminlte/AdminLTE.css" rel="stylesheet"> <link href="/StrideToolkit/assets/css/theme/theme.css" rel="stylesheet"> <link href="//fonts.googleapis.com/css?family=Roboto+Mono:400,700|Roboto:400,400i,700,700i" rel="stylesheet"> <link href="/StrideToolkit/assets/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="/StrideToolkit/assets/css/override.css" rel="stylesheet"> <script src="/StrideToolkit/assets/js/jquery-2.2.3.min.js"></script> <script src="/StrideToolkit/assets/js/bootstrap.min.js"></script> <script src="/StrideToolkit/assets/js/app.min.js"></script> <script src="/StrideToolkit/assets/js/highlight.pack.js"></script> <script src="/StrideToolkit/assets/js/jquery.slimscroll.min.js"></script> <script src="/StrideToolkit/assets/js/jquery.sticky-kit.min.js"></script> <script src="/StrideToolkit/assets/js/mermaid.min.js"></script> <script src="/StrideToolkit/assets/js/svg-pan-zoom.min.js"></script> <!--[if lt IE 9]> <script src="/StrideToolkit/assets/js/html5shiv.min.js"></script> <script src="/StrideToolkit/assets/js/respond.min.js"></script> <![endif]--> </head> <body class="hold-transition wyam layout-boxed "> <div class="top-banner"></div> <div class="wrapper with-container"> <!-- Header --> <header class="main-header"> <a href="/StrideToolkit/" class="logo"> <!-- mini logo for sidebar mini 50x50 pixels --> <span class="logo-mini"><img src="/StrideToolkit/assets/img/logo.png"></span> <!-- logo for regular state and mobile devices --> <span class="logo-lg"><img src="/StrideToolkit/assets/img/logo.png"></span> </a> <nav class="navbar navbar-static-top" role="navigation"> <!-- Sidebar toggle button--> <a href="#" class="sidebar-toggle visible-xs-block" data-toggle="offcanvas" role="button"> <span class="sr-only">Toggle side menu</span> <i class="fa fa-chevron-circle-right"></i> </a> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse"> <span class="sr-only">Toggle side menu</span> <i class="fa fa-chevron-circle-down"></i> </button> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse pull-left" id="navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="/StrideToolkit/docs">Documentation</a></li> <li class="active"><a href="/StrideToolkit/api">API</a></li> <li><a href="https://github.com/dfkeenan/StrideToolkit"><i class="fa fa-github"></i> Source</a></li> </ul> </div> <!-- /.navbar-collapse --> <!-- Navbar Right Menu --> </nav> </header> <!-- Left side column. contains the logo and sidebar --> <aside class="main-sidebar "> <section class="infobar" data-spy="affix" data-offset-top="60" data-offset-bottom="200"> <div id="infobar-headings"><h6>On This Page</h6><p><a href="#Summary">Summary</a></p> <p><a href="#Syntax">Syntax</a></p> <p><a href="#Remarks">Remarks</a></p> <p><a href="#Attributes">Attributes</a></p> <p><a href="#Parameters">Parameters</a></p> <p><a href="#ReturnValue">Return Value</a></p> <hr class="infobar-hidden"> </div> </section> <section class="sidebar"> <script src="/StrideToolkit/assets/js/lunr.min.js"></script> <script src="/StrideToolkit/assets/js/searchIndex.js"></script> <div class="sidebar-form"> <div class="input-group"> <input type="text" name="search" id="search" class="form-control" placeholder="Search Types..."> <span class="input-group-btn"> <button class="btn btn-flat"><i class="fa fa-search"></i></button> </span> </div> </div> <div id="search-results"> </div> <script> function runSearch(query){ $("#search-results").empty(); if( query.length < 2 ){ return; } var results = searchModule.search("*" + query + "*"); var listHtml = "<ul class='sidebar-menu'>"; listHtml += "<li class='header'>Type Results</li>"; if(results.length == 0 ){ listHtml += "<li>No results found</li>"; } else { for(var i = 0; i < results.length; ++i){ var res = results[i]; listHtml += "<li><a href='" + res.url + "'>" + htmlEscape(res.title) + "</a></li>"; } } listHtml += "</ul>"; $("#search-results").append(listHtml); } $(document).ready(function(){ $("#search").on('input propertychange paste', function() { runSearch($("#search").val()); }); }); function htmlEscape(html) { return document.createElement('div') .appendChild(document.createTextNode(html)) .parentNode .innerHTML; } </script> <hr> <ul class="sidebar-menu"> <li class="header">Namespace</li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics">StrideToolkit<wbr>.Mathematics</a></li> <li class="header">Type</li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx">MathUtilEx</a></li> <li role="separator" class="divider"></li> <li class="header">Method Members</li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx/CF5F15B4">CeilingToInt<wbr>(float)<wbr></a></li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx/D8B6E4B4">Clamp01<wbr>(float)<wbr></a></li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx/A6316132">FloorToInt<wbr>(float)<wbr></a></li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx/A8639173">Interpolate<wbr>(float, <wbr>float, <wbr>float, <wbr>EasingFunction)<wbr></a></li> <li class="selected"><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx/A9859409">Interpolate<wbr>(Vector2, <wbr>Vector2, <wbr>float, <wbr>EasingFunction, <wbr>Vector2)<wbr></a></li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx/FB432B9B">Interpolate<wbr>(Vector2, <wbr>Vector2, <wbr>float, <wbr>EasingFunction)<wbr></a></li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx/F8BA550B">Interpolate<wbr>(Vector3, <wbr>Vector3, <wbr>float, <wbr>EasingFunction, <wbr>Vector3)<wbr></a></li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx/79C36B03">Interpolate<wbr>(Vector3, <wbr>Vector3, <wbr>float, <wbr>EasingFunction)<wbr></a></li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx/4F061207">Interpolate<wbr>(Vector4, <wbr>Vector4, <wbr>float, <wbr>EasingFunction, <wbr>Vector4)<wbr></a></li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx/754C4A7C">Interpolate<wbr>(Vector4, <wbr>Vector4, <wbr>float, <wbr>EasingFunction)<wbr></a></li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx/1936ACEB">Interpolate<wbr>(Color, <wbr>Color, <wbr>float, <wbr>EasingFunction, <wbr>Color)<wbr></a></li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx/907AFB42">Interpolate<wbr>(Color, <wbr>Color, <wbr>float, <wbr>EasingFunction)<wbr></a></li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx/7E770CD4">LookRotation<wbr>(Vector3, <wbr>Vector3, <wbr>Vector3, <wbr>Quaternion)<wbr></a></li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx/8FC87DE6">LookRotation<wbr>(Vector3, <wbr>Vector3, <wbr>Vector3)<wbr></a></li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx/4891755F">Orthonormalize<wbr>(Vector3, <wbr>Vector3)<wbr></a></li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx/7290798F">RoundToInt<wbr>(float)<wbr></a></li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx/62A7BD1C">ToQuaternion<wbr>(Vector3, <wbr>Quaternion)<wbr></a></li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx/AB32D4EF">ToQuaternion<wbr>(Vector3)<wbr></a></li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx/A482218F">ToRotationEulerXYZ<wbr>(Quaternion, <wbr>Vector3)<wbr></a></li> <li><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx/3C816E77">ToRotationEulerXYZ<wbr>(Quaternion)<wbr></a></li> </ul> </section> </aside> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <section class="content-header"> <h3><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx">MathUtilEx</a>.</h3> <h1>Interpolate<wbr>(Vector2, <wbr>Vector2, <wbr>float, <wbr>EasingFunction, <wbr>Vector2)<wbr> <small>Method</small></h1> </section> <section class="content"> <h1 id="Summary">Summary</h1> <div class="lead"> Performs an interpolation between two vectors using an easing function. </div> <div class="panel panel-default"> <div class="panel-body"> <dl class="dl-horizontal"> <dt>Namespace</dt> <dd><a href="/StrideToolkit/api/StrideToolkit.Mathematics">StrideToolkit<wbr>.Mathematics</a></dd> <dt>Containing Type</dt> <dd><a href="/StrideToolkit/api/StrideToolkit.Mathematics/MathUtilEx">MathUtilEx</a></dd> </dl> </div> </div> <h1 id="Syntax">Syntax</h1> <pre><code>[MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Interpolate(ref Vector2 start, ref Vector2 end, float amount, EasingFunction easingFunction, out Vector2 result)</code></pre> <h1 id="Remarks">Remarks</h1> <div> Passing <span name="amount" class="paramref">amount</span> a value of 0 will cause <span name="start" class="paramref">start</span> to be returned; a value of 1 will cause <span name="end" class="paramref">end</span> to be returned. </div> <h1 id="Attributes">Attributes</h1> <div class="box"> <div class="box-body no-padding table-responsive"> <table class="table table-striped table-hover two-cols"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody><tr> <td>MethodImplAttribute</td> <td></td> </tr> </tbody></table> </div> </div> <h1 id="Parameters">Parameters</h1> <div class="box"> <div class="box-body no-padding table-responsive"> <table class="table table-striped table-hover three-cols"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr> </thead> <tbody><tr> <td>start</td> <td>Vector2</td> <td>Start vector.</td> </tr> <tr> <td>end</td> <td>Vector2</td> <td>End vector.</td> </tr> <tr> <td>amount</td> <td>float</td> <td>Value between 0 and 1 indicating the weight of <span name="end" class="paramref">end</span>.</td> </tr> <tr> <td>easingFunction</td> <td><a href="/StrideToolkit/api/StrideToolkit.Mathematics/EasingFunction">EasingFunction</a></td> <td>The function used to ease the interpolation.</td> </tr> <tr> <td>result</td> <td>Vector2</td> <td>When the method completes, contains the interpolation of the two vectors.</td> </tr> </tbody></table> </div> </div> <h1 id="ReturnValue">Return Value</h1> <div class="box"> <div class="box-body no-padding table-responsive"> <table class="table table-striped table-hover two-cols"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody><tr> <td>void</td> <td></td> </tr> </tbody></table> </div> </div> </section> </div> <!-- Footer --> <footer class="main-footer"> </footer> </div> <div class="wrapper bottom-wrapper"> <footer class="bottom-footer"> <p class="text-muted"> <a href="https://github.com/dfkeenan/StrideToolkit"><i class="fa fa-github"></i> GitHub</a> | <a href="https://twitter.com/dfkeenan"><i class="fa fa-twitter"></i> Twitter</a> <br> Copyright © Daniel Keenan. <br> Generated by <a href="http://wyam.io">Wyam</a> </p> <script> anchors.add(); </script> </footer> </div> <a href="javascript:" id="return-to-top"><i class="fa fa-chevron-up"></i></a> <script> // Close the sidebar if we select an anchor link $(".main-sidebar a[href^='#']:not('.expand')").click(function(){ $(document.body).removeClass('sidebar-open'); }); $(document).ready(function() { mermaid.initialize( { flowchart: { useMaxWidth: false }, startOnLoad: false, cloneCssStyles: false }); mermaid.init(undefined, ".mermaid"); // Remove the max-width setting that Mermaid sets var mermaidSvg = $('.mermaid svg'); mermaidSvg.addClass('img-responsive'); mermaidSvg.css('max-width', ''); // Make it scrollable var target = document.querySelector(".mermaid svg"); if(target !== null) { var panZoom = window.panZoom = svgPanZoom(target, { zoomEnabled: true, controlIconsEnabled: true, fit: true, center: true, maxZoom: 20, zoomScaleSensitivity: 0.6 }); // Do the reset once right away to fit the diagram panZoom.resize(); panZoom.fit(); panZoom.center(); $(window).resize(function(){ panZoom.resize(); panZoom.fit(); panZoom.center(); }); } $('pre code').each(function(i, block) { hljs.highlightBlock(block); }); }); hljs.initHighlightingOnLoad(); // Back to top $(window).scroll(function() { if ($(this).scrollTop() >= 200) { // If page is scrolled more than 50px $('#return-to-top').fadeIn(1000); // Fade in the arrow } else { $('#return-to-top').fadeOut(1000); // Else fade out the arrow } }); $('#return-to-top').click(function() { // When arrow is clicked $('body,html').animate({ scrollTop : 0 // Scroll to top of body }, 500); }); </script> </body></html>
<?php /** * Store your app related helpers in this file. * You can access them in your Controllers, Views and Models. */
.locked .form-content { pointer-events: none; filter: blur(3px); opacity: .7; } .locker { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: 80%; text-align: center; }
import { defaultAction, } from '../actions'; import { DEFAULT_ACTION, } from '../constants'; describe('Marginals actions', () => { describe('Default Action', () => { it('has a type of DEFAULT_ACTION', () => { const expected = { type: DEFAULT_ACTION, }; expect(defaultAction()).toEqual(expected); }); }); });
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("thirdProblem")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("thirdProblem")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b4573fd0-d91b-4158-b943-1a7d4a343eac")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
/* * Fiahil * 12.05.2012 */ #if !defined(__Bomberman_Bonus_h) #define __Bomberman_Bonus_h #include <Model.hpp> #include "enum.hpp" #include "AObj.hpp" class Bonus : public AObj { public: Bonus(BonusType::eBonus t, Point const&, gdl::Model&); virtual ~Bonus(); private: BonusType::eBonus _type; gdl::Model& _model; public: BonusType::eBonus getType(void) const; void initialize(void); void draw(); void update(gdl::GameClock const&, gdl::Input&); }; #endif
//A simple build file using the tests directory for requirejs { baseUrl: "../../../requirejs/tests/text", paths: { text: "../../../requirejs/../text/text" }, dir: "builds/text", optimize: "none", optimizeAllPluginResources: true, modules: [ { name: "widget" } ] }
#include "DirectFormOscillator.h" using namespace DSP; DirectFormOscillator::DirectFormOscillator(){ init = false; } void DirectFormOscillator::setFrequency(float frequency, float sampleRate){ if(fo != frequency){ flush(); fo = frequency; } fs = sampleRate; theta = 2 * PI * fo / fs; b1 = -2 * cosf(theta); b2 = 1.0f; if(!init){ yn1 = sinf(-1 * theta); yn2 = sinf(-2 * theta); init = true; } } float DirectFormOscillator::getNextSample(float input){ float output = - (b1 * yn1) - (b2 * yn2); yn2 = yn1; yn1 = output; return output; } void DirectFormOscillator::flush(){ yn1 = yn2 = 0; init = false; }
namespace BankAccountApp.MSTests.Integration { using System; using Bank; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public sealed class IntegrationTest { private readonly AccountRepository _accountRepository = new AccountRepository(); [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void ExistingAccount_AccountRepository_CanDeleteSavedAccount() { // Given const string accountName = "Foo"; // When var result = this._accountRepository.Delete(accountName); // Then Assert.IsTrue(result); this._accountRepository.Get(accountName); // Expect exception } [TestMethod] public void ExistingAccount_AccountRepository_CanRetrieveSavedAccount() { // Given const string accountName = "Foo"; // When var account = this._accountRepository.Get(accountName); // Then Assert.AreEqual(account.Name, accountName); } [TestMethod] public void NewAccount_AccountRepository_CanSaveAccount() { // Given var account = new Account("Foo", 10); // When this._accountRepository.Add(account); // Then var persisted = this._accountRepository.Get("Foo"); Assert.AreEqual(account, persisted); } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void NonExistingAccount_AccountRepository_GetThrows() { // Given const string accountName = "Foo"; // When / Then this._accountRepository.Get(accountName); } } }
<!DOCTYPE html><html><head><title>http://sanjeevkpandit.github.io/categories/development/</title><link rel="canonical" href="http://sanjeevkpandit.github.io/categories/development/"/><meta name="robots" content="noindex"><meta charset="utf-8" /><meta http-equiv="refresh" content="0; url=http://sanjeevkpandit.github.io/categories/development/" /></head></html>
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Arc.Grammar.Tokens { public sealed class EndOfInputToken : IToken { } }
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'stylescombo', 'no', { label: 'Stil', panelTitle: 'Stilformater', panelTitle1: 'Blokkstiler', panelTitle2: 'Inlinestiler', panelTitle3: 'Objektstiler' } );
//Language: GNU C++ /** Be name Khoda **/ #include <iostream> #include <iomanip> #include <fstream> #include <sstream> #include <map> #include <vector> #include <list> #include <set> #include <queue> #include <deque> #include <algorithm> #include <bitset> #include <cstring> #include <cstdio> #include <cstdlib> #include <cctype> #include <cmath> #include <climits> using namespace std; #define ll long long #define un unsigned #define pii pair<ll, ll> #define pb push_back #define mp make_pair #define VAL(x) #x << " = " << x << " " #define SQR(a) ((a) * (a)) #define SZ(x) ((int) x.size()) #define ALL(x) x.begin(), x.end() #define CLR(x, a) memset(x, a, sizeof x) #define FOREACH(i, x) for(__typeof((x).begin()) i = (x).begin(); i != (x).end(); i ++) #define X first #define Y second #define PI (3.141592654) //#define cout fout //#define cin fin //ifstream fin("problem.in"); //ofstream fout("problem.out"); const int MAXN = 100 * 1000 + 10, INF = INT_MAX, MOD = 1e9 + 7; ll a[MAXN]; int main () { ios::sync_with_stdio(false); ll n, m; cin >> n >> m; for (int i = 0, t; i < m; i ++) cin >> t >> a[i]; sort(a, a + m, greater<int>()); ll ans = 0; for (ll i = 0; i < m; i ++) { if (!(i % 2) && n - 1 < i * (i + 1) / 2) break; if ((i % 2) && n < SQR(i + 1) / 2) break; ans += a[i]; } cout << ans << endl; return 0; }