text:
//
//  JXSMTP.m
//  JXMail
//
//  Created by andy on 9/8/14.
//  Copyright (c) 2014 JianXiang Jin. All rights reserved.
//

#import "JXSMTP.h"

@implementation JXSMTP

- (id)init
{
    if (self = [super init]) {

        _session = [[MCOSMTPSession alloc] init];
        _session.hostname = SMTP_HOSTNAME;
        _session.port = SMTP_PORT;
        _session.connectionType = MCOConnectionTypeTLS;

        JXAccount *account = [JXAccountManager shareManager].currentAccount;
        _session.username = account.username;
        _session.password = account.password;
    }
    return self;
}

/**
 *  验证用户信息
 */
- (void)checkAccount:(JXCheckAccountBlock)checkAccountBlock
{

}

/**
 *  接收邮件
 */
- (void)receive:(JXReceiveBlock)receiveBlock
{

}

/**
 *  发送邮件
 */
- (void)sendMail:(JXMailPacket *)packet compelete:(JXSendBlock)sendBlock
{
    JXAccount *acount = [[JXAccountManager shareManager] currentAccount];

    // 发信人信息
    MCOAddress *from = [MCOAddress addressWithDisplayName:acount.nickname
                                                  mailbox:acount.username];
    // 收信人信息
    MCOAddress *to = [MCOAddress addressWithDisplayName:packet.displayName
                                                mailbox:packet.mailBox];
    // 发送内容
    MCOMessageBuilder *builder = [[MCOMessageBuilder alloc] init];
    [[builder header] setFrom:from];
    [[builder header] setTo:@[to]];
    [[builder header] setSubject:packet.subject];
    [builder setHTMLBody:packet.body];
    NSData * data = [builder data];

    // 发送任务
    MCOSMTPSendOperation *sendOperation =
    [_session sendOperationWithData:data];

    // 发送结果
    [sendOperation start:^(NSError *error) {

        if (error) {
            sendBlock(error);
            return ;
        }

        sendBlock(nil);
    }];
}

@end


text:
<?php

namespace Jasny\DB\Mongo\Document;

use Jasny\Meta;
use Jasny\DB\Data;
use Jasny\DB\Entity;
use Jasny\DB\Entity\LazyLoading;
use Jasny\DB\EntitySet;
use Jasny\DB\FieldMapping;
use Jasny\DB\Mongo\Dataset;
use Jasny\DB\Dataset\Sorted;
use Jasny\DB\Entity\ChangeAware;
use function Jasny\DB\Mongo\get_object_public_properties;

/**
 * Static methods to interact with a collection (as document)
 *
 * @author  Arnold Daniels <arnold@jasny.net>
 * @license https://raw.github.com/jasny/db-mongo/master/LICENSE MIT
 * @link    https://jasny.github.io/db-mongo
 */
trait BasicImplementation
{
    use Entity\Implementation,
        FieldMapping\Implementation,
        Dataset\Implementation
    {
        Entity\Implementation::fromData as private _entity_fromData;
    }

    /**
     * Get the field map.
     *
     * @return array
     */
    protected static function getFieldMap()
    {
        return ['_id' => static::getIdProperty()];
    }

    /**
     * Get the property used to identify the document
     *
     * @return string
     */
    public static function getIdProperty()
    {
        return 'id';
    }

    /**
     * Get document id.
     *
     * @return string
     */
    public function getId()
    {
        $prop = static::getIdProperty();
        return $this->$prop;
    }

    /**
     * Get the data that needs to be saved in the DB
     *
     * @return array
     */
    public function toData()
    {
        $values = get_object_public_properties($this);

        foreach ($values as &$item) {
            if ($item instanceof Entity\Identifiable) {
                $item = $this->childEntityToId($item);
            } elseif ($item instanceof EntitySet && is_a($item->getEntityClass(), Entity\Identifiable::class, true)) {
                $ids = [];
                foreach ($item as $child) {
                    $ids[] = $this->childEntityToId($child);
                }
                $item = $ids;
            } elseif ($item instanceof Data) {
                $item = $item->toData();
            }
        }

        if ($this instanceof Sorted && method_exists($this, 'prepareDataForSort')) {
            $values += $this->prepareDataForSort();
        }

        $casted = static::castForDB($values);
        $data = static::mapToFields($casted);

        if (array_key_exists('_id', $data) && is_null($data['_id'])) {
            unset($data['_id']);
        }

        return $data;
    }

