text:
module RuboCop
  module Cop
    module Style
      # This cop checks for big numeric literals without _ between groups
      # of digits in them.
      #
      # @example
      #
      #   # bad
      #
      #   1000000
      #   1_00_000
      #   1_0000
      #
      #   # good
      #
      #   1_000_000
      #   1000
      #
      #   # good unless Strict is set
      #
      #   10_000_00 # typical representation of $10,000 in cents
      #
      class NumericLiterals < Cop
        # The parameter is called MinDigits (meaning the minimum number of
        # digits for which an offense can be registered), but essentially it's
        # a Max parameter (the maximum number of something that's allowed).
        include ConfigurableMax
        include IntegerNode

        MSG = 'Use underscores(_) as decimal mark and ' \
              'separate every 3 digits with them.'.freeze

        def on_int(node)
          check(node)
        end

        def on_float(node)
          check(node)
        end

        def autocorrect(node)
          lambda do |corrector|
            corrector.replace(node.source_range, format_number(node))
          end
        end

        private

        def max_parameter_name
          'MinDigits'
        end

        def check(node)
          int = integer_part(node)

          # TODO: handle non-decimal literals as well
          return if int.start_with?('0')
          return unless int.size >= min_digits

          case int
          when /^\d+$/
            add_offense(node) { self.max = int.size + 1 }
          when /\d{4}/, short_group_regex
            add_offense(node) do
              self.config_to_allow_offenses = { 'Enabled' => false }
            end
          end
        end

        def short_group_regex
          cop_config['Strict'] ? /_\d{1,2}(_|$)/ : /_\d{1,2}_/
        end

        def format_number(node)
          int_part, float_part = node.source.split('.')
          int_part = Integer(int_part)
          formatted_int = int_part
                          .abs
                          .to_s
                          .reverse
                          .gsub(/...(?=.)/, '\&_')
                          .reverse
          formatted_int.insert(0, '-') if int_part < 0

          if float_part
            format('%<int>s.%<float>s', int: formatted_int, float: float_part)
          else
            formatted_int
          end
        end

        def min_digits
          cop_config['MinDigits']
        end
      end
    end
  end
end


text:
   <title>TrevorC.ca</title>
   <link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">
   <link rel="stylesheet" type="text/css" href="main.css">

<canvas id="c"></canvas>

redpajama_set_name: RedPajamaGithub


text:
package com.epam.catgenome.entity.bam;

import com.epam.catgenome.entity.reference.Chromosome;
import com.epam.catgenome.util.BamUtil;
import com.fasterxml.jackson.annotation.JsonIgnore;

/**
 * Source:
 * Created:     7/5/2016
 * Project:     CATGenome Browser
 * Make:        IntelliJ IDEA 14.1.1, JDK 1.8
 * Class represents the available options for track/get API
 */
public class BamQueryOption {
    private Boolean showClipping;
    private Boolean showSpliceJunction;
    private TrackDirectionType trackDirection;
    private BamTrackMode mode;
    private Integer frame;
    private Integer count;
    private boolean filterNotPrimary = false;
    private boolean filterVendorQualityFail = false;
    private boolean filterDuplicate = false;
    private boolean filterSupplementaryAlignment = false;

    @JsonIgnore
    private Long refID;
    @JsonIgnore
    private String chromosomeName;
    @JsonIgnore
    private boolean downSampling = false;

    /**
     * Default constructor for representing missing options
     */
    public BamQueryOption() {
        mode = BamTrackMode.FULL; // FULL query by default
        //        Empty constructor for initialization from the code
    }

    /**
     * Constructor for filling all options below
     * @param showClipping if true return the track with soft clipping
     * @param showSpliceJunction  if true return a information about splice junction
     * @param trackDirection represents the approach to read filtering with respect to track borders
     * @param frame size of frame for downsampling
     * @param count number of reads in the frame
     * @param chromosome reference sequence
     */
    public BamQueryOption(Boolean showClipping, Boolean showSpliceJunction, TrackDirectionType trackDirection,
                          Integer frame, Integer count, Chromosome chromosome) {
        this(showClipping, showSpliceJunction, trackDirection, frame, count);
        this.chromosomeName = chromosome.getName();
        this.refID = chromosome.getReferenceId();
        BamUtil.validateOptions(this, chromosome);
    }

    /**
     * Constructor without reference sequence
     * @param showClipping if true return the track with soft clipping
     * @param showSpliceJunction if true return a information about track junction
     * @param trackDirection represents the approach to read filtering with respect to frame borders
     * @param frame size of frame for downsampling
     * @param count number of reads in the frame
     */
    public BamQueryOption(Boolean showClipping, Boolean showSpliceJunction, TrackDirectionType trackDirection,
            Integer frame, Integer count) {
        this();
        this.showClipping = showClipping;
        this.count = count;
        this.frame = frame;
        this.showSpliceJunction = showSpliceJunction;
        this.trackDirection = trackDirection;
    }

    public Boolean getShowClipping() {
        return showClipping;
    }

    public void setShowClipping(Boolean showClipping) {
        this.showClipping = showClipping;
    }

    public TrackDirectionType getTrackDirection() {
        return trackDirection;
    }

    public void setTrackDirection(TrackDirectionType trackDirection) {
        this.trackDirection = trackDirection;
    }

    public String getChromosomeName() {
        return chromosomeName;
    }

    public void setChromosomeName(String chromosomeName) {
        this.chromosomeName = chromosomeName;
    }

    public Integer getFrame() {
        return frame;
    }

