text:
using Caps.Consumer.ContentControls;
using Caps.Consumer.Localization;
using Caps.Consumer.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;

namespace Caps.Consumer
{
    public class ContentService
    {
        CapsHttpClient client;

        public ContentService(CapsHttpClient client)
        {
            this.client = client;
        }

        /// <summary>
        /// Returns the currently published version of the sitemap
        /// node with the given permanent id.
        /// </summary>
        /// <param name="permanentId"></param>
        /// <returns></returns>
        public async Task<DbSiteMapNode> GetCurrentNodeVersion(int websiteId, int permanentId)
        {
            var response = await client.GetAsync("api/websites/" + websiteId.ToString() + "/content/" + permanentId.ToString());
            if (response.IsSuccessStatusCode)
                return await response.Content.ReadAsAsync<DbSiteMapNode>();
            return null;
        }

        /// <summary>
        /// Returns a localized ContentModel-Instance for the sitemap node with the given
        /// permanent id and the language set by Caps.Data.Localization.Language.CurrentLanguage.
        /// </summary>
        /// <param name="permanentId"></param>
        /// <returns></returns>
        public async Task<ContentModel> GetContent(int websiteId, int permanentId, ContentScriptManager scriptManager = null)
        {
            var entity = await GetCurrentNodeVersion(websiteId, permanentId);
            if (entity == null)
                throw new ContentNotFoundException();
            return CreateContentModel(entity, scriptManager);
        }

        /// <summary>
        /// Returns a DbFileVersion-Instance representing the file version with the given id.
        /// </summary>
        /// <param name="fileVersionId"></param>
        /// <returns></returns>
        public async Task<DbFileVersion> GetContentFileVersion(int websiteId, int fileVersionId)
        {
            var response = await client.GetAsync("api/websites/" + websiteId.ToString() + "/fileversions/" + fileVersionId.ToString());
            if (response.IsSuccessStatusCode)
                return await response.Content.ReadAsAsync<DbFileVersion>();
            return null;
        }

        /// <summary>
        /// Returns a DbFileThumbnail-Instance representing a thumbnail for the file version with the given id.
        /// </summary>
        /// <param name="fileVersionId"></param>
        /// <returns></returns>
        public async Task<DbThumbnail> GetThumbnail(int websiteId, int fileVersionId, String nameOrSize, String fitMode = "Default", String scaleMode = "Default")
        {
            var response = await client.GetAsync("api/websites/" + websiteId.ToString() + "/fileversions/" + fileVersionId.ToString() + "/thumbnails/" + nameOrSize + "?fitMode=" + fitMode + "&scaleMode=" + scaleMode);
            if (response.IsSuccessStatusCode)
                return await response.Content.ReadAsAsync<DbThumbnail>();
            return null;
        }

        /// <summary>
        /// Returns a DbFileThumbnail-Instance representing a thumbnail for the first picture of the content with the given id.
        /// </summary>
        /// <returns></returns>
        public async Task<DbThumbnail> GetContentThumbnail(int websiteId, int permanentId, String nameOrSize, String fitMode = "Default", String scaleMode = "Default")
        {
            var response = await client.GetAsync("api/websites/" + websiteId.ToString() + "/content/" + permanentId.ToString() + "/thumbnail/" + nameOrSize + "?fitMode=" + fitMode + "&scaleMode=" + scaleMode);
            if (response.IsSuccessStatusCode)
                return await response.Content.ReadAsAsync<DbThumbnail>();
            return null;
        }

        /// <summary>
        /// Returns a IEnumerable<TeaserModel>-Instance that contains all
        /// teasers placed on the start page.
        /// </summary>
        /// <param name="websiteId"></param>
        /// <returns></returns>
        public async Task<IEnumerable<TeaserModel>> GetTeasers(int websiteId)
        {
            var response = await client.GetAsync("api/websites/" + websiteId.ToString() + "/teasers");
            if (response.IsSuccessStatusCode)
                return await response.Content.ReadAsAsync<IEnumerable<TeaserModel>>();
            return null;
        }

        public static ContentModel CreateContentModel(DbSiteMapNode entity, ContentScriptManager scriptManager = null)
        {
            var contentParts = entity.Content != null ? entity.Content.ContentParts.Select(p =>
                p.GetValueForLanguage(Language.CurrentLanguage, r =>
                {
                    if (String.IsNullOrWhiteSpace(r.Content))
                        return null;

                    return new ContentPartModel
                    {
                        Content = r.Content,
                        Language = r.Language,
                        Usage = p.Name,
                        IsFallback = !String.Equals(Language.CurrentLanguage, r.Language, StringComparison.OrdinalIgnoreCase)
                    };
                }
                , null, "en", "de")) : new List<ContentPartModel>();

            var contentFiles = new List<ContentFileModel>();
            if (entity.Content != null)
            {
                contentFiles = entity.Content.Files.Select(f =>
                {

                    var fileVersion = f.GetValueForLanguage(Language.CurrentLanguage, r => r.FileVersion, null, "de", "en");
                    var title = LocalizedFileTitle(f, Language.CurrentLanguage);
                    var description = f.GetValueForLanguage(Language.CurrentLanguage, r => r.Description, String.Empty, "de", "en");

                    return new ContentFileModel
                    {
                        Name = f.Name,
                        Language = Language.CurrentLanguage,
                        Determination = f.Determination,
                        Group = f.Group,
                        Ranking = f.Ranking,
                        Title = title,
                        Description = description,
                        FileVersionId = fileVersion != null ? fileVersion.Id : 0,
                        FileSize = fileVersion != null ? fileVersion.FileSize : 0,
                        FileName = fileVersion != null && fileVersion.File != null ? fileVersion.File.FileName : String.Empty
                    };
                })
                .ToList();
            }

            var result = new ContentModel(scriptManager ?? new ContentScriptManager())
            {
                SiteMapNode = entity,
                ContentParts = contentParts.Where(c => c != null),
                ContentFiles = contentFiles.Where(f => f != null)
            };

            return result;
        }

        static String LocalizedFileTitle(PublicationFile f, String language)
        {
            var result = f.GetValueForLanguage(language, r => r.Title, String.Empty, "de", "en");
            if (String.IsNullOrWhiteSpace(result))
            {
                var v = f.FileVersionForLanguage(language, "de", "en");
                if (v != null) result = v.File.FileName;
            }
            return String.IsNullOrWhiteSpace(result) ? String.Empty : result;
        }
    }

    public class ContentNotFoundException : Exception
    {
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Exports object contains arguments names and their configuration objects
 *
 * @example
 * module.exports = {
 *   argName: {
 *       desc: 'Argument description',
 *       required: false,
 *       optional: true,
 *       type: String || Number || Array || Object,
 *       defaults: 'test'
 *   }
 * };
 */

module.exports = {};


text:
{% extends "layout.html" %}

{% block page_title %}
  GOV.UK prototyping kit
{% endblock %}

{% block propositionHeader %}
  {% include "includes/propositional_navigation.html" %}
{% endblock %}

{% block content %}

Home

Jobcentre

Benefit centre

Admin

Stats

Home > Benefit centre > Edit record

  Close claim #310 - John Smith

Search

Advanced search

New record

                      View record

                      Edit record

                      Maintenance

                      Payment

                      Closure

Confirm closure

                        Closure date:
                        14/08/2015

                        Reason:
                        Found employment

                  Edit
                  Submit

{% endblock %}


text:
layout: secondary_pages
---

You can find my [CV here](/assets/CV_Sarmiento_Barbieri.pdf).


text:
import { BlobService, createBlobService } from 'azure-storage';
import { promisify } from 'util';

export class BlobServiceAsPromised {

  public createContainerIfNotExists: (container: string, options: BlobService.CreateContainerOptions) => Promise<BlobService.ContainerResult>;
  public createBlockBlobFromText: (container: string, blob: string, text: string | Buffer, options: BlobService.CreateBlobRequestOptions) => Promise<BlobService.BlobResult>;
  public blobToText: (container: string, blob: string) => Promise<string>;

  constructor(blobService = createBlobService()) {
    this.createContainerIfNotExists = promisify<string, BlobService.CreateContainerOptions, BlobService.ContainerResult>(blobService.createContainerIfNotExists).bind(blobService);
    this.createBlockBlobFromText = promisify(blobService.createBlockBlobFromText).bind(blobService);
    this.blobToText = promisify(blobService.getBlobToText).bind(blobService);
  }
}


text:
import { FunctionComponent, useMemo } from 'react';

import { OfferingNamesManagedByUser } from '@waldur/customer/team/OfferingNamesManagedByUser';
import { ProjectRolesList } from '@waldur/customer/team/ProjectRolesList';
import { getRoles } from '@waldur/customer/team/utils';
import { translate } from '@waldur/i18n';

export const CustomerUsersListExpandableRow: FunctionComponent<any> = ({
  row,
}) => {
  const roles = useMemo(getRoles, []);
  return (
    <>
      {roles.map((role) => (

          {translate('{label} in:', role)}{' '}
          <ProjectRolesList roleName={role.value} row={row} />

      ))}
      {row.is_service_manager && (

          {translate('Service manager of:')}{' '}
          <OfferingNamesManagedByUser userUuid={row.uuid} />

      )}
    </>
  );
};


text:
/**
 * Created by irahmed on 12/14/16.
 */

var when = require("when");
var request = require("request");

function WeatherService(API_KEY, options) {
  this.settings = {};
  if (options.proxy) {
    this.settings.proxy = options.proxy;
  }
  this.URL = "http://api.openweathermap.org/data/2.5/weather?appid=" + API_KEY + "&units=imperial";
}

WeatherService.prototype.getWeather = function (place) {
  if (!place || !place.place) {
    return when.reject("Missing place name. Cannot get weather. Provide name or zip");
  }
  var url = this.URL;
  if (place.zip) {
    if (!place.country_code) {
      place.country_code = "us"
    }
    url += "&zip=" + place.zip + "," + place.country_code;
  } else if (place.place) {
    url += "&q=" + encodeURIComponent(place.place);
  }
  var settings = Object.assign({}, this.settings, {
    url: url
  });
  console.log("Getting Weather: ", place, settings);
  return when.promise(function (resolve, reject) {
    request(settings, function (err, response, body) {
      if (err) {
        console.log("Error in getting weather", settings, err);
        return reject(err);
      }
      if (response.statusCode === 200) {
        var data = JSON.parse(body);
        resolve(data);
      }
    })
  })
};

module.exports = function (API_KEY, config) {
  return new WeatherService(API_KEY, config);
};


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;
using UnityEngine;

namespace Microsoft.MixedReality.Toolkit.Core.Utilities.Gltf.Schema
{
    /// <summary>
    /// Image data used to create a texture. Image can be referenced by URI or
    /// `bufferView` index. `mimeType` is required in the latter case.
    /// </summary>
    [Serializable]
    public class GltfImage : GltfChildOfRootProperty
    {
        #region Serialized Fields