    /**
     * Convert child to an id
     *
     * @param Entity $item
     * @return \MongoDB\BSON\ObjectId|mixed
     */
    protected function childEntityToId(Entity $item)
    {
        if (
            $item instanceof Meta\Introspection &&
            is_scalar($item::getIdProperty()) &&
            $item::meta()->ofProperty($item::getIdProperty())['dbFieldType'] === '\\MongoDB\\BSON\\ObjectId'
        ) {
            $id = new \MongoDB\BSON\ObjectId($item->getId());
        } else {
            $id = $item->getId();
        }

        return $id;
    }

    /**
     * Save the document
     *
     * @param array $opts
     * @return $this
     */
    public function save(array $opts = [])
    {
        if ($this instanceof Entity\LazyLoading && $this->isGhost()) {
            $msg = "This " . get_called_class() . " entity isn't fully loaded. First expand, than edit, than save.";
            throw new \Exception("Unable to save: $msg");
        }

        $data = $this->toData();
        $collection = static::getCollection();

        if ($this instanceof ChangeAware && $this->isNew()) {
            $result = $collection->insertOne($data, $opts);
        } else {
            $result = $collection->save($data, $opts);
        }

        $idName = static::getIdProperty();
        $collection->useResultId($this, $idName, $result);

        $this->cast();

        return $this;
    }

    /**
     * Delete the document
     *
     * @param array $opts
     * @return $this
     */
    public function delete(array $opts = [])
    {
        $properties = [static::getIdProperty() => $this->getId()];
        $filter = static::castForDB($properties);
        $query = static::mapToFields($filter);

        static::getCollection()->deleteOne($query, $opts);
        return $this;
    }

    /**
     * Reload the entity from the DB
     *
     * @param array $opts
     * @return $this|false
     */
    public function reload(array $opts = [])
    {
        $entity = static::fetch($this, $opts);
        if (!$entity) {
            return false;
        }

        foreach ((array)$entity as $prop => $value) {
            // Ignore private and protected properties
            if ($prop[0] !== "\0") {
                $this->$prop = $value;
            }
        }

        return $this;
    }

    /**
     * Check no other document with the same value of the property exists
     *
     * @param string        $property
     * @param array|string  $group     List of properties that should match
     * @param array         $opts
     * @return boolean
     */
    public function hasUnique($property, $group = null, array $opts = [])
    {
        if (!isset($this->$property)) {
            return true;
        }

        $filter = [static::getIdProperty() . '(not)' => $this->getId(), $property => $this->$property];
        foreach ((array)$group as $prop) {
            if (isset($this->$prop)) $filter[$prop] = $this->$prop;
        }

        return !static::exists($filter, $opts);
    }

    /**
     * Prepare result when casting object to JSON
     *
     * @return object
     */
    public function jsonSerialize()
    {
        if ($this instanceof LazyLoading) {
            $this->expand();
        }

        $values = $this->getValues();

        foreach ($values as &$value) {
            if ($value instanceof \DateTime) {
                $value = $value->format(\DateTime::ISO8601);
            } elseif ($value instanceof \MongoDB\BSON\ObjectId) {
                $value = (string)$value;
            }
        }

        return $this->jsonSerializeFilter((object)$values);
    }

    /**
     * Convert loaded values to an entity
     *
     * @param array|object $values
     * @return static
     */
    public static function fromData($values)
    {
        if (is_object($values)) {
            $values = (array)$values;
        }

        $mapped = static::mapFromFields($values);
        return static::_entity_fromData($mapped);
    }
}

redpajama_set_name: RedPajamaGithub


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_83.h
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE129.label.xml
Template File: sources-sinks-83.tmpl.h
*/
/*
 * @description
 * CWE: 122 Heap Based Buffer Overflow
 * BadSource: fgets Read data from the console using fgets()
 * GoodSource: Larger than zero but less than 10
 * Sinks:
 *    GoodSink: Ensure the array index is valid
 *    BadSink : Improperly check the array index by not checking the upper bound
 * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
 *
 * */

#include "std_testcase.h"