    public void setFrame(Integer frame) {
        this.frame = frame;
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    public Boolean getShowSpliceJunction() {
        return showSpliceJunction;
    }

    public void setShowSpliceJunction(Boolean showSpliceJunction) {
        this.showSpliceJunction = showSpliceJunction;
    }

    public void setRefID(Long refID) {
        this.refID = refID;
    }

    public Long getRefID() {
        return refID;
    }

    public boolean isDownSampling() {
        return downSampling;
    }

    public void setDownSampling(boolean downSampling) {
        this.downSampling = downSampling;
    }

    public boolean isFilterNotPrimary() {
        return filterNotPrimary;
    }

    public void setFilterNotPrimary(boolean filterNotPrimary) {
        this.filterNotPrimary = filterNotPrimary;
    }

    public boolean isFilterVendorQualityFail() {
        return filterVendorQualityFail;
    }

    public void setFilterVendorQualityFail(boolean filterVendorQualityFail) {
        this.filterVendorQualityFail = filterVendorQualityFail;
    }

    public boolean isFilterDuplicate() {
        return filterDuplicate;
    }

    public void setFilterDuplicate(boolean filterDuplicate) {
        this.filterDuplicate = filterDuplicate;
    }

    public boolean isFilterSupplementaryAlignment() {
        return filterSupplementaryAlignment;
    }

    public void setFilterSupplementaryAlignment(boolean filterSupplementaryAlignment) {
        this.filterSupplementaryAlignment = filterSupplementaryAlignment;
    }

    public BamTrackMode getMode() {
        return mode;
    }

    public void setMode(BamTrackMode mode) {
        this.mode = mode;
    }
}


text:
This is a boiler-plate project to generate your own client library with Swagger.  Its goal is
to get you started with the basic plumbing so you can put in your own logic.  It won't work without
your changes applied.

## What's Swagger?
The goal of Swagger™ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swagger removes the guesswork in calling the service.

Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more.

## How do I use this?
At this point, you've likely generated a client setup.  It will include something along these lines:

```
.
|- README.md    // this file
|- pom.xml      // build script
|-- src
|--- main
|---- java
|----- strava.api.developers.codegen.HugoGenerator.java // generator file
|---- resources
|----- hugo // template files
|----- META-INF
|------ services
|------- io.swagger.codegen.CodegenConfig
```

You _will_ need to make changes in at least the following:

`HugoGenerator.java`

Templates in this folder:

`src/main/resources/hugo`

Once modified, you can run this:

```
mvn package
```

In your generator project.  A single jar file will be produced in `target`.  You can now use that with codegen:

```
java -cp /path/to/swagger-codegen-cli.jar:/path/to/your.jar io.swagger.codegen.Codegen -l hugo -i /path/to/swagger.yaml -o ./test
```

Now your templates are available to the client generator and you can write output values

## But how do I modify this?
The `HugoGenerator.java` has comments in it--lots of comments.  There is no good substitute
for reading the code more, though.  See how the `HugoGenerator` implements `CodegenConfig`.
That class has the signature of all values that can be overridden.

For the templates themselves, you have a number of values available to you for generation.
You can execute the `java` command from above while passing different debug flags to show
the object you have available during client generation:

```
# The following additional debug options are available for all codegen targets:
# -DdebugSwagger prints the OpenAPI Specification as interpreted by the codegen
# -DdebugModels prints models passed to the template engine
# -DdebugOperations prints operations passed to the template engine
# -DdebugSupportingFiles prints additional data passed to the template engine

java -DdebugOperations -cp /path/to/swagger-codegen-cli.jar:/path/to/your.jar io.swagger.codegen.Codegen -l hugo -i /path/to/swagger.yaml -o ./test
```

Will, for example, output the debug info for operations.  You can use this info
in the `api.mustache` file.


text:
#include "ccharsound.h"
#include <stdio.h>
#include <math.h>
#include "../fjay/fjson.h"

#include<QDebug>

/*
    CWaveTimer
*/
CWaveTimer::CWaveTimer(){
    h=0;
    m=0;
    s=0;
    ms=0;
}

CWaveTimer::CWaveTimer(int msc){
    h=msc/1000/60/60;
    m=(msc-h*60*60*1000)/60/1000;
    s=(msc-h*60*60*1000-m*60*1000)/1000;
    ms=msc-h*60*60*1000-m*60*1000-s*1000;
}

CWaveTimer::~CWaveTimer(){
}

string CWaveTimer::ToStr(){
    string result;
    char buf[20];
    sprintf (buf, "%d:%d:%d.%d", h, m, s, ms);
    result=buf;
    return result;
}

/*
    CSoundInterval
*/
CSoundInterval::~CSoundInterval(){
    if(data)
        delete[] data;
}

/*
    CCharSound
*/

CCharSound::CCharSound()
{
    data=nullptr;
    intervals=nullptr;
    iSamplesCount=0;
    iIntervalsCount=0;
    iPeak=0;
    bSigned=false;
    ibytesPerSample=0;
    fDynamicRange=0;
}

CCharSound::~CCharSound()
{
    if(data)
        delete[] data;
    if(intervals)
        delete[] intervals;
}

WAVHEADER* CCharSound::Header(){
    return &header;
}

float CCharSound::Duration(){
    return fDuration;
}

unsigned int CCharSound::SamplesCount(){
    return iSamplesCount;
}

unsigned int CCharSound::IntervalsCount(){
    return iIntervalsCount;
}

unsigned int CCharSound::SamplesPerInterval(){
    return iSamplesPerInterval;
}

CSoundInterval* CCharSound::GetIntervals(){
    return intervals;
}

unsigned int CCharSound:: Size(){
    return header.subchunk2Size;
}

char* CCharSound::GetLastError(){
    return lasterror;
}

float CCharSound::SampleNoToSecond(unsigned int n){
    if(header.byteRate>0)
        return 1.0*header.blockAlign*n/header.byteRate;
    else return 0;
}

int CCharSound::Peak(){
    return iPeak;
}

double CCharSound::Silent(){
    return DBFSToVolume(SILENT);
}

bool CCharSound::IsSigned(){
    return bSigned;
}

short CCharSound::BytesPerSample(){
    return ibytesPerSample;
}

CWaveTimer CCharSound::SampleNoToTime(unsigned int n){
    return CWaveTimer((int)(SampleNoToSecond(n)*1000));
}

double CCharSound::VolumeToDBFS(double volume){
    return 20*log10(volume*1.22474487139);
}

double CCharSound::DBFSToVolume(double dbfs){
    return pow(10.0, dbfs * 0.05 )*0.81649658092;
}

int CCharSound::SampleToVal(CWaveSample &s){
    switch(header.bitsPerSample){
        case 8:
            return s.sample8;
        case 16:
            return s.sample16;
        case 24:
            return s.sample24;
        case 32:
            return s.sample32;
        default:
            return s.sample16;
    }
}

CWaveSample CCharSound::ValToSample(int value){
    CWaveSample s;

    switch(header.bitsPerSample){
        case 8:
            s.sample8=value;
            break;
        case 16:
            s.sample16=value;
            break;
        case 24:
            s.sample24=value;
            break;
        case 32:
            s.sample32=value;
            break;
        default:
            s.sample16=value;
            break;
    }
    return s;
}

int CCharSound::Data(unsigned int i){
    if(data==nullptr) return 0;
    CWaveSample amp;
    memcpy((void*)&amp.data[0],(void*)&data[i*ibytesPerSample*header.numChannels],ibytesPerSample);
    if(bSigned)
        return SampleToVal(amp);
    else
        return SampleToVal(amp)-(iPeak*0.5);
}

char* CCharSound::Data(){
    return data;
}

CSoundInterval* CCharSound::Interval(unsigned int i){
    if(i<iIntervalsCount)
        return &intervals[i];
    return nullptr;
}

void CCharSound::SetData(unsigned int pos, int value){
    if(data==nullptr) return;

    if(value>=iPeak*0.5)
        value=iPeak*0.5-1;
    else
    if(value<=-iPeak*0.5)
        value=-iPeak*0.5+1;

    CWaveSample amp;

    if(bSigned)
        amp=ValToSample(value);
    else
        amp=ValToSample(value+iPeak*0.5);

    memcpy((void*)&data[pos*ibytesPerSample*header.numChannels],(void*)&amp.data[0],ibytesPerSample);
}

void CCharSound::Normalize(short aligment, short rmswindow, short rmsoverlap, short silent){
    if(data==nullptr) return;
    unsigned int count(0), stepsamples(0), k(0), oversamples(0);
    unsigned int i(0);
    double dRMS(0), tmp(0);
    long double s(0);
    double dTargetMax=DBFSToVolume(fDynamicRange-aligment);
    double dSilent=DBFSToVolume(silent);
    stepsamples=rmswindow*(header.byteRate/ibytesPerSample/header.numChannels)/1000;
    oversamples=rmsoverlap*(header.byteRate/ibytesPerSample/header.numChannels)/1000;

    qDebug()<<"Normalazing. "<<"DynamicRange="<<fDynamicRange<<" dTargetMax="<<QString::number(dTargetMax,'f')
           <<" dSilent"<<dSilent<<" StepSamples="<<stepsamples<<" oversamples="<<oversamples;

    while(i<iSamplesCount){
        tmp=Data(i);
        if(abs(tmp)>dSilent){
            s+=tmp*tmp;
            count++;
        }

        if( k==stepsamples || i==iSamplesCount-1){
            if(count>0){
                dRMS=sqrt(s / (double)count);
                qDebug()<<"window: ["<<i-k<<", "<<i<<"]";
                for(unsigned int j=i-k;j<i;j++){
                    tmp=Data(j);
                    if(abs(tmp)>dSilent)
                        SetData(j,(dTargetMax/dRMS) * tmp);
                }
                count=0;
            }
            s=0;
            k=0;
            if(i>oversamples && i<iSamplesCount-oversamples)
                i-=oversamples;
        }
        i++;
        k++;
    }

    qDebug()<<"Done";
}

void CCharSound::GetFloatDataFromInterval(unsigned int i, double* array){
    if(array==nullptr) return;
    unsigned int k=intervals[i].begin;
    unsigned int j(0);
    for(unsigned int i=k;i<k+iSamplesPerInterval && i<Size();i++,j++){
        array[j]=Data(i);
    }
}

void CCharSound::FormIntervals(unsigned int msec, unsigned int overlap){
    if(data==nullptr) return;
    unsigned int samples=msec*(header.byteRate/ibytesPerSample/header.numChannels)/1000;
    unsigned int ovsamples=overlap*(header.byteRate/ibytesPerSample/header.numChannels)/1000;
    double dSilent=DBFSToVolume(SILENT);
    iSamplesPerInterval=samples+2*ovsamples;
    unsigned int k(0);

    if(this->intervals)
        delete[] intervals;
    iIntervalsCount=0;

    for(unsigned int i=0;i<iSamplesCount;i++){
        if(abs(Data(i))>dSilent){
            i+=samples;
            iIntervalsCount++;
        }
    }
    if(iIntervalsCount==0) return;

    intervals=new CSoundInterval[iIntervalsCount];
    for(unsigned int i=0;i<iSamplesCount;i++){
        if(abs(Data(i))>dSilent){
            if(i>ovsamples)
                intervals[k].begin=i-ovsamples;
            else
                intervals[k].begin=0;

            if(intervals[k].end+ovsamples<iSamplesCount)
                intervals[k].end=i+samples+ovsamples;
            else
                intervals[k].end=iSamplesCount-1;
            i+=samples;
            k++;
        }
    }

    qDebug()<<"Formed "<<iIntervalsCount<<" intervals. Samples count="<<samples;
}

bool CCharSound::SaveIntervalsToFile(const char* filename){
    fjObject obj;
    obj.Set("SampleRate", header.sampleRate);
    obj.Set("BytesPerSample", ibytesPerSample);
    obj.Set("PeakValue", iPeak);
    obj.Set("SamplesPerInterval",(int)iSamplesPerInterval);
    fjArray abc;

    for(unsigned int i=0;i<iIntervalsCount;i++){
        if(intervals[i].ch>""){
            fjObject tobj;
            tobj.Set("Char",make_shared<fjString>(intervals[i].ch));
            tobj.Set("Begin",make_shared<fjInt>(intervals[i].begin));
            fjArray tarr;
            for(unsigned int k=intervals[i].begin;k<=intervals[i].end;k++)
                tarr.Add((float)(Data(k)/(iPeak*0.5)));
                //tarr.Add(Data(k));
            tobj.Set("Samples", make_shared<fjArray>(tarr));
            abc.Add(make_shared<fjObjValue>(tobj));
        }
    }

    obj.Set("Alphabet", make_shared<fjArray>(abc));
    obj.SaveToFile(filename);
    return true;
}

bool CCharSound::LoadIntervalsFromFile(const char* filename){

    fjObject obj;
    obj.LoadFromFile(filename);

    if(!obj.exists("SampleRate") || !obj.exists("BytesPerSample") || !obj.exists("SamplesPerInterval") || !obj.exists("Alphabet") ){
        strcpy(lasterror,"Wrong file format! SampleRate, BytesPerSample, SamplesPerInterval and Alphabet fields needed");
        return false;
    }

    if(data!=nullptr){
        if(obj["SampleRate"]->asInt()!=header.sampleRate){
            strcpy(lasterror,"Another SampleRate detected!");
            return false;
        }
        if(obj["BytesPerSample"]->asInt()!=ibytesPerSample){
            strcpy(lasterror,"Another BytesPerSample detected!");
            return false;
        }
    }

    iSamplesPerInterval=obj["SamplesPerInterval"]->asInt();

    if(intervals)
        delete[] intervals;

    fjArray *abcarr=(fjArray*)obj["Alphabet"].get();
    iIntervalsCount=abcarr->Size();
    intervals=new CSoundInterval[iIntervalsCount];

    qDebug()<<iIntervalsCount<<" intervals loaded";

    for(unsigned int k=0;k<abcarr->Size();k++){
        fjObjValue *tobj=(*abcarr)[k]->asfjObjValue().get();
        intervals[k].ch=(*tobj)["Char"]->asString();

        fjArray *subarr=(*tobj)["Samples"]->asfjArray().get();
        //qDebug()<<"ch: "<<intervals[k].ch.c_str()<<" begin: "<<(*tobj)["Begin"]->asInt();
        intervals[k].begin=(*tobj)["Begin"]->asInt();
        intervals[k].end=intervals[k].begin+iSamplesPerInterval;

        //load intervals data if sound data is empty
        if(data==nullptr){
            iPeak=obj["PeakValue"]->asInt();
            intervals[k].data=new double[subarr->Size()];
            for(unsigned int j=0;j<subarr->Size();j++){
                intervals[k].data[j]=(*subarr)[j]->asFloat();
            }
        }
    }

    return true;
}

bool CCharSound::LoadFromFile(const char* filename){
    FILE *file;
    file = fopen(filename,"rb");
    if(file == nullptr) {
        strcpy(lasterror,"Can't load file");
        return false;
    }

    if(data)
        delete[] data;
    data=nullptr;
    iSamplesCount=0;
    iPeak=0;

    if(intervals)
        delete[] intervals;
    iIntervalsCount=0;
    intervals=nullptr;

    size_t aread(0);
    aread=fread((void*)&header, sizeof(WAVHEADER), 1, file);

    if(aread!=1){
        strcpy(lasterror,"Can't read wave header");
        fclose(file);
        return false;
    }

    if(memcmp(header.chunkId,"RIFF",4)!=0){
        strcpy(lasterror,"Wrong file format (RIFF)");
        fclose(file);
        return false;
    }
    if(memcmp(header.format,"WAVE",4)!=0){
        strcpy(lasterror,"Wrong file format (WAVE)");
        fclose(file);
        return false;
    }
    if(memcmp(header.subchunk1Id,"fmt ",4)!=0){
        strcpy(lasterror,"Wrong file format (fmt )");
        fclose(file);
        return false;
    }
    if(memcmp(header.subchunk2Id,"data",4)!=0){
        strcpy(lasterror,"Wrong file format (data section)");
        fclose(file);
        return false;
    }
    if(header.audioFormat!=1){
        strcpy(lasterror,"Wrong audio format. Support only PCM");
        fclose(file);
        return false;
    }

    ibytesPerSample=header.bitsPerSample / 8;

    iSamplesCount=header.subchunk2Size/ibytesPerSample;
    data=new char[header.subchunk2Size];
    aread=fread((void*)data, 1, header.subchunk2Size, file);
    if(aread!=header.subchunk2Size){
        strcpy(lasterror,"Can't read whole data section");
        fclose(file);
        return false;
    }
    fclose(file);

    CWaveSample amp;
    bSigned=false;
    if(header.bitsPerSample>8){
        for(unsigned int i=0;i<iSamplesCount;i++){
            amp.sample32=0;
            memcpy((void*)&amp.data[0],(void*)&data[i*ibytesPerSample*header.numChannels],ibytesPerSample);
            if(SampleToVal(amp)<0){
                bSigned=true;
                break;
            }
        }
    }

    iPeak=pow(2,header.bitsPerSample);

    fDuration=1.0 * header.subchunk2Size / ibytesPerSample / header.numChannels / header.sampleRate;
    fDynamicRange=VolumeToDBFS(iPeak*0.5);

    qDebug()<<"SubCh1Size="<<header.subchunk1Size<<" SizeofHeader="<<sizeof(WAVHEADER)<<" SamplesCount="<<iSamplesCount<<" subchunk2="<<header.subchunk2Size;
    qDebug()<<"peak: "<<iPeak<<" signed: "<<bSigned<<"Bits per sample:"<<header.bitsPerSample;

    return true;
}


text:
const leaveKeywords = require('../appConfig').leaveKeywords;

/**
 * Checks if the event is an all day event (contains only a date).
 *
 * @param event Event to scan
 * @returns {boolean} True if only start date exists without timestamp, false otherwise
 */
function allDayEventFilter(event) {
  let retVal = false;

  if (event && event.start && event.start.date) {
    retVal = true;
  }

  return retVal;
}

/**
 * Checks if the event summary contains any of the keywords that indicate it would be a leave event.
 *
 * @param event Event to scan
 * @returns {boolean} True if a leave event, false otherwise
 */
function leaveEventFilter(event) {
  let retVal = false;

  leaveKeywords.some((keyword) => {
    const regexString = `(^|\\s)${keyword}(?=\\s|$)`;
    const regex = new RegExp(regexString, 'gi');

    if (event.summary.match(regex)) {
      retVal = true;
    }
  });

  return retVal;
}

module.exports = {allDayEventFilter, leaveEventFilter};


text:
import mimetypes
import os
import smtplib

from email import encoders
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def adiciona_anexo(msg, filename):
    if not os.path.isfile(filename):
        return