        /// <summary>
        /// The uri of the image.  Relative paths are relative to the .gltf file.
        /// Instead of referencing an external file, the uri can also be a data-uri.
        /// The image format must be jpg, png, bmp, or gif.
        /// </summary>
        public string uri;

        /// <summary>
        /// The image's MIME type.
        /// <minLength>1</minLength>
        /// </summary>
        public string mimeType;

        /// <summary>
        /// The index of the bufferView that contains the image.
        /// Use this instead of the image's uri property.
        /// </summary>
        public int bufferView;

        #endregion Serialized Fields

        public Texture2D Texture { get; internal set; }
    }
}


text:
#include <sys/lock.h>
#include <stdlib.h>
#include <sys/reent.h>
#include "esp_attr.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "freertos/portable.h"
#include "esp_rom_caps.h"

/* Notes on our newlib lock implementation:
 *
 * - Use FreeRTOS mutex semaphores as locks.
 * - lock_t is int, but we store an SemaphoreHandle_t there.
 * - Locks are no-ops until the FreeRTOS scheduler is running.
 * - Due to this, locks need to be lazily initialised the first time
 *   they are acquired. Initialisation/deinitialisation of locks is
 *   protected by lock_init_spinlock.
 * - Race conditions around lazy initialisation (via lock_acquire) are
 *   protected against.
 * - Anyone calling lock_close is reponsible for ensuring noone else
 *   is holding the lock at this time.
 * - Race conditions between lock_close & lock_init (for the same lock)
 *   are the responsibility of the caller.
 */

static portMUX_TYPE lock_init_spinlock = portMUX_INITIALIZER_UNLOCKED;

/* Initialize the given lock by allocating a new mutex semaphore
   as the _lock_t value.

   Called by _lock_init*, also called by _lock_acquire* to lazily initialize locks that might have
   been initialised (to zero only) before the RTOS scheduler started.
*/
static void IRAM_ATTR lock_init_generic(_lock_t *lock, uint8_t mutex_type) {
    portENTER_CRITICAL(&lock_init_spinlock);
    if (*lock) {
         /* Lock already initialised (either we didn't check earlier,
          or it got initialised while we were waiting for the
          spinlock.) */
    }
    else
    {
        /* Create a new semaphore

           this is a bit of an API violation, as we're calling the
           private function xQueueCreateMutex(x) directly instead of
           the xSemaphoreCreateMutex / xSemaphoreCreateRecursiveMutex
           wrapper functions...

           The better alternative would be to pass pointers to one of
           the two xSemaphoreCreate___Mutex functions, but as FreeRTOS
           implements these as macros instead of inline functions
           (*party like it's 1998!*) it's not possible to do this
           without writing wrappers. Doing it this way seems much less
           spaghetti-like.
        */
        SemaphoreHandle_t new_sem = xQueueCreateMutex(mutex_type);
        if (!new_sem) {
            abort(); /* No more semaphores available or OOM */
        }
        *lock = (_lock_t)new_sem;
    }
    portEXIT_CRITICAL(&lock_init_spinlock);
}

void IRAM_ATTR _lock_init(_lock_t *lock) {
    *lock = 0; // In case lock's memory is uninitialized
    lock_init_generic(lock, queueQUEUE_TYPE_MUTEX);
}

void IRAM_ATTR _lock_init_recursive(_lock_t *lock) {
    *lock = 0; // In case lock's memory is uninitialized
    lock_init_generic(lock, queueQUEUE_TYPE_RECURSIVE_MUTEX);
}

/* Free the mutex semaphore pointed to by *lock, and zero it out.

   Note that FreeRTOS doesn't account for deleting mutexes while they
   are held, and neither do we... so take care not to delete newlib
   locks while they may be held by other tasks!

   Also, deleting a lock in this way will cause it to be lazily
   re-initialised if it is used again. Caller has to avoid doing
   this!
*/
void IRAM_ATTR _lock_close(_lock_t *lock) {
    portENTER_CRITICAL(&lock_init_spinlock);
    if (*lock) {
        SemaphoreHandle_t h = (SemaphoreHandle_t)(*lock);
#if (INCLUDE_xSemaphoreGetMutexHolder == 1)
        configASSERT(xSemaphoreGetMutexHolder(h) == NULL); /* mutex should not be held */
#endif
        vSemaphoreDelete(h);
        *lock = 0;
    }
    portEXIT_CRITICAL(&lock_init_spinlock);
}

void _lock_close_recursive(_lock_t *lock) __attribute__((alias("_lock_close")));

/* Acquire the mutex semaphore for lock. wait up to delay ticks.
   mutex_type is queueQUEUE_TYPE_RECURSIVE_MUTEX or queueQUEUE_TYPE_MUTEX
*/
static int IRAM_ATTR lock_acquire_generic(_lock_t *lock, uint32_t delay, uint8_t mutex_type) {
    SemaphoreHandle_t h = (SemaphoreHandle_t)(*lock);
    if (!h) {
        if (xTaskGetSchedulerState() == taskSCHEDULER_NOT_STARTED) {
            return 0; /* locking is a no-op before scheduler is up, so this "succeeds" */
        }
        /* lazy initialise lock - might have had a static initializer (that we don't use) */
        lock_init_generic(lock, mutex_type);
        h = (SemaphoreHandle_t)(*lock);
        configASSERT(h != NULL);
    }

    if (xTaskGetSchedulerState() == taskSCHEDULER_NOT_STARTED) {
        return 0; /* locking is a no-op before scheduler is up, so this "succeeds" */
    }
    BaseType_t success;
    if (!xPortCanYield()) {
        /* In ISR Context */
        if (mutex_type == queueQUEUE_TYPE_RECURSIVE_MUTEX) {
            abort(); /* recursive mutexes make no sense in ISR context */
        }
        BaseType_t higher_task_woken = false;
        success = xSemaphoreTakeFromISR(h, &higher_task_woken);
        if (!success && delay > 0) {
            abort(); /* Tried to block on mutex from ISR, couldn't... rewrite your program to avoid libc interactions in ISRs! */
        }
        if (higher_task_woken) {
            portYIELD_FROM_ISR();
        }
    }
    else {
        /* In task context */
        if (mutex_type == queueQUEUE_TYPE_RECURSIVE_MUTEX) {
            success = xSemaphoreTakeRecursive(h, delay);
        } else {
            success = xSemaphoreTake(h, delay);
        }
    }

    return (success == pdTRUE) ? 0 : -1;
}

void IRAM_ATTR _lock_acquire(_lock_t *lock) {
    lock_acquire_generic(lock, portMAX_DELAY, queueQUEUE_TYPE_MUTEX);
}

void IRAM_ATTR _lock_acquire_recursive(_lock_t *lock) {
    lock_acquire_generic(lock, portMAX_DELAY, queueQUEUE_TYPE_RECURSIVE_MUTEX);
}

int IRAM_ATTR _lock_try_acquire(_lock_t *lock) {
    return lock_acquire_generic(lock, 0, queueQUEUE_TYPE_MUTEX);
}

int IRAM_ATTR _lock_try_acquire_recursive(_lock_t *lock) {
    return lock_acquire_generic(lock, 0, queueQUEUE_TYPE_RECURSIVE_MUTEX);
}

/* Release the mutex semaphore for lock.
   mutex_type is queueQUEUE_TYPE_RECURSIVE_MUTEX or queueQUEUE_TYPE_MUTEX
*/
static void IRAM_ATTR lock_release_generic(_lock_t *lock, uint8_t mutex_type) {
    if (xTaskGetSchedulerState() == taskSCHEDULER_NOT_STARTED) {
        return; /* locking is a no-op before scheduler is up */
    }
    SemaphoreHandle_t h = (SemaphoreHandle_t)(*lock);
    assert(h);

    if (!xPortCanYield()) {
        if (mutex_type == queueQUEUE_TYPE_RECURSIVE_MUTEX) {
            abort(); /* indicates logic bug, it shouldn't be possible to lock recursively in ISR */
        }
        BaseType_t higher_task_woken = false;
        xSemaphoreGiveFromISR(h, &higher_task_woken);
        if (higher_task_woken) {
            portYIELD_FROM_ISR();
        }
    } else {
        if (mutex_type == queueQUEUE_TYPE_RECURSIVE_MUTEX) {
            xSemaphoreGiveRecursive(h);
        } else {
            xSemaphoreGive(h);
        }
    }
}

void IRAM_ATTR _lock_release(_lock_t *lock) {
    lock_release_generic(lock, queueQUEUE_TYPE_MUTEX);
}

void IRAM_ATTR _lock_release_recursive(_lock_t *lock) {
    lock_release_generic(lock, queueQUEUE_TYPE_RECURSIVE_MUTEX);
}

/* To ease the transition to newlib 3.3.0, this part is kept under an ifdef.
 * After the toolchain with newlib 3.3.0 is released and merged, the ifdefs
 * can be removed.
 *
 * Also the retargetable locking functions still rely on the previous
 * implementation. Once support for !_RETARGETABLE_LOCKING is removed,
 * the code can be simplified, removing support for lazy initialization of
 * locks. At the same time, IDF code which relies on _lock_acquire/_lock_release
 * will have to be updated to not depend on lazy initialization.
 *
 * Explanation of the different lock types:
 *
 *  Newlib 2.2.0 and 3.0.0:
 *    _lock_t is defined as int, stores SemaphoreHandle_t.
 *
 *  Newlib 3.3.0:
 *    struct __lock is (or contains) StaticSemaphore_t
 *    _LOCK_T is a pointer to struct __lock, equivalent to SemaphoreHandle_t.
 *    It has the same meaning as _lock_t in the previous implementation.
 *
 */

/* This ensures the platform-specific definition in lock.h is correct.
 * We use "greater or equal" since the size of StaticSemaphore_t may
 * vary by 2 words, depending on whether configUSE_TRACE_FACILITY is enabled.
 */
_Static_assert(sizeof(struct __lock) >= sizeof(StaticSemaphore_t),
               "Incorrect size of struct __lock");

/* FreeRTOS configuration check */
_Static_assert(configSUPPORT_STATIC_ALLOCATION,
               "FreeRTOS should be configured with static allocation support");

/* These 2 locks are used instead of 9 distinct newlib static locks,
 * as most of the locks are required for lesser-used features, so
 * the chance of performance degradation due to lock contention is low.
 */
static StaticSemaphore_t s_common_mutex;
static StaticSemaphore_t s_common_recursive_mutex;

#if ESP_ROM_HAS_RETARGETABLE_LOCKING
/* C3 and S3 ROMs are built without Newlib static lock symbols exported, and
 * with an extra level of _LOCK_T indirection in mind.
 * The following is a workaround for this:
 * - on startup, we call esp_rom_newlib_init_common_mutexes to set
 *   the two mutex pointers to magic values.
 * - if in __retarget_lock_acquire*, we check if the argument dereferences
 *   to the magic value. If yes, we lock the correct mutex defined in the app,
 *   instead.
 * Casts from &StaticSemaphore_t to _LOCK_T are okay because _LOCK_T
 * (which is SemaphoreHandle_t) is a pointer to the corresponding
 * StaticSemaphore_t structure. This is ensured by asserts below.
 */

#define ROM_NEEDS_MUTEX_OVERRIDE
#endif // ESP_ROM_HAS_RETARGETABLE_LOCKING

#ifdef ROM_NEEDS_MUTEX_OVERRIDE
#define ROM_MUTEX_MAGIC  0xbb10c433
/* This is a macro, since we are overwriting the argument  */
#define MAYBE_OVERRIDE_LOCK(_lock, _lock_to_use_instead) \
    if (*(int*)_lock == ROM_MUTEX_MAGIC) { \
        (_lock) = (_LOCK_T) (_lock_to_use_instead); \
    }
#else  // ROM_NEEDS_MUTEX_OVERRIDE
#define MAYBE_OVERRIDE_LOCK(_lock, _lock_to_use_instead)
#endif // ROM_NEEDS_MUTEX_OVERRIDE

void IRAM_ATTR __retarget_lock_init(_LOCK_T *lock)
{
    *lock = NULL;  /* In case lock's memory is uninitialized */
    lock_init_generic(lock, queueQUEUE_TYPE_MUTEX);
}

void IRAM_ATTR __retarget_lock_init_recursive(_LOCK_T *lock)
{
    *lock = NULL;  /* In case lock's memory is uninitialized */
    lock_init_generic(lock, queueQUEUE_TYPE_RECURSIVE_MUTEX);
}

void IRAM_ATTR __retarget_lock_close(_LOCK_T lock)
{
    _lock_close(&lock);
}

void IRAM_ATTR __retarget_lock_close_recursive(_LOCK_T lock)
{
    _lock_close_recursive(&lock);
}

/* Separate function, to prevent generating multiple assert strings */
static void IRAM_ATTR check_lock_nonzero(_LOCK_T lock)
{
    assert(lock != NULL && "Uninitialized lock used");
}

void IRAM_ATTR __retarget_lock_acquire(_LOCK_T lock)
{
    check_lock_nonzero(lock);
    MAYBE_OVERRIDE_LOCK(lock, &s_common_mutex);
    _lock_acquire(&lock);
}

void IRAM_ATTR __retarget_lock_acquire_recursive(_LOCK_T lock)
{
    check_lock_nonzero(lock);
    MAYBE_OVERRIDE_LOCK(lock, &s_common_recursive_mutex);
    _lock_acquire_recursive(&lock);
}

int IRAM_ATTR __retarget_lock_try_acquire(_LOCK_T lock)
{
    check_lock_nonzero(lock);
    MAYBE_OVERRIDE_LOCK(lock, &s_common_mutex);
    return _lock_try_acquire(&lock);
}

int IRAM_ATTR __retarget_lock_try_acquire_recursive(_LOCK_T lock)
{
    check_lock_nonzero(lock);
    MAYBE_OVERRIDE_LOCK(lock, &s_common_recursive_mutex);
    return _lock_try_acquire_recursive(&lock);
}

void IRAM_ATTR __retarget_lock_release(_LOCK_T lock)
{
    check_lock_nonzero(lock);
    _lock_release(&lock);
}

void IRAM_ATTR __retarget_lock_release_recursive(_LOCK_T lock)
{
    check_lock_nonzero(lock);
    _lock_release_recursive(&lock);
}

/* When _RETARGETABLE_LOCKING is enabled, newlib expects the following locks to be provided: */

extern StaticSemaphore_t __attribute__((alias("s_common_recursive_mutex"))) __lock___sinit_recursive_mutex;
extern StaticSemaphore_t __attribute__((alias("s_common_recursive_mutex"))) __lock___malloc_recursive_mutex;
extern StaticSemaphore_t __attribute__((alias("s_common_recursive_mutex"))) __lock___env_recursive_mutex;
extern StaticSemaphore_t __attribute__((alias("s_common_recursive_mutex"))) __lock___sfp_recursive_mutex;
extern StaticSemaphore_t __attribute__((alias("s_common_recursive_mutex"))) __lock___atexit_recursive_mutex;
extern StaticSemaphore_t __attribute__((alias("s_common_mutex"))) __lock___at_quick_exit_mutex;
extern StaticSemaphore_t __attribute__((alias("s_common_mutex"))) __lock___tz_mutex;
extern StaticSemaphore_t __attribute__((alias("s_common_mutex"))) __lock___dd_hash_mutex;
extern StaticSemaphore_t __attribute__((alias("s_common_mutex"))) __lock___arc4random_mutex;

void esp_newlib_locks_init(void)
{
    /* Initialize the two mutexes used for the locks above.
     * Asserts below check our assumption that SemaphoreHandle_t will always
     * point to the corresponding StaticSemaphore_t structure.
     */
    SemaphoreHandle_t handle;
    handle = xSemaphoreCreateMutexStatic(&s_common_mutex);
    assert(handle == (SemaphoreHandle_t) &s_common_mutex);
    handle = xSemaphoreCreateRecursiveMutexStatic(&s_common_recursive_mutex);
    assert(handle == (SemaphoreHandle_t) &s_common_recursive_mutex);
    (void) handle;

    /* Chip ROMs are built with older versions of newlib, and rely on different lock variables.
     * Initialize these locks to the same values.
     */
#ifdef CONFIG_IDF_TARGET_ESP32
    /* Newlib 2.2.0 is used in ROM, the following lock symbols are defined: */
    extern _lock_t __sfp_lock;
    __sfp_lock = (_lock_t) &s_common_recursive_mutex;
    extern _lock_t __sinit_lock;
    __sinit_lock = (_lock_t) &s_common_recursive_mutex;
    extern _lock_t __env_lock_object;
    __env_lock_object = (_lock_t) &s_common_mutex;
    extern _lock_t __tz_lock_object;
    __tz_lock_object = (_lock_t) &s_common_recursive_mutex;
#elif defined(CONFIG_IDF_TARGET_ESP32S2)
    /* Newlib 3.0.0 is used in ROM, the following lock symbols are defined: */
    extern _lock_t __sinit_recursive_mutex;
    __sinit_recursive_mutex = (_lock_t) &s_common_recursive_mutex;
    extern _lock_t __sfp_recursive_mutex;
    __sfp_recursive_mutex = (_lock_t) &s_common_recursive_mutex;
#elif ESP_ROM_HAS_RETARGETABLE_LOCKING
    /* Newlib 3.3.0 is used in ROM, built with _RETARGETABLE_LOCKING.
     * No access to lock variables for the purpose of ECO forward compatibility,
     * however we have an API to initialize lock variables used in the ROM.
     */
    extern void esp_rom_newlib_init_common_mutexes(_LOCK_T, _LOCK_T);
    /* See notes about ROM_NEEDS_MUTEX_OVERRIDE above */
    int magic_val = ROM_MUTEX_MAGIC;
    _LOCK_T magic_mutex = (_LOCK_T) &magic_val;
    esp_rom_newlib_init_common_mutexes(magic_mutex, magic_mutex);
#else // other target
#error Unsupported target
#endif
}


text:
package com.trovebox.android.common.net;

import org.json.JSONException;
import org.json.JSONObject;

import com.trovebox.android.common.model.Token;

/**
 * The class which represents token api json response
 *
 * @author Eugene Popovich
 */
public class TokenResponse extends TroveboxResponse {
    private final Token mToken;