namespace CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_83
{

#ifndef OMITBAD

class CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_83_bad
{
public:
    CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_83_bad(int dataCopy);
    ~CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_83_bad();

private:
    int data;
};

#endif /* OMITBAD */

#ifndef OMITGOOD

class CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_83_goodG2B
{
public:
    CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_83_goodG2B(int dataCopy);
    ~CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_83_goodG2B();

private:
    int data;
};

class CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_83_goodB2G
{
public:
    CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_83_goodB2G(int dataCopy);
    ~CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_83_goodB2G();

private:
    int data;
};

#endif /* OMITGOOD */

}


text:
onepoint.js

Onepoint.js is a simple library written in JavaScript that organizes scripts with ease. It's perfect for beginners and even for professionals.

Plugin example: Drawing

	Download picture

	<canvas id="testCanvas" width="500" height="300"></canvas>

Debug console:

console ready

Plugin example: Noparse

	<noparse>this is surrounded in  noparse tags</noparse>


text:
'use strict'
const Dicebag = require('smecky-dicebag')

module.exports = () => {
  let roll

  roll = (roll_log) => {
    let table_roll

    table_roll = Dicebag.roll(100, 1, { verbose: true })
    roll_log.push({ dice: '1d100', rolls: table_roll.roll_log })

    if (table_roll.sum < 21) {
      return 'magicitems?name=Potion of Supreme Healing'
    } else if (table_roll.sum < 31) {
      return 'magicitems?name=Potion of Invisibility'
    } else if (table_roll.sum < 41) {
      return 'magicitems?name=Potion of Speed'
    } else if (table_roll.sum < 51) {
      return 'magicitems?name=Spell Scroll&modifier=6'
    } else if (table_roll.sum < 58) {
      return 'magicitems?name=Spell Scroll&modifier=7'
    } else if (table_roll.sum < 63) {
      return 'magicitems?name=Ammunition&modifier=3'
    } else if (table_roll.sum < 68) {
      return 'magicitems?name=Oil of Sharpness'
    } else if (table_roll.sum < 73) {
      return 'magicitems?name=Potion of Flying'
    } else if (table_roll.sum < 78) {
      return 'magicitems?name=Potion of Cloud Giant Strength'
    } else if (table_roll.sum < 83) {
      return 'magicitems?name=Potion of Longevity'
    } else if (table_roll.sum < 88) {
      return 'magicitems?name=Potion of Vitality'
    } else if (table_roll.sum < 93) {
      return 'magicitems?name=Spell Scroll&modifier=8'
    } else if (table_roll.sum < 96) {
      return 'magicitems?name=Horseshoes of a Zephyr'
    } else if (table_roll.sum < 99) {
      return "magicitems?name=Nolzur's Marvelous Pigments"
    } else if (table_roll.sum < 100) {
      return 'magicitems?name=Bag of Devouring'
    } else if (table_roll.sum < 101) {
      return 'magicitems?name=Portable Hole'
    } else {
      // TODO: Handle this error
    }
  }

  return {
    roll: roll
  }
}


text:
/*!
 * Module dependencies
 */

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

/**
 * User schema
 */

var PinSchema = new Schema({
  id: { type: String, default: '' },
  url: { type: String, default: '' },
  note: { type: String, default: '' },
  created_at: {type: Number},
  creator: {
    firstName: { type: String, default: '' },
    lastName: { type: String, default: '' }
  }
});

/**
 * Add your
 * - pre-save hooks
 * - validations
 * - virtuals
 */

/**
 * Methods
 */

PinSchema.method({
  getJSONFormattedSession: function() {
    var createdAt = new Date(this.created_at);
    var formattedPin = {
      type: "pin",
      id: this.id,
      attributes: {
        "description": this.note,
        "pinLink": this.url,
        "imageLink": this.imageLink,
        "created_at": this.created_at
      }
    };
    return formattedPin;
  }
});

/**
 * Statics
 */

PinSchema.static({
  list: function(options, cb) {
    var criteria = options || {}
    this.find(criteria)
      .sort({'createdAt': -1})
      .limit(100)
      .exec(cb);
  },
  findSession: function(id, cb) {
    this.findOne({_id: id}).exec(cb);
  }
});

/**
 * Register
 */

mongoose.model('Pin', PinSchema);