    ctype, encoding = mimetypes.guess_type(filename)

    if ctype is None or encoding is not None:
        ctype = 'application/octet-stream'

    maintype, subtype = ctype.split('/', 1)

    if maintype == 'text':
        with open(filename) as f:
            mime = MIMEText(f.read(), _subtype=subtype)
    elif maintype == 'image':
        with open(filename, 'rb') as f:
            mime = MIMEImage(f.read(), _subtype=subtype)
    elif maintype == 'audio':
        with open(filename, 'rb') as f:
            mime = MIMEAudio(f.read(), _subtype=subtype)
    else:
        with open(filename, 'rb') as f:
            mime = MIMEBase(maintype, subtype)
            mime.set_payload(f.read())

        encoders.encode_base64(mime)

    mime.add_header('Content-Disposition', 'attachment', filename=filename)
    msg.attach(mime)

de = 'seumail@gmail.com'
para = ['outroemail@gmail.com']

msg = MIMEMultipart()
msg['From'] = de
msg['To'] = ', '.join(para)
msg['Subject'] = 'Buteco Open Source'

# Corpo da mensagem
msg.attach(MIMEText('Exemplo de email HTML com anexo do <b>Buteco Open Source<b/>.', 'html', 'utf-8'))

# Arquivos anexos.
adiciona_anexo(msg, 'texto.txt')
adiciona_anexo(msg, 'imagem.jpg')

raw = msg.as_string()

smtp = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtp.login('seumail@gmail.com', 'suasenha')
smtp.sendmail(de, para, raw)
smtp.quit()


text:
Camera_positions_list::Camera_positions_list(QWidget* parent)
  : QDockWidget(parent), m_viewer(0), counter(0), m_model(new QStandardItemModel(this))
{
  Ui::Camera_positions_list ui;
  ui.setupUi(this);
  m_listView = ui.listView;
  m_listView->setModel(m_model);

  m_listView->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed);
  connect(m_listView, SIGNAL(activated(QModelIndex)),
          this, SLOT(activatedRow(QModelIndex)));
}

void Camera_positions_list::setViewer(CGAL::Three::Viewer_interface* viewer)
{
  m_viewer = viewer;
}

void Camera_positions_list::on_plusButton_pressed()
{
  if(!m_viewer) return;
  addItem(tr("Camera Position #%1").arg(++counter),
          m_viewer->dumpCameraCoordinates());
}

void Camera_positions_list::addItem(QString text, QString data)
{
  QStandardItem* item = new QStandardItem(text);
  item->setData(data, Qt::UserRole);
  m_model->insertRow(m_model->rowCount(), item);
}

void Camera_positions_list::on_upButton_pressed()
{
  int row = m_listView->selectionModel()->currentIndex().row();
  if(row!=0)
  {
  m_model->insertRow(row-1, m_model->takeRow(row));
  m_listView->selectionModel()->setCurrentIndex(m_model->index(row-1, 0),
                                                QItemSelectionModel::Clear);
  }
}

void Camera_positions_list::on_downButton_pressed()
{
  int row = m_listView->selectionModel()->currentIndex().row();
  if(row!= m_listView->model()->rowCount()-1)
  {
  m_model->insertRow(row+1, m_model->takeRow(row));
  m_listView->selectionModel()->setCurrentIndex(m_model->index(row+1, 0),
                                                QItemSelectionModel::Clear);
  }
}

void Camera_positions_list::on_minusButton_pressed()
{
  Q_FOREACH(QModelIndex index,
            m_listView->selectionModel()->selectedIndexes()) {
    m_model->removeRows(index.row(), 1);
  }
}

void Camera_positions_list::on_clearButton_pressed()
{
  m_model->clear();
}

// void Camera_positions_list::editItem(QListWidgetItem* item)
// {
//   std::cerr << "is_editable: " << m_listView->flags(item)QListWidget

//   m_listView->editItem(item);
// }

void Camera_positions_list::activatedRow(QModelIndex index)
{
  QString s = m_model->data(index, Qt::UserRole).toString();
  if(s.isNull()) return;
  m_viewer->moveCameraToCoordinates(s);
}

void Camera_positions_list::on_saveButton_pressed()
{
  QString filename =
    QFileDialog::getSaveFileName(this,
                                 tr("Save camera coordinates to file"),
                                 QString(),
                                 tr("(*.camera.txt)"));
  QFile file(filename);
  file.open(QIODevice::WriteOnly);
  QTextStream out(&file);
  for(int i = 0; i < m_model->rowCount(); ++i)
  {
    QStandardItem* item = m_model->item(i);
    out << item->data(Qt::DisplayRole).toString()
        << "\n"
        << item->data(Qt::UserRole).toString()
        << "\n";
  }
  file.close();
}

void Camera_positions_list::on_openButton_pressed()
{
  QString filename =
    QFileDialog::getOpenFileName(this,
                                 tr("Read camera coordinates from file"),
                                 QString(),
                                 tr("(*.camera.txt)"));
  load(filename);
}

void Camera_positions_list::load(QString filename) {
  QFile file(filename);
  std::clog << "Loading camera positions " << qPrintable(filename) << std::endl;
  file.open(QIODevice::ReadOnly);
  QTextStream input(&file);
  while(!input.atEnd()) {
    QString text = input.readLine(1000);
    QString coord = input.readLine(1000);
    if(text.isNull() || coord.isNull()) return;
    qglviewer::Frame frame;
    if(m_viewer->readFrame(coord, frame))
    {
      addItem(text,
              m_viewer->dumpFrame(frame));
    }
  }
}

void Camera_positions_list::on_frontButton_pressed()
{
    qglviewer::Vec posFront = qglviewer::Vec(0,0,m_viewer->sceneRadius()/(sin (m_viewer->camera()->fieldOfView()/2)));
#if QGLVIEWER_VERSION >= 0x020502
    qglviewer::Vec trans = m_viewer->camera()->pivotPoint();
#else
    qglviewer::Vec trans = m_viewer->camera()->revolveAroundPoint();
#endif
    posFront = posFront + trans;
    qglviewer::Quaternion dirFront;
    dirFront.setAxisAngle(qglviewer::Vec(0,1,0),0);
    QString frontCoord = QString("%1 %2 %3 %4 %5 %6 %7")
            .arg(posFront[0])
            .arg(posFront[1])
            .arg(posFront[2])
            .arg(dirFront[0])
            .arg(dirFront[1])
            .arg(dirFront[2])
            .arg(dirFront[3]);

   m_viewer->moveCameraToCoordinates(frontCoord, 0.5f);
}

void Camera_positions_list::on_backButton_pressed()
{
    qglviewer::Vec posBack = qglviewer::Vec(0,0,-m_viewer->sceneRadius()/(sin (m_viewer->camera()->fieldOfView()/2)));
#if QGLVIEWER_VERSION >= 0x020502
    qglviewer::Vec trans = m_viewer->camera()->pivotPoint();
#else
    qglviewer::Vec trans = m_viewer->camera()->revolveAroundPoint();
#endif
    posBack+= trans;
    qglviewer::Quaternion dirBack;
    dirBack.setAxisAngle(qglviewer::Vec(0,1,0),CGAL_PI);
    QString backCoord = QString("%1 %2 %3 %4 %5 %6 %7")
            .arg(posBack[0])
            .arg(posBack[1])
            .arg(posBack[2])
            .arg(dirBack[0])
            .arg(dirBack[1])
            .arg(dirBack[2])
            .arg(dirBack[3]);
    m_viewer->moveCameraToCoordinates(backCoord, 0.5f);
}

void Camera_positions_list::on_topButton_pressed()
{
    qglviewer::Vec posTop = qglviewer::Vec(0,m_viewer->sceneRadius()/(sin (m_viewer->camera()->fieldOfView()/2)), 0);
#if QGLVIEWER_VERSION >= 0x020502
    qglviewer::Vec trans = m_viewer->camera()->pivotPoint();
#else
    qglviewer::Vec trans = m_viewer->camera()->revolveAroundPoint();
#endif
    posTop += trans;
    qglviewer::Quaternion dirTop;
    dirTop.setAxisAngle(qglviewer::Vec(1,0,0), -CGAL_PI/2);
    QString topCoord = QString("%1 %2 %3 %4 %5 %6 %7")
            .arg(posTop[0])
            .arg(posTop[1])
            .arg(posTop[2])
            .arg(dirTop[0])
            .arg(dirTop[1])
            .arg(dirTop[2])
            .arg(dirTop[3]);
     m_viewer->moveCameraToCoordinates(topCoord, 0.5f);
}

void Camera_positions_list::on_botButton_pressed()
{
    qglviewer::Vec posBot = qglviewer::Vec(0,-m_viewer->sceneRadius()/(sin (m_viewer->camera()->fieldOfView()/2)), 0);;
#if QGLVIEWER_VERSION >= 0x020502
    qglviewer::Vec trans = m_viewer->camera()->pivotPoint();
#else
    qglviewer::Vec trans = m_viewer->camera()->revolveAroundPoint();
#endif
    posBot += trans;
    qglviewer::Quaternion dirBot;
    dirBot.setAxisAngle(qglviewer::Vec(1,0,0),CGAL_PI/2);
    QString botCoord = QString("%1 %2 %3 %4 %5 %6 %7")
            .arg(posBot[0])
            .arg(posBot[1])
            .arg(posBot[2])
            .arg(dirBot[0])
            .arg(dirBot[1])
            .arg(dirBot[2])
            .arg(dirBot[3]);
     m_viewer->moveCameraToCoordinates(botCoord, 0.5f);
}

