text:
module Grape
  module Validations
    module Types
      # Work out the +Virtus::Attribute+ object to
      # use for coercing strings to the given +type+.
      # Coercion +method+ will be inferred if none is
      # supplied.
      #
      # If a +Virtus::Attribute+ object already built
      # with +Virtus::Attribute.build+ is supplied as
      # the +type+ it will be returned and +method+
      # will be ignored.
      #
      # See {CustomTypeCoercer} for further details
      # about coercion and type-checking inference.
      #
      # @param type [Class] the type to which input strings
      #   should be coerced
      # @param method [Class,#call] the coercion method to use
      # @return [Virtus::Attribute] object to be used
      #   for coercion and type validation
      def self.build_coercer(type, method = nil)
        cache_instance(type, method) do
          create_coercer_instance(type, method)
        end
      end

      def self.create_coercer_instance(type, method = nil)
        # Accept pre-rolled virtus attributes without interference
        return type if type.is_a? Virtus::Attribute

        converter_options = {
          nullify_blank: true
        }
        conversion_type = if method == JSON
                            Object
                            # because we want just parsed JSON content:
                            # if type is Array and data is `"{}"`
                            # result will be [] because Virtus converts hashes
                            # to arrays
                          else
                            type
                          end

        # Use a special coercer for multiply-typed parameters.
        if Types.multiple?(type)
          converter_options[:coercer] = Types::MultipleTypeCoercer.new(type, method)
          conversion_type = Object

        # Use a special coercer for custom types and coercion methods.
        elsif method || Types.custom?(type)
          converter_options[:coercer] = Types::CustomTypeCoercer.new(type, method)

        # Special coercer for collections of types that implement a parse method.
        # CustomTypeCoercer (above) already handles such types when an explicit coercion
        # method is supplied.
        elsif Types.collection_of_custom?(type)
          converter_options[:coercer] = Types::CustomTypeCollectionCoercer.new(
            type.first, type.is_a?(Set)
          )

        # Grape swaps in its own Virtus::Attribute implementations
        # for certain special types that merit first-class support
        # (but not if a custom coercion method has been supplied).
        elsif Types.special?(type)
          conversion_type = Types::SPECIAL[type]
        end

        # Virtus will infer coercion and validation rules
        # for many common ruby types.
        Virtus::Attribute.build(conversion_type, converter_options)
      end

      def self.cache_instance(type, method, &_block)
        key = cache_key(type, method)

        return @__cache[key] if @__cache.key?(key)

        instance = yield

        @__cache_write_lock.synchronize do
          @__cache[key] = instance
        end

        instance
      end

      def self.cache_key(type, method)
        [type, method].compact.map(&:to_s).join('_')
      end

      instance_variable_set(:@__cache,            {})
      instance_variable_set(:@__cache_write_lock, Mutex.new)
    end
  end
end


text:
package org.apache.druid.segment.serde.cell;

public class TestCaseResult
{
  public final byte[] bytes;
  public final int size;
  public final Exception exception;

  private TestCaseResult(byte[] bytes, int size, Exception exception)
  {
    this.bytes = bytes;
    this.size = size;
    this.exception = exception;
  }

  public static TestCaseResult of(Exception exception)
  {
    return new TestCaseResult(null, -1, exception);
  }

  public static TestCaseResult of(int sizeBytes)
  {
    return new TestCaseResult(null, sizeBytes, null);
  }

  public static TestCaseResult of(byte[] bytes)
  {
    return new TestCaseResult(bytes, bytes.length, null);
  }

