text:
package com.intellij.codeInsight.unwrap;

import com.intellij.psi.*;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.Nls;

public abstract class JavaUnwrapper extends AbstractUnwrapper<JavaUnwrapper.Context> {

  public JavaUnwrapper(@Nls String description) {
    super(description);
  }

  @Override
  protected Context createContext() {
    return new Context();
  }

  protected static class Context extends AbstractUnwrapper.AbstractContext {

    public void extractFromBlockOrSingleStatement(PsiStatement block, PsiElement from) throws IncorrectOperationException {
      if (block instanceof PsiBlockStatement) {
        extractFromCodeBlock(((PsiBlockStatement)block).getCodeBlock(), from);
      }
      else if (block != null && !(block instanceof PsiEmptyStatement)) {
        extract(block, block, from);
      }
    }

    public void extractFromCodeBlock(PsiCodeBlock block, PsiElement from) throws IncorrectOperationException {
      if (block == null) return;
      extract(block.getFirstBodyElement(), block.getLastBodyElement(), from);
    }

    public void setElseBranch(PsiIfStatement ifStatement, PsiStatement elseBranch) throws IncorrectOperationException {
      PsiStatement toExtract = elseBranch;
      if (myIsEffective) {
        ifStatement.setElseBranch(copyElement(elseBranch));
        toExtract = ifStatement.getElseBranch();
      }
      addElementToExtract(toExtract);
    }

    @Override
    protected boolean isWhiteSpace(PsiElement element) {
      return element instanceof PsiWhiteSpace;
    }

    private static PsiStatement copyElement(PsiStatement e) throws IncorrectOperationException {
      // We cannot call el.copy() for 'else' since it sets context to parent 'if'.
      // This causes copy to be invalidated after parent 'if' is removed by setElseBranch method.
      PsiElementFactory factory = JavaPsiFacade.getElementFactory(e.getProject());
      return factory.createStatementFromText(e.getText(), null);
    }

    public void setInitializer(PsiVariable variable, PsiExpression returnValue) {
      PsiExpression toExtract = returnValue;
      if (myIsEffective) {
        final PsiExpression initializer = copyExpression(returnValue);
        variable.setInitializer(initializer);
        toExtract = variable.getInitializer();
      }
      addElementToExtract(toExtract);
    }

    private static PsiExpression copyExpression(PsiExpression returnValue) {
      return JavaPsiFacade.getElementFactory(returnValue.getProject()).createExpressionFromText(returnValue.getText(), null);
    }
  }
}


text:
package com.stackify.api;

import org.junit.Assert;
import org.junit.Test;

import java.util.Collections;
import java.util.Date;
import java.util.Map;

/**
 * StackifyError JUnit Test
 *
 * @author Eric Martin
 */
public class StackifyErrorTest {