void Camera_positions_list::on_leftButton_pressed()
{
    qglviewer::Vec posLeft = qglviewer::Vec(-m_viewer->sceneRadius()/(sin (m_viewer->camera()->fieldOfView()/2)), 0, 0);;
#if QGLVIEWER_VERSION >= 0x020502
    qglviewer::Vec trans = m_viewer->camera()->pivotPoint();
#else
    qglviewer::Vec trans = m_viewer->camera()->revolveAroundPoint();
#endif
    posLeft += trans;
    qglviewer::Quaternion dirLeft;
    dirLeft.setAxisAngle(qglviewer::Vec(0,1,0),-CGAL_PI/2);
    QString leftCoord = QString("%1 %2 %3 %4 %5 %6 %7")
            .arg(posLeft[0])
            .arg(posLeft[1])
            .arg(posLeft[2])
            .arg(dirLeft[0])
            .arg(dirLeft[1])
            .arg(dirLeft[2])
            .arg(dirLeft[3]);
    m_viewer->moveCameraToCoordinates(leftCoord, 0.5f);
}

void Camera_positions_list::on_rightButton_pressed()
{
    qglviewer::Vec posRight = qglviewer::Vec(m_viewer->sceneRadius()/(sin (m_viewer->camera()->fieldOfView()/2)), 0,0);
#if QGLVIEWER_VERSION >= 0x020502
    qglviewer::Vec trans = m_viewer->camera()->pivotPoint();
#else
    qglviewer::Vec trans = m_viewer->camera()->revolveAroundPoint();
#endif
    posRight += trans;
    qglviewer::Quaternion dirRight;
    dirRight.setAxisAngle(qglviewer::Vec(0,1,0),CGAL_PI/2);
    QString rightCoord = QString("%1 %2 %3 %4 %5 %6 %7")
            .arg(posRight[0])
            .arg(posRight[1])
            .arg(posRight[2])
            .arg(dirRight[0])
            .arg(dirRight[1])
            .arg(dirRight[2])
            .arg(dirRight[3]);
    m_viewer->moveCameraToCoordinates(rightCoord, 0.5f);

}


text:
//============================================================================
//
// Copyright (C) 2006-2022 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
//============================================================================
package org.talend.components.google.drive.runtime;

import static java.lang.String.format;
import static java.util.Arrays.asList;
import static org.talend.components.google.drive.GoogleDriveMimeTypes.MIME_TYPE_FOLDER;
import static org.talend.components.google.drive.runtime.GoogleDriveConstants.DRIVE_ROOT_FOLDER;
import static org.talend.components.google.drive.runtime.GoogleDriveConstants.QUERY_NOTTRASHED_NAME_NOTMIME_INPARENTS;
import static org.talend.components.google.drive.runtime.GoogleDriveConstants.Q_AND;
import static org.talend.components.google.drive.runtime.GoogleDriveConstants.Q_IN_PARENTS;
import static org.talend.components.google.drive.runtime.GoogleDriveConstants.Q_MIME_FOLDER;
import static org.talend.components.google.drive.runtime.GoogleDriveConstants.Q_MIME_NOT_FOLDER;
import static org.talend.components.google.drive.runtime.GoogleDriveConstants.Q_NAME;
import static org.talend.components.google.drive.runtime.GoogleDriveConstants.Q_NOT_TRASHED;
import static org.talend.components.google.drive.runtime.GoogleDriveConstants.ROOT_OR_SHARED_WITH_ME_PARENT;
import static org.talend.components.google.drive.runtime.GoogleDriveConstants.ROOT_FOLDER_SEPARATOR;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.talend.components.google.drive.GoogleDriveMimeTypes;
import org.talend.components.google.drive.GoogleDriveComponentProperties.Corpora;
import org.talend.components.google.drive.runtime.utils.GoogleDriveGetParameters;
import org.talend.components.google.drive.runtime.utils.GoogleDriveGetResult;
import org.talend.components.google.drive.runtime.utils.GoogleDrivePutParameters;
import org.talend.daikon.i18n.GlobalI18N;
import org.talend.daikon.i18n.I18nMessages;

import com.google.api.client.http.AbstractInputStreamContent;
import com.google.api.client.http.ByteArrayContent;
import com.google.api.client.http.FileContent;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;

public class GoogleDriveUtils {

    private static final Logger LOG = LoggerFactory.getLogger(GoogleDriveUtils.class);

    private static final I18nMessages messages =
            GlobalI18N.getI18nMessageProvider().getI18nMessages(GoogleDriveUtils.class);

    private Drive drive;

    private static final String FILE_TYPE = "file";

    private static final String FOLDER_TYPE = "folder";

    private static final String FILEFOLDER_TYPE = "filefolder";

    private static final String PATH_SEPARATOR = "/";

    private boolean includeSharedItems;

    private boolean includeSharedDrives;

    private Corpora corpora;

    private String driveId;

    public GoogleDriveUtils(Drive drive) {
        this.drive = drive;
    }

    public void setIncludeSharedDrives(boolean includeSharedDrives) {
        this.includeSharedDrives = includeSharedDrives;
    }

    public void setCorpora(Corpora corpora) {
        this.corpora = corpora;
    }

    public void setDriveId(String driveId) {
        this.driveId = driveId;
    }

    private Files.List createListRequest(String query) throws IOException {
        Files.List request = drive
                .files()
                .list()
                .setQ(query)
                .setSupportsAllDrives(includeSharedDrives)
                .setIncludeItemsFromAllDrives(includeSharedDrives);
        if (corpora != null) {
            request.setCorpora(corpora.getCorporaName());
            if (corpora == Corpora.DRIVE) {
                request.setDriveId(driveId);
            }
        }
        return request;
    }

    public List<String> getExplodedPath(String resourcePath) {
        LOG.debug("[getExplodedPath] resourcePath :`{}`.", resourcePath);
        String path = resourcePath.trim();
        path = path.startsWith(PATH_SEPARATOR) ? path.substring(1) : path;
        path = path.endsWith(PATH_SEPARATOR) ? path.substring(0, path.length() - 1) : path;
        return asList(path.split(PATH_SEPARATOR));
    }

    public File getMetadata(String id, String metadata) throws IOException {
        LOG.debug("[getMetadata] id={}, metadata={}.", id, metadata);
        return drive.files().get(id).setFields(metadata).setSupportsAllDrives(includeSharedDrives).execute();
    }

    public String getResourceId(String query, String resourceName, String type) throws IOException {
        LOG.debug("[getResourceId] Searching for {} named {} with `{}`.", type, resourceName, query);
        FileList files = createListRequest(query).execute();
        if (files.getFiles().size() > 1) {
            String errorMsg = messages.getMessage(format("error.%s.more.than.one", type), resourceName);
            LOG.error(errorMsg);
            throw new IOException(errorMsg);
        } else if (files.getFiles().isEmpty()) {
            String errorMsg = messages.getMessage(format("error.%s.inexistant", type), resourceName);
            LOG.error(errorMsg);
            throw new IOException(errorMsg);
        }
        LOG.debug("[getResourceId] Found `{}` [{}].", resourceName, files.getFiles().get(0).getId());

        return files.getFiles().get(0).getId();
    }

    private List<String> checkPath(int pathLevel, List<String> path, String folderName, String parentId,
            boolean searchInTrash) throws IOException {
        List<String> result = new ArrayList<>();
        LOG.debug("[checkPath] (pathLevel = [{}], path = [{}], folderName = [{}], parentId = [{}], searchInTrash = [{}]).",
                        pathLevel, path, folderName, parentId, searchInTrash);
        String query = null;
        if (includeSharedDrives && DRIVE_ROOT_FOLDER.equals(parentId)) {
            query = new StringBuilder()
                    .append(format(Q_NAME, folderName))
                    .append(Q_AND)
                    .append(Q_MIME_FOLDER)
                    .append(searchInTrash ? "" : Q_AND + Q_NOT_TRASHED)
                    .toString();
        } else {
            String parentIdFormatted =
                    includeSharedItems && DRIVE_ROOT_FOLDER.equals(parentId)
                            ? ROOT_OR_SHARED_WITH_ME_PARENT
                            : format(Q_IN_PARENTS, parentId);
            query = new StringBuilder()
                    .append(format(Q_NAME, folderName))
                    .append(Q_AND)
                    .append(parentIdFormatted)
                    .append(Q_AND)
                    .append(Q_MIME_FOLDER)
                    .append(searchInTrash ? "" : Q_AND + Q_NOT_TRASHED)
                    .toString();
        }
        LOG.debug("[checkPath] Query({}).", query);
        FileList files = createListRequest(query).execute();
        if (files.getFiles().isEmpty()) {
            return Collections.emptyList();
        }
        int idx = pathLevel + 1;
        if (files.getFiles().size() > 1) {
            for (File f : files.getFiles()) {
                if (idx == path.size()) {
                    result.add(f.getId());// last level, give up...
                } else {
                    result.addAll(checkPath(idx, path, path.get(idx), f.getId(), searchInTrash));
                }
            }
        } else {
            File f = files.getFiles().get(0);
            String currentId = f.getId();
            if (idx == path.size()) {
                result.add(currentId);

            } else {
                String next = path.get(idx);
                result.addAll(checkPath(idx, path, next, currentId, searchInTrash));
            }
        }
        LOG.debug("[checkPath] `{}` => [{}].", String.join("/", path), result);

        return result;
    }

    public List<String> getFolderIds(String folderName, boolean searchInTrash, boolean includeSharedItems)
            throws IOException {
        LOG.debug("[getFolderIds] (folderName = [{}], searchInTrash = [{}]).", folderName, searchInTrash);
        List<String> result = new ArrayList<>();
        if (DRIVE_ROOT_FOLDER.equals(folderName) || ROOT_FOLDER_SEPARATOR.equals(folderName) || folderName.isEmpty()) {
            result.add(DRIVE_ROOT_FOLDER);
            return result;
        }
        this.includeSharedItems = includeSharedItems;
        List<String> path = getExplodedPath(folderName);
        String start = path.get(0);
        result = checkPath(0, path, start, "root", searchInTrash);
        LOG.debug("[getFolderIds] checkPath returned : {}", result);
        if (result.isEmpty() && !folderName.contains(PATH_SEPARATOR)) {
            LOG.debug("[getFolderIds] Searching with global search...");
            result = new ArrayList<>();
            result.add(findResourceByGlobalSearch(folderName, FOLDER_TYPE));
        }

        LOG.debug("[getFolderIds] Returning {}.", result);
        return result;
    }

