text:
package org.hisp.dhis.web.ohie.csd.domain;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import java.util.Date;

/**
 * @author Morten Olav Hansen <mortenoh@gmail.com>
 */
@XmlAccessorType( XmlAccessType.FIELD )
@XmlType( name = "operatingHours", namespace = "urn:ihe:iti:csd:2013" )
public class OperatingHours
{
    @XmlElement( name = "openFlag", namespace = "urn:ihe:iti:csd:2013" )
    private String openFlag;

    @XmlElement( name = "dayOfTheWeek", namespace = "urn:ihe:iti:csd:2013" )
    private String dayOfTheWeek;

    @XmlElement( name = "beginningHour", namespace = "urn:ihe:iti:csd:2013" )
    private Date beginningHour;

    @XmlElement( name = "endingHour", namespace = "urn:ihe:iti:csd:2013" )
    private Date endingHour;

    @XmlElement( name = "beginEffectiveDate", namespace = "urn:ihe:iti:csd:2013" )
    private Date beginEffectiveDate;

    public OperatingHours()
    {
    }

    public String getOpenFlag()
    {
        return openFlag;
    }

    public void setOpenFlag( String openFlag )
    {
        this.openFlag = openFlag;
    }

    public String getDayOfTheWeek()
    {
        return dayOfTheWeek;
    }

    public void setDayOfTheWeek( String dayOfTheWeek )
    {
        this.dayOfTheWeek = dayOfTheWeek;
    }

    public Date getBeginningHour()
    {
        return beginningHour;
    }

    public void setBeginningHour( Date beginningHour )
    {
        this.beginningHour = beginningHour;
    }

    public Date getEndingHour()
    {
        return endingHour;
    }

    public void setEndingHour( Date endingHour )
    {
        this.endingHour = endingHour;
    }

    public Date getBeginEffectiveDate()
    {
        return beginEffectiveDate;
    }

    public void setBeginEffectiveDate( Date beginEffectiveDate )
    {
        this.beginEffectiveDate = beginEffectiveDate;
    }
}


text:
OC.L10N.register(
    "user_webdavauth",
    {
    "WebDAV Authentication" : "WebDAV Authentication",
    "Address:" : "Address:",
    "Save" : "Save",
    "The user credentials will be sent to this address. This plugin checks the response and will interpret the HTTP statuscodes 401 and 403 as invalid credentials, and all other responses as valid credentials." : "The user credentials will be sent to this address. This plugin checks the response and will interpret the HTTP statuscodes 401 and 403 as invalid credentials, and all other responses as valid credentials."
},
"nplurals=2; plural=(n != 1);");

redpajama_set_name: RedPajamaGithub


text:
id: 5900f40a1000cf542c50ff1d
challengeType: 5
title: 'Problem 158: Exploring strings for which only one character comes lexicographically after its neighbour to the left'
videoUrl: ''
localeTitle: 'Problema 158: Explorar cadenas para las que solo un personaje viene lexicográficamente después de su vecino a la izquierda'
---

## Description

 Tomando tres letras diferentes de las 26 letras del alfabeto, se pueden formar cadenas de caracteres de longitud tres. Los ejemplos son 'abc', 'hat' y 'zyx'. Cuando estudiamos estos tres ejemplos, vemos que para 'abc' dos personajes vienen lexicográficamente después de su vecino a la izquierda. Para 'hat' hay exactamente un personaje que viene lexicográficamente después de su vecino a la izquierda. Para 'zyx' hay cero caracteres que vienen lexicográficamente después de su vecino a la izquierda. En total, hay 10400 cadenas de longitud 3 para las cuales exactamente un personaje viene lexicográficamente después de su vecino a la izquierda. Ahora consideramos cadenas de n ≤ 26 caracteres diferentes del alfabeto. Para cada n, p (n) es el número de cadenas de longitud n para las cuales exactamente un personaje aparece lexicográficamente después de su vecino a la izquierda. ¿Cuál es el valor máximo de p (n)?

## Instructions

## Tests

```yml
tests:
  - text: <code>euler158()</code> debe devolver 409511334375.
    testString: 'assert.strictEqual(euler158(), 409511334375, "<code>euler158()</code> should return 409511334375.");'

```

## Challenge Seed

```js
function euler158() {
  // Good luck!
  return true;
}

euler158();

```

## Solution

```js
// solution required
```


text:
module Semaphoreapp
  class Deploy < Base

    def get_information
      Semaphoreapp::DeployInformation.build(
        Semaphoreapp::JsonApi.get_deploy_information(project_hash_id, server_id, deploy_number)
      )
    end

    def get_log
      Semaphoreapp::DeployLog.build(
        Semaphoreapp::JsonApi.get_deploy_log(project_hash_id, server_id, deploy_number)
      )
    end

    def self.build(source, project_hash_id, deploy_number)
      super(source, project_hash_id, deploy_number)
    end

    private

    def self.build_from_hash(build, project_hash_id, deploy_number)
      super do |hash|
        hash['commit'] = Semaphoreapp::Commit.build(hash['commit'])
        hash['project_hash_id'] = project_hash_id
        hash['deploy_number'] = deploy_number
      end
    end

  end