    public TokenResponse(RequestType requestType, JSONObject json) throws JSONException {
        super(requestType, json);
        if (isSuccess() && json.get("result") instanceof JSONObject) {
            mToken = Token.fromJson(json.getJSONObject("result"));
        } else {
            mToken = null;
        }
    }

    /**
     * @return the photo contained in the response from the server
     */
    public Token getToken() {
        return mToken;
    }
}


text:
from __future__ import print_function
import random

import numpy as np
from sklearn.cross_validation import train_test_split
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.optimizers import SGD
from keras.utils import np_utils
from keras.models import load_model
from keras import backend as K
from keras.utils import plot_model

from FaceInput import extract_data, resize_with_pad, IMAGE_SIZE
import os

class Dataset(object):

    def __init__(self):
        self.X_train = None
        self.X_valid = None
        self.X_test = None
        self.Y_train = None
        self.Y_valid = None
        self.Y_test = None

    def read(self, nb_classes, img_rows=IMAGE_SIZE, img_cols=IMAGE_SIZE, img_channels=3):
        images, labels = extract_data('./train/')
        labels = np.reshape(labels, [-1])
        # numpy.reshape
        X_train, X_test, y_train, y_test = train_test_split(images, labels, test_size=0.3, random_state=random.randint(0, 100))
        X_valid, X_test, y_valid, y_test = train_test_split(images, labels, test_size=0.5, random_state=random.randint(0, 100))

        X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 3)
        X_valid = X_valid.reshape(X_valid.shape[0], img_rows, img_cols, 3)
        X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 3)
        input_shape = (img_rows, img_cols, 3)

        # the data, shuffled and split between train and test sets
        print('X_train shape:', X_train.shape)
        print(X_train.shape[0], 'train samples')
        print(X_valid.shape[0], 'valid samples')
        print(X_test.shape[0], 'test samples')

        # convert class vectors to binary class matrices
        Y_train = np_utils.to_categorical(y_train, nb_classes)
        Y_valid = np_utils.to_categorical(y_valid, nb_classes)
        Y_test = np_utils.to_categorical(y_test, nb_classes)

        X_train = X_train.astype('float32')
        X_valid = X_valid.astype('float32')
        X_test = X_test.astype('float32')
        X_train /= 255
        X_valid /= 255
        X_test /= 255

        self.X_train = X_train
        self.X_valid = X_valid
        self.X_test = X_test
        self.Y_train = Y_train
        self.Y_valid = Y_valid
        self.Y_test = Y_test