    public String findResourceByName(String resource, String type) throws IOException {
        if (resource.contains(PATH_SEPARATOR)) {
            long tries = 0;
            while (tries <= 3) {
                if (tries > 0) {
                    long sleepTime = 1 << (tries - 1);
                    LOG.debug("[findResourceByName] Error detected! Attempting retry in {} second(s).", sleepTime);
                    try {
                        TimeUnit.SECONDS.sleep(sleepTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    return findResourceByPath(resource, type);
                } catch (IOException e) {
                    if (tries == 3) {
                        throw e;
                    } else {
                        tries++;
                    }
                }
            }
            return "";
        } else {
            return findResourceByGlobalSearch(resource, type);
        }
    }

    private String findResourceByGlobalSearch(String resource, String type) throws IOException {
        StringBuilder querybuilder = new StringBuilder();
        // Location restriction: do not search in shared locations if not required
        String locationRestriction = includeSharedItems ? "" : Q_AND + "'me' in owners";
        switch (type) {
        case FILE_TYPE:
            querybuilder.append(format(Q_NAME, resource)).append(Q_AND).append(Q_MIME_NOT_FOLDER).append(locationRestriction);
            break;
        case FOLDER_TYPE:
            querybuilder.append(format(Q_NAME, resource)).append(Q_AND).append(Q_MIME_FOLDER).append(locationRestriction);
            break;
        case FILEFOLDER_TYPE:
            querybuilder.append(format(Q_NAME, resource)).append(locationRestriction);
            break;
        default:
        }

    	String query = querybuilder.toString();

        LOG.debug("[findResourceByGlobalSearch] Searching for {} [{}] with `{}`.", resource, type, query);
        return getResourceId(query, resource, type);
    }

    private String findResourceByPath(String resourceName, String type) throws IOException {
        List<String> path = getExplodedPath(resourceName);
        String fileName = path.get(path.size() - 1);
        String parentId = DRIVE_ROOT_FOLDER;
        String query;
        LOG
                .debug("[findResourceByPath] Searching for {} [{}]. Path: {}; FileName:{}", resourceName,
                        type.toUpperCase(), path,
                        fileName);
        switch (type) {
        case FILE_TYPE:
            // We may have the case of "/FileA". So parentId is root and otherwise :
            if (path.size() > 1) {
                parentId = handleCheckPathResult(
                        checkPath(0, path.subList(0, (path.size() - 1)), path.get(0), "root", true));
            }
            query = format(Q_NAME, fileName) + Q_AND + //
                    format(Q_IN_PARENTS, parentId) + Q_AND + //
                    Q_MIME_NOT_FOLDER;
            return getResourceId(query, fileName, FILE_TYPE);
        case FOLDER_TYPE:
            return handleCheckPathResult(checkPath(0, path, path.get(0), "root", true));
        case FILEFOLDER_TYPE:
            // try a full path first...
            LOG.debug("[findResourceByPath] Searching for a full path...");
            List<String> searchPath = checkPath(0, path, path.get(0), "root", true);
            if (searchPath.size() == 1) {
                return searchPath.get(0);
            }
            // try path + fileName
            LOG.debug("[findResourceByPath] Searching for fileName because did not find a full path");
            parentId =
                    handleCheckPathResult(checkPath(0, path.subList(0, (path.size() - 1)), path.get(0), "root", true));
            query = format(Q_NAME, fileName) + Q_AND + //
                    format(Q_IN_PARENTS, parentId) + Q_AND + //
                    Q_MIME_NOT_FOLDER;
            return getResourceId(query, fileName, FILE_TYPE);
        default:
        }
        return null;
    }

    private String handleCheckPathResult(List<String> path) throws IOException {
        if (path.size() == 1) {
            return path.get(0);
        }
        String errorMsg = "";
        if (path.size() > 1) {
            errorMsg = messages.getMessage("error.folder.more.than.one", path);
        } else {
            errorMsg = messages.getMessage("error.folder.inexistant", path);
        }
        LOG.error(errorMsg);
        throw new IOException(errorMsg);
    }

    /**
     * @param folderName searched folder name
     * @param searchInTrash include folders in trash
     * @return the folder ID value
     * @throws IOException when the folder doesn't exist or there are more than one folder named like {@code folderName}
     */
    public String getFolderId(String folderName, boolean searchInTrash, boolean includeSharedItems) throws IOException {
        if (DRIVE_ROOT_FOLDER.equals(folderName) || ROOT_FOLDER_SEPARATOR.equals(folderName) || folderName.isEmpty()) {
            return DRIVE_ROOT_FOLDER;
        }
        this.includeSharedItems = includeSharedItems;
        return findResourceByName(folderName, FOLDER_TYPE);
    }

    /**
     * @param fileName searched fileName name
     * @return the fileName ID value
     * @throws IOException when the fileName doesn't exist or there are more than one fileName named like
     * {@code fileName}
     */
    public String getFileId(String fileName, boolean includeSharedItems) throws IOException {
        this.includeSharedItems = includeSharedItems;
        return findResourceByName(fileName, FILE_TYPE);
    }

    /**
     * @param fileOrFolderName searched fileName name or folder
     * @return fileName ID value
     * @throws IOException when the fileName/folder doesn't exist or there are more than one fileName/folder named like
     * {@code fileOrFolderName}
     */
    public String getFileOrFolderId(String fileOrFolderName, boolean includeSharedItems) throws IOException {
        this.includeSharedItems = includeSharedItems;
        return findResourceByName(fileOrFolderName, FILEFOLDER_TYPE);
    }

    /**
     * Create a folder in the specified parent folder
     *
     * @param parentFolderId folder ID where to create folderName
     * @param folderName new folder's name
     * @return folder ID value
     * @throws IOException when operation fails
     */
    public String createFolder(String parentFolderId, String folderName) throws IOException {
        File createdFolder = new File();
        createdFolder.setName(folderName);
        createdFolder.setMimeType(MIME_TYPE_FOLDER);
        createdFolder.setParents(Collections.singletonList(parentFolderId));

        return drive
                .files()
                .create(createdFolder)
                .setFields("id")
                .setSupportsAllDrives(includeSharedDrives)
                .execute()
                .getId();
    }

    /**
     * @param fileId ID of the fileName to copy
     * @param destinationFolderId folder ID where to copy the fileId
     * @param newName if not empty rename copy to this name
     * @param deleteOriginal remove original fileName (aka mv)
     * @return copied fileName ID
     * @throws IOException when copy fails
     */
    public String copyFile(String fileId, String destinationFolderId, String newName, boolean deleteOriginal)
            throws IOException {
        LOG
                .debug("[copyFile] fileId: {}; destinationFolderId: {}, newName: {}; deleteOriginal: {}.", fileId,
                        destinationFolderId,
                        newName, deleteOriginal);
        File copy = new File();
        copy.setParents(Collections.singletonList(destinationFolderId));
        if (!newName.isEmpty()) {
            copy.setName(newName);
        }
        File resultFile = drive
                .files()
                .copy(fileId, copy)
                .setFields("id, parents")
                .setSupportsAllDrives(includeSharedDrives)
                .execute();
        String copiedResourceId = resultFile.getId();
        if (deleteOriginal) {
            drive.files().delete(fileId).setSupportsAllDrives(includeSharedDrives).execute();
        }

        return copiedResourceId;
    }

    /**
     * @param sourceFolderId source folder ID
     * @param destinationFolderId folder ID where to copy the sourceFolderId's content
     * @param newName folder name to assign
     * @return created folder ID
     * @throws IOException when operation fails
     */
    public String copyFolder(String sourceFolderId, String destinationFolderId, String newName) throws IOException {
        LOG
                .debug("[copyFolder] sourceFolderId: {}; destinationFolderId: {}; newName: {}", sourceFolderId,
                        destinationFolderId,
                        newName);
        // create a new folder
        String newFolderId = createFolder(destinationFolderId, newName);
        // Make a recursive copy of all files/folders inside the source folder
        String query = format(Q_IN_PARENTS, sourceFolderId) + Q_AND + Q_NOT_TRASHED;
        FileList originals = createListRequest(query).execute();
        LOG.debug("[copyFolder] Searching for copy {}", query);
        for (File file : originals.getFiles()) {
            if (file.getMimeType().equals(MIME_TYPE_FOLDER)) {
                copyFolder(file.getId(), newFolderId, file.getName());
            } else {
                copyFile(file.getId(), newFolderId, file.getName(), false);
            }
        }

        return newFolderId;
    }

    private String removeResource(String resourceId, boolean useTrash) throws IOException {
        if (useTrash) {
            LOG.info(messages.getMessage("message.trashing.resource", resourceId, resourceId));
            drive
                    .files()
                    .update(resourceId, new File().setTrashed(true))
                    .setSupportsAllDrives(includeSharedDrives)
                    .execute();
        } else {
            LOG.info(messages.getMessage("message.deleting.resource", resourceId, resourceId));
            drive
                    .files()
                    .delete(resourceId)
                    .setSupportsAllDrives(includeSharedDrives)
                    .execute();
        }
        return resourceId;
    }

    public String deleteResourceByName(String resourceName, boolean useTrash, boolean includeSharedItems)
            throws IOException {
        return removeResource(getFileOrFolderId(resourceName, includeSharedItems), useTrash);
    }

    public String deleteResourceById(String resourceId, boolean useTrash) throws IOException {
        return removeResource(resourceId, useTrash);
    }

    public GoogleDriveGetResult getResource(GoogleDriveGetParameters parameters) throws IOException {
        String fileId = parameters.getResourceId();
        File file = getMetadata(fileId, "id,mimeType,fileExtension");
        String fileMimeType = file.getMimeType();
        String outputFileExt = "." + file.getFileExtension();
        LOG
                .debug("[getResource] Found fileName `{}` [id: {}, mime: {}, ext: {}]", parameters.getResourceId(),
                        fileId,
                        fileMimeType, file.getFileExtension());
        if(!parameters.isStoreToLocal() && !parameters.isCreateByteArray()) {
            LOG
            .debug("[getResource] Skipping file `{}` [id: {}, mime: {}, ext: {}], wrong configuration : either save to local file or provide an outgoing link for the component!", parameters.getResourceId(),
                    fileId, fileMimeType, file.getFileExtension());
            return new GoogleDriveGetResult(fileId, null);
        }

        String localFile = null;
        if (parameters.isStoreToLocal()) {
            localFile = parameters.getOutputFileName();
            if (parameters.isAddExt()) {
                localFile = localFile + ((localFile.endsWith(outputFileExt)) ? "" : outputFileExt);
            }
        }

        if (!parameters.isCreateByteArray() && parameters.isStoreToLocal()) {
            LOG.info(messages.getMessage("message.writing.resource", parameters.getResourceId(), localFile));
        }

        byte[] content = null;
        try (OutputStream outputStream = (parameters.isCreateByteArray() || !parameters.isStoreToLocal())
                ? new ByteArrayOutputStream() : new FileOutputStream(localFile)) {
            if (GoogleDriveMimeTypes.GOOGLE_DRIVE_APPS.contains(fileMimeType)) {
                String exportFormat = parameters.getMimeType().get(fileMimeType).getMimeType();
                outputFileExt = parameters.getMimeType().get(fileMimeType).getExtension();
                drive.files().export(fileId, exportFormat).executeMediaAndDownloadTo(outputStream);
            } else { /* Standard fileName */
                drive.files().get(fileId).setSupportsAllDrives(includeSharedDrives)
                    .executeMediaAndDownloadTo(outputStream);
            }

            if (parameters.isCreateByteArray()) {
                content = ((ByteArrayOutputStream) outputStream).toByteArray();
                if (parameters.isStoreToLocal()) {
                    LOG.info(messages.getMessage("message.writing.resource", parameters.getResourceId(), localFile));
                    try (FileOutputStream fout = new FileOutputStream(localFile)) {
                        fout.write(content);
                    }
                }
            }
        }

        return new GoogleDriveGetResult(fileId, content);
    }

    public File putResource(GoogleDrivePutParameters parameters) throws IOException {
        String folderId = parameters.getDestinationFolderId();
        File putFile = new File();
        putFile.setParents(Collections.singletonList(folderId));
        Files.List fileRequest = createListRequest(
                format(QUERY_NOTTRASHED_NAME_NOTMIME_INPARENTS, parameters.getResourceName(), MIME_TYPE_FOLDER,
                        folderId));
        LOG
                .debug("[putResource] `{}` Exists in `{}` ? with `{}`.", parameters.getResourceName(),
                        parameters.getDestinationFolderId(), fileRequest.getQ());
        FileList existingFiles = fileRequest.execute();
        if (existingFiles.getFiles().size() > 1) {
            throw new IOException(messages.getMessage("error.file.more.than.one", parameters.getResourceName()));
        }
        if (existingFiles.getFiles().size() == 1) {
            if (!parameters.isOverwriteIfExist()) {
                throw new IOException(messages.getMessage("error.file.already.exist", parameters.getResourceName()));
            }
            LOG.debug("[putResource] {} will be overwritten...", parameters.getResourceName());
            drive
                    .files()
                    .delete(existingFiles.getFiles().get(0).getId())
                    .setSupportsAllDrives(includeSharedDrives)
                    .execute();
        }
        putFile.setName(parameters.getResourceName());
        String metadata = "id,parents,name";
        if (!StringUtils.isEmpty(parameters.getFromLocalFilePath())) {
            // Reading content from local fileName
            FileContent fContent = new FileContent(null, new java.io.File(parameters.getFromLocalFilePath()));
            putFile = drive
                    .files()
                    .create(putFile, fContent)
                    .setFields(metadata)
                    .setSupportsAllDrives(includeSharedDrives)
                    .execute();
            //

        } else if (parameters.getFromBytes() != null) {
            AbstractInputStreamContent content = new ByteArrayContent(null, parameters.getFromBytes());
            putFile = drive
                    .files()
                    .create(putFile, content)
                    .setFields(metadata)
                    .setSupportsAllDrives(includeSharedDrives)
                    .execute();
        }
        return putFile;
    }

}


text:
import React from 'react';

import { StageConfigField } from 'core/pipeline';
import { CheckboxInput, TextInput } from 'core/presentation';
import { MapEditor } from 'core/forms';
import { IArtifact, IExpectedArtifact, IPipeline } from 'core/domain';
import { StageArtifactSelectorDelegate } from 'core/artifact';
import { IFormikStageConfigInjectedProps } from '../../FormikStageConfig';

interface IBakeHelmConfigFormProps {
  updatePipeline: (pipeline: IPipeline) => void;
}

export class BakeHelmConfigForm extends React.Component<IBakeHelmConfigFormProps & IFormikStageConfigInjectedProps> {
  public componentDidMount() {
    const stage = this.props.formik.values;
    if (stage.inputArtifacts && stage.inputArtifacts.length === 0) {
      this.props.formik.setFieldValue('inputArtifacts', [
        {
          account: '',
          id: '',
        },
      ]);
    }
  }

  private onTemplateArtifactEdited = (artifact: IArtifact, index: number) => {
    this.props.formik.setFieldValue(`inputArtifacts[${index}].id`, null);
    this.props.formik.setFieldValue(`inputArtifacts[${index}].artifact`, artifact);
    this.props.formik.setFieldValue(`inputArtifacts[${index}].account`, artifact.artifactAccount);
  };

  private onTemplateArtifactSelected = (id: string, index: number) => {
    this.props.formik.setFieldValue(`inputArtifacts[${index}].id`, id);
    this.props.formik.setFieldValue(`inputArtifacts[${index}].artifact`, null);
  };

  private onTemplateArtifactAccountSelected = (account: string, index: number) => {
    this.props.formik.setFieldValue(`inputArtifacts[${index}].account`, account);
  };

  private addInputArtifact = () => {
    const stage = this.props.formik.values;
    const newInputArtifacts = [
      ...stage.inputArtifacts,
      {
        account: '',
        id: '',
      },
    ];

    this.props.formik.setFieldValue('inputArtifacts', newInputArtifacts);
  };

  private removeInputArtifact = (index: number) => {
    const stage = this.props.formik.values;
    const newInputArtifacts = [...stage.inputArtifacts];
    newInputArtifacts.splice(index, 1);
    this.props.formik.setFieldValue('inputArtifacts', newInputArtifacts);
  };

  private getInputArtifact = (stage: any, index: number) => {
    if (!stage.inputArtifacts || stage.inputArtifacts.length === 0) {
      return {
        account: '',
        id: '',
      };
    } else {
      return stage.inputArtifacts[index];
    }
  };

  private outputNameChange = (outputName: string) => {
    const stage = this.props.formik.values;
    const expectedArtifacts = stage.expectedArtifacts;
    if (
      expectedArtifacts &&
      expectedArtifacts.length === 1 &&
      expectedArtifacts[0].matchArtifact &&
      expectedArtifacts[0].matchArtifact.type === 'embedded/base64'
    ) {
      this.props.formik.setFieldValue('expectedArtifacts', [
        {
          ...expectedArtifacts[0],
          matchArtifact: {
            ...expectedArtifacts[0].matchArtifact,
            name: outputName,
          },
        },
      ]);
    }
  };

  private overrideChanged = (overrides: any) => {
    this.props.formik.setFieldValue('overrides', overrides);
  };

  public render() {
    const stage = this.props.formik.values;

    return (
      <>

Helm Options

        <StageConfigField fieldColumns={3} label={'Name'}>
          <TextInput
            onChange={(e: React.ChangeEvent<any>) => {
              this.props.formik.setFieldValue('outputName', e.target.value);
              this.outputNameChange(e.target.value);
            }}
            value={stage.outputName}
          />
        </StageConfigField>
        <StageConfigField fieldColumns={3} label={'Namespace'}>
          <TextInput
            onChange={(e: React.ChangeEvent<any>) => {
              this.props.formik.setFieldValue('namespace', e.target.value);
            }}
            value={stage.namespace}
          />
        </StageConfigField>

Template Artifact

        <StageArtifactSelectorDelegate
          artifact={this.getInputArtifact(stage, 0).artifact}
          excludedArtifactTypePatterns={[]}
          expectedArtifactId={this.getInputArtifact(stage, 0).id}
          helpKey="pipeline.config.bake.manifest.expectedArtifact"
          label="Expected Artifact"
          onArtifactEdited={artifact => {
            this.onTemplateArtifactEdited(artifact, 0);
          }}
          onExpectedArtifactSelected={(artifact: IExpectedArtifact) => this.onTemplateArtifactSelected(artifact.id, 0)}
          pipeline={this.props.pipeline}
          selectedArtifactAccount={this.getInputArtifact(stage, 0).account}
          selectedArtifactId={this.getInputArtifact(stage, 0).id}
          setArtifactAccount={account => this.onTemplateArtifactAccountSelected(account, 0)}
          setArtifactId={id => this.onTemplateArtifactSelected(id, 0)}
          stage={stage}
          updatePipeline={this.props.updatePipeline}
        />

Overrides

        {stage.inputArtifacts && stage.inputArtifacts.length > 1 && (

            {stage.inputArtifacts.slice(1).map((a: any, index: number) => {
              return (

                    <StageArtifactSelectorDelegate
                      artifact={a.artifact}
                      excludedArtifactTypePatterns={[]}
                      expectedArtifactId={a.id}
                      label="Expected Artifact"
                      onArtifactEdited={artifact => {
                        this.onTemplateArtifactEdited(artifact, index + 1);
                      }}
                      onExpectedArtifactSelected={(artifact: IExpectedArtifact) =>
                        this.onTemplateArtifactSelected(artifact.id, index + 1)
                      }
                      pipeline={this.props.pipeline}
                      selectedArtifactAccount={this.getInputArtifact(stage, index + 1).account}
                      selectedArtifactId={this.getInputArtifact(stage, index + 1).id}
                      setArtifactAccount={account => this.onTemplateArtifactAccountSelected(account, index + 1)}
                      setArtifactId={id => this.onTemplateArtifactSelected(id, index + 1)}
                      stage={stage}
                      updatePipeline={this.props.updatePipeline}
                    />

                      <button onClick={() => this.removeInputArtifact(index + 1)}>

                        Remove field
                      </button>

              );
            })}

        )}
        <StageConfigField fieldColumns={8} label={''}>
          <button className="btn btn-block btn-sm add-new" onClick={() => this.addInputArtifact()}>

            Add value artifact
          </button>
        </StageConfigField>
        <StageConfigField fieldColumns={6} label="Overrides">
          {stage.overrides && (
            <MapEditor
              addButtonLabel={'Add override'}
              model={stage.overrides}
              allowEmpty={true}
              onChange={(o: any) => this.overrideChanged(o)}
            />
          )}
        </StageConfigField>
        <StageConfigField
          fieldColumns={6}
          helpKey={'pipeline.config.bake.manifest.helm.rawOverrides'}
          label="Raw Overrides"
        >
          <CheckboxInput
            value={stage.rawOverrides}
            text={''}
            onChange={() => this.props.formik.setFieldValue('rawOverrides', !stage.rawOverrides)}
          />
        </StageConfigField>
        <StageConfigField
          fieldColumns={6}
          helpKey={'pipeline.config.bake.manifest.overrideExpressionEvaluation'}
          label="Expression Evaluation"
        >
          <CheckboxInput
            value={stage.evaluateOverrideExpressions}
            text={'Evaluate SpEL expressions in overrides at bake time'}
            onChange={() =>
              this.props.formik.setFieldValue('evaluateOverrideExpressions', !stage.evaluateOverrideExpressions)
            }
          />
        </StageConfigField>
      </>
    );
  }
}


text:
'use strict'

/*=======================================
=              Action types             =
=======================================*/
/**
 * @todo Define action types for this area
 *
 * [Action name] action type
 * @constant
 * @type {[type]}
 */
export const ACTION_NAME = 'ACTION_NAME'

/*=====  End of Action types  ======*/

/*=======================================
=            Action creators            =
=======================================*/

/** @module <%= areaName %>/actions */

/**
 * @todo Implement action creators for this area
 *
 * [Action name] action creator
 * @param {[type]} payload [description]
 * @return {@link ACTION_NAME} action object
 */
export function actionName (payload) {
    return {
        type: ACTION_NAME,
        payload
    }
}

/*=====  End of Action creators  ======*/


text:
import { toHiragana } from 'wanakana';

const WHITELIST = ['tin can', 'kimono'];

/**
 * Removes meanings that are romaji versions of valid answers
 * If no meanings left, returns original meanings
 * @param  {Array} [meanings=[]] review meanings
 * @param  {Array} [readings=[]] review readings
 * @return {Array} filtered meanings
 * @example
 * filterRomajiReadings(['Southern Barbarians, Nanban'], ['なんばん'])
 * // => ['Southern Barbarians']
 */
const filterRomajiReadings = (meanings = [], readings = []) => {
  if (WHITELIST.some((word) => meanings.includes(word))) {
    return meanings;
  }

  // TODO: filter out meanings that are modified versions of long o
  // IE: jomon / joumon, tohoku / touhoku

  const filteredMeanings = meanings.filter(
    (meaning) => !readings.some((reading) => RegExp(`^${reading}`, 'i').test(toHiragana(meaning)))
  );
  return filteredMeanings.length ? filteredMeanings : meanings;
};

export default filterRomajiReadings;


text:
module MHMC.Display.Playlist
(
    playlist
) where

import Data.Default
import Data.Foldable (toList)
import Data.Maybe
import qualified Data.Sequence as S
import Graphics.Vty
import MHMC.MPD
import qualified Network.MPD as MPD

playlist :: (Int, Int) -> Playlist -> MPD.Response MPD.Status -> Int -> Int -> Image
playlist (width, height) hash status cursor songpos =
    let cursorString = (take cursor $ repeat "") ++ ["->"] ++ (take height $ repeat "")
        cursorImg = vertCat $ map (string (def `withForeColor` white)) cursorString
        artists = map (lookup MPD.Artist) hash
        artistsString = S.fromList $ map (fromMaybe [] . fmap (MPD.toString . (!! 0))) artists
        artistsImg = vertCat . toList $ S.mapWithIndex
            (\line str -> string (test line (def `withForeColor` white)) str) formatStr
            where formatStr = if S.null artistsString then S.singleton "Empty Playlist" else artistsString
        titles = map (lookup MPD.Title) hash
        titlesString = S.fromList $ map (fromMaybe [] . fmap (MPD.toString . (!! 0))) titles
        titlesImg = vertCat . toList $ S.mapWithIndex
            (\line str -> string (test line (def `withForeColor` white)) str) formatStr
            where formatStr = if S.null artistsString then S.singleton "Empty Playlist" else titlesString
        albums = map (lookup MPD.Album) hash
        albumsString = S.fromList $ map (fromMaybe [] . fmap (MPD.toString . (!! 0))) albums
        albumsImg = vertCat . toList $ S.mapWithIndex
            (\line str -> string (test line (def `withForeColor` white)) str) formatStr
            where formatStr = if S.null artistsString then S.singleton "Empty Playlist" else albumsString
    in cropBottom (height - 4)
        $ pad 0 0 0 height (cursorImg
            <|> (sizeof 0.25 artistsImg)
            <|> (string def " ")
            <|> (sizeof 0.5 titlesImg)
            <|> (string def " ")
            <|> (sizeof 0.25 albumsImg))
    where sizeof frac image = cropRight (fromEnum (fromIntegral width * frac)) $ pad 0 0 (fromEnum (fromIntegral width * frac)) 0 image
          test line = if line == songpos then \attr -> withStyle attr bold else id

reverseColors :: Attr -> Attr
reverseColors attr = attr { attrBackColor = attrForeColor attr,
                            attrForeColor = attrBackColor attr}


text:
#ifndef ECMA_STRING_OBJECT_H
#define ECMA_STRING_OBJECT_H

#include "ecma-globals.h"

/** \addtogroup ecma ECMA
 * @{
 *
 * \addtogroup ecmastringobject ECMA String object related routines
 * @{
 */

ecma_value_t
ecma_op_create_string_object (const ecma_value_t *arguments_list_p, ecma_length_t arguments_list_len);

void
ecma_op_string_list_lazy_property_names (ecma_object_t *obj_p,
                                         bool separate_enumerable,
                                         ecma_collection_header_t *main_collection_p,
                                         ecma_collection_header_t *non_enum_collection_p);

/**
 * @}
 * @}
 */

#endif /* !ECMA_STRING_OBJECT_H */


text:
Lunatest is an xUnit-style, Lua-based unit testing framework with
additional support for randomized testing (a la QuickCheck).

It's largely upwardly compatible from [lunit][], with the following changes:

* Where lunit uses assert(), lunatest uses assert_true(). lunatest does
  not change any functions from the standard library.
* If running tests in only one file, no module declaration is necessary.
* For multiple suites, register them with lunatest.suite("file").
  This uses require the file suite to return a table containing the suite
  related functions as well as the test functions. (Note: non local tests
  functions found outside the returned table go to the main suite.)
* It doesn't have any dependencies except Lua, though if present, it
  will use lhf's [lrandom][] module (for consistent pseudorandom numbers
  across operating systems) and [luasocket][]'s gettime() for timestamps).

The main (or only) test file should end in lunatest.run(), and can be
run as a normal lua script. The following command-line arguments are
supported:

* -v: verbose mode, which lists every test's name, result, and runtime.
* -s / --suite *pattern*: Only run suite(s) with names matching the pattern.
* -t / --test *pattern*: Only run test(s) with names matching the pattern.

[lunit]: http://www.nessie.de/mroth/lunit/
[lrandom]: http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/#lrandom
[luasocket]: http://luaforge.net/projects/luasocket/

For further examples, see the API documentation and included test suite.


text:
<?php
declare(strict_types=1);

class Engineer extends SpecialisedSoldier implements IEngineer
{
    private $partsArr = [];
    public function __construct($firstName, $lastName, $id, float $salary, string $corps, array $parts)
    {
        parent::__construct($firstName, $lastName, $id, $salary, $corps);
        $this->setParts($parts);
    }
    private function setParts(array $parts)
    {
        $count = count($parts);
        for ($i = 0; $i < $count; $i += 2) {
            $this->partsArr[$parts[$i]] = $parts[$i + 1];
        }
    }
    public function getRepairs()
    {
        $partString = null;
        foreach ($this->partsArr as $key => $value) {
            $partString .= '  Part Name: ' . $key . ' Hours Worked: ' . $value . PHP_EOL;
        }
        return $partString;
    }
    public function __toString()
    {
        return parent::__toString() . 'Repairs:' . PHP_EOL . $this->getRepairs();
    }
}


text:
=============================
dj-stripe
=============================

.. image:: https://badge.fury.io/py/dj-stripe.png
    :target: http://badge.fury.io/py/dj-stripe

.. image:: https://travis-ci.org/pydanny/dj-stripe.png?branch=master
        :target: https://travis-ci.org/pydanny/dj-stripe

.. image:: https://pypip.in/d/dj-stripe/badge.png
        :target: https://pypi.python.org/pypi/dj-stripe/

Django + Stripe Made Easy

Documentation
-------------

The full documentation is at http://dj-stripe.rtfd.org.

Features
--------

* Subscription management
* Designed for easy implementation of post-registration subscription forms
* Single-unit purchases (forthcoming)
* Works with Django 1.6, 1.5, 1.4
* Works with Python 3.3, 2.7, 2.6
* Works with Bootstrap 3
* Built-in South migrations
* Dead-Easy installation
* Leverages in the best of the 3rd party Django package ecosystem
* `djstripe` namespace so you can have more than one payments related app
* Documented (Making good progress)
* Tested (Making good progress)

Constraints
------------

1. For stripe.com only
2. Only use or support well-maintained third-party libraries
3. For modern Python and Django

Quickstart
----------

Install dj-stripe:

.. code-block:: bash

