text:
package org.drools.process.instance;

import java.util.Map;

public interface WorkItem extends org.kie.runtime.process.WorkItem {

    void setName(String name);

    void setParameter(String name, Object value);

    void setParameters(Map<String, Object> parameters);

    void setResults(Map<String, Object> results);

    void setState(int state);

    void setProcessInstanceId(long processInstanceId);

}


text:
package com.perforce.p4java.exception;

/**
 * Class intended to be used to signal unrecoverable errors that a client
 * or other package should probably not handle or that signal serious
 * errors without known fixes.

 *
 * The intention here is to use this for things like null pointer
 * errors, etc., that methods may check for but that should not have to
 * be explicitly mentioned in the "throws" clause or dealt with by all
 * callers.

 *
 * Note that P4JavaError and derived classes don't use the P4JavaException resource
 * bundle scheme for error messages -- the thinking here is that errors are thrown
 * when bundles, etc. may fail and all hell is breaking loose....
 *
 *
 */

public class P4JavaError extends Error {

	private static final long serialVersionUID = 1L;

	public P4JavaError() {
	}

	public P4JavaError(String message) {
		super(message);
	}

	public P4JavaError(Throwable cause) {
		super(cause);
	}

	public P4JavaError(String message, Throwable cause) {
		super(message, cause);
	}
}

redpajama_set_name: RedPajamaGithub


text:
package ks.web;

import ks.web.annotation.Path;

public class DemoController {

	@Path(name = "sayHello")
	public String sayHello() {
		return "hello";
	}

	@Path(name = "login")
	public void login(String userName, String password) throws Exception {
		if ("admin".equals(userName)) {
			throw new SecurityException("管理员禁止登录");
		}
	}
}


text:
@protocol IO2GTradeRow <IO2GRow>
    - (NSString*) getTradeID;
    - (NSString*) getAccountID;
    - (NSString*) getAccountName;
    - (NSString*) getAccountKind;
    - (NSString*) getOfferID;
    - (int) getAmount;
    - (NSString*) getBuySell;
    - (double) getOpenRate;
    - (DATE) getOpenTime;
    - (NSString*) getOpenQuoteID;
    - (NSString*) getOpenOrderID;
    - (NSString*) getOpenOrderReqID;
    - (NSString*) getOpenOrderRequestTXT;
    - (double) getCommission;
    - (double) getRolloverInterest;
    - (NSString*) getTradeIDOrigin;
    - (int) getUsedMargin;
    - (NSString*) getValueDate;
    - (NSString*) getParties;
    //

@end

@protocol IO2GTradeTableRow <IO2GTradeRow>
    - (double) getPL;
    - (double) getGrossPL;
    - (double) getClose;
    - (double) getStop;
    - (double) getLimit;
    //

@end


text:
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using AlcoFlightLogger.Data;

namespace AlcoFlightLogger.Data.Migrations
{
    [DbContext(typeof(ApplicationDbContext))]
    partial class ApplicationDbContextModelSnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
            modelBuilder
                .HasAnnotation("ProductVersion", "1.0.1")
                .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

            modelBuilder.Entity("AlcoFlightLogger.Models.Flight", b =>
                {
                    b.Property<int>("FlightId")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Description");

                    b.Property<string>("Name");

                    b.Property<int>("PilotId");

                    b.Property<int>("Score");

                    b.HasKey("FlightId");

                    b.HasIndex("PilotId");

                    b.ToTable("Flights");
                });

            modelBuilder.Entity("AlcoFlightLogger.Models.FuelPoint", b =>
                {
                    b.Property<int>("FuelPointId")
                        .ValueGeneratedOnAdd();

                    b.Property<DateTime>("Date");

                    b.Property<int>("FlightId");

                    b.Property<string>("Latitude");

                    b.Property<string>("Longitude");

                    b.HasKey("FuelPointId");

                    b.HasIndex("FlightId");

                    b.ToTable("FuelPoint");
                });