class Model(object):

    FILE_PATH = './model/model.h5'

    def __init__(self):
        self.model = None

    def build_model(self, nb_classes):
        self.model = Sequential()

        self.model.add(
            Convolution2D(
                filters=32,
                kernel_size=(5, 5),
                padding='same',
                dim_ordering='tf',
                input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3),
                name="1"
            )
        )

        self.model.add(Activation('relu',name="2"))
        self.model.add(
            MaxPooling2D(
                pool_size=(2, 2),
                strides=(2, 2),
                padding='same',
                name="3"
            )
        )

        self.model.add(Convolution2D(filters=64, kernel_size=(5, 5), padding='same', name='4'))
        self.model.add(Activation('relu',name='5'))
        self.model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same',name='6'))

        self.model.add(Flatten(name='7'))
        self.model.add(Dense(512,name="8"))
        self.model.add(Activation('relu',name='9'))

        self.model.add(Dense(nb_classes,name='10'))
        self.model.add(Activation('softmax',name='11'))
        self.model.summary()

    def train(self, dataset, batch_size=20, nb_epoch=1, data_augmentation=True):
        self.dataset = dataset
        self.model.compile(
            optimizer='adam',  #有很多可选的optimizer,例如RMSprop,Adagrad,你也可以试试哪个好,我个人感觉差异不大
            loss='categorical_crossentropy',  #你可以选用squared_hinge作为loss看看哪个好
            metrics=['accuracy'])

        if not data_augmentation:
            print('Not using data augmentation.')
            self.model.fit(dataset.X_train, dataset.Y_train,
                           batch_size=batch_size,
                           nb_epoch=nb_epoch,
                           validation_data=(dataset.X_valid, dataset.Y_valid),
                           shuffle=True)
            #epochs、batch_size为可调的参数,epochs为训练多少轮、batch_size为每次训练多少个样本
            #self.model.fit(self.dataset.X_train,self.dataset.Y_train,nb_epoch,batch_size)
        else:
            print('Using real-time data augmentation.')

            # this will do preprocessing and realtime data augmentation
            datagen = ImageDataGenerator(
                featurewise_center=False,             # set input mean to 0 over the dataset
                samplewise_center=False,              # set each sample mean to 0
                featurewise_std_normalization=False,  # divide inputs by std of the dataset
                samplewise_std_normalization=False,   # divide each input by its std
                zca_whitening=False,                  # apply ZCA whitening
                rotation_range=20,                     # randomly rotate images in the range (degrees, 0 to 180)
                width_shift_range=0.2,                # randomly shift images horizontally (fraction of total width)
                height_shift_range=0.2,               # randomly shift images vertically (fraction of total height)
                horizontal_flip=True,                 # randomly flip images
                vertical_flip=False)                  # randomly flip images

            # compute quantities required for featurewise normalization
            # (std, mean, and principal components if ZCA whitening is applied)
            datagen.fit(dataset.X_train)

            # fit the model on the batches generated by datagen.flow()
            self.model.fit_generator(datagen.flow(dataset.X_train, dataset.Y_train,
                                                  batch_size=batch_size),
                                     samples_per_epoch=dataset.X_train.shape[0],
                                     nb_epoch=nb_epoch,
                                     validation_data=(dataset.X_valid, dataset.Y_valid))

    def save(self, file_path=FILE_PATH):
        print('Model Saved.')
        self.model.save(file_path)

    def load(self, file_path=FILE_PATH):
        print('Model Loaded.')
        self.model = load_model(file_path)

    def predict(self, image):
        if K.image_dim_ordering() == 'tf' and image.shape != (1, IMAGE_SIZE, IMAGE_SIZE, 3):
            image = resize_with_pad(image)
            image = image.reshape((1, IMAGE_SIZE, IMAGE_SIZE, 3))
        image = image.astype('float32')
        image /= 255
        result = self.model.predict_proba(image)
        print(result)
        max_index = np.argmax(result)

        return max_index,result[0][max_index]

    def evaluate(self, dataset):
        score = self.model.evaluate(dataset.X_test, dataset.Y_test, verbose=0)
        print("%s: %.2f%%" % (self.model.metrics_names[1], score[1] * 100))

    def getTrainCfg(self):
        array=[]
        with open("./model/train.cfg", 'r') as fread:
            lines = fread.readlines()
            for name in lines:
                array.append(name.strip("\n"))
        print(array)
        return enumerate(array)

    def generateTrainCfg(self):
        with open("./model/train.cfg", "w+") as fwrite:
            for dir in os.listdir("train"):
                if not dir.startswith("."):  # avoid hidden folder like .DS_Store
                    fwrite.write("{}\n".format(dir))

if __name__ == '__main__':
    count = 0
    for dir in os.listdir("train"):
        count +=1
    print("%d type objects need to be trained" % count)

    dataset = Dataset()
    dataset.read(count)

    model = Model()
    model.build_model(count)
    model.train(dataset, data_augmentation=False)
    model.save()

    model = Model()
    model.load()
    model.evaluate(dataset)
    model.generateTrainCfg()
    print("Model training completed.")


text:
package org.apache.hadoop.hdfs.qjournal.client;

import java.io.IOException;

class LoggerTooFarBehindException extends IOException {
  private static final long serialVersionUID = 1L;

}


text:
export class ModelProject{
    public id: number;
    public name: string;
    public info: string;
    public detail: string[];
    public year: string;
    public link: string;
    public tab: string;

    constructor( id: number,
    name: string,
    info: string,
    detail: string[],
    year: string,
    link: string,
    tab: string) {
         this.id = id;
         this.name = name;
         this.info = info;
         this.detail = detail;
         this.year = year;
         this.link = link;
         this.tab = tab;
         // code...
    }

}


text:
const conf = require('./conf');
const download = require('./download');
const paths = require('./paths');
const search = require('./search');

module.exports = {
  conf,
  download,
  paths,
  search,
};


text:
Toggle visibility

 	Container 1:
 	The visibility of this text is also toggled.

Test

Test2


text:
<?php

namespace App\Services;

use App\Models\Album;
use App\Models\Artist;
use App\Models\Song;
use App\Models\User;
use App\Services\ApiClients\LastfmClient;
use App\Values\AlbumInformation;
use App\Values\ArtistInformation;
use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Promise\Utils;
use Illuminate\Support\Collection;

class LastfmService implements MusicEncyclopedia
{
    public function __construct(private LastfmClient $client)
    {
    }

    /**
     * Determine if our application is using Last.fm.
     */
    public static function used(): bool
    {
        return (bool) config('koel.lastfm.key');
    }

    /**
     * Determine if Last.fm integration is enabled.
     */
    public static function enabled(): bool
    {
        return config('koel.lastfm.key') && config('koel.lastfm.secret');
    }

    public function getArtistInformation(Artist $artist): ?ArtistInformation
    {
        return attempt_if(static::enabled(), function () use ($artist): ?ArtistInformation {
            $name = urlencode($artist->name);
            $response = $this->client->get("?method=artist.getInfo&autocorrect=1&artist=$name&format=json");

            return $response?->artist ? ArtistInformation::fromLastFmData($response->artist) : null;
        });
    }

    public function getAlbumInformation(Album $album): ?AlbumInformation
    {
        return attempt_if(static::enabled(), function () use ($album): ?AlbumInformation {
            $albumName = urlencode($album->name);
            $artistName = urlencode($album->artist->name);

            $response = $this->client
                ->get("?method=album.getInfo&autocorrect=1&album=$albumName&artist=$artistName&format=json");

            return $response?->album ? AlbumInformation::fromLastFmData($response->album) : null;
        });
    }

    public function scrobble(Song $song, User $user, int $timestamp): void
    {
        $params = [
            'artist' => $song->artist->name,
            'track' => $song->title,
            'timestamp' => $timestamp,
            'sk' => $user->lastfm_session_key,
            'method' => 'track.scrobble',
        ];

        if ($song->album->name !== Album::UNKNOWN_NAME) {
            $params['album'] = $song->album->name;
        }

        attempt(fn () => $this->client->post('/', $params, false));
    }

    public function toggleLoveTrack(Song $song, User $user, bool $love): void
    {
        attempt(fn () => $this->client->post('/', [
            'track' => $song->title,
            'artist' => $song->artist->name,
            'sk' => $user->lastfm_session_key,
            'method' => $love ? 'track.love' : 'track.unlove',
        ], false));
    }

    /**
     * @param Collection|array<array-key, Song> $songs
     */
    public function batchToggleLoveTracks(Collection $songs, User $user, bool $love): void
    {
        $promises = $songs->map(
            function (Song $song) use ($user, $love): Promise {
                return $this->client->postAsync('/', [
                    'track' => $song->title,
                    'artist' => $song->artist->name,
                    'sk' => $user->lastfm_session_key,
                    'method' => $love ? 'track.love' : 'track.unlove',
                ], false);
            }
        );

        attempt(static fn () => Utils::unwrap($promises));
    }

    public function updateNowPlaying(Song $song, User $user): void
    {
        $params = [
            'artist' => $song->artist->name,
            'track' => $song->title,
            'duration' => $song->length,
            'sk' => $user->lastfm_session_key,
            'method' => 'track.updateNowPlaying',
        ];

        if ($song->album->name !== Album::UNKNOWN_NAME) {
            $params['album'] = $song->album->name;
        }

        attempt(fn () => $this->client->post('/', $params, false));
    }

    public function getSessionKey(string $token): ?string
    {
        return $this->client->getSessionKey($token);
    }

    public function setUserSessionKey(User $user, ?string $sessionKey): void
    {
        $user->preferences->lastFmSessionKey = $sessionKey;
        $user->save();
    }
}


text:
const DrawCard = require('../../../drawcard.js');

class RedGodsBlessing extends DrawCard {
    setupCardAbilities(ability) {
        this.whileAttached({
            effect: [
                ability.effects.addTrait('R\'hllor'),
                ability.effects.dynamicStrength(() => this.getNumberOfCardsWithRhllor())
            ]
        });
    }

    getNumberOfCardsWithRhllor() {
        var cardsWithRhllor = this.controller.cardsInPlay.reduce((runningTotal, c) => {
            if(c.hasTrait('R\'hllor') && c.getType() === 'character') {
                return runningTotal + 1;
            }

            return runningTotal;
        }, 0);

        return cardsWithRhllor;
    }
}

RedGodsBlessing.code = '04068';

module.exports = RedGodsBlessing;


text:
package com.effektif.workflow.api.condition;

import java.util.ArrayList;
import java.util.List;

import com.effektif.workflow.api.bpmn.BpmnElement;
import com.effektif.workflow.api.bpmn.BpmnReader;
import com.effektif.workflow.api.bpmn.BpmnWriter;
import com.effektif.workflow.api.bpmn.XmlElement;
import com.effektif.workflow.api.json.TypeName;

/**
 * Logical and, for combining {@link Condition} instances.
 *
 * @author Tom Baeyens
 */
@TypeName("and")
@BpmnElement("and")
public class And extends Condition {

  protected List<Condition> conditions;

  @Override
  public boolean isEmpty() {
    return conditions == null || conditions.isEmpty();
  }

  public List<Condition> getConditions() {
    return this.conditions;
  }
  public void setConditions(List<Condition> conditions) {
    this.conditions = conditions;
  }