end


text:
jQuery(function($) {

  scrollConverter.activate();

  $('body > header a').click(function(e) {
    var href = $(this).attr('href');
    $('html, body').stop().animate({scrollLeft: $(href).offset().left},  { queue: false, duration: 1000});
    $('body > header a').parent().removeClass('active');
    $(this).parent().addClass('active');
    e.preventDefault();
  });

  $('body > header h1').css('cursor', 'pointer');
  $('body > header h1').click(function(e) {
    var href = "#quebec-numerique";
    $('html, body').stop().animate({scrollLeft: $(href).offset().left},  { queue: false, duration: 1000});
    e.preventDefault();
  });

  $('.goto-section a').click(function(e) {
    var href = $(this).attr('href');
    $('html, body').stop().animate({scrollLeft: $(href).offset().left},  { queue: false, duration: 1000});
    e.preventDefault();
  });

  $('.buttonjs').each(function(){
    var content = $(this).html();
    var classes = $(this).attr('class');
    var newButton = '<button class="'+classes+'">'+content+'</button>';
    $(this).replaceWith(newButton);
  });

  $(document.body).on('click', '.our-events .nav-links button.right', function() {
    var windowWidth = $(window).width();
    $('.our-events .event-list').animate({marginLeft : '-='+windowWidth},500);

    var articleIndex = $('.our-events article').index($(this).parents('article'))+1;
    $('.our-events .event-nav li').removeClass('active');
    $('.our-events .event-nav li').eq(articleIndex).addClass('active');
  });

  $(document.body).on('click', '.our-events .nav-links button.left', function() {
    var windowWidth = $(window).width();
    $('.our-events .event-list').animate({marginLeft : '+='+windowWidth},500);

    var articleIndex = $('.our-events article').index($(this).parents('article'))-1;
    $('.our-events .event-nav li').removeClass('active');
    $('.our-events .event-nav li').eq(articleIndex).addClass('active');
  });

  $(document.body).on('click', '.our-events .event-nav .buttonjs', function() {
    var windowWidth = $(window).width();
    var posActiveSlide = $('.event-nav .active').index();
    var newPosActiveSlide = $(this).parent().index();
    var diffPosSlides = newPosActiveSlide - posActiveSlide;
    var newActiveSlidePosition = Math.abs(diffPosSlides) * windowWidth;

    $('.our-events .event-list').animate({marginLeft : (diffPosSlides < 0 ? '+=' : '-=') + newActiveSlidePosition},500);

    $('.our-events .event-nav li').removeClass('active');
    $('.our-events .event-nav li').eq(newPosActiveSlide).addClass('active');
  });

  $(window).scroll(
    // Détecte la fin du scroll
    function(){
      clearTimeout($.data(this, "scrolltimeout"));
      $.data(this, "scrolltimeout", setTimeout(function() {
        if($(window).width() < 768 && $(window).scrollLeft() != getPageActive(2)){
          $('html, body').stop().animate({scrollLeft: getPageActive(2)}, { queue: false, duration: 100, easing: "swing" });
          updateMenu();
          updateHash();
        }
        else if((($(window).scrollLeft() + $(window).width()) - getPageActive(1) < ($(window).width() * 0.15) || getPageActive(1) - $(window).scrollLeft() < ($(window).width() * 0.15)) && $(window).scrollLeft() != getPageActive(2)){
          $('html, body').stop().animate({scrollLeft: getPageActive(2)}, { queue: false, duration: 100, easing: "swing" });
          updateMenu();
          updateHash();
        }
        else{
          updateMenu();
          updateHash();
        }
      }, 500));
      window.pageactive = getPageActive(2, 'id');
      $(window).clearQueue();
      $('html, body').clearQueue();
    }
    );

});

/* Fonctions */