    /**
     * testBuilder
     */
    @Test
    public void testBuilder() {
        EnvironmentDetail environment = EnvironmentDetail.newBuilder().build();
        Date timeStamp = new Date();
        ErrorItem errorDetail = ErrorItem.newBuilder().build();
        WebRequestDetail webRequestDetail = WebRequestDetail.newBuilder().build();
        Map<String, String> serverVariables = Collections.singletonMap("serverKey", "serverValue");
        String customerName = "customerName";
        String userName = "userName";

        StackifyError.Builder builder = StackifyError.newBuilder();
        builder.environmentDetail(environment);
        builder.occurredEpochMillis(timeStamp.getTime());
        builder.error(errorDetail);
        builder.webRequestDetail(webRequestDetail);
        builder.serverVariables(serverVariables);
        builder.customerName(customerName);
        builder.userName(userName);
        StackifyError stackifyError = builder.build();

        Assert.assertNotNull(stackifyError);

        Assert.assertEquals(environment, stackifyError.getEnvironmentDetail());
        Assert.assertEquals(timeStamp.getTime(), (long) stackifyError.getOccurredEpochMillis());
        Assert.assertEquals(errorDetail, stackifyError.getError());
        Assert.assertEquals(webRequestDetail, stackifyError.getWebRequestDetail());
        Assert.assertEquals(serverVariables, stackifyError.getServerVariables());
        Assert.assertEquals(customerName, stackifyError.getCustomerName());
        Assert.assertEquals(userName, stackifyError.getUserName());

        StackifyError stackifyErrorCopy = stackifyError.toBuilder().build();

        Assert.assertNotNull(stackifyErrorCopy);

        Assert.assertEquals(environment, stackifyErrorCopy.getEnvironmentDetail());
        Assert.assertEquals(timeStamp.getTime(), (long) stackifyErrorCopy.getOccurredEpochMillis());
        Assert.assertEquals(errorDetail, stackifyErrorCopy.getError());
        Assert.assertEquals(webRequestDetail, stackifyErrorCopy.getWebRequestDetail());
        Assert.assertEquals(serverVariables, stackifyErrorCopy.getServerVariables());
        Assert.assertEquals(customerName, stackifyErrorCopy.getCustomerName());
        Assert.assertEquals(userName, stackifyErrorCopy.getUserName());
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.example.firstapp;
import android.content.Context;
import android.os.RemoteException;

import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import androidx.test.uiautomator.UiDevice;
import androidx.test.uiautomator.By;
import androidx.test.uiautomator.UiObject2;
import androidx.test.uiautomator.UiObjectNotFoundException;
import androidx.test.uiautomator.Until;

import java.io.IOException;

import static java.lang.Thread.sleep;

import static org.junit.Assert.*;

/**
 * Instrumented test, which will execute on an Android device.
 *
 * @see Testing documentation
 */
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {

    private static final String BASIC_SAMPLE_PACKAGE = "com.example.firstapp";
    private static final int TIMEOUT = 5000;

    //target value for searchForTargetNumber()
    private static Integer TARGET = 2;
    //Celebration message to be displayed when target is found
    private static String CELEBRATION = "YAYYYY! " + TARGET + "!!";

    private ShellUtility shellUtility;

    @Before
    public void getDevice() {
        shellUtility = new ShellUtility(TIMEOUT);
    }

    @Test
    public void useAppContext() {
        // Context of the app under test.
        Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
        assertEquals("com.example.firstapp", appContext.getPackageName());
    }

    @Test
    public void searchForTargetNumber() throws InterruptedException, IOException, RemoteException, UiObjectNotFoundException {
        shellUtility.launchApp(BASIC_SAMPLE_PACKAGE);

        Integer val = -1;
        //Keep getting random values in the range [0, TARGET] until TARGET comes up
        while (val != TARGET) {
            //wait for count and random buttons to appear on screen
            UiObject2 countButton = shellUtility.device.wait(Until.findObject(By.res(BASIC_SAMPLE_PACKAGE, "count_button")),TIMEOUT);
            UiObject2 randomButton = shellUtility.device.wait(Until.findObject(By.res(BASIC_SAMPLE_PACKAGE,"random_button")), TIMEOUT);

            int count = TARGET;
            while (count-- != 0) countButton.click();
            //get random number in range [0, counter] (counter is now TARGET)
            randomButton.click();
            UiObject2 randomText = shellUtility.device.wait(Until.findObject(By.res(BASIC_SAMPLE_PACKAGE, "textview_random")), TIMEOUT );
            UiObject2 previousButton = shellUtility.device.wait(Until.findObject(By.res(BASIC_SAMPLE_PACKAGE, "button_second")),TIMEOUT);

            //ensure that random produced a value in the appropriate range
            val = Integer.parseInt((randomText.getText()));
            assert(0 <= val && val <= TARGET);

            //go back to first fragment
            previousButton.click();
        }
        //display CELEBRATION message and make sure it appears on the screen
        sleep(1000);
        UiObject2 sentimentText = shellUtility.device.wait(Until.findObject(By.res(BASIC_SAMPLE_PACKAGE, "plaintext_sentiment")),TIMEOUT);
        sentimentText.setText(CELEBRATION);
        assertEquals(CELEBRATION, sentimentText.getText());
        sleep(1000);

        //Can we use old UIObjects after leaving a fragment and returning?

    }

}


text:
[![Build Status](https://travis-ci.org/TerrySoba/retro-game.svg?branch=master)](https://travis-ci.org/TerrySoba/retro-game)

# retro-game
Experiments using [libretro](https://www.libretro.com/).

This is supposed to become a simple arcade style game.
It is also supposed to become a tutorial on how to design a
simple game using libretro.

##Building the Game
The game is being developed using Linux.
It may or may not run using Windows.

The game is built using cmake.
In the base directory type:
```
cmake . && make
```
Now the game should be built.

For windows follow these instructions: [Building on Windows](win32_build.md)

##Running the Game
To run the game you need to install [Retroarch](https://www.libretro.com/index.php/retroarch-2/).
On Ubuntu type:
```
sudo apt-get install retroarch
```

When retroarch is installed, you can play the game using the commandline
```
retroarch -L libRetroGame.so
```
while in the build directory.

##Using Blender to create Pixel Graphics
I mainly use [Blender](http://blender.org) to create the assets for the game.
Here is a small [tutorial](./doc/blender_tutorial.md) on how to use Blender to create pixel graphics.


text:
NES_ID = [0x4e, 0x45, 0x53, 0x1a]

class Cartridge(object):

    def __init__(self):
        self.banks = {}
        self.bank_id = 0
        self.pc = 0
        self.inespgr = 1
        self.ineschr = 1
        self.inesmap = 1
        self.inesmir = 1
        self.rs = 0
        self.path = ''

    def nes_get_header(self):
        unused = [0, 0, 0, 0, 0, 0, 0, 0]
        header = []
        header.extend(NES_ID)
        header.append(self.inespgr)
        header.append(self.ineschr)
        header.append(self.inesmir)
        header.append(self.inesmap)
        header.extend(unused)
        return header

    def set_iNES_prg(self, inespgr):
        self.inespgr = inespgr

    def set_iNES_chr(self, ineschr):
        self.ineschr = ineschr

    def set_iNES_map(self, inesmap):
        self.inesmap = inesmap

    def set_iNES_mir(self, inesmir):
        self.inesmir = inesmir

    def set_bank_id(self, _id):
        if _id not in self.banks:
            self.banks[_id] = dict(code=[], start=None, size=(1024 * 8))
        self.bank_id = _id

    def set_org(self, org):
        if self.bank_id not in self.banks:
            self.set_bank_id(self.bank_id)
        if not self.banks[self.bank_id]['start']:
            self.banks[self.bank_id]['start'] = org
            self.pc = org
        else:
            while self.pc < org:
                self.append_code([0xff])
            self.pc = org

    def append_code(self, code):
        if self.bank_id not in self.banks:
            self.set_bank_id(self.bank_id)
        for c in code:
            assert c <= 0xff
        self.banks[self.bank_id]['code'].extend(code)
        self.pc += len(code)

    def get_code(self):
        if self.bank_id not in self.banks:
            self.set_bank_id(self.bank_id)
        return self.banks[self.bank_id]['code']

    def get_ines_code(self):
        if self.bank_id not in self.banks:
            self.set_bank_id(self.bank_id)
        opcodes = []
        nes_header = self.nes_get_header()
        opcodes.extend(nes_header)
        try:
            _values = self.banks.itervalues
        except AttributeError:
            _values = self.banks.values
        for bank in _values():
            for _ in range(len(bank['code']), bank['size']):
                bank['code'].append(0xff)
            opcodes.extend(bank['code'])
        return opcodes


text:
This repository contains the OPL2 / OPL3 audio library for the OPL2 Audio Board or OPL3 Duo! board. It is compatible with Arduino, Teensy, Raspberry Pi and other Arduino-like boards. A number of examples are included on how the library can be used. You can use the OPL2 Audio Board or OPL3 Duo! to:
* Experiment with the YM3812 or YMF262 chip
* Build your own synthesizer
* Play your own OPL2 tunes
* Instrument definitions from Adlib and The Fat Man are included in the library for both 2-op OPL3 and 4-op OPL3.
* Play exported OPL2 music (DRO, IMF, VGM) or Reality Adlib Tracker music files
* Use the board as a MIDI synthesizer (Teensy++ 2.0 and later example included)
* Emulation with DosBox; you can use the board to output MIDI music (Teensy++ 2.0 and later)
* Use the board directly as a synthesizer by using the [OPL3BankEditor](https://github.com/Wohlstand/OPL3BankEditor) software by Wohlstand

Current library version is 2.1.2, 7th March 2022

### OPL2 Audio Board
The OPL2 Audio Board is fun and easy board to get started with an OPL2 synthesizer. It is built around the YM3812 OPL2 chip that gives you 9 channels with 2-operators each to produce the classic OPL2 sound that you may remember from early 90s computer games.
For more info visit the [Hackaday project page](https://hackaday.io/project/18995-opl2-audio-board-for-arduino-raspberry-pi).

To obtain your own OPL2 Audio Board visit my [Tindie store](https://www.tindie.com/products/DhrBaksteen/opl2-audio-board/).
![](https://raw.githubusercontent.com/DhrBaksteen/ArduinoOPL2/master/extra/OPL2_board.jpg)

### OPL3 Duo! Board
The OPL3 Duo! is a more capable version of the OPL2 Audio Board. It has 2 YMF262 OPL3 chips that allow for up to 36 channels of 2-operator sounds or up to 12 4-operator + 12 2-operator sounds. It also has stereo sound and is fully OPL2 compatible. Each OPL3 chip can be controlled individually or the library can control the board as if it were one big OPL3 chip with 36 channels.

The OPL3 Duo! board is available on my [Tindie store](https://www.tindie.com/products/cheerful/opl3-duo/).
![](https://raw.githubusercontent.com/DhrBaksteen/ArduinoOPL2/master/extra/OPL3Duo_board.jpg)

## 1. Installing the library
#### Arduino / Teensy
The easiest way to install the library it do download it through the Arduino Library Manager. Open the Library Manager from your Arduino IDE's Sketch > Include Library > Library Manager menu. A new window will open that allows you to search for a library. Search for 'Arduino OPL2' and it should show this libarary. Select the library, click the install button and you're good to go.

Alternatively you can clone this repo in the `libraries` folder of the Arduino IDE. or you can download the zip file and extract it in the libraries folder.

For more information see the [instructions](https://www.arduino.cc/en/Guide/Libraries) on the Arduino website.

#### Raspberry Pi / Orange Pi and compatibles
To install the library onto your Pi clone this repo and run `./build`. The OPL2 library requires [WiringPi](http://wiringpi.com/) to be installed on your Pi. Normally this library is already installed, but if this is not the case then the build script can install it for you.


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `StaticMutex` struct in crate `std`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, StaticMutex">

    <title>std::sync::StaticMutex - Rust</title>

    <link rel="stylesheet" type="text/css" href="../../main.css">

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

std::<wbr>sync

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Struct std::<wbr>sync::<wbr>StaticMutex<wbr>Unstable
            [-] [+]
        [src]

pub struct StaticMutex {
    // some fields omitted
}

The static mutex type is provided to allow for static allocation of mutexes.

Note that this is a separate type because using a Mutex correctly means that
it needs to have a destructor run. In Rust, statics are not allowed to have
destructors. As a result, a StaticMutex has one extra method when compared
to a Mutex, a destroy method. This method is unsafe to call, and
documentation can be found directly on the method.

Example
fn main() {
    use std::sync::{StaticMutex, MUTEX_INIT};

    static LOCK: StaticMutex = MUTEX_INIT;

    {
        let _g = LOCK.lock().unwrap();
        // do some productive work
    }
    // lock is unlocked here.
}

use std::sync::{StaticMutex, MUTEX_INIT};

static LOCK: StaticMutex = MUTEX_INIT;

{
    let _g = LOCK.lock().unwrap();
    // do some productive work
}
// lock is unlocked here.

Methods

impl StaticMutex

fn lock(&'static self) -> LockResult<MutexGuard<()>>

Acquires this lock, see Mutex::lock

fn try_lock(&'static self) -> TryLockResult<MutexGuard<()>>

Attempts to grab this lock, see Mutex::try_lock

unsafe fn destroy(&'static self)

Deallocates resources associated with this static mutex.

This method is unsafe because it provides no guarantees that there are
no active users of this mutex, and safety is not guaranteed if there are
active users of this mutex.

This method is required to ensure that there are no memory leaks on
all platforms. It may be the case that some platforms do not leak
memory if this method is not called, but this is not guaranteed to be
true on all platforms.

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).


text:
/*
* Public Key Interface
* (C) 1999-2010 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#ifndef BOTAN_PUBKEY_H_
#define BOTAN_PUBKEY_H_

#include <botan/pk_keys.h>
#include <botan/pk_ops_fwd.h>
#include <botan/symkey.h>
#include <string>

#if defined(BOTAN_HAS_SYSTEM_RNG)
  #include <botan/system_rng.h>
  #define BOTAN_PUBKEY_INCLUDE_DEPRECATED_CONSTRUCTORS
#endif

namespace Botan {

class RandomNumberGenerator;

/**
* Public Key Encryptor
* This is the primary interface for public key encryption
*/
class BOTAN_PUBLIC_API(2,0) PK_Encryptor
   {
   public:

      /**
      * Encrypt a message.
      * @param in the message as a byte array
      * @param length the length of the above byte array
      * @param rng the random number source to use
      * @return encrypted message
      */
      std::vector<uint8_t> encrypt(const uint8_t in[], size_t length,
                                 RandomNumberGenerator& rng) const
         {
         return enc(in, length, rng);
         }

      /**
      * Encrypt a message.
      * @param in the message
      * @param rng the random number source to use
      * @return encrypted message
      */
      template<typename Alloc>
      std::vector<uint8_t> encrypt(const std::vector<uint8_t, Alloc>& in,
                                RandomNumberGenerator& rng) const
         {
         return enc(in.data(), in.size(), rng);
         }

      /**
      * Return the maximum allowed message size in bytes.
      * @return maximum message size in bytes
      */
      virtual size_t maximum_input_size() const = 0;

      /**
      * Return an upper bound on the ciphertext length
      */
      virtual size_t ciphertext_length(size_t ctext_len) const = 0;

      PK_Encryptor() = default;
      virtual ~PK_Encryptor() = default;

      PK_Encryptor(const PK_Encryptor&) = delete;
      PK_Encryptor& operator=(const PK_Encryptor&) = delete;

   private:
      virtual std::vector<uint8_t> enc(const uint8_t[], size_t,
                                    RandomNumberGenerator&) const = 0;
   };

/**
* Public Key Decryptor
*/
class BOTAN_PUBLIC_API(2,0) PK_Decryptor
   {
   public:
      /**
      * Decrypt a ciphertext, throwing an exception if the input
      * seems to be invalid (eg due to an accidental or malicious
      * error in the ciphertext).
      *
      * @param in the ciphertext as a byte array
      * @param length the length of the above byte array
      * @return decrypted message
      */
      secure_vector<uint8_t> decrypt(const uint8_t in[], size_t length) const;

      /**
      * Same as above, but taking a vector
      * @param in the ciphertext
      * @return decrypted message
      */
      template<typename Alloc>
      secure_vector<uint8_t> decrypt(const std::vector<uint8_t, Alloc>& in) const
         {
         return decrypt(in.data(), in.size());
         }

      /**
      * Decrypt a ciphertext. If the ciphertext is invalid (eg due to
      * invalid padding) or is not the expected length, instead
      * returns a random string of the expected length. Use to avoid
      * oracle attacks, especially against PKCS #1 v1.5 decryption.
      */
      secure_vector<uint8_t>
      decrypt_or_random(const uint8_t in[],
                        size_t length,
                        size_t expected_pt_len,
                        RandomNumberGenerator& rng) const;

      /**
      * Decrypt a ciphertext. If the ciphertext is invalid (eg due to
      * invalid padding) or is not the expected length, instead
      * returns a random string of the expected length. Use to avoid
      * oracle attacks, especially against PKCS #1 v1.5 decryption.
      *
      * Additionally checks (also in const time) that:
      *    contents[required_content_offsets[i]] == required_content_bytes[i]
      * for 0 <= i < required_contents
      *
      * Used for example in TLS, which encodes the client version in
      * the content bytes: if there is any timing variation the version
      * check can be used as an oracle to recover the key.
      */
      secure_vector<uint8_t>
      decrypt_or_random(const uint8_t in[],
                        size_t length,
                        size_t expected_pt_len,
                        RandomNumberGenerator& rng,
                        const uint8_t required_content_bytes[],
                        const uint8_t required_content_offsets[],
                        size_t required_contents) const;

      /**
      * Return an upper bound on the plaintext length for a particular
      * ciphertext input length
      */
      virtual size_t plaintext_length(size_t ctext_len) const = 0;

      PK_Decryptor() = default;
      virtual ~PK_Decryptor() = default;

      PK_Decryptor(const PK_Decryptor&) = delete;
      PK_Decryptor& operator=(const PK_Decryptor&) = delete;

   private:
      virtual secure_vector<uint8_t> do_decrypt(uint8_t& valid_mask,
                                             const uint8_t in[], size_t in_len) const = 0;
   };

/**
* Public Key Signer. Use the sign_message() functions for small
* messages. Use multiple calls update() to process large messages and
* generate the signature by finally calling signature().
*/
class BOTAN_PUBLIC_API(2,0) PK_Signer final
   {
   public:

      /**
      * Construct a PK Signer.
      * @param key the key to use inside this signer
      * @param rng the random generator to use
      * @param emsa the EMSA to use
      * An example would be "EMSA1(SHA-224)".
      * @param format the signature format to use
      * @param provider the provider to use
      */
      PK_Signer(const Private_Key& key,
                RandomNumberGenerator& rng,
                const std::string& emsa,
                Signature_Format format = IEEE_1363,
                const std::string& provider = "");

#if defined(BOTAN_PUBKEY_INCLUDE_DEPRECATED_CONSTRUCTORS)
      /**
      * Construct a PK Signer.
      * @param key the key to use inside this signer
      * @param emsa the EMSA to use
      * An example would be "EMSA1(SHA-224)".
      * @param format the signature format to use
      */
      BOTAN_DEPRECATED("Use constructor taking a RNG object")
      PK_Signer(const Private_Key& key,
                const std::string& emsa,
                Signature_Format format = IEEE_1363,
                const std::string& provider = "") :
         PK_Signer(key, system_rng(), emsa, format, provider)
         {}
#endif

      ~PK_Signer();

      PK_Signer(const PK_Signer&) = delete;
      PK_Signer& operator=(const PK_Signer&) = delete;

      /**
      * Sign a message all in one go
      * @param in the message to sign as a byte array
      * @param length the length of the above byte array
      * @param rng the rng to use
      * @return signature
      */
      std::vector<uint8_t> sign_message(const uint8_t in[], size_t length,
                                     RandomNumberGenerator& rng)
         {
         this->update(in, length);
         return this->signature(rng);
         }

      /**
      * Sign a message.
      * @param in the message to sign
      * @param rng the rng to use
      * @return signature
      */
      template<typename Alloc>
         std::vector<uint8_t> sign_message(const std::vector<uint8_t, Alloc>& in,
                                           RandomNumberGenerator& rng)
         {
         return sign_message(in.data(), in.size(), rng);
         }

      /**
      * Add a message part (single byte).
      * @param in the byte to add
      */
      void update(uint8_t in) { update(&in, 1); }

      /**
      * Add a message part.
      * @param in the message part to add as a byte array
      * @param length the length of the above byte array
      */
      void update(const uint8_t in[], size_t length);

      /**
      * Add a message part.
      * @param in the message part to add
      */
      template<typename Alloc>
      void update(const std::vector<uint8_t, Alloc>& in)
         {
         update(in.data(), in.size());
         }

      /**
      * Add a message part.
      * @param in the message part to add
      */
      void update(const std::string& in)
         {
         update(cast_char_ptr_to_uint8(in.data()), in.size());
         }

      /**
      * Get the signature of the so far processed message (provided by the
      * calls to update()).
      * @param rng the rng to use
      * @return signature of the total message
      */
      std::vector<uint8_t> signature(RandomNumberGenerator& rng);

      /**
      * Set the output format of the signature.
      * @param format the signature format to use
      */
      void set_output_format(Signature_Format format) { m_sig_format = format; }

      /**
      * Return an upper bound on the length of the signatures this
      * PK_Signer will produce
      */
      size_t signature_length() const;

   private:
      std::unique_ptr<PK_Ops::Signature> m_op;
      Signature_Format m_sig_format;
      size_t m_parts, m_part_size;
   };

/**
* Public Key Verifier. Use the verify_message() functions for small
* messages. Use multiple calls update() to process large messages and
* verify the signature by finally calling check_signature().
*/
class BOTAN_PUBLIC_API(2,0) PK_Verifier final
   {
   public:
      /**
      * Construct a PK Verifier.
      * @param pub_key the public key to verify against
      * @param emsa the EMSA to use (eg "EMSA3(SHA-1)")
      * @param format the signature format to use
      * @param provider the provider to use
      */
      PK_Verifier(const Public_Key& pub_key,
                  const std::string& emsa,
                  Signature_Format format = IEEE_1363,
                  const std::string& provider = "");

      ~PK_Verifier();

      PK_Verifier& operator=(const PK_Verifier&) = delete;
      PK_Verifier(const PK_Verifier&) = delete;

      /**
      * Verify a signature.
      * @param msg the message that the signature belongs to, as a byte array
      * @param msg_length the length of the above byte array msg
      * @param sig the signature as a byte array
      * @param sig_length the length of the above byte array sig
      * @return true if the signature is valid
      */
      bool verify_message(const uint8_t msg[], size_t msg_length,
                          const uint8_t sig[], size_t sig_length);
      /**
      * Verify a signature.
      * @param msg the message that the signature belongs to
      * @param sig the signature
      * @return true if the signature is valid
      */
      template<typename Alloc, typename Alloc2>
      bool verify_message(const std::vector<uint8_t, Alloc>& msg,
                          const std::vector<uint8_t, Alloc2>& sig)
         {
         return verify_message(msg.data(), msg.size(),
                               sig.data(), sig.size());
         }

      /**
      * Add a message part (single byte) of the message corresponding to the
      * signature to be verified.
      * @param in the byte to add
      */
      void update(uint8_t in) { update(&in, 1); }

      /**
      * Add a message part of the message corresponding to the
      * signature to be verified.
      * @param msg_part the new message part as a byte array
      * @param length the length of the above byte array
      */
      void update(const uint8_t msg_part[], size_t length);

      /**
      * Add a message part of the message corresponding to the
      * signature to be verified.
      * @param in the new message part
      */
      template<typename Alloc>
         void update(const std::vector<uint8_t, Alloc>& in)
         {
         update(in.data(), in.size());
         }

      /**
      * Add a message part of the message corresponding to the
      * signature to be verified.
      */
      void update(const std::string& in)
         {
         update(cast_char_ptr_to_uint8(in.data()), in.size());
         }

      /**
      * Check the signature of the buffered message, i.e. the one build
      * by successive calls to update.
      * @param sig the signature to be verified as a byte array
      * @param length the length of the above byte array
      * @return true if the signature is valid, false otherwise
      */
      bool check_signature(const uint8_t sig[], size_t length);

      /**
      * Check the signature of the buffered message, i.e. the one build
      * by successive calls to update.
      * @param sig the signature to be verified
      * @return true if the signature is valid, false otherwise
      */
      template<typename Alloc>
      bool check_signature(const std::vector<uint8_t, Alloc>& sig)
         {
         return check_signature(sig.data(), sig.size());
         }

      /**
      * Set the format of the signatures fed to this verifier.
      * @param format the signature format to use
      */
      void set_input_format(Signature_Format format);

   private:
      std::unique_ptr<PK_Ops::Verification> m_op;
      Signature_Format m_sig_format;
      size_t m_parts, m_part_size;
   };

/**
* Object used for key agreement
*/
class BOTAN_PUBLIC_API(2,0) PK_Key_Agreement final
   {
   public:

      /**
      * Construct a PK Key Agreement.
      * @param key the key to use
      * @param rng the random generator to use
      * @param kdf name of the KDF to use (or 'Raw' for no KDF)
      * @param provider the algo provider to use (or empty for default)
      */
      PK_Key_Agreement(const Private_Key& key,
                       RandomNumberGenerator& rng,
                       const std::string& kdf,
                       const std::string& provider = "");

#if defined(BOTAN_PUBKEY_INCLUDE_DEPRECATED_CONSTRUCTORS)
      /**
      * Construct a PK Key Agreement.
      * @param key the key to use
      * @param kdf name of the KDF to use (or 'Raw' for no KDF)
      * @param provider the algo provider to use (or empty for default)
      */
      BOTAN_DEPRECATED("Use constructor taking a RNG object")
      PK_Key_Agreement(const Private_Key& key,
                       const std::string& kdf,
                       const std::string& provider = "") :
         PK_Key_Agreement(key, system_rng(), kdf, provider)
         {}
#endif

      ~PK_Key_Agreement();

      // For ECIES
      PK_Key_Agreement& operator=(PK_Key_Agreement&&);
      PK_Key_Agreement(PK_Key_Agreement&&);

      PK_Key_Agreement& operator=(const PK_Key_Agreement&) = delete;
      PK_Key_Agreement(const PK_Key_Agreement&) = delete;

      /**
      * Perform Key Agreement Operation
      * @param key_len the desired key output size
      * @param in the other parties key
      * @param in_len the length of in in bytes
      * @param params extra derivation params
      * @param params_len the length of params in bytes
      */
      SymmetricKey derive_key(size_t key_len,
                              const uint8_t in[],
                              size_t in_len,
                              const uint8_t params[],
                              size_t params_len) const;

      /**
      * Perform Key Agreement Operation
      * @param key_len the desired key output size
      * @param in the other parties key
      * @param params extra derivation params
      * @param params_len the length of params in bytes
      */
      SymmetricKey derive_key(size_t key_len,
                              const std::vector<uint8_t>& in,
                              const uint8_t params[],
                              size_t params_len) const
         {
         return derive_key(key_len, in.data(), in.size(),
                           params, params_len);
         }

      /**
      * Perform Key Agreement Operation
      * @param key_len the desired key output size
      * @param in the other parties key
      * @param in_len the length of in in bytes
      * @param params extra derivation params
      */
      SymmetricKey derive_key(size_t key_len,
                              const uint8_t in[], size_t in_len,
                              const std::string& params = "") const
         {
         return derive_key(key_len, in, in_len,
                           cast_char_ptr_to_uint8(params.data()),
                           params.length());
         }

      /**
      * Perform Key Agreement Operation
      * @param key_len the desired key output size
      * @param in the other parties key
      * @param params extra derivation params
      */
      SymmetricKey derive_key(size_t key_len,
                              const std::vector<uint8_t>& in,
                              const std::string& params = "") const
         {
         return derive_key(key_len, in.data(), in.size(),
                           cast_char_ptr_to_uint8(params.data()),
                           params.length());
         }

      /**
      * Return the underlying size of the value that is agreed.
      * If derive_key is called with a length of 0 with a "Raw"
      * KDF, it will return a value of this size.
      */
      size_t agreed_value_size() const;

   private:
      std::unique_ptr<PK_Ops::Key_Agreement> m_op;
   };

/**
* Encryption using a standard message recovery algorithm like RSA or
* ElGamal, paired with an encoding scheme like OAEP.
*/
class BOTAN_PUBLIC_API(2,0) PK_Encryptor_EME final : public PK_Encryptor
   {
   public:
      size_t maximum_input_size() const override;

      /**
      * Construct an instance.
      * @param key the key to use inside the encryptor
      * @param rng the RNG to use
      * @param padding the message encoding scheme to use (eg "OAEP(SHA-256)")
      * @param provider the provider to use
      */
      PK_Encryptor_EME(const Public_Key& key,
                       RandomNumberGenerator& rng,
                       const std::string& padding,
                       const std::string& provider = "");

#if defined(BOTAN_PUBKEY_INCLUDE_DEPRECATED_CONSTRUCTORS)
      /**
      * Construct an instance.
      * @param key the key to use inside the encryptor
      * @param padding the message encoding scheme to use (eg "OAEP(SHA-256)")
      */
      BOTAN_DEPRECATED("Use constructor taking a RNG object")
      PK_Encryptor_EME(const Public_Key& key,
                       const std::string& padding,
                       const std::string& provider = "") :
         PK_Encryptor_EME(key, system_rng(), padding, provider) {}
#endif

      ~PK_Encryptor_EME();

      PK_Encryptor_EME& operator=(const PK_Encryptor_EME&) = delete;
      PK_Encryptor_EME(const PK_Encryptor_EME&) = delete;

      /**
      * Return an upper bound on the ciphertext length for a particular
      * plaintext input length
      */
      size_t ciphertext_length(size_t ptext_len) const override;
   private:
      std::vector<uint8_t> enc(const uint8_t[], size_t,
                             RandomNumberGenerator& rng) const override;

      std::unique_ptr<PK_Ops::Encryption> m_op;
   };

/**
* Decryption with an MR algorithm and an EME.
*/
class BOTAN_PUBLIC_API(2,0) PK_Decryptor_EME final : public PK_Decryptor
   {
   public:
     /**
      * Construct an instance.
      * @param key the key to use inside the decryptor
      * @param rng the random generator to use
      * @param eme the EME to use
      * @param provider the provider to use
      */
      PK_Decryptor_EME(const Private_Key& key,
                       RandomNumberGenerator& rng,
                       const std::string& eme,
                       const std::string& provider = "");

#if defined(BOTAN_PUBKEY_INCLUDE_DEPRECATED_CONSTRUCTORS)
      /**
      * Construct an instance.
      * @param key the key to use inside the decryptor
      * @param eme the message encoding scheme to use (eg "OAEP(SHA-256)")
      */
      BOTAN_DEPRECATED("Use constructor taking a RNG object")
      PK_Decryptor_EME(const Private_Key& key,
                       const std::string& eme,
                       const std::string& provider = "") :
         PK_Decryptor_EME(key, system_rng(), eme, provider) {}
#endif

      size_t plaintext_length(size_t ptext_len) const override;

      ~PK_Decryptor_EME();
      PK_Decryptor_EME& operator=(const PK_Decryptor_EME&) = delete;
      PK_Decryptor_EME(const PK_Decryptor_EME&) = delete;
   private:
      secure_vector<uint8_t> do_decrypt(uint8_t& valid_mask,
                                     const uint8_t in[],
                                     size_t in_len) const override;

      std::unique_ptr<PK_Ops::Decryption> m_op;
   };

/**
* Public Key Key Encapsulation Mechanism Encryption.
*/
class BOTAN_PUBLIC_API(2,0) PK_KEM_Encryptor final
   {
   public:
      /**
      * Construct an instance.
      * @param key the key to use inside the encryptor
      * @param rng the RNG to use
      * @param kem_param additional KEM parameters
      * @param provider the provider to use
      */
      PK_KEM_Encryptor(const Public_Key& key,
                       RandomNumberGenerator& rng,
                       const std::string& kem_param = "",
                       const std::string& provider = "");

#if defined(BOTAN_PUBKEY_INCLUDE_DEPRECATED_CONSTRUCTORS)
      BOTAN_DEPRECATED("Use constructor taking a RNG object")
      PK_KEM_Encryptor(const Public_Key& key,
                       const std::string& kem_param = "",
                       const std::string& provider = "") :
         PK_KEM_Encryptor(key, system_rng(), kem_param, provider) {}
#endif

      ~PK_KEM_Encryptor();

      PK_KEM_Encryptor& operator=(const PK_KEM_Encryptor&) = delete;
      PK_KEM_Encryptor(const PK_KEM_Encryptor&) = delete;

      /**
      * Generate a shared key for data encryption.
      * @param out_encapsulated_key the generated encapsulated key
      * @param out_shared_key the generated shared key
      * @param desired_shared_key_len desired size of the shared key in bytes
      * @param rng the RNG to use
      * @param salt a salt value used in the KDF
      * @param salt_len size of the salt value in bytes
      */
      void encrypt(secure_vector<uint8_t>& out_encapsulated_key,
                   secure_vector<uint8_t>& out_shared_key,
                   size_t desired_shared_key_len,
                   Botan::RandomNumberGenerator& rng,
                   const uint8_t salt[],
                   size_t salt_len);

      /**
      * Generate a shared key for data encryption.
      * @param out_encapsulated_key the generated encapsulated key
      * @param out_shared_key the generated shared key
      * @param desired_shared_key_len desired size of the shared key in bytes
      * @param rng the RNG to use
      * @param salt a salt value used in the KDF
      */
      template<typename Alloc>
         void encrypt(secure_vector<uint8_t>& out_encapsulated_key,
                      secure_vector<uint8_t>& out_shared_key,
                      size_t desired_shared_key_len,
                      Botan::RandomNumberGenerator& rng,
                      const std::vector<uint8_t, Alloc>& salt)
         {
         this->encrypt(out_encapsulated_key,
                       out_shared_key,
                       desired_shared_key_len,
                       rng,
                       salt.data(), salt.size());
         }

      /**
      * Generate a shared key for data encryption.
      * @param out_encapsulated_key the generated encapsulated key
      * @param out_shared_key the generated shared key
      * @param desired_shared_key_len desired size of the shared key in bytes
      * @param rng the RNG to use
      */
      void encrypt(secure_vector<uint8_t>& out_encapsulated_key,
                   secure_vector<uint8_t>& out_shared_key,
                   size_t desired_shared_key_len,
                   Botan::RandomNumberGenerator& rng)
         {
         this->encrypt(out_encapsulated_key,
                       out_shared_key,
                       desired_shared_key_len,
                       rng,
                       nullptr,
                       0);
         }

   private:
      std::unique_ptr<PK_Ops::KEM_Encryption> m_op;
   };

/**
* Public Key Key Encapsulation Mechanism Decryption.
*/
class BOTAN_PUBLIC_API(2,0) PK_KEM_Decryptor final
   {
   public:
      /**
      * Construct an instance.
      * @param key the key to use inside the decryptor
      * @param rng the RNG to use
      * @param kem_param additional KEM parameters
      * @param provider the provider to use
      */
      PK_KEM_Decryptor(const Private_Key& key,
                       RandomNumberGenerator& rng,
                       const std::string& kem_param = "",
                       const std::string& provider = "");

#if defined(BOTAN_PUBKEY_INCLUDE_DEPRECATED_CONSTRUCTORS)
      BOTAN_DEPRECATED("Use constructor taking a RNG object")
      PK_KEM_Decryptor(const Private_Key& key,
                       const std::string& kem_param = "",
                       const std::string& provider = "") :
         PK_KEM_Decryptor(key, system_rng(), kem_param, provider)
         {}
#endif

      ~PK_KEM_Decryptor();
      PK_KEM_Decryptor& operator=(const PK_KEM_Decryptor&) = delete;
      PK_KEM_Decryptor(const PK_KEM_Decryptor&) = delete;

      /**
      * Decrypts the shared key for data encryption.
      * @param encap_key the encapsulated key
      * @param encap_key_len size of the encapsulated key in bytes
      * @param desired_shared_key_len desired size of the shared key in bytes
      * @param salt a salt value used in the KDF
      * @param salt_len size of the salt value in bytes
      * @return the shared data encryption key
      */
      secure_vector<uint8_t> decrypt(const uint8_t encap_key[],
                                  size_t encap_key_len,
                                  size_t desired_shared_key_len,
                                  const uint8_t salt[],
                                  size_t salt_len);

      /**
      * Decrypts the shared key for data encryption.
      * @param encap_key the encapsulated key
      * @param encap_key_len size of the encapsulated key in bytes
      * @param desired_shared_key_len desired size of the shared key in bytes
      * @return the shared data encryption key
      */
      secure_vector<uint8_t> decrypt(const uint8_t encap_key[],
                                  size_t encap_key_len,
                                  size_t desired_shared_key_len)
         {
         return this->decrypt(encap_key, encap_key_len,
                              desired_shared_key_len,
                              nullptr, 0);
         }

      /**
      * Decrypts the shared key for data encryption.
      * @param encap_key the encapsulated key
      * @param desired_shared_key_len desired size of the shared key in bytes
      * @param salt a salt value used in the KDF
      * @return the shared data encryption key
      */
      template<typename Alloc1, typename Alloc2>
         secure_vector<uint8_t> decrypt(const std::vector<uint8_t, Alloc1>& encap_key,
                                     size_t desired_shared_key_len,
                                     const std::vector<uint8_t, Alloc2>& salt)
         {
         return this->decrypt(encap_key.data(), encap_key.size(),
                              desired_shared_key_len,
                              salt.data(), salt.size());
         }

   private:
      std::unique_ptr<PK_Ops::KEM_Decryption> m_op;
   };

}

#endif


text:
define(function(){
    var generateRandomAlphaNum = function (len) {
        var rdmString = "";
        //toSting接受的参数表示进制,默认为10进制。36进制为0-9 a-z
        for (; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
        return rdmString.substr(0, len);
    };

    return generateRandomAlphaNum;
});


text:
namespace AvangateAPI
{

enum State {
    IDLE = 0,
    LOGIN = 1,
    SETLANGUAGE = 2,
    SETCOUNTRY = 4,
    SETCURRENCY = 8,
    SETIP = 16,
    SETBILLINGDETAILS = 32,
    SETPAYMENTDETAILS = 64,
    ADDPRODUCT = 128,
    PLACEORDER = 256,
    GETORDER = 1024
};

class Response
{
public:
    struct Error {
        qint32 code;
        QString message;
    };

private:
    ushort m_id;
    Error m_error;
    float m_jsonrpc;
    QVariant* m_result;

public:
//    explicit Response(const ushort id, const float jsonrpc);
//    void read(const QJsonObject &json);
    void write(QJsonObject &json) const;

    void setResult (QVariant *result);
    QVariant *result();

    void setError (const Error err);
    Error *error();
    bool isError ();

    void setId (const ushort id);
    ushort id() const;

    void setJsonRPC (const float version);
    float jsonRPC() const;
};
}
#endif // RESPONSE_H


text:
/*
 * L.LineUtil contains different utility functions for line segments
 * and polylines (clipping, simplification, distances, etc.)
 */

/*jshint bitwise:false */ // allow bitwise oprations for this file

L.LineUtil = {

	// Simplify polyline with vertex reduction and Douglas-Peucker simplification.
	// Improves rendering performance dramatically by lessening the number of points to draw.

	simplify: function (/*Point[]*/ points, /*Number*/ tolerance) {
		if (!tolerance || !points.length) {
			return points.slice();
		}

		var sqTolerance = tolerance * tolerance;

		// stage 1: vertex reduction
		points = this._reducePoints(points, sqTolerance);

		// stage 2: Douglas-Peucker simplification
		points = this._simplifyDP(points, sqTolerance);

		return points;
	},

	// distance from a point to a segment between two points
	pointToSegmentDistance:  function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
		return Math.sqrt(this._sqClosestPointOnSegment(p, p1, p2, true));
	},

	closestPointOnSegment: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
		return this._sqClosestPointOnSegment(p, p1, p2);
	},

	// Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
	_simplifyDP: function (points, sqTolerance) {

		var len = points.length,
		    ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
		    markers = new ArrayConstructor(len);

		markers[0] = markers[len - 1] = 1;

		this._simplifyDPStep(points, markers, sqTolerance, 0, len - 1);

		var i,
		    newPoints = [];

		for (i = 0; i < len; i++) {
			if (markers[i]) {
				newPoints.push(points[i]);
			}
		}

		return newPoints;
	},

	_simplifyDPStep: function (points, markers, sqTolerance, first, last) {

		var maxSqDist = 0,
		    index, i, sqDist;

		for (i = first + 1; i <= last - 1; i++) {
			sqDist = this._sqClosestPointOnSegment(points[i], points[first], points[last], true);

			if (sqDist > maxSqDist) {
				index = i;
				maxSqDist = sqDist;
			}
		}

		if (maxSqDist > sqTolerance) {
			markers[index] = 1;

			this._simplifyDPStep(points, markers, sqTolerance, first, index);
			this._simplifyDPStep(points, markers, sqTolerance, index, last);
		}
	},

	// reduce points that are too close to each other to a single point
	_reducePoints: function (points, sqTolerance) {
		var reducedPoints = [points[0]];

		for (var i = 1, prev = 0, len = points.length; i < len; i++) {
			if (this._sqDist(points[i], points[prev]) > sqTolerance) {
				reducedPoints.push(points[i]);
				prev = i;
			}
		}
		if (prev < len - 1) {
			reducedPoints.push(points[len - 1]);
		}
		return reducedPoints;
	},

	// Cohen-Sutherland line clipping algorithm.
	// Used to avoid rendering parts of a polyline that are not currently visible.

	clipSegment: function (a, b, bounds, useLastCode) {
		var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds),
		    codeB = this._getBitCode(b, bounds),

		    codeOut, p, newCode;

		// save 2nd code to avoid calculating it on the next segment
		this._lastCode = codeB;

		while (true) {
			// if a,b is inside the clip window (trivial accept)
			if (!(codeA | codeB)) {
				return [a, b];
			// if a,b is outside the clip window (trivial reject)
			} else if (codeA & codeB) {
				return false;
			// other cases
			} else {
				codeOut = codeA || codeB;
				p = this._getEdgeIntersection(a, b, codeOut, bounds);
				newCode = this._getBitCode(p, bounds);

				if (codeOut === codeA) {
					a = p;
					codeA = newCode;
				} else {
					b = p;
					codeB = newCode;
				}
			}
		}
	},

	_getEdgeIntersection: function (a, b, code, bounds) {
		var dx = b.x - a.x,
		    dy = b.y - a.y,
		    min = bounds.min,
		    max = bounds.max;

		if (code & 8) { // top
			return new L.Point(a.x + dx * (max.y - a.y) / dy, max.y);
		} else if (code & 4) { // bottom
			return new L.Point(a.x + dx * (min.y - a.y) / dy, min.y);
		} else if (code & 2) { // right
			return new L.Point(max.x, a.y + dy * (max.x - a.x) / dx);
		} else if (code & 1) { // left
			return new L.Point(min.x, a.y + dy * (min.x - a.x) / dx);
		}
	},

	_getBitCode: function (/*Point*/ p, bounds) {
		var code = 0;

		if (p.x < bounds.min.x) { // left
			code |= 1;
		} else if (p.x > bounds.max.x) { // right
			code |= 2;
		}
		if (p.y < bounds.min.y) { // bottom
			code |= 4;
		} else if (p.y > bounds.max.y) { // top
			code |= 8;
		}

		return code;
	},

	// square distance (to avoid unnecessary Math.sqrt calls)
	_sqDist: function (p1, p2) {
		var dx = p2.x - p1.x,
		    dy = p2.y - p1.y;
		return dx * dx + dy * dy;
	},

	// return closest point on segment or distance to that point
	_sqClosestPointOnSegment: function (p, p1, p2, sqDist) {
		var x = p1.x,
		    y = p1.y,
		    dx = p2.x - x,
		    dy = p2.y - y,
		    dot = dx * dx + dy * dy,
		    t;

		if (dot > 0) {
			t = ((p.x - x) * dx + (p.y - y) * dy) / dot;

			if (t > 1) {
				x = p2.x;
				y = p2.y;
			} else if (t > 0) {
				x += dx * t;
				y += dy * t;
			}
		}

		dx = p.x - x;
		dy = p.y - y;

		return sqDist ? dx * dx + dy * dy : new L.Point(x, y);
	}
};


text:
package dynamiclistener

import (
	"context"
	"crypto"
	"crypto/tls"
	"crypto/x509"
	"net"
	"net/http"
	"strings"
	"sync"
	"time"

	"github.com/rancher/dynamiclistener/factory"
	"github.com/sirupsen/logrus"
	v1 "k8s.io/api/core/v1"
)

type TLSStorage interface {
	Get() (*v1.Secret, error)
	Update(secret *v1.Secret) error
}

type TLSFactory interface {
	Refresh(secret *v1.Secret) (*v1.Secret, error)
	AddCN(secret *v1.Secret, cn ...string) (*v1.Secret, bool, error)
	Merge(target *v1.Secret, additional *v1.Secret) (*v1.Secret, bool, error)
}

type SetFactory interface {
	SetFactory(tls TLSFactory)
}

func NewListener(l net.Listener, storage TLSStorage, caCert *x509.Certificate, caKey crypto.Signer, config Config) (net.Listener, http.Handler, error) {
	if config.CN == "" {
		config.CN = "dynamic"
	}
	if len(config.Organization) == 0 {
		config.Organization = []string{"dynamic"}
	}
	if config.TLSConfig == nil {
		config.TLSConfig = &tls.Config{}
	}

	dynamicListener := &listener{
		factory: &factory.TLS{
			CACert:       caCert,
			CAKey:        caKey,
			CN:           config.CN,
			Organization: config.Organization,
		},
		Listener:  l,
		storage:   &nonNil{storage: storage},
		sans:      config.SANs,
		tlsConfig: config.TLSConfig,
	}
	if dynamicListener.tlsConfig == nil {
		dynamicListener.tlsConfig = &tls.Config{}
	}
	dynamicListener.tlsConfig.GetCertificate = dynamicListener.getCertificate

	if config.CloseConnOnCertChange {
		dynamicListener.conns = map[int]*closeWrapper{}
	}

	if setter, ok := storage.(SetFactory); ok {
		setter.SetFactory(dynamicListener.factory)
	}

	if config.ExpirationDaysCheck == 0 {
		config.ExpirationDaysCheck = 30
	}

	tlsListener := tls.NewListener(dynamicListener.WrapExpiration(config.ExpirationDaysCheck), dynamicListener.tlsConfig)
	return tlsListener, dynamicListener.cacheHandler(), nil
}

type cancelClose struct {
	cancel func()
	net.Listener
}

func (c *cancelClose) Close() error {
	c.cancel()
	return c.Listener.Close()
}

type Config struct {
	CN                    string
	Organization          []string
	TLSConfig             *tls.Config
	SANs                  []string
	ExpirationDaysCheck   int
	CloseConnOnCertChange bool
}

type listener struct {
	sync.RWMutex
	net.Listener

	conns    map[int]*closeWrapper
	connID   int
	connLock sync.Mutex

	factory   TLSFactory
	storage   TLSStorage
	version   string
	tlsConfig *tls.Config
	cert      *tls.Certificate
	sans      []string
	init      sync.Once
}

func (l *listener) WrapExpiration(days int) net.Listener {
	ctx, cancel := context.WithCancel(context.Background())
	go func() {
		time.Sleep(5 * time.Minute)

		for {
			wait := 6 * time.Hour
			if err := l.checkExpiration(days); err != nil {
				logrus.Errorf("failed to check and refresh dynamic cert: %v", err)
				wait = 5 + time.Minute
			}
			select {
			case <-ctx.Done():
				return
			case <-time.After(wait):
			}
		}
	}()

	return &cancelClose{
		cancel:   cancel,
		Listener: l,
	}
}

func (l *listener) checkExpiration(days int) error {
	l.Lock()
	defer l.Unlock()

	if days == 0 {
		return nil
	}

	if l.cert == nil {
		return nil
	}

	secret, err := l.storage.Get()
	if err != nil {
		return err
	}

	cert, err := tls.X509KeyPair(secret.Data[v1.TLSCertKey], secret.Data[v1.TLSPrivateKeyKey])
	if err != nil {
		return err
	}

	certParsed, err := x509.ParseCertificate(cert.Certificate[0])
	if err != nil {
		return err
	}

	if time.Now().UTC().Add(time.Hour * 24 * time.Duration(days)).After(certParsed.NotAfter) {
		secret, err := l.factory.Refresh(secret)
		if err != nil {
			return err
		}
		return l.storage.Update(secret)
	}

	return nil
}

func (l *listener) Accept() (net.Conn, error) {
	l.init.Do(func() {
		if len(l.sans) > 0 {
			l.updateCert(l.sans...)
		}
	})

	conn, err := l.Listener.Accept()
	if err != nil {
		return conn, err
	}

	addr := conn.LocalAddr()
	if addr == nil {
		return conn, nil
	}

	host, _, err := net.SplitHostPort(addr.String())
	if err != nil {
		logrus.Errorf("failed to parse network %s: %v", addr.Network(), err)
		return conn, nil
	}

	if !strings.Contains(host, ":") {
		if err := l.updateCert(host); err != nil {
			logrus.Infof("failed to create TLS cert for: %s", host)
		}
	}

	if l.conns != nil {
		conn = l.wrap(conn)
	}

	return conn, nil
}

func (l *listener) wrap(conn net.Conn) net.Conn {
	l.connLock.Lock()
	defer l.connLock.Unlock()
	l.connID++

	wrapper := &closeWrapper{
		Conn: conn,
		id:   l.connID,
		l:    l,
	}
	l.conns[l.connID] = wrapper

	return wrapper
}

type closeWrapper struct {
	net.Conn
	id int
	l  *listener
}

func (c *closeWrapper) close() error {
	delete(c.l.conns, c.id)
	return c.Conn.Close()
}

func (c *closeWrapper) Close() error {
	c.l.connLock.Lock()
	defer c.l.connLock.Unlock()
	return c.close()
}

func (l *listener) getCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
	if hello.ServerName != "" {
		if err := l.updateCert(hello.ServerName); err != nil {
			return nil, err
		}
	}

	return l.loadCert()
}

func (l *listener) updateCert(cn ...string) error {
	l.RLock()
	defer l.RUnlock()

	secret, err := l.storage.Get()
	if err != nil {
		return err
	}

	if !factory.NeedsUpdate(secret, cn...) {
		return nil
	}

	l.RUnlock()
	l.Lock()
	defer l.RLock()
	defer l.Unlock()

	secret, updated, err := l.factory.AddCN(secret, append(l.sans, cn...)...)
	if err != nil {
		return err
	}

	if updated {
		if err := l.storage.Update(secret); err != nil {
			return err
		}
		// clear version to force cert reload
		l.version = ""
	}

	if l.conns != nil {
		l.connLock.Lock()
		for _, conn := range l.conns {
			_ = conn.close()
		}
		l.connLock.Unlock()
	}

	return nil
}

func (l *listener) loadCert() (*tls.Certificate, error) {
	l.RLock()
	defer l.RUnlock()

	secret, err := l.storage.Get()
	if err != nil {
		return nil, err
	}
	if l.cert != nil && l.version == secret.ResourceVersion {
		return l.cert, nil
	}

	defer l.RLock()
	l.RUnlock()
	l.Lock()
	defer l.Unlock()

	secret, err = l.storage.Get()
	if err != nil {
		return nil, err
	}
	if l.cert != nil && l.version == secret.ResourceVersion {
		return l.cert, nil
	}

	cert, err := tls.X509KeyPair(secret.Data[v1.TLSCertKey], secret.Data[v1.TLSPrivateKeyKey])
	if err != nil {
		return nil, err
	}

	l.cert = &cert
	return l.cert, nil
}

func (l *listener) cacheHandler() http.Handler {
	return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
		h, _, err := net.SplitHostPort(req.Host)
		if err != nil {
			h = req.Host
		}

		ip := net.ParseIP(h)
		if len(ip) > 0 {
			l.updateCert(h)
		}
	})
}

type nonNil struct {
	sync.Mutex
	storage TLSStorage
}

func (n *nonNil) Get() (*v1.Secret, error) {
	n.Lock()
	defer n.Unlock()

	s, err := n.storage.Get()
	if err != nil || s == nil {
		return &v1.Secret{}, err
	}
	return s, nil
}

func (n *nonNil) Update(secret *v1.Secret) error {
	n.Lock()
	defer n.Unlock()

	return n.storage.Update(secret)
}


text:
module Ci
  class CreatePipelineService < BaseService
    attr_reader :pipeline

    CreateError = Class.new(StandardError)

    SEQUENCE = [Gitlab::Ci::Pipeline::Chain::Build,
                Gitlab::Ci::Pipeline::Chain::RemoveUnwantedChatJobs,
                Gitlab::Ci::Pipeline::Chain::Validate::Abilities,
                Gitlab::Ci::Pipeline::Chain::Validate::Repository,
                Gitlab::Ci::Pipeline::Chain::Validate::Config,
                Gitlab::Ci::Pipeline::Chain::Skip,
                Gitlab::Ci::Pipeline::Chain::Limit::Size,
                Gitlab::Ci::Pipeline::Chain::Populate,
                Gitlab::Ci::Pipeline::Chain::Create,
                Gitlab::Ci::Pipeline::Chain::Limit::Activity].freeze

    def execute(source, ignore_skip_ci: false, save_on_errors: true, trigger_request: nil, schedule: nil, merge_request: nil, **options, &block)
      @pipeline = Ci::Pipeline.new

      command = Gitlab::Ci::Pipeline::Chain::Command.new(
        source: source,
        origin_ref: params[:ref],
        checkout_sha: params[:checkout_sha],
        after_sha: params[:after],
        before_sha: params[:before],          # The base SHA of the source branch (i.e merge_request.diff_base_sha).
        source_sha: params[:source_sha],      # The HEAD SHA of the source branch (i.e merge_request.diff_head_sha).
        target_sha: params[:target_sha],      # The HEAD SHA of the target branch.
        trigger_request: trigger_request,
        schedule: schedule,
        merge_request: merge_request,
        ignore_skip_ci: ignore_skip_ci,
        save_incompleted: save_on_errors,
        seeds_block: block,
        variables_attributes: params[:variables_attributes],
        project: project,
        current_user: current_user,
        push_options: params[:push_options] || {},
        chat_data: params[:chat_data],
        **extra_options(options))

      sequence = Gitlab::Ci::Pipeline::Chain::Sequence
        .new(pipeline, command, SEQUENCE)

      sequence.build! do |pipeline, sequence|
        schedule_head_pipeline_update

        if sequence.complete?
          cancel_pending_pipelines if project.auto_cancel_pending_pipelines?
          pipeline_created_counter.increment(source: source)

          pipeline.process!
        end
      end

      # If pipeline is not persisted, try to recover IID
      pipeline.reset_project_iid unless pipeline.persisted? ||
          Feature.disabled?(:ci_pipeline_rewind_iid, project, default_enabled: true)

      pipeline
    end

    def execute!(*args, &block)
      execute(*args, &block).tap do |pipeline|
        unless pipeline.persisted?
          raise CreateError, pipeline.errors.full_messages.join(',')
        end
      end
    end

    private

    def commit
      @commit ||= project.commit(origin_sha || origin_ref)
    end

    def sha
      commit.try(:id)
    end

    def cancel_pending_pipelines
      Gitlab::OptimisticLocking.retry_lock(auto_cancelable_pipelines) do |cancelables|
        cancelables.find_each do |cancelable|
          cancelable.auto_cancel_running(pipeline)
        end
      end
    end

    # rubocop: disable CodeReuse/ActiveRecord
    def auto_cancelable_pipelines
      project.ci_pipelines
        .where(ref: pipeline.ref)
        .where.not(id: pipeline.id)
        .where.not(sha: project.commit(pipeline.ref).try(:id))
        .created_or_pending
    end
    # rubocop: enable CodeReuse/ActiveRecord

    def pipeline_created_counter
      @pipeline_created_counter ||= Gitlab::Metrics
        .counter(:pipelines_created_total, "Counter of pipelines created")
    end

    def schedule_head_pipeline_update
      pipeline.all_merge_requests.opened.each do |merge_request|
        UpdateHeadPipelineForMergeRequestWorker.perform_async(merge_request.id)
      end
    end

    def extra_options(options = {})
      # In Ruby 2.4, even when options is empty, f(**options) doesn't work when f
      # doesn't have any parameters. We reproduce the Ruby 2.5 behavior by
      # checking explicitly that no arguments are given.
      raise ArgumentError if options.any?

      {} # overridden in EE
    end
  end
end


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe YARD::Tags::OverloadTag do
  before do
    @tag = Tags::OverloadTag.new(:overload, <<-'eof')
      def bar(a, b = 1, &block)
        Hello world
        @param a [String]
        @return [String]
    eof
  end

  it "should parse the first line as a method signature" do
    @tag.signature.should == "def bar(a, b = 1, &block)"
    @tag.parameters.should == [['a', nil], ['b', "1"], ['&block', nil]]
  end

  it "should parse the rest of the text as a new Docstring" do
    @tag.docstring.should be_instance_of(Docstring)
    @tag.docstring.should == "Hello world"
  end

  it "should set Docstring's object after #object= is called" do
    m = mock(:object)
    @tag.object = m
    @tag.docstring.object.should == m
  end

  it "should respond to #tag, #tags and #has_tag?" do
    @tag.object = mock(:object)
    @tag.tags.size.should == 2
    @tag.tag(:param).name.should == "a"
    @tag.has_tag?(:return).should == true
  end

  it "should not be a CodeObjects::Base when not hooked up to an object" do
    @tag.object = nil
    @tag.is_a?(CodeObjects::Base).should == false
  end

  it "should be a CodeObjects::Base when hooked up to an object" do
    @tag.object = mock(:object)
    @tag.object.should_receive(:is_a?).at_least(3).times.with(CodeObjects::Base).and_return(true)
    @tag.is_a?(CodeObjects::Base).should == true
    @tag.kind_of?(CodeObjects::Base).should == true
    (CodeObjects::Base === @tag).should == true
  end

  it "should not parse 'def' out of method name" do
    tag = Tags::OverloadTag.new(:overload, "default")
    tag.signature.should == "default"
  end
end


text:
using System;
using OrchardCore.Data.Migration;
using OrchardCore.Workflows.Indexes;
using YesSql.Sql;

namespace OrchardCore.Workflows
{
    public class Migrations : DataMigration
    {
        public int Create()
        {
            SchemaBuilder.CreateMapIndexTable<WorkflowTypeIndex>(table => table
                .Column<string>("WorkflowTypeId")
                .Column<string>("Name")
                .Column<bool>("IsEnabled")
                .Column<bool>("HasStart")
            );

            SchemaBuilder.CreateMapIndexTable<WorkflowTypeStartActivitiesIndex>(table => table
                .Column<string>("WorkflowTypeId")
                .Column<string>("Name")
                .Column<bool>("IsEnabled")
                .Column<string>("StartActivityId")
                .Column<string>("StartActivityName")
            );

            SchemaBuilder.CreateMapIndexTable<WorkflowIndex>(table => table
                .Column<string>("WorkflowTypeId")
                .Column<string>("WorkflowId")
                .Column<string>("WorkflowStatus")
                .Column<DateTime>("CreatedUtc")
            );

            SchemaBuilder.CreateMapIndexTable<WorkflowBlockingActivitiesIndex>(table => table
                .Column<string>("ActivityId")
                .Column<string>("ActivityName")
                .Column<bool>("ActivityIsStart")
                .Column<string>("WorkflowTypeId")
                .Column<string>("WorkflowId")
                .Column<string>("WorkflowCorrelationId")
            );

            return 2;
        }

        public int UpdateFrom1()
        {
            SchemaBuilder.AlterTable(nameof(WorkflowIndex), table =>
            {
                table.AddColumn<string>("WorkflowStatus");
            });

            return 2;
        }
    }
}


text:
layout: page
title: Township Tone Research Trade Fair
date: 2016-05-24
author: Eugene Molina
tags: weekly links, java
status: published
summary: Proin tempor non mi id mattis. Maecenas fermentum tincidunt.
banner: images/banner/leisure-02.jpg
booking:
  startDate: 03/11/2018
  endDate: 03/13/2018
  ctyhocn: YULDVHX
  groupCode: TTRTF
published: true
---
Praesent blandit elit et pulvinar gravida. Sed pellentesque faucibus risus vitae convallis. Phasellus quis consectetur ipsum. Donec pretium pretium rhoncus. Nullam ultricies cursus finibus. Quisque porttitor lorem et sodales semper. Praesent volutpat sem et lectus sollicitudin, eget faucibus enim congue. Proin nec lorem eu mauris auctor aliquam at eget magna. Donec fringilla vel nisl vehicula hendrerit. Vestibulum consequat turpis quis metus sollicitudin, quis semper ex faucibus. Duis molestie mi non iaculis auctor. Morbi et felis tempus, placerat mi in, dictum diam. Nulla dictum lectus quis tempor ornare. Nulla hendrerit mattis leo vitae pulvinar.

* Nulla tempor diam ut dolor condimentum interdum
* Aenean eget est ac turpis dapibus molestie
* Cras vel quam vel dui elementum malesuada
* Mauris quis turpis at sapien semper sollicitudin.

Aliquam erat volutpat. Curabitur dapibus sodales purus, id commodo tortor viverra at. Mauris magna dolor, tincidunt eu ullamcorper non, venenatis eget ex. Etiam sit amet nibh augue. Cras vulputate, nisi eget dictum cursus, nisl massa hendrerit mauris, sit amet vestibulum elit ex a est. In eu magna tortor. Suspendisse lobortis pharetra venenatis. Cras a massa quis nisl luctus varius ut sit amet lacus. Aliquam erat volutpat. Nulla facilisi. Fusce pulvinar eu turpis quis euismod.


text:
var PlaceMarkerView = Backbone.View.extend({

    initialize: function(options) {
        var self = this;
        var shadow = new google.maps.MarkerImage("images/pins/shadow-Pin.png",
            new google.maps.Size(51.0, 44.0),
            new google.maps.Point(0, 0),
            new google.maps.Point(14.0, 44.0)
        );
        var loc = new google.maps.LatLng(self.model.get('lat'),self.model.get('lon'));
        var options = {map: self.map,
            animation: google.maps.Animation.DROP,
            title: self.model.name,
            icon:   App.getPinNumber(self.model,false),
            shadow: shadow,
            map: App.getMap(),

            position: loc,
            zIndex: 999999};

        var marker = new google.maps.Marker(options);
        self.model.marker = marker;
        marker.model = self.model;
        marker.setMap(App.getMap());

        if(Places.models.indexOf(this.model) == Places.models.length-1){
            //zoom map to show all markers
            var bounds = new google.maps.LatLngBounds();
            for(var i=0;i<Places.models.length;i++){

                bounds.extend(Places.models[i].marker.getPosition());
            }
            App.getMap().fitBounds(bounds);
        }
        google.maps.event.addListener(marker, 'click', function(){

            App.showContent(marker.model);

        });

    }

});


text:
/* First created by JCasGen Sat Mar 07 22:05:57 CET 2015 */
package de.julielab.jules.types;

import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.JCasRegistry;
import org.apache.uima.cas.impl.CASImpl;
import org.apache.uima.cas.impl.FSGenerator;
import org.apache.uima.cas.FeatureStructure;
import org.apache.uima.cas.impl.TypeImpl;
import org.apache.uima.cas.Type;
import org.apache.uima.cas.impl.FeatureImpl;
import org.apache.uima.cas.Feature;

/** Penn Treebank constituent annotation (see Penn Treebank)
 * Updated by JCasGen Sat Mar 07 22:05:57 CET 2015
 * @generated */
public class PTBConstituent_Type extends Constituent_Type {
  /** @generated
   * @return the generator for this type
   */
  @Override
  protected FSGenerator getFSGenerator() {return fsGenerator;}
  /** @generated */
  private final FSGenerator fsGenerator =
    new FSGenerator() {
      public FeatureStructure createFS(int addr, CASImpl cas) {
  			 if (PTBConstituent_Type.this.useExistingInstance) {
  			   // Return eq fs instance if already created
  		     FeatureStructure fs = PTBConstituent_Type.this.jcas.getJfsFromCaddr(addr);
  		     if (null == fs) {
  		       fs = new PTBConstituent(addr, PTBConstituent_Type.this);
  			   PTBConstituent_Type.this.jcas.putJfsFromCaddr(addr, fs);
  			   return fs;
  		     }
  		     return fs;
        } else return new PTBConstituent(addr, PTBConstituent_Type.this);
  	  }
    };
  /** @generated */
  @SuppressWarnings ("hiding")
  public final static int typeIndexID = PTBConstituent.typeIndexID;
  /** @generated
     @modifiable */
  @SuppressWarnings ("hiding")
  public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.julielab.jules.types.PTBConstituent");

  /** @generated */
  final Feature casFeat_formFuncDisc;
  /** @generated */
  final int     casFeatCode_formFuncDisc;
  /** @generated
   * @param addr low level Feature Structure reference
   * @return the feature value
   */
  public String getFormFuncDisc(int addr) {
        if (featOkTst && casFeat_formFuncDisc == null)
      jcas.throwFeatMissing("formFuncDisc", "de.julielab.jules.types.PTBConstituent");
    return ll_cas.ll_getStringValue(addr, casFeatCode_formFuncDisc);
  }
  /** @generated
   * @param addr low level Feature Structure reference
   * @param v value to set
   */
  public void setFormFuncDisc(int addr, String v) {
        if (featOkTst && casFeat_formFuncDisc == null)
      jcas.throwFeatMissing("formFuncDisc", "de.julielab.jules.types.PTBConstituent");
    ll_cas.ll_setStringValue(addr, casFeatCode_formFuncDisc, v);}

  /** @generated */
  final Feature casFeat_gramRole;
  /** @generated */
  final int     casFeatCode_gramRole;
  /** @generated
   * @param addr low level Feature Structure reference
   * @return the feature value
   */
  public String getGramRole(int addr) {
        if (featOkTst && casFeat_gramRole == null)
      jcas.throwFeatMissing("gramRole", "de.julielab.jules.types.PTBConstituent");
    return ll_cas.ll_getStringValue(addr, casFeatCode_gramRole);
  }
  /** @generated
   * @param addr low level Feature Structure reference
   * @param v value to set
   */
  public void setGramRole(int addr, String v) {
        if (featOkTst && casFeat_gramRole == null)
      jcas.throwFeatMissing("gramRole", "de.julielab.jules.types.PTBConstituent");
    ll_cas.ll_setStringValue(addr, casFeatCode_gramRole, v);}

  /** @generated */
  final Feature casFeat_adv;
  /** @generated */
  final int     casFeatCode_adv;
  /** @generated
   * @param addr low level Feature Structure reference
   * @return the feature value
   */
  public String getAdv(int addr) {
        if (featOkTst && casFeat_adv == null)
      jcas.throwFeatMissing("adv", "de.julielab.jules.types.PTBConstituent");
    return ll_cas.ll_getStringValue(addr, casFeatCode_adv);
  }
  /** @generated
   * @param addr low level Feature Structure reference
   * @param v value to set
   */
  public void setAdv(int addr, String v) {
        if (featOkTst && casFeat_adv == null)
      jcas.throwFeatMissing("adv", "de.julielab.jules.types.PTBConstituent");
    ll_cas.ll_setStringValue(addr, casFeatCode_adv, v);}

  /** @generated */
  final Feature casFeat_misc;
  /** @generated */
  final int     casFeatCode_misc;
  /** @generated
   * @param addr low level Feature Structure reference
   * @return the feature value
   */
  public String getMisc(int addr) {
        if (featOkTst && casFeat_misc == null)
      jcas.throwFeatMissing("misc", "de.julielab.jules.types.PTBConstituent");
    return ll_cas.ll_getStringValue(addr, casFeatCode_misc);
  }
  /** @generated
   * @param addr low level Feature Structure reference
   * @param v value to set
   */
  public void setMisc(int addr, String v) {
        if (featOkTst && casFeat_misc == null)
      jcas.throwFeatMissing("misc", "de.julielab.jules.types.PTBConstituent");
    ll_cas.ll_setStringValue(addr, casFeatCode_misc, v);}

  /** @generated */
  final Feature casFeat_nullElement;
  /** @generated */
  final int     casFeatCode_nullElement;
  /** @generated
   * @param addr low level Feature Structure reference
   * @return the feature value
   */
  public String getNullElement(int addr) {
        if (featOkTst && casFeat_nullElement == null)
      jcas.throwFeatMissing("nullElement", "de.julielab.jules.types.PTBConstituent");
    return ll_cas.ll_getStringValue(addr, casFeatCode_nullElement);
  }
  /** @generated
   * @param addr low level Feature Structure reference
   * @param v value to set
   */
  public void setNullElement(int addr, String v) {
        if (featOkTst && casFeat_nullElement == null)
      jcas.throwFeatMissing("nullElement", "de.julielab.jules.types.PTBConstituent");
    ll_cas.ll_setStringValue(addr, casFeatCode_nullElement, v);}

  /** @generated */
  final Feature casFeat_ref;
  /** @generated */
  final int     casFeatCode_ref;
  /** @generated
   * @param addr low level Feature Structure reference
   * @return the feature value
   */
  public int getRef(int addr) {
        if (featOkTst && casFeat_ref == null)
      jcas.throwFeatMissing("ref", "de.julielab.jules.types.PTBConstituent");
    return ll_cas.ll_getRefValue(addr, casFeatCode_ref);
  }
  /** @generated
   * @param addr low level Feature Structure reference
   * @param v value to set
   */
  public void setRef(int addr, int v) {
        if (featOkTst && casFeat_ref == null)
      jcas.throwFeatMissing("ref", "de.julielab.jules.types.PTBConstituent");
    ll_cas.ll_setRefValue(addr, casFeatCode_ref, v);}

  /** @generated */
  final Feature casFeat_map;
  /** @generated */
  final int     casFeatCode_map;
  /** @generated
   * @param addr low level Feature Structure reference
   * @return the feature value
   */
  public int getMap(int addr) {
        if (featOkTst && casFeat_map == null)
      jcas.throwFeatMissing("map", "de.julielab.jules.types.PTBConstituent");
    return ll_cas.ll_getRefValue(addr, casFeatCode_map);
  }
  /** @generated
   * @param addr low level Feature Structure reference
   * @param v value to set
   */
  public void setMap(int addr, int v) {
        if (featOkTst && casFeat_map == null)
      jcas.throwFeatMissing("map", "de.julielab.jules.types.PTBConstituent");
    ll_cas.ll_setRefValue(addr, casFeatCode_map, v);}

  /** @generated */
  final Feature casFeat_tpc;
  /** @generated */
  final int     casFeatCode_tpc;
  /** @generated
   * @param addr low level Feature Structure reference
   * @return the feature value
   */
  public boolean getTpc(int addr) {
        if (featOkTst && casFeat_tpc == null)
      jcas.throwFeatMissing("tpc", "de.julielab.jules.types.PTBConstituent");
    return ll_cas.ll_getBooleanValue(addr, casFeatCode_tpc);
  }
  /** @generated
   * @param addr low level Feature Structure reference
   * @param v value to set
   */
  public void setTpc(int addr, boolean v) {
        if (featOkTst && casFeat_tpc == null)
      jcas.throwFeatMissing("tpc", "de.julielab.jules.types.PTBConstituent");
    ll_cas.ll_setBooleanValue(addr, casFeatCode_tpc, v);}

  /** initialize variables to correspond with Cas Type and Features
	 * @generated
	 * @param jcas JCas
	 * @param casType Type
	 */
  public PTBConstituent_Type(JCas jcas, Type casType) {
    super(jcas, casType);
    casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator());

    casFeat_formFuncDisc = jcas.getRequiredFeatureDE(casType, "formFuncDisc", "uima.cas.String", featOkTst);
    casFeatCode_formFuncDisc  = (null == casFeat_formFuncDisc) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_formFuncDisc).getCode();

    casFeat_gramRole = jcas.getRequiredFeatureDE(casType, "gramRole", "uima.cas.String", featOkTst);
    casFeatCode_gramRole  = (null == casFeat_gramRole) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_gramRole).getCode();

    casFeat_adv = jcas.getRequiredFeatureDE(casType, "adv", "uima.cas.String", featOkTst);
    casFeatCode_adv  = (null == casFeat_adv) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_adv).getCode();

    casFeat_misc = jcas.getRequiredFeatureDE(casType, "misc", "uima.cas.String", featOkTst);
    casFeatCode_misc  = (null == casFeat_misc) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_misc).getCode();

    casFeat_nullElement = jcas.getRequiredFeatureDE(casType, "nullElement", "uima.cas.String", featOkTst);
    casFeatCode_nullElement  = (null == casFeat_nullElement) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_nullElement).getCode();

    casFeat_ref = jcas.getRequiredFeatureDE(casType, "ref", "de.julielab.jules.types.Constituent", featOkTst);
    casFeatCode_ref  = (null == casFeat_ref) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_ref).getCode();

    casFeat_map = jcas.getRequiredFeatureDE(casType, "map", "de.julielab.jules.types.Constituent", featOkTst);
    casFeatCode_map  = (null == casFeat_map) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_map).getCode();

    casFeat_tpc = jcas.getRequiredFeatureDE(casType, "tpc", "uima.cas.Boolean", featOkTst);
    casFeatCode_tpc  = (null == casFeat_tpc) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_tpc).getCode();

  }
}


text:
/****************************************************************************/
/*                                                                          */
/*    The Mondo Libraries  							                        */
/*                                                                          */
/*        Namespace: Mondo.Database							                */
/*             File: DatabaseExtensions.cs								    */
/*        Class(es): DatabaseExtensions								        */
/*          Purpose: Database helper functions                              */
/*                                                                          */
/*  Original Author: Jim Lightfoot                                          */
/*    Creation Date: 1 Aug 2016                                             */
/*                                                                          */
/*   Copyright (c) 2016 - Jim Lightfoot, All rights reserved                */
/*                                                                          */
/*  Licensed under the MIT license:                                         */
/*    http://www.opensource.org/licenses/mit-license.php                    */
/*                                                                          */
/****************************************************************************/

using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;

using Mondo.Common;

namespace Mondo.Database
{
    /****************************************************************************/
    /****************************************************************************/
    public static class DatabaseExtensions
    {
        /************************************************************************/
        public static IList<T> ToList<T>(this DataTable table, bool dispose = true) where T : new()
        {
            DataSourceList dataSource = DataSourceList.Create(table);

            IList<T> list = dataSource.ToList<T>();

            if(dispose)
              table.Dispose();

            return list;
        }

        /************************************************************************/
        public static string QueryString(this Database db, Operation op)
        {
            return db.ExecuteScalar(op).Normalized();
        }
    }

    /****************************************************************************/
    /****************************************************************************/
    public class DatabaseTransaction : IDisposable
    {
        /************************************************************************/
        public DatabaseTransaction(string connectionString = "", bool lookup = false, IConfig config = null)
        {
            this.Database = Database.Create(connectionString, lookup, config);

            this.Database.Open();

            this.Database.BeginTransaction();
        }

        /************************************************************************/
        public Database Database
        {
            get; private set;
        }

        /*************************************************************************/
        public void Commit()
        {
            this.Database.Commit();
        }

        /************************************************************************/
        public void Dispose()
        {
            if(this.Database != null)
            {
                if(this.Database.IsOpen)
                {
                    // If we still have a valid transaction then it wasn't committed so we'll roll it back
                    if(this.Database.Transaction != null)
                      this.Database.Rollback();

                    this.Database.Close();
                }

                this.Database.Dispose();
                this.Database = null;
            }
        }
    }
}


text:
<?php

namespace Example\UseFactory;

use Symfony\Component\DependencyInjection\Annotation\Service;

/**
 * @Service(
 *     public=true,
 *     factoryClass=TestStaticFactory::class,
 *     factoryMethod="create"
 * )
 */
class TestStaticService
{
    private $passedFromFactory;

    public function __construct($passedFromFactory)
    {
        $this->passedFromFactory = $passedFromFactory;
    }

    public function get()
    {
        return $this->passedFromFactory;
    }
}


text:
module.exports = function() {
	var moduleTest = 'It works';
}


text:
#import <Foundation/Foundation.h>
#import "ASPObject.h"

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

#import "ASPBookmarks.h"

@protocol ASPBookmarksResponse
@end

@interface ASPBookmarksResponse : ASPObject

@property(nonatomic) ASPBookmarks* bookmarks;

@property(nonatomic) NSString* code;

@property(nonatomic) NSString* status;

@end


text:
package com.wb.nextgenlibrary.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Utilities related to postal codes.
 */
public class PostalCodeUtils {

    public static final int COUNTRY_US = 1;
    public static final int COUNTRY_UK = 2;
    public static final int COUNTRY_CA = 3;
    public static final int COUNTRY_AU = 4;

    public static Pattern CANADIAN_POSTAL_CODE_PATTERN = Pattern
            .compile("[ABCEGHJKLMNPRSTVXYabceghjklmnprstvxy]\\d[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstvwxyz][\\s-]?\\d[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstvwxyz]\\d");
    // Eg: r3m 0k2
    public static Pattern US_ZIP_CODE_PATTERN = Pattern.compile("\\d{5}"); // Eg:
                                                                           // 94103
    public static Pattern AU_POSTAL_CODE_PATTERN = Pattern.compile("\\d{4}");
    public static Pattern UK_POSTCODE_PATTERN = Pattern.compile("[A-Z]{1,2}\\d[A-Z\\d]?( )?(\\d[ABD-HJLNP-UW-Z]{2})?"); // Eg:
                                                                                // SW1A
                                                                                // 0AA
                                                                                // now
                                                                                // allows
                                                                                // no
                                                                                // space
    protected static Pattern CONTAINS_DIGIT = Pattern.compile(".*\\d.*");
    protected static Pattern ALL_NUMERIC = Pattern.compile("\\d+");

    private static boolean isValueMatchesPattern(Pattern pattern, String value) {
        Matcher matcher = pattern.matcher(value);
        return matcher.matches();
    }

    public static boolean isValidUnitedStatesZipCode(String value) {
        return isValueMatchesPattern(US_ZIP_CODE_PATTERN, value);
    }

    public static boolean isValidCanadianPostalCode(String value) {
        return isValueMatchesPattern(CANADIAN_POSTAL_CODE_PATTERN, value);
    }

    public static boolean isValidUnitedKingdomPostcode(String value) {
        return isValueMatchesPattern(UK_POSTCODE_PATTERN, value);
    }

    public static boolean isValidAustraliaPostcode(String value) {
        return isValueMatchesPattern(AU_POSTAL_CODE_PATTERN, value);
    }

    public static boolean isProbablePostalCode(String value) {
        return isValueMatchesPattern(CONTAINS_DIGIT, value);
    }

    public static boolean isAllNumeric(String value) {
        return isValueMatchesPattern(ALL_NUMERIC, value);
    }

    /**
     * Returns canonical Canadian Postal Code string "ccc ccc"
     *
     * @param postalCode
     * @return
     */
    public static String getCanonicalCanadianPostalCode(String postalCode) {

        if (postalCode == null) {
            return null;
        }

        if (postalCode.length() == 6) {

            // missing space
            postalCode = postalCode.substring(0, 3) + " " + postalCode.substring(3);
        } else if (postalCode.length() == 7) {

            // ensure separator is blank space and not hyphen or anything else
            postalCode = postalCode.substring(0, 3) + " " + postalCode.substring(4);
        }

        postalCode = postalCode.toUpperCase();

        return postalCode;
    }

    public static String[] splitPostalCode(int country, String code) {
        if (country == 0 || country > COUNTRY_AU) {
            return new String[] { code, null };
        }
        code = code.trim();
        String first = code;
        String last = null;
        if (country == COUNTRY_US) {
            if (code.indexOf("-") > 0) {
                first = code.substring(0, code.indexOf("-"));
                last = code.substring(code.indexOf("-") + 1, code.length());
            } else if (isValueMatchesPattern(ALL_NUMERIC, code) && code.length() > 5) {
                first = code.substring(0, 5);
                last = code.substring(6, code.length());
            }

        } else if (country == COUNTRY_UK && code.length() <= 4) {
            first = code;
            last = null;
        } else if (country == COUNTRY_UK && code.contains(" ")) {
            String[] pair = code.split(" ");
            first = pair[0];
            last = pair[1];
        } else if (country == COUNTRY_UK && code.length() >= 5) {
            // this part is a hack to support the iphone client, which gives us
            // uk postal codes as one long string
            // without a space. will be fixed in september 2008 update.
            first = code.substring(0, code.length() - 3);
            last = code.substring(code.length() - 3, code.length());
        } else if (country == COUNTRY_CA) {
            if (code.length() == 6) {
                first = code.substring(0, 3) + " " + code.substring(3, 6);
            } else if (code.length() == 7 && code.indexOf("-") > 0) {
                first = code.substring(0, 3) + " " + code.substring(4, 7);
            }
        }
        return new String[] { first, last };
    }

    /**
     * Only supports UK, US, and CA
     */
    public static String parseZipcodeForShowtimes(String value) {

        // String postalCode = value;
        if (value == null || value.length() == 0)
            return null;
        String postal = value.trim().toUpperCase();

        String code;

        if (isValidUnitedStatesZipCode(postal)) {
            code = splitPostalCode(COUNTRY_US, postal)[0];
        } else if (isValidAustraliaPostcode(postal)) {
            code = splitPostalCode(COUNTRY_AU, postal)[0];
        } else if (isValidCanadianPostalCode(postal)) {
            code = splitPostalCode(COUNTRY_CA, postal)[0];
        } else if (isValidUnitedKingdomPostcode(postal)) {
            code = splitPostalCode(COUNTRY_UK, postal)[0];
        } else {
            return null;
        }

        return code;
    }
}


text:
{% extends "base.html" %}
{% block content %}

Toggle README

English

What is the django-action?

Django-action is a small and simple application which would help you to implement actions similar to django.contrib.admin case for your custom tasks outside django admin. Also it provides custom form support if you would like to change some data for the queryset instances.

Fast use

(sample with approval and custom forms you will find withing example app into the repository)

Fast model instances deletion (without form’s approval):

Model:

from django.db import models
from apps.files.actions import force_delete_action
class File(models.Model):
    title = models.CharField('Title', max_length=128)
    file = models.FileField(upload_to='media/files')
    actions = [force_delete_action, ]

django-action (apps.files.actions):

def force_delete_action(request, qset, model, **kwargs):
    for q in qset:
        q.file.delete() #deletes file
        q.delete() #deletes instance
    return {'qset': qset}
force_delete_action.short_description = 'force delete files'

Template:

{% extends "base.html" %} {% load actiontags %}
{% block content %}
    {% if posts %}
    {# {% get_action_list for 'example.post' as actions %} #} {# works as well as listed below #}
    {% get_action_list for posts as actions %}
    {% if actions.object_list %}
        <form action='{% url url_act actions.action %}' method='post' id='id_action_posts'>
        {% csrf_token %}
        {% show_actions actions.object_list %}
    {% endif %}
        {% for p in posts %}
            <li>{% if actions.object_list %}
                <input name='items' value='{{ p.id }}' type='checkbox' class='void'>

                {% endif %}
                {{ p.title }}: {{ p.category }}
                <div class='content'>
                    {{ p.content }}
                <div class='author'>{{ p.author }} ({{ p.ip_addr }})</div>
                </div>
            </li>
        {% endfor %}
    {% if actions.object_list %}
        <input type='submit' value='submit'>

    </form>
    {% endif %}
    {% else %}
        <h3>It might be usefull to add some posts ;), don't you find it?</h3>
    {% endif %}
{% endblock %}

Russian

Что такое django-action?

Django-action – небольшое приложение, которое повторяет возможности actions django.contrib.admin вне django админки.

Использование

См. выше

Viewed, sample based on view modification (apps.example.views.viewed)

Viewless, non-view based example (apps.example.views.viewless)

{% endblock %}


text:
package cafe.audio;

import java.io.File;

import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;

public class DrawWaveform {

	private Image image;
	private int width;
	private int height;
	private Device device;
	private String fileName;
	public DrawWaveform(int w, int h,Device dv,String fn) {
		width = w;
		height = h;
		device=dv;
		fileName=fn;
	}

	public void draw() {
		image = new Image(device,width,height);
		GC gc = new GC(image);
		Rectangle bounds = image.getBounds();

		try {

			WavFile wavFile = WavFile.openWavFile(new File(fileName));
			int numChannels = wavFile.getNumChannels();
			double[] buffer = new double[100 * numChannels];
			int framesRead;
			double x = 0;
			double dx = ((double) width / wavFile.getNumFrames());
			do {
				framesRead = wavFile.readFrames(buffer, 100);
				for (int s=0 ; s<(framesRead * numChannels)-1 ; s++)
				{
					gc.drawLine((int) x,(int)((1+buffer[s* numChannels])*(height/2.0)),(int) x,(int)((1+buffer[(s+1)* numChannels])*(height/2.0)));
					x += dx;
				}
			}
			while ((framesRead != 0) && (x<width));
			wavFile.close();
			gc.dispose();

/*
			WavFile wavFile = WavFile.openWavFile(new File(fileName));
			int numChannels = wavFile.getNumChannels();
			int samplesPerSec = (int) wavFile.getSampleRate();
			double x = 0;
			double dx = ((double) width / (wavFile.getNumFrames()/10.0));
			int start = 0;
			int finish = (int) wavFile.getNumFrames();
			int[] buffer = new int[10 * numChannels];
			int framesRead;
			int last;

			buffer[0] = 0;
			for (int i=0; i<start; i+=10)
				framesRead = wavFile.readFrames(buffer,10);
			last = last=buffer[0];

			for (int i=start; i<finish; i+=10) {
				framesRead = wavFile.readFrames(buffer,10);
				gc.drawLine((int) x,(int)(((65536/2.0+buffer[0])/65536.0)*(height/2.0)),(int) (x+dx),(int)(((65536/2.0+last)/65536.0)*(height/2.0)));
				x += dx;
				last=buffer[0];
			}
			wavFile.close();
			gc.dispose();
*/
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void redraw(int w,int h){
		width=w;
		height=h;
		draw();
	}
	public Image getImage() {
		return image;
	}

}


text:
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';

// Config.
import { AppConfig } from '../app/app.config';

@Injectable()
export class StorageUtil {

    constructor(private appConfig: AppConfig, private storage: Storage) {

    }

    set(key, value) {
        return this.storage.set(key, value);
    }

    get(key) {
        return this.storage.get(key);
    }

    remove(key) {
        this.storage.remove(key);
    }
}


text:
class ChangeDateOnSurveyToDatetime < ActiveRecord::Migration[5.0]
  def change
    change_column :surveys, :date, :datetime
  end
end