            modelBuilder.Entity("AlcoFlightLogger.Models.Pilot", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<int>("AccessFailedCount");

                    b.Property<string>("ConcurrencyStamp")
                        .IsConcurrencyToken();

                    b.Property<string>("Email")
                        .HasAnnotation("MaxLength", 256);

                    b.Property<bool>("EmailConfirmed");

                    b.Property<bool>("LockoutEnabled");

                    b.Property<DateTimeOffset?>("LockoutEnd");

                    b.Property<string>("NormalizedEmail")
                        .HasAnnotation("MaxLength", 256);

                    b.Property<string>("NormalizedUserName")
                        .HasAnnotation("MaxLength", 256);

                    b.Property<string>("PasswordHash");

                    b.Property<string>("PhoneNumber");

                    b.Property<bool>("PhoneNumberConfirmed");

                    b.Property<string>("SecurityStamp");

                    b.Property<bool>("TwoFactorEnabled");

                    b.Property<string>("UserName")
                        .HasAnnotation("MaxLength", 256);

                    b.HasKey("Id");

                    b.HasIndex("NormalizedEmail")
                        .HasName("EmailIndex");

                    b.HasIndex("NormalizedUserName")
                        .IsUnique()
                        .HasName("UserNameIndex");

                    b.ToTable("AspNetUsers");
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole<int>", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("ConcurrencyStamp")
                        .IsConcurrencyToken();

                    b.Property<string>("Name")
                        .HasAnnotation("MaxLength", 256);

                    b.Property<string>("NormalizedName")
                        .HasAnnotation("MaxLength", 256);

                    b.HasKey("Id");

                    b.HasIndex("NormalizedName")
                        .HasName("RoleNameIndex");

                    b.ToTable("AspNetRoles");
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<int>", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("ClaimType");

                    b.Property<string>("ClaimValue");

                    b.Property<int>("RoleId");

                    b.HasKey("Id");

                    b.HasIndex("RoleId");

                    b.ToTable("AspNetRoleClaims");
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<int>", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("ClaimType");

                    b.Property<string>("ClaimValue");

                    b.Property<int>("UserId");

                    b.HasKey("Id");

                    b.HasIndex("UserId");

                    b.ToTable("AspNetUserClaims");
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<int>", b =>
                {
                    b.Property<string>("LoginProvider");

                    b.Property<string>("ProviderKey");

                    b.Property<string>("ProviderDisplayName");

                    b.Property<int>("UserId");

                    b.HasKey("LoginProvider", "ProviderKey");

                    b.HasIndex("UserId");

                    b.ToTable("AspNetUserLogins");
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<int>", b =>
                {
                    b.Property<int>("UserId");

                    b.Property<int>("RoleId");

                    b.HasKey("UserId", "RoleId");

                    b.HasIndex("RoleId");

                    b.HasIndex("UserId");

                    b.ToTable("AspNetUserRoles");
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<int>", b =>
                {
                    b.Property<int>("UserId");

                    b.Property<string>("LoginProvider");

                    b.Property<string>("Name");

                    b.Property<string>("Value");

                    b.HasKey("UserId", "LoginProvider", "Name");

                    b.ToTable("AspNetUserTokens");
                });

            modelBuilder.Entity("AlcoFlightLogger.Models.Flight", b =>
                {
                    b.HasOne("AlcoFlightLogger.Models.Pilot")
                        .WithMany("Flights")
                        .HasForeignKey("PilotId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("AlcoFlightLogger.Models.FuelPoint", b =>
                {
                    b.HasOne("AlcoFlightLogger.Models.Flight")
                        .WithMany("FuelPoints")
                        .HasForeignKey("FlightId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<int>", b =>
                {
                    b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole<int>")
                        .WithMany("Claims")
                        .HasForeignKey("RoleId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<int>", b =>
                {
                    b.HasOne("AlcoFlightLogger.Models.Pilot")
                        .WithMany("Claims")
                        .HasForeignKey("UserId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<int>", b =>
                {
                    b.HasOne("AlcoFlightLogger.Models.Pilot")
                        .WithMany("Logins")
                        .HasForeignKey("UserId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<int>", b =>
                {
                    b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole<int>")
                        .WithMany("Users")
                        .HasForeignKey("RoleId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("AlcoFlightLogger.Models.Pilot")
                        .WithMany("Roles")
                        .HasForeignKey("UserId")
                        .OnDelete(DeleteBehavior.Cascade);
                });
        }
    }
}


text:
title: IT lesson 6
layout: post
author: felix.warry
permalink: /it-lesson-6/
source-id: 1Vp-bLooxJVEiU4AMCrPk1IC_-cikTBXofjNdgXyvE2Q
published: true
---

    Title
    IT lesson 6
    Date
    5/2/18

    Starting point:
    To encrypt

    Target for this lesson?
    To have encrypted hello and found a way to decypher khoor

    Did I reach my target?
(add details to "Lesson Review")
     Yes

    Lesson Review

    How did I learn? What strategies were effective?

    I learnt that to encrypt a message you need 2 columns,1 with the normal alphabet and the other with a alphabet with the letters added by 3.

    What limited my learning? Which habits do I need to work on?

    I didn't manage to get onto the deciphering part of the sheet because i could not remember how.

    What will I change for next time? How will I improve my learning?

    I will put in my decypering code.


text:
Conflict-Free Replicated Data Type
==================================

This is work-in-progress. We have library modules to support the following data types.

1. Multi-Valued Register
2. Grow-Only Counter
3. PN-Counter
4. Enable-Wins Flag
5. Disable-Wins Flag
6. Add-Wins Observe-Remove Set
7. Remove-Wins Observe-Remove Set
8. Put-Wins Observe-Remove Map
9. Remove-Wins Observe-Remove Map
10. Recursive Composite Map

Please refer to erlang_crdt.pdf for more details.


text:
Featured

Take on Dragons

Take on Establishments

Take on Magic Items

Other Profiles

Google+ Profile

@takeonrules

Board Game Geek

@jeremyfriesen

Github Profile

blogs.nd.edu/jeremyfriesen

Contributor To

ndlib Github Profile

projecthydra Github Profile

ndlib.github.io

Categories

  {% for category in site.sorted_categories %}

{{ category.first }}

  {% endfor %}

Tags

  {% for tag in site.sorted_tags %}

{{ tag.first }}

  {% endfor %}


text:
"""Tests for tensorflow.kernels.sparse_op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import tensorflow as tf

def _SparseToDense(sparse_indices, output_size, sparse_values,
                   default_value, validate_indices=True):
  return tf.sparse_to_dense(sparse_indices, output_size,
                            sparse_values,
                            default_value=default_value,
                            validate_indices=validate_indices)

class SparseToDenseTest(tf.test.TestCase):

  def testInt(self):
    with self.test_session(use_gpu=False):
      tf_ans = _SparseToDense([1, 3], [5], 1, 0).eval()
    np_ans = np.array([0, 1, 0, 1, 0]).astype(np.int32)
    self.assertAllClose(np_ans, tf_ans)

  def testFloat(self):
    with self.test_session(use_gpu=False):
      tf_ans = _SparseToDense([1, 3], [5], 1.0, 0.0).eval()
    np_ans = np.array([0, 1, 0, 1, 0]).astype(np.float32)
    self.assertAllClose(np_ans, tf_ans)

  def testString(self):
    with self.test_session(use_gpu=False):
      tf_ans = _SparseToDense([1, 3], [5], "a", "b").eval()
    np_ans = np.array(["b", "a", "b", "a", "b"]).astype(np.string_)
    self.assertAllEqual(np_ans, tf_ans)

  def testSetValue(self):
    with self.test_session(use_gpu=False):
      tf_ans = _SparseToDense([1, 3], [5], [1, 2], -1).eval()
    np_ans = np.array([-1, 1, -1, 2, -1]).astype(np.int32)
    self.assertAllClose(np_ans, tf_ans)

  def testSetSingleValue(self):
    with self.test_session(use_gpu=False):
      tf_ans = _SparseToDense([1, 3], [5], 1, -1).eval()
    np_ans = np.array([-1, 1, -1, 1, -1]).astype(np.int32)
    self.assertAllClose(np_ans, tf_ans)

  def test2d(self):
    # pylint: disable=bad-whitespace
    with self.test_session(use_gpu=False):
      tf_ans = _SparseToDense([[1, 3], [2, 0]], [3, 4], 1, -1).eval()
    np_ans = np.array([[-1, -1, -1, -1],
                       [-1, -1, -1,  1],
                       [ 1, -1, -1, -1]]).astype(np.int32)
    self.assertAllClose(np_ans, tf_ans)

  def testZeroDefault(self):
    with self.test_session():
      x = tf.sparse_to_dense(2, [4], 7).eval()
      self.assertAllEqual(x, [0, 0, 7, 0])

  def test3d(self):
    with self.test_session(use_gpu=False):
      tf_ans = _SparseToDense([[1, 3, 0], [2, 0, 1]], [3, 4, 2], 1, -1).eval()
    np_ans = np.ones((3, 4, 2), dtype=np.int32) * -1
    np_ans[1, 3, 0] = 1
    np_ans[2, 0, 1] = 1
    self.assertAllClose(np_ans, tf_ans)

  def testBadShape(self):
    with self.test_session():
      with self.assertRaisesWithPredicateMatch(
          ValueError, lambda e: ("Input shape should be a vector" == str(e))):
        _SparseToDense([1, 3], [[5], [3]], 1, -1)

  def testBadValue(self):
    with self.test_session():
      dense = _SparseToDense([1, 3], [5], [[5], [3]], -1)
      with self.assertRaisesOpError(
          r"sparse_values has incorrect shape \[2,1\], "
          r"should be \[\] or \[2\]"):
        dense.eval()

  def testBadNumValues(self):
    with self.test_session():
      dense = _SparseToDense([1, 3], [5], [1, 2, 3], -1)
      with self.assertRaisesOpError(
          r"sparse_values has incorrect shape \[3\], should be \[\] or \[2\]"):
        dense.eval()

  def testBadDefault(self):
    with self.test_session():
      dense = _SparseToDense([1, 3], [5], [1, 2], [0])
      with self.assertRaisesOpError("default_value should be a scalar"):
        dense.eval()

  def testOutOfBoundsIndicesWithWithoutValidation(self):
    with self.test_session():
      dense = _SparseToDense(
          sparse_indices=[[1], [10]], output_size=[5],
          sparse_values=[-1.0, 1.0], default_value=0.0)
      with self.assertRaisesOpError(
          r"indices\[1\] = \[10\] is out of bounds: need 0 <= index < \[5\]"):
        dense.eval()
      # Disable checks, the allocation should still fail.
      with self.assertRaisesOpError("out of bounds"):
        dense_without_validation = _SparseToDense(
            sparse_indices=[[1], [10]], output_size=[5],
            sparse_values=[-1.0, 1.0], default_value=0.0,
            validate_indices=False)
        dense_without_validation.eval()

  def testRepeatingIndicesWithWithoutValidation(self):
    with self.test_session():
      dense = _SparseToDense(
          sparse_indices=[[1], [1]], output_size=[5],
          sparse_values=[-1.0, 1.0], default_value=0.0)
      with self.assertRaisesOpError(r"indices\[1\] = \[1\] is repeated"):
        dense.eval()
      # Disable checks
      dense_without_validation = _SparseToDense(
          sparse_indices=[[1], [1]], output_size=[5],
          sparse_values=[-1.0, 1.0], default_value=0.0, validate_indices=False)
      dense_without_validation.eval()

  def testUnsortedIndicesWithWithoutValidation(self):
    with self.test_session():
      dense = _SparseToDense(
          sparse_indices=[[2], [1]], output_size=[5],
          sparse_values=[-1.0, 1.0], default_value=0.0)
      with self.assertRaisesOpError(r"indices\[1\] = \[1\] is out of order"):
        dense.eval()
      # Disable checks
      dense_without_validation = _SparseToDense(
          sparse_indices=[[2], [1]], output_size=[5],
          sparse_values=[-1.0, 1.0], default_value=0.0, validate_indices=False)
      dense_without_validation.eval()

  def testShapeInferenceKnownShape(self):
    with self.test_session(use_gpu=False):
      indices = tf.placeholder(tf.int64)

      shape = [4, 5, 6]
      output = tf.sparse_to_dense(indices, shape, 1, 0)
      self.assertEqual(output.get_shape(), [4, 5, 6])

      shape = tf.placeholder(tf.int64, shape=(3,))
      output = tf.sparse_to_dense(indices, shape, 1, 0)
      self.assertEqual(output.get_shape().as_list(), [None, None, None])

  def testShapeInferenceUnknownShape(self):
    with self.test_session(use_gpu=False):
      indices = tf.placeholder(tf.int64)
      shape = tf.placeholder(tf.int64)
      output = tf.sparse_to_dense(indices, shape, 1, 0)
      self.assertEqual(output.get_shape().ndims, None)

if __name__ == "__main__":
  tf.test.main()


text:
namespace CanvasToy {

    export interface ProgramPass {
        faces?: Faces;
        uniforms?: any;
        attributes?: any;
        textures?: any;
        vertexShader?: string;
        fragmentShader?: string;
        prefix?: string[]
    }

    export class Faces {
        public buffer: WebGLBuffer = gl.createBuffer();
        constructor(public data: number[]) { }
    }

    export class Attribute {
        size: number = 3;
        data: number[] = [];
        type: number;
        index: number = 0;
        stride: number = 0;
        buffer: WebGLBuffer = gl.createBuffer();
        constructor(paramter: { type: number, size?: number, data?: number[], stride?: number }) {
            for (let attributeInfo in paramter) {
                this[attributeInfo] = paramter[attributeInfo] ? paramter[attributeInfo] : this[attributeInfo];
            }
            switch (paramter.type) {
                case DataType.float: this.type = gl.FLOAT; break;
                case DataType.int: this.type = gl.INT; break;
            }
        }
    }

    export class Program implements ProgramPass {

        faces: Faces;
        enableDepthTest: boolean = true;
        enableStencilTest: boolean = true;
        uniforms = {};
        attributes = {};
        attributeLocations = {};
        attribute0: string;
        webGlProgram: WebGLProgram;
        drawMode: number = gl.STATIC_DRAW;
        textures: Array<Texture> = [];
        vertexPrecision: string = 'highp';
        fragmentPrecision: string = 'mediump';
        vertexShader: string;
        fragmentShader: string;

        prefix: string[] = [];

        private passings: Array<(mesh: Mesh, scene: Scene, camera: Camera) => ProgramPass> = [];

        constructor(passing: (mesh: Mesh, scene: Scene, camera: Camera) => ProgramPass) {
            this.passings.push(passing);
        }

        public make(material: Material, mesh: Mesh, scene: Scene, camera: Camera) {
            this.prefix = [
                material.mainTexture ? '#define USE_TEXTURE ' : '',
                material.color ? '#define USE_COLOR ' : '',
                scene.openLight ? '#define OPEN_LIGHT \n#define LIGHT_NUM '
                    + scene.lights.length : ''
            ];
            if (!!this.passings) {
                let passes = this.passings.map((passing) => { return passing(mesh, scene, camera) });
                let finalPass: any = {};
                passes.forEach((pass) => {
                    mixin(finalPass, pass);
                });
                this.rePass(finalPass);
            };
        }

        public addPassing(passing: (mesh: Mesh, scene: Scene, camera: Camera) => ProgramPass) {
            this.passings.push(passing);
        }

        private rePass(parameter: ProgramPass) {
            if (!!(parameter.vertexShader) || !!(parameter.fragmentShader) || !!(parameter.prefix)) {
                this.vertexShader = parameter.vertexShader || this.vertexShader;
                this.fragmentShader = parameter.fragmentShader || this.fragmentShader;
                this.webGlProgram = createEntileShader(gl,
                    'precision ' + this.vertexPrecision + ' float;\n' + this.prefix.join('\n') + '\n' + this.vertexShader,
                    'precision ' + this.fragmentPrecision + ' float;\n' + this.prefix.join('\n') + '\n' + this.fragmentShader);
            }
            this.faces = (parameter.faces == undefined ? this.faces : parameter.faces);
            for (let nameInShader in parameter.uniforms) {
                if (parameter.uniforms[nameInShader] != undefined) {
                    this.addUniform(nameInShader, parameter.uniforms[nameInShader]);
                }
            }
            for (let sampler in parameter.textures) {
                this.textures[sampler] = parameter.textures[sampler];
            }
            for (let nameInShader in parameter.attributes) {
                this.addAttribute(nameInShader, parameter.attributes[nameInShader]);
            }
            this.checkState();
        }

        public checkState() {
            let maxIndex = 0;
            for (let index of this.faces.data) {
                maxIndex = Math.max(maxIndex, index);
            }
            for (let attributeName in this.attributes) {
                console.assert(this.attributes[attributeName].size <= 4 && this.attributes[attributeName].size >= 1,
                    attributeName + "size error, now: " + this.attributes[attributeName].size + " should be 1-4");
                console.assert((maxIndex + 1) * this.attributes[attributeName].stride <=
                    this.attributes[attributeName].data.length,
                    attributeName + " length error, now:" + this.attributes[attributeName].data.length
                    + ", should bigger than:" + (maxIndex + 1) * this.attributes[attributeName].stride);
            }
        }

        setAttribute0(name: string) {
            this.attribute0 = name;
            gl.bindAttribLocation(this.webGlProgram, 0, name);
        }

        addUniform(nameInShader, uniform: { type: DataType, updator: (mesh?, camera?) => any }) {
            gl.useProgram(this.webGlProgram);
            let location = this.getUniformLocation(nameInShader);
            let last = uniform.updator;
            //uniform.updator = () => { console.log(location); return last() };
            switch (uniform.type) {
                case DataType.float:
                    this.uniforms[nameInShader] = (mesh?, camera?) => {
                        gl.uniform1f(location, uniform.updator(mesh, camera));
                    };
                    break;
                case DataType.int:
                    this.uniforms[nameInShader] = (mesh?, camera?) => {
                        gl.uniform1i(location, uniform.updator(mesh, camera));
                    };
                    break;
                case DataType.vec2:
                    this.uniforms[nameInShader] = (mesh?, camera?) => {
                        let value = uniform.updator(mesh, camera);
                        gl.uniform2f(location, value[0], value[1]);
                    };
                    break;
                case DataType.vec3:
                    this.uniforms[nameInShader] = (mesh?, camera?) => {
                        let value = uniform.updator(mesh, camera);
                        gl.uniform3f(location, value[0], value[1], value[2]);
                    };
                    break;
                case DataType.vec4:
                    this.uniforms[nameInShader] = (mesh?, camera?) => {
                        let value = uniform.updator(mesh, camera);
                        gl.uniform4f(location, value[0], value[1], value[2], value[3]);
                    };
                    break;
                case DataType.mat2:
                    this.uniforms[nameInShader] = (mesh?, camera?) => {
                        gl.uniformMatrix2fv(location, false, uniform.updator(mesh, camera));
                    };
                case DataType.mat3:
                    this.uniforms[nameInShader] = (mesh?, camera?) => {
                        gl.uniformMatrix3fv(location, false, uniform.updator(mesh, camera));
                    }; case DataType.mat4:
                    this.uniforms[nameInShader] = (mesh?, camera?) => {
                        gl.uniformMatrix4fv(location, false, uniform.updator(mesh, camera));
                    };
                    break;
            }
        }

        public addAttribute(nameInShader, attribute: Attribute) {
            let location = this.getAttribLocation(nameInShader);
            if (location != null && location != -1) {
                this.attributes[nameInShader] = attribute;
                this.attributeLocations[nameInShader] = location;
                gl.enableVertexAttribArray(location);
            }
        }

        private getUniformLocation(name: string): WebGLUniformLocation {
            if (gl == undefined || gl == null) {
                console.error("WebGLRenderingContext has not been initialize!");
                return null;
            }
            var result = gl.getUniformLocation(this.webGlProgram, name);
            if (result == null) {
                console.warn("uniform " + name + " not found!");
                return null;
            }
            return result;
        }

        private getAttribLocation(name: string): number {
            if (gl == undefined || gl == null) {
                console.error("WebGLRenderingContext has not been initialize!");
                return null;
            }
            var result = gl.getAttribLocation(this.webGlProgram, name);
            if (result == null) {
                console.error("attribute " + name + " not found!");
                return null;
            }
            return result;
        }

    }
}


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

namespace Gdbots\Pbjx\EventSearch\Elastica;

use Elastica\Client;
use Elastica\Connection;
use Gdbots\Pbjx\Exception\InvalidArgumentException;
use Psr\Log\LoggerInterface;

class ClientManager
{
    protected const MAX_CLI_CONNECT_ATTEMPTS = 100;
    protected const MAX_CONNECT_ATTEMPTS = 5;

    /**
     * An array of clusters keyed by a name.  This factory will create the elastica
     * client for a given cluster using the settings in the key.
     *
     * The reason for the "clusters" (not just single cluster) config is to make it
     * possible to manage a multi-tenant app or run different clusters for different
     * parts of the same app (logging vs content, etc.).
     *
     *  [
     *      'default' => [
     *          'round_robin' => true,
     *          'timeout' => 300,
     *          'debug' => false,
     *          'persistent' => true
     *          'servers' => [
     *              ['host' => 'localhost', 'port' => 9200]
     *          ]
     *      ],
     *      'client1' => [...],
     *      'client2' => [...],
     *      'logging' => [...],
     *  ]
     *
     * @var array
     */
    protected array $clusters;

    protected ?LoggerInterface $logger;

    /** @var Client[] */
    protected array $clients = [];

    protected bool $isCli = false;

    public function __construct(array $clusters, ?LoggerInterface $logger = null)
    {
        $this->clusters = $clusters;
        $this->logger = $logger;
        $this->isCli = php_sapi_name() === 'cli';
    }

    /**
     * Gets an elastica client using the config from the provided cluster name.
     *
     * All calls with the same cluster name will return the same client instance.
     *
     * @param string $cluster
     *
     * @return Client
     */
    public function getClient(string $cluster = 'default'): Client
    {
        if (isset($this->clients[$cluster])) {
            return $this->clients[$cluster];
        }

        if (!$this->hasCluster($cluster)) {
            throw new InvalidArgumentException(
                sprintf(
                    'The cluster [%s] is not one of the available clusters [%s].',
                    $cluster,
                    implode(',', $this->getAvailableClusters())
                )
            );
        }

        $config = $this->clusters[$cluster];

        if (isset($config['debug'])) {
            $config['log'] = filter_var($config['debug'], FILTER_VALIDATE_BOOLEAN);
            unset($config['debug']);
        } else {
            $config['log'] = false;
        }

        if (isset($config['round_robin'])) {
            $config['roundRobin'] = filter_var($config['round_robin'], FILTER_VALIDATE_BOOLEAN);
            unset($config['round_robin']);
        }

        $config['clusterName'] = $cluster;
        $config['connectAttempts'] = 0;

        if (!isset($config['maxConnectAttempts'])) {
            $config['maxConnectAttempts'] = $this->isCli
                ? static::MAX_CLI_CONNECT_ATTEMPTS
                : static::MAX_CONNECT_ATTEMPTS;
        }

        if (!isset($config['connectTimeout'])) {
            $config['connectTimeout'] = 1;
        }

        $config = $this->configureCluster($cluster, $config);
        $servers = $config['servers'];
        $configuredServers = [];
        unset($config['servers']);

        foreach ($servers as $server) {
            $configuredServers[] = array_merge($config, $server);
        }

        $config['servers'] = $configuredServers;
        return $this->clients[$cluster] = new Client($config, [$this, 'onConnectionFailure'], $config['log'] ? $this->logger : null);
    }

    public function hasCluster(string $cluster): bool
    {
        return isset($this->clusters[$cluster]);
    }

    /**
     * Returns the names of the available clusters.
     *
     * @return string[]
     */
    public function getAvailableClusters(): array
    {
        return array_keys($this->clusters);
    }

    public function onConnectionFailure(Connection $connection, \Throwable $e, Client $client): void
    {
        $attempts = $client->getConfigValue('connectAttempts') + 1;
        $client->setConfigValue('connectAttempts', $attempts);
        $maxAttempts = $client->getConfigValue('maxConnectAttempts');

        if ($attempts > $maxAttempts) {
            return;
        }

        usleep(mt_rand(10, 100) * 1000);
        $connection->setEnabled(true);
    }

    protected function configureCluster(string $cluster, array $config): array
    {
        return $config;
    }
}


text:
package lebah.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public interface IServlet {

	void doService(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException;
}


text:
<?php
(SECURITY == "*)WT#&YHfd" && SECHASH_CHECK) ? die("public/index.php -> Set a new SECURITY value to continue") : 0;
$defflip = (!cfip()) ? exit(header('HTTP/1.1 401 Unauthorized')) : 1;

// SHA/Scrypt check
if (empty($config['algorithm']) || $config['algorithm'] == 'scrypt') {
  $config['target_bits'] = 16;
} else {
  $config['target_bits'] = 32;
}

// Default classes
require_once(INCLUDE_DIR . '/lib/KLogger.php');
require_once(CLASS_DIR . '/logger.class.php');
require_once(CLASS_DIR . '/debug.class.php');
if ($config['mysql_filter']) {
  require_once(CLASS_DIR . '/strict.class.php');
}
require_once(INCLUDE_DIR . '/database.inc.php');
require_once(INCLUDE_DIR . '/config/memcache_keys.inc.php');
require_once(INCLUDE_DIR . '/config/error_codes.inc.php');

// We need to load these two first
require_once(CLASS_DIR . '/base.class.php');
require_once(CLASS_DIR . '/setting.class.php');

// We need this one in here to properly set our theme
require_once(INCLUDE_DIR . '/lib/Mobile_Detect.php');

// Detect device
if ($detect->isMobile() && $setting->getValue('website_mobile_theme')) {
  // Set to mobile theme
  $setting->getValue('website_mobile_theme') ? $theme = $setting->getValue('website_mobile_theme') : $theme = 'mobile';
} else if ( PHP_SAPI == 'cli') {
  // Create a new compile folder just for crons
  // We call mail templates directly anyway
  $theme = 'cron';
} else {
  // Use configured theme, fallback to default theme
  $setting->getValue('website_theme') ? $theme = $setting->getValue('website_theme') : $theme = 'mpos';
}
define('THEME', $theme);

//Required for Smarty
require_once(CLASS_DIR . '/template.class.php');
// Load smarty now that we have our theme defined
require_once(INCLUDE_DIR . '/smarty.inc.php');

// Load everything else in proper order
require_once(CLASS_DIR . '/mail.class.php');
require_once(CLASS_DIR . '/tokentype.class.php');
require_once(CLASS_DIR . '/token.class.php');
require_once(CLASS_DIR . '/payout.class.php');
require_once(CLASS_DIR . '/block.class.php');

// We require the block class to properly grab the round ID
require_once(CLASS_DIR . '/statscache.class.php');

require_once(CLASS_DIR . '/bitcoin.class.php');
require_once(CLASS_DIR . '/bitcoinwrapper.class.php');
require_once(CLASS_DIR . '/monitoring.class.php');
require_once(CLASS_DIR . '/notification.class.php');
require_once(CLASS_DIR . '/user.class.php');
require_once(CLASS_DIR . '/csrftoken.class.php');
require_once(CLASS_DIR . '/invitation.class.php');
require_once(CLASS_DIR . '/share.class.php');
require_once(CLASS_DIR . '/worker.class.php');
require_once(CLASS_DIR . '/statistics.class.php');
require_once(CLASS_DIR . '/transaction.class.php');
require_once(CLASS_DIR . '/roundstats.class.php');
require_once(CLASS_DIR . '/news.class.php');
require_once(CLASS_DIR . '/api.class.php');
require_once(INCLUDE_DIR . '/lib/Michelf/Markdown.php');
require_once(INCLUDE_DIR . '/lib/scrypt.php');

?>


text:
<?php

namespace Phwoolcon\Queue;

use Exception;
use Phwoolcon\Queue;
use Phwoolcon\Queue\Adapter\JobInterface;
use Phwoolcon\Queue\Adapter\JobTrait;
use Phwoolcon\Queue\Listener\Result;
use Throwable;

class Listener
{

    /**
     * Log a failed job into storage.
     *
     * @param JobInterface|JobTrait $job
     */
    protected function fail($job)
    {
        Queue::getFailLogger()->log($job->getQueue()->getConnectionName(), $job->getQueueName(), $job->getRawBody());
        $job->delete();
    }

    /**
     * Listen to the given queue.
     *
     * @param  string $connectionName
     * @param  string $queue
     * @param  int    $delay
     * @param  int    $sleep
     * @param  int    $maxTries
     * @return Result
     */
    public function pop($connectionName, $queue = null, $delay = 0, $sleep = 3, $maxTries = 0)
    {
        $connection = Queue::connection($connectionName);

        if ($job = $connection->pop($queue)) {
            return $this->process($job, $maxTries, $delay);
        }
        // Sleep the worker for the specified number of seconds, if no jobs
        sleep($sleep);
        return Result::success(null);
    }

    /**
     * Process a given job from the queue.
     *
     * @param JobInterface|JobTrait $job
     * @param int                   $maxTries
     * @param int                   $delay
     * @return Result
     *
     * @throws Throwable
     */
    public function process(JobInterface $job, $maxTries = 0, $delay = 0)
    {
        if ($maxTries > 0 && $job->attempts() > $maxTries) {
            $this->fail($job);
            return Result::failed($job);
        }

        try {
            $job->fire();
            return Result::success($job);
        } catch (Exception $e) {
            // If we catch an exception, we will attempt to release the job back onto
            // the queue so it is not lost. This will let is be retried at a later
            // time by another listener (or the same one). We will do that here.
            if (!$job->isDeleted()) {
                $job->release($delay);
            }
            throw $e;
        } // @codeCoverageIgnoreStart
        catch (Throwable $e) {
            if (!$job->isDeleted()) {
                $job->release($delay);
            }
            throw $e;
        }
        // @codeCoverageIgnoreEnd
    }
}


text:
import * as fs from "fs";
import * as path from "path";

export function rmDirSync(dirPath: string): void {
    let filenames = [];

    try {
        filenames = fs.readdirSync(dirPath);
    } catch (_err) {
        return;
    }

    for (const filename of filenames) {
        const filePath = path.join(dirPath, filename);

        if (fs.statSync(filePath).isFile()) {
            fs.unlinkSync(filePath);
        } else {
            rmDirSync(filePath);
        }
    }

    fs.rmdirSync(dirPath);
}

export function getFileSize(filePath: string): number {
    const stats = fs.statSync(filePath);
    return stats.size;
}


text:
import { failure, input, strong } from './color';

export async function diffPatch(filename: string, text1: string, text2: string): Promise<string> {
  const JsDiff = await import('diff');

  return JsDiff.createPatch(filename, text1, text2, '', '').split('\n').map(line => {
    if (line.indexOf('-') === 0 && line.indexOf('---') !== 0) {
      line = strong(failure(line));
    } else if (line.indexOf('+') === 0 && line.indexOf('+++') !== 0) {
      line = strong(input(line));
    }

    return line;
  }).slice(2).join('\n');
}


text:
class Timeline < ActiveRecord::Base
  class Empty
    attr_accessor :id, :name

    def id
      @id ||= -1
    end

    def name
      @name ||= ::I18n.t('timelines.filter.noneElement')
    end

  end

  unloadable

  serialize :options

  self.table_name = 'timelines'

  default_scope :order => 'name ASC'

  belongs_to :project, :class_name => "Project"

  validates_presence_of :name, :project
  validates_length_of :name, :maximum => 255, :unless => lambda { |e| e.name.blank? }

  attr_accessible :name, :options

  before_save :remove_empty_options_values
  before_save :split_joined_options_values

  @@allowed_option_keys = [
    "columns",
    "compare_to_absolute",
    "compare_to_historical_one",
    "compare_to_historical_two",
    "compare_to_relative",
    "compare_to_relative_unit",
    "comparison",
    "exclude_empty",
    "exclude_own_planning_elements",
    "exclude_reporters",
    "exist",
    "grouping_one_enabled",
    "grouping_one_selection",
    "grouping_one_sort",
    "grouping_two_enabled",
    "grouping_two_selection",
    "grouping_two_sort",
    "hide_chart",
    "hide_other_group",
    "initial_outline_expansion",
    "parents",
    "planning_element_responsibles",
    "planning_element_status",
    "planning_element_time",
    "planning_element_time_absolute_one",
    "planning_element_time_absolute_two",
    "planning_element_time_relative_one",
    "planning_element_time_relative_one_unit",
    "planning_element_time_relative_two",
    "planning_element_time_relative_two_unit",
    "planning_element_time_types",
    "planning_element_types",
    "project_responsibles",
    "project_sort",
    "project_status",
    "project_types",
    "timeframe_end",
    "timeframe_start",
    "vertical_planning_elements",
    "zoom_factor"
  ]

  @@available_columns = [
    "start_date",
    "due_date",
    "type",
    "status",
    "responsible",
    "assigned_to"
  ]

  @@available_zoom_factors = [
    'years',
    'quarters',
    'months',
    'weeks',
    'days'
  ]

  @@available_initial_outline_expansions = [
    'aggregation',
    'level1',
    'level2',
    'level3',
    'level4',
    'level5',
    'all'
  ]

  def filter_options
    @@allowed_option_keys
  end

  def default_options
    {}
  end

  def options
    read_attribute(:options) || self.default_options
  end

  def options=(other)
    other.assert_valid_keys(*filter_options)
    write_attribute(:options, other)
  end

  def json_options
    json = with_escape_html_entities_in_json{ options.to_json }
    json.html_safe
  end

  def available_columns
    @@available_columns
  end

  def available_initial_outline_expansions
    @@available_initial_outline_expansions
  end

  def selected_initial_outline_expansion
    if options["initial_outline_expansion"].present?
      options["initial_outline_expansion"].first.to_i
    else
      -1
    end
  end

  def available_zoom_factors
    @@available_zoom_factors
  end

  def selected_zoom_factor
    if options["zoom_factor"].present?
      options["zoom_factor"].first.to_i
    else
      -1
    end
  end

  def available_planning_element_types

    # TODO: this should not be all planning element types, but instead
    # all types that are available in the project the timeline is
    # referencing, and all planning element types available in projects
    # that are reporting into the project that this timeline is
    # referencing.

    Type.find(:all, :order => :name)
  end

  def available_planning_element_status
    types = Project.visible.includes(:types).map(&:types).flatten.uniq
    types.map(&:statuses).flatten.uniq
  end

  def selected_planning_element_status
    resolve_with_none_element(:planning_element_status) do |ary|
      Status.find(ary)
    end
  end

  def selected_planning_element_types
    resolve_with_none_element(:planning_element_types) do |ary|
      Type.find(ary)
    end
  end

  def selected_planning_element_time_types
    resolve_with_none_element(:planning_element_time_types) do |ary|
      Type.find(ary)
    end
  end

  def available_project_types
    ProjectType.find(:all)
  end

  def selected_project_types
    resolve_with_none_element(:project_types) do |ary|
      ProjectType.find(ary)
    end
  end

  def available_project_status
    ReportedProjectStatus.find(:all, :order => :name)
  end

  def selected_project_status
    resolve_with_none_element(:project_status) do |ary|
      ReportedProjectStatus.find(ary)
    end
  end

  def available_responsibles
    User.find(:all).sort_by(&:name)
  end

  def selected_project_responsibles
    resolve_with_none_element(:project_responsibles) do |ary|
      User.find(ary)
    end
  end

  def selected_planning_element_responsibles
    resolve_with_none_element(:planning_element_responsibles) do |ary|
      User.find(ary)
    end
  end

  def available_parents
    selectable_projects
  end

  def selected_parents
    resolve_with_none_element(:parents) do |ary|
      Project.find(ary)
    end
  end

  def selected_columns
    if options["columns"].present?
      options["columns"]
    else
      []
    end
  end

  def planning_element_time
    if options["planning_element_time"].present?
      options["planning_element_time"]
    else
      'absolute'
    end
  end

  def comparison
    if options["comparison"].present?
      options["comparison"]
    else
      'none'
    end
  end

  def selected_grouping_projects
    resolve_with_none_element(:grouping_one_selection) do |ary|
      projects = Project.find(ary)
      projectsHashMap = Hash[projects.collect { |v| [v.id, v]}]

      ary.map { |a| projectsHashMap[a] }
    end
  end

  def available_grouping_projects
    selectable_projects
  end

  def selectable_projects
    Project.selectable_projects
  end

  def selected_grouping_project_types
    resolve_with_none_element(:grouping_two_selection) do |ary|
      ProjectType.find(ary)
    end
  end

  def available_grouping_project_types
    ProjectType.available_grouping_project_types
  end

  protected

  def remove_empty_options_values
    unless self[:options].nil?
      self[:options].reject! do |key, value|
        value.instance_of?(Array) && value.length == 1 && value.first.empty?
      end
    end
  end

  def split_joined_options_values
    unless self[:options].nil?
      self[:options].each_pair do |key, value|
        if value.instance_of?(Array) && value.length == 1 then
          self[:options][key] = value[0].split(",")
        end
      end
    end
  end

  def array_of_ids_or_empty_array(options_field)
    array_or_empty(options_field) { |ary| ary.delete_if(&:empty?).map(&:to_i) }
  end

  def array_or_empty(options_field)
    if options[options_field].present?
      if block_given?
        yield options[options_field]
      else
        return options[options_field]
      end
    else
      []
    end
  end

  def resolve_with_none_element(options_field, &block)
    collection = []
    collection += [Empty.new] if (ary = array_of_comma_seperated(options_field)).delete(-1)
    begin
      collection += block.call(ary);
    rescue

    end
    return collection
  end

  def array_of_comma_seperated(options_field)
    array_or_empty(options_field) do |ary|
      ary.map(&:to_i).reject do |value|
        value < -1 || value == 0
      end
    end
  end

  # TODO: this should go somewhere else, once it is needed at multiple places
  def with_escape_html_entities_in_json
    oldvalue = ActiveSupport.escape_html_entities_in_json
    ActiveSupport.escape_html_entities_in_json = true

    yield
  ensure
    ActiveSupport.escape_html_entities_in_json = oldvalue
  end
end


text:
external help file: Microsoft.Azure.Commands.Resources.dll-Help.xml
ms.assetid: 115A7612-4856-47AE-AEE4-918350CD7009
online version:
schema: 2.0.0
---

# Set-AzureRmRoleDefinition

## SYNOPSIS
Modifies a custom role in Azure RBAC.
Provide the modified role definition either as a JSON file or as a PSRoleDefinition.
First, use the Get-AzureRmRoleDefinition command to retrieve the custom role that you wish to modify.
Then, modify the properties that you wish to change.
Finally, save the role definition using this command.

## SYNTAX

### InputFileParameterSet
```
Set-AzureRmRoleDefinition -InputFile <String> [-InformationAction <ActionPreference>]
 [-InformationVariable <String>]
```

### RoleDefinitionParameterSet
```
Set-AzureRmRoleDefinition -Role <PSRoleDefinition> [-InformationAction <ActionPreference>]
 [-InformationVariable <String>]
```

## DESCRIPTION
The Set-AzureRmRoleDefinition cmdlet updates an existing custom role in Azure Role-Based Access Control.
Provide the updated role definition as an input to the command as a JSON file or a PSRoleDefinition object.
The role definition for the updated custom role MUST contain the Id and all other required properties of the role even if they are not updated: DisplayName, Description, Actions, AssignableScopes.
NotActions is optional.

Following is a sample updated role definition json for Set-AzureRmRoleDefinition

{
        "Id": "52a6cc13-ff92-47a8-a39b-2a8205c3087e",
        "Name": "Updated Role",
        "Description": "Can monitor all resources and start and restart virtual machines",
        "Actions":
        \[
            "*/read",
            "Microsoft.ClassicCompute/virtualmachines/restart/action",
            "Microsoft.ClassicCompute/virtualmachines/start/action"
        \]
        "AssignableScopes": \["/subscriptions/4004a9fd-d58e-48dc-aeb2-4a4aec58606f"\]
    }

## EXAMPLES

### --------------------------  Update using PSRoleDefinitionObject  --------------------------
@{paragraph=PS C:\\\>}

```
PS C:\> $roleDef = Get-AzureRmRoleDefinition "Contoso On-Call"
          PS C:\> $roleDef.Actions.Add("Microsoft.ClassicCompute/virtualmachines/start/action")
          PS C:\> $roleDef.Description = "Can monitor all resources and start and restart virtual machines"
          PS C:\> $roleDef.AssignableScopes = @("/subscriptions/eb910d4f-edbf-429b-94F6-d76bae7ff401", "/subscriptions/a846d197-5eac-45c7-b885-a6227fe6d388")

          PS C:\> New-AzureRmRoleDefinition -Role $roleDef
```

### --------------------------  Create using JSON file  --------------------------
@{paragraph=PS C:\\\>}

```
PS C:\> Set-AzureRmRoleDefinition -InputFile C:\Temp\roleDefinition.json
```

## PARAMETERS

### -InputFile
File name containing a single json role definition to be updated.
Only include the properties that are to be updated in the JSON.
Id property is Required.

```yaml
Type: String
Parameter Sets: InputFileParameterSet
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -InformationAction
Specifies how this cmdlet responds to an information event.

The acceptable values for this parameter are:

- Continue
- Ignore
- Inquire
- SilentlyContinue
- Stop
- Suspend

```yaml
Type: ActionPreference
Parameter Sets: (All)
Aliases: infa

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -InformationVariable
Specifies an information variable.

```yaml
Type: String
Parameter Sets: (All)
Aliases: iv

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Role
Role definition object to be updated

```yaml
Type: PSRoleDefinition
Parameter Sets: RoleDefinitionParameterSet
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: True (ByValue)
Accept wildcard characters: False
```

## INPUTS

## OUTPUTS

## NOTES
Keywords: azure, azurerm, arm, resource, management, manager, resource, group, template, deployment

## RELATED LINKS

[Get-AzureRmProviderOperation]()

[Get-AzureRmRoleDefinition]()

[New-AzureRmRoleDefinition]()

[Remove-AzureRmRoleDefinition]()


text:
#include <rtthread.h>
#include <rtdevice.h>
#include "board.h"
#include "cpuport.h"

#ifdef RT_USING_SERIAL
    #include <drv_uart.h>
#endif

/** _end symbol defined in linker script of Nuclei SDK */
extern void *_end;

/** _heap_end symbol defined in linker script of Nuclei SDK */
extern void *_heap_end;
#define HEAP_BEGIN  &_end
#define HEAP_END    &_heap_end

/*
 * - Implemented and defined in Nuclei SDK system_<Device>.c file
 * - Required macro NUCLEI_BANNER set to 0
 */
extern void _init(void);

/**
 * @brief Setup hardware board for rt-thread
 *
 */
void rt_hw_board_init(void)
{
    /* OS Tick Configuration */
    rt_hw_ticksetup();

#ifdef RT_USING_HEAP
    rt_system_heap_init((void *) HEAP_BEGIN, (void *) HEAP_END);
#endif

    _init(); // __libc_init_array is not used in RT-Thread

    /* UART driver initialization is open by default */
#ifdef RT_USING_SERIAL
    rt_hw_uart_init();
#endif

    /* Set the shell console output device */
#if defined(RT_USING_CONSOLE) && defined(RT_USING_DEVICE)
    rt_console_set_device(RT_CONSOLE_DEVICE_NAME);
#endif

    /* Board underlying hardware initialization */
#ifdef RT_USING_COMPONENTS_INIT
    rt_components_board_init();
#endif
}

/******************** end of file *******************/


text:
const DEFAULT_DURATION = 600;

const easeOutQuad = (t: number) => (t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1);

const createScrollIntoView = (target: Element, container: Element, indefinite?: boolean, offset = 0) => {
    let rafId: number;
    let start: number;
    const duration = DEFAULT_DURATION;

    const run = (timestamp: number) => {
        if (!start) {
            start = timestamp;
        }

        const time = timestamp - start;
        const percent = easeOutQuad(Math.min(time / duration, 1));

        const rectTarget = target.getBoundingClientRect();
        const rectContainer = container.getBoundingClientRect();
        const diff = rectTarget.top - rectContainer.top - offset;
        const scrollY = container.scrollTop + diff * percent;

        container.scrollTop = Math.round(scrollY);

        if (time < duration || indefinite) {
            rafId = requestAnimationFrame(run);
        }
    };
    rafId = requestAnimationFrame(run);

    return () => {
        cancelAnimationFrame(rafId);
    };
};

export default createScrollIntoView;


text:
<ion-header>
    <ion-navbar color="light">
        <button ion-button menuToggle>
            <ion-icon name="ios-menu-outline"></ion-icon>
        </button>
        <ion-title>
            {{'ACCOUNT' | translate }}
        </ion-title>
    </ion-navbar>
</ion-header>

<ion-content id="account" padding>

                {{'YOUR_ADDRESS' | translate }}

                {{selectedWallet?.address.pretty()}}

            <button ion-button color="positive" block on-click="shareAddress()">
                {{'SHARE_ADDRESS' | translate }}
            </button>

                {{'PRIVATE_KEY' | translate }}

                {{'PRIVATE_KEY_SUBTITLE' | translate }}

            <ion-list id="private-key-list">
                <ion-item id="password-input" *ngIf='!privateKey'>
                    <ion-label>
                        {{'PASSWORD' | translate }}
                    </ion-label>
                    <ion-input type="password" [(ngModel)]="password" name="password"></ion-input>
                </ion-item>

                    {{'PASSWORD_WARNING' | translate }}

            </ion-list>

            <ion-row *ngIf='privateKey'>
                <ion-col col-8>
{{privateKey}}

                </ion-col>
                <ion-col col-4>
                    <button ion-button color="stable" block on-click="copyPrivateKeyToClipboard()">
                        {{'COPY' | translate }}
                    </button>
                </ion-col>
            </ion-row>
            <button id="show-button" ion-button color="stable" block on-click="showPrivateKey()"
                    [disabled]="!password" *ngIf='!privateKey'>
                {{'SHOW_PRIVATE_KEY' | translate }}

            </button>
            <button id="hide-button" ion-button color="stable" block on-click="clearPrivateKey()"
                    *ngIf='privateKey'>
                {{'HIDE_PRIVATE_KEY' | translate }}
            </button>

            <button ion-button color="positive" block on-click="logout()">
                {{'LOGOUT' | translate }}
            </button>

</ion-content>


text:
package com.conmigo.app.util;

public final class Constant {

    private Constant() {
        super();
    }

    // Strings
    public static final String BARRA = "/";
    public final static String OK = "OK";
    public final static String KO = "KO";
    public final static String ANONYMOUS_USER = "anonymousUser";
    public final static String LOCALE_ES = "es";

    public static enum Role {
        USER, ADMIN
    }

    public static enum Combo {
        GENDER
    }
}


text:
<?php
/**
 *
 * User: Martin Halamíček
 * Date: 16.5.12
 * Time: 11:46
 *
 */

namespace Keboola\Test\Backend\CommonPart2;

use Keboola\StorageApi\Client;
use Keboola\StorageApi\ClientException;
use Keboola\StorageApi\Downloader\BlobClientFactory;
use Keboola\Test\StorageApiTestCase;
use Keboola\Csv\CsvFile;

class SlicedImportsTest extends StorageApiTestCase
{

    public function setUp(): void
    {
        parent::setUp();
        $this->initEmptyTestBucketsForParallelTests();
    }

    public function testSlicedImportGzipped(): void
    {
        $slices = [
            __DIR__ . '/../../_data/sliced/neco_0000_part_00.gz',
            __DIR__ . '/../../_data/sliced/neco_0001_part_00.gz',
        ];

        $uploadOptions = new \Keboola\StorageApi\Options\FileUploadOptions();
        $uploadOptions
            ->setFileName('entries_')
            ->setIsEncrypted(true)
            ->setIsSliced(true);

        $fileId = $this->_client->uploadSlicedFile(
            $slices,
            $uploadOptions
        );

        $headerFile = new CsvFile(__DIR__ . '/../../_data/sliced/header.csv');
        $tableId = $this->_client->createTable($this->getTestBucketId(self::STAGE_IN), 'entries', $headerFile, [
            'primaryKey' => 'id',
        ]);
        $table = $this->_client->getTable($tableId);
        if ($table['bucket']['backend'] === self::BACKEND_SYNAPSE) {
            $this->markTestSkipped('Empty ECLOSURE is not possible with synapse.');
        }
        $this->_client->writeTableAsyncDirect($tableId, [
            'dataFileId' => $fileId,
            'columns' => $headerFile->getHeader(),
            'delimiter' => '|',
            'enclosure' => '',
        ]);
    }

    public function testSlicedImportSingleFile(): void
    {
        $slices = [
            __DIR__ . '/../../_data/languages.no-headers.csv',
        ];

        $uploadOptions = new \Keboola\StorageApi\Options\FileUploadOptions();
        $uploadOptions
            ->setFileName('languages_')
            ->setIsSliced(true)
            ->setIsEncrypted(false);

        $fileId = $this->_client->uploadSlicedFile(
            $slices,
            $uploadOptions
        );

        $tableId = $this->_client->createTable(
            $this->getTestBucketId(self::STAGE_IN),
            'entries',
            new CsvFile(__DIR__ . '/../../_data/languages.not-normalized-column-names.csv')
        );
        $this->_client->deleteTableRows($tableId);
        $this->_client->writeTableAsyncDirect($tableId, [
            'dataFileId' => $fileId,
            'delimiter' => ',',
            'enclosure' => '"',
            'escapedBy' => '',
            'columns' => [
                'language-id',
                'language-name',
            ],
        ]);

        $this->assertLinesEqualsSorted(
            file_get_contents(__DIR__ . '/../../_data/languages.normalized-column-names.csv'),
            $this->_client->getTableDataPreview($tableId, [
                'format' => 'rfc',
            ]),
            'imported data comparsion'
        );

        // incremental
        $this->_client->writeTableAsyncDirect($tableId, [
            'dataFileId' => $fileId,
            'incremental' => true,
            'delimiter' => ',',
            'enclosure' => '"',
            'escapedBy' => '',
            'columns' => [
                'language-id',
                'language-name',
            ],
        ]);

        $data = (string) file_get_contents(__DIR__ . '/../../_data/languages.normalized-column-names.csv');
        $lines = explode("\n", $data);
        array_shift($lines);
        $data = $data . implode("\n", $lines);

        $this->assertLinesEqualsSorted(
            $data,
            $this->_client->getTableDataPreview($tableId, [
                'format' => 'rfc',
            ]),
            'imported data comparsion'
        );
    }

    public function testSlicedImportMissingManifest(): void
    {
        $uploadOptions = new \Keboola\StorageApi\Options\FileUploadOptions();
        $uploadOptions
            ->setFileName('entries_')
            ->setIsEncrypted(false)
            ->setIsSliced(true);
        $slicedFile = $this->_client->prepareFileUpload($uploadOptions);

        $tableId = $this->_client->createTable($this->getTestBucketId(self::STAGE_IN), 'entries', new CsvFile(__DIR__ . '/../../_data/sliced/header.csv'));

        try {
            $this->_client->writeTableAsyncDirect($tableId, [
                'dataFileId' => $slicedFile['id'],
                'withoutHeaders' => true,
                'delimiter' => '|',
                'enclosure' => '',
                'escapedBy' => '',
            ]);
            $this->fail('Exception should be thrown');
        } catch (\Keboola\StorageApi\ClientException $e) {
            $this->assertEquals('storage.manifestFileMissing', $e->getStringCode());
        }
    }

    public function testInvalidFilesInManifest(): void
    {
        $tokenData = $this->_client->verifyToken();
        if ($tokenData['owner']['defaultBackend'] == self::BACKEND_REDSHIFT) {
            $this->markTestSkipped('TODO: redshift bug to fix');
        }

        $uploadOptions = new \Keboola\StorageApi\Options\FileUploadOptions();
        $uploadOptions
            ->setFileName('entries_')
            ->setIsEncrypted(false)
            ->setIsSliced(true);
        $slicedFile = $this->_client->prepareFileUpload($uploadOptions);

        if ($slicedFile['provider'] === Client::FILE_PROVIDER_GCP) {
            $uploadParams = $slicedFile['gcsUploadParams'];

            $client = $this->getGcsClientClient($uploadParams);

            $bucket = $client->bucket($uploadParams['bucket']);
            $file = fopen(__DIR__ . '/../../_data/sliced/neco_0000_part_00.gz', 'r');
            if (!$file) {
                throw new ClientException("Cannot open file {$file}");
            }
            $bucket->upload(
                $file,
                [
                    'name' => $uploadParams['key'] . 'part001.gz',
                ]
            );

            /** @var string $data */
            $data = json_encode([
                'entries' => [
                    [
                        'url' => 'gs://' . $uploadParams['bucket'] . '/' . $uploadParams['key'] . 'part001.gz',
                        'mandatory' => true,
                    ],
                    [
                        'url' => 'gs://' . $uploadParams['bucket'] . '/' . $uploadParams['key'] . 'part001.gzsome',
                        'mandatory' => true,
                    ],
                ],
            ]);
            $bucket->upload(
                $data,
                [
                    'name' => $uploadParams['key'] . 'manifest',
                ]
            );
        } elseif ($slicedFile['provider'] === Client::FILE_PROVIDER_AZURE) {
            $uploadParams = $slicedFile['absUploadParams'];

            $blobClient = BlobClientFactory::createClientFromConnectionString(
                $uploadParams['absCredentials']['SASConnectionString']
            );
            $blobClient->createBlockBlob(
                $uploadParams['container'],
                sprintf(
                    '%s%s',
                    $uploadParams['blobName'],
                    'part001.gz'
                ),
                fopen(__DIR__ . '/../../_data/sliced/neco_0000_part_00.gz', 'r')
            );

            $blobClient->createBlockBlob(
                $uploadParams['container'],
                $uploadParams['blobName'] . 'manifest',
                json_encode([
                    'entries' => [
                        [
                            'url' => sprintf(
                                'azure://%s.blob.core.windows.net/%s/%s%s',
                                $uploadParams['accountName'],
                                $uploadParams['container'],
                                $uploadParams['blobName'],
                                'part001.gz'
                            ),
                        ],
                        [
                            'url' => sprintf(
                                'azure://%s.blob.core.windows.net/%s/%s%s',
                                $uploadParams['accountName'],
                                $uploadParams['container'],
                                $uploadParams['blobName'],
                                'part001.gzsome'
                            ),
                        ],
                    ],
                ])
            );
        } else {
            $uploadParams = $slicedFile['uploadParams'];

            $s3Client = new \Aws\S3\S3Client([
                'credentials' => [
                    'key' => $uploadParams['credentials']['AccessKeyId'],
                    'secret' => $uploadParams['credentials']['SecretAccessKey'],
                    'token' => $uploadParams['credentials']['SessionToken'],
                ],
                'version' => 'latest',
                'region' => $slicedFile['region'],
            ]);

            $s3Client->putObject([
                'Bucket' => $uploadParams['bucket'],
                'Key' => $uploadParams['key'] . 'part001.gz',
                'Body' => fopen(__DIR__ . '/../../_data/sliced/neco_0000_part_00.gz', 'r+'),
            ])->get('ObjectURL');

            $s3Client->putObject([
                'Bucket' => $uploadParams['bucket'],
                'Key' => $uploadParams['key'] . 'manifest',
                'Body' => json_encode([
                    'entries' => [
                        [
                            'url' => 's3://' . $uploadParams['bucket'] . '/' . $uploadParams['key'] . 'part001.gz',
                            'mandatory' => true,
                        ],
                        [
                            'url' => 's3://' . $uploadParams['bucket'] . '/' . $uploadParams['key'] . 'part001.gzsome',
                            'mandatory' => true,
                        ],
                    ],
                ]),
            ])->get('ObjectURL');
        }

        $tableId = $this->_client->createTable($this->getTestBucketId(), 'entries', new CsvFile(__DIR__ . '/../../_data/sliced/header.csv'));

        try {
            $this->_client->writeTableAsyncDirect($tableId, [
                'dataFileId' => $slicedFile['id'],
                'columns' => ['id', 'added_manually', 'start', 'end', 'task_id', 'project_id'],
                'delimiter' => '|',
            ]);
            $this->fail('Exception should be thrown');
        } catch (\Keboola\StorageApi\ClientException $e) {
            $this->assertEquals('storage.importFileMissing', $e->getStringCode());
        }
    }

    public function testUnauthorizedAccessInManifestFile(): void
    {
        $tableId = $this->_client->createTable($this->getTestBucketId(self::STAGE_IN), 'entries', new CsvFile(__DIR__ . '/../../_data/sliced/header.csv'));

        $uploadOptions = new \Keboola\StorageApi\Options\FileUploadOptions();
        $uploadOptions
            ->setFileName('entries_')
            ->setIsEncrypted(false)
            ->setIsSliced(true);

        // First upload
        $slicedFile = $this->_client->prepareFileUpload($uploadOptions);

        if ($slicedFile['provider'] === Client::FILE_PROVIDER_GCP) {
            $uploadParams = $slicedFile['gcsUploadParams'];
            $client = $this->getGcsClientClient($uploadParams);

            $bucket = $client->bucket($uploadParams['bucket']);

            $file = fopen(__DIR__ . '/../../_data/escaping.csv', 'r+');
            if (!$file) {
                throw new ClientException("Cannot open file {$file}");
            }
            $object = $bucket->upload(
                $file,
                [
                    'name' => $uploadParams['key'] . 'part001.gz',
                ]
            );

            $part1URL = $object->gcsUri();
        } elseif ($slicedFile['provider'] === Client::FILE_PROVIDER_AZURE) {
            $uploadParams = $slicedFile['absUploadParams'];

            $blobClient = BlobClientFactory::createClientFromConnectionString(
                $uploadParams['absCredentials']['SASConnectionString']
            );

            $blobClient->createBlockBlob(
                $uploadParams['container'],
                sprintf(
                    '%s%s',
                    $uploadParams['blobName'],
                    'part001.gz'
                ),
                fopen(__DIR__ . '/../../_data/escaping.csv', 'r')
            );

            $part1URL = sprintf(
                'azure://%s.blob.core.windows.net/%s/%s%s',
                $uploadParams['accountName'],
                $uploadParams['container'],
                $uploadParams['blobName'],
                'part001.gz'
            );
        } else {
            $uploadParams = $slicedFile['uploadParams'];
            $s3Client = new \Aws\S3\S3Client([
                'credentials' => [
                    'key' => $uploadParams['credentials']['AccessKeyId'],
                    'secret' => $uploadParams['credentials']['SecretAccessKey'],
                    'token' => $uploadParams['credentials']['SessionToken'],
                ],
                'version' => 'latest',
                'region' => $slicedFile['region'],
            ]);

            $part1URL = $s3Client->putObject([
                'Bucket' => $uploadParams['bucket'],
                'Key' => $uploadParams['key'] . 'part001.gz',
                'Body' => fopen(__DIR__ . '/../../_data/escaping.csv', 'r+'),
            ])->get('ObjectURL');
        }

        // Second upload
        $slicedFile = $this->_client->prepareFileUpload($uploadOptions);

        if ($slicedFile['provider'] === Client::FILE_PROVIDER_GCP) {
            $uploadParams = $slicedFile['gcsUploadParams'];
            $client = $this->getGcsClientClient($uploadParams);

            $bucket = $client->bucket($uploadParams['bucket']);

            /** @var string $data */
            $data = json_encode([
                'entries' => [
                    [
                        'url' => $part1URL,
                    ],
                ],
            ]);
            $bucket->upload(
                $data,
                [
                    'name' => $uploadParams['key'] . 'manifest',
                ]
            );
        } elseif ($slicedFile['provider'] === Client::FILE_PROVIDER_AZURE) {
            $uploadParams = $slicedFile['absUploadParams'];

            $blobClient = BlobClientFactory::createClientFromConnectionString(
                $uploadParams['absCredentials']['SASConnectionString']
            );

            $blobClient->createBlockBlob(
                $uploadParams['container'],
                $uploadParams['blobName'] . 'manifest',
                json_encode([
                    'entries' => [
                        [
                            'url' => $part1URL,
                        ],
                    ],
                ])
            );
        } else {
            $uploadParams = $slicedFile['uploadParams'];
            $s3Client = new \Aws\S3\S3Client([
                'credentials' => [
                    'key' => $uploadParams['credentials']['AccessKeyId'],
                    'secret' => $uploadParams['credentials']['SecretAccessKey'],
                    'token' => $uploadParams['credentials']['SessionToken'],
                ],
                'version' => 'latest',
                'region' => $slicedFile['region'],
            ]);

            $s3Client->putObject([
                'Bucket' => $uploadParams['bucket'],
                'Key' => $uploadParams['key'] . 'manifest',
                'Body' => json_encode([
                    'entries' => [
                        [
                            'url' => $part1URL,
                        ],
                    ],
                ]),
            ])->get('ObjectURL');
        }

        try {
            $this->_client->writeTableAsyncDirect($tableId, [
                'dataFileId' => $slicedFile['id'],
                'withoutHeaders' => true,
                'delimiter' => '|',
            ]);
            $this->fail('Exception should be thrown');
        } catch (\Keboola\StorageApi\ClientException $e) {
            $this->assertEquals('storage.unauthorizedAccess', $e->getStringCode());
        }
    }
}


text:
<?php
namespace Ginger\Model\File;

use Zend\Stdlib\ArrayUtils;

class File
{
    protected $dir;
    protected $filename;

    public function __construct($dir, $filename)
    {
        $this->dir = $dir;
        $this->filename = $filename;
    }

    public function getFilename()
    {
        return $this->filename;
    }

    public function getDir()
    {
        return $this->dir;
    }

    public function getPath()
    {
        return $this->dir . '/' . $this->filename;
    }

    /**
     *
     * @return array
     *
     * @throws Exception\RuntimeException
     */
    public function getData()
    {
        try {
            return ReaderFactory::fromFile($this->getPath());
        } catch (\Zend\Config\Exception\ExceptionInterface $e) {
            throw new Exception\RuntimeException(
                sprintf(
                    'An error occured while reading data from file "%s". See previous exception for more details.',
                    $this->getPath()
                    ),
                $e->getCode(),
                $e
                );
        }

    }

    public function writeData(array $data)
    {
        WriterFactory::toFile($this->getPath(), $data);
        return $this;
    }

    public function appendElement(array $dataElement)
    {
        WriterFactory::addToFile($this->getPath(), $dataElement);
    }

    public function mergeData(array $data)
    {
        $data = ArrayUtils::merge($this->getData(), $data);

        WriterFactory::toFile($this->getPath(), $data);
    }

    /**
     * Rename the file
     *
     * @param stirng $filename
     *
     * @return File
     *
     * @throws Exception\RuntimeException
     */
    public function rename($filename)
    {
        set_error_handler(
            function($error, $message = '', $file = '', $line = 0) use ($filename) {
                throw new Exception\RuntimeException(sprintf(
                    'Error renaming file "%s" to "%s": %s',
                    $filename, $message
                ), $error);
            }, E_WARNING
        );

        rename($this->dir . '/' . $this->filename, $this->dir . '/' . $filename);

        restore_error_handler();

        $this->filename = $filename;
        return $this;
    }

    /**
     * @param string $dir
     *
     * @return File
     *
     * @throws Exception\RuntimeException
     */
    public function move($dir)
    {
        $oldDir = $this->dir;
        $filename = $this->filename;

        set_error_handler(
            function($error, $message = '', $file = '', $line = 0) use ($dir, $oldDir, $filename) {
                throw new Exception\RuntimeException(sprintf(
                    'Failed to move file "%s" from "%s" to "%s": %s',
                    $filename, $oldDir, $dir, $message
                ), $error);
            }, E_WARNING
        );

        copy($this->getPath(), $dir . '/' . $this->filename);

        restore_error_handler();

        $this->remove();

        $this->dir = $dir;
        return $this;
    }

    /**
     * @param string $dir
     *
     * @return File
     *
     * @throws Exception\RuntimeException
     */
    public function copy($dir)
    {
        $oldDir = $this->dir;
        $filename = $this->filename;

        set_error_handler(
            function($error, $message = '', $file = '', $line = 0) use ($dir, $oldDir, $filename) {
                throw new Exception\RuntimeException(sprintf(
                    'Failed to copy file "%s" from "%s" to "%s": %s',
                    $filename, $oldDir, $dir, $message
                ), $error);
            }, E_WARNING
        );

        copy($this->getPath(), $dir . '/' . $this->filename);

        restore_error_handler();

        return new File($dir, $this->filename);
    }

    /**
     *
     * @return File
     *
     * @throws Exception\RuntimeException
     */
    public function remove()
    {
        $dir = $this->dir;
        $filename = $this->filename;

        set_error_handler(
            function($error, $message = '', $file = '', $line = 0) use ($dir, $filename) {
                throw new Exception\RuntimeException(sprintf(
                    'Failed to remove file "%s" from "%s": %s',
                    $filename, $dir, $message
                ), $error);
            }, E_WARNING
        );

        unlink($this->getPath());

        restore_error_handler();

        return $this;
    }
}


text:
import { Admin } from './../../components/admins/admin';

export const ADMIN: Admin = {
    id:1,
    name:"admin1",
    password: "sadıou8oıasjd1023klsadmo"
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/BrainifyNodeServer.iml" filepath="$PROJECT_DIR$/BrainifyNodeServer.iml" />
    </modules>
  </component>
</project>


text:
class ReportIssue
  include ActiveModel::Validations
  include ActiveModel::Conversion
  include SimpleCaptcha::ModelHelpers
  extend ActiveModel::Naming
  apply_simple_captcha

  # The name of the person reporting the issue
  attr_accessor :name
  # The email of the person reporting the issue
  attr_accessor :email
  # The category that the issue falls into
  attr_accessor :category
  # The approximate date/time that the issue occured
  attr_accessor :when_issue_occured
  # A description of the issue
  attr_accessor :description
  # A captcha to prove that the person submitting the issue is not a spam bot
  attr_accessor :captcha
  # The available valid options for the #category attribute
  attr_reader   :available_categories

  # The available valid options for the #category attribute
  AVAILABLE_CATEGORIES = [
    'Applying For An Account',
    'Uploading Cuffdiff Data',
    'Uploading Trinity With EdgeR Data',
    'Uploading Fasta Sequences (Any Program)',
    'Querying for Gene Differential Expression Tests',
    'Querying for Transcript Differential Expression Tests',
    'Querying for Transcript Isoforms',
    'Querying With Blastn',
    'Querying With TBlastn',
    'Querying With TBlastx',
    'Other'
  ]

  validates :name, :presence => true
  validates :email, :presence => true,
                    :format => /\A[^@]+@[^@]+\z/
  validates :category, :presence => true,
                       :inclusion => {:in => AVAILABLE_CATEGORIES}
  validates :when_issue_occured, :presence => true
  validates :description, :presence => true

  ###
  # parameters::
  # * <b>current_user:</b> The currently logged in user
  def initialize(current_user)
    @current_user = current_user
  end

  # Set the view model's attributes or set those attributes to their
  # default values
  def set_attributes_and_defaults(attributes = {})
    if not attributes.empty?
      year = attributes['when_issue_occured(1i)'].to_i
      month = attributes['when_issue_occured(2i)'].to_i
      day = attributes['when_issue_occured(3i)'].to_i
      hour = attributes['when_issue_occured(4i)'].to_i
      minute = attributes['when_issue_occured(5i)'].to_i
      @when_issue_occured = DateTime.new(year,month,day,hour,minute)
    else
      @when_issue_occured = DateTime.now
    end
    #Load in any values from the form
    attributes.each do |name, value|
        next if name.match(/when_issue_occured/)
        send("#{name}=", value)
    end
    #Set available categories
    @available_categories = AVAILABLE_CATEGORIES
    if not @current_user.nil?
      @name = @current_user.name
      @email = @current_user.email
    end
  end

  ###
  # Report the issue to the adminstrator(s) by sending email(s) containing the
  # issue information.
  def report_issue()
    #Don't query if it is not valid
    return if not self.valid?
    #Send email
    HomeMailer.send_report_on_issue(self)
  end

  ###
  # According http://railscasts.com/episodes/219-active-model?view=asciicast,
  # this defines that this model does not persist in the database.
  def persisted?
      return false
  end
end


text:
div.jGrowl {
	padding: 			10px;
	z-index: 			9999;
	color: 				#fff;
	font-size: 			12px;
}

/** Special IE6 Style Positioning **/
div.ie6 {
	position: 			absolute;
}

div.ie6.top-right {
	right: 				auto;
	bottom: 			auto;
	left: 				expression( ( 0 - jGrowl.offsetWidth + ( document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth ) + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px' );
  	top: 				expression( ( 0 + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px' );
}

div.ie6.top-left {
	left: 				expression( ( 0 + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px' );
	top: 				expression( ( 0 + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px' );
}

div.ie6.bottom-right {
	left: 				expression( ( 0 - jGrowl.offsetWidth + ( document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth ) + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px' );
	top: 				expression( ( 0 - jGrowl.offsetHeight + ( document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px' );
}

div.ie6.bottom-left {
	left: 				expression( ( 0 + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px' );
	top: 				expression( ( 0 - jGrowl.offsetHeight + ( document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px' );
}

div.ie6.center {
	left: 				expression( ( 0 + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px' );
	top: 				expression( ( 0 + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px' );
	width: 				100%;
}

/** Normal Style Positions **/
div.jGrowl {
	position:			absolute;
}

body > div.jGrowl {
	position:			fixed;
}

div.jGrowl.top-left {
	left: 				0px;
	top: 				0px;
}

div.jGrowl.top-right {
	right: 				0px;
	top: 				0px;
}

div.jGrowl.bottom-left {
	left: 				0px;
	bottom:				0px;
}

div.jGrowl.bottom-right {
	right: 				0px;
	bottom: 			0px;
}

div.jGrowl.center {
	top: 				0px;
	width: 				50%;
	left: 				25%;
}

/** Cross Browser Styling **/
div.center div.jGrowl-notification, div.center div.jGrowl-closer {
	margin-left: 		auto;
	margin-right: 		auto;
}

div.jGrowl div.jGrowl-notification, div.jGrowl div.jGrowl-closer {
	background-color: 		#000000;
	background-image:		url(../../images/headers/carbon.png);
	background-repeat:		repeat;
	color:					#ffffff;
	zoom: 					1;
	width: 					235px;
	padding: 				10px;
	margin-top: 			5px;
	margin-bottom: 			5px;
	font-family: 			Tahoma, Arial, Helvetica, sans-serif;
	font-size: 				1em;
	text-align: 			left;
	display: 				none;
	border:					1px solid #000000;
	border:					1px solid rgba(0, 0, 0, .95);
	-moz-border-radius: 	5px;
	-webkit-border-radius:	5px;
	border-radius:			5px;
	-webkit-box-shadow:		0 2px 5px rgba(0, 0, 0, .5), inset 0 1px 0 rgba(255, 255, 255, .1), inset 0 0 0 1px rgba(255, 255, 255, .075);
	-moz-box-shadow:		0 2px 5px rgba(0, 0, 0, .5), inset 0 1px 0 rgba(255, 255, 255, .1), inset 0 0 0 1px rgba(255, 255, 255, .075);
	box-shadow:				0 2px 5px rgba(0, 0, 0, .5), inset 0 1px 0 rgba(255, 255, 255, .1), inset 0 0 0 1px rgba(255, 255, 255, .075);
}

div.jGrowl div.jGrowl-notification {
	min-height: 			40px;
}

div.jGrowl div.jGrowl-notification div.jGrowl-header {
	font-weight: 			bold;
	font-size:				14px;
}

div.jGrowl div.jGrowl-notification div.jGrowl-close {
	z-index:				99;
	float: 					right;
	font-weight: 			bold;
	font-size: 				1em;
	cursor:					pointer;
	width:					18px;
	text-align:				center;
	border:					1px solid transparent;
	border-color:			#1a1a1a;
	background-color:		rgba(32, 32, 32, 0.5);
	-webkit-border-radius:	3px;
	-moz-border-radius:		3px;
	-o-border-radius:		3px;
	-webkit-box-shadow:		inset 0 1px 0 rgba(255, 255, 255, .1);
	-moz-box-shadow:		inset 0 1px 0 rgba(255, 255, 255, .1);
	box-shadow:				inset 0 1px 0 rgba(255, 255, 255, .1);
}

div.jGrowl div.jGrowl-closer {
	padding-top: 			4px;
	padding-bottom: 		4px;
	cursor: 				pointer;
	font-size:				.9em;
	font-weight: 			bold;
	text-align: 			center;
}

/** Hide jGrowl when printing **/
@media print {
	div.jGrowl {
		display: 			none;
	}
}


text:
package harmony.mastermind.storage;

import javax.xml.bind.annotation.XmlElement;

import harmony.mastermind.commons.exceptions.IllegalValueException;
import harmony.mastermind.model.tag.Tag;
import harmony.mastermind.model.tag.UniqueTagList;
import harmony.mastermind.model.task.ReadOnlyTask;
import harmony.mastermind.model.task.Task;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * JAXB-friendly version of the Task.
 */
public class XmlAdaptedTask {

    @XmlElement(required = true)
    private String name;

    @XmlElement(required = true)
    private Date createdDate;

    @XmlElement
    private List<XmlAdaptedTag> tagged = new ArrayList<>();

    /**
     * No-arg constructor for JAXB use.
     */
    public XmlAdaptedTask() {}

    /**
     * Converts a given Task into this class for JAXB use.
     *
     * @param source future changes to this will not affect the created XmlAdaptedTask
     */
    //@@author A0138862W
    public XmlAdaptedTask(ReadOnlyTask source) {
        name = source.getName();
        createdDate = source.getCreatedDate();

        tagged = new ArrayList<>();
        for (Tag tag : source.getTags()) {
            tagged.add(new XmlAdaptedTag(tag));
        }
    }
    // @@author

    /**
     * Converts this jaxb-friendly adapted task object into the model's Task object.
     *
     * @throws IllegalValueException if there were any data constraints violated in the adapted task
     */
    public Task toModelType() throws IllegalValueException {
        final List<Tag> taskTags = new ArrayList<>();
        for (XmlAdaptedTag tag : tagged) {
            taskTags.add(tag.toModelType());
        }

        final String name = this.name;
        final UniqueTagList tags = new UniqueTagList(taskTags);

        return new Task(name, tags, createdDate);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2016 Red Hat, Inc. and/or its affiliates.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~  http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <parent>
    <artifactId>kie-wb-common-stunner-core</artifactId>
    <groupId>org.kie.workbench.stunner</groupId>
    <version>7.7.0-SNAPSHOT</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>

  <artifactId>kie-wb-common-stunner-processors</artifactId>
  <name>Kie Workbench - Common - Stunner - Processors</name>
  <description>Kie Workbench - Common - Stunner - Processors</description>
  <packaging>jar</packaging>

  <properties>
    <java.module.name>org.kie.wb.common.stunner.processors</java.module.name>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.kie.workbench.stunner</groupId>
      <artifactId>kie-wb-common-stunner-core-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.stunner</groupId>
      <artifactId>kie-wb-common-stunner-core-common</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.stunner</groupId>
      <artifactId>kie-wb-common-stunner-backend-common</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.stunner</groupId>
      <artifactId>kie-wb-common-stunner-client-api</artifactId>
    </dependency>

    <!-- Uberfire & Errai. -->
    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-bus</artifactId>
    </dependency>

    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-common</artifactId>
    </dependency>

    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-ioc</artifactId>
    </dependency>

    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-data-binding</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-commons</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.soup</groupId>
      <artifactId>kie-soup-commons</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-commons-editor-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-workbench-processors</artifactId>
    </dependency>

    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
    </dependency>

    <dependency>
      <groupId>com.thoughtworks.xstream</groupId>
      <artifactId>xstream</artifactId>
    </dependency>

    <dependency>
      <groupId>org.freemarker</groupId>
      <artifactId>freemarker</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
    </dependency>

  </dependencies>

  <build>
    <plugins>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <proc>none</proc>
        </configuration>
      </plugin>

    </plugins>
  </build>

</project>


text:
<?xml version='1.0'?>
<xslTutorial>
<OPTGROUP>this</OPTGROUP><OPTGROUP>rocks</OPTGROUP>
<OPTGROUP>this</OPTGROUP> <OPTGROUP>rocks</OPTGROUP>
<OPTGROUP>this</OPTGROUP>
<OPTGROUP>rocks</OPTGROUP>
<OPTGROUP>this</OPTGROUP>		<OPTGROUP>rocks</OPTGROUP>

this<OPTGROUP>rocks</OPTGROUP>
this <OPTGROUP>rocks</OPTGROUP>
</xslTutorial>


text:
/**
 * {@code PTransform}s to compute statistical sketches on data streams based on the <a
 * href="https://github.com/google/zetasketch">ZetaSketch</a> implementation.
 */
@Experimental
package org.apache.beam.sdk.extensions.zetasketch;

import org.apache.beam.sdk.annotations.Experimental;


text:
<?php

class Membership_model extends CI_Model{
	function validate(){
		$this->db->where('username', $this->input->post('username'));
		$this->db->where('password', md5($this->input->post('password')));
		$query = $this->db->get('members');

		if($query->num_rows == 1){
			return true;
		}
	}

	function create_member(){
		$new_member_insert_data=array(
			'first_name' => $this->input->post('first_name'),
			'last_name' => $this->input->post('last_name'),
			'e-mail' => $this->input->post('e-mail'),
			'username' => $this->input->post('username'),
			'password' => md5($this->input->post('password'))
		);

		$insert = $this->db->insert('members', $new_member_insert_data);
		return $insert;
	}
}


text:
<?php

namespace CBLib\Entity;

defined('CBLIB') or die();

interface EntityInterface
{
}