function getPageActive(breakpoint,type){

  /* Cette fonction retourne le offset left de la page active si le paramètre de type n'est pas spécifié.
     Si le paramètre de type est égale à "id", la fonction retourne le id de la page active
     Si le paramètre de type est égale à "class", la fonction retourne la classe de la page active */

  // Sections breakpoints
  var pos_home        =   $('#quebec-numerique').offset().left;
  var pos_about       =   $('#a-propos').offset().left;
  var pos_events      =   $('#evenements').offset().left;
  var pos_ourevents   =   $('#nos-evenements').offset().left;
  var pos_place       =   $('#le-lieu').offset().left;
  var pos_whoarewe    =   $('#qui-sommes-nous').offset().left;
  var pos_contact     =   $('#nous-contacter').offset().left;

  var pos_active = $(window).scrollLeft() + ($(window).width() / breakpoint);
  var page_active = "";

  if(pos_home < pos_active && pos_active <= pos_about){
      // Accueil
      switch(type){
        case 'id': page_active = 'quebec-numerique'; break;
        case 'class' : page_active = 'home'; break;
        default: page_active = pos_home; break;
      }
    }
    else if(pos_about < pos_active && pos_active <= pos_events){
      // À propos
      switch(type){
        case 'id': page_active = 'a-propos'; break;
        case 'class' : page_active = 'about'; break;
        default: page_active = pos_about; break;
      }
    }
    else if(pos_events < pos_active && pos_active <= pos_ourevents){
      // Évènements
      switch(type){
        case 'id': page_active = 'evenements'; break;
        case 'class' : page_active = 'events'; break;
        default: page_active = pos_events; break;
      }
    }
    else if(pos_ourevents < pos_active && pos_active <= pos_place){
      // Nos évènements
      switch(type){
        case 'id': page_active = 'nos-evenements'; break;
        case 'class' : page_active = 'our-events'; break;
        default: page_active = pos_ourevents; break;
      }
    }
    else if(pos_place < pos_active && pos_active <= pos_whoarewe){
      // Le lieu
      switch(type){
        case 'id': page_active = 'le-lieu'; break;
        case 'class' : page_active = 'place'; break;
        default: page_active = pos_place; break;
      }
    }
    else if(pos_whoarewe < pos_active && pos_active <= pos_contact){
      // Qui sommes nous
      switch(type){
        case 'id': page_active = 'qui-sommes-nous'; break;
        case 'class' : page_active = 'who-are-we'; break;
        default: page_active = pos_whoarewe; break;
      }
    }
    else if(pos_contact < pos_active && pos_active <= $(document).width()){
      // Contact
      switch(type){
        case 'id': page_active = 'nous-contacter'; break;
        case 'class' : page_active = 'contact'; break;
        default: page_active = pos_contact; break;
      }
    }

    return page_active;
  }

function getPageActivePos(pageID){

  /* Cette fonction retourne la position de la page passée en paramètre */

  // Sections positions
  var positions = {
    'quebec-numerique' : $('#quebec-numerique').offset().left,
    'a-propos' : $('#a-propos').offset().left,
    'evenements' : $('#evenements').offset().left,
    'nos-evenements' : $('#nos-evenements').offset().left,
    'le-lieu' : $('#le-lieu').offset().left,
    'qui-sommes-nous' : $('#qui-sommes-nous').offset().left,
    'nous-contacter' : $('#nous-contacter').offset().left
  };

  return positions[pageID];

}

function updateHash(){
  var hash = (location.hash != "" ? location.hash : "#quebec-numerique");
  if(hash != "#" + getPageActive(2,'id')){
    if(history.pushState) {
      history.pushState(null, null, '#' + getPageActive(2,'id'));
    } else {
      // Fallback old browsers
      //location.hash = '#' + getPageActive(2,'id');
    }
  }
}

function updateMenu(){
  $('body > header a').parent().removeClass('active');
  $('body > header li.' + getPageActive(2,'class')).addClass('active');
}