text:
class ArduinoDevice : public ArduinoObject {
};

#endif //ARDUINOEXAMPLE_ARDUINODEVICE_H


text:
"""
Tests for :module:`flocker.filesystems.memory`.
"""

from __future__ import absolute_import

from twisted.internet.defer import succeed, fail
from twisted.trial.unittest import SynchronousTestCase
from twisted.python.filepath import FilePath

from .filesystemtests import (
    make_ifilesystemsnapshots_tests, make_istoragepool_tests,
)
from ..filesystems.memory import (
    CannedFilesystemSnapshots, FilesystemStoragePool,
    DirectoryFilesystem,
)
from ...testtools import (
    assert_equal_comparison, assert_not_equal_comparison
)

class IFilesystemSnapshotsTests(make_ifilesystemsnapshots_tests(
    lambda test_case: CannedFilesystemSnapshots(
        [succeed(None), succeed(None)]))):
    """``IFilesystemSnapshotsTests`` for in-memory filesystem."""

class CannedFilesystemSnapshotsTests(SynchronousTestCase):
    """
    Additional test cases for CannedFilesystemSnapshots.
    """
    def test_failed(self):
        """
        Failed snapshots are not added to the list of snapshots.
        """
        snapshotter = CannedFilesystemSnapshots([fail(RuntimeError())])
        self.failureResultOf(snapshotter.create(b"name"))
        self.assertEqual(self.successResultOf(snapshotter.list()), [])

    def test_too_many(self):
        """
        Creating more than the canned number of snapshots results in an error.

        This is useful for unit testing.
        """
        snapshotter = CannedFilesystemSnapshots([])
        self.assertRaises(IndexError, snapshotter.create, b"first")

class IStoragePoolTests(make_istoragepool_tests(
        lambda test_case:
        FilesystemStoragePool(FilePath(test_case.mktemp())),
        lambda fs: CannedFilesystemSnapshots([succeed(None), succeed(None)]))):
    """``IStoragePoolTests`` for fake storage pool."""

class DirectoryFilesystemTests(SynchronousTestCase):
    """
    Direct tests for ``FilesystemStoragePool``\ 's ``IFilesystem``
    implementation, ``DirectoryFilesystem``.
    """
    def test_equality(self):
        """
        Two ``DirectoryFilesystem`` instances are equal if they refer to the
        same directory.
        """
        path = FilePath(b"/foo/bar")
        assert_equal_comparison(
            self,
            DirectoryFilesystem(path=path, size=123),
            DirectoryFilesystem(path=path, size=321)
        )

    def test_inequality(self):
        """
        Two ``DirectoryFilesystem`` instances are not equal if they refer to
        different directories.
        """
        assert_not_equal_comparison(
            self,
            DirectoryFilesystem(path=FilePath(b"/foo/bar"), size=123),
            DirectoryFilesystem(path=FilePath(b"/foo/baz"), size=123)
        )

    def test_repr(self):
        """
        A ``DirectoryFilesystem`` instance represents itself as a string
        including the type name and the values of its attributes.
        """
        self.assertEqual(
            "<DirectoryFilesystem(path=FilePath('/foo/bar'), size=123)>",
            repr(DirectoryFilesystem(
                path=FilePath(b"/foo/bar"), size=123))
        )