    pip install dj-stripe

Add ``djstripe`` to your ``INSTALLED_APPS``:

.. code-block:: python

    INSTALLED_APPS +=(
        "djstripe",
    )

Add the context processor to your ``TEMPLATE_CONTEXT_PROCESSORS``:

.. code-block:: python

    TEMPLATE_CONTEXT_PROCESSORS +=(
        'djstripe.context_processors.djstripe_settings',
    )

Add your stripe keys:

.. code-block:: python

    STRIPE_PUBLIC_KEY = os.environ.get("STRIPE_PUBLIC_KEY", "<your publishable test key>")
    STRIPE_SECRET_KEY = os.environ.get("STRIPE_SECRET_KEY", "<your secret test key>")

Add some payment plans:

.. code-block:: python

    DJSTRIPE_PLANS = {
        "monthly": {
            "stripe_plan_id": "pro-monthly",
            "name": "Web App Pro ($24.99/month)",
            "description": "The monthly subscription plan to WebApp",
            "price": 2499,  # $24.99
            "currency": "usd",
            "interval": "month"
        },
        "yearly": {
            "stripe_plan_id": "pro-yearly",
            "name": "Web App Pro ($199/year)",
            "description": "The annual subscription plan to WebApp",
            "price": 19900,  # $199.00
            "currency": "usd",
            "interval": "year"
        }
    }

Add to the urls.py:

.. code-block:: python