text:
package com.amazonaws.services.networkmanager.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Describes a resource count.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class NetworkResourceCount implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The resource type.
     *

     */
    private String resourceType;
    /**
     *

     * The resource count.
     *

     */
    private Integer count;

    /**
     *

     * The resource type.
     *

     *
     * @param resourceType
     *        The resource type.
     */

    public void setResourceType(String resourceType) {
        this.resourceType = resourceType;
    }

    /**
     *

     * The resource type.
     *

     *
     * @return The resource type.
     */

    public String getResourceType() {
        return this.resourceType;
    }

    /**
     *

     * The resource type.
     *

     *
     * @param resourceType
     *        The resource type.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public NetworkResourceCount withResourceType(String resourceType) {
        setResourceType(resourceType);
        return this;
    }

    /**
     *

     * The resource count.
     *

     *
     * @param count
     *        The resource count.
     */

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

    /**
     *

     * The resource count.
     *

     *
     * @return The resource count.
     */

    public Integer getCount() {
        return this.count;
    }

    /**
     *

     * The resource count.
     *

     *
     * @param count
     *        The resource count.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public NetworkResourceCount withCount(Integer count) {
        setCount(count);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getResourceType() != null)
            sb.append("ResourceType: ").append(getResourceType()).append(",");
        if (getCount() != null)
            sb.append("Count: ").append(getCount());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof NetworkResourceCount == false)
            return false;
        NetworkResourceCount other = (NetworkResourceCount) obj;
        if (other.getResourceType() == null ^ this.getResourceType() == null)
            return false;
        if (other.getResourceType() != null && other.getResourceType().equals(this.getResourceType()) == false)
            return false;
        if (other.getCount() == null ^ this.getCount() == null)
            return false;
        if (other.getCount() != null && other.getCount().equals(this.getCount()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getResourceType() == null) ? 0 : getResourceType().hashCode());
        hashCode = prime * hashCode + ((getCount() == null) ? 0 : getCount().hashCode());
        return hashCode;
    }

    @Override
    public NetworkResourceCount clone() {
        try {
            return (NetworkResourceCount) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.networkmanager.model.transform.NetworkResourceCountMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
from django.http import HttpResponseRedirect
from datetime import datetime
from django.core.urlresolvers import reverse
from meregistro.shortcuts import my_render
from apps.seguridad.decorators import login_required, credential_required
from django.db import connection
from datetime import date
import csv
from apps.reportes.models import Reporte

ITEMS_PER_PAGE = 100000

@login_required
@credential_required('reportes_seguimiento_cohortes')
def seguimiento(request):
    ambito = request.get_perfil().ambito
    sql = Reporte.get_sql_file_content('417_seguimiento_cohortes_b.sql').replace('{{AMBITO_PATH}}', "'" + str(ambito.path) + "%%'")

    cursor = connection.cursor()
    cursor.execute(sql)

    filename = 'seguimiento_cohortes_' + str(date.today()) + '.xls'
    reporte = Reporte(headers=[\
        'JURISDICCIÓN',\
        'GESTIÓN',\
        'CLAVE',\
        'TIPO',\
        'CUE',\
        'ESTABLECIMIENTO',\
        'CARRERA',\
        'COHORTE',\
        'CURSADA',\
        'INSCRIPTOS',\
        'SOLO CURSAN NUEVAS UNIDADES',\
        'SOLO RECURSAN NUEVAS UNIDADES',\
        'RECURSAN Y CURSAN NUEVAS UNIDADES',\
        'NO CURSAN',\
        'EGRESADOS',\
        'INICIAL',\
        'CONTÍNUA',\
        'INVESTIGACIÓN',\
        'APOYO',\
        'INICIAL',\
        'PRIMARIA',\
        'MEDIA',\
        'SUPERIOR'\
    ], filename=filename)
    for row in Reporte.dictfetchall(cursor):
        reporte.rows.append([\
            row['jurisdiccion'].encode('utf8') if row['jurisdiccion'] else '',\
            row['gestion'].encode('utf8') if row['gestion'] else '',\
            row['clave'] if row['clave'] else '',\
            row['tipo'].encode('utf8') if row['tipo'] else '',\
            row['cue'].encode('utf8') if row['cue'] else '',\
            row['establecimiento'].encode('utf8') if row['establecimiento'] else '',\
            row['carrera'].encode('utf8') if row['carrera'] else '',\
            row['cohorte'] if row['cohorte'] else '',\
            row['cursada'] if row['cursada'] else '',\
            row['inscriptos'] if row['inscriptos'] else '',\
            row['solo_cursan_nuevas_unidades'] if row['solo_cursan_nuevas_unidades'] else '',\
            row['solo_recursan_nuevas_unidades'] if row['solo_recursan_nuevas_unidades'] else '',\
            row['recursan_cursan_nuevas_unidades'] if row['recursan_cursan_nuevas_unidades'] else '',\
            row['no_cursan'] if row['no_cursan'] else '',\
            row['egresados'] if row['egresados'] else '',\
            row['inicial'].encode('utf8') if row['inicial'] else '',\
            row['continua'].encode('utf8') if row['continua'] else '',\
            row['investigacion'].encode('utf8') if row['investigacion'] else '',\
            row['apoyo'].encode('utf8') if row['apoyo'] else '',\
            row['inicial'].encode('utf8') if row['inicial'] else '',\
            row['primaria'].encode('utf8') if row['primaria'] else '',\
            row['media'].encode('utf8') if row['media'] else '',\
            row['superior'].encode('utf8') if row['superior'] else ''\
        ])
    return reporte.as_csv()


text:
category: portfolio
layout: project
title: 'aquellex.ws'
description: 'Website design for Aquellex, a chiptune musician based in Australia.'
year: 2017
header_image: preview.png
project_url: 'https://aquellex.ws'
redirect_from:
  - 'projects/design/2017/aquellexws'
tags:
  - 'design'
  - 'react'
  - 'javascript'
---

<figure>
  <img src="./preview.png" alt="aquellex.ws">
</figure>

**[Aquellex](https://aquellex.ws)** is an Australian chiptune musician. I was tasked to assist him in implementing an existing HTML/CSS design on an easy-to-use static-site generation system. This was also a chance for me to try out [Gatsby.js](https://www.gatsbyjs.org/), which is a really sleek static-site generator powered by React.

This was a fun project overall, since I got the chance to play around with modern web technologies and implement it on a retro-themed website. If chiptune music is your thing, go check out his music!

## Technologies Used

- [React](https://reactjs.org/)
- [Gatsby.js](https://www.gatsbyjs.org/)
- [CSS Modules](https://github.com/css-modules/css-modules)


text:
const AppConstants = {
    api: 'http://localhost:3000/api',
    jwtKey: 'jwtToken',
    appName: 'Starter'
};

export default AppConstants;


text:
package invtweaks.forge.asm;

import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.*;

public class ASMHelper {
    /**
     * Generate a new method "boolean name()", returning a constant value
     *
     * @param clazz  Class to add method to
     * @param name   Name of method
     * @param retval Return value of method
     */
    public static void generateBooleanMethodConst(ClassNode clazz, String name, boolean retval) {
        MethodNode method = new MethodNode(Opcodes.ASM4, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name, "()Z", null,
                null);
        InsnList code = method.instructions;

        code.add(new InsnNode(retval ? Opcodes.ICONST_1 : Opcodes.ICONST_0));
        code.add(new InsnNode(Opcodes.IRETURN));

        clazz.methods.add(method);
    }

    /**
     * Generate a new method "int name()", returning a constant value
     *
     * @param clazz  Class to add method to
     * @param name   Name of method
     * @param retval Return value of method
     */
    public static void generateIntegerMethodConst(ClassNode clazz, String name, short retval) {
        MethodNode method = new MethodNode(Opcodes.ASM4, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name, "()I", null,
                null);
        InsnList code = method.instructions;

        // Probably doesn't make a huge difference, but use BIPUSH if the value is small enough.
        if(retval >= Byte.MIN_VALUE && retval <= Byte.MAX_VALUE) {
            code.add(new IntInsnNode(Opcodes.BIPUSH, retval));
        } else {
            code.add(new IntInsnNode(Opcodes.SIPUSH, retval));
        }
        code.add(new InsnNode(Opcodes.IRETURN));

        clazz.methods.add(method);
    }

    /**
     * Generate a forwarding method of the form "T name() { return this.forward(); }
     *
     * @param clazz       Class to generate new method on
     * @param name        Name of method to generate
     * @param forwardname Name of method to call
     * @param rettype     Return type of method
     */
    public static void generateSelfForwardingMethod(ClassNode clazz, String name, String forwardname, Type rettype) {
        MethodNode method = new MethodNode(Opcodes.ASM4, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name,
                "()" + rettype.getDescriptor(), null, null);

        populateSelfForwardingMethod(method, forwardname, rettype, Type.getObjectType(clazz.name));

        clazz.methods.add(method);
    }

    /**
     * Generate a forwarding method of the form "static T name(S object) { return object.forward(); }
     *
     * @param clazz       Class to generate new method on
     * @param name        Name of method to generate
     * @param forwardname Name of method to call
     * @param rettype     Return type of method
     */
    public static void generateStaticForwardingMethod(ClassNode clazz, String name, String forwardname, Type rettype,
                                                      Type argtype) {
        MethodNode method = new MethodNode(Opcodes.ASM4,
                Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name,
                "()" + rettype.getDescriptor(), null, null);

        populateSelfForwardingMethod(method, forwardname, rettype, argtype);

        clazz.methods.add(method);
    }

    /**
     * Generate a forwarding method of the form "T name() { return Class.forward(this); }
     *
     * @param clazz       Class to generate new method on
     * @param name        Name of method to generate
     * @param forwardname Name of method to call
     * @param rettype     Return type of method
     */
    public static void generateForwardingToStaticMethod(ClassNode clazz, String name, String forwardname, Type rettype,
                                                        Type fowardtype) {
        MethodNode method = new MethodNode(Opcodes.ASM4, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name,
                "()" + rettype.getDescriptor(), null, null);

        populateForwardingToStaticMethod(method, forwardname, rettype, Type.getObjectType(clazz.name), fowardtype);

        clazz.methods.add(method);
    }

    /**
     * Generate a forwarding method of the form "T name() { return Class.forward(this); }
     *
     * @param clazz       Class to generate new method on
     * @param name        Name of method to generate
     * @param forwardname Name of method to call
     * @param rettype     Return type of method
     * @param thistype    Type to treat 'this' as for overload searching purposes
     */
    public static void generateForwardingToStaticMethod(ClassNode clazz, String name, String forwardname, Type rettype,
                                                        Type fowardtype, Type thistype) {
        MethodNode method = new MethodNode(Opcodes.ASM4, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name,
                "()" + rettype.getDescriptor(), null, null);

        populateForwardingToStaticMethod(method, forwardname, rettype, thistype, fowardtype);

        clazz.methods.add(method);
    }

    /**
     * Replace a method's code with a forward to another method on itself (or the first argument of a static method as
     * the argument takes the place of this)
     *
     * @param method      Method to replace code of
     * @param forwardname Name of method to forward to
     * @param thistype    Type of object method is being replaced on
     */
    public static void replaceSelfForwardingMethod(MethodNode method, String forwardname, Type thistype) {
        Type methodType = Type.getMethodType(method.desc);

        method.instructions.clear();

        populateSelfForwardingMethod(method, forwardname, methodType.getReturnType(), thistype);
    }

    /**
     * Generate a forwarding method of the form "T name(S object) { return object.forward(); }
     *
     * @param clazz       Class to generate new method on
     * @param name        Name of method to generate
     * @param forwardname Name of method to call
     * @param rettype     Return type of method
     * @param argtype     Type of object to call method on
     */
    public static void generateForwardingMethod(ClassNode clazz, String name, String forwardname, Type rettype,
                                                Type argtype) {
        MethodNode method = new MethodNode(Opcodes.ASM4, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name,
                "()" + rettype.getDescriptor(), null, null);

        populateForwardingMethod(method, forwardname, rettype, argtype, Type.getObjectType(clazz.name));

        clazz.methods.add(method);
    }

    /**
     * Replace a method's code with a forward to an method on its first argument
     *
     * @param method      Method to replace code of
     * @param forwardname Name of method to forward to
     * @param thistype    Type of object method is being replaced on
     */
    public static void replaceForwardingMethod(MethodNode method, String forwardname, Type thistype) {
        Type methodType = Type.getMethodType(method.desc);

        method.instructions.clear();

        populateForwardingMethod(method, forwardname, methodType.getReturnType(), methodType.getArgumentTypes()[0],
                thistype);
    }

    /**
     * Populate a forwarding method of the form "T name() { return Class.forward(this); }"
     *
     * @param method      Method to generate code for
     * @param forwardname Name of method to call
     * @param rettype     Return type of method
     * @param thistype    Type of object method is being generated on
     * @param forwardtype Type to forward method to
     */
    public static void populateForwardingToStaticMethod(MethodNode method, String forwardname, Type rettype,
                                                        Type thistype, Type forwardtype) {
        InsnList code = method.instructions;

        code.add(new VarInsnNode(thistype.getOpcode(Opcodes.ILOAD), 0));
        code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, forwardtype.getInternalName(), forwardname,
                Type.getMethodDescriptor(rettype, thistype), false));
        code.add(new InsnNode(rettype.getOpcode(Opcodes.IRETURN)));
    }

    /**
     * Populate a forwarding method of the form "T name() { return this.forward(); }" This is also valid for methods of
     * the form "static T name(S object) { return object.forward() }"
     *
     * @param method      Method to generate code for
     * @param forwardname Name of method to call
     * @param rettype     Return type of method
     * @param thistype    Type of object method is being generated on
     */
    public static void populateSelfForwardingMethod(MethodNode method, String forwardname, Type rettype,
                                                    Type thistype) {
        InsnList code = method.instructions;

        code.add(new VarInsnNode(thistype.getOpcode(Opcodes.ILOAD), 0));
        code.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, thistype.getInternalName(), forwardname,
                "()" + rettype.getDescriptor(), false));
        code.add(new InsnNode(rettype.getOpcode(Opcodes.IRETURN)));
    }

    /**
     * Populate a forwarding method of the form "T name(S object) { return object.forward(); }"
     *
     * @param method      Method to generate code for
     * @param forwardname Name of method to call
     * @param rettype     Return type of method
     * @param argtype     Type of object to call method on
     * @param thistype    Type of object method is being generated on
     */
    public static void populateForwardingMethod(MethodNode method, String forwardname, Type rettype, Type argtype,
                                                Type thistype) {
        InsnList code = method.instructions;

        code.add(new VarInsnNode(argtype.getOpcode(Opcodes.ILOAD), 1));
        code.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, argtype.getInternalName(), forwardname,
                "()" + rettype.getDescriptor(), false));
        code.add(new InsnNode(rettype.getOpcode(Opcodes.IRETURN)));
    }
}