text:
(function() {
  var YAMLError, events, nodes, util, _ref,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  events = require('./events');

  nodes = require('./nodes');

  util = require('./util');

  YAMLError = require('./errors').YAMLError;

  this.SerializerError = (function(_super) {
    __extends(SerializerError, _super);

    function SerializerError() {
      _ref = SerializerError.__super__.constructor.apply(this, arguments);
      return _ref;
    }

    return SerializerError;

  })(YAMLError);

  this.Serializer = (function() {
    function Serializer(_arg) {
      var _ref1;
      _ref1 = _arg != null ? _arg : {}, this.encoding = _ref1.encoding, this.explicit_start = _ref1.explicit_start, this.explicit_end = _ref1.explicit_end, this.version = _ref1.version, this.tags = _ref1.tags;
      this.serialized_nodes = {};
      this.anchors = {};
      this.last_anchor_id = 0;
      this.closed = null;
    }

    Serializer.prototype.open = function() {
      if (this.closed === null) {
        this.emit(new events.StreamStartEvent(this.encoding));
        return this.closed = false;
      } else if (this.closed) {
        throw new SerializerError('serializer is closed');
      } else {
        throw new SerializerError('serializer is already open');
      }
    };

    Serializer.prototype.close = function() {
      if (this.closed === null) {
        throw new SerializerError('serializer is not opened');
      } else if (!this.closed) {
        this.emit(new events.StreamEndEvent);
        return this.closed = true;
      }
    };

    Serializer.prototype.serialize = function(node) {
      if (this.closed === null) {
        throw new SerializerError('serializer is not opened');
      } else if (this.closed) {
        throw new SerializerError('serializer is closed');
      }
      if (node != null) {
        this.emit(new events.DocumentStartEvent(void 0, void 0, this.explicit_start, this.version, this.tags));
        this.anchor_node(node);
        this.serialize_node(node);
        this.emit(new events.DocumentEndEvent(void 0, void 0, this.explicit_end));
      }
      this.serialized_nodes = {};
      this.anchors = {};
      return this.last_anchor_id = 0;
    };

    Serializer.prototype.anchor_node = function(node) {
      var item, key, value, _base, _i, _j, _len, _len1, _name, _ref1, _ref2, _ref3, _results, _results1;
      if (node.unique_id in this.anchors) {
        return (_base = this.anchors)[_name = node.unique_id] != null ? (_base = this.anchors)[_name = node.unique_id] : _base[_name] = this.generate_anchor(node);
      } else {
        this.anchors[node.unique_id] = null;
        if (node instanceof nodes.SequenceNode) {
          _ref1 = node.value;
          _results = [];
          for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
            item = _ref1[_i];
            _results.push(this.anchor_node(item));
          }
          return _results;
        } else if (node instanceof nodes.MappingNode) {
          _ref2 = node.value;
          _results1 = [];
          for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
            _ref3 = _ref2[_j], key = _ref3[0], value = _ref3[1];
            this.anchor_node(key);
            _results1.push(this.anchor_node(value));
          }
          return _results1;
        }
      }
    };

    Serializer.prototype.generate_anchor = function(node) {
      return "id" + (util.pad_left(++this.last_anchor_id, '0', 4));
    };

    Serializer.prototype.serialize_node = function(node, parent, index) {
      var alias, default_tag, detected_tag, implicit, item, key, value, _i, _j, _len, _len1, _ref1, _ref2, _ref3;
      alias = this.anchors[node.unique_id];
      if (node.unique_id in this.serialized_nodes) {
        return this.emit(new events.AliasEvent(alias));
      } else {
        this.serialized_nodes[node.unique_id] = true;
        this.descend_resolver(parent, index);
        if (node instanceof nodes.ScalarNode) {
          detected_tag = this.resolve(nodes.ScalarNode, node.value, [true, false]);
          default_tag = this.resolve(nodes.ScalarNode, node.value, [false, true]);
          implicit = [node.tag === detected_tag, node.tag === default_tag];
          this.emit(new events.ScalarEvent(alias, node.tag, implicit, node.value, void 0, void 0, node.style));
        } else if (node instanceof nodes.SequenceNode) {
          implicit = node.tag === this.resolve(nodes.SequenceNode, node.value, true);
          this.emit(new events.SequenceStartEvent(alias, node.tag, implicit, void 0, void 0, node.flow_style));
          _ref1 = node.value;
          for (index = _i = 0, _len = _ref1.length; _i < _len; index = ++_i) {
            item = _ref1[index];
            this.serialize_node(item, node, index);
          }
          this.emit(new events.SequenceEndEvent);
        } else if (node instanceof nodes.MappingNode) {
          implicit = node.tag === this.resolve(nodes.MappingNode, node.value, true);
          this.emit(new events.MappingStartEvent(alias, node.tag, implicit, void 0, void 0, node.flow_style));
          _ref2 = node.value;
          for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
            _ref3 = _ref2[_j], key = _ref3[0], value = _ref3[1];
            this.serialize_node(key, node, null);
            this.serialize_node(value, node, key);
          }
          this.emit(new events.MappingEndEvent);
        }
        return this.ascend_resolver();
      }
    };

    return Serializer;

  })();

}).call(this);