    url(r'^payments/', include('djstripe.urls', namespace="djstripe")),

Run the commands::

    python manage.py syncdb

    python manage.py migrate  # if you are using South

    python manage.py djstripe_init_customers

    python manage.py djstripe_init_plans

If you haven't already, add JQuery and the Bootstrap 3.0.0 JS and CSS to your base template:

.. code-block:: html

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">

    <!-- Optional theme -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css">

    <!-- Latest JQuery -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

    <!-- Latest compiled and minified JavaScript -->
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>

Also, if you don't have it already, add a javascript block to your base.html file:

.. code-block:: html

    {% block javascript %}{% endblock %}

Start up the webserver:

    * http://127.0.0.1:8000/payments/

Running the Tests
------------------

Assuming the tests are run against PostgreSQL::

    createdb djstripe
    pip install -r requirements_test.txt
    coverage run --source djstripe runtests.py
    coverage report -m

Follows Best Practices
======================

.. image:: http://twoscoops.smugmug.com/Two-Scoops-Press-Media-Kit/i-C8s5jkn/0/O/favicon-152.png
   :name: Two Scoops Logo
   :align: center
   :alt: Two Scoops of Django
   :target: http://twoscoopspress.org/products/two-scoops-of-django-1-6

This project follows best practices as espoused in `Two Scoops of Django: Best Practices for Django 1.6`_.

.. _`Two Scoops of Django: Best Practices for Django 1.6`: http://twoscoopspress.org/products/two-scoops-of-django-1-6

Similar Projects
----------------

* https://github.com/eldarion/django-stripe-payments - The project that dj-stripe forked. It's an awesome project and worth checking out.
* https://github.com/agiliq/merchant - A single charge payment processing system that also includes many other Gateways. Really nice but doesn't out-of-the-box handle the use case of subscription payments.
* https://github.com/GoodCloud/django-zebra - One of the first stripe payment systems for Django.


text:
<!DOCTYPE html>

    <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<meta name="keyword" content="">

    <link rel="shortcut icon" href="/node-mongodb-native/3.2/img/favicon.png">

    <title>Authentication</title>

    <link rel="stylesheet" href="/node-mongodb-native/3.2/lib/bootstrap.css" type="text/css" />
<link rel="stylesheet" href="/node-mongodb-native/3.2/lib/font-awesome/css/font-awesome.min.css" type="text/css" />
<link rel="stylesheet" href="/node-mongodb-native/3.2/css/mongodb-docs.css" type="text/css" />
<link rel="stylesheet" href="/node-mongodb-native/3.2/css/overrides.css" type="text/css" />
<link rel="stylesheet" href="/node-mongodb-native/3.2/lib/highlight/styles/idea.css" />
<link rel="stylesheet" href="/node-mongodb-native/3.2/lib/bootstrap-toggle/bootstrap-toggle.min.css" type="text/css" />
<link rel="stylesheet" href="/node-mongodb-native/3.2/css/java.css" type="text/css" />