text:
(function () {
  'use strict';
  angular
    .module('com.module.settings')
    .service('SettingService', function ($state, CoreService, Setting, gettextCatalog) {

      this.find = function () {
        return Setting.find().$promise;
      };

      this.findById = function (id) {
        return Setting.findById({
          id: id
        }).$promise;
      };

      this.upsert = function (setting) {
        return Setting.upsert(setting).$promise
          .then(function () {
            CoreService.toastSuccess(
              gettextCatalog.getString('Setting saved'),
              gettextCatalog.getString('Your setting is safe with us!')
            );
          })
          .catch(function (err) {
            CoreService.toastError(
              gettextCatalog.getString('Error saving setting '),
              gettextCatalog.getString('This setting could no be saved: ' + err)
            );
          }
        );
      };

      this.delete = function (id, successCb, cancelCb) {
        CoreService.confirm(
          gettextCatalog.getString('Are you sure?'),
          gettextCatalog.getString('Deleting this cannot be undone'),
          function () {
            Setting.deleteById({id: id}, function () {
              CoreService.toastSuccess(
                gettextCatalog.getString('Setting deleted'),
                gettextCatalog.getString('Your setting is deleted!'));
              successCb();
            }, function (err) {
              CoreService.toastError(
                gettextCatalog.getString('Error deleting setting'),
                gettextCatalog.getString('Your setting is not deleted! ') + err);
              cancelCb();
            });
          },
          function () {
            cancelCb();
          }
        );
      };

      this.getFormFields = function () {
        var form = [
          {
            key: 'key',
            type: 'input',
            templateOptions: {
              label: gettextCatalog.getString('Value'),
              required: true
            }
          },
          {
            key: 'value',
            type: 'input',
            templateOptions: {
              label: gettextCatalog.getString('Key'),
              required: true
            }
          }
        ];
        return form;
      };

    });

})();


