text:
using System;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Http;
using TerrainGenerator.Services.Contracts;
using TerrainGenerator.Services.Interfaces;
using TerrainGenerator.WebApi.Controllers;
using TerrainGenerator.WebApi.Models;

namespace TerrainGenerator.WebApi.Pipeline.Controllers
{
    [Authorize]
    [RoutePrefix("api/Account")]
    public class AccountController : BaseController
    {
        public AccountController(IAccountsManager accountsManager) : base(accountsManager)
        {
        }

        //[AllowAnonymous]
        //[AcceptVerbs("OPTIONS")]
        //[Route("~/Token")]
        //public HttpResponseMessage TokenCors()
        //{
        //    var response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
        //    response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
        //    return response;
        //}

        [AllowAnonymous]
        [HttpPost]
        [Route("Register")]
        public IHttpActionResult Register([FromBody] RegisterModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var account = AccountsManager.GetAccount(model.Email);

            if (account != null)
            {
                ModelState.AddModelError("", new DuplicateNameException("The user name is already in use."));
                return BadRequest(ModelState);
            }

            try
            {
                // TODO: This can be done better
                AccountsManager.AddAccount(model.Email, model.Password, new Uri(Request.RequestUri.ToString().Replace("Register", "Activate")));
            }
            catch (InsufficientMemoryException ime)
            {
                Trace.TraceWarning(ime.Message);
                ModelState.AddModelError("", new InsufficientMemoryException("The number of users as reach the comfigured limit. Please contact with alvaromontero@gmail.com to ask for access.", ime));
                return BadRequest(ModelState);
            }
            catch (Exception ex)
            {
                Trace.TraceWarning(ex.Message);
                ModelState.AddModelError("", new Exception("Unknown error registering the account.", ex));
                return BadRequest(ModelState);
            }

            return Ok();
        }

        [AllowAnonymous]
        [HttpGet]
        [Route("Activate/{id}")]
        public HttpResponseMessage Activate([FromUri] string id)
        {
            HttpResponseMessage response;

            if (string.IsNullOrEmpty(id))
            {
                response = Request.CreateResponse(HttpStatusCode.BadRequest);
                response.Content = new StringContent("Invalid request");
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                return response;
            }

            var account = AccountsManager.ActivateAccount(id);

            if (account == null)
            {
                response = Request.CreateResponse(HttpStatusCode.BadRequest);
                response.Content = new StringContent("Invalid activation key");
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                return response;
            }

            response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent("Your account has been activated");
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
            return response;
        }

        [HttpPut]
        [Route("Location")]
        public async Task<IHttpActionResult> Location([FromBody] TilePosition tilePosition)
        {
            if (tilePosition == null)
            {
                throw new InvalidDataException("null location");
            }

            var account = this.AccountsManager.GetAccount(User.Identity.Name);

            if (account == null)
            {
                throw new InvalidDataException("Unknown account");
            }

            if (!account.IsDemoAccount())
            {
                // TODO: This has to be async
                account.TilePosition = tilePosition;
                this.AccountsManager.UpdateAccount(account);
            }

            return Ok();
        }
    }
}


text:
import { isEqual, uniq } from 'underscore';
import { query } from '../utils/restful';

import { getSelectedKeys, getOpenKeys } from '../services/sidebar';

export default {
  namespace: 'sidebar',
  state: {
    menus: [],
    openKeys: [],
    selectedKeys: [],
  },
  reducers: {
    UPDATE_SIDEBAR: function (state, action) {
      return Object.assign({}, state, action.payload);
    }
  },
  effects: {
    INIT: function* ({ payload }, { select, call, put }) {
      const menus = yield call(query, '/test/sidebar', payload);
      if (menus && menus.length > 0) {
        let defaultSelectedKeys: string[] = yield call(getSelectedKeys, { menus, pathname: payload.pathname });
        let defaultOpenKeys: string[] = [];
        for (let i of defaultSelectedKeys) {
          defaultOpenKeys = Object.assign([], defaultOpenKeys, yield call(getOpenKeys, { menus, id: i }));
        }
        yield put({
          type: 'UPDATE_SIDEBAR',
          payload: {
            menus: menus,
            openKeys: defaultOpenKeys,
            selectedKeys: defaultSelectedKeys,
          }
        });
      }
    },
  },
  subscriptions: {
    setup: function ({ dispatch, history }) {
      let bool: boolean = false;
      history.listen(function (location) {
        if (!bool) {
          dispatch({
            type: 'INIT',
            payload: {
              pathname: location.pathname,
            }
          });
          bool = true;
        }
      });
    },
  },
};

redpajama_set_name: RedPajamaGithub


text:
"""
This module contains unit tests for the "InstructionPacket" class.
"""

import pyax12.packet as pk
import pyax12.instruction_packet as ip

import unittest