  public And condition(Condition condition) {
    if (conditions==null) {
      conditions = new ArrayList<>();
    }
    conditions.add(condition);
    return this;
  }

  @Override
  public void readBpmn(BpmnReader r) {
    conditions = r.readConditions();
  }

  @Override
  public void writeBpmn(BpmnWriter w) {
    if (!isEmpty()) {
      w.startElementEffektif(getClass());
      for (Condition condition : conditions) {
        condition.writeBpmn(w);
      }
      w.endElement();
    }
  }

  @Override
  public String toString() {
    if (conditions==null) {
      return "true";
    }
    StringBuilder string = new StringBuilder();
    String separator = null;
    for (Condition condition: conditions) {
      if (separator==null) {
        separator = " and ";
      } else {
        string.append(separator);
      }
      string.append(toString(condition));
    }
    return string.toString();
  }
}


text:
<?php

class login_model extends CI_Model {

	public function get_user($mail, $password) {
		$query = $this->db->get_where('users', array('mail'=>$mail, 'password'=>$password));
		$data = new StdClass();
		if($query->num_rows == 0) {
			$data->check = false;
		}
		else {
			$result = $query->result();
			$data->serial = $result[0]->id;
			$data->check = true;
		}
		return $data;
	}
}


text:
@font-face {
    font-family: 'Dirty Ego';
    src: url('dirtyego-webfont.woff') format('woff');
    font-weight: normal;
    font-style: normal;

}


text:
export interface NestGateway {
  afterInit?: (server: any) => void;
  handleConnection?: (...args: any[]) => void;
  handleDisconnect?: (client: any) => void;
}


text:
"use strict";

var SfzElement = require('./sfz-element');

var SfzRegion = function () {
    SfzElement.call(this, 'region');
    this.innerSequence = 0;
};

SfzRegion.prototype = Object.create(SfzElement.prototype);
SfzRegion.prototype.innerSequence = 0;

/**
 * Check if the region must be triggered by an incoming event
 * @param {Number} channel - Channel number
 * @param {Number} key - Midi value
 * @param {Number} bend - Pitch bend
 * @param {Number} velocity - Velocity
 * @param {Number} bpm - Tempo in beats per minutes
 * @param {Number} rand - Random value for round robin
 * @return {boolean} Return whether the region must be triggered
 */
SfzRegion.prototype.matchInput = function (channel, key, bend, velocity, bpm, rand) {
    var prop = this.properties;

    //TODO retrieve those values as arguments
    var chanaft = 0,
        polyaft = 0;

    this.innerSequence++;

    if (this.innerSequence > prop.seq_length) {
        this.innerSequence = 1;
    }

    return (
        channel >= prop.lochan && channel <= prop.hichan && // channel check
        key >= prop.lokey && key <= prop.hikey && // midi value check
        velocity >= prop.lovel && velocity <= prop.hivel && // velocity layer
        rand >= prop.lorand && rand <= prop.hirand && // randomizing
        bpm >= prop.lobpm && bpm <= prop.hibpm && // bpm check
        bend >= prop.lobend && bend <= prop.hibend && // pitch bend check
        chanaft >= prop.lochanaft && bend <= prop.hichanaft && // channel aftertouch check
        polyaft >= prop.lopolyaft && bend <= prop.hipolyaft && // polyphonic aftertouch check
        this.innerSequence === prop.seq_position // round robin
    );
};

module.exports = SfzRegion;


text:
from django.db import models
##from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ugettext as _
# Модели для подключения активов

class Asset(models.Model):
    asset_type = models.ForeignKey('Asset_type')
    payment = models.ForeignKey('Payment')
    date_of_write_off = models.DateTimeField(blank=True, null=True)
    garanty = models.ForeignKey('Garanty')
    # current_place = models.ForeignKey('Place_Asset',related_name='for_asset')
    model = models.CharField(max_length=140)
    status = models.ForeignKey('Status')
    # claim = models.ForeignKey('Claim',blank=True, null=True)
    guarantee_period = models.IntegerField()
    note = models.TextField(blank=True, null=True)
    price = models.DecimalField(decimal_places=2, max_digits=8)
    def __unicode__(self):
        return u';'.join((str(self.id),self.asset_type.asset_type,self.model,self.status.status))
# Оплата - либо нал, либо безнал, либо то и то
class Payment(models.Model):
    cash = models.ForeignKey('Cash',blank=True, null=True)
    cashless = models.ForeignKey('Cashless',blank=True, null=True)
    deleted = models.BooleanField(default=False)
    def __unicode__(self):
        if not self.cash:
            return u';'.join((str(self.id),u"CASHLESS:"+self.cashless.__unicode__()))
        if not self.cashless:
            return u';'.join((str(self.id),u"CASH:"+self.cash.__unicode__()))
        return u';'.join((str(self.id),u"CASH:"+self.cash.__unicode__(),u"CASHLESS:"+self.cashless.__unicode__()))

# Чек/Остатки - то, что за нал
class Cash(models.Model):
    date = models.DateTimeField()
    contractor = models.ForeignKey('Contractor')
    bill_number =  models.CharField(max_length=40)
    closed_for = models.TextField(blank = True, null = True)
    def __unicode__(self):
        return u';'.join((str(self.id),self.bill_number,str(self.date),self.contractor.name))
# Счёт по безналу
class Cashless(models.Model):
    date_of_invoice = models.DateTimeField()
    dates = models.TextField(blank = True, null = True) # даты прохождения этапов, разделённые ;
    stages = models.TextField() # этапы прохождения счёта, разделённые ;
    date_of_assets = models.DateTimeField(blank = True, null = True)
    date_of_documents = models.DateTimeField(blank = True, null = True)
    contractor = models.ForeignKey('Contractor')
    bill_number =  models.CharField(max_length=40)
    def __unicode__(self):
        return u';'.join((str(self.id),self.bill_number,self.contractor.name,self.stages))
# Заявка
class Claim(models.Model):
    date_of_invoice = models.DateTimeField()
    dates = models.TextField()
    stages = models.TextField()
    date_of_assets = models.DateTimeField()
    date_of_documents = models.DateTimeField()
    # Сколько денег дано по заявке
    price = models.DecimalField(decimal_places=2, max_digits=8)
    contractor = models.ForeignKey('Contractor')
class Contractor(models.Model):
    name = models.CharField(max_length=140)
    tel = models.CharField(max_length=10,blank = True, null = True)
    email = models.EmailField(blank = True, null = True)
    tel_of_support = models.CharField(max_length=10,blank = True, null = True)
    contact_name = models.CharField(max_length=140)
    def __unicode__(self):
        return u';'.join((str(self.id),self.name,self.contact_name))
class Garanty(models.Model):
    number = models.IntegerField()
    def __unicode__(self):
        return u';'.join((str(self.id),str(self.number)))
class Asset_type(models.Model):
    asset_type = models.CharField(max_length=200)
    catalogue_name = models.CharField(max_length=30)
    def __unicode__(self):
        return u';'.join((str(self.id),self.asset_type,self.catalogue_name))
class Status(models.Model):
    status = models.CharField(max_length=100)
    def __unicode__(self):
        return str(self.id)+';'+self.status
class Budget(models.Model):
    start = models.DateTimeField()
    end = models.DateTimeField()
class Repair(models.Model):
    date_of_failure = models.DateTimeField()
    failure = models.TextField()
    repair = models.TextField()
    date_repair_start = models.DateTimeField()
    date_repair_end = models.DateTimeField()
    payment = models.ForeignKey('Payment')
    date_of_write_off = models.DateTimeField()
    garanty = models.ForeignKey('Garanty')
    guarantee_period = models.IntegerField()
    asset = models.ForeignKey('Asset')
class Place_Asset(models.Model):
    installation_date = models.DateTimeField()
    drawdown_date = models.DateTimeField(blank = True, null = True)
    asset = models.ForeignKey('Asset')
    place = models.ForeignKey('Place')
    reason_of_drawdown = models.TextField(blank = True, null = True)
    def __unicode__(self):
        # a = str(self.id)
        # b = unicode(self.asset.model)
        # c = self.place.place
        # d = str(self.installation_date)
        return u';'.join((str(self.id),unicode(self.asset.model),unicode(self.place.place),str(self.installation_date),str(self.drawdown_date)))
class Place(models.Model):
    place = models.CharField(max_length=140)
    def __unicode__(self):
        return str(self.id)+';'+self.place
class Cartridge(models.Model):
    model = models.CharField(max_length=140)
    payment = models.ForeignKey('Payment')
    status = models.ForeignKey('Status')
class Cartridge_Model_General_Model(models.Model):
    model = models.CharField(max_length=140)      # общая
    model_name = models.CharField(max_length=140) # частная
class Cartridge_General_Model_Printer_Model(models.Model):
    printer_model = models.CharField(max_length=140)
    cartrige_model = models.CharField(max_length=140)
class Cartridge_Printer(models.Model):
    installation_date = models.DateTimeField()
    drawdown_date = models.DateTimeField()
    cartridge = models.ForeignKey('Cartridge')
    printer = models.ForeignKey('Asset')

# Таблицы справочников моделей по типам
# Все варианты выбора, такие как производители, форм-факторы памяти и т.д. хранятся в catalogue.py
import catalogue
class ROM(models.Model):
    model_name = models.CharField(max_length=50)
    firm = models.CharField(max_length=50, choices = catalogue.ROM_firms)
    rom_type = models.CharField(max_length=50, choices = catalogue.ROM_type)
    form_factor = models.CharField(max_length=50, choices = catalogue.ROM_form_factors)
    v = models.CharField(max_length=50, choices = catalogue.ROM_V)
    clock_ferquency = models.CharField(max_length=50, choices = catalogue.ROM_clock_frequency)
    throughput = models.CharField(max_length=50, choices = catalogue.ROM_throughput)
    low_profile = models.BooleanField(default=False)
    radiator = models.BooleanField(default=False)
class Cooler(models.Model):
    model_name = models.CharField(max_length=50)
    firm = models.CharField(max_length=50, choices = catalogue.Cooler_firms)
    destination = models.CharField(max_length=50, choices = catalogue.Cooler_destination)
    sockets = models.TextField(blank = True, null = True)
    number_of_fans = models.IntegerField()
    diametr_of_fans = models.IntegerField()
    type_of_connector = models.CharField(max_length=10, choices = catalogue.Cooler_connector)
    rpm = models.CharField(max_length=12)
    cfm = models.CharField(max_length=15)
    noise  = models.CharField(max_length=20)