text:
package com.baidu.rigel.biplatform.queryrouter.queryplugin.plugins.common.jdbc;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.baidu.rigel.biplatform.ac.query.data.DataSourceInfo;
import com.baidu.rigel.biplatform.queryrouter.handle.QueryRouterContext;
import com.baidu.rigel.biplatform.queryrouter.queryplugin.plugins.common.jdbc.connection.DataSourceException;
import com.baidu.rigel.biplatform.queryrouter.queryplugin.plugins.common.jdbc.connection.DataSourcePoolService;
import com.baidu.rigel.biplatform.queryrouter.queryplugin.plugins.common.jdbc.connection.SqlDataSourceWrap;

/**
 *
 * 处理Jdbc sql query请求
 *
 * @author luowenlei
 *
 */
@Service("jdbcHandler")
@Scope("prototype")
public class JdbcHandler {

    /**
     * Logger
     */
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * jdbcTemplate
     */
    private JdbcTemplate jdbcTemplate = null;

    /**
     * dataSourcePoolService
     */
    @Resource(name="localDataSourcePoolServiceImpl")
    private DataSourcePoolService dataSourcePoolService;

    /**
     *
     * initJdbcTemplate
     *
     * @param dataSource
     *            dataSource
     */
    private synchronized void initJdbcTemplate(DataSourceInfo dataSourceInfo) {
        long begin = System.currentTimeMillis();
        try {
            DataSource dataSource = (SqlDataSourceWrap) this.dataSourcePoolService
                    .getDataSourceByKey(dataSourceInfo);

            if (jdbcTemplate == null
                    || !this.jdbcTemplate.getDataSource().equals(dataSource)) {
                this.jdbcTemplate = null;
                jdbcTemplate = new JdbcTemplate(dataSource);
            }
        } catch (DataSourceException e) {
            e.printStackTrace();
            logger.error("getDataSource error:" + e.getCause().getMessage());
        }
        logger.info("initJdbcTemplate cost:"
                + (System.currentTimeMillis() - begin) + "ms");
    }