class TestInstructionPacket(unittest.TestCase):
    """
    Contains unit tests for the "InstructionPacket" class.
    """

    # Test the "dynamixel_id" argument ########################################

    def test_wrong_id_type(self):
        """Check that the instanciation of InstructionPacket fails when the
        argument "dynamixel_id" has a wrong type."""

        # Check with None
        dynamixel_id = None       # wrong id
        instruction = ip.READ_DATA
        params = (pk.PRESENT_TEMPERATURE, 0x01)

        with self.assertRaises(TypeError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

        # Check with float
        dynamixel_id = 1.0        # wrong id
        instruction = ip.READ_DATA
        params = (pk.PRESENT_TEMPERATURE, 0x01)

        with self.assertRaises(TypeError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

        # Check with string
        dynamixel_id = "hi"       # wrong id
        instruction = ip.READ_DATA
        params = (pk.PRESENT_TEMPERATURE, 0x01)

        with self.assertRaises(TypeError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

        # Check with tuple
        dynamixel_id = ()         # wrong id
        instruction = ip.READ_DATA
        params = (pk.PRESENT_TEMPERATURE, 0x01)

        with self.assertRaises(TypeError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

    def test_wrong_id_value(self):
        """Check that the instanciation of InstructionPacket fails when the
        argument "dynamixel_id" has a wrong value (too low or too high)."""

        # Too high
        dynamixel_id = 0xff  # wrong id
        instruction = ip.READ_DATA
        params = (pk.PRESENT_TEMPERATURE, 0x01)

        with self.assertRaises(ValueError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

        # Too low
        dynamixel_id = -1    # wrong id
        instruction = ip.READ_DATA
        params = (pk.PRESENT_TEMPERATURE, 0x01)

        with self.assertRaises(ValueError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

#    # TODO: should it be considered as an actual error or can it be neglected?
#    def test_wrong_id_value_sync_write(self):
#        """Check that the instanciation of InstructionPacket fails when the
#        argument "dynamixel_id" has a wrong value (the SYNC_WRITE
#        instruction expects the broadcast id)."""
#
#        dynamixel_id = 1                  # wrong id (must be 0xfe)
#        instruction = ip.SYNC_WRITE
#        params = (pk.LED, 1, 1, 1)
#
#        with self.assertRaises(ValueError):
#            ip.InstructionPacket(dynamixel_id, instruction, params)

    # Test the "instruction" argument #########################################

    def test_wrong_instruction_type(self):
        """Check that the instanciation of InstructionPacket fails when the
        argument "instruction" has a wrong type."""

        # Check with None
        dynamixel_id = 1
        instruction = None   # wrong instruction
        params = (pk.PRESENT_TEMPERATURE, 0x01)

        with self.assertRaises(TypeError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

        # Check with float
        dynamixel_id = 1
        instruction = 1.0    # wrong instruction
        params = (pk.PRESENT_TEMPERATURE, 0x01)

        with self.assertRaises(TypeError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

        # Check with string
        dynamixel_id = 1
        instruction = "hi"   # wrong instruction
        params = (pk.PRESENT_TEMPERATURE, 0x01)

        with self.assertRaises(TypeError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

        # Check with tuple
        dynamixel_id = 1
        instruction = ()     # wrong instruction
        params = (pk.PRESENT_TEMPERATURE, 0x01)

        with self.assertRaises(TypeError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

    def test_wrong_instruction_value(self):
        """Check that the instanciation of InstructionPacket fails when the
        argument "instruction" has a wrong value."""

        dynamixel_id = 1
        instruction = 1000   # wrong instruction
        params = (pk.PRESENT_TEMPERATURE, 0x01)

        with self.assertRaises(ValueError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

    # Test the "parameters" argument ##########################################

    def test_wrong_params_type(self):
        """Check that the instanciation of InstructionPacket fails when the
        argument "parameters" has a wrong type."""

        # Check with a float.
        dynamixel_id = 1
        instruction = ip.READ_DATA
        params = 1.0                                  # wrong type

        with self.assertRaises(TypeError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

        # Check with a string.
        dynamixel_id = 1
        instruction = ip.READ_DATA
        params = "hello world"                        # wrong type

        with self.assertRaises(TypeError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

        # Check with an integer.
        # There is no instruction which take only one parameter (some take 0
        # parameters, some take 2 or more parameters but none take 1
        # parameter).
        dynamixel_id = 1
        instruction = ip.PING
        params = 1

        with self.assertRaises(TypeError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

    def test_good_params_type(self):
        """Check that the instanciation of InstructionPacket doesn't fail when
        the argument "parameters" has a right type."""

        # Check with None (some instructions like "PING" doesn't take any
        # parameter)
        dynamixel_id = 1
        instruction = ip.PING
        params = None                                 # wrong type

        try:
            ip.InstructionPacket(dynamixel_id, instruction, params)
        except (TypeError, ValueError):
            self.fail("Encountered an unexpected exception.")

        # Check with a tuple
        dynamixel_id = 1
        instruction = ip.READ_DATA
        params = (pk.PRESENT_TEMPERATURE, 0x01)

        try:
            ip.InstructionPacket(dynamixel_id, instruction, params)
        except (TypeError, ValueError):
            self.fail("Encountered an unexpected exception.")

        # Check with a list
        dynamixel_id = 1
        instruction = ip.READ_DATA
        params = [pk.PRESENT_TEMPERATURE, 0x01]

        try:
            ip.InstructionPacket(dynamixel_id, instruction, params)
        except (TypeError, ValueError):
            self.fail("Encountered an unexpected exception.")

        # Check with a bytes string
        dynamixel_id = 1
        instruction = ip.READ_DATA
        params = bytes((pk.PRESENT_TEMPERATURE, 0x01))

        try:
            ip.InstructionPacket(dynamixel_id, instruction, params)
        except (TypeError, ValueError):
            self.fail("Encountered an unexpected exception.")

        # Check with a bytearray
        dynamixel_id = 1
        instruction = ip.READ_DATA
        params = bytearray((pk.PRESENT_TEMPERATURE, 0x01))

        try:
            ip.InstructionPacket(dynamixel_id, instruction, params)
        except (TypeError, ValueError):
            self.fail("Encountered an unexpected exception.")

    def test_wrong_params_items_type(self):
        """Check that the instanciation of InstructionPacket fails when the
        "parameters" items type is wrong."""

        # Check with None
        dynamixel_id = 1
        instruction = ip.READ_DATA
        params = (pk.PRESENT_TEMPERATURE, None)      # wrong value

        with self.assertRaises(TypeError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

        # Check with float
        dynamixel_id = 1
        instruction = ip.READ_DATA
        params = (pk.PRESENT_TEMPERATURE, 1.0)       # wrong value

        with self.assertRaises(TypeError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

        # Check with string
        dynamixel_id = 1
        instruction = ip.READ_DATA
        params = (pk.PRESENT_TEMPERATURE, "hi")      # wrong value

        with self.assertRaises(TypeError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

        # Check with tuple
        dynamixel_id = 1
        instruction = ip.READ_DATA
        params = (pk.PRESENT_TEMPERATURE, ())        # wrong value

        with self.assertRaises(TypeError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

    def test_wrong_params_items_value(self):
        """Check that the instanciation of InstructionPacket fails when the
        "parameters" items type is value."""

        # Too high value
        dynamixel_id = 1
        instruction = ip.READ_DATA
        params = (pk.PRESENT_TEMPERATURE, 0xffff)     # wrong value

        with self.assertRaises(ValueError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

        # Too low value
        dynamixel_id = 1
        instruction = ip.READ_DATA
        params = (pk.PRESENT_TEMPERATURE, -1)         # wrong value

        with self.assertRaises(ValueError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

    def test_wrong_num_params_ping(self):
        """Check that the instanciation of InstructionPacket fails when the
        number of paramaters is wrong (greater than 0 for the PING
        instruction)."""

        # Too high
        dynamixel_id = 1
        instruction = ip.PING
        params = (0x00, )                             # wrong nb of params

        with self.assertRaises(ValueError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

    def test_wrong_num_params_read(self):
        """Check that the instanciation of InstructionPacket fails when the
        number of paramaters is wrong (for the READ_DATA instruction)."""

        # Too high
        dynamixel_id = 1
        instruction = ip.READ_DATA
        params = (pk.PRESENT_TEMPERATURE, 0x01, 0x00) # wrong nb of params

        with self.assertRaises(ValueError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

        # Too low
        dynamixel_id = 1
        instruction = ip.READ_DATA
        params = (pk.PRESENT_TEMPERATURE, )           # wrong nb of params

        with self.assertRaises(ValueError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

    def test_wrong_num_params_write(self):
        """Check that the instanciation of InstructionPacket fails when the
        number of paramaters is wrong (for the WRITE_DATA instruction)."""

        # Too low
        dynamixel_id = 1
        instruction = ip.WRITE_DATA
        params = (pk.LED, )                           # wrong nb of params

        with self.assertRaises(ValueError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

    def test_wrong_num_params_reg_write(self):
        """Check that the instanciation of InstructionPacket fails when the
        number of paramaters is wrong (for the REG_WRITE instruction)."""

        # Too low
        dynamixel_id = 1
        instruction = ip.REG_WRITE
        params = (pk.LED, )                           # wrong nb of params

        with self.assertRaises(ValueError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

    def test_wrong_num_params_action(self):
        """Check that the instanciation of InstructionPacket fails when the
        number of paramaters is wrong (greater than 0 for the ACTION
        instruction)."""

        # Too high
        dynamixel_id = 1
        instruction = ip.ACTION
        params = (0x00, )                             # wrong nb of params

        with self.assertRaises(ValueError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

    def test_wrong_num_params_reset(self):
        """Check that the instanciation of InstructionPacket fails when the
        number of paramaters is wrong (greater than 0 for the RESET
        instruction)."""

        # Too high
        dynamixel_id = 1
        instruction = ip.RESET
        params = (0x00, )                             # wrong nb of params

        with self.assertRaises(ValueError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

    def test_wrong_num_params_sync_write(self):
        """Check that the instanciation of InstructionPacket fails when the
        number of paramaters is wrong (for the SYNC_WRITE instruction)."""

        # Too low (1)
        dynamixel_id = 0xfe
        instruction = ip.SYNC_WRITE
        params = (pk.LED, )                           # wrong nb of params

        with self.assertRaises(ValueError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

        # Too low (2)
        dynamixel_id = 0xfe
        instruction = ip.SYNC_WRITE
        params = (pk.LED, 1)                          # wrong nb of params

        with self.assertRaises(ValueError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

        # Too low (3)
        dynamixel_id = 0xfe
        instruction = ip.SYNC_WRITE
        params = (pk.LED, 1, 1)                       # wrong nb of params

        with self.assertRaises(ValueError):
            ip.InstructionPacket(dynamixel_id, instruction, params)

    # Full examples ###########################################################

    def test_example1(self):
        """Check the example 1 from the Dynamixel user guide: "Setting the ID
        of a connected Dynamixel actuator to 1" (p.20)."""

        dxl_id = pk.BROADCAST_ID
        instruction = ip.WRITE_DATA
        params = (pk.ID, 1)

        instruction_packet = ip.InstructionPacket(dxl_id, instruction, params)

        expected_str = "ff ff fe 04 03 03 01 f6"
        self.assertEqual(instruction_packet.to_printable_string(), expected_str)

    def test_example2(self):
        """Check the example 2 from the Dynamixel user guide: "Reading the
        internal temperature of the Dynamixel actuator with an ID of 1"
        (p.20)."""

        dxl_id = 1
        instruction = ip.READ_DATA
        params = (pk.PRESENT_TEMPERATURE, 1)

        instruction_packet = ip.InstructionPacket(dxl_id, instruction, params)

        expected_str = "ff ff 01 04 02 2b 01 cc"
        self.assertEqual(instruction_packet.to_printable_string(), expected_str)

    def test_example3(self):
        """Check the example 3 from the Dynamixel user guide: "Obtaining the
        status packet of the Dynamixel actuator with an ID of 1" (p.22) i.e.
        PING the Dynamixel #1."""

        dxl_id = 1
        instruction = ip.PING
        params = ()

        instruction_packet = ip.InstructionPacket(dxl_id, instruction, params)

        expected_str = "ff ff 01 02 01 fb"
        self.assertEqual(instruction_packet.to_printable_string(), expected_str)

if __name__ == '__main__':
    unittest.main()


text:
<!DOCTYPE html>

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

        <title>OverTheWire - Bandit</title>

    <meta name="description" content="Who cares?">

    <link rel="icon" href="/assets/img/favicon.png">
    <link href='https://fonts.googleapis.com/css?family=Inconsolata:400,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="/assets/css/main.css">
    <link rel="stylesheet" type="text/css" href="/assets/css/rouge.css">

    <-- home

OverTheWire - Bandit

March 15, 2016

O bandit é um dos muitos interessantíssimos challenges disponíveis no Overthewire que eu e o fallc0nn começamos a fazer há algum tempo.

Nesse post vamos postar o walkthru desse challenge.

Level 0

O level 0 é extremamente simples. Basta logar no servidor e dar um cat no arquivo readme

ssh bandit0@bandit.labs.overthewire.org
cat readme

e usar a senha encontrada para dar ssh para o próximo level

ssh bandit1@localhost

Level 1

O level 1 exige um conhecimento básico de linux, mas que muita gente não sabe.

Ao se logar, você verá um arquivo chamado "-". Isso mesmo, é só o famoso dash, ou traço.

De cara, todos tentariam dar um cat – ou cat -, mas não funcionaria. Alguns programas do linux adotam uma convenção de que o – sozinho significa stdout. Assim, temos duas formas de resolver o problema:

cat ./-
#  ou
cat < -

e usar a senha encontrada para dar ssh para o próximo level

ssh bandit2@localhost

Level 2

O 2 não vale nem a pena perder tempo. É um arquivo com espaços no filename, onde você deveria escapar os espaços para conseguir dar o cat.

Porém, o tab completion faz isso por você.

cat spaces\ in\ this\ filename

novamente, use a senha para logar como bandit3.

Level 3

Como o dois, bem simples. Uma pasta com um arquivo oculto dentro.

cat .hidden

Agora é só fazer o login como bandit4

Level 4

O 4 também tem uma pegadinha que pouca gente sabe.

Tratar arquivos que começam com dash (-) tem uma particularidade no linux. Quando você usa um comando e ele vê o caractere -, ele espera que você esteja começando a setar argumentos do programa, como "ls -lA" ou "cat -vet".

Portanto, existe uma forma não tão conhecida de avisar ao programa em questão que você acabou de informar seus argumentos, que é utilizando dois traços (–).

Nesse nível temos os seguintes arquivos:

-file00
-file01
-file02
-file03
-file04
-file05
-file06
-file07
-file08
-file09

e se você tentar dar um simples cat em qualquer um deles, dará erro.

Então, deve utilizar a dica dos dois traços. Mas antes disso, você vai perceber que dentro da maioria dos arquivos existem strings ininteligíveis. Para evitar ter que dar cat em todos, faça:

$ file -- *
-file00: data
-file01: data
-file02: data
-file03: data
-file04: data
-file05: data
-file06: data
-file07: ASCII text
-file08: data
-file09: data

e assim saberá que a senha está no arquivo "-file07".

cat -- -file07
#  ou
cat < -file07

Level 5

O level 5 é o mais chato até aqui

Basta dar um ls -R para ver que existem dezenas de pastas e subpastas e arquivos… demoraria horas para encontrar a senha olhando um por um.

Vou economizar na explicação dos problemas, pois todos já encontramos até aqui, e focar na solução:

A melhor forma que encontrei aqui foi listar todos os arquivos com find -type f, adicionar aspas em volta deles, para evitar problemas com espaços, com sed 's/^|$/\"/g' e jogar o output para o comando file — (lembram dos dois traços?).

Porém, a lista de arquivos é imensa. Como até aqui já aprendemos que a senha vem num arquivo texto, podemos usar grep ASCII na saída do file –, assim nosso universo foi reduzido a poucos arquivos.

find -type f | sed 's/^\|$/\"/g'  | xargs file --  | grep ASCII

Com essas informações, tudo que precisamos é, depois do pipe, dar um cut, fazer novamente o truque das aspas e jogar o output para um xargs head -1

find -type f | sed 's/^\|$/\"/g'  | xargs file --  | grep ASCII | \
cut -f1 -d: | sed 's/^\|$/\"/g' | xargs head -1 | less

Se você prestou atenção no formato das senhas até agora, vai identificar só de olhar!

MAS

isso tudo é pra quem é desatento, e num CTF toda informação é valiosa.

Na página do challenge, no item "level 5 – level6" tem uma dica de ouro:

"The password for the next level is stored in a file somewhere under the inhere directory and has all of the following properties: – human-readable – 1033 bytes in size – not executable"

Então basta fazer:

$ find -size 1033c | xargs cat

e correr para o abraço. E, a partir de agora, ficar olho no site!

Level 6

Seguindo as intruções do site, temos os atributos do arquivo:user: bandit7, group: bandit6, size: 33 bytes.

find / -user bandit7 -group bandit6 -size 33c | xargs cat

Level 7

Instruções no site!

grep millionth data.txt

Level 8

A senha está no arquivo data.txt e é a única linha que aparece apenas uma vez

sort data.txt | uniq -u

Level 9

A senha está em uma das poucas linhas 'legíveis' do arquivo data.txt que começam com algumas vezes o caractere "="

Para esse nível vamos usar pela primeira vez o comando strings

strings data.txt  | grep -E "^=+"

Level 10

A senha está no arquivo data.txt, codificado em base64

base64 -d < data.txt

Level 11

O level 11 é a conhecida cifra de césar, algoritmo de rotação de caracteres.

tr a-zA-Z n-za-mN-ZA-M < data.txt

Level 12

O 12 é bem chatinho. Se você der um cat no arquivo vai ver que se trata de um hexdump de algum arquivo.

Muita gente ao fazer esse nível jogava o output para algum arquivo e dava um file, para depois usar algum outro comando, salvar em outro arquivo e dar outro file, assim sucessivamente.

Mas como expliquei no level 1, podemos usar o – em alguns programas simbolizando o stdout. Então basta fazer o seguinte:

bandit12@melinda:~$ xxd -r data.txt | file -
/dev/stdin: gzip compressed data, was "data2.bin", from Unix, last modified: ..
bandit12@melinda:~$ xxd -r data.txt | zcat | file -
/dev/stdin: bzip2 compressed data, block size = 900k
bandit12@melinda:~$ xxd -r data.txt | zcat | bzcat| file -
/dev/stdin: gzip compressed data, was "data4.bin", from Unix, last modified: ..
bandit12@melinda:~$ xxd -r data.txt | zcat | bzcat| zcat| file -
/dev/stdin: POSIX tar archive (GNU)
bandit12@melinda:~$ xxd -r data.txt | zcat | bzcat| zcat| tar xO | file -
/dev/stdin: POSIX tar archive (GNU)
bandit12@melinda:~$ xxd -r data.txt | zcat | bzcat| zcat| tar xO | tar xO | file -
/dev/stdin: bzip2 compressed data, block size = 900k
bandit12@melinda:~$ xxd -r data.txt | zcat | bzcat| zcat| tar xO | tar xO | \
bzcat | file -
/dev/stdin: POSIX tar archive (GNU)
bandit12@melinda:~$ xxd -r data.txt | zcat | bzcat| zcat| tar xO | tar xO | \
bzcat | tar xO | file -
/dev/stdin: gzip compressed data, was "data9.bin", from Unix, last modified: ..
bandit12@melinda:~$ xxd -r data.txt | zcat | bzcat| zcat| tar xO | tar xO | \
bzcat | tar xO | zcat | file -
/dev/stdin: ASCII text
bandit12@melinda:~$ xxd -r data.txt | zcat | bzcat| zcat| tar xO | tar xO | \
bzcat | tar xO | zcat | cat
The password is 8ZjyCRiBWFYkneahHwxCv3wb2a1ORpYL

Level 13

Fácil, né?

ssh -i sshkey.private bandit14@localhost

Depois de logar, não se esqueça de pegar a senha

cat /etc/bandit_pass/bandit14

Level 14

A dica no site diz que se enviarmos a senha do nível atual na porta 30000 do servidor, receberemos a senha para o proximo.

echo "4wcYUJFw0k0XLShlDzztnTBHiqxU3b3e" | netcat localhost 30000

Level 15

O 15 é igual ao 14, mas via openssl

echo BfMYroe26WYalil77FoDi9qh59eK5xNr | \
openssl s_client -connect localhost:30001 -ign_eof

Level 16

Trabalhosa! O site informa que você deve submeter a senha atual em uma porta no localhost entre 31000 e 32000, sem saber qual é.

Recomenda que você primeiro veja quais portas estão abertas (nmap?) pra depois saber quais falam SSL e quais não falam, e então submeter a senha. Eu prefiro ganhar tempo:

for i in {31000..32000}; do
   netcat -zv localhost $i 2>/dev/null && {
      echo porta $i aberta;
      echo "cluFn7wTiGryunymYOu4RcffSxQluehd" | \
      timeout 2 openssl s_client -connect localhost:$i -ign_eof ;
   };
done

Assim ele já vai enviar a string via SSL pra todas as portas abertas, depois basta você olhar o buffer do seu terminal pra encontrar a resposta.

Nesse caso, temos como retorno uma chave privada que deve ser usada para acessar o próximo nível. O problema é que não temos permissão de escrita no diretório.

Tentei salvar a key numa variavel e usar como file descriptor, mas pelo visto o sistema não permite. A solução, então, é criar no /tmp/.

mkdir -p /tmp/318br/
cd /tmp/318br/
vi key
# (cole o conteúdo da key no arquivo)
ssh -i key bandit17@localhost

Level 17

A dica no site diz que a senha está na única linha que é diferente entre os arquivos passwords.new e passwords.old

diff passwords.*

Quando você tentar se logar no próximo level, vai ter uma surpresa…

Level 18

OOOOH! Não dá pra logar!!

Mas a essa altura do campeonato você já sabe a solução. A dica no site diz que a senha está no arquivo readme do homedir do usuário

ssh bandit18@localhost cat readme

Level 19

Bem simples, nem sei porque está no final

./bandit20-do cat /etc/bandit_pass/bandit20

Level 20

Nesse level o enunciado diz que é preciso abrir dois shells pra passar. Mas como hackinagem pouca é bobagem, vou ensinar aqui como fazer com um shell só!

Seguindo o enunciado, teoricamente você deveria abrir um listener com netcat, por exemplo

nc -l 12345

Depois abrir outra sessão ssh, executar

./suconnect 12345

Então, voltar ao primeiro terminal e submeter a key via listener, para que o suconnect enviasse a resposta de volta

Muito trabalho, não?

Aqui o negócio é simples.

(sleep 10; echo GbKksEFF4yrVs6il55v6gwY5aVje5f0j) | nc -l 12345 &
[1] 8230
./suconnect 12345
Read: GbKksEFF4yrVs6il55v6gwY5aVje5f0j
Password matches, sending next password
gE269g2h3mw3pwgrj0Ha9Uoqen1c9DGr

Deu pra entender? Na primeira linha abrimos o netcat escutando na porta 12345 e enviamos via pipe pra ele o comando agrupado entre parenteses para aguardar 10 segundos e depois enviar a key, já enviando tudo para background com o & no final.

Depois disso, é só digitar o ./suconnect 12345 em menos de 10 segundos e aguardar o tempo setado que a senha vai aparecer facilmente pra você!

Level 21

Dentro da pasta /etc/cron.d/ tem vários cronjobs de vários usuários. Nosso próximo level é o 22, nele que devemos focar.

cat /etc/cron.d/cronjob_bandit22
* * * * * bandit22 /usr/bin/cronjob_bandit22.sh &> /dev/null
cat /usr/bin/cronjob_bandit22.sh
# !/bin/bash
chmod 644 /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
cat /etc/bandit_pass/bandit22 > /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv

Analisando o código, você pode ver que a senha do bandit22 está sendo enviada para aquele arquivo de nome estranho no /tmp

É só dar um cat nele!

cat /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
Yk7owGAcWjwMVRwrTesJEwB7WVOiILLI

Level 22

O início é igual ao level 21. Você deve verificar o cronjob do bandit23.

# !/bin/bash

myname=$(whoami)
mytarget=$(echo I am user $myname | md5sum | cut -d ' ' -f 1)

echo "Copying passwordfile /etc/bandit_pass/$myname to /tmp/$mytarget"

cat /etc/bandit_pass/$myname > /tmp/$mytarget

Um poquinho de leitura de código resolve seu trabalho:

myname=bandit23
cat /tmp/$(echo I am user $myname | md5sum | cut -d ' ' -f 1)
jc1udXuA1tiHqjIsL8yaapX5XIAI6i0n

Level 23

Mesma coisa no início, olho no cronjobs_bandit24.

Você pode ver no script que ele executa que ele procura arquivos em uma determinada pasta e executa tudo que estiver la a todo minuto

Então é simples!

cd /var/spool/bandit24
echo "cat /etc/bandit_pass/bandit24 > /tmp/318br.bandit24" > script.sh
chmod +x script.sh
#  agora basta esperar virar para o próximo minuto e
cat /tmp/318br.bandit24
UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ

Level 24

Brute Force!

for i in {0000..9999}; do
   echo  "UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ $i"; done | \
   netcat localhost 30002 | grep bandit25

Dentro do loop geramos a lista com a senha do level 24 combinada com todas as combinações de 4 dígitos possíveis, e depois de pronta, jogamos essa lista via pipe pro netcat.

Pode ser preciso rodar o comando algumas vezes, porque aparentemente o daemon não aguenta a pressão, mas é só insistir duas ou três vezes q vai dar certo.

Level 25

Essa eu apanhei muito. O shell do usuário bandit26 parece ser diferente, e é.

Para passar desse nível, você deve redimensionar seu terminal, conforme a imagem abaixo:

Ao dar enter, você vai se deparar com um "more"

O truque aqui é dar fallback do more para o vi!

Digite esc, depois v.

O arquivo será aberto no vi. Agora você só precisa digitar esc, e depois: e: /etc/bandit_pass/bandit26 e enter.

O arquivo bandit26 aparecerá com a senha.

5czgV9L3Xx8JPOyRbXh6lQbmIOWvPT6Z

Como o level 27 ainda não existe, acabamos de bater o desafio BANDIT do Overthewire!!


text:
import sys
import csv
import getopt
import subprocess
import shlex
import pickle

from PyQt4 import QtGui
from GenericCommandDialog import Ui_GenericCommandDialog
from HTMLParser import HTMLParser
from HTMLDocsParser import HTMLDocsParser
from struct import *

class SubsystemCommands(QtGui.QDialog):

    pktCount = 0

    #
    # Init the class
    #
    def __init__(self):
        QtGui.QDialog.__init__(self)
        self.ui = Ui_GenericCommandDialog()
        self.ui.setupUi(self)
        self.setWindowTitle(pageTitle)
        self.parser = HTMLDocsParser()

        self.ui.SendButton_1.clicked.connect(self.ProcessSendButton_1)
        self.ui.SendButton_2.clicked.connect(self.ProcessSendButton_2)
        self.ui.SendButton_3.clicked.connect(self.ProcessSendButton_3)
        self.ui.SendButton_4.clicked.connect(self.ProcessSendButton_4)
        self.ui.SendButton_5.clicked.connect(self.ProcessSendButton_5)
        self.ui.SendButton_6.clicked.connect(self.ProcessSendButton_6)
        self.ui.SendButton_7.clicked.connect(self.ProcessSendButton_7)
        self.ui.SendButton_8.clicked.connect(self.ProcessSendButton_8)
        self.ui.SendButton_9.clicked.connect(self.ProcessSendButton_9)
        self.ui.SendButton_10.clicked.connect(self.ProcessSendButton_10)
        self.ui.SendButton_11.clicked.connect(self.ProcessSendButton_11)
        self.ui.SendButton_12.clicked.connect(self.ProcessSendButton_12)
        self.ui.SendButton_13.clicked.connect(self.ProcessSendButton_13)
        self.ui.SendButton_14.clicked.connect(self.ProcessSendButton_14)
        self.ui.SendButton_15.clicked.connect(self.ProcessSendButton_15)
        self.ui.SendButton_16.clicked.connect(self.ProcessSendButton_16)
        self.ui.SendButton_17.clicked.connect(self.ProcessSendButton_17)
        self.ui.SendButton_18.clicked.connect(self.ProcessSendButton_18)
        self.ui.SendButton_19.clicked.connect(self.ProcessSendButton_19)
        self.ui.SendButton_20.clicked.connect(self.ProcessSendButton_20)
        self.ui.SendButton_21.clicked.connect(self.ProcessSendButton_21)
        self.ui.SendButton_22.clicked.connect(self.ProcessSendButton_22)
        self.ui.SendButton_23.clicked.connect(self.ProcessSendButton_23)
        self.ui.SendButton_24.clicked.connect(self.ProcessSendButton_24)
        self.ui.SendButton_25.clicked.connect(self.ProcessSendButton_25)

    #
    # Button press methods
    #
    def ProcessSendButton_1(self):
        self.ProcessSendButtonGeneric(0)
    def ProcessSendButton_2(self):
        self.ProcessSendButtonGeneric(1)
    def ProcessSendButton_3(self):
        self.ProcessSendButtonGeneric(2)
    def ProcessSendButton_4(self):
        self.ProcessSendButtonGeneric(3)
    def ProcessSendButton_5(self):
        self.ProcessSendButtonGeneric(4)
    def ProcessSendButton_6(self):
        self.ProcessSendButtonGeneric(5)
    def ProcessSendButton_7(self):
        self.ProcessSendButtonGeneric(6)
    def ProcessSendButton_8(self):
        self.ProcessSendButtonGeneric(7)
    def ProcessSendButton_9(self):
        self.ProcessSendButtonGeneric(8)
    def ProcessSendButton_10(self):
        self.ProcessSendButtonGeneric(9)
    def ProcessSendButton_11(self):
        self.ProcessSendButtonGeneric(10)
    def ProcessSendButton_12(self):
        self.ProcessSendButtonGeneric(11)
    def ProcessSendButton_13(self):
        self.ProcessSendButtonGeneric(12)
    def ProcessSendButton_14(self):
        self.ProcessSendButtonGeneric(13)
    def ProcessSendButton_15(self):
        self.ProcessSendButtonGeneric(14)
    def ProcessSendButton_16(self):
        self.ProcessSendButtonGeneric(15)
    def ProcessSendButton_17(self):
        self.ProcessSendButtonGeneric(16)
    def ProcessSendButton_18(self):
        self.ProcessSendButtonGeneric(17)
    def ProcessSendButton_19(self):
        self.ProcessSendButtonGeneric(18)
    def ProcessSendButton_20(self):
        self.ProcessSendButtonGeneric(19)
    def ProcessSendButton_21(self):
        self.ProcessSendButtonGeneric(20)
    def ProcessSendButton_22(self):
        self.ProcessSendButtonGeneric(21)
    def ProcessSendButton_23(self):
        self.ProcessSendButtonGeneric(22)
    def ProcessSendButton_24(self):
        self.ProcessSendButtonGeneric(23)
    def ProcessSendButton_25(self):
        self.ProcessSendButtonGeneric(24)

    #
    # Determines if command requires parameters
    #
    def checkParams(self, idx):
        pickle_file = 'ParameterFiles/' + param_files[idx]
        try:
            with open(pickle_file,'rb') as pickle_obj:
                dataTypesOrig, paramNames, paramLen, paramDesc, dataTypesNew, stringLen = pickle.load(pickle_obj)
                if len(paramNames) > 0: # if has parameters
                   return True
                else:
                   return False
        except IOError:
            return False

    #
    # Generic button press method
    #
    def ProcessSendButtonGeneric(self, idx):
        if cmdItemIsValid[idx] == True:
            param_bool = self.checkParams(idx)
            address = str(Commands.ui.commandAddressLineEdit.text())

            # If parameters are required, launches Parameters page
            if param_bool == True:
                prog = 'python Parameter.py'
                launch_string = prog+' --title=\"'+pageTitle+'\" --descrip=\"'+cmdDesc[idx]+'\" --idx='+str(idx)+' --host=\"'+address+'\" --port='+str(pagePort)+' --pktid='+str(pagePktId)+' --endian='+pageEndian+' --cmdcode='+cmdCodes[idx]+' --file='+param_files[idx]

            # If parameters not required, directly calls cmdUtil to send command
            else:
                prog = '../cmdUtil/cmdUtil '
                launch_string = prog + ' --host=' + address + ' --port=' + str(pagePort) + ' --pktid=' + str(pagePktId) + ' --endian=' + pageEndian + ' --cmdcode=' + cmdCodes[idx]

            cmd_args = shlex.split(launch_string)
            subprocess.Popen(cmd_args)

#
# Display usage
#
def usage():
    print "Must specify --title=<page name> --file=<cmd_def_file> --pktid=<packet_app_id(hex)> --endian=<LE|BE> --address=<IP address> --port=<UDP port>"
    print "     example: --title=\"Executive Services\" --file=cfe-es-cmds.txt --pktid=1806  --endian=LE --address=127.0.0.1 --port=1234"

#
# Main
#
if __name__ == '__main__':

    #
    # Set defaults for the arguments
    #
    pageTitle = "Command Page"
    pagePort  = 1234
    pageAddress = "127.0.0.1"
    pagePktId = 1801
    pageEndian = "LE"
    pageDefFile = "cfe__es__msg_8h"

    #
    # process cmd line args
    #
    try:
        opts, args = getopt.getopt(sys.argv[1:], "htpfeap", ["help", "title=", "pktid=", "file=", "endian=", "address=", "port="])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit()
        elif opt in ("-t", "--title"):
            pageTitle = arg
        elif opt in ("-f", "--file"):
            pageDefFile = arg
        elif opt in ("-p", "--pktid"):
            pagePktId = arg
        elif opt in ("-e", "--endian"):
            pageEndian = arg
        elif opt in ("-a", "--address"):
            pageAddress = arg
        elif opt in ("-p", "--port"):
            pagePort = arg

    #
    # Init the QT application and the command class
    #
    app = QtGui.QApplication(sys.argv)
    Commands = SubsystemCommands()
    Commands.ui.subSystemTextBrowser.setText(pageTitle)
    Commands.ui.packetId.display(pagePktId)
    Commands.ui.commandAddressLineEdit.setText(pageAddress)

    #
    # Reads commands from command definition file
    #
    pickle_file = 'CommandFiles/'+pageDefFile
    with open(pickle_file, 'rb') as pickle_obj:
        cmdDesc, cmdCodes, param_files = pickle.load(pickle_obj)

    cmdItemIsValid = []
    for i in range(len(cmdDesc)):
        cmdItemIsValid.append(True)
    for i in range (len(cmdDesc), 26):
        cmdItemIsValid.append(False)

    #
    # Fill the data fields on the page
    #
    if cmdItemIsValid[0] == True:
       Commands.ui.itemLabelTextBrowser_1.setText(cmdDesc[0])
    else:
       Commands.ui.itemLabelTextBrowser_1.setText("(unused)")

    if cmdItemIsValid[1] == True:
       Commands.ui.itemLabelTextBrowser_2.setText(cmdDesc[1])
    else:
       Commands.ui.itemLabelTextBrowser_2.setText("(unused)")

    if cmdItemIsValid[2] == True:
       Commands.ui.itemLabelTextBrowser_3.setText(cmdDesc[2])
    else:
       Commands.ui.itemLabelTextBrowser_3.setText("(unused)")

    if cmdItemIsValid[3] == True:
       Commands.ui.itemLabelTextBrowser_4.setText(cmdDesc[3])
    else:
       Commands.ui.itemLabelTextBrowser_4.setText("(unused)")

    if cmdItemIsValid[4] == True:
       Commands.ui.itemLabelTextBrowser_5.setText(cmdDesc[4])
    else:
       Commands.ui.itemLabelTextBrowser_5.setText("(unused)")

    if cmdItemIsValid[5] == True:
       Commands.ui.itemLabelTextBrowser_6.setText(cmdDesc[5])
    else:
       Commands.ui.itemLabelTextBrowser_6.setText("(unused)")

    if cmdItemIsValid[6] == True:
       Commands.ui.itemLabelTextBrowser_7.setText(cmdDesc[6])
    else:
       Commands.ui.itemLabelTextBrowser_7.setText("(unused)")

    if cmdItemIsValid[7] == True:
       Commands.ui.itemLabelTextBrowser_8.setText(cmdDesc[7])
    else:
       Commands.ui.itemLabelTextBrowser_8.setText("(unused)")

    if cmdItemIsValid[8] == True:
       Commands.ui.itemLabelTextBrowser_9.setText(cmdDesc[8])
    else:
       Commands.ui.itemLabelTextBrowser_9.setText("(unused)")

    if cmdItemIsValid[9] == True:
       Commands.ui.itemLabelTextBrowser_10.setText(cmdDesc[9])
    else:
       Commands.ui.itemLabelTextBrowser_10.setText("(unused)")

    if cmdItemIsValid[10] == True:
       Commands.ui.itemLabelTextBrowser_11.setText(cmdDesc[10])
    else:
       Commands.ui.itemLabelTextBrowser_11.setText("(unused)")

    if cmdItemIsValid[11] == True:
       Commands.ui.itemLabelTextBrowser_12.setText(cmdDesc[11])
    else:
       Commands.ui.itemLabelTextBrowser_12.setText("(unused)")

    if cmdItemIsValid[12] == True:
       Commands.ui.itemLabelTextBrowser_13.setText(cmdDesc[12])
    else:
       Commands.ui.itemLabelTextBrowser_13.setText("(unused)")

    if cmdItemIsValid[13] == True:
       Commands.ui.itemLabelTextBrowser_14.setText(cmdDesc[13])
    else:
       Commands.ui.itemLabelTextBrowser_14.setText("(unused)")

    if cmdItemIsValid[14] == True:
       Commands.ui.itemLabelTextBrowser_15.setText(cmdDesc[14])
    else:
       Commands.ui.itemLabelTextBrowser_15.setText("(unused)")

    if cmdItemIsValid[15] == True:
       Commands.ui.itemLabelTextBrowser_16.setText(cmdDesc[15])
    else:
       Commands.ui.itemLabelTextBrowser_16.setText("(unused)")

    if cmdItemIsValid[16] == True:
       Commands.ui.itemLabelTextBrowser_17.setText(cmdDesc[16])
    else:
       Commands.ui.itemLabelTextBrowser_17.setText("(unused)")

    if cmdItemIsValid[17] == True:
       Commands.ui.itemLabelTextBrowser_18.setText(cmdDesc[17])
    else:
       Commands.ui.itemLabelTextBrowser_18.setText("(unused)")

    if cmdItemIsValid[18] == True:
       Commands.ui.itemLabelTextBrowser_19.setText(cmdDesc[18])
    else:
       Commands.ui.itemLabelTextBrowser_19.setText("(unused)")

    if cmdItemIsValid[19] == True:
       Commands.ui.itemLabelTextBrowser_20.setText(cmdDesc[19])
    else:
       Commands.ui.itemLabelTextBrowser_20.setText("(unused)")

    if cmdItemIsValid[20] == True:
       Commands.ui.itemLabelTextBrowser_21.setText(cmdDesc[20])
    else:
       Commands.ui.itemLabelTextBrowser_21.setText("(unused)")

    if cmdItemIsValid[21] == True:
       Commands.ui.itemLabelTextBrowser_22.setText(cmdDesc[21])
    else:
       Commands.ui.itemLabelTextBrowser_22.setText("(unused)")

    if cmdItemIsValid[22] == True:
       Commands.ui.itemLabelTextBrowser_23.setText(cmdDesc[22])
    else:
       Commands.ui.itemLabelTextBrowser_23.setText("(unused)")

    if cmdItemIsValid[23] == True:
       Commands.ui.itemLabelTextBrowser_24.setText(cmdDesc[23])
    else:
       Commands.ui.itemLabelTextBrowser_24.setText("(unused)")

    if cmdItemIsValid[24] == True:
       Commands.ui.itemLabelTextBrowser_25.setText(cmdDesc[24])
    else:
       Commands.ui.itemLabelTextBrowser_25.setText("(unused)")

    #
    # Display the page
    #
    Commands.show()
    Commands.raise_()
    sys.exit(app.exec_())


text:
youtube-playlist-control
========================

AppleScript for controlling YouTube playlist.

What is it?
===========

``youtube-playlist-controll`` is a collection of AppleScript files to control YouTube playlist opened in web browser.

How to use
==========

Basically, you want to execute the scripts when certain hotkey is triggered. I use [alfred](http://www.alfredapp.com/), but I think you can use [quicksilver](http://qsapp.com/) or [automator](https://www.google.com/search?q=automator+service+applescript) to execute them when hotkey is triggered.

I actually execute shell script that executes the script because none of them allows to set a path to the script to execute; rather they ask you to copy and paste the code. I don't like that.

You can execute the script from terminal like following:

```
$ osascript next.scpt
```

Assumptions
===========
Before using it, you need to make sure that:

- Using OS X.
- Using Chrome.
- YouTube is opened (doesn't matter in which tab nor window), showing a playlist on the page, and already playing some video. The scripts don't know how to initiate to play a video.

How does it work?
=================

It uses AppleScript interface that chrome provides and goes through all windows and tabs to find the tab that has YouTube opened. Then it executes JavaScript on the page that sends appropriate keyboard shortcuts to control it.

License
========

MIT


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ConTangibles")]
[assembly: AssemblyDescription("The all new tangible contact manager")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("TU-Darmstadt")]
[assembly: AssemblyProduct("ConTangibles")]
[assembly: AssemblyCopyright("Copyright ©  2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)]

//      DIM     31.03.2016      1.0.0.0         First stable release


text:
CVE-2022-35937

### Impact
The [`GatherNd`](https://github.com/tensorflow/tensorflow/blob/f463040eb3997e42e60a2ffc6dc72de7ef11dbb4/tensorflow/lite/kernels/gather_nd.cc#L105-L111) function takes arguments that determine the sizes of inputs and outputs. If the inputs given are greater than or equal to the sizes of the outputs, an out-of-bounds memory read is triggered.

### Patches
We have patched the issue in GitHub commit [595a65a3e224a0362d7e68c2213acfc2b499a196](https://github.com/tensorflow/tensorflow/commit/595a65a3e224a0362d7e68c2213acfc2b499a196).

The fix will be included in TensorFlow 2.10.0. We will also cherrypick this commit on TensorFlow 2.9.1, TensorFlow 2.8.1, and TensorFlow 2.7.2, as these are also affected and still in supported range.

### For more information
Please consult [our security guide](https://github.com/tensorflow/tensorflow/blob/master/SECURITY.md) for more information regarding the security model and how to contact us with issues and questions.

### Attribution
This vulnerability has been reported by Hui Peng from Baidu Security.


text:
ADDRESS=$1
PORT=$2

echo -n | openssl s_client -connect $ADDRESS:$PORT | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /tmp/$ADDRESS.$PORT.cert
$JAVA_HOME/bin/keytool -import -alias $ADDRESS-$PORT -keystore $JAVA_HOME/jre/lib/security/cacerts -file /tmp/$ADDRESS.$PORT.cert


text:
Getting The Code
=================

There are two ways to use this library in your applications. You can either:

1. Use [Composer](https://getcomposer.org/), or
2. `require_once` a single `.phar` file in your application.

Option 1: Using Composer
-------------------------

Run this inside the directory of your composer-enabled project:

```sh
composer require defuse/php-encryption
```

Unfortunately, composer doesn't provide a way for you to verify that the code
you're getting was signed by this library's authors. If you want a more secure
option, use the `.phar` method described below.

Option 2: Including a PHAR
----------------------------

The `.phar` option lets you include this library into your project simply by
calling `require_once` on a single file. Download `defuse-crypto.phar` and
`defuse-crypto.phar.sig` from this project's
[releases](https://github.com/defuse/php-encryption/releases) page.

You should verify the integrity of the `.phar`. The `defuse-crypto.phar.sig`
contains the signature of `defuse-crypto.phar`. It is signed with Taylor
Hornby's PGP key. You can find Taylor's public key in `dist/signingkey.asc`. You
can verify the public key's fingerprint against the Taylor Hornby's [contact
page](https://defuse.ca/contact.htm) and
[twitter](https://twitter.com/DefuseSec/status/723741424253059074).

Once you have verified the signature, it is safe to use the `.phar`. Place it
somewhere in your file system, e.g. `/var/www/lib/defuse-crypto.phar`, and then
pass that path to `require_once`.

```php
<?php

    require_once('/var/www/lib/defuse-crypto.phar');

    // ... the Crypto, File, Key, and KeyProtectedByPassword classes are now
    // available ...

    // ...
```


text:
date: 2010-03-01
update: 2014-11-21
author: Nathan
email: nesquena@gmail.com
title: Padrino Admin
permalink: /guides/padrino-admin/
---

Padrino comes shipped with a slick and beautiful Admin Interface, with the following features:

||
|Orm Agnostic|Adapters for datamapper, sequel, activerecord, mongomapper, mongoid, couchrest|
|Authentication|User Authentication Support, User Authorization Management|
|Template Agnostic|Erb and Haml Rendering Support|
|Scaffold|You can create a new "admin interface" by providing a single Model|
|MultiLanguage|English, German, Russian, Danish, French, Brazilian and Italian localizations|

## Admin Usage

Create a new project:

```sh
$ padrino g project fun-test -d datamapper
$ cd fun-test
```

Create the admin application:

```ruby
fun-test $ padrino g admin
```

Follow the instructions in your terminal and provide some valid email and password for your newly created admin account:

- edit your config/database.rb
- migrate your database \# padrino rake ar:migrate or \# dm:migrate
- seed your database with some data \# padrino rake seed

Your admin section is now "setup": you can start padrino `padrino start` and point your web browser to <http://localhost:3000/admin> and log in with your admin account credentials.

If you need to create some sort of "scaffold" (basic CRUD actions) create a *model*, migrate your database, generate your scaffolding folder structure and views and add those to your admin section by running this series of commands:

```sh
fun-test $ padrino g model post title:string body:text
fun-test $ padrino rake dm:migrate # or ar:migrate
fun-test $ padrino g admin_page post
fun-test $ padrino start
```

That's it! Browse to <http://localhost:3000/admin> and access your model by clicking on the newly created tab on your admin navbar: there you can create, edit, destroy and display your objects.

## Admin Authentication

Padrino Admin uses a single model Account for managing roles, memberships and permissions (User Authentication and Authorization).

### Scenario Ecommerce (User Authentication)

To make some practical example, let's examine some common ecommerce application scenario, where we usually need to restrain some users to get access to some of our controllers actions; we can easily accomplish this by editing `app.rb` accordingly:

```ruby
class MyEcommerce < Padrino::Application
  register Padrino::Admin::AccessControl

  enable :authentication
  enable :store_location
  set    :login_page, "/login"

  access_control.roles_for :any do |role|
    role.protect "/customer/orders"
    role.protect "/cart/checkout"
  end
end
```

In the above example we are protecting those paths starting with `/customer/orders` and `/cart/checkout`. The result will be that an unauthenticated user will not be able to access those actions, and he will be asked to authenticate first by visiting our `:login_page` defined as `/login` and by providing his login credentials (default authentication behaviour is email and password).

When successfully logged in, he will be granted access to those two pages.

### Admin Scenario (User Authorization)

For Another example, let's suppose that you need your **admin** account to do certain things and have access to certain controller actions, and your **editor** account needs to be restrained to get access to those same admin actions.

Padrino admin generator, will create for you a new `Account` model with a default `role` attribute.

```ruby
class Admin < Padrino::Application
  register Padrino::Admin::AccessControl

  enable :authentication
  disable :store_location
  set :login_page, "/admin/sessions/new"

  access_control.roles_for :any do |role|
    role.protect "/"
    role.allow "/sessions"
  end

  access_control.roles_for :admin do |role|
    role.project_module :settings, "/settings"
  end

  access_control.roles_for :editor do |role|
    role.project_module :posts, "/posts"
    role.project_module :categories, "/categories"
  end
end
```

In the above example, we *protect* the entire admin section (all paths starting with "/") with the only exception for all those paths starting with `/sessions` giving our `unauthenticated` users the possibility to log in by redirecting them to our login page and asking them to provide their email and password.

If we are logged in as an **admin** (account.role == 'admin') we will have access **only** to the `/settings` path.

If we are logged in as an **editor** (account.role == 'editor') we will have access **only** to the `/posts` and `/categories` paths instead.

### Sharing Sessions Between Mounted Applications

Sessions can be shared between mounted applications by setting a `:session_id` with the line `set :session_id, "your_session_id"` in each apps `app.rb`.

## Contributing Persistence Adapters

If you are planning to use padrino with other adapters rather than the currently supported ones, and you want to contribute to the project by extending its support with additional adapters like ohm, cassandra and so on, be sure to check out the [adding new components](/guides/adding-new-components) guide.


text:
package org.eclipse.bpel4chor.model.chor.common.impl;

import org.eclipse.bpel4chor.model.chor.common.CommonPackage;
import org.eclipse.bpel4chor.model.chor.common.LoopElementInstance;

import org.eclipse.emf.common.notify.Notification;

import org.eclipse.emf.ecore.EClass;

import org.eclipse.emf.ecore.impl.ENotificationImpl;

/**
 *
 * An implementation of the model object 'Loop Element Instance'.
 *
 *

 * The following features are implemented:
 *

 *
{@link org.eclipse.bpel4chor.model.chor.common.impl.LoopElementInstanceImpl#getLoopCounter Loop Counter}

 *

 *

 *
 * @generated
 */
public class LoopElementInstanceImpl extends ExtElementsElementInstanceImpl implements LoopElementInstance {
	/**
	 * The default value of the '{@link #getLoopCounter() Loop Counter}' attribute.
	 *
	 *
	 * @see #getLoopCounter()
	 * @generated
	 * @ordered
	 */
	protected static final long LOOP_COUNTER_EDEFAULT = 0L;

	/**
	 * The cached value of the '{@link #getLoopCounter() Loop Counter}' attribute.
	 *
	 *
	 * @see #getLoopCounter()
	 * @generated
	 * @ordered
	 */
	protected long loopCounter = LOOP_COUNTER_EDEFAULT;

	/**
	 *
	 *
	 * @generated
	 */
	protected LoopElementInstanceImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return CommonPackage.Literals.LOOP_ELEMENT_INSTANCE;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public long getLoopCounter() {
		return loopCounter;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setLoopCounter(long newLoopCounter) {
		long oldLoopCounter = loopCounter;
		loopCounter = newLoopCounter;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, CommonPackage.LOOP_ELEMENT_INSTANCE__LOOP_COUNTER, oldLoopCounter, loopCounter));
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case CommonPackage.LOOP_ELEMENT_INSTANCE__LOOP_COUNTER:
				return getLoopCounter();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case CommonPackage.LOOP_ELEMENT_INSTANCE__LOOP_COUNTER:
				setLoopCounter((Long)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case CommonPackage.LOOP_ELEMENT_INSTANCE__LOOP_COUNTER:
				setLoopCounter(LOOP_COUNTER_EDEFAULT);
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case CommonPackage.LOOP_ELEMENT_INSTANCE__LOOP_COUNTER:
				return loopCounter != LOOP_COUNTER_EDEFAULT;
		}
		return super.eIsSet(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public String toString() {
		if (eIsProxy()) return super.toString();

		StringBuffer result = new StringBuffer(super.toString());
		result.append(" (loopCounter: ");
		result.append(loopCounter);
		result.append(')');
		return result.toString();
	}

} //LoopElementInstanceImpl


text:
#ifndef CSSMutableValue_h
#define CSSMutableValue_h

#include "CSSValue.h"
#include "Node.h"

namespace WebCore {

class CSSMutableValue : public CSSValue {
public:
    CSSMutableValue()
        : m_node(0)
    {
    }

    virtual ~CSSMutableValue() { }
    virtual bool isMutableValue() const { return true; }

    Node* node() const { return m_node; }
    void setNode(Node* node) { m_node = node; }

    void setNeedsStyleRecalc()
    {
        if (!m_node)
            return;
        m_node->setNeedsStyleRecalc(FullStyleChange);
    }

private:
    Node* m_node;
};

} // namespace WebCore

#endif // CSSMutableValue_h


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Concurrent;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeQuality.Analyzers.Maintainability;

namespace Microsoft.CodeQuality.CSharp.Analyzers.Maintainability
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    public sealed class CSharpAvoidUninstantiatedInternalClasses : AvoidUninstantiatedInternalClassesAnalyzer
    {
        public override void RegisterLanguageSpecificChecks(CompilationStartAnalysisContext context, ConcurrentDictionary<INamedTypeSymbol, object?> instantiatedTypes)
        {
            context.RegisterSyntaxNodeAction(context =>
            {
                var usingDirective = (UsingDirectiveSyntax)context.Node;

                if (usingDirective.Alias != null &&
                    usingDirective.DescendantNodes().OfType<GenericNameSyntax>().Any() &&
                    context.SemanticModel.GetDeclaredSymbol(usingDirective) is IAliasSymbol aliasSymbol &&
                    aliasSymbol.Target is INamedTypeSymbol namedTypeSymbol &&
                    namedTypeSymbol.IsGenericType)
                {
                    var generics = namedTypeSymbol.TypeParameters.Zip(namedTypeSymbol.TypeArguments, (parameter, argument) => (parameter, argument));
                    ProcessGenericTypes(generics, instantiatedTypes);
                }
            }, SyntaxKind.UsingDirective);
        }
    }
}


text:
<?php
namespace TYPO3\CMS\SysNote\Controller;

/**
 * Note controller
 */
class NoteController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
    /**
     * @var \TYPO3\CMS\SysNote\Domain\Repository\SysNoteRepository
     */
    protected $sysNoteRepository;

    /**
     * @var \TYPO3\CMS\Extbase\Domain\Repository\BackendUserRepository
     */
    protected $backendUserRepository;

    /**
     * @param \TYPO3\CMS\SysNote\Domain\Repository\SysNoteRepository $sysNoteRepository
     */
    public function injectSysNoteRepository(\TYPO3\CMS\SysNote\Domain\Repository\SysNoteRepository $sysNoteRepository)
    {
        $this->sysNoteRepository = $sysNoteRepository;
    }

    /**
     * @param \TYPO3\CMS\Extbase\Domain\Repository\BackendUserRepository $backendUserRepository
     */
    public function injectBackendUserRepository(\TYPO3\CMS\Extbase\Domain\Repository\BackendUserRepository $backendUserRepository)
    {
        $this->backendUserRepository = $backendUserRepository;
    }

    /**
     * Render notes by single PID or PID list
     *
     * @param string $pids Single PID or comma separated list of PIDs
     * @return string
     * @ignorevalidation $pids
     */
    public function listAction($pids)
    {
        if (empty($pids) || empty($GLOBALS['BE_USER']->user['uid'])) {
            return '';
        }
        $author = $this->backendUserRepository->findByUid($GLOBALS['BE_USER']->user['uid']);
        $notes = $this->sysNoteRepository->findByPidsAndAuthor($pids, $author);
        $this->view->assign('notes', $notes);
    }
}


text:
namespace clover {
namespace nodes {
class NodeType;

class CompositionNodeLogicGroup;

/// Contains settings for a NodeType which'll be instantiated
class ENGINE_API CompositionNodeLogic : public util::Callbacker<util::OnChangeCb> {
public: // Copypasted from former BaseCompositionNodeScriptLogic

	typedef util::UniquePtr<CompositionNodeSlot> CompositionNodeSlotPtr;
	typedef util::UniquePtr<CompositionNodeSlotTemplateGroup> CompositionNodeSlotTemplateGroupPtr;

	CompositionNodeSlot& addInputSlot(const SlotIdentifier& identifier, const util::Any& init_value);

	template <typename T>
	CompositionNodeSlot& addInputSlot(const util::Str8& name, const SignalType& signal_type, const T& init_value){
		return addInputSlot(name, "", signal_type, init_value);
	}

	template <typename T>
	CompositionNodeSlot& addInputSlot(const util::Str8& name, const util::Str8& group, const SignalType& signal_type, const T& init_value){
		return addInputSlot(SlotIdentifier{name, group, signal_type, true}, util::Any(init_value));
	}

	CompositionNodeSlot& addInputSlot(const util::Str8& name, const SignalType& signal_type){
		return addInputSlot(name, "", signal_type);
	}

	CompositionNodeSlot& addInputSlot(const SlotIdentifier& id){
		return addInputSlot(id.name, id.groupName, id.signalType);
	}

	CompositionNodeSlot& addInputSlot(const util::Str8& name, const util::Str8& group, const SignalType& signal_type){
		return addInputSlot(SlotIdentifier{name, group, signal_type, true}, RuntimeSignalTypeTraits::defaultInitValue(signal_type));
	}

	CompositionNodeSlot& addOutputSlot(const SlotIdentifier& identifier);

	CompositionNodeSlot& addOutputSlot(const util::Str8& name, const SignalType& signal_type){
		return addOutputSlot(name, "", signal_type);
	}

	CompositionNodeSlot& addOutputSlot(const util::Str8& name, const util::Str8& group, const SignalType& signal_type){
		return addOutputSlot(SlotIdentifier{name, group, signal_type, false});
	}

	CompositionNodeSlot& addSlot(const SlotIdentifier& id, util::Any init_value);
	CompositionNodeSlot& addSlot(const SlotIdentifier& id);

	void removeSlot(const SlotIdentifier& id);
	void removeSlot(const CompositionNodeSlot& slot){ removeSlot(slot.getIdentifier()); }

	CompositionNodeSlot& getSlot(const SlotIdentifier& id) const;
	bool hasSlot(const SlotIdentifier& id) const { return slots.find(id) != slots.end(); }

	const util::DynArray<CompositionNodeSlot*>& getSlots() const { return slotArray; }
	util::DynArray<CompositionNodeSlot*>& getSlots() { return slotArray; }

	util::DynArray<SlotIdentifier> getSlotIdentifiers() const;

	CompositionNodeSlotTemplateGroup& addSlotTemplateGroup(const util::Str8& name, bool input);
	CompositionNodeSlotTemplateGroup& addInputSlotTemplateGroup(const util::Str8& name){ return addSlotTemplateGroup(name, true); }
	CompositionNodeSlotTemplateGroup& addOutputSlotTemplateGroup(const util::Str8& name){ return addSlotTemplateGroup(name, false); }

	const CompositionNodeSlotTemplateGroup& getSlotTemplateGroup(const util::Str8& name) const;
	CompositionNodeSlotTemplateGroup& getSlotTemplateGroup(const util::Str8& name);

	bool hasSlotTemplateGroup(const util::Str8& name) const;

	/// First to update in a NodeGroup
	void setAsUpdateRouteStart(bool b);
	bool isUpdateRouteStart() const { return updateRouteStart; }

	template <typename T>
	void addResourceChangeListener(const typename resources::ResourceTraits<T>::IdentifierValue& identifier){
		const auto& res= global::g_env.resCache->getResource<T>(identifier);
		addOnResourceChangeCallback(res);
	}
	void clearResourceChangeListeners(){ resourceChangeListener.clear(); }

	void setBatched(bool b= true){ batched= b; }
	void setBatchPriority(int32 p){ batchPriority= p; }

	bool isBatched() const { return batched; }
	int32 getBatchPriority() const { return batchPriority; }

	const util::HashMap<util::Str8, CompositionNodeSlotTemplateGroupPtr>& getSlotTemplateGroups() const { return templateGroups; }

	virtual void onDefaultValueChange(CompositionNodeSlot& slot);
	void onRoutingChange(CompositionNodeSlot& slot);
	virtual void onResourceChange(const resources::Resource& res) {}

	void clear();

	// Doesn't send events if silent
	void setSilent(bool b= true){ silent= b; }

private:
	// Just adds a new slot to the containers
	CompositionNodeSlot& addSlotMinimal(const SlotIdentifier& id);

	void sendOnSlotAddEvent(const SlotIdentifier& id);
	void sendOnSlotRemoveEvent(const SlotIdentifier& id);

	void addOnResourceChangeCallback(const resources::Resource& res);

	const NodeType* type;
	const CompositionNodeLogicGroup* owner;

	bool batched;
	int32 batchPriority;

	util::HashMap<SlotIdentifier, CompositionNodeSlotPtr> slots;
	util::DynArray<CompositionNodeSlot*> slotArray; // To preserve ordering
	util::HashMap<util::Str8, CompositionNodeSlotTemplateGroupPtr> templateGroups;

	bool updateRouteStart;
	bool silent; // Don't emit any events (doesn't probably cover all cases, is used when slot is replaced by changed one)
	util::CbMultiListener<util::OnChangeCb> resourceChangeListener;

public: // Original CompositionNodeLogic
	CompositionNodeLogic();
	~CompositionNodeLogic();
	void setType(const NodeType& type_);
	CompositionNodeLogic(CompositionNodeLogic&&)= delete;

	void setOwner(const CompositionNodeLogicGroup& o){ owner= &o; }
	const CompositionNodeLogicGroup& getOwner() const { ensure(owner); return *owner; }

	CompositionNodeSlot& getInputSlot(const SlotIdentifier& id) const;
	CompositionNodeSlot& getOutputSlot(const SlotIdentifier& id) const;

	const NodeType& getType() const;

	util::DynArray<CompositionNodeSlot*> getTemplateGroupSlots() const;

	util::DynArray<CompositionNodeSlotTemplateGroup*> getInputSlotTemplateGroups() const;
	util::DynArray<CompositionNodeSlotTemplateGroup*> getOutputSlotTemplateGroups() const;
	util::DynArray<CompositionNodeSlotTemplateGroup*> getSlotTemplateGroups(bool input) const;

	void addSlot(const SlotTemplate& slot);
	void removeSlot(const SlotTemplate& slot);

	void setPosition(const util::Vec2d& p){ position= p; }
	const util::Vec2d& getPosition() const { return position; }

private:
	void recreate();

	util::Vec2d position;
	util::CbListener<util::OnChangeCb> typeChangeListener;
};

} // nodes
namespace util {

template <>
struct TypeStringTraits<nodes::CompositionNodeLogic> {
	static util::Str8 type(){ return "::CompositionNodeLogic"; }
};

} // util
} // clover

#endif // CLOVER_NODES_COMPOSITIONNODELOGIC_HPP


text:
require 'test_helper'

class InstanceTest < BaseTest
  Song = Struct.new(:id, :title)
  Song.class_eval do
    def self.find(id)
      new(id, "Invincible")
    end
  end

  describe "lambda { fragment } (new way of class: lambda { nil })" do
    representer! do
      property :title, :instance  => lambda { |fragment, args| fragment }
    end

    it "skips creating new instance" do
      object = Object.new
      object.instance_eval do
        def from_hash(hash, *args)
          hash
        end
      end

      song = OpenStruct.new.extend(representer).from_hash(hash = {"title" => object})
      song.title.must_equal object
    end
  end

# TODO: use *args in from_hash.
# DISCUSS: do we need parse_strategy?
  describe "property with :instance" do
    representer!(:inject => :song_representer) do
      property :song,
        :instance => lambda { |fragment, *args| fragment["id"] == song.id ? song : Song.find(fragment["id"]) },
        :extend => song_representer
    end

    it { OpenStruct.new(:song => Song.new(1, "The Answer Is Still No")).extend(representer).
      from_hash("song" => {"id" => 1}).song.must_equal Song.new(1, "The Answer Is Still No") }

    it { OpenStruct.new(:song => Song.new(1, "The Answer Is Still No")).extend(representer).
      from_hash("song" => {"id" => 2}).song.must_equal Song.new(2, "Invincible") }
  end

  describe "collection with :instance" do
    representer!(:inject => :song_representer) do
      collection :songs,
        :instance => lambda { |fragment, i, *args|

          fragment["id"] == songs[i].id ? songs[i] : Song.find(fragment["id"])
        }, # let's not allow returning nil anymore. make sure we can still do everything as with nil. also, let's remove parse_strategy: sync.

        :extend => song_representer
    end

    it {
      album= Struct.new(:songs).new(songs = [
      Song.new(1, "The Answer Is Still No"),
      Song.new(2, "")])

      album.
        extend(representer).
        from_hash("songs" => [{"id" => 2},{"id" => 2, "title"=>"The Answer Is Still No"}]).songs.must_equal [
          Song.new(2, "Invincible"), Song.new(2, "The Answer Is Still No")]
    }
  end

  describe "property with lambda receiving fragment and args" do
    representer!(:inject => :song_representer) do
      property :song, :instance => lambda { |fragment, args| Struct.new(:args, :id).new([fragment, args]) }, :extend => song_representer
    end

    it { OpenStruct.new(:song => Song.new(1, "The Answer Is Still No")).extend(representer).
      from_hash({"song" => {"id" => 1}}, {:volume => 1}).song.args.must_equal([{"id"=>1}, {:volume=>1}]) }
  end

  # TODO: raise and test instance:{nil}
  # describe "property with instance: { nil }" do # TODO: introduce :representable option?
  #   representer!(:inject => :song_representer) do
  #     property :song, :instance => lambda { |*| nil }, :extend => song_representer
  #   end

  #   let (:hit) { hit = OpenStruct.new(:song => song).extend(representer) }

  #   it "calls #to_hash on song instance, nothing else" do
  #     hit.to_hash.must_equal("song"=>{"title"=>"Resist Stance"})
  #   end

  #   it "calls #from_hash on the existing song instance, nothing else" do
  #     song_id = hit.song.object_id
  #     hit.from_hash("song"=>{"title"=>"Suffer"})
  #     hit.song.title.must_equal "Suffer"
  #     hit.song.object_id.must_equal song_id
  #   end
  # end

  # lambda { |fragment, i, Context(binding: <..>, args: [..])| }

  describe "sync" do
    representer!(:inject => :song_representer) do
      collection :songs,
        :instance => lambda { |fragment, i, *args|
          songs[i]
        },
        :extend => song_representer,
        # :parse_strategy => :sync
        :setter => lambda { |*|  }
    end

    it {
      album= Struct.new(:songs).new(songs = [
      Song.new(1, "The Answer Is Still No"),
      Song.new(2, "Invncble")])

      album.
        extend(representer).
        from_hash("songs" => [{"title" => "The Answer Is Still No"}, {"title" => "Invincible"}])

      album.songs.must_equal [
        Song.new(1, "The Answer Is Still No"),
        Song.new(2, "Invincible")]

      songs.object_id.must_equal album.songs.object_id
      songs[0].object_id.must_equal album.songs[0].object_id
      songs[1].object_id.must_equal album.songs[1].object_id
    }
  end

  describe "update existing elements, only" do
    representer!(:inject => :song_representer) do
      collection :songs,
        :instance => lambda { |fragment, i, *args|

          #fragment["id"] == songs[i].id ? songs[i] : Song.find(fragment["id"])
          songs.find { |s| s.id == fragment["id"] }
        }, # let's not allow returning nil anymore. make sure we can still do everything as with nil. also, let's remove parse_strategy: sync.

        :extend => song_representer,
        # :parse_strategy => :sync
        :setter => lambda { |*|  }
    end

    it {
      album= Struct.new(:songs).new(songs = [
      Song.new(1, "The Answer Is Still No"),
      Song.new(2, "Invncble")])

      album.
        extend(representer).
        from_hash("songs" => [{"id" => 2, "title" => "Invincible"}]).
        songs.must_equal [
          Song.new(1, "The Answer Is Still No"),
          Song.new(2, "Invincible")]
          # TODO: check elements object_id!

      songs.object_id.must_equal album.songs.object_id
      songs[0].object_id.must_equal album.songs[0].object_id
      songs[1].object_id.must_equal album.songs[1].object_id
    }
  end

  describe "add incoming elements, only" do
    representer!(:inject => :song_representer) do
      collection :songs,
        :instance => lambda { |fragment, i, *args|
          songs << song=Song.new(2)
          song
        }, # let's not allow returning nil anymore. make sure we can still do everything as with nil. also, let's remove parse_strategy: sync.

        :extend => song_representer,
        # :parse_strategy => :sync
        :setter => lambda { |*|  }
    end

    it {
      album= Struct.new(:songs).new(songs = [
        Song.new(1, "The Answer Is Still No")])

      album.
        extend(representer).
        from_hash("songs" => [{"title" => "Invincible"}]).
        songs.must_equal [
          Song.new(1, "The Answer Is Still No"),
          Song.new(2, "Invincible")]

      songs.object_id.must_equal album.songs.object_id
      songs[0].object_id.must_equal album.songs[0].object_id
    }
  end

  # not sure if this must be a library strategy
  describe "replace existing element" do
    representer!(:inject => :song_representer) do
      collection :songs,
        :instance => lambda { |fragment, i, *args|
          id = fragment.delete("replace_id")
          replaced = songs.find { |s| s.id == id }
          songs[songs.index(replaced)] = song=Song.new(3)
          song
        }, # let's not allow returning nil anymore. make sure we can still do everything as with nil. also, let's remove parse_strategy: sync.

        :extend => song_representer,
        # :parse_strategy => :sync
        :setter => lambda { |*|  }
    end

    it {
      album= Struct.new(:songs).new(songs = [
        Song.new(1, "The Answer Is Still No"),
        Song.new(2, "Invincible")])

      album.
        extend(representer).
        from_hash("songs" => [{"replace_id"=>2, "id" => 3, "title" => "Soulmate"}]).
        songs.must_equal [
          Song.new(1, "The Answer Is Still No"),
          Song.new(3, "Soulmate")]

      songs.object_id.must_equal album.songs.object_id
      songs[0].object_id.must_equal album.songs[0].object_id
    }
  end

  describe "replace collection" do
    representer!(:inject => :song_representer) do
      collection :songs,
        :extend => song_representer, :class => Song
    end

    it {
      album= Struct.new(:songs).new(songs = [
        Song.new(1, "The Answer Is Still No")])

      album.
        extend(representer).
        from_hash("songs" => [{"title" => "Invincible"}]).
        songs.must_equal [
          Song.new(nil, "Invincible")]

      songs.object_id.wont_equal album.songs.object_id
    }
  end

  describe "new syntax for instance: true" do
    representer!(:inject => :song_representer) do
      property :song, :pass_options => true,
        :extend => song_representer, :instance => lambda { |fragment, args| args.binding.get }
    end

    it "uses Binding#get instead of creating an instance, but deprecates" do
      album= Struct.new(:song).new(song = Song.new(1, "The Answer Is Still No"))

      album.
        extend(representer).
        from_hash("song" => {"title" => "Invincible"}).
        song.must_equal Song.new(1, "Invincible")

      album.song.object_id.must_equal song.object_id
    end
  end
end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="theme" content="hugo-academic">
  <meta name="generator" content="Hugo 0.37.1" />
  <meta name="author" content="Dang-Khoa">
  <meta name="description" content="Research Assistant">

  <link rel="alternate" hreflang="en-us" href="http://dangkhoasdc.github.io/post/linear_models/">

        <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha512-6MXa8B6uaO18Hid6blRMetEIoPqHf7Ux1tnyIQdpt9qI5OACx7C+O3IVTr98vwGnlcg0LOLa02i9Y1HpVhlfiw==" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.8.1/css/academicons.min.css" integrity="sha512-NThgw3XKQ1absAahW6to7Ey42uycrVvfNfyjqcFNgCmOCQ5AR4AO0SiXrN+8ZtYeappp56lk1WtvjVmEa+VR6A==" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha512-SfTiTlX6kk+qitfevl/7LibUOeJWlt9rbyDn92a1DqWOw9vWG2MFoays0sgObmWazO5BQPiFucnnEAjpAB+/Sw==" crossorigin="anonymous">

  <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Montserrat:400,700%7cRoboto:400,400italic,700%7cRoboto+Mono">

  <link rel="stylesheet" href="/styles.css">

  <link rel="stylesheet" href="/css/custom-theme.css">

  <link rel="manifest" href="/site.webmanifest">
  <link rel="icon" type="image/png" href="/img/icon.png">
  <link rel="apple-touch-icon" type="image/png" href="/img/icon-192.png">

  <link rel="canonical" href="http://dangkhoasdc.github.io/post/linear_models/">

  <meta property="twitter:card" content="summary_large_image">

  <meta property="twitter:site" content="@dksdc">
  <meta property="twitter:creator" content="@dksdc">

  <meta property="og:site_name" content="Dang-Khoa's blog ">
  <meta property="og:url" content="http://dangkhoasdc.github.io/post/linear_models/">
  <meta property="og:title" content="Linear Models | Dang-Khoa's blog ">
  <meta property="og:description" content="">
  <meta property="og:locale" content="en-us">

  <meta property="article:published_time" content="2018-03-10T00:00:00+00:00">

  <meta property="article:modified_time" content="2018-03-10T00:00:00+00:00">

  <title>Linear Models | Dang-Khoa's blog </title>

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
              data-target=".navbar-collapse" aria-expanded="false">
        Toggle navigation

      </button>

      Dang-Khoa's blog

            Posts

            Home

            Projects

            Publications

            About

            Notes

Linear Models

    <time datetime="2018-03-10 00:00:00 +0000 UTC" itemprop="datePublished">
      2018-03-10
    </time>

    0 min read

  machine learning

Please enable JavaScript to view the comments powered by Disqus.
comments powered by Disqus

      © 2017 Dang-Khoa ·

      Powered by the
      Academic theme for
      Hugo.

        <button type="button" class="close btn-large" data-dismiss="modal">×</button>

Cite

           Copy

           Download


text:
class AddRecipientIdToMessages < ActiveRecord::Migration
  def self.up
    add_column :messages, :recipient_id, :integer
  end

  def self.down
    remove_column :messages, :recipient_id
  end
end


text:
package com.futureprocessing.documentjuggler.versioning;

import com.futureprocessing.documentjuggler.insert.InsertProcessor;
import com.futureprocessing.documentjuggler.query.QueryProcessor;
import com.futureprocessing.documentjuggler.query.ReadQueriedDocuments;
import com.futureprocessing.documentjuggler.read.ReadProcessor;
import com.futureprocessing.documentjuggler.update.BaseUpdateResult;
import com.futureprocessing.documentjuggler.update.RootUpdateBuilder;
import com.futureprocessing.documentjuggler.update.UpdateProcessor;
import com.futureprocessing.documentjuggler.update.UpdateResult;
import com.mongodb.*;
import org.bson.types.ObjectId;

import java.util.Date;
import java.util.function.Consumer;

import static com.futureprocessing.documentjuggler.versioning.VersionedDocument.*;

public class VersioningRepository<MODEL extends VersionedDocument<MODEL>> {

    private final DBCollection dbCollection;
    private final DBCollection archiveCollection;

    private final ReadProcessor<MODEL> readProcessor;
    private final QueryProcessor<MODEL> queryProcessor;
    private final InsertProcessor<MODEL> insertProcessor;
    private final UpdateProcessor<MODEL> updateProcessor;

    public VersioningRepository(DBCollection dbCollection, DBCollection archiveCollection, Class<MODEL> modelClass) {

        this.dbCollection = dbCollection;
        this.archiveCollection = archiveCollection;

        this.readProcessor = new ReadProcessor<>(modelClass, dbCollection);
        this.queryProcessor = new QueryProcessor<>(modelClass);
        this.insertProcessor = new InsertProcessor<>(modelClass);
        this.updateProcessor = new UpdateProcessor<>(modelClass);
    }

    public ReadQueriedDocuments<MODEL> find(Consumer<MODEL> consumer) {
        return new VersionedQueriedDocuments<>(dbCollection, queryProcessor.process(consumer), readProcessor, updateProcessor);
    }

    public ReadQueriedDocuments<MODEL> find() {
        return new VersionedQueriedDocuments<>(dbCollection, null, readProcessor, updateProcessor);
    }

    public String insert(Consumer<MODEL> consumer) {
        BasicDBObject document = insertProcessor.process(consumer);

        final ObjectId docId = new ObjectId();

        document.put(DOC_ID, docId);
        document.put(VERSION, 1);
        document.put(DATE, new Date());
        document.put(PENDING_ARCHIVE, true);

        dbCollection.insert(document);

        document.remove(PENDING_ARCHIVE);
        archiveCollection.insert(document);

        unsetPending(docId);

        return docId.toHexString();
    }

    public UpdateResult update(final String docIdString, int version, Consumer<MODEL> consumer) {
        final ObjectId docId = new ObjectId(docIdString);
        final BasicDBObject updateOperation = updateProcessor.process(consumer);

        RootUpdateBuilder updateBuilder = new RootUpdateBuilder(updateOperation);
        updateBuilder.set(PENDING_ARCHIVE, true);
        updateBuilder.inc(VERSION, 1);

        final DBObject query = QueryBuilder.start(DOC_ID).is(docId)
                .and(VERSION).is(version)
                .and(PENDING_ARCHIVE).exists(false).get();

        BasicDBObject modified = (BasicDBObject) dbCollection.findAndModify(query, null, null, false, updateBuilder.getDocument(), true, false);
        if (modified == null) {

            query.removeField(PENDING_ARCHIVE);
            BasicDBObject foundPending = (BasicDBObject) dbCollection.findOne(query);
            if (foundPending == null) {
                return new InvalidVersionUpdateResult();
            }
            copyToArchive(foundPending);
            unsetPending(docId);
            return update(docIdString, version, consumer);
        }

        copyToArchive(modified);

        WriteResult result = unsetPending(docId);
        return new BaseUpdateResult(result);

    }

    private WriteResult copyToArchive(BasicDBObject document) {

        DBObject docIdVersionQuery = QueryBuilder.start(DOC_ID).is(document.getObjectId(DOC_ID))
                .and(VERSION).is(document.getInt(VERSION)).get();

        document.remove("_id");
        document.remove(PENDING_ARCHIVE);

        return archiveCollection.update(docIdVersionQuery, document, true, false);
    }

    private WriteResult unsetPending(ObjectId docId) {
        BasicDBObject query = new BasicDBObject(DOC_ID, docId);

        RootUpdateBuilder updateBuilder = new RootUpdateBuilder();
        updateBuilder.unset(PENDING_ARCHIVE);

        return dbCollection.update(query, updateBuilder.getDocument());
    }
}


text:
// Archive/RarHeader.h

#ifndef __ARCHIVE_RAR_HEADER_H
#define __ARCHIVE_RAR_HEADER_H

#include "Common/Types.h"

namespace NArchive {
namespace NRar {
namespace NHeader {

const int kMarkerSize = 7;
extern Byte kMarker[kMarkerSize];

const int kArchiveSolid = 0x1;

namespace NBlockType
{
  enum EBlockType
  {
    kMarker = 0x72,
    kArchiveHeader,
    kFileHeader,
    kCommentHeader,
    kOldAuthenticity,
    kOldSubBlock,
    kRecoveryRecord,
    kAuthenticity,
    kSubBlock,
    kEndOfArchive
  };
}

namespace NArchive
{
  const UInt16 kVolume  = 1;
  const UInt16 kComment = 2;
  const UInt16 kLock    = 4;
  const UInt16 kSolid   = 8;
  const UInt16 kNewVolName = 0x10; // ('volname.partN.rar')
  const UInt16 kAuthenticity  = 0x20;
  const UInt16 kRecovery = 0x40;
  const UInt16 kBlockEncryption  = 0x80;
  const UInt16 kFirstVolume = 0x100; // (set only by RAR 3.0 and later)
  const UInt16 kEncryptVer = 0x200; // RAR 3.6 there is EncryptVer Byte in End of MainHeader

  const int kHeaderSizeMin = 7;

  const int kArchiveHeaderSize = 13;

  const int kBlockHeadersAreEncrypted = 0x80;

}

namespace NFile
{
  const int kSplitBefore = 1 << 0;
  const int kSplitAfter  = 1 << 1;
  const int kEncrypted   = 1 << 2;
  const int kComment     = 1 << 3;
  const int kSolid       = 1 << 4;

  const int kDictBitStart     = 5;
  const int kNumDictBits  = 3;
  const int kDictMask         = (1 << kNumDictBits) - 1;
  const int kDictDirectoryValue  = 0x7;

  const int kSize64Bits    = 1 << 8;
  const int kUnicodeName   = 1 << 9;
  const int kSalt          = 1 << 10;
  const int kOldVersion    = 1 << 11;
  const int kExtTime       = 1 << 12;
  // const int kExtFlags      = 1 << 13;
  // const int kSkipIfUnknown = 1 << 14;

  const int kLongBlock    = 1 << 15;

  /*
  struct CBlock
  {
    // UInt16 HeadCRC;
    // Byte Type;
    // UInt16 Flags;
    // UInt16 HeadSize;
    UInt32 PackSize;
    UInt32 UnPackSize;
    Byte HostOS;
    UInt32 FileCRC;
    UInt32 Time;
    Byte UnPackVersion;
    Byte Method;
    UInt16 NameSize;
    UInt32 Attributes;
  };
  */

  /*
  struct CBlock32
  {
    UInt16 HeadCRC;
    Byte Type;
    UInt16 Flags;
    UInt16 HeadSize;
    UInt32 PackSize;
    UInt32 UnPackSize;
    Byte HostOS;
    UInt32 FileCRC;
    UInt32 Time;
    Byte UnPackVersion;
    Byte Method;
    UInt16 NameSize;
    UInt32 Attributes;
    UInt16 GetRealCRC(const void *aName, UInt32 aNameSize,
        bool anExtraDataDefined = false, Byte *anExtraData = 0) const;
  };
  struct CBlock64
  {
    UInt16 HeadCRC;
    Byte Type;
    UInt16 Flags;
    UInt16 HeadSize;
    UInt32 PackSizeLow;
    UInt32 UnPackSizeLow;
    Byte HostOS;
    UInt32 FileCRC;
    UInt32 Time;
    Byte UnPackVersion;
    Byte Method;
    UInt16 NameSize;
    UInt32 Attributes;
    UInt32 PackSizeHigh;
    UInt32 UnPackSizeHigh;
    UInt16 GetRealCRC(const void *aName, UInt32 aNameSize) const;
  };
  */

  const int kLabelFileAttribute            = 0x08;
  const int kWinFileDirectoryAttributeMask = 0x10;

  enum CHostOS
  {
    kHostMSDOS = 0,
      kHostOS2   = 1,
      kHostWin32 = 2,
      kHostUnix  = 3,
      kHostMacOS = 4,
      kHostBeOS = 5
  };
}

namespace NBlock
{
  const UInt16 kLongBlock = 1 << 15;
  struct CBlock
  {
    UInt16 CRC;
    Byte Type;
    UInt16 Flags;
    UInt16 HeadSize;
    //  UInt32 DataSize;
  };
}

/*
struct CSubBlock
{
  UInt16 HeadCRC;
  Byte HeadType;
  UInt16 Flags;
  UInt16 HeadSize;
  UInt32 DataSize;
  UInt16 SubType;
  Byte Level; // Reserved : Must be 0
};

struct CCommentBlock
{
  UInt16 HeadCRC;
  Byte HeadType;
  UInt16 Flags;
  UInt16 HeadSize;
  UInt16 UnpSize;
  Byte UnpVer;
  Byte Method;
  UInt16 CommCRC;
};

struct CProtectHeader
{
  UInt16 HeadCRC;
  Byte HeadType;
  UInt16 Flags;
  UInt16 HeadSize;
  UInt32 DataSize;
  Byte Version;
  UInt16 RecSectors;
  UInt32 TotalBlocks;
  Byte Mark[8];
};
*/

}}}

#endif


text:
// Code generated by client-gen. DO NOT EDIT.

package fake

import (
	core_v1 "k8s.io/api/core/v1"
	v1beta1 "k8s.io/api/extensions/v1beta1"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	labels "k8s.io/apimachinery/pkg/labels"
	schema "k8s.io/apimachinery/pkg/runtime/schema"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	testing "k8s.io/client-go/testing"
)

// FakeReplicationControllers implements ReplicationControllerInterface
type FakeReplicationControllers struct {
	Fake *FakeCoreV1
	ns   string
}

var replicationcontrollersResource = schema.GroupVersionResource{Group: "", Version: "v1", Resource: "replicationcontrollers"}

var replicationcontrollersKind = schema.GroupVersionKind{Group: "", Version: "v1", Kind: "ReplicationController"}

// Get takes name of the replicationController, and returns the corresponding replicationController object, and an error if there is any.
func (c *FakeReplicationControllers) Get(name string, options v1.GetOptions) (result *core_v1.ReplicationController, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewGetAction(replicationcontrollersResource, c.ns, name), &core_v1.ReplicationController{})

	if obj == nil {
		return nil, err
	}
	return obj.(*core_v1.ReplicationController), err
}

// List takes label and field selectors, and returns the list of ReplicationControllers that match those selectors.
func (c *FakeReplicationControllers) List(opts v1.ListOptions) (result *core_v1.ReplicationControllerList, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewListAction(replicationcontrollersResource, replicationcontrollersKind, c.ns, opts), &core_v1.ReplicationControllerList{})

	if obj == nil {
		return nil, err
	}

	label, _, _ := testing.ExtractFromListOptions(opts)
	if label == nil {
		label = labels.Everything()
	}
	list := &core_v1.ReplicationControllerList{}
	for _, item := range obj.(*core_v1.ReplicationControllerList).Items {
		if label.Matches(labels.Set(item.Labels)) {
			list.Items = append(list.Items, item)
		}
	}
	return list, err
}

// Watch returns a watch.Interface that watches the requested replicationControllers.
func (c *FakeReplicationControllers) Watch(opts v1.ListOptions) (watch.Interface, error) {
	return c.Fake.
		InvokesWatch(testing.NewWatchAction(replicationcontrollersResource, c.ns, opts))

}

// Create takes the representation of a replicationController and creates it.  Returns the server's representation of the replicationController, and an error, if there is any.
func (c *FakeReplicationControllers) Create(replicationController *core_v1.ReplicationController) (result *core_v1.ReplicationController, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewCreateAction(replicationcontrollersResource, c.ns, replicationController), &core_v1.ReplicationController{})

	if obj == nil {
		return nil, err
	}
	return obj.(*core_v1.ReplicationController), err
}

// Update takes the representation of a replicationController and updates it. Returns the server's representation of the replicationController, and an error, if there is any.
func (c *FakeReplicationControllers) Update(replicationController *core_v1.ReplicationController) (result *core_v1.ReplicationController, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewUpdateAction(replicationcontrollersResource, c.ns, replicationController), &core_v1.ReplicationController{})

	if obj == nil {
		return nil, err
	}
	return obj.(*core_v1.ReplicationController), err
}

// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *FakeReplicationControllers) UpdateStatus(replicationController *core_v1.ReplicationController) (*core_v1.ReplicationController, error) {
	obj, err := c.Fake.
		Invokes(testing.NewUpdateSubresourceAction(replicationcontrollersResource, "status", c.ns, replicationController), &core_v1.ReplicationController{})

	if obj == nil {
		return nil, err
	}
	return obj.(*core_v1.ReplicationController), err
}

// Delete takes name of the replicationController and deletes it. Returns an error if one occurs.
func (c *FakeReplicationControllers) Delete(name string, options *v1.DeleteOptions) error {
	_, err := c.Fake.
		Invokes(testing.NewDeleteAction(replicationcontrollersResource, c.ns, name), &core_v1.ReplicationController{})

	return err
}

// DeleteCollection deletes a collection of objects.
func (c *FakeReplicationControllers) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
	action := testing.NewDeleteCollectionAction(replicationcontrollersResource, c.ns, listOptions)

	_, err := c.Fake.Invokes(action, &core_v1.ReplicationControllerList{})
	return err
}

// Patch applies the patch and returns the patched replicationController.
func (c *FakeReplicationControllers) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *core_v1.ReplicationController, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewPatchSubresourceAction(replicationcontrollersResource, c.ns, name, data, subresources...), &core_v1.ReplicationController{})

	if obj == nil {
		return nil, err
	}
	return obj.(*core_v1.ReplicationController), err
}

// GetScale takes name of the replicationController, and returns the corresponding scale object, and an error if there is any.
func (c *FakeReplicationControllers) GetScale(replicationControllerName string, options v1.GetOptions) (result *v1beta1.Scale, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewGetSubresourceAction(replicationcontrollersResource, c.ns, "scale", replicationControllerName), &v1beta1.Scale{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.Scale), err
}

// UpdateScale takes the representation of a scale and updates it. Returns the server's representation of the scale, and an error, if there is any.
func (c *FakeReplicationControllers) UpdateScale(replicationControllerName string, scale *v1beta1.Scale) (result *v1beta1.Scale, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewUpdateSubresourceAction(replicationcontrollersResource, "scale", c.ns, scale), &v1beta1.Scale{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.Scale), err
}