class Storage(models.Model):
    model_name = models.CharField(max_length=50)
    firm = models.CharField(max_length=50, choices = catalogue.Storage_firms)
    form_factor = models.CharField(max_length=10, choices = catalogue.Storage_form_factor)
    volume = models.IntegerField()
    interfaces = models.TextField(blank = True, null = True) #?
    rpm = models.CharField(max_length=20, choices = catalogue.Storage_rpm)

    # TODO: добавить кеш
    # В Mb/сек
    v_read = models.IntegerField()
    v_write = models.IntegerField()
class Acoustics(models.Model):
    model_name = models.CharField(max_length=50)
    firm = models.CharField(max_length=50, choices = catalogue.Acoustics_firms)
    acoustics_type = models.CharField(max_length=10, choices = catalogue.Acoustics_type)
    # Суммарная мощность в ваттах
    rms = models.IntegerField()
    power_form_usb = models.BooleanField(default=False)
    power_from_circuit = models.BooleanField(default=False)
    power_from_battary = models.BooleanField(default=False)
    remote_control = models.BooleanField(default=False)
    frequency_interval = models.CharField(max_length=20)
    headphone_jack = models.BooleanField(default=False)
    # В децебелах
    signal_noise_ratio = models.CharField(max_length=20)
class Telephone(models.Model):
    model_name = models.CharField(max_length=50)
    firm = models.CharField(max_length=50, choices = catalogue.Telephone_firms)
    aon = models.BooleanField(default=False)
    display = models.BooleanField(default=False)
    tel_book = models.BooleanField(default=False)
    clock = models.BooleanField(default=False)
    alarm_clock = models.BooleanField(default=False)
    speakerphone = models.BooleanField(default=False)
    frequency = models.CharField(max_length=20, choices = catalogue.Telephone_frequency)
    DECT = models.BooleanField(default=False)
    GAP = models.BooleanField(default=False)
    headset = models.BooleanField(default=False)
class Battery(models.Model):
    model_name = models.CharField(max_length=50)
    firm = models.CharField(max_length=50, choices = catalogue.Battery_firms)
    battery_type = models.CharField(max_length=10, choices = catalogue.Battery_type)
    rechargeable = models.BooleanField(default=False)
class Optical_Drive(models.Model):
    model_name = models.CharField(max_length=50)
    firm = models.CharField(max_length=50, choices = catalogue.Optical_Drive_firms)
    optical_drive_type = models.CharField(max_length=10, choices = catalogue.Optical_Drive_type)
    interface = models.CharField(max_length=20, choices = catalogue.Optical_Drive_interfaces)
class Network_equipment(models.Model):
    model_name = models.CharField(max_length=50)
    firm = models.CharField(max_length=50, choices = catalogue.Network_equipment_firms)
    equipment_type = models.CharField(max_length=15, choices = catalogue.Network_equipment_type)
    # Можно устанавливать в стойку
    rackable = models.BooleanField(default=False)
    dhcp_server = models.BooleanField(default=False)
    firewall = models.BooleanField(default=False)
    nat = models.BooleanField(default=False)
    vpn = models.BooleanField(default=False)
    ipv6_ready = models.BooleanField(default=False)
    WiFi = models.CharField(max_length=20, choices = catalogue.Network_equipment_WiFi_type)
    SNMP = models.BooleanField(default=False)
    Web = models.BooleanField(default=False)
    Telnet = models.BooleanField(default=False)
    Serial = models.BooleanField(default=False)
class Printer(models.Model):
    model_name = models.CharField(max_length=50,verbose_name=_("Model name"))
    wifi = models.BooleanField(default=False,verbose_name=_("WiFi connection"))
    ethernet = models.BooleanField(default=False,verbose_name=_("Ethernet connection"))
    lazer = models.BooleanField(default=True,verbose_name=_("Laser printing"))
    firm = models.CharField(max_length=20, choices = catalogue.Printer_firm,verbose_name=_("Firm"))
    color = models.BooleanField(default=False,verbose_name=_("Colored?"))
    v_mono_print = models.IntegerField(verbose_name=_("Monochrome printing speed"))
    v_color_print = models.IntegerField(blank = True, null = True,verbose_name=_("Color printing speed"))
    def __unicode__(self):
        return str(self.id)+';'+self.firm+" "+self.model_name+";color="+str(self.color)+";ethernet="+str(self.ethernet)+";wifi="+str(self.wifi)+";v="+str(self.v_mono_print)+";vc="+str(self.v_color_print)
class Power_suply(models.Model):
    model_name = models.CharField(max_length=50)
    firm = models.CharField(max_length=20, choices = catalogue.Power_suply_firm)
    power = models.IntegerField()
    modular = models.BooleanField(default=False)
    performance = models.DecimalField(max_digits=4,decimal_places=2)
    ATX_version = models.CharField(max_length=10, choices = catalogue.Power_ATX_version)
    number_of_sata = models.DecimalField(max_digits=1,decimal_places=0)
    number_of_molex = models.DecimalField(max_digits=1,decimal_places=0)
class UPS(models.Model):
    """
    модель
    производитель
    количество комп. разъёмов с батареей
    количество комп. разъёмов без батареи
    количество розеток с батарей
    количество розеток без батареи
    защита телефонии
    защита rj-45
    выходная мощность
    время работы
    RS-232
    USB
    ethernet
    LCD-дисплей
    вес
    тип
    """
    model_name = models.CharField(max_length=50)
    firm = models.CharField(max_length=30, choices = catalogue.UPS_firm)
    number_of_comp_connectors_with_batt = models.IntegerField()
    number_of_comp_connectors_without_batt = models.IntegerField()
    number_of_outlets_with_batt = models.IntegerField()
    number_of_outlets_without_batt = models.IntegerField()
    telephone_line_protection = models.BooleanField(default=False)
    lan_protection = models.BooleanField(default=False)
    output_power = models.IntegerField()
    working_time = models.DecimalField(max_digits=4,decimal_places=2)
    rs232_interface = models.BooleanField(default=False)
    usb_interface = models.BooleanField(default=False)
    ethernet_interface = models.BooleanField(default=False)
    lcd_display = models.BooleanField(default=False)
    weight = models.DecimalField(max_digits=4,decimal_places=2)
    type = models.CharField(max_length=30, choices = catalogue.UPS_types)
class Delivery(models.Model):
    model_name = models.CharField(max_length=50)
# class Delivery(models.Model):
#     model_name = models.CharField(max_length=50)
class Motherboard(models.Model):
    model_name = models.CharField(max_length=50, verbose_name=_("Model name"))
    firm = models.CharField(max_length=20, choices = catalogue.Motherboard_firm)
    socket = models.CharField(max_length=20, choices = catalogue.Sockets)
    chipset = models.CharField(max_length=20, choices = catalogue.Motherboard_chipset)
    EFI = models.BooleanField(default=False)
    rom_type = models.CharField(max_length=20, choices = catalogue.Motherboard_rom_types)
    rom_number = models.IntegerField()
    rom_max_value = models.IntegerField()
    rom_frequency = models.CharField(max_length=50)
    FSB  = models.CharField(max_length=50, blank = True, null = True)
    FDD = models.IntegerField()
    IDE = models.IntegerField()
    COM = models.IntegerField()
    USB2 = models.IntegerField()
    USB3 = models.IntegerField()
    PCI_E_number = models.IntegerField()
    PCI_E_type = models.CharField(max_length=10, choices = catalogue.Motherboard_pci_e_types)
    graphics = models.CharField(max_length=10, choices = catalogue.Motherboard_integrated_graphics)
    form_factor = models.CharField(max_length=10, choices = catalogue.Motherboard_form_factor)
    HDMI = models.BooleanField(default=False)
    SLI = models.BooleanField(default=False)
    CrossFire = models.BooleanField(default=False)
    eSATA = models.IntegerField()
    SATA_RAID = models.CharField(max_length=15)
    Ethernet = models.CharField(max_length=20, choices = catalogue.Ethernet_types)
    Ethernet_number = models.IntegerField()
    WiFi = models.CharField(max_length=20, choices = catalogue.WiFi_types)
    Bluetooth = models.BooleanField(default=False)
    Audio = models.CharField(max_length=10, choices = catalogue.Motherboard_audio)
    FireWire = models.IntegerField()
    LPT = models.IntegerField()
    PS_2 = models.IntegerField()
    DisplayPort = models.IntegerField()
    SupportedROM = models.TextField(blank = True, null = True)
    SupportedCPU = models.TextField(blank = True, null = True)
class CPU(models.Model):
    model_name = models.CharField(max_length=50)
    firm = models.CharField(max_length=20, choices = catalogue.CPU_firm)
    socket = models.CharField(max_length=20, choices = catalogue.Sockets)
    frequency = models.CharField(max_length=20)
    core = models.CharField(max_length=20, choices = catalogue.CPU_core)
    L1 = models.CharField(max_length=20, choices = catalogue.CPU_L1)
    L2 = models.CharField(max_length=20, choices = catalogue.CPU_L2)
    L3 = models.CharField(max_length=20, choices = catalogue.CPU_L3)
    technology = models.CharField(max_length=20, choices = catalogue.CPU_technology)
    core_number = models.IntegerField()
    VT = models.BooleanField(default=False)
    integrated_graphics = models.BooleanField(default=False)
    # TODO: добавить описание графики
    TPD = models.CharField(max_length=20)
class Case(models.Model):
    model_name = models.CharField(max_length=50)
    firm = models.CharField(max_length=20, choices = catalogue.Case_firm)
    form_factor = models.CharField(max_length=20, choices = catalogue.Case_form_factor)
    supported_mb_types = models.TextField()
    place_of_power_suply = models.CharField(max_length=20, choices = catalogue.Case_power_suply_place)
    usb_fp = models.IntegerField()
    audio_fp = models.IntegerField()
    eSATA_fp = models.IntegerField()
    eSATA_rp = models.IntegerField()
    FireWire_fp = models.IntegerField()
    FireWire_rp = models.IntegerField()
    number_of_35 = models.IntegerField()
    number_of_525 = models.IntegerField()
    water_ready = models.BooleanField(default=False)
    number_of_extension_slot = models.IntegerField()
    number_of_fan_places = models.IntegerField()
    size = models.CharField(max_length=50)

class CKC(models.Model):
    model_name = models.CharField(max_length=150,verbose_name=_("Model name"))
    def __unicode__(self):
        return str(self.id)+';'+self.model_name
class Telephone_Works(models.Model):
    model_name = models.CharField(max_length=150,verbose_name=_("Model name"))
    def __unicode__(self):
        return str(self.id)+';'+self.model_name

"""
    def __unicode__(self):
        return u";".join((str(self.id),self.name,"\t"+self.worker.fio))
    class Meta:
        ordering = ['priority','due_date']
"""


text:
import pymongo
import urllib2
import urllib
import cookielib
import random
import re
import string
import sys
import getopt

# this is a validation program to make sure that the blog works correctly.
# If you are reading this in clear text, you are probably violating the honor code