  MongoDB University
  Downloads
  Community
  Docs
  Blog

<form method="get" action="//www.google.com/search" target="_blank">
    <input type="text" name="searchQuery" size="20" value="" autocomplete="off" placeholder="Search docs">
    <input type="hidden" name="site" value="/node-mongodb-native/3.2">
    <input type="hidden" name="q" value="">

</form>

          MongoDB Node.js Driver
          3.2

        Installation Guide

        Quick Start

      Tutorials

      Connect to MongoDB

        Authentication

        SSL Settings

        Collations

        Collections

        Create Indexes

        CRUD Operations

        Projections

        Aggregation

        Text Search

        Geospatial Search

        Database Commands

      GridFS

        GridFS API

        Legacy GridStore

      Reference

      Connection Options

        Connection Settings

      ECMAScript Next

        Connecting

        CRUD Operations

      Management

        Logging

        APM

        Topology Monitoring

        Pool Design

        Frequently Asked Questions

      Upgrade Guide

        Upgrading to 2.x

        API Documentation

        Source Code

        Issues & Help

  OPTIONS

        Version

          <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
            Select Version
          </button>

  Note: You are currently viewing version 3.2 of the Node.js driver documentation.
  Click here for the latest version.

Tutorials

Connect to MongoDB

Authentication

Authentication

The Node.js driver supports all MongoDB authentication mechanisms, including those only available in the MongoDB Enterprise Edition.

DEFAULT

Note

Starting in MongoDB 3.0, MongoDB changed the default authentication mechanism from MONGODB-CR to SCRAM-SHA-1.

To use the default mechanism, either omit the authentication mechanism specification or specify DEFAULT as the mechanism in the URI ConnectionString. The driver will attempt to authenticate using the SCRAM-SHA-1 authentication method if it is available on the MongoDB server. If the server does not support SCRAM-SHA-1, the driver will authenticate using MONGODB-CR.

Include the name and password and the authentication database (authSource) in the connection string.

In the following example, the connection string specifies the user dave, password abc123, and authentication mechanism DEFAULT.

important

The user and password should always be URI encoded using encodeURIComponent to ensure any non URI compliant user or password characters are correctly parsed.

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

const user = encodeURIComponent('dave');
const password = encodeURIComponent('abc123');
const authMechanism = 'DEFAULT';

// Connection URL
const url = `mongodb://${user}:${password}@localhost:27017/?authMechanism=${authMechanism}`;

// Create a new MongoClient
const client = new MongoClient(url);

// Use connect method to connect to the Server
client.connect(function(err) {
  assert.equal(null, err);
  console.log("Connected correctly to server");

  client.close();
});

SCRAM-SHA-1

To explicitly connect to MongoDB using SCRAM-SHA-1, specify SCRAM-SHA-1 as the mechanism in the URI connection string.

Include the name and password and the authentication database (authSource) in the connection string.

In the following example, the connection string specifies the user dave, password abc123, authentication mechanism SCRAM-SHA-1, and authentication database myprojectdb

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://dave:abc123@localhost:27017/?authMechanism=SCRAM-SHA-1&authSource=myprojectdb';

// Create a new MongoClient
const client = new MongoClient(url);

// Use connect method to connect to the Server
client.connect(function(err) {
  assert.equal(null, err);
  console.log("Connected correctly to server");

  client.close();
});

MONGODB-CR

Note

MONGODB-CR was deprecated starting in MongoDB 3.6, and is no longer supported as of MongoDB 4.0

To explicitly connect to MongoDB using MONGODB-CR, specify MONGODB-CR as the mechanism in the URI connection string.

Include the name and password and the authentication database (authSource) in the connection string.

In the following example, the connection string specifies the user dave, password abc123, authentication mechanism MONGODB-CR, and authentication database myprojectdb.

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://dave:abc123@localhost:27017/?authMechanism=MONGODB-CR&authSource=myprojectdb';

// Create a new MongoClient
const client = new MongoClient(url);

// Use connect method to connect to the Server
client.connect(function(err) {
  assert.equal(null, err);
  console.log("Connected correctly to server");

  client.close();
});

important

If you have upgraded the authentication schema from MONGODB-CR to SCRAM-SHA-1, MONGODB-CR credentials will fail to authenticate.

X509

With  X.509 mechanism, MongoDB uses the X.509 certificate presented during SSL negotiation to authenticate a user whose name is derived from the distinguished name of the X.509 certificate.

X.509 authentication requires the use of SSL connections with certificate validation and is available in MongoDB 2.6 and newer.

To connect using the X.509 authentication mechanism, specify MONGODB-X509 as the mechanism in the URI connection string, ssl=true, and the username. Use enodeURIComponent to encode the username string.

In addition to the connection string, pass to the new MongoClient a connections options for the server with  the X.509 certificate and other TLS/SSL connections options.

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Read the cert and key
const cert = fs.readFileSync(__dirname + "/ssl/x509/client.pem");
const key = fs.readFileSync(__dirname + "/ssl/x509/client.pem");

// User name
const userName = encodeURIComponent("CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US");
const url = `mongodb://${userName}:${password}@server:27017?authMechanism=MONGODB-X509&ssl=true`;

// Create a new MongoClient
const client = new MongoClient(url, {
  sslKey: key,
  sslCert: cert,
  sslValidate: false
});

// Use connect method to connect to the Server
client.connect(function(err) {
  assert.equal(null, err);
  console.log("Connected correctly to server");

  client.close();
});

For more information on connecting to MongoDB instance, replica set, and sharded cluster with TLS/SSL options, see TLS/SSL connections options.

For more information, refer to the MongoDB manual
X.509 tutorial for more information about determining the subject name from the certificate.

Kerberos (GSSAPI/SSPI)

MongoDB Enterprise supports proxy authentication through a Kerberos service. The Node.js driver supports Kerberos on UNIX via the MIT Kerberos library and on Windows via the SSPI API.

To connect using the GSSAPI authentication mechanism, specify authMechanism=GSSAPI as the mechanism in the URI connection string. Specify the user principal and the service name in the connection string.  Use enodeURIComponent to encode the user principal string.

The following example connects to MongoDB using Kerberos for UNIX.

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// KDC Server
const server = "mongo-server.example.com";
const principal = "drivers@KERBEROS.EXAMPLE.COM";
const urlEncodedPrincipal = encodeURIComponent(principal);

const url = `mongodb://${urlEncodedPrincipal}@${server}/?authMechanism=GSSAPI&gssapiServiceName=mongodb`;

const client = new MongoClient(url);

// Let's write the actual connection code
client.connect(function(err) {
  assert.equal(null, err);

  client.close();
});

Note

The method refers to the GSSAPI authentication mechanism instead of Kerberos because technically the driver authenticates via the GSSAPI SASL mechanism.

LDAP (PLAIN)

MongoDB Enterprise supports proxy authentication through a Lightweight Directory Access Protocol (LDAP) service.

To connect using the LDAP authentication mechanism, specify authMechanism=PLAIN as the mechanism in the URI connection string.

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// LDAP Server
const server = "ldap.example.com";
const user = "ldap-user";
const pass = "ldap-password";

// Url
const url = `mongodb://${user}:${pass}@${server}?authMechanism=PLAIN&maxPoolSize=1`;

// Client
const client = new MongoClient(url);

// Let's write the actual connection code
client.connect(function(err) {
  assert.equal(null, err);

  client.close();
});

Note

The method refers to the PLAIN authentication mechanism instead of LDAP because technically the driver authenticates via the PLAIN SASL mechanism.

    SSL Settings

    On this page

Authentication

DEFAULT

SCRAM-SHA-1

MONGODB-CR

X509

Kerberos (GSSAPI/SSPI)

LDAP (PLAIN)


text:
package chapter8;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Base64;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import static java.util.Collections.checkedQueue;

public class Exercise {
	public static long add(int a, int b) {
		return Integer.toUnsignedLong(a) + Integer.toUnsignedLong(b);
	}

	public static long substract(int a, int b) {
		return Integer.toUnsignedLong(a) - Integer.toUnsignedLong(b);
	}

	public static long multiply(int a, int b) {
		return Integer.toUnsignedLong(a) * Integer.toUnsignedLong(b);
	}

	public static long divide(int a, int b) {
		return Long.divideUnsigned(Integer.toUnsignedLong(a), Integer.toUnsignedLong(b));
	}

	public static int compare(int a, int b) {
		return Long.compareUnsigned(Integer.toUnsignedLong(a), Integer.toUnsignedLong(b));
	}

	public static int countShortWords(List<String> words) {
		words.removeIf(w -> w.length() >= 12);
		return words.size();
	}

	public static <T extends Comparable<? super T>> Comparator<T> getReversedNaturalOrderComparator() {
		return Comparator.nullsLast(Comparator.reverseOrder());
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void showBenefitOfCheckedQueue() {
		Queue queue = checkedQueue(new LinkedList<Path>(), Path.class);
		queue.add(new File("a.txt").toPath());
		queue.add(new File("b.txt").toPath());
		// runtime error
		queue.add("c.txt");
	}

	public static Stream<String> turnScannerIntoStreamOfWords(final Scanner scanner) {
        Iterator<String> iter = new Iterator<String>() {
            String nextLine = null;

            @Override
            public boolean hasNext() {
                if (nextLine != null) {
                    return true;
                } else {
                    try {
                        nextLine = scanner.nextLine();
                        return true;
                    } catch (NoSuchElementException e) {
                    	nextLine = null;
                    	return false;
                    }
                }
            }

            @Override
            public String next() {
                if (nextLine != null || hasNext()) {
                    String line = nextLine;
                    nextLine = null;
                    return line;
                } else {
                    throw new NoSuchElementException();
                }
            }
        };
        return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
                iter, Spliterator.ORDERED | Spliterator.NONNULL), false);
	}

	public static Stream<Path> findTransientAndVolatile(Path root) throws IOException {
		return Files.walk(root, FileVisitOption.FOLLOW_LINKS).filter(path -> {
			try {
				return Files.lines(path).anyMatch(line -> { return line.indexOf("volatile") >= 0 || line.indexOf("transient") >= 0; });
			}
			catch (IOException e) {
				return false;
			}
		});
	}

	public static String[] getContent(URL url, String user, String password) throws IOException {
		String encoded = Base64.getEncoder().encodeToString(String.format("%s:%s", user, password).getBytes(StandardCharsets.UTF_8));
		URLConnection connection = url.openConnection();
		connection.connect();
		connection.setRequestProperty("Authorization", "Basic " + encoded);
		try (
			InputStream stream = connection.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
		) {
			return reader.lines().toArray(String[]::new);
		}
	}

	public static void main(String... args) {
		showBenefitOfCheckedQueue();
	}
}

interface Point {
	public int x();
	public int y();

	public static final Comparator<Point> COMPARATOR =
			Comparator.comparing(Point::x).thenComparing(Point::y);
}

interface Rectangle {
	public Point ul();
	public Point ur();
	public Point ll();
	public Point lr();

	public static final Comparator<Rectangle> COMPARATOR =
			Comparator
			.comparing(Rectangle::ul, Point.COMPARATOR)
			.thenComparing(Rectangle::ur, Point.COMPARATOR)
			.thenComparing(Rectangle::ll, Point.COMPARATOR)
			.thenComparing(Rectangle::lr, Point.COMPARATOR);
}