    /**
     * 通过sql查询数据库中的数据
     *
     * @param sqlQuery
     *            sql
     * @param dataSourceInfo
     *            dataSourceInfo
     * @return List<Map<String, Object>> formd tableresult data
     */
    public List<Map<String, Object>> queryForList(String sql,
            List<Object> whereValues, DataSourceInfo dataSourceInfo) {
        initJdbcTemplate(dataSourceInfo);
        long begin = System.currentTimeMillis();
        List<Map<String, Object>> result = null;
        try {
            logger.info("queryId:{} sql: {}", QueryRouterContext
                    .getQueryId(), this.toPrintString(sql, whereValues));
            result = this.jdbcTemplate.queryForList(sql, whereValues.toArray());
        } catch (Exception e) {
            logger.error("queryId:{} select sql error:{}",
                    QueryRouterContext.getQueryId(), e.getCause().getMessage());
            throw e;
        } finally {
            logger.info("queryId:{} select sql cost:{} ms",
                    QueryRouterContext.getQueryId(), System.currentTimeMillis() - begin);
        }
        return result;
    }

    /**
     * queryForInt
     *
     * @param sql
     *            sql
     * @param whereValues
     *            whereValues
     * @param dataSourceInfo
     *            dataSourceInfo
     * @return int count
     */
    public int queryForInt(String sql, List<Object> whereValues,
            DataSourceInfo dataSourceInfo) {
        initJdbcTemplate(dataSourceInfo);
        long begin = System.currentTimeMillis();
        Map<String, Object> result = null;
        int count = 0;
        try {
            logger.info("queryId:{} count sql: {}", QueryRouterContext
                    .getQueryId(), this.toPrintString(sql, whereValues));
            result = this.jdbcTemplate.queryForMap(sql, whereValues.toArray());
            count = Integer.valueOf(result.values().toArray()[0].toString())
                    .intValue();
        } catch (Exception e) {
            logger.error("queryId:{} select sql error:{}",
                    QueryRouterContext.getQueryId(), e.getCause().getMessage());
            throw e;
        } finally {
            logger.info("queryId:{} select count sql cost:{} ms, result: {}",
                    QueryRouterContext.getQueryId(), System.currentTimeMillis()
                            - begin, count);
        }
        return count;
    }

    /**
     * toPrintString
     *
     * @param sql
     *            sql
     * @param objects
     *            objects
     * @return sql String
     */
    public String toPrintString(String sql, List<Object> objects) {
        if (CollectionUtils.isEmpty(objects)) {
            return sql;
        }
        String printSql = new String(sql);
        int valuesCount = 0;
        if (!StringUtils.isEmpty(printSql)) {
            for (Object value : objects) {
                valuesCount ++;
                if (value instanceof String) {
                    printSql = StringUtils.replaceOnce(printSql, "?", "'"
                            + value.toString() + "'");
                } else {
                    printSql = StringUtils.replaceOnce(printSql, "?",
                            value.toString());
                }
                if (valuesCount > 2000) {
                    return printSql;
                }
            }
            return printSql;
        } else {
            return "";
        }
    }
}


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

namespace KK.WX.Messages
{
    public class MessageBase
    {

        /// 接收方
        public String ToUserName { get; set; }
        /// 发送方
        public String FromUserName { get; set; }
        /// 创建时间
        public Int32 CreateTime { get; set; }
        /// 消息类型
        public String MsgType { get; set; }

        #region MyRegion