# init the global cookie jar
cj = cookielib.CookieJar()
# declare the variables to connect to db
connection = None
db = None
webhost = "localhost:8082"
mongostr = "mongodb://localhost:27017"
db_name = "blog"

# this script will check that homework 3.2 is correct

# makes a little salt
def make_salt(n):
    salt = ""
    for i in range(n):
        salt = salt + random.choice(string.ascii_letters)
    return salt

# this is a validation program to make sure that the blog works correctly.

def create_user(username, password):

    global cj

    try:
        print "Trying to create a test user ", username
        url = "http://{0}/signup".format(webhost)

        data = urllib.urlencode([("email",""),("username",username), ("password",password), ("verify",password)])
        request = urllib2.Request(url=url, data=data)
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        f = opener.open(request)

        users = db.users
        # check that the user is in users collection
        user = users.find_one({'_id':username})
        if (user == None):
            print "Could not find the test user ", username, "in the users collection."
            return False
        print "Found the test user ", username, " in the users collection"

        # check that the user has been built
        result = f.read()
        expr = re.compile("Welcome\s+"+ username)
        if expr.search(result):
            return True

        print "When we tried to create a user, here is the output we got\n"
        print result

        return False
    except:
        print "the request to ", url, " failed, so your blog may not be running."
        raise
        return False

def try_to_login(username, password):

    try:
        print "Trying to login for test user ", username
        url = "http://{0}/login".format(webhost)

        data = urllib.urlencode([("username",username), ("password",password)])
        request = urllib2.Request(url=url, data=data)
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        f = opener.open(request)

        # check for successful login
        result = f.read()
        expr = re.compile("Welcome\s+"+ username)
        if expr.search(result):
            return True

        print "When we tried to login, here is the output we got\n"
        print result
        return False
    except:
        print "the request to ", url, " failed, so your blog may not be running."
        return False

def add_blog_post(title,post,tags):

    try:
        print "Trying to submit a post with title ", title
        data = urllib.urlencode([("body",post), ("subject",title), ("tags",tags)])
        url = "http://{0}/newpost".format(webhost)
        request = urllib2.Request(url=url, data=data)
        cj.add_cookie_header(request)
        opener = urllib2.build_opener()
        f = opener.open(request)

        # check for successful login
        result = f.read()
        expr = re.compile(title + ".+" + post, re.DOTALL)

        if expr.search(result):
            return True

        print "When we tried to post, here is the output we got\n"
        print result
        return False

    except:
        print "the request to ", url, " failed, so your blog may not be running."
        raise

        return False

def add_blog_comment(title,post):

    try:
        print "Trying to submit a blog comment for post with title", title
        url = "http://{0}/newcomment".format(webhost)

        doc = {}
        check_mongo_for_post(title, post, doc)

        permalink = doc['doc']['permalink']

        comment_name = make_salt(12)
        comment_body = make_salt(12)

        data = urllib.urlencode([("commentName",comment_name), ("commentBody",comment_body), ("permalink",permalink)])
        request = urllib2.Request(url=url, data=data)
        cj.add_cookie_header(request)
        opener = urllib2.build_opener()
        f = opener.open(request)

        # check for successful addition of comment on page
        result = f.read()
        expr = re.compile(title + ".+" + post, re.DOTALL)

        if not expr.search(result):
            print "When we tried to find the comment we posted at the  ", url, " here is what we got"
            print result
            return False

        # check for successful addition of comment..retrieve the doc again
        if(not check_mongo_for_post(title, post, doc)):
            print "Could not find comment in database"
            return False

        found = False
        if ('comments' in doc['doc']):
            for comment in doc['doc']['comments']:
                if (comment['body'] == comment_body and comment['author'] == comment_name):
                    found = True

        return found

    except:
        print "the request to ", url, " failed, so your blog may not be running."
        raise

        return False

# grabs the blog index and checks that the posts appear in the right order
def check_blog_index(title1, title2):

    try:
        url = "http://{0}/".format(webhost)
        print "Trying to grab the blog home page at url ", url
        request = urllib2.Request(url=url)
        cj.add_cookie_header(request)
        opener = urllib2.build_opener()
        f = opener.open(request)

        # check for successful login
        result = f.read()
        expr = re.compile(title2 + ".+" + title2, re.DOTALL)

        if expr.search(result):
            return True

        print "When we tried to read the blog index at ", url, " here is what we got"
        print result
        return False

    except:
        print "the request to ", url, " failed, so your blog may not be running."
        raise

        return False

# check that a particular blog post is in the collection
def check_mongo_for_post(title, body, document):

    posts = db.posts
    try:
        post = posts.find_one({'title':title, 'body':body})
        if (post is None):
            print "Can't find post with title ", title, " in collection"
            return False
        document['doc'] = post
        return True
    except:
        print "can' query MongoDB..is it running?"
        raise

        return False

# command line arg parsing to make folks happy who want to run at mongolabs or mongohq
# this functions uses global vars to communicate. forgive me.
def arg_parsing(argv):

    global webhost
    global mongostr
    global db_name

    try:
        opts, args = getopt.getopt(argv, "-p:-m:-d:")
    except getopt.GetoptError:
        print "usage validate.py -p webhost -m mongoConnectString -d databaseName"
        print "\twebhost defaults to {0}".format(webhost)
        print "\tmongoConnectionString default to {0}".format(mongostr)
        print "\tdatabaseName defaults to {0}".format(db_name)
        sys.exit(2)
    for opt, arg in opts:
        if (opt == '-h'):
            print "usage validate.py -p webhost -m mongoConnectString -d databaseName"
            sys.exit(2)
        elif opt in ("-p"):
            webhost = arg
            print "Overriding HTTP host to be ", webhost
        elif opt in ("-m"):
            mongostr = arg
            print "Overriding MongoDB connection string to be ", mongostr
        elif opt in ("-d"):
            db_name = arg
            print "Overriding MongoDB database to be ", db_name

# main section of the code
def main(argv):

    arg_parsing(argv)
    global connection
    global db

    print "Welcome to the HW 3.2 and HW 3.3 validation tester"

    # connect to the db (mongostr was set in arg_parsing)
    connection = pymongo.MongoClient(mongostr)
    db = connection[db_name]

    username = make_salt(7)
    password = make_salt(8)

     # try to create user

    if (create_user(username, password)):
        print "User creation successful. "
         # try to login
        if (try_to_login(username, password)):
            print "User login successful."
        else:
            print "User login failed"
            print "Odd, this weeks's code should do that as given"
            sys.exit(1)

    else:
        print "Sorry, you have not solved it yet."
        sys.exit(1)

    # try to create a blog post
    post1 = make_salt(30)
    title1 = make_salt(30)
    tags1 = make_salt(5) + ", " + make_salt(5) + ", " + make_salt(5)

    if (add_blog_post(title1, post1,tags1)):
        print "Submission of single post successful"
    else:
        print "Unable to create a post"
        sys.exit(1)

    # try to create a second blog post
    post2 = make_salt(30)
    title2 = make_salt(30)
    tags2 = make_salt(5) + ", " + make_salt(5) + ", " + make_salt(5)

    if (add_blog_post(title2, post2,tags2)):
        print "Submission of second post successful"
    else:
        print "Unable to create second post"
        sys.exit(1)

    # now let's make sure that both posts appear on the home page of the blog, in the correct order

    if (check_blog_index(title1, title2)):
        print "Block index looks good."
    else:
        print "Blog index does not have the posts present, ordered correctly"
        sys.exit(1)

    # check for DB data integrity
    if (not check_mongo_for_post(title1, post1, {})):
        print "Can't find blog post in blog db, posts collection with title ", title
        sys.exit(1)
    else:
        print "Found blog post in posts collection"

    print "Tests Passed for HW 3.2. Your HW 3.2 validation code is 89jklfsjrlk209jfks2j2ek"

    # now check that you can post a comment
    if (not add_blog_comment(title1,post1)):
        print "Can't add blog comments (so HW 3.3 not yet complete)"
        sys.exit(1)
    else:
        print "Successfully added blog comments"

    print "Tests Passed for HW 3.3. Your HW 3.3 validation code is jk1310vn2lkv0j2kf0jkfs"

if __name__ == "__main__":
    main(sys.argv[1:])


text:
package me.romankh.resumegenerator.parser;

/**
 * @author Roman Khmelichek
 */
public enum Html5VoidTag {
  AREA("area"),
  BASE("base"),
  BR("br"),
  COL("col"),
  COMMAND("command"),
  EMBED("embed"),
  HR("hr"),
  IMG("img"),
  INPUT("input"),
  KEYGEN("keygen"),
  LINK("link"),
  META("meta"),
  PARAM("param"),
  SOURCE("source"),
  TRACK("track"),
  WBR("wbr");

  private String tag;

  Html5VoidTag(String tag) {
    this.tag = tag;
  }

  String getTag() {
    return tag;
  }