  public static TestCaseResult of(byte[] bytes, int sizeBytes)
  {
    return new TestCaseResult(bytes, sizeBytes, null);
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8" ?>
<widget xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0" id="com.salesucation.youarehere" version="0.0.3">

    <name>You are here</name>

    <description>
        You are here example
    </description>
    <content src="www/index.html" />
    <author href="https://rhildred.github.io" email="rhildred@gmail.com">
        Rich Hildred and Mobile App Class of 2015
    </author>
    <!-- We'll include the Barcode plugin as an example -->
    <gap:plugin name="de.appplant.cordova.plugin.badge" />
    <gap:plugin name="org.apache.cordova.geolocation" />
    <gap:plugin name="org.apache.cordova.device" />
    <feature name="Geolocation">
        <param name="ios-package" value="CDVLocation" />
    </feature>
</widget>


text:
package com.chicm.cmraft.rpc;

import org.junit.Test;

import com.chicm.cmraft.common.CmRaftConfiguration;
import com.chicm.cmraft.common.ServerInfo;
import com.chicm.cmraft.core.RaftRpcService;

public class TestRpcServer {

  public static void main(String[] args) {
    RpcServer server = new RpcServer(CmRaftConfiguration.create(), RaftRpcService.create(),
      new ServerInfo("localhost", 12888));
    server.startRpcServer();
    //server.startTPSReport();
    /*
    for (int i =0; i < 5; i++) {
      //final RpcClient client = new RpcClient(CmRaftConfiguration.create(), new ServerInfo("localhost", 18080));
      final RpcClient client = new RpcClient(CmRaftConfiguration.create(), server.getServerInfo());
      for(int j = 0; j < 5; j++) {
        new Thread(new Runnable() {
          public void run() {
            client.sendRequest(100);

          }
        }).start();
      }
    }*/
  }

  @Test
  public void testStartServer() {
    RpcServer server = new RpcServer(CmRaftConfiguration.create(), RaftRpcService.create(), new ServerInfo("localhost", 12888));
    //server.startRpcServer();
  }
}

/*
class TestClient implements Runnable {
  private static final int NTHREADS = 100;

  public static void sendData() {
    ExecutorService es = Executors.newFixedThreadPool(NTHREADS);
    Thread[] threads = new Thread[NTHREADS];
    for(int i = 0; i < NTHREADS; i++) {
      threads[i] = new Thread(new TestClient());
      threads[i].setName(String.format("CLIENT%02d", i));
      es.submit(threads[i]);

    }
    try {
      es.awaitTermination(Integer.MAX_VALUE, TimeUnit.DAYS);
    } catch (InterruptedException e) {

    }
  }

  public void run() {
    try (SocketChannel channel = SocketChannel.open()) {
      SocketAddress adr = new InetSocketAddress("localhost", RpcServer.DEFAULT_SERVER_PORT);
      channel.connect(adr);

      for(int i =0; i< 1; i++) {
      String str = Thread.currentThread().getName() + " Hello";
      byte[] bytes = str.getBytes();
      ByteBuffer buf = ByteBuffer.wrap(bytes);
      channel.write(buf);

      channel.close();
      }
    } catch(Exception e) {
      e.printStackTrace(System.out);
    }
  }
}*/


text:
@implementation MikeInstagramPost

- (instancetype)initWithJSON:(NSDictionary *)json {

    if (self = [super init]) {

        self.tags = json[@"tags"];
        self.commentCount = [json[@"comments"][@"count"] integerValue];
        self.likeCount = [json[@"likes"][@"count"] integerValue];
        self.caption = json[@"caption"];
        self.username = json[@"user"][@"username"];
        self.fullName = json[@"user"][@"full_name"];
        self.imageURL = json[@"images"][@"standard_resolution"][@"url"];

        self.avatarImageURL = json[@"user"][@"profile_picture"];

        self.comments = [[NSMutableArray alloc] init];
        if (json[@"caption"]) {
            [self.comments addObject:[self parseComment:json[@"caption"]]];
        }

        for (NSDictionary *comment in json[@"comments"][@"data"]) {
            [self.comments addObject:[self parseComment:comment]];
        }

        return self;
    }
    return nil;
}

- (NSMutableAttributedString *)parseComment:(NSDictionary *)json {
    NSString *fromUsername = json[@"from"][@"username"];
    NSString *text = json[@"text"];

    NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ %@ \n\n", fromUsername, text]];

    UIFont *font = [UIFont systemFontOfSize:13];
    [resultString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, resultString.length)];

    UIFont *mediumFont = [UIFont systemFontOfSize:13 weight:UIFontWeightMedium];
    [resultString addAttribute:NSFontAttributeName value:mediumFont range:NSMakeRange(0, fromUsername.length)];
    [resultString addAttribute:NSForegroundColorAttributeName value:[UIColor darkBlueColor] range:NSMakeRange(0, fromUsername.length)];

    return resultString;
}

@end


text:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { RouterModule } from '@angular/router';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
import { routes } from './routes';

import { App } from './components/app';
import { Header } from './components/common/header';
import { LoginPage } from './components/login/loginPage';
import { Banner } from './components/login/banner';
import { LoginForm } from './components/login/loginForm';
import { PatientsPage } from './components/patients/patientsPage';

@NgModule({
  declarations: [
    App,
    Header,
    LoginPage,
    Banner,
    LoginForm,
    PatientsPage
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  bootstrap: [App],
  providers: [
    { provide: LocationStrategy, useClass: HashLocationStrategy }
  ]
})
class AppModule {

}

platformBrowserDynamic().bootstrapModule(AppModule)


text:
import React from 'react';
import { render } from 'react-dom';
import { browserHistory } from 'react-router';
import injectTapEventPlugin from 'react-tap-event-plugin';
import { syncHistoryWithStore } from 'react-router-redux';
import initStore from './store';
import initTheme from './theme';
import routes from './routes';
import App from './containers/App';
import './styles/common.scss';

const { env: { NODE_ENV, RENDERING_ON } } = process;

const { INITIAL_STATE } = window;

const store = initStore(INITIAL_STATE);
const theme = initTheme(navigator.userAgent);
const history = syncHistoryWithStore(browserHistory, store);

injectTapEventPlugin();

function renderApp() {
  render(
    <App
      store={store}
      theme={theme}
      routes={routes}
      history={history}
    />,
    document.getElementById('app'),
  );
}

if (NODE_ENV === 'development' && RENDERING_ON === 'client') {
  if (module.hot) {
    module.hot.accept('./routes', () => {
      require('./routes');

      renderApp();
    });
  }
}

document.addEventListener('DOMContentLoaded', () => {
  renderApp();
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AInBox.Astove.Core.Attributes;

namespace AInBox.Astove.Core.Logging
{
    public interface ILog<T>
        where T: class
    {
        [StringFormatMethodAttribute("format")]
        void Debug(string format, params object[] args);
        [StringFormatMethodAttribute("format")]
        void Info(string format, params object[] args);
        [StringFormatMethodAttribute("format")]
        void Warn(string format, params object[] args);

        [StringFormatMethodAttribute("format")]
        void Error(string format, params object[] args);
        void Error(Exception ex);

        [StringFormatMethodAttribute("format")]
        void Error(Exception ex, string format, params object[] args);

        [StringFormatMethodAttribute("format")]
        void Fatal(Exception ex, string format, params object[] args);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RateAndReview
{
    class RateReviewService : IRateReview
    {
        private readonly RateReviewHelper _helper;

         public RateReviewService()
        {
            _helper = new RateReviewHelper();
        }

        public void LaunchRateAndReview(int count)
        {
            _helper.LaunchRateAndReview(count);
        }
    }
}


text:
layout: post
title: La digestión de las serpientes
---

Por todos es sabido que las serpientes son animales de "sangre fría", que significa que no son capaces de regular su temperatura corporal y que por tanto dependen de la temperatura ambiental para sobrevivir[^1].

Para incrementar su temperatura interna suelen tomar el sol en rocas u otros tipos de suelos que transmitan bien el calor. De esta forma consiguen subir su temperatura en un corto espacio de tiempo y pueden volver a lugares seguros donde son menos visibles.

Aunque son capaces de sobrevivir con temperaturas bajas, en ciertos momentos les resulta imprescindible mantener una temperatura corporal elevada. Uno de esos momentos es durante la caza: la temperatura elevada les proporciona la energía necesaria para la actividad. Otro momento importante es inmediatamente después, durante la digestión. En caso de que sus cuerpos sufrieran un enfriamiento, la presa engullida podría pudrirse y terminar matándolas "desde dentro".

Debido a esto, las serpientes deben planificar muy bien cuándo salir de caza. Necesitan buscar el momento del día en el que la temperatura ambiente se mantiene por encima de un umbral por más tiempo; eso les garantiza que tendrán tiempo suficiente para calentarse, buscar la presa, cazarla y digerirla.

Como miembros del equipo de apoyo de los biólogos australianos que estudian la fauna local, debemos comprobar si las serpientes escogen el momento de caza de forma óptima o no. Nuestra primera tarea es analizar la secuencia de temperatura ambiente de un día y encontrar la duración del periodo más largo en la que esa temperatura se mantiene lo suficientemente elevada. Eso sí, las serpientes tienen cierta tolerancia y admiten pequeños intervalos de tiempo con temperaturas por debajo del umbral deseado.

[^1]: En realidad en un contexto científico, el término "sangre fría" y "sangre caliente" ya no se utiliza directamente, pues se ha visto que los tipos de temperatura corporal no son tan simples como para utilizar únicamente esas dos categorías.

# Entrada

La entrada estará compuesta por distintos casos de prueba, cada uno ocupando dos líneas.

La primera línea de cada caso de prueba tendrá dos enteros, el primero indicando el número de mediciones realizadas (1 ≤ n ≤ 100.000), y el segundo el número k de mediciones consecutivas por debajo del umbral que una serpiente es capaz de soportar entre dos mediciones con temperaturas altas.

La segunda línea contiene n números que serán siempre ceros o unos. Un cero indica una temperatura demasiado baja para la serpiente para calentarse, mientras que un uno indica una temperatura aceptable.

La entrada termina con una línea con dos ceros, que no deberá procesarse.

# Salida

Por cada caso de prueba se escribirá la longitud del periodo más largo (medido en número de muestras) que tiene la serpiente para comer.

Un periodo es válido si comienza y termina por unos y entre dos lecturas con temperaturas por encima del umbral no hay más de k medidas consecutivas con temperaturas por debajo.

# Entrada de ejemplo

```
6 0
0 1 0 1 0 0
6 0
0 1 0 1 1 0
8 1
1 0 0 1 0 1 0 1
0 0
```

# Salida de ejemplo

```
1
2
5
```

# Solución propuesta

``` python

```

[Enlace del código](https://github.com/israelem/aceptaelreto/blob/master/codes/2018-07-23-digestion.py)

[Enlace en aceptaelreto.com](https://www.aceptaelreto.com/problem/statement.php?id=444)


text:
define(['Backbone', 'bootstrap', 'views/zs_notify_view'], function(B, b, zsNotifyView) {
  console.log("inside zs_all_question_view")

  var zsAllQuestionView = Backbone.View.extend({
    el: 'body',

    events: {
      // #TODO replace load more button click with page end scroll event
      "click .question-short-load-more": "load_more",
      "click .question_short_body.shrunk": "expand_question",
      // "click .question_short_body.expanded": "expand_question",
    },

    initialize: function() {
      console.log("zs all question view initialized");
      zsNotifyView = new zsNotifyView();
    },

    expand_question: function(e) {
      console.log("inside expand_question");
      // console.log(e.target);
      zsNotifyView.nv_show(1);

      var clicked_element = $(e.target);
      var parent_div = clicked_element.closest(".post-div");
      var element = parent_div.find("a.question_short_body");
      var post_permalink = parent_div.find("#permalink a").attr("href");
      // console.log(post_permalink);

      $.ajax({
        type: 'GET',
        url: post_permalink+'/html',
        success: function(data, status, jqxhr) {
          // console.log(jqxhr.status);
          // $(".question_short_list").append(data);
          if (data.question_data.content_text){
            // console.log("putting it in...");
            // console.log(data.question_data.content_text);
            element.html(data.question_data.content_text);
            element.removeClass("shrunk");
            element.removeAttr("href");
          }
          zsNotifyView.nv_hide(1);
        },
        error: function(jqxhr, status) {
          // console.log(jqxhr.status);
          zsNotifyView.nv_show(1, jqxhr.responseText, 5000);
        },
      });

      return false;
    },

    load_more: function() {
      zsNotifyView.nv_show(1);
      // console.log("load even more button clicked");
      //#TODO#DONE get more stuff and stuff it in the thing
      var post_short = $(".post-div.post-short");
      var lastId = $(post_short[post_short.length - 1]).attr("num");
      var limit = 20;
      var order = $(".question_short_list").attr("order");

      // console.log("lastId:", lastId);
      // console.log("limit:", limit);
      // console.log("order:", order);

      $.ajax({
        type: 'GET',
        url: '/questions/'+order+'/'+lastId+'/'+limit+'/html',
        success: function(data, status, jqxhr) {
          // console.log(jqxhr.status);
          $(".question_short_list").append(data);
          zsNotifyView.nv_hide(1);
        },
        error: function(jqxhr, status) {
          // console.log(jqxhr.status);
          zsNotifyView.nv_show(1, jqxhr.responseText, 5000);
        },
      });

    },

    render: function() {
      // console.log("in zs_all_question_view render function");
      return this;
    }

  });

  return zsAllQuestionView;
});


text:
<!doctype html>

    <meta charset="utf-8">
    <title>Weather stations</title>
    <meta name="description" content="View detailed information from weather stations located all around Slovenia.">
    <meta name="viewport" content="width=device-width">

    <link rel="stylesheet" href="styles/layout.css">


text:
module Spree
  Payment.class_eval do
    state_machine initial: :checkout do
      after_transition to: :completed, do: :create_subscriptions!
    end

    def create_subscriptions!
      self.order.create_subscriptions
    end
  end
end


text:
Given the position of two queens on a chess board, indicate whether or not they
are positioned so that they can attack each other.

In the game of chess, a queen can attack pieces which are on the same
row, column, or diagonal.

A chessboard can be represented by an 8 by 8 array.

So if you're told the white queen is at (2, 3) and the black queen at
(5, 6), then you'd know you've got a set-up like so:

```text
_ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _
_ _ _ W _ _ _ _
_ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _
_ _ _ _ _ _ B _
_ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _
```

You'd also be able to answer whether the queens can attack each other.
In this case, that answer would be yes, they can, because both pieces
share a diagonal.

## Exception messages

Sometimes it is necessary to raise an exception. When you do this, you should include a meaningful error message to
indicate what the source of the error is. This makes your code more readable and helps significantly with debugging. Not
every exercise will require you to raise an exception, but for those that do, the tests will only pass if you include
a message.

To raise a message with an exception, just write it as an argument to the exception type. For example, instead of
`raise Exception`, you shold write:

```python
raise Exception("Meaningful message indicating the source of the error")
```

## Submitting Exercises

Note that, when trying to submit an exercise, make sure the solution is in the `exercism/python/<exerciseName>` directory.

For example, if you're submitting `bob.py` for the Bob exercise, the submit command would be something like `exercism submit <path_to_exercism_dir>/python/bob/bob.py`.

For more detailed information about running tests, code style and linting,
please see the [help page](http://exercism.io/languages/python).

## Source

J Dalbey's Programming Practice problems [http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html](http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html)

## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.


text:
console.log('renderer process  called ');

var webFrame = require('electron').webFrame;
var SpellCheckProvider = require('electron-spell-check-provider');
var spellchecker = require('spellchecker');
var word1 = 'ttst'
console.log('Test log: Test spellchecker with word '+word1+' '+ spellchecker.isMisspelled(word1) + ' suggestions include '+ spellchecker.getCorrectionsForMisspelling(word1) );

webFrame.setSpellCheckProvider('en-US', true,
    new SpellCheckProvider('en-US').on('misspelling', function(suggestions) {
        console.log('The text at the site of the cursor is misspelled.',
            'Maybe the user meant to type:', suggestions);
    }));


text:
<?php

namespace MixedElements;

function ($mixed) {
	die;
};


text: mailru-verification: a786979addadc345


text:
package heroku

import (
	"crypto/tls"
	"os"
	"strings"

	"github.com/Shopify/sarama"
)

// NewConsumer creates a github.com/Shopify/sarama.Consumer configured from the
// standard Heroku Kafka environment.
func NewConsumer(cfg *sarama.Config) (sarama.Consumer, error) {
	herokuCfg, err := NewConfig()
	if err != nil {
		return nil, err
	}

	if cfg == nil {
		cfg = sarama.NewConfig()
	}

	cfg.Net.TLS.Enable = herokuCfg.TLS()
	cfg.Net.TLS.Config = herokuCfg.TLSConfig()

	consumer, err := sarama.NewConsumer(herokuCfg.Brokers(), cfg)
	if err != nil {
		return nil, err
	}

	return consumer, nil
}

// NewAsyncProducer creates a github.com/Shopify/sarama.AsyncProducer
// configured from the standard Heroku Kafka environment. When publishing
// messages to Multitenant Kafka all topics need to start with KAFKA_PREFIX
// which is best added using AppendPrefixTo.
func NewAsyncProducer(cfg *sarama.Config) (sarama.AsyncProducer, error) {
	herokuCfg, err := NewConfig()
	if err != nil {
		return nil, err
	}

	if cfg == nil {
		cfg = sarama.NewConfig()
	}

	cfg.Net.TLS.Enable = herokuCfg.TLS()
	cfg.Net.TLS.Config = herokuCfg.TLSConfig()

	return sarama.NewAsyncProducer(herokuCfg.Brokers(), cfg)
}

// NewSyncProducer creates a github.com/Shopify/sarama.SyncProducer configured
// from the standard Heroku Kafka environment. When publishing messages to
// Multitenant Kafka all topics need to start with KAFKA_PREFIX which is best
// added using AppendPrefixTo.
func NewSyncProducer(cfg *sarama.Config) (sarama.SyncProducer, error) {
	herokuCfg, err := NewConfig()
	if err != nil {
		return nil, err
	}

	if cfg == nil {
		cfg = sarama.NewConfig()
	}

	cfg.Net.TLS.Enable = herokuCfg.TLS()
	cfg.Net.TLS.Config = herokuCfg.TLSConfig()

	return sarama.NewSyncProducer(herokuCfg.Brokers(), cfg)
}

// AppendPrefixTo adds the env variable KAFKA_PREFIX to the given string if
// necessary. Heroku requires prefixing topics and consumer group names with
// the prefix on multi-tenant plans. It is safe to use on dedicated clusters if
// KAFKA_PREFIX is not set.
func AppendPrefixTo(name string) string {
	prefix := os.Getenv("KAFKA_PREFIX")

	if strings.HasPrefix(name, prefix) {
		return name
	}

	return prefix + name
}

// Create the TLS context, using the key and certificates provided.
func TLSConfig() (*tls.Config, error) {
	config, err := NewConfig()
	if err != nil {
		return nil, err
	}

	return config.TLSConfig(), nil
}

// Brokers returns a list of host:port addresses for the Kafka brokers set in
// KAFKA_URL.
func Brokers() ([]string, error) {
	config, err := NewConfig()
	if err != nil {
		return nil, err
	}

	return config.Brokers(), nil
}


text:
<!DOCTYPE html>

		<title>{{siteTitle}}</title>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />

		<link rel="stylesheet" href="/css/wing-0.1.9.min.css" />
		<link rel="stylesheet" href="/css/main.css" />
		<link rel="stylesheet" href="/css/index.css" />
		<link rel="stylesheet" href="/css/theme.css" />

		{{#if user.confirmed}}
			{{#if settings.qrEnabled}}

			{{/if}}
		{{/if}}

		{{#> sidebar}}

Dashboard

Application Submission

Application Decision

Confirmation Submission

Team Formation (optional)

Your status:

						{{status}}

Welcome back, {{user.name}}!

					{{#if user.confirmed}}

Application type: {{user.applicationBranch}}

Confirmation type: {{user.confirmationBranch}}

						{{#unless autoConfirm}}
							{{#if confirmationStatus.areOpen}}

Feel free to edit your RSVP at any time. However, once RSVPing closes on {{confirmationClose}}, you will not be able to edit it anymore.

								Edit your confirmation
							{{else}}

RSVPing closed on {{confirmationClose}}.

							{{/if}}
						{{/unless}}

						{{#if settings.qrEnabled}}
							{{#if user.accepted}}

Show your QR code to check in when you get here.

							{{/if}}
						{{/if}}
					{{else if user.confirmationBranch}}
						{{#if confirmationStatus.areOpen}}

Please confirm your application decision.

Application type: {{user.applicationBranch}}

Confirmation type: {{user.confirmationBranch}}

							{{#ifCond allConfirmationTimes.length 1}}

You must confirm your decision by {{confirmationClose}}.

							{{else}}

If you do not RSVP before the deadline for your confirmation type, you will not be able to attend {{siteTitle}}!

									{{#each allConfirmationTimes}}

{{this.name}}: {{this.open}} until {{this.close}}

									{{/each}}

							{{/ifCond}}
							Confirm your attendance
						{{else}}

Application type: {{user.applicationBranch}}

							{{#if confirmationStatus.beforeOpen}}
								{{#ifCond allConfirmationTimes.length 1}}

RSVPing will open on {{confirmationOpen}}.

								{{else}}

RSVPing will be open during the following times:

										{{#each allConfirmationTimes}}

{{this.name}}: {{this.open}} until {{this.close}}

										{{/each}}

								{{/ifCond}}
							{{/if}}
							{{#if confirmationStatus.afterClose}}
								{{#ifCond allConfirmationTimes.length 1}}

RSVPs closed on {{confirmationClose}}. Thanks for your interest in {{siteTitle}} — we hope to see you next time!

								{{else}}

RSVPs closed at the following times. Thanks for your interest in {{siteTitle}} — we hope to see you next time!

										{{#each allConfirmationTimes}}

{{this.name}}: {{this.close}}

										{{/each}}

								{{/ifCond}}
							{{/if}}
						{{/if}}
					{{else if user.applied}}

You've applied and are all set for now!

Application type: {{user.applicationBranch}}

						{{#if applicationStatus.areOpen}}

Feel free to edit your application at any time. However, once registration closes on {{applicationClose}}, you will not be able to edit it any further.

							Edit your application
						{{else}}

Applications closed on {{applicationClose}}.

						{{/if}}
					{{else}}
						{{#if applicationStatus.areOpen}}

You still need to complete your application!

							{{#ifCond allApplicationTimes.length 1}}

If you do not complete your application before {{applicationClose}}, you will not be considered for {{siteTitle}}!

							{{else}}

If you do not complete your application before the following times, you will not be considered for {{siteTitle}}:

									{{#each allApplicationTimes}}

{{this.name}}: {{this.close}}

									{{/each}}

							{{/ifCond}}
							Complete your application
						{{else}}
							{{#if applicationStatus.beforeOpen}}
								{{#ifCond allApplicationTimes.length 1}}

Applications are currently closed and will open on {{applicationOpen}}.

								{{else}}

Applications are currently closed and will open at the following times:

										{{#each allApplicationTimes}}

{{this.name}}: {{this.open}}

										{{/each}}

								{{/ifCond}}
							{{/if}}
							{{#if applicationStatus.afterClose}}
								{{#ifCond allApplicationTimes.length 1}}

Applications closed on {{applicationClose}}. Thanks for your interest in {{siteTitle}} — we hope to see you next time!

								{{else}}

Applications closed at the following times. Thanks for your interest in {{siteTitle}} — we hope to see you next time!

										{{#each allApplicationTimes}}

{{this.name}}: {{this.close}}

										{{/each}}

								{{/ifCond}}
							{{/if}}
						{{/if}}
					{{/if}}

		{{/sidebar}}


text: module.exports = require('sails-auth/api/services/protocols/basic');


text:
package filters

import (
	"errors"
	"fmt"
	"net/http"
	"strings"

	"github.com/golang/glog"

	"k8s.io/apiserver/pkg/authentication/serviceaccount"
	"k8s.io/apiserver/pkg/authentication/user"
	"k8s.io/apiserver/pkg/authorization/authorizer"
	"k8s.io/apiserver/pkg/endpoints/handlers/responsewriters"
	"k8s.io/apiserver/pkg/endpoints/request"
	"k8s.io/apiserver/pkg/server/httplog"
	"k8s.io/client-go/pkg/api"
	authenticationapi "k8s.io/client-go/pkg/apis/authentication"
)

// WithImpersonation is a filter that will inspect and check requests that attempt to change the user.Info for their requests
func WithImpersonation(handler http.Handler, requestContextMapper request.RequestContextMapper, a authorizer.Authorizer) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		impersonationRequests, err := buildImpersonationRequests(req.Header)
		if err != nil {
			glog.V(4).Infof("%v", err)
			responsewriters.InternalError(w, req, err)
			return
		}
		if len(impersonationRequests) == 0 {
			handler.ServeHTTP(w, req)
			return
		}

		ctx, exists := requestContextMapper.Get(req)
		if !exists {
			responsewriters.InternalError(w, req, errors.New("no context found for request"))
			return
		}
		requestor, exists := request.UserFrom(ctx)
		if !exists {
			responsewriters.InternalError(w, req, errors.New("no user found for request"))
			return
		}

		// if groups are not specified, then we need to look them up differently depending on the type of user
		// if they are specified, then they are the authority (including the inclusion of system:authenticated/system:unauthenticated groups)
		groupsSpecified := len(req.Header[authenticationapi.ImpersonateGroupHeader]) > 0

		// make sure we're allowed to impersonate each thing we're requesting.  While we're iterating through, start building username
		// and group information
		username := ""
		groups := []string{}
		userExtra := map[string][]string{}
		for _, impersonationRequest := range impersonationRequests {
			actingAsAttributes := &authorizer.AttributesRecord{
				User:            requestor,
				Verb:            "impersonate",
				APIGroup:        impersonationRequest.GetObjectKind().GroupVersionKind().Group,
				Namespace:       impersonationRequest.Namespace,
				Name:            impersonationRequest.Name,
				ResourceRequest: true,
			}

			switch impersonationRequest.GetObjectKind().GroupVersionKind().GroupKind() {
			case api.Kind("ServiceAccount"):
				actingAsAttributes.Resource = "serviceaccounts"
				username = serviceaccount.MakeUsername(impersonationRequest.Namespace, impersonationRequest.Name)
				if !groupsSpecified {
					// if groups aren't specified for a service account, we know the groups because its a fixed mapping.  Add them
					groups = serviceaccount.MakeGroupNames(impersonationRequest.Namespace, impersonationRequest.Name)
				}

			case api.Kind("User"):
				actingAsAttributes.Resource = "users"
				username = impersonationRequest.Name

			case api.Kind("Group"):
				actingAsAttributes.Resource = "groups"
				groups = append(groups, impersonationRequest.Name)

			case authenticationapi.Kind("UserExtra"):
				extraKey := impersonationRequest.FieldPath
				extraValue := impersonationRequest.Name
				actingAsAttributes.Resource = "userextras"
				actingAsAttributes.Subresource = extraKey
				userExtra[extraKey] = append(userExtra[extraKey], extraValue)

			default:
				glog.V(4).Infof("unknown impersonation request type: %v", impersonationRequest)
				responsewriters.Forbidden(actingAsAttributes, w, req, fmt.Sprintf("unknown impersonation request type: %v", impersonationRequest))
				return
			}

			allowed, reason, err := a.Authorize(actingAsAttributes)
			if err != nil || !allowed {
				glog.V(4).Infof("Forbidden: %#v, Reason: %s, Error: %v", req.RequestURI, reason, err)
				responsewriters.Forbidden(actingAsAttributes, w, req, reason)
				return
			}
		}

		if !groupsSpecified && username != user.Anonymous {
			// When impersonating a non-anonymous user, if no groups were specified
			// if neither the system:authenticated nor system:unauthenticated groups are explicitly included,
			// include the system:authenticated group in the impersonated user info
			found := false
			for _, group := range groups {
				if group == user.AllAuthenticated || group == user.AllUnauthenticated {
					found = true
					break
				}
			}
			if !found {
				groups = append(groups, user.AllAuthenticated)
			}
		}

		newUser := &user.DefaultInfo{
			Name:   username,
			Groups: groups,
			Extra:  userExtra,
		}
		requestContextMapper.Update(req, request.WithUser(ctx, newUser))

		oldUser, _ := request.UserFrom(ctx)
		httplog.LogOf(req, w).Addf("%v is acting as %v", oldUser, newUser)

		// clear all the impersonation headers from the request
		req.Header.Del(authenticationapi.ImpersonateUserHeader)
		req.Header.Del(authenticationapi.ImpersonateGroupHeader)
		for headerName := range req.Header {
			if strings.HasPrefix(headerName, authenticationapi.ImpersonateUserExtraHeaderPrefix) {
				req.Header.Del(headerName)
			}
		}

		handler.ServeHTTP(w, req)
	})
}

// buildImpersonationRequests returns a list of objectreferences that represent the different things we're requesting to impersonate.
// Also includes a map[string][]string representing user.Info.Extra
// Each request must be authorized against the current user before switching contexts.
func buildImpersonationRequests(headers http.Header) ([]api.ObjectReference, error) {
	impersonationRequests := []api.ObjectReference{}

	requestedUser := headers.Get(authenticationapi.ImpersonateUserHeader)
	hasUser := len(requestedUser) > 0
	if hasUser {
		if namespace, name, err := serviceaccount.SplitUsername(requestedUser); err == nil {
			impersonationRequests = append(impersonationRequests, api.ObjectReference{Kind: "ServiceAccount", Namespace: namespace, Name: name})
		} else {
			impersonationRequests = append(impersonationRequests, api.ObjectReference{Kind: "User", Name: requestedUser})
		}
	}

	hasGroups := false
	for _, group := range headers[authenticationapi.ImpersonateGroupHeader] {
		hasGroups = true
		impersonationRequests = append(impersonationRequests, api.ObjectReference{Kind: "Group", Name: group})
	}

	hasUserExtra := false
	for headerName, values := range headers {
		if !strings.HasPrefix(headerName, authenticationapi.ImpersonateUserExtraHeaderPrefix) {
			continue
		}

		hasUserExtra = true
		extraKey := strings.ToLower(headerName[len(authenticationapi.ImpersonateUserExtraHeaderPrefix):])

		// make a separate request for each extra value they're trying to set
		for _, value := range values {
			impersonationRequests = append(impersonationRequests,
				api.ObjectReference{
					Kind: "UserExtra",
					// we only parse out a group above, but the parsing will fail if there isn't SOME version
					// using the internal version will help us fail if anyone starts using it
					APIVersion: authenticationapi.SchemeGroupVersion.String(),
					Name:       value,
					// ObjectReference doesn't have a subresource field.  FieldPath is close and available, so we'll use that
					// TODO fight the good fight for ObjectReference to refer to resources and subresources
					FieldPath: extraKey,
				})
		}
	}

	if (hasGroups || hasUserExtra) && !hasUser {
		return nil, fmt.Errorf("requested %v without impersonating a user", impersonationRequests)
	}

	return impersonationRequests, nil
}


text:
package ca.ualberta.cmput301f13t13.storyhoard.serverClasses;

import java.util.ArrayList;
import java.util.Collection;

/**
 * Role: Holds a collection of the SimpleESResponses. Needed when
 * doing an advanced elastic search which will possibly be retrieving
 * more than one response from the server. </br></br>
 *
 * CODE REUSE: </br>
 * This code was taken directly from: </br>
 * URL: https://github.com/rayzhangcl/ESDemo/blob/master/ESDemo/src/ca/ualberta/cs/CMPUT301/chenlei/ElasticSearchSearchResponse.java
 * </br>
 * Date: Nov. 4th, 2013 </br>
 * Licensed under CC0 (available at http://creativecommons.org/choose/zero/)
 *
 * @author Abram Hindle
 * @author Chenlei Zhang
 * @author Ashley Brown
 * @author Stephanie Gil
 *
 * @see SimpleESResponse
 * @see ESUpdates
 */
public class ElasticSearchResponse<T> {
	int took;
	boolean timed_out;
	transient Object _shards;
	Hits<T> hits;
	boolean exists;

	public Collection<SimpleESResponse<T>> getHits() {
		return hits.getHits();
	}

	public Collection<T> getSources() {
		Collection<T> out = new ArrayList<T>();
		for (SimpleESResponse<T> essrt : getHits()) {
			out.add(essrt.getSource());
		}
		return out;
	}

	public String toString() {
		return (super.toString() + ":" + took + "," + _shards + "," + exists
				+ "," + hits);
	}
}


text:
'use strict';
const express = require('express');
const app = express();
// const bodyParser = require('body-parser');
//slash as the end indicated you look in index first
// const routes = require('./routes/');

//set up environment port if none given default to 3000
const PORT = process.env.PORT || 3000;
// const SESSION_SECRET = process.env.SESSION_SECRET || 'secret';

//urlencoded parse url
// app.use(bodyParser.urlencoded({ extended: false }));
 //parse json
// app.use(bodyParser.json());

//this tells the server where to get the static files--the ones that don't change
app.use(express.static(__dirname + "/public"));

//allows you to use the diferent routes
// app.use(routes);

app.listen(PORT, () => {
  console.log(`${PORT} at your service. Node.js server started`);
});


text:
package com.pinterest.secor.parser;

import org.apache.commons.lang3.StringUtils;
import org.apache.thrift.TDeserializer;
import org.apache.thrift.TException;
import org.apache.thrift.TFieldIdEnum;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocolFactory;

import com.pinterest.secor.common.SecorConfig;
import com.pinterest.secor.message.Message;

/**
 * Thrift message parser extracts date partitions from thrift messages.
 *
 * @author Pawel Garbacki (pawel@pinterest.com)
 */
public class ThriftMessageParser extends TimestampedMessageParser {
    private final TDeserializer mDeserializer;
    private final ThriftPath mThriftPath;
    private final String mTimestampType;

    class ThriftPath implements TFieldIdEnum {
        private final String mFieldName;
        private final short mFieldId;

        public ThriftPath(final String fieldName, final short fieldId) {
            this.mFieldName = fieldName;
            this.mFieldId = fieldId;
        }

        @Override
        public short getThriftFieldId() {
            return mFieldId;
        }

        @Override
        public String getFieldName() {
            return mFieldName;
        }
    }

    public ThriftMessageParser(SecorConfig config)
            throws InstantiationException, IllegalAccessException,
            ClassNotFoundException {
        super(config);
        TProtocolFactory protocolFactory = null;
        String protocolName = mConfig.getThriftProtocolClass();

        if (StringUtils.isNotEmpty(protocolName)) {
            String factoryClassName = protocolName.concat("$Factory");
            protocolFactory = ((Class<? extends TProtocolFactory>) Class.forName(factoryClassName)).newInstance();
        } else
            protocolFactory = new TBinaryProtocol.Factory();

        mDeserializer = new TDeserializer(protocolFactory);
        mThriftPath = new ThriftPath(mConfig.getMessageTimestampName(),(short) mConfig.getMessageTimestampId());
        mTimestampType = mConfig.getMessageTimestampType();
    }

    @Override
    public long extractTimestampMillis(final Message message) throws TException {
        long timestamp;
        if ("i32".equals(mTimestampType)) {
            timestamp = (long) mDeserializer.partialDeserializeI32(message.getPayload(), mThriftPath);
        } else {
            timestamp = mDeserializer.partialDeserializeI64(message.getPayload(), mThriftPath);
        }

        return toMillis(timestamp);
    }
}


text:
package org.apache.ode.ql.tree.nodes;

import javax.xml.namespace.QName;

public class Property implements Identifier {
    private static final long serialVersionUID = -6249689910742825036L;

    private final QName name;

    /**
     * @param name
     */
    public Property(final QName name) {
        super();
        this.name = name;
    }

    public String getNamespace() {
        return name.getNamespaceURI();
    }
    /**
     * @return the name
     */
    public String getName() {
        return name.getLocalPart();
    }

}


text:
package ro.satrapu.homebudget.ui.internationalization;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Currency;
import java.util.List;
import java.util.Locale;
import javax.annotation.PostConstruct;
import javax.enterprise.inject.Model;
import javax.faces.model.SelectItem;
import javax.inject.Inject;

/**
 * Manages currencies using the current {@link Locale} instance.
 *
 * @author satrapu
 */
@Model
public class CurrencyManager {

    @Inject
    @CurrentLocale
    Locale currentLocale;
    private List<SelectItem> currencies;

    @PostConstruct
    public void init() {
        currencies = new ArrayList<>();

        for (Currency currency : Currency.getAvailableCurrencies()) {
            currencies.add(new SelectItem(currency.getCurrencyCode(),
                    MessageFormat.format("{0} ({1})", currency.getDisplayName(currentLocale), currency.getCurrencyCode())));
        }

        Collections.sort(currencies, new Comparator<SelectItem>() {
            @Override
            public int compare(SelectItem leftCurrency, SelectItem rightCurrency) {
                return leftCurrency.getLabel().compareTo(rightCurrency.getLabel());
            }
        });
    }

    public Collection<SelectItem> getCurrencies() {
        return currencies;
    }
}


text:
export var x;

//// [separateCompilationUnspecifiedModule.js]


text:
//
//  sdProtoMeta.h
//  libSpatDIFTest
//
//  Created by Chikashi Miyama on 14/10/2016.
//  Copyright © 2016 ICST. All rights reserved.
//

#pragma once
#include "sdDescriptor.h"

/**
 * @brief  An abstract class that connect an sdEntity and descriptor.
 * @detail This class holds a descriptor and a pointer to the parent Entity
 */

class sdEntity;
class sdProtoMeta: public sdDescriptor{
public:
    /*!
     returns an immutable pointer to its parent entity
     @returns a pointer to its parent entity
     */
    const sdEntity * const getParent() const {return parent;}

    virtual std::string getValueAsString() const = 0;

protected:
    sdProtoMeta(const EDescriptor descriptor, const sdEntity * const parent):
    sdDescriptor(descriptor),
    parent(parent)
    {}

    const sdEntity * const parent;/*!< a pointer to the belonging entity. unmutable */

};


text:
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import resolve, get_script_prefix
from tastypie import fields
from tastypie.fields import RelatedField
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from tastypie.authorization import DjangoAuthorization
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from tastypie.exceptions import Unauthorized, ImmediateHttpResponse, NotFound
from tastypie.http import HttpCreated
from tastypie.resources import ModelResource, Resource
from tastypie.serializers import Serializer
from tastypie.validation import FormValidation, Validation
from django.core.exceptions import ObjectDoesNotExist
from pytz import timezone
from django.conf import settings

from dojo.models import Product, Engagement, Test, Finding, \
    User, ScanSettings, IPScan, Scan, Stub_Finding, Risk_Acceptance, \
    Finding_Template, Test_Type, Development_Environment, \
    BurpRawRequestResponse, Endpoint, Notes
from dojo.forms import ProductForm, EngForm2, TestForm, \
    ScanSettingsForm, FindingForm, StubFindingForm, FindingTemplateForm, \
    ImportScanForm, SEVERITY_CHOICES
from dojo.tools.factory import import_parser_factory
from dojo.utils import get_system_setting
from datetime import datetime

localtz = timezone(get_system_setting('time_zone'))

"""
    Setup logging for the api

logging.basicConfig(
    level=logging.DEBUG,
    format='[%(asctime)s] %(levelname)s [%(name)s:%(lineno)d] %(message)s',
    datefmt='%d/%b/%Y %H:%M:%S',
    filename=settings.DOJO_ROOT + '/../dojo.log',
)
logger = logging.getLogger(__name__)
"""

class ModelFormValidation(FormValidation):
    """
    Override tastypie's standard ``FormValidation`` since this does not care
    about URI to PK conversion for ``ToOneField`` or ``ToManyField``.
    """

    resource = ModelResource

    def __init__(self, **kwargs):
        if not 'resource' in kwargs:
            raise ImproperlyConfigured("You must provide a 'resource' to 'ModelFormValidation' classes.")

        self.resource = kwargs.pop('resource')

        super(ModelFormValidation, self).__init__(**kwargs)

    def _get_pk_from_resource_uri(self, resource_field, resource_uri):
        """ Return the pk of a resource URI """
        base_resource_uri = resource_field.to().get_resource_uri()
        if not resource_uri.startswith(base_resource_uri):
            raise Exception("Couldn't match resource_uri {0} with {1}".format(
                                        resource_uri, base_resource_uri))
        before, after = resource_uri.split(base_resource_uri)
        return after[:-1] if after.endswith('/') else after

    def form_args(self, bundle):
        rsc = self.resource()
        kwargs = super(ModelFormValidation, self).form_args(bundle)

        for name, rel_field in rsc.fields.items():
            data = kwargs['data']
            if not issubclass(rel_field.__class__, RelatedField):
                continue # Not a resource field
            if name in data and data[name] is not None:
                resource_uri = (data[name] if rel_field.full is False
                                            else data[name]['resource_uri'])
                pk = self._get_pk_from_resource_uri(rel_field, resource_uri)
                kwargs['data'][name] = pk

        return kwargs

class BaseModelResource(ModelResource):
    @classmethod
    def get_fields(cls, fields=None, excludes=None):
        """
         Unfortunately we must override this method because tastypie ignores
         'blank' attribute on model fields.

         Here we invoke an insane workaround hack due to metaclass inheritance
         issues:
          http://stackoverflow.com/questions/12757468/invoking-super-in-classmethod-called-from-metaclass-new
        """
        this_class = next(
            c for c in cls.__mro__
            if c.__module__ == __name__ and c.__name__ == 'BaseModelResource')
        fields = super(this_class, cls).get_fields(fields=fields,
                                                   excludes=excludes)
        if not cls._meta.object_class:
            return fields
        for django_field in cls._meta.object_class._meta.fields:
            if django_field.blank is True:
                res_field = fields.get(django_field.name, None)
                if res_field:
                    res_field.blank = True
        return fields

class MultipartResource(object):
    def deserialize(self, request, data, format=None):
        if not format:
            format = request.Meta.get('CONTENT_TYPE', 'application/json')
        if format == 'application/x-www-form-urlencoded':
            return request.POST
        if format.startswith('multipart'):
            data = request.POST.copy()
            data.update(request.FILES)
            return data

        return super(MultipartResource, self).deserialize(request, data, format)

# Authentication class - this only allows for header auth, no url parms allowed
# like parent class.

class DojoApiKeyAuthentication(ApiKeyAuthentication):
    def extract_credentials(self, request):
        if (request.META.get('HTTP_AUTHORIZATION') and
                request.META['HTTP_AUTHORIZATION'].lower().startswith('apikey ')):
            (auth_type, data) = request.META['HTTP_AUTHORIZATION'].split()

            if auth_type.lower() != 'apikey':
                raise ValueError("Incorrect authorization header.")

            username, api_key = data.split(':', 1)
        else:
            raise ValueError("Incorrect authorization header.")

        return username, api_key

# Authorization class for Product
class UserProductsOnlyAuthorization(Authorization):
    def read_list(self, object_list, bundle):
        # This assumes a ``QuerySet`` from ``ModelResource``.
        if bundle.request.user.is_staff:
            return object_list
        return object_list.filter(authorized_users__in=[bundle.request.user])

    def read_detail(self, object_list, bundle):
        # Is the requested object owned by the user?
        return (bundle.request.user.is_staff or
                bundle.request.user in bundle.obj.authorized_users)

    def create_list(self, object_list, bundle):
        # Assuming they're auto-assigned to ``user``.
        return object_list.filter(authorized_users__in=[bundle.request.user])

    def create_detail(self, object_list, bundle):
        return (bundle.request.user.is_staff or
                bundle.request.user in bundle.obj.authorized_users)

    def update_list(self, object_list, bundle):
        allowed = []

        # Since they may not all be saved, iterate over them.
        for obj in object_list:
            if (bundle.request.user.is_staff or
                        bundle.request.user in bundle.obj.authorized_users):
                allowed.append(obj)

        return allowed

    def update_detail(self, object_list, bundle):
        return (bundle.request.user.is_staff or
                bundle.request.user in bundle.obj.authorized_users)

    def delete_list(self, object_list, bundle):
        # Sorry user, no deletes for you!
        raise Unauthorized("Sorry, no deletes.")

    def delete_detail(self, object_list, bundle):
        raise Unauthorized("Sorry, no deletes.")

# Authorization class for Scan Settings
class UserScanSettingsAuthorization(Authorization):
    def read_list(self, object_list, bundle):
        # This assumes a ``QuerySet`` from ``ModelResource``.
        if bundle.request.user.is_staff:
            return object_list

        return object_list.filter(product__authorized_users__in=[
            bundle.request.user])

    def read_detail(self, object_list, bundle):
        # Is the requested object owned by the user?
        return (bundle.request.user.is_staff or
                bundle.request.user in bundle.obj.product.authorized_users)

    def create_list(self, object_list, bundle):
        # Assuming they're auto-assigned to ``user``.
        if bundle.request.user.is_staff:
            return object_list
        else:
            return object_list.filter(
                product__authorized_users__in=[bundle.request.user])

    def create_detail(self, object_list, bundle):
        return (bundle.request.user.is_staff or
                bundle.request.user in bundle.obj.product.authorized_users)

    def update_list(self, object_list, bundle):
        allowed = []

        # Since they may not all be saved, iterate over them.
        for obj in object_list:
            if (bundle.request.user.is_staff or
                        bundle.request.user in
                        bundle.obj.product.authorized_users):
                allowed.append(obj)

        return allowed

    def update_detail(self, object_list, bundle):
        return (bundle.request.user.is_staff or
                bundle.request.user in bundle.obj.product.authorized_users)

    def delete_list(self, object_list, bundle):
        return (bundle.request.user.is_staff or
                bundle.request.user in bundle.obj.product.authorized_users)

    def delete_detail(self, object_list, bundle):
        return (bundle.request.user.is_staff or
                bundle.request.user in bundle.obj.product.authorized_users)

# Authorization class for Scan Settings
class UserScanAuthorization(Authorization):
    def read_list(self, object_list, bundle):
        # This assumes a ``QuerySet`` from ``ModelResource``.
        if bundle.request.user.is_staff:
            return object_list

        return object_list.filter(
            scan_settings__product__authorized_users__in=[
                bundle.request.user])

    def read_detail(self, object_list, bundle):
        # Is the requested object owned by the user?
        return (bundle.request.user.is_staff or
                bundle.request.user in
                bundle.obj.scan_settings.product.authorized_users)

    def create_list(self, object_list, bundle):
        # Assuming they're auto-assigned to ``user``.
        if bundle.request.user.is_staff:
            return object_list
        else:
            return object_list.filter(
                scan_settings__product__authorized_users__in=[
                    bundle.request.user])

    def create_detail(self, object_list, bundle):
        return (bundle.request.user.is_staff or
                bundle.request.user in
                bundle.obj.scan_settings.product.authorized_users)

    def update_list(self, object_list, bundle):
        allowed = []

        # Since they may not all be saved, iterate over them.
        for obj in object_list:
            if (bundle.request.user.is_staff or
                        bundle.request.user in
                        bundle.obj.scan_settings.product.authorized_users):
                allowed.append(obj)

        return allowed

    def update_detail(self, object_list, bundle):
        return (bundle.request.user.is_staff or
                bundle.request.user in
                bundle.obj.scan_settings.product.authorized_users)

    def delete_list(self, object_list, bundle):
        return (bundle.request.user.is_staff or
                bundle.request.user in
                bundle.obj.scan_settings.product.authorized_users)

    def delete_detail(self, object_list, bundle):
        return (bundle.request.user.is_staff or
                bundle.request.user in
                bundle.obj.scan_settings.product.authorized_users)

"""
  Look up resource only, no update, store, delete
"""

class UserResource(BaseModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'users'
        fields = ['id', 'username', 'first_name', 'last_name', 'last_login']

        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        include_resource_uri = True
        filtering = {
            'id': ALL,
            'username': ALL,
            'first_name': ALL,
            'last_name': ALL
        }
        authorization = DjangoAuthorization()
        authentication = DojoApiKeyAuthentication()
        serializer = Serializer(formats=['json'])

"""
    POST, PUT
    Expects *product name, *description, *prod_type [1-7]
"""

class ProductResource(BaseModelResource):
    class Meta:
        resource_name = 'products'
        # disabled delete. Should not be allowed without fine authorization.
        list_allowed_methods = ['get', 'post']  # only allow get for lists
        detail_allowed_methods = ['get', 'post', 'put']
        queryset = Product.objects.all().order_by('name')
        ordering = ['name', 'id', 'description', 'findings_count', 'created',
                    'product_type_id']
        excludes = ['tid', 'manager', 'prod_manager', 'tech_contact',
                    'updated']
        include_resource_uri = True
        filtering = {
            'id': ALL,
            'name': ALL,
            'prod_type': ALL,
            'created': ALL,
            'findings_count': ALL
        }
        authentication = DojoApiKeyAuthentication()
        authorization = UserProductsOnlyAuthorization()
        serializer = Serializer(formats=['json'])

        @property
        def validation(self):
            return ModelFormValidation(form_class=ProductForm, resource=ProductResource)

    def dehydrate(self, bundle):
        try:
            bundle.data['prod_type'] = bundle.obj.prod_type
        except:
            bundle.data['prod_type'] = 'unknown'
        bundle.data['findings_count'] = bundle.obj.findings_count
        return bundle

"""
    POST, PUT [/id/]
    Expects *product *target_start, *target_end, *status[In Progress, On Hold,
    Completed], threat_model, pen_test, api_test, check_list
"""

class EngagementResource(BaseModelResource):
    product = fields.ForeignKey(ProductResource, 'product',
                                full=False, null=False)
    lead = fields.ForeignKey(UserResource, 'lead',
                             full=False, null=True)

    class Meta:
        resource_name = 'engagements'
        list_allowed_methods = ['get', 'post']
        # disabled delete for /id/
        detail_allowed_methods = ['get', 'post', 'put']
        queryset = Engagement.objects.all()
        include_resource_uri = True
        filtering = {
            'id': ALL,
            'active': ALL,
            'eng_type': ALL,
            'target_start': ALL,
            'target_end': ALL,
            'requester': ALL,
            'report_type': ALL,
            'updated': ALL,
            'threat_model': ALL,
            'api_test': ALL,
            'pen_test': ALL,
            'status': ALL,
            'product': ALL,
        }
        authentication = DojoApiKeyAuthentication()
        authorization = DjangoAuthorization()
        serializer = Serializer(formats=['json'])

        @property
        def validation(self):
            return ModelFormValidation(form_class=EngForm2, resource=EngagementResource)

    def dehydrate(self, bundle):
        if bundle.obj.eng_type is not None:
            bundle.data['eng_type'] = bundle.obj.eng_type.name
        else:
            bundle.data['eng_type'] = None
        bundle.data['product_id'] = bundle.obj.product.id
        bundle.data['report_type'] = bundle.obj.report_type
        bundle.data['requester'] = bundle.obj.requester
        return bundle

"""
    /api/v1/tests/
    GET [/id/], DELETE [/id/]
    Expects: no params or engagement_id
    Returns test: ALL or by engagement_id
    Relevant apply filter ?test_type=?, ?id=?

    POST, PUT [/id/]
    Expects *test_type, *engagement, *target_start, *target_end,
    estimated_time, actual_time, percent_complete, notes
"""

class TestResource(BaseModelResource):
    engagement = fields.ForeignKey(EngagementResource, 'engagement',
                                   full=False, null=False)

    class Meta:
        resource_name = 'tests'
        list_allowed_methods = ['get', 'post']
        # disabled delete. Should not be allowed without fine authorization.
        detail_allowed_methods = ['get', 'post', 'put']
        queryset = Test.objects.all().order_by('target_end')
        include_resource_uri = True
        filtering = {
            'id': ALL,
            'test_type': ALL,
            'target_start': ALL,
            'target_end': ALL,
            'notes': ALL,
            'percent_complete': ALL,
            'actual_time': ALL,
            'engagement': ALL,
        }
        authentication = DojoApiKeyAuthentication()
        authorization = DjangoAuthorization()
        serializer = Serializer(formats=['json'])

        @property
        def validation(self):
            return ModelFormValidation(form_class=TestForm, resource=TestResource)

    def dehydrate(self, bundle):
        bundle.data['test_type'] = bundle.obj.test_type
        return bundle

class RiskAcceptanceResource(BaseModelResource):
    class Meta:
        resource_name = 'risk_acceptances'
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        queryset = Risk_Acceptance.objects.all().order_by('created')

"""
    /api/v1/findings/
    GET [/id/], DELETE [/id/]
    Expects: no params or test_id
    Returns test: ALL or by test_id
    Relevant apply filter ?active=True, ?id=?, ?severity=?

    POST, PUT [/id/]
    Expects *title, *date, *severity, *description, *mitigation, *impact,
    *endpoint, *test, cwe, active, false_p, verified,
    mitigated, *reporter

"""

class FindingResource(BaseModelResource):
    reporter = fields.ForeignKey(UserResource, 'reporter', null=False)
    test = fields.ForeignKey(TestResource, 'test', null=False)
    risk_acceptance = fields.ManyToManyField(RiskAcceptanceResource, 'risk_acceptance', null=True)
    product = fields.ForeignKey(ProductResource, 'test__engagement__product', full=False, null=False)
    engagement = fields.ForeignKey(EngagementResource, 'test__engagement', full=False, null=False)

    class Meta:
        resource_name = 'findings'
        queryset = Finding.objects.select_related("test")
        # deleting of findings is not allowed via API.
        # Admin interface can be used for this.
        list_allowed_methods = ['get', 'post']
        detail_allowed_methods = ['get', 'post', 'put']
        include_resource_uri = True
        filtering = {
            'id': ALL,
            'title': ALL,
            'date': ALL,
            'severity': ALL,
            'description': ALL,
            'mitigated': ALL,
            'endpoint': ALL,
            'test': ALL_WITH_RELATIONS,
            'active': ALL,
            'verified': ALL,
            'false_p': ALL,
            'reporter': ALL,
            'url': ALL,
            'out_of_scope': ALL,
            'duplicate': ALL,
            'risk_acceptance': ALL,
            'engagement': ALL_WITH_RELATIONS,
            'product': ALL_WITH_RELATIONS
            #'build_id': ALL
        }
        authentication = DojoApiKeyAuthentication()
        authorization = DjangoAuthorization()
        serializer = Serializer(formats=['json'])

        @property
        def validation(self):
            return ModelFormValidation(form_class=FindingForm, resource=FindingResource)

    def dehydrate(self, bundle):
        engagement = Engagement.objects.select_related('product'). \
            filter(test__finding__id=bundle.obj.id)
        bundle.data['engagement'] = "/api/v1/engagements/%s/" % engagement[0].id
        bundle.data['product'] = \
            "/api/v1/products/%s/" % engagement[0].product.id
        return bundle

"""
    /api/v1/finding_templates/
    GET [/id/], DELETE [/id/]
    Expects: no params or test_id
    Returns test: ALL or by test_id
    Relevant apply filter ?active=True, ?id=?, ?severity=?

    POST, PUT [/id/]
    Expects *title, *severity, *description, *mitigation, *impact,
    *endpoint, *test, cwe, active, false_p, verified,
    mitigated, *reporter

"""

class FindingTemplateResource(BaseModelResource):

    class Meta:
        resource_name = 'finding_templates'
        queryset = Finding_Template.objects.all()
        excludes= ['numerical_severity']
        # deleting of Finding_Template is not allowed via API.
        # Admin interface can be used for this.
        list_allowed_methods = ['get', 'post']
        detail_allowed_methods = ['get', 'post', 'put']
        include_resource_uri = True
        """
        title = models.TextField(max_length=1000)
    cwe = models.IntegerField(default=None, null=True, blank=True)
    severity = models.CharField(max_length=200, null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    mitigation = models.TextField(null=True, blank=True)
    impact = models.TextField(null=True, blank=True)
    references = models.TextField(null=True, blank=True, db_column="refs")
    numerical_severity
    """
        filtering = {
            'id': ALL,
            'title': ALL,
            'cwe': ALL,
            'severity': ALL,
            'description': ALL,
            'mitigated': ALL,
        }
        authentication = DojoApiKeyAuthentication()
        authorization = DjangoAuthorization()
        serializer = Serializer(formats=['json'])

        @property
        def validation(self):
            return ModelFormValidation(form_class=FindingTemplateForm, resource=FindingTemplateResource)

class StubFindingResource(BaseModelResource):
    reporter = fields.ForeignKey(UserResource, 'reporter', null=False)
    test = fields.ForeignKey(TestResource, 'test', null=False)

    class Meta:
        resource_name = 'stub_findings'
        queryset = Stub_Finding.objects.select_related("test")
        # deleting of findings is not allowed via UI or API.
        # Admin interface can be used for this.
        list_allowed_methods = ['get', 'post']
        detail_allowed_methods = ['get', 'post', 'put']
        include_resource_uri = True
        filtering = {
            'id': ALL,
            'title': ALL,
            'date': ALL,
            'severity': ALL,
            'description': ALL,
        }

        authentication = DojoApiKeyAuthentication()
        authorization = DjangoAuthorization()
        serializer = Serializer(formats=['json'])

        @property
        def validation(self):
            return ModelFormValidation(form_class=StubFindingForm, resource=StubFindingResource)

    def dehydrate(self, bundle):
        engagement = Engagement.objects.select_related('product'). \
            filter(test__stub_finding__id=bundle.obj.id)
        bundle.data['engagement'] = "/api/v1/engagements/%s/" % engagement[0].id
        bundle.data['product'] = \
            "/api/v1/products/%s/" % engagement[0].product.id
        return bundle

'''
    /api/v1/scansettings/
    GET [/id/], DELETE [/id/]
    Expects: no params or product_id
    Returns test: ALL or by product_id

    POST, PUT [/id/]
    Expects *addresses, *user, *date, *frequency, *email, *product
'''

class ScanSettingsResource(BaseModelResource):
    user = fields.ForeignKey(UserResource, 'user', null=False)
    product = fields.ForeignKey(ProductResource, 'product', null=False)

    class Meta:
        resource_name = 'scan_settings'
        queryset = ScanSettings.objects.all()

        list_allowed_methods = ['get', 'post']
        detail_allowed_methods = ['get', 'put', 'post', 'delete']
        include_resource_uri = True
        filtering = {
            'id': ALL,
            'date': ALL,
            'user': ALL,
            'frequency': ALL,
            'product': ALL,
            'addresses': ALL
        }

        authentication = DojoApiKeyAuthentication()
        authorization = UserScanSettingsAuthorization()
        serializer = Serializer(formats=['json'])

        @property
        def validation(self):
            return ModelFormValidation(form_class=ScanSettingsForm, resource=ScanSettingsResource)

"""
    /api/v1/ipscans/
    Not exposed via API - but used as part of
    ScanResource return values
"""

class IPScanResource(BaseModelResource):
    class Meta:
        resource_name = 'ipscans'
        queryset = IPScan.objects.all()

        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        include_resource_uri = True
        filtering = {
            'id': ALL,
            'address': ALL,
            'services': ALL,
            'scan': ALL
        }

        authentication = DojoApiKeyAuthentication()
        authorization = DjangoAuthorization()
        serializer = Serializer(formats=['json'])

"""
    /api/v1/scans/
    GET [/id/], DELETE [/id/]
    Expects: no params
    Returns scans: ALL
    Relevant filters: ?scan_setting=?
"""

class ScanResource(BaseModelResource):
    scan_settings = fields.ForeignKey(ScanSettingsResource,
                                      'scan_settings',
                                      null=False)
    ipscans = fields.ToManyField(
        IPScanResource,
        attribute=lambda bundle: IPScan.objects.filter(
            scan__id=bundle.obj.id) if IPScan.objects.filter(
            scan__id=bundle.obj.id) != [] else [], full=True, null=True)

    class Meta:
        resource_name = 'scans'
        queryset = Scan.objects.all()

        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        include_resource_uri = True
        filtering = {
            'id': ALL,
            'date': ALL,
            'scan_settings': ALL
        }

        authentication = DojoApiKeyAuthentication()
        authorization = UserScanAuthorization()
        serializer = Serializer(formats=['json'])

# Method used to get Private Key from uri, Used in the ImportScan and ReImportScan resources
def get_pk_from_uri(uri):
    prefix = get_script_prefix()
    chomped_uri = uri

    if prefix and chomped_uri.startswith(prefix):
        chomped_uri = chomped_uri[len(prefix)-1:]

    try:
        view, args, kwargs = resolve(chomped_uri)
    except Resolver404:
        raise NotFound("The URL provided '%s' was not a link to a valid resource." % uri)

    return kwargs['pk']

"""
    /api/v1/importscan/
    POST
    Expects file, scan_date, scan_type, tags, active, engagement
"""

# Create an Object that will store all the information sent to the endpoint
class ImportScanObject(object):
    def __init__(self, initial=None):
        self.__dict__['_data'] = {}
        if initial:
            self.update(initial)

    def __getattr__(self, name):
        return self._data.get(name, None)

    def __setattr__(self, name, value):
        self.__dict__['_data'][name] = value

    def update(self, other):
        for k in other:
            self.__setattr__(k, other[k])

    def to_dict(self):
        return self._data

# The default form validation was buggy so I implemented a custom validation class
class ImportScanValidation(Validation):
    def is_valid(self, bundle, request=None):
        if not bundle.data:
            return {'__all__': 'You didn\'t seem to pass anything in.'}

        errors = {}

        # Make sure file is present
        if 'file' not in bundle.data:
            errors.setdefault('file', []).append('You must pass a file in to be imported')

        # Make sure scan_date matches required format
        if 'scan_date' in bundle.data:
            try:
                datetime.strptime(bundle.data['scan_date'], '%Y-%m-%d')
            except ValueError:
                errors.setdefault('scan_date', []).append("Incorrect scan_date format, should be YYYY-MM-DD")

        # Make sure scan_type and minimum_severity have valid options
        if 'engagement' not in bundle.data:
            errors.setdefault('engagement', []).append('engagement must be given')
        else:
            # verify the engagement is valid
            try:
                get_pk_from_uri(uri=bundle.data['engagement'])
            except NotFound:
                errors.setdefault('engagement', []).append('A valid engagement must be supplied. Ex. /api/v1/engagements/1/')
        scan_type_list = list(map(lambda x: x[0], ImportScanForm.SCAN_TYPE_CHOICES))
        if 'scan_type' in bundle.data:
            if bundle.data['scan_type'] not in scan_type_list:
                errors.setdefault('scan_type', []).append('scan_type must be one of the following: ' + ', '.join(scan_type_list))
        else:
            errors.setdefault('scan_type', []).append('A scan_type must be given so we know how to import the scan file.')
        severity_list = list(map(lambda x: x[0], SEVERITY_CHOICES))
        if 'minimum_severity' in bundle.data:
            if bundle.data['minimum_severity'] not in severity_list:
                errors.setdefault('minimum_severity', []).append('minimum_severity must be one of the following: ' + ', '.join(severity_list))

        # Make sure active and verified are booleans
        if 'active' in bundle.data:
            if bundle.data['active'] in ['false', 'False', '0']:
                bundle.data['active'] = False
            elif bundle.data['active'] in ['true', 'True', '1']:
                bundle.data['active'] = True

            if not isinstance(bundle.data['active'], bool):
                errors.setdefault('active', []).append('active must be a boolean')
        if 'verified' in bundle.data:
            if bundle.data['verified'] in ['false', 'False', '0']:
                bundle.data['verified'] = False
            elif bundle.data['verified'] in ['true', 'True', '1']:
                bundle.data['verified'] = True

            if not isinstance(bundle.data['verified'], bool):
                errors.setdefault('verified', []).append('verified must be a boolean')

        return errors

class ImportScanResource(MultipartResource, Resource):
    scan_date = fields.DateTimeField(attribute='scan_date')
    minimum_severity = fields.CharField(attribute='minimum_severity')
    active = fields.BooleanField(attribute='active')
    verified = fields.BooleanField(attribute='verified')
    scan_type = fields.CharField(attribute='scan_type')
    tags = fields.CharField(attribute='tags')
    file = fields.FileField(attribute='file')
    engagement = fields.CharField(attribute='engagement')

    class Meta:
        resource_name = 'importscan'
        fields = ['scan_date', 'minimum_severity', 'active', 'verified', 'scan_type', 'tags', 'file']
        list_allowed_methods = ['post']
        detail_allowed_methods = []
        include_resource_uri = True

        authentication = DojoApiKeyAuthentication()
        authorization = DjangoAuthorization()
        validation = ImportScanValidation()
        object_class = ImportScanObject

    def hydrate(self, bundle):
        if 'scan_date' not in bundle.data:
            bundle.data['scan_date'] = datetime.now().strftime("%Y/%m/%d")
        if 'minimum_severity' not in bundle.data:
            bundle.data['minimum_severity'] = "Info"
        if 'active' not in bundle.data:
            bundle.data['active'] = True
        if 'verified' not in bundle.data:
            bundle.data['verified'] = True
        if 'tags' not in bundle.data:
            bundle.data['tags'] = ""

        bundle.obj.__setattr__('engagement_obj',
                               Engagement.objects.get(id=get_pk_from_uri(bundle.data['engagement'])))

        return bundle

    def detail_uri_kwargs(self, bundle_or_obj):
        kwargs = {}
        return kwargs

    def obj_create(self, bundle, **kwargs):
        bundle.obj = ImportScanObject(initial=kwargs)
        self.is_valid(bundle)
        if bundle.errors:
            raise ImmediateHttpResponse(response=self.error_response(bundle.request, bundle.errors))
        bundle = self.full_hydrate(bundle)

        # We now have all the options we need and will just replicate the process in views.py
        tt, t_created = Test_Type.objects.get_or_create(name=bundle.data['scan_type'])
        # will save in development environment
        environment, env_created = Development_Environment.objects.get_or_create(name="Development")
        scan_date = datetime.strptime(bundle.data['scan_date'], '%Y-%m-%d')
        t = Test(engagement=bundle.obj.__getattr__('engagement_obj'), test_type=tt, target_start=scan_date,
                 target_end=scan_date, environment=environment, percent_complete=100)
        t.full_clean()
        t.save()
        t.tags = bundle.data['tags']

        try:
            parser = import_parser_factory(bundle.data['file'], t)
        except ValueError:
            raise NotFound("Parser ValueError")

        try:
            for item in parser.items:
                sev = item.severity
                if sev == 'Information' or sev == 'Informational':
                    sev = 'Info'

                item.severity = sev

                if Finding.SEVERITIES[sev] > Finding.SEVERITIES[bundle.data['minimum_severity']]:
                    continue

                item.test = t
                item.date = t.target_start
                item.reporter = bundle.request.user
                item.last_reviewed = datetime.now(tz=localtz)
                item.last_reviewed_by = bundle.request.user
                item.active = bundle.data['active']
                item.verified = bundle.data['verified']
                item.save()

                if hasattr(item, 'unsaved_req_resp') and len(item.unsaved_req_resp) > 0:
                    for req_resp in item.unsaved_req_resp:
                        burp_rr = BurpRawRequestResponse(finding=item,
                                                         burpRequestBase64=req_resp["req"],
                                                         burpResponseBase64=req_resp["resp"],
                                                         )
                        burp_rr.clean()
                        burp_rr.save()

                if item.unsaved_request is not None and item.unsaved_response is not None:
                    burp_rr = BurpRawRequestResponse(finding=item,
                                                     burpRequestBase64=item.unsaved_request,
                                                     burpResponseBase64=item.unsaved_response,
                                                     )
                    burp_rr.clean()
                    burp_rr.save()

                for endpoint in item.unsaved_endpoints:
                    ep, created = Endpoint.objects.get_or_create(protocol=endpoint.protocol,
                                                                 host=endpoint.host,
                                                                 path=endpoint.path,
                                                                 query=endpoint.query,
                                                                 fragment=endpoint.fragment,
                                                                 product=t.engagement.product)

                    item.endpoints.add(ep)

                if item.unsaved_tags is not None:
                    item.tags = item.unsaved_tags

        except SyntaxError:
            raise NotFound("Parser SyntaxError")

        # Everything executed fine. We successfully imported the scan.
        res = TestResource()
        uri = res.get_resource_uri(t)
        raise ImmediateHttpResponse(HttpCreated(location = uri))

# The default form validation was buggy so I implemented a custom validation class
class ReImportScanValidation(Validation):
    def is_valid(self, bundle, request=None):
        if not bundle.data:
            return {'__all__': 'You didn\'t seem to pass anything in.'}

        errors = {}

        # Make sure file is present
        if 'file' not in bundle.data:
            errors.setdefault('file', []).append('You must pass a file in to be imported')

        # Make sure scan_date matches required format
        if 'scan_date' in bundle.data:
            try:
                datetime.strptime(bundle.data['scan_date'], '%Y/%m/%d')
            except ValueError:
                errors.setdefault('scan_date', []).append("Incorrect scan_date format, should be YYYY/MM/DD")

        # Make sure scan_type and minimum_severity have valid options
        if 'test' not in bundle.data:
            errors.setdefault('test', []).append('test must be given')
        else:
            # verify the engagement is valid
            try:
                get_pk_from_uri(uri=bundle.data['test'])
            except NotFound:
                errors.setdefault('engagement', []).append('A valid engagement must be supplied. Ex. /api/v1/engagements/1/')
        scan_type_list = list(map(lambda x: x[0], ImportScanForm.SCAN_TYPE_CHOICES))
        if 'scan_type' in bundle.data:
            if bundle.data['scan_type'] not in scan_type_list:
                errors.setdefault('scan_type', []).append('scan_type must be one of the following: ' + ', '.join(scan_type_list))
        else:
            errors.setdefault('scan_type', []).append('A scan_type must be given so we know how to import the scan file.')
        severity_list = list(map(lambda x: x[0], SEVERITY_CHOICES))
        if 'minimum_severity' in bundle.data:
            if bundle.data['minimum_severity'] not in severity_list:
                errors.setdefault('minimum_severity', []).append('minimum_severity must be one of the following: ' + ', '.join(severity_list))

        # Make sure active and verified are booleans
        if 'active' in bundle.data:
            if bundle.data['active'] in ['false', 'False', '0']:
                bundle.data['active'] = False
            elif bundle.data['active'] in ['true', 'True', '1']:
                bundle.data['active'] = True

            if not isinstance(bundle.data['active'], bool):
                errors.setdefault('active', []).append('active must be a boolean')
        if 'verified' in bundle.data:
            if bundle.data['verified'] in ['false', 'False', '0']:
                bundle.data['verified'] = False
            elif bundle.data['verified'] in ['true', 'True', '1']:
                bundle.data['verified'] = True

            if not isinstance(bundle.data['verified'], bool):
                errors.setdefault('verified', []).append('verified must be a boolean')

        return errors

class ReImportScanResource(MultipartResource, Resource):
    scan_date = fields.DateTimeField(attribute='scan_date')
    minimum_severity = fields.CharField(attribute='minimum_severity')
    active = fields.BooleanField(attribute='active')
    verified = fields.BooleanField(attribute='verified')
    scan_type = fields.CharField(attribute='scan_type')
    tags = fields.CharField(attribute='tags')
    file = fields.FileField(attribute='file')
    test = fields.CharField(attribute='test')

    class Meta:
        resource_name = 'reimportscan'
        fields = ['scan_date', 'minimum_severity', 'active', 'verified', 'scan_type', 'tags', 'file']
        list_allowed_methods = ['post']
        detail_allowed_methods = []
        include_resource_uri = True

        authentication = DojoApiKeyAuthentication()
        authorization = DjangoAuthorization()
        validation = ReImportScanValidation()
        object_class = ImportScanObject

    def hydrate(self, bundle):
        if 'scan_date' not in bundle.data:
            bundle.data['scan_date'] = datetime.now().strftime("%Y/%m/%d")
        if 'minimum_severity' not in bundle.data:
            bundle.data['minimum_severity'] = "Info"
        if 'active' not in bundle.data:
            bundle.data['active'] = True
        if 'verified' not in bundle.data:
            bundle.data['verified'] = True
        if 'tags' not in bundle.data:
            bundle.data['tags'] = ""

        bundle.obj.__setattr__('test_obj',
                               Test.objects.get(id=get_pk_from_uri(bundle.data['test'])))

        return bundle

    def detail_uri_kwargs(self, bundle_or_obj):
        kwargs = {}
        return kwargs

    def obj_create(self, bundle, **kwargs):
        bundle.obj = ImportScanObject(initial=kwargs)
        self.is_valid(bundle)
        if bundle.errors:
            raise ImmediateHttpResponse(response=self.error_response(bundle.request, bundle.errors))
        bundle = self.full_hydrate(bundle)

        test = bundle.obj.__getattr__('test_obj')
        scan_type = bundle.obj.__getattr__('scan_type')
        min_sev = bundle.obj.__getattr__('minimum_severity')
        scan_date = bundle.obj.__getattr__('scan_date')
        verified = bundle.obj.__getattr__('verified')
        active = bundle.obj.__getattr__('active')

        try:
            parser = import_parser_factory(bundle.data['file'], test)
        except ValueError:
            raise NotFound("Parser ValueError")

        try:
            items = parser.items
            original_items = test.finding_set.all().values_list("id", flat=True)
            new_items = []
            mitigated_count = 0
            finding_count = 0
            finding_added_count = 0
            reactivated_count = 0
            for item in items:
                sev = item.severity
                if sev == 'Information' or sev == 'Informational':
                    sev = 'Info'

                if Finding.SEVERITIES[sev] > Finding.SEVERITIES[min_sev]:
                    continue

                if scan_type == 'Veracode Scan' or scan_type == 'Arachni Scan':
                    find = Finding.objects.filter(title=item.title,
                                                  test__id=test.id,
                                                  severity=sev,
                                                  numerical_severity=Finding.get_numerical_severity(sev),
                                                  description=item.description
                                                  )
                else:
                    find = Finding.objects.filter(title=item.title,
                                                  test__id=test.id,
                                                  severity=sev,
                                                  numerical_severity=Finding.get_numerical_severity(sev),
                                                  )

                if len(find) == 1:
                    find = find[0]
                    if find.mitigated:
                        # it was once fixed, but now back
                        find.mitigated = None
                        find.mitigated_by = None
                        find.active = True
                        find.verified = verified
                        find.save()
                        note = Notes(entry="Re-activated by %s re-upload." % scan_type,
                                     author=bundle.request.user)
                        note.save()
                        find.notes.add(note)
                        reactivated_count += 1
                    new_items.append(find.id)
                else:
                    item.test = test
                    item.date = test.target_start
                    item.reporter = bundle.request.user
                    item.last_reviewed = datetime.now(tz=localtz)
                    item.last_reviewed_by = bundle.request.user
                    item.verified = verified
                    item.active = active
                    item.save()
                    finding_added_count += 1
                    new_items.append(item.id)
                    find = item

                    if hasattr(item, 'unsaved_req_resp') and len(item.unsaved_req_resp) > 0:
                        for req_resp in item.unsaved_req_resp:
                            burp_rr = BurpRawRequestResponse(finding=find,
                                                             burpRequestBase64=req_resp["req"],
                                                             burpResponseBase64=req_resp["resp"],
                                                             )
                            burp_rr.clean()
                            burp_rr.save()

                    if item.unsaved_request is not None and item.unsaved_response is not None:
                        burp_rr = BurpRawRequestResponse(finding=find,
                                                         burpRequestBase64=item.unsaved_request,
                                                         burpResponseBase64=item.unsaved_response,
                                                         )
                        burp_rr.clean()
                        burp_rr.save()
                if find:
                    finding_count += 1
                    for endpoint in item.unsaved_endpoints:
                        ep, created = Endpoint.objects.get_or_create(protocol=endpoint.protocol,
                                                                     host=endpoint.host,
                                                                     path=endpoint.path,
                                                                     query=endpoint.query,
                                                                     fragment=endpoint.fragment,
                                                                     product=test.engagement.product)
                        find.endpoints.add(ep)

                    if item.unsaved_tags is not None:
                        find.tags = item.unsaved_tags
            # calculate the difference
            to_mitigate = set(original_items) - set(new_items)
            for finding_id in to_mitigate:
                finding = Finding.objects.get(id=finding_id)
                finding.mitigated = datetime.combine(scan_date, datetime.now(tz=localtz).time())
                finding.mitigated_by = bundle.request.user
                finding.active = False
                finding.save()
                note = Notes(entry="Mitigated by %s re-upload." % scan_type,
                             author=bundle.request.user)
                note.save()
                finding.notes.add(note)
                mitigated_count += 1

        except SyntaxError:
            raise NotFound("Parser SyntaxError")

        # Everything executed fine. We successfully imported the scan.
        raise ImmediateHttpResponse(HttpCreated(location = bundle.obj.__getattr__('test')))


text:
NS_ASSUME_NONNULL_BEGIN

FOUNDATION_EXPORT void
mcs_queue_init(void);

FOUNDATION_EXPORT void
mcs_queue_sync(NS_NOESCAPE dispatch_block_t block);

FOUNDATION_EXPORT void
mcs_queue_async(dispatch_block_t block);

FOUNDATION_EXPORT dispatch_queue_t
mcs_queue(void);

NS_ASSUME_NONNULL_END


text:
/**
 * Types responsible for generating dependency reports.
 */
@NonNullApi
package org.gradle.api.reporting.dependencies;

import org.gradle.api.NonNullApi;