        ///
        /// 尝试将XML文档转换为基本消息类型对象
        ///
        /// <param name="msg"></param>
        /// <param name="o"></param>
        /// <returns></returns>
        public static Boolean Parse(String msg, out MessageBase o)
        {
            XElement root = null;
            try
            {
                root = XElement.Parse(msg);
                MessageBase result = new MessageBase();
                if (root.HasElements)
                {
                    IEnumerable<XElement> elements = root.Elements();
                    foreach (XElement e in elements)
                    {
                        if (e.Name == "ToUserName") result.ToUserName = e.Value;
                        if (e.Name == "FromUserName") result.FromUserName = e.Value;
                        if (e.Name == "CreateTime") result.CreateTime = Int32.Parse(e.Value);
                        if (e.Name == "MsgType") result.MsgType = e.Value;
                    }
                }
                o = result;
                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }

        #endregion

    }
}


text:
#ifndef __SIM_BUFVAL_HH__
#define __SIM_BUFVAL_HH__

#include <cstddef>
#include <cstdint>
#include <string>
#include <utility>

#include "enums/ByteOrder.hh"

namespace gem5
{

// Extract an integer with a given endianness from a variably sized buffer.
// Returns the value extraced (if any) and a bool indicating success.
std::pair<std::uint64_t, bool> getUintX(const void *buf, std::size_t bytes,
        ByteOrder endian);

// Set a variably sized buffer to an integer value with a given endianness.
// Returns whether the assignment was successful.
bool setUintX(std::uint64_t val, void *buf, std::size_t bytes,
        ByteOrder endian);

// Print an integer with a given endianness into a string from a variably
// sized buffer. Returns the string (if any) and a bool indicating success.
std::pair<std::string, bool> printUintX(const void *buf, std::size_t bytes,
        ByteOrder endian);

// Print a buffer as "chunk_size" sized groups of bytes. The endianness
// determines if the bytes are output in memory order (little) or inverse of
// memory order (big). The default is in memory order so that this acts like
// a hexdump type utility. The return value is a string holding the printed
// bytes.
std::string printByteBuf(const void *buf, std::size_t bytes,
        ByteOrder endian=ByteOrder::little, std::size_t chunk_size=4);

} // namespace gem5

#endif // __SIM_BUFVAL_HH__


text:
public class StereoOffCommand implements Command {
    Stereo stereo;

    public StereoOffCommand(Stereo stereo) {
        this.stereo = stereo;
    }

    public void execute() {
        stereo.off();
    }
}


text:
@import UIKit;

/*!
    A lightweight controller object that is responsible for displaying the content in a group within the
    \c AAPLListsInterfaceController controller's \c WKInterfaceTable property.
 */
@interface AAPLColoredTextRowController : NSObject

- (void)setText:(NSString *)text;
- (void)setColor:(UIColor *)color;

@end


text:
namespace Perfectial.UnitTests.Application
{
    using System.Data.Entity;

    using Perfectial.Infrastructure.Persistence.EntityFramework;

    public class ApplicationDbInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
    {
        public override void InitializeDatabase(ApplicationDbContext context)
        {
            context.Database.ExecuteSqlCommand(
                TransactionalBehavior.DoNotEnsureTransaction,
                $"ALTER DATABASE {context.Database.Connection.Database} SET SINGLE_USER WITH ROLLBACK IMMEDIATE");

            base.InitializeDatabase(context);
        }
    }
}


text:
package boltdb

import (
	"os"
	"testing"

	"github.com/blevesearch/bleve/index/store"
	"github.com/blevesearch/bleve/index/store/test"
)

func open(t *testing.T, mo store.MergeOperator) store.KVStore {
	rv, err := New(mo, map[string]interface{}{"path": "test"})
	if err != nil {
		t.Fatal(err)
	}
	return rv
}

func cleanup(t *testing.T, s store.KVStore) {
	err := s.Close()
	if err != nil {
		t.Fatal(err)
	}
	err = os.RemoveAll("test")
	if err != nil {
		t.Fatal(err)
	}
}

func TestBoltDBKVCrud(t *testing.T) {
	s := open(t, nil)
	defer cleanup(t, s)
	test.CommonTestKVCrud(t, s)
}

func TestBoltDBReaderIsolation(t *testing.T) {
	s := open(t, nil)
	defer cleanup(t, s)
	test.CommonTestReaderIsolation(t, s)
}

func TestBoltDBReaderOwnsGetBytes(t *testing.T) {
	s := open(t, nil)
	defer cleanup(t, s)
	test.CommonTestReaderOwnsGetBytes(t, s)
}

func TestBoltDBWriterOwnsBytes(t *testing.T) {
	s := open(t, nil)
	defer cleanup(t, s)
	test.CommonTestWriterOwnsBytes(t, s)
}

func TestBoltDBPrefixIterator(t *testing.T) {
	s := open(t, nil)
	defer cleanup(t, s)
	test.CommonTestPrefixIterator(t, s)
}

func TestBoltDBPrefixIteratorSeek(t *testing.T) {
	s := open(t, nil)
	defer cleanup(t, s)
	test.CommonTestPrefixIteratorSeek(t, s)
}

func TestBoltDBRangeIterator(t *testing.T) {
	s := open(t, nil)
	defer cleanup(t, s)
	test.CommonTestRangeIterator(t, s)
}

func TestBoltDBRangeIteratorSeek(t *testing.T) {
	s := open(t, nil)
	defer cleanup(t, s)
	test.CommonTestRangeIteratorSeek(t, s)
}

func TestBoltDBMerge(t *testing.T) {
	s := open(t, &test.TestMergeCounter{})
	defer cleanup(t, s)
	test.CommonTestMerge(t, s)
}