  static Html5VoidTag findTag(String tag) {
    for (Html5VoidTag html5VoidTag : values()) {
      if (html5VoidTag.tag.equals(tag))
        return html5VoidTag;
    }

    return null;
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 9(1-6): 31 (1955)

#### Original name
Irene sororcula var. vernoniae F. Stevens

### Remarks
null


text:
package io.tetrapod.web;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.channel.socket.SocketChannel;
import io.tetrapod.core.Session;
import io.tetrapod.core.StructureFactory;
import io.tetrapod.core.json.JSONObject;
import io.tetrapod.core.logging.CommsLogger;
import io.tetrapod.core.rpc.Structure;
import io.tetrapod.core.serialize.datasources.*;
import io.tetrapod.protocol.core.*;

abstract class WebSession extends Session {
   private static final Logger   logger       = LoggerFactory.getLogger(WebSession.class);

   protected final AtomicInteger requestCount = new AtomicInteger(0);
   private int                   alternateId;

   public WebSession(SocketChannel channel, Session.Helper helper) {
      super(channel, helper);
   }

   public SessionType getSessionType() {
      return SessionType.WEB;
   }

   abstract protected Object makeFrame(JSONObject jo, boolean keepAlive);

   protected Structure readRequest(RequestHeader header, JSONObject params) throws IOException {
      Structure request = StructureFactory.make(header.contractId, header.structId);
      if (request == null) {
         logger.error("Could not find request structure contractId={} structId-{}", header.contractId, header.structId);
         return null;
      }
      request.read(new WebJSONDataSource(params, request.tagWebNames()));

      CommsLogger.append(this, false, header, request);
      return request;
   }

   @Override
   protected Object makeFrame(Structure header, Structure payload, byte envelope) {
      try {
         JSONObject jo = extractHeader(header);
         JSONDataSource jd = new WebJSONDataSource(jo, payload.tagWebNames());
         payload.write(jd);
         return makeFrame(jo, true);
      } catch (IOException e) {
         logger.error("Could not make web frame for {}", header.dump());
         return null;
      }
   }

   protected JSONObject toJSON(Structure header, ByteBuf payloadBuf, byte envelope) {
      try {
         JSONObject jo = extractHeader(header);
         Structure payload = StructureFactory.make(jo.optInt("_contractId"), jo.optInt("_structId"));
         ByteBufDataSource bd = new ByteBufDataSource(payloadBuf);
         payload.read(bd);
         JSONDataSource jd = new WebJSONDataSource(jo, payload.tagWebNames());
         payload.write(jd);
         return jo;
      } catch (Exception e) {
         logger.error("Could not make web frame for {}", header.dump());
         return null;
      }
   }

   @Override
   protected Object makeFrame(Structure header, ByteBuf payloadBuf, byte envelope) {
      JSONObject jo = toJSON(header, payloadBuf, envelope);
      if (jo != null) {
         return makeFrame(jo, true);
      } else {
         return null;
      }
   }

   protected JSONObject extractHeader(Structure header) {
      JSONObject jo = new JSONObject();
      switch (header.getStructId()) {
         case RequestHeader.STRUCT_ID:
            RequestHeader reqH = (RequestHeader) header;
            jo.put("_contractId", reqH.contractId);
            jo.put("_structId", reqH.structId);
            jo.put("_requestId", reqH.requestId);
            break;

         case ResponseHeader.STRUCT_ID:
            ResponseHeader respH = (ResponseHeader) header;
            jo.put("_contractId", respH.contractId);
            jo.put("_structId", respH.structId);
            jo.put("_requestId", respH.requestId);
            jo.put("_contextId", String.format("%016x", respH.contextId));
            break;

         case MessageHeader.STRUCT_ID:
            MessageHeader messH = (MessageHeader) header;
            jo.put("_contractId", messH.contractId);
            jo.put("_structId", messH.structId);
            jo.put("_topicId", messH.topicId);
            jo.put("_contextId", String.format("%016x", messH.contextId));
            break;
      }
      return jo;
   }

   public synchronized void setAlternateId(int alternateId) {
      this.alternateId = alternateId;
   }

   public synchronized int getAlternateId() {
      return alternateId;
   }

}


text:
<!DOCTYPE html>

    <title>aadm: weekly snaps 6</title>

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="http://aadm.github.io/favicon.png" rel="icon">

<link rel="canonical" href="http://aadm.github.io/2012-09-14-weekly-snaps-6.html">

        <meta name="author" content="Alessandro Amato del Monte" />
        <meta name="keywords" content="photo" />
        <meta name="description" content="I did a few experiments with the camera over the past two weekends. Thought to share a few pictures here, even if they are not particularly inspired shots. But if you're trying to find how damn good is the D7000 sensor, just look at the green tomato shot. All …" />

        <meta property="og:site_name" content="aadm" />
        <meta property="og:type" content="article"/>
        <meta property="og:title" content="weekly snaps 6"/>
        <meta property="og:url" content="http://aadm.github.io/2012-09-14-weekly-snaps-6.html"/>
        <meta property="og:description" content="I did a few experiments with the camera over the past two weekends. Thought to share a few pictures here, even if they are not particularly inspired shots. But if you're trying to find how damn good is the D7000 sensor, just look at the green tomato shot. All …"/>
        <meta property="article:published_time" content="2012-09-14" />
            <meta property="article:section" content="misc" />
            <meta property="article:tag" content="photo" />
            <meta property="article:author" content="Alessandro Amato del Monte" />

        <link rel="stylesheet" href="http://aadm.github.io/theme/css/bootstrap.journal.min.css" type="text/css"/>
    <link href="http://aadm.github.io/theme/css/font-awesome.min.css" rel="stylesheet">

    <link href="http://aadm.github.io/theme/css/pygments/tango.css" rel="stylesheet">
        <link href="http://aadm.github.io/theme/css/typogrify.css" rel="stylesheet">
    <link rel="stylesheet" href="http://aadm.github.io/theme/css/style.css" type="text/css"/>
        <link href="http://aadm.github.io/static/custom.css" rel="stylesheet">

        <link href="http://aadm.github.io/feeds/all.atom.xml" type="application/atom+xml" rel="alternate"
              title="aadm ATOM Feed"/>

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
                Toggle navigation

            </button>

aadm

                        weekly snaps 6

    Date

        <time datetime="2012-09-14T00:00:00+02:00"> 2012-09-14</time>

Tags
	photo

I did a few experiments with the camera over the past two weekends. Thought to share a few pictures here, even if they are not particularly inspired shots. But if you're trying to find how damn good is the D7000 sensor, just look at the green tomato shot.

All shots taken at "Il Montale", Sala Baganza (Parma), with my usual gear (Nikon D7000, 35mm f/1.8, 50mm f/1.4, Tokina 12-24mm f/4).

I was told to take photos of a stupid tree. Man, it is hard to shoot a stupid tree.

Green tomato.

A view of Parma by night #1.

A view of Parma by night #2.

Segafredo.

Segafredo (Kodak Tri-X 400 filter).

Nothing to see here.

weekly snaps

This post is #6 of the "weekly snaps" series:

                weekly snaps 1

                weekly snaps 2

                weekly snaps 3

                weekly snaps 4

                weekly snaps 5

                weekly snaps 6

                weekly snaps 7

                weekly snaps 9

                weekly snaps 10

                weekly snaps 11

                weekly snaps 12

                weekly snaps 13

                weekly snaps 14 / san siro

                weekly snaps 15 / atmosfere

                weekly snaps 16 / quarantuno

                weekly snaps 17

Related Posts:

the end of gear addiction (addendum)

the end of gear addiction

best sensor ever

two sides of photography

bari

 PREVIOUS

NEXT

© 2005-2019 Alessandro Amato del Monte

  Creative Commons Attribution 4.0 International License

 TOP


text:
package testclasses;

import de.unifreiburg.cs.proglang.jgs.support.DynamicLabel;

public class MakeHigh {

	public static String field = "initfield";

	/**
	 * Test if setting all kinds of variable types works properly.
	 * @param args The arguments are ignored in this method.
	 */
	public static void main(String[] args) {
		String local = "initlocal";
		String[] arr = {"a", "b"};
		String[][] mularr = { {"aa"},{"bb"}};

		local = DynamicLabel.makeHigh(local);
		local = DynamicLabel.makeHigh("bg");
		field = DynamicLabel.makeHigh(field);
		arr[0] = DynamicLabel.makeHigh(arr[1]);
		mularr[1] = DynamicLabel.makeHigh(mularr[1]);
	}

}


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/schemeDarkTurquoise</item>
        <item name="colorPrimaryDark">@color/schemeBlack</item>
        <item name="colorAccent">@color/schemeLightGrey</item>
    </style>

</resources>


text:
require( "DotaHS_AI_FollowerBase" )

--
-- TODO:
--

--------------------------------------------------------------------------------
-- AI / Luna
--------------------------------------------------------------------------------
if AI_Luna == nil then
	AI_BehaviorTreeBuilder_Luna = class({}, nil, AI_BehaviorTreeBuilder)

	AI_Luna = class({}, nil, AI_FollowerBase)

	AI_Luna.btreeBuilderClass = AI_BehaviorTreeBuilder_Luna

	-- Hero specific properties
	AI_Luna.unitClassname	= "npc_dota_hero_luna"
	AI_Luna.unitShortname	= "Luna"

	AI_Luna.vAbilityNameList = {
		"luna_lucent_beam",		-- 1
		"luna_moon_glaive",		-- 2
		"luna_lunar_blessing",	-- 3
		"luna_eclipse",			-- 4
		"attribute_bonus",		-- 5
	}
	AI_Luna.vAbilityUpgradeSequence = {
		3, 2, 3, 1, 3,
		4, 3, 2, 2, 2,
		4, 1, 1, 1, 5,
		4, 5, 5, 5, 5,
		5, 5, 5, 5, 5,
	}

	AI_Luna.vItemPropertyRating = {
		damage	= 5,
		str		= 2,
		agi		= 5,
		int		= 1,
		as		= 5,
		armor	= 2,
		mr		= 2,
		hp		= 2,
		mana	= 1,
		hpreg	= 3,
		manareg	= 2,
		ms		= 3,
	}
end

--------------------------------------------------------------------------------
function AI_Luna:constructor( unit )
	AI_FollowerBase.constructor( self, unit )

	-- Abilities
	self.ABILITY_lucent_beam	= self.vAbilities["luna_lucent_beam"]
	self.ABILITY_eclipse		= self.vAbilities["luna_eclipse"]
end

--------------------------------------------------------------------------------
-- CONDITIONS
--------------------------------------------------------------------------------
function AI_Luna:COND_ReadyForEclipse()
	if not self.ABILITY_eclipse:IsFullyCastable() then
		return false
	end

	-- Num enemies
	local radius = DotaHS_GetAbilitySpecialValue( self.ABILITY_eclipse, "radius" )
	radius = radius * 0.75
	local numEnemies = #self:FindEnemiesInRange( radius )

	if numEnemies < 7 then
		return false
	end

	return true
end

--------------------------------------------------------------------------------
-- ACTIONS
--------------------------------------------------------------------------------
function AI_Luna:ACT_CastEclipse()
	return self:GetCastingAbilityState( self.ABILITY_eclipse, function ()
		self:CreateOrder( DOTA_UNIT_ORDER_CAST_NO_TARGET, nil, self.ABILITY_eclipse )
	end )
end

--------------------------------------------------------------------------------
-- Behavior Tree Builder
--------------------------------------------------------------------------------
function AI_BehaviorTreeBuilder_Luna:ARRAY_DecisionMakingChildren()
	local array = AI_BehaviorTreeBuilder.ARRAY_DecisionMakingChildren( self )

	-- Modify
	self:InsertBefore( array, "Flee", self:NODE_Eclipse() )

	return array
end

--------------------------------------------------------------------------------
function AI_BehaviorTreeBuilder_Luna:NODE_Eclipse()
	return Decorator_CooldownRandomAlsoFailure( 0.5, 1.0,
		SequenceNode( "Eclipse", {
			ConditionNode( "Ready?", "COND_ReadyForEclipse" ),
			ActionNode( "Cast Eclipse", "ACT_CastEclipse" ),
		} )
	)
end


text:
export default function commonHead($){
    $("head")
        .append('<script src="http://localhost:35729/livereload.js"></script>')
        .append(`<title>${this.name} | ${this.req.url.replace("/", "")}</title>`)
        .append("<link rel='stylesheet' type='text/css' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'/>")
        .append("<link rel='stylesheet' type='text/css' href='/styles/cyberian-common.css'/>")

    $("body").append('<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>');
}