text:
[Defining Variables](https://github.com/abernet2/phase-0/blob/master/week-4/defining-variables.rb)

[Simple Strings](https://github.com/abernet2/phase-0/blob/master/week-4/simple-string.rb)

[Basic Math](https://github.com/abernet2/phase-0/blob/master/week-4/basic-math.rb)

# Release 7 Reflections

##How does Ruby handle addition, subtraction, multiplication, and division of numbers?

Pretty much like the normal math, it obeys order of operations and can perform any of
those on most numbers, although there are limitations to how specific or large the ans-
wer can be.

Where it diverges from normal math is that it treats numbers with decimals differently.
If Ruby sees a decimal on a number that you enter, it will store it and treat it as a
floating point (number with a decimal). If you want to mix them, it will always give
you a float for an answer. If you want to divide two fixnums (numbers without decimals)
with the result of a float, then you need to convert one to a float. 15/2 will never
return 7.5 if you dont.

##What is the difference between integers and floats?

Integers aren't encoded to store decimals, floats are. [Here's a demonstration](http://www.dummies.com/how-to/content/the-real-difference-between-integers-and-floatingp.html).
You might think, 'why don't I just use floats all the time?' For the same amount
of memory, you can store bigger numbers if you don't include decimals. Also it's
just simpler, and sometimes you might actually want to use remainders and whole
number division.

##What is the difference between integer and float division?

Integer division returns a quotient or a remainder. Float returns a decimal number.

##What are strings? Why and when would you use them?

Strings are a how we store text in vairables. You would use them to manipulate any
textual data, or to communicate with yourself or the user of your program. You can
also use strings to deal with input or information that comes from text.

##What are local variables? Why and when would you use them?

Local variables are variables that live inside a specific method or class.

You would use them to keep your code organized and multifunctional. Say you make a
function that adds numbers 'a' and 'b', if these were not local variables you could
not declare an 'a' or 'b' anywhere else in your program without potential corruption.

##How was this challenge? Did you get a good review of some of the basics?

I feel pretty comfortable with all of this stuff. I actually find the reflection
more useful than the challenges since I already have habits and quick reactions for
these tinier assignments, I feel like I get more use out of examining those habits
and also I want to say things in these reviews that I'm not sure of, so it forces
me to re-research things I thought I already knew.

# Release 2 Reflections
>>>>>>> master
##What does puts do?

Puts prints whatever string you give it and then it puts a new line on the back
of it so that it sits on its own. You could also use p or print but they dont
add the new line character. Puts also doesnt return the value you give it,
it simply prints it.

##What is an integer? What is a float?

An integer is a number without decimals at the back and a float is a number with
decimals. Because numbers are stored in bits and bytes, its much easier to store
whole numbers and they are also used more often.

##What is the difference between float and integer division?
How would you explain the difference to someone who doesnt know anything about
programming?

###Integer Division

Integer division always returns a whole number. For example, 15 / 2 will be 7.
If you want the remainder, you can do 15 % (mod) 2 and get 1, and so you can
know that 15/2 is 7R1, just like grade school arithmetic.

###Floating Point Division

Floating Point Division works more like a calculator: it gives you a pretty
exact result. 15/2 would be 7.5 with floating point division.

I would describe the difference to someone who knows nothing about programming
as, basically, do you want a remainder or a decimal from your division? Although
you should keep your ear out for more information on the differences between
floats and integers.

## Ruby Code
```
daysPerYear = 365
hoursPerDay = 24
puts daysPerYear * hoursPerDay
```

```
yearsPerDecade = 10
daysPerYear = 365
hoursPerDay = 24
minutesPerHour = 60
puts yearsPerDecade * daysPerYear * hoursPerDay * minutesPerHour
```


text:
/**
 *
 */

import {quickSort} from '../components/quickSort'
import {quickSort2} from '../components/quickSort2'
import {generateRandomArray, testSort, generateNearlyOrderedArray} from './sortTestHelper'

const n = 10000;

const arr1 = generateRandomArray(n, 0, 5);
const arr2 = arr1.concat();

testSort('Quick Sort', quickSort, arr1);
testSort('Quick Sort2', quickSort2, arr2);

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * @var $this  yii\web\View
 * @var $model jarrus90\User\models\Role
 */
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use kartik\select2\Select2;
use jarrus90\Multilang\Models\Language;
use yii\web\JsExpression;
use yii\helpers\Url;
$this->params['breadcrumbs'][] = $this->title;
?>
<?php $this->beginContent('@jarrus90/Support/views/_adminFaqLayout.php') ?>

<?php
$form = ActiveForm::begin([
            'layout' => 'horizontal',
            'enableAjaxValidation' => true,
            'enableClientValidation' => false,
            'fieldConfig' => [
                'horizontalCssClasses' => [
                    'wrapper' => 'col-sm-9',
                ],
            ],
        ])
?>

<?= $form->field($model, 'lang_code')->widget(Select2::className(), [
    'theme' => 'default',
    'data' => Language::listMap(),
    'pluginEvents' => [
        "change" => "function() { $('#page-category_key').val('').trigger('change'); }",
    ],
    'options' => [
        'placeholder' => Yii::t('support', 'Select language'),
    ],
]);
?>
<?= $form->field($model, 'title') ?>
<?= $form->field($model, 'key') ?>
<?= $form->field($model, 'content')->widget(\jarrus90\Support\Widgets\Redactor::className(), [
    'clientOptions' => [
        'lang' => Yii::$app->language,
        'minHeight' => 200,
        'plugins' => [
            'fontsize',
            'fontcolor',
            'fontfamily',
            'table',
            'counter',
            'fullscreen',
            'imagemanager'
        ],
    ]
])
?>
<?= $form->field($model, 'category_key')->widget(Select2::className(), [
    'theme' => 'default',
    'pluginOptions' => [
        'ajax' => [
            'url' => Url::toRoute('/support/category/list'),
            'dataType' => 'json',
            'delay' => 50,
            'data' => new JsExpression('function(params) { return {lang: $(\'#page-lang_code\').val()}; }')
        ],
        'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
        'templateResult' => new JsExpression('function (procedure) { return procedure.text; }'),
        'templateSelection' => new JsExpression('function (procedure) { return procedure.text; }'),
    ],
    'options' => [
        'placeholder' => Yii::t('support', 'Select category'),
    ],
]);
?>

<?= Html::submitButton(Yii::t('support', 'Save'), ['class' => 'btn btn-success btn-block']) ?>

<?php ActiveForm::end() ?>
<?php $this->endContent() ?>


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.lianzong.logistics.app">

    <!-- Push service 运行需要的权限 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER" />
    <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
    <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />

    <application
        android:name=".LogisticsApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">
        <!-- config -->
        <meta-data
            android:name="cfg_all_module_type"
            android:value="false" /><!--boolean-->
        <meta-data
            android:name="cfg_enable_account"
            android:value="false" /><!--boolean-->
        <meta-data
            android:name="cfg_version"
            android:value="release" /><!--debug/release-->

        <activity
            android:name=".ui.activity.MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@style/MaterialDrawerTheme.Light.DarkToolbar.TranslucentStatus">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".ui.activity.GoodsDetailsActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.Toolbar">
        </activity>

        <activity
            android:name=".ui.activity.GoodListActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.Toolbar">
        </activity>

        <activity
            android:name=".ui.activity.VehicleListActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.Toolbar">
        </activity>

        <activity
            android:name=".ui.activity.AddEditVehicleActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.Toolbar">
        </activity>

        <!-- 功能测试 -->
        <activity
            android:name=".ui.view.pulltorefresh.XListViewActivity"
            android:label="@string/drawer_test_debug_xlistview"
            android:screenOrientation="portrait"
            android:theme="@style/MaterialDrawerTheme.Light.DarkToolbar.TranslucentStatus">
        </activity>

        <activity
            android:name=".ui.view.fab.FBMainActivity"
            android:label="@string/app_name"
            android:theme="@style/MaterialDrawerTheme.Light.DarkToolbar.TranslucentStatus">
        </activity>
        <activity
            android:name=".ui.view.fab.FBRecyclerViewActivity"
            android:label="@string/recyclerview_fab_example"
            android:theme="@style/MaterialDrawerTheme.Light.DarkToolbar.TranslucentStatus">
        </activity>
        <activity
            android:name=".ui.view.fab.FBFloatingMenusActivity"
            android:label="@string/floating_action_menu"
            android:theme="@style/MaterialDrawerTheme.Light.DarkToolbar.TranslucentStatus">
        </activity>

        <!-- Baidu Yun Push start-->
        <activity
            android:name="com.lianzong.logistics.app.push.PushDemoActivity"
            android:label="@string/app_name"
            android:launchMode="singleTask"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.wsl" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.lianzong.logistics.app.push.LoginActivity"
            android:configChanges="orientation|keyboardHidden"
            android:label="login" >
        </activity>
        <activity
            android:name="com.lianzong.logistics.app.push.CustomActivity"
            android:configChanges="orientation|keyboardHidden"
            android:launchMode="singleTask" >
        </activity>

        <!-- push富媒体,不使用富媒体推送不需要 -->
        <activity
            android:name="com.baidu.android.pushservice.richmedia.MediaViewActivity"
            android:configChanges="orientation|keyboardHidden"
            android:label="MediaViewActivity" >
        </activity>
        <activity
            android:name="com.baidu.android.pushservice.richmedia.MediaListActivity"
            android:configChanges="orientation|keyboardHidden"
            android:label="MediaListActivity"
            android:launchMode="singleTask" >
        </activity>
        <!-- push富媒体结束 -->

        <!-- push应用定义消息receiver声明 -->
        <receiver android:name="com.lianzong.logistics.app.push.MyPushMessageReceiver" >
            <intent-filter>

                <!-- 接收push消息 -->
                <action android:name="com.baidu.android.pushservice.action.MESSAGE" />
                <!-- 接收bind,unbind,fetch,delete等反馈消息 -->
                <action android:name="com.baidu.android.pushservice.action.RECEIVE" />
                <action android:name="com.baidu.android.pushservice.action.notification.CLICK" />
            </intent-filter>
        </receiver>

        <!-- push必须的receviver和service声明 -->
        <receiver
            android:name="com.baidu.android.pushservice.PushServiceReceiver"
            android:process=":bdservice_v1" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="com.baidu.android.pushservice.action.notification.SHOW" />
                <action android:name="com.baidu.android.pushservice.action.media.CLICK" />
                <!-- 以下四项为可选的action声明,可大大提高service存活率和消息到达速度 -->
                <action android:name="android.intent.action.MEDIA_MOUNTED" />
                <action android:name="android.intent.action.USER_PRESENT" />
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
            </intent-filter>
        </receiver>
        <receiver
            android:name="com.baidu.android.pushservice.RegistrationReceiver"
            android:process=":bdservice_v1" >
            <intent-filter>
                <action android:name="com.baidu.android.pushservice.action.METHOD" />
                <action android:name="com.baidu.android.pushservice.action.BIND_SYNC" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_REMOVED" />

                <data android:scheme="package" />
            </intent-filter>
        </receiver>

        <service
            android:name="com.baidu.android.pushservice.PushService"
            android:exported="true"
            android:process=":bdservice_v1" >
            <intent-filter>
                <action android:name="com.baidu.android.pushservice.action.PUSH_SERVICE" />
            </intent-filter>
        </service>
        <service
            android:name="com.baidu.android.pushservice.CommandService"
            android:exported="true" />
        <!-- push结束 -->

        <!-- 在百度开发者中心查询应用的API Key -->
        <meta-data
            android:name="api_key"
            android:value="pnLVGRWxwSysboGN5qFLToI3" />
    </application>

</manifest>


text:
package org.cloudbus.cloudsim.container.lists;

import org.cloudbus.cloudsim.container.core.ContainerVm;
import org.cloudbus.cloudsim.core.CloudSim;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by sareh on 28/07/15.
 */
public class PowerContainerVmList extends ContainerVmList {

        /**
         * Sort by cpu utilization.
         *
         * @param vmList the vm list
         */
        public static <T extends ContainerVm> void sortByCpuUtilization(List<T> vmList) {
            Collections.sort(vmList, new Comparator<T>() {

                @Override
                public int compare(T a, T b) throws ClassCastException {
                    Double aUtilization = a.getTotalUtilizationOfCpuMips(CloudSim.clock());
                    Double bUtilization = b.getTotalUtilizationOfCpuMips(CloudSim.clock());
                    return bUtilization.compareTo(aUtilization);
                }
            });
        }

    }


text:
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os"

	"github.com/tidwall/gjson"
)

var src = "./files/"
var custom = "./custom/"
var dst = "/files"

var out = "./list.json"

// Result is a single geojson search result
type Result struct {
	Name string `json:"name"`
	ID   string `json:"id"`
	Tag  string `json:"tag"`
}

func main() {
	files, err := ioutil.ReadDir(src)
	if err != nil {
		panic(err)
	}
	custom, err := ioutil.ReadDir(custom)
	if err != nil {
		panic(err)
	}
	files = append(files, custom...)

	var results []Result
	for _, f := range files {
		file, err := os.Open(fmt.Sprintf("%s/%s", src, f.Name()))
		if err != nil {
			log.Fatal(err)
		}
		defer file.Close()
		buf, _ := ioutil.ReadAll(file)
		str := string(buf)
		name := gjson.Get(str, "properties.name").String()
		id := gjson.Get(str, "properties.id").String()
		tag := gjson.Get(str, "properties.type").String()

		res := Result{
			Name: name,
			ID:   id,
			Tag:  tag,
		}
		results = append(results, res)
	}

	wr, _ := json.Marshal(results)
	_ = ioutil.WriteFile(out, wr, 0644)
}


text:
'use strict';

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

// Server & DB config
const port = process.env.PORT || 31337;
const databaseURI = 'mongodb://localhost/registry';

// Express setup
const app = express();
const router = express.Router();

// Body Parser setup
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

// Mongoose setup
const registry = mongoose.connect(databaseURI);

registry.connection.on('error', console.error.bind(console, 'Error connecting to registry database:'));
registry.connection.once('open', console.log.bind(console, 'Connection to registry database was successful!'));

// Mongoose models
const ComponentSet = require('./db/models/component-set');

// Routes
router.route('/sets/search/:name')
	.get((req, res) => {
		ComponentSet.find({'name': req.params.name}, 'location', (err, componentSet) => {
			if(err) res.send(err);
			res.json(componentSet);
		});
	});

router.route('/sets')
	.get((req, res) => {
		ComponentSet.find((err, componentSets) => {
			if(err) res.send(err);
			res.json(componentSets);
		});
	})
	.post(function(req, res) {
		// Create set
		let componentSet = new ComponentSet();

		// Assign our values
		componentSet.name = req.body.name;
		componentSet.type = req.body.type;
		componentSet.location = req.body.location;
		componentSet.owner = req.body.owner;
		componentSet.description = req.body.description;

		// And finally, save
		componentSet.save(err => {
			if(err) res.send(err);
			res.json(componentSet);
		});
	});

router.route('/sets/:set_id')
	.get((req, res) => {
		ComponentSet.findById(req.params.set_id, (err, componentSet) => {
			if(err) res.send(err);
			res.json(componentSet);
		});
	})
	.put((req, res) => {
		ComponentSet.findById(req.params.set_id, (err, componentSet) => {
			if(err) res.send(err);

			// Update values
			componentSet.name = req.body.name;
			componentSet.type = req.body.type;
			componentSet.location = req.body.location;
			componentSet.owner = req.body.owner;
			componentSet.description = req.body.description;

			// And save again
			componentSet.save(err => {
				if(err) res.send(err);
				res.json(componentSet);
			});
		});
	})
	.delete((req, res) => {
		ComponentSet.remove({
			_id: req.params.set_id
		}, (err, response) => {
			if(err) res.send(err);
			res.json(response);
		});
	});

router.get('/', (req, res) => {
	res.json({
		welcome: 'to the periodic registry'
	});
});

app.use('/registry', router);

// Bind and listen
app.listen(port, () => {
	console.log('Server started and listening at http://localhost:%s', port);
});


text:
//
//  RootTabbarController.m
//  MobileFramework
//
//  Created by 刘博 on 14-6-3.
//  Copyright (c) 2014年 wt. All rights reserved.
//

#import "RootTabbarController.h"
#import "WebController.h"
#import "SetController.h"
@interface RootTabbarController ()

@end

@implementation RootTabbarController

@synthesize roleArr,dataPerse_delegate;

/**
 *  初始化
 *
 *  @param arr 节点结合
 *
 *  @return self
 */
-(id)initWithArr:(NSArray *)arr
{
    self = [super init];
    if (self)
    {
        self.roleArr = arr;
        self.dataPerse_delegate = CLASS_ALLOC(DATA_PERSE_BO);
        [self createHeader];
        [self createView];
        [self createController];
    }
    return self;
}

/**
 *  加载View
 */
-(void)loadView
{
    [super loadView];
    self.tabBar.hidden = YES;
    self.moreNavigationController.navigationBar.hidden = YES;
}

/**
 *  创建自定义bar
 */
-(void)createView
{

}

/**
 *  创建ViewController
 */
-(void)createController
{
    NSMutableArray *controllers = [[NSMutableArray alloc] init];
    for (int i = 0; i < self.roleArr.count; i++)
    {
        NodeVO *vo = [self.roleArr objectAtIndex:i];
        if (vo.index >=0)
        {
            if ([vo.name isEqualToString:@"设置"])
            {
                SetController *setController = [[SetController alloc] init];
                setController.nodeVO = vo;
                setController.web_delegate = self;
                [controllers addObject:setController];
            }
            else
            {
                WebController *webController = [[WebController alloc] init];
                webController.web_delegate = self;
                webController.nodeVO = vo;
                [controllers addObject:webController];

            }
        }
    }
    self.viewControllers = controllers;
}

#pragma mark - WebControllerDelegate
/**
 *  退回到rootcontroller
 */
-(void)toRootController
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

/**
 *  左按钮点击
 */
-(void)leftBtnClick
{

}

#pragma mark - TabViewDelegate
/**
 *  选择下一级
 *
 *  @param vo
 */
-(void)cellClick:(NodeVO *)vo
{

}

/**
 *  返回上一级
 */
-(void)forward
{

}

@end


text:
from data import getStock_A, getStock_C
from featureGeneration import addFeatures
from machineLearning import Classify
from preprocess import Prep
from CV import CV
from performance import Portfolio, MarketIntradayPortfolio
import pandas as pd
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from pylab import *
from datetime import datetime

HS300 = getStock_C('000300')
SP500 = getStock_A('^GSPC')
HS300 = addFeatures(HS300)
SP500 = addFeatures(SP500)
HS300.drop('ADOSC', axis=1)
X_train, y_train, X_test, y_test = Prep(HS300)
Classify(X_train, y_train, X_test, y_test, 'RF')
CV(X_train, y_train, 9, 'RF')
clf = LDA()
y_pred = clf.fit(X_train, y_train).predict(X_test)
symbol = 'CSI300'
start_test = datetime(2014,1,1)
end_period = datetime(2015,9,29)
bars = HS300[['Open','AdjClose']]

bars = bars[start_test:end_period]

signals = pd.DataFrame(index=bars.index)
signals['signal'] = 0.0
signals['signal'] = y_pred
#Short the stock
signals.signal[signals.signal == 0] = -1

# positions change
signals['positions'] = signals['signal'].diff()

pf = MarketIntradayPortfolio(symbol, bars, signals)

returns = pf.backtest_portfolio()

# Plot results
f, ax = plt.subplots(2, sharex=True)
f.patch.set_facecolor('white')
ylabel = symbol + ' Close Price in RMB'
bars['AdjClose'].plot(ax=ax[0], color='r', lw=3.)
ax[0].set_ylabel(ylabel, fontsize=18)
ax[0].set_xlabel('', fontsize=18)
ax[0].set_ylim([0,6000])
ax[0].legend(('Close Price of CSI300',), loc='upper left', prop={"size":18})
ax[0].set_title('CSI300 Close Price VS Portofolio Performance (1 January 2014 - 29 September 2015)', fontsize=20, fontweight="bold")
returns['total'].plot(ax=ax[1], color='b', lw=3.)
ax[1].set_ylabel('Portfolio value in RMB', fontsize=18)
ax[1].set_xlabel('Date', fontsize=18)
ax[1].legend(('Portofolio Performance. Capital Invested: 100k RMB. Shares Traded per day: 500+500',), loc='upper left', prop={"size":18})
plt.tick_params(axis='both', which='major', labelsize=14)
loc = ax[1].xaxis.get_major_locator()
loc.maxticks[DAILY] = 24
plt.show()


text:
import pygame
import pygame.locals
from pygame.locals import *

class GameWorld(object):
    windowWidth = 600
    windowHeight = 600
    backgroundColor = (254, 184, 188)
    fps = 40
    keepRunning = True
    gameClock = None
    windowSurface = None

    mousedownCallbacks = None
    keydownCallbacks = None
    #
    # This will end up being the list of participants in our little
    # petri dish.
    worldObjects = None

    def __init__(self):
        self.gameClock = pygame.time.Clock()
        self.windowSurface = pygame.display.set_mode((self.windowWidth, self.windowHeight))

        self.mousedownCallbacks = []
        self.keydownCallbacks = []

        # Create our object list.
        self.worldObjects = []

    def addcallback(self, event, callback):
        if hasattr(self, event+"Callbacks"):
            getattr(self, event+"Callbacks").append(callback)

    def removecallback(self, event, callback):
        if hasattr(self, event+"Callbacks"):
            getattr(self, event+"Callbacks").remove(callback)

    # This will add an object to the gameworld.
    def addobj(self, obj):
        # NOTE: We might want to check if the object exists first, but for
        # our simple example, we should only ever be adding objects that
        # don't yet exist in our world.
        self.worldObjects.append(obj)

    # For when we want to remove an object. (Food gets eaten, blob dies, etc.)
    def removeobj(self, obj):
        self.worldObjects.remove(obj)

    def run(self):
        while self.keepRunning:

            for event in pygame.event.get():
                if event.type == QUIT:
                    self.keepRunning = False

                if event.type == MOUSEBUTTONDOWN:
                    for callback in self.mousedownCallbacks:
                        callback(gameworld=self, event=event)

                if event.type == KEYDOWN:
                    for callback in self.keydownCallbacks:
                        callback(gameworld=self, event=event)

            self.windowSurface.fill(self.backgroundColor)

            # Loop through all objects in the game world and draw them.
            for obj in self.worldObjects:
                # We'll be over cautious and check to see if the object
                # has a draw item on it.
                if hasattr(obj, "draw"):
                    # We need to give the object access to gameworld.
                    obj.draw(self)

            pygame.display.update()

            self.gameClock.tick(self.fps)


text:
<!DOCTYPE html>

<meta charset="UTF-8">

<title>class EpicGeo::Writers::HTML::ArchiveMaker - RDoc Documentation</title>

<link href="../../../fonts.css" rel="stylesheet">
<link href="../../../rdoc.css" rel="stylesheet">

    Home

    Pages
    Classes
    Methods

  <form action="#" method="get" accept-charset="utf-8">

      <input id="search-field" role="combobox" aria-label="Search"
             aria-autocomplete="list" aria-controls="search-results"
             type="text" name="search" placeholder="Search" spellcheck="false"
             title="Type to search, Up and Down to navigate, Enter to load">

  </form>

Parent

Object

Methods

::new

#add_style

#add_user_page

#write_index

    class EpicGeo::Writers::HTML::ArchiveMaker

Public Class Methods

          new(dir_name, dir_path='./')

          click to toggle source

Initialize an Archive with a path and a name.

# File lib/epic_geo/writers/html/archive_maker.rb, line 19
def initialize(dir_name, dir_path='./')
        @directory_name = dir_name
        @dir_path = dir_path+dir_name
        @css_path = @dir_path+'/css'

        unless Dir.exists? @dir_path
                Dir.mkdir @dir_path
        end

        unless Dir.exists? @css_path
                Dir.mkdir @css_path
        end

        #This will be an array of hashes for the nav table:
        # => [{:name=> name, :file=>filename.html},..]
        @dir_contents = []
end

Public Instance Methods

          add_style(style="styles.css")

          click to toggle source

# File lib/epic_geo/writers/html/archive_maker.rb, line 73
def add_style(style="styles.css")
        src = File.dirname(__FILE__) + "/templates/css/styles.css"
        FileUtils.cp(src, @css_path)
end

          add_user_page(user, contents, kml=nil)

          click to toggle source

# File lib/epic_geo/writers/html/archive_maker.rb, line 37
def add_user_page(user, contents, kml=nil)
        this_file = EpicGeo::Writers::HTML::UserPage.new(user+'.html', @dir_path)

        @dir_contents << {:name=>user, :file=>this_file.filename}

        if kml
                kml_scripts=["https://www.google.com/jsapi"]
        end
        this_file.write_header(
                user,
                styles=["css/styles.css"],
                scripts=kml_scripts
        )
        this_file.add_home_button
        this_file.h1 user
        unless kml.nil?
                this_file.write_link("KML File", kml)
                this_file.add_google_earth(kml)
        end

        this_file.add_content(contents)

        this_file.write_footer
end

          write_index()

          click to toggle source

# File lib/epic_geo/writers/html/archive_maker.rb, line 62
def write_index
        index = EpicGeo::Writers::HTML::Homepage.new(@dir_path)
        index.write_header("Users to Code", styles=["css/styles.css"], scripts=[])
        index.h1 "Users to Code"
        index.p "The full contextual streams for these users along with small interactive maps of their storm migration activities is available under the links to the left."

        index.write_navigation(@dir_contents)

        index.write_footer
end

Validate

Generated by RDoc 4.1.1.

Based on Darkfish by Michael Granger.


text:
package sfix.msgcodec.message.codec;

import io.netty.buffer.ByteBuf;

/**
 * Specification for a MessageSerializer, which should take a message type and return a netty ByteBuf object.
 */
public interface MessageSerializer {

    /**
     * Encode a message and return a ByteBuf instance with its contents.
     *
     * @param message The message type this MessageSerializer was created for.
     * @return The encoded message.
     */
    ByteBuf serialize(Object message);
}


text:
package entitlements

import (
	"context"

	"github.com/containerd/containerd/containers"
	"github.com/containerd/containerd/oci"
	specs "github.com/opencontainers/runtime-spec/specs-go"
)

// WithInsecureSpec sets spec with All capability.
func WithInsecureSpec() oci.SpecOpts {
	return func(_ context.Context, _ oci.Client, _ *containers.Container, s *specs.Spec) error {
		addCaps := []string{
			"CAP_FSETID",
			"CAP_KILL",
			"CAP_FOWNER",
			"CAP_MKNOD",
			"CAP_CHOWN",
			"CAP_DAC_OVERRIDE",
			"CAP_NET_RAW",
			"CAP_SETGID",
			"CAP_SETUID",
			"CAP_SETPCAP",
			"CAP_SETFCAP",
			"CAP_NET_BIND_SERVICE",
			"CAP_SYS_CHROOT",
			"CAP_AUDIT_WRITE",
			"CAP_MAC_ADMIN",
			"CAP_MAC_OVERRIDE",
			"CAP_DAC_READ_SEARCH",
			"CAP_SYS_PTRACE",
			"CAP_SYS_MODULE",
			"CAP_SYSLOG",
			"CAP_SYS_RAWIO",
			"CAP_SYS_ADMIN",
			"CAP_LINUX_IMMUTABLE",
			"CAP_SYS_BOOT",
			"CAP_SYS_NICE",
			"CAP_SYS_PACCT",
			"CAP_SYS_TTY_CONFIG",
			"CAP_SYS_TIME",
			"CAP_WAKE_ALARM",
			"CAP_AUDIT_READ",
			"CAP_AUDIT_CONTROL",
			"CAP_SYS_RESOURCE",
			"CAP_BLOCK_SUSPEND",
			"CAP_IPC_LOCK",
			"CAP_IPC_OWNER",
			"CAP_LEASE",
			"CAP_NET_ADMIN",
			"CAP_NET_BROADCAST",
		}
		for _, cap := range addCaps {
			s.Process.Capabilities.Bounding = append(s.Process.Capabilities.Bounding, cap)
			s.Process.Capabilities.Ambient = append(s.Process.Capabilities.Ambient, cap)
			s.Process.Capabilities.Effective = append(s.Process.Capabilities.Effective, cap)
			s.Process.Capabilities.Inheritable = append(s.Process.Capabilities.Inheritable, cap)
			s.Process.Capabilities.Permitted = append(s.Process.Capabilities.Permitted, cap)
		}
		s.Linux.ReadonlyPaths = []string{}
		s.Linux.MaskedPaths = []string{}
		s.Process.ApparmorProfile = ""

		return nil
	}
}


text:
// <copyright  file="Chart.cs" company="Balloons-Pop-5">
// All rights reserved.
// </copyright>
// <author>DimitarSD, alexizvely, fr0wsTyl</author>

namespace BalloonsPop.Game
{
    using System;
    using System.Collections.Generic;
    using BalloonsPop.Console.ConsoleIO;
    using BalloonsPop.Console.ConsoleIO.Reader;

    /// <summary>
    /// creates instance of the chart for scoreboard
    /// </summary>
    public class Chart
    {
        /// <summary>
        /// takes the current user points, sorts them with the top 5 user points form before and writes only the best 5 back in the file
        /// </summary>
        /// <param name="spentMoves">takes int value of how many moves the user has made before wining</param>
        public static void SortAndPrintChartFive(int spentMoves)
        {
            var consoleInut = new Reader().ReadUserInput();
            var userName = new Reader().ReadUsername();
            var currentScore = new Highscore(userName, spentMoves); // get current score
            var scores = GetHighScoresFromFile(); // read from file
            var results = new List<Highscore>();
            foreach (var item in scores)
            {
                results.Add(ScoreParser(item));
            } // add old highscores
            results.Add(currentScore); // add current score to highscores
            results.Sort((x1, x2) => x1.Value.CompareTo(x2.Value)); // sort score

            if (results.Count == Common.Constants.GlobalGameLogicDependencesValues.TopChartLength + 1)
            {
                results.RemoveAt(Common.Constants.GlobalGameLogicDependencesValues.TopChartLength);
            } // remove the last score from the sorted highscore list
            SaveToFile(results); // save to file
        }

        /// <summary>
        /// takes old highscores from file
        /// </summary>
        private static IEnumerable<string> GetHighScoresFromFile()
        {
            string[] scores = System.IO.File.ReadAllLines("../../Game/HighScore.txt");
            return scores;
        }

        /// <summary>
        /// parses the score-username string
        /// </summary>
        /// <param name="scoreText">string representing one line form the scoreboard file</param>
        private static Highscore ScoreParser(string scoreText)
        {
            string[] temp = scoreText.Split('\t');
            return new Highscore(temp[0], int.Parse(temp[1]));
        }

        /// <summary>
        /// saves scores to file
        /// </summary>
        /// <param name="tempScore">the latets sorted highscore list</param>
        private static void SaveToFile(List<Highscore> tempScore)
        {
            List<string> output = new List<string>();

            foreach (var item in tempScore)
            {
                output.Add(item.ToString());
                Console.WriteLine(item.ToString());
            }

            System.IO.File.WriteAllLines("../../Game/HighScore.txt", output.ToArray());
        }
    }
}


text:
class AddAuthorToContra < ActiveRecord::Migration
  def change
    add_column :contras, :author_id, :integer
    remove_column :contras, :author, :string
  end
end


text:
package de.katzenpapst.amunra.entity.ai;

import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.ai.EntityAIBase;
import net.minecraft.entity.player.EntityPlayer;

public class AIFollowClosest extends EntityAIBase {

    private EntityLiving theWatcher;
    /** The closest entity which is being watched by this one. */
    protected Entity closestEntity;
    /** This is the Maximum distance that the AI will look for the Entity */
    private float maxDistanceForPlayer;
    private int lookTime;
    private float someProbability;
    private Class watchedClass;
    protected float minDistance;

    public AIFollowClosest(EntityLiving user, Class classToFollow, float maxDistance, float minDistance)
    {
        this.theWatcher = user;
        this.watchedClass = classToFollow;
        this.maxDistanceForPlayer = maxDistance;
        this.someProbability = 0.02F;
        this.setMutexBits(2);
    }

    public AIFollowClosest(EntityLiving user, Class classToFollow, float maxDistance, float minDistance, float probability)
    {
        this.theWatcher = user;
        this.watchedClass = classToFollow;
        this.maxDistanceForPlayer = maxDistance;
        this.someProbability = probability;
        this.setMutexBits(2);
    }

    /**
     * Returns whether the EntityAIBase should begin execution.
     */
    @Override
    public boolean shouldExecute()
    {
        if (this.theWatcher.getRNG().nextFloat() >= this.someProbability)
        {
            return false;
        }
        else
        {
            if (this.theWatcher.getAttackTarget() != null)
            {
                this.closestEntity = this.theWatcher.getAttackTarget();
            }

            if (this.watchedClass == EntityPlayer.class)
            {
                this.closestEntity = this.theWatcher.worldObj.getClosestPlayerToEntity(this.theWatcher, (double)this.maxDistanceForPlayer);
            }
            else
            {
                this.closestEntity = this.theWatcher.worldObj.findNearestEntityWithinAABB(this.watchedClass, this.theWatcher.boundingBox.expand((double)this.maxDistanceForPlayer, 3.0D, (double)this.maxDistanceForPlayer), this.theWatcher);
            }

            return this.closestEntity != null;
        }
    }

    /**
     * Returns whether an in-progress EntityAIBase should continue executing
     */
    @Override
    public boolean continueExecuting()
    {
        return !this.closestEntity.isEntityAlive()
                ?
                        false
                :
                    (this.theWatcher.getDistanceSqToEntity(this.closestEntity) > (double)(this.maxDistanceForPlayer * this.maxDistanceForPlayer)
                            ?
                                    false
                            :
                                this.lookTime > 0
                    );
    }

    /**
     * Execute a one shot task or start executing a continuous task
     */
    @Override
    public void startExecuting()
    {
        this.lookTime = 40 + this.theWatcher.getRNG().nextInt(40);
    }

    /**
     * Resets the task
     */
    @Override
    public void resetTask()
    {
        this.closestEntity = null;
    }

    /**
     * Updates the task
     */
    @Override
    public void updateTask()
    {
        this.theWatcher.getLookHelper().setLookPosition(
                this.closestEntity.posX,
                this.closestEntity.posY + (double)this.closestEntity.getEyeHeight(),
                this.closestEntity.posZ, 10.0F,
                (float)this.theWatcher.getVerticalFaceSpeed()
        );
        --this.lookTime;
    }

}


text:
package org.apache.activemq.artemis.core.io.util;

import java.nio.ByteBuffer;

/**
 * Object Pool that allows to borrow and release {@link ByteBuffer}s according to a specific type (direct/heap).

 * The suggested usage pattern is:
 *
{@code
 *    ByteBuffer buffer = pool.borrow(size);
 *    //...using buffer...
 *    pool.release(buffer);
 * }

 */
public interface ByteBufferPool {

   /**
    * It returns a {@link ByteBuffer} with {@link ByteBuffer#capacity()}>={@code size}.

    * The {@code buffer} is zeroed until {@code size} if {@code zeroed=true}, with {@link ByteBuffer#position()}=0 and {@link ByteBuffer#limit()}={@code size}.
    */
   ByteBuffer borrow(int size, boolean zeroed);

   /**
    * It pools or free {@code buffer} that cannot be used anymore.

    * If {@code buffer} is of a type different from the one that the pool can borrow, it will ignore it.
    */
   void release(ByteBuffer buffer);

   /**
    * Factory method that creates a thread-local pool of capacity 1 of {@link ByteBuffer}s of the specified type (direct/heap).
    */
   static ByteBufferPool threadLocal(boolean direct) {
      return new ThreadLocalByteBufferPool(direct);
   }

}


text:
using FishKing.Entities;
using FishKing.Managers;
using FlatRedBall.Glue.StateInterpolation;
using Microsoft.Xna.Framework.Audio;
using StateInterpolationPlugin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static FishKing.Enums.WaterTypes;

namespace FishKing.GumRuntimes
{
    public partial class FishCatchingInterfaceRuntime
    {
        SoundEffectInstance underwaterSound;
        public bool HasAttachedFish { get { return FramedCatchingBackgroundInstance.AttachedFish != null; } }
        public bool FishHasEscaped { get { return FramedCatchingBackgroundInstance.FishHasEscaped; } }
        public bool LineHasSnapped { get { return FishingLineStatusInstance.LineHasSnapped;  } }
        public bool FishIsCaught { get { return (
#if DEBUG
                DebuggingVariables.ImmediatelyCatchFish ||
#endif
                FramedCatchingBackgroundInstance.IsFishCaught); } }

        partial void CustomInitialize()
        {
            underwaterSound = GlobalContent.UnderwaterSound.CreateInstance();
            underwaterSound.IsLooped = true;
            underwaterSound.Volume = 0.25f * OptionsManager.Options.SoundEffectsVolume;
        }

        public void AttachFish(Fish fish, WaterType waterType)
        {
            Reset();
            FramedCatchingBackgroundInstance.AttachFish(fish);
            FramedCatchingBackgroundInstance.SetBackgroundFrom(waterType);
        }

        public void Update()
        {
            if (Visible)
            {
                if (underwaterSound.State != SoundState.Playing)
                {
                    underwaterSound.Play();
                }
                SpinningReelInstance.Update();
                FishingLineStatusInstance.Update();

                if (FishingLineStatusInstance.LineHasSnapped)
                {
                    FramedCatchingBackgroundInstance.LineHasSnapped = true;
                }
                else
                {
                    FramedCatchingBackgroundInstance.CurrentReelSpeed = SpinningReelInstance.ReelSpeed;
                }
                FramedCatchingBackgroundInstance.Update();

                if (LineHasSnapped || FishIsCaught)
                {
                    SpinningReelInstance.Stop();
                }
#if DEBUG
                if (DebuggingVariables.FishShouldImmediatelyEscape) FishingLineStatusInstance.LineStress = 200;
#endif
            }
            else
            {
                Stop();
            }
        }

        public void RaiseAlignmentBar(float percentPressure = 1f)
        {
            FramedCatchingBackgroundInstance.RaiseAlignmentBar(percentPressure);
        }

        public void SpinReel(float percentPressure = 1f)
        {
            if (!LineHasSnapped && !FishIsCaught)
            {
                if (FramedCatchingBackgroundInstance.IsAligned)
                {
                    SpinningReelInstance.SpinReel(percentPressure);
                }
                else
                {
                    SpinningReelInstance.JamReel();
                    FishingLineStatusInstance.IncreaseStress();
                }
            }
        }

        public void Reset()
        {
            FishingLineStatusInstance.Reset();
            FramedCatchingBackgroundInstance.Reset();
            SpinningReelInstance.Reset();
        }

        public void Stop()
        {
            SpinningReelInstance.Stop();
            underwaterSound.Stop();
        }
    }
}


text:
<?php

namespace libraries\shared;

use models\shared\rights\SiteRoles;
use models\shared\rights\SystemRoles;
use models\ProjectModel;
use models\UserModel;

class AuthHelper
{
    // return status
    const LOGIN_FAIL = 'loginFail';
    const LOGIN_FAIL_USER_UNAUTHORIZED = 'loginFailUserUnauthorized';
    const LOGIN_SUCCESS = 'loginSuccess';

    private $_ion_auth;

    private $_session;

    public function __construct($ion_auth, $session)
    {
        $this->_ion_auth = $ion_auth;
        $this->_session = $session;
    }

    /**
     *
     * @param string $identity
     * @param string $password
     * @param Website $website
     * @param bool $remember
     */
    public function login($website, $identity, $password, $remember = false)
    {
        if ($this->_ion_auth->login($identity, $password, $remember)) {

            // successful login
            $this->_session->set_flashdata('message', $this->_ion_auth->messages());

            $user = new UserModel((string) $this->_session->userdata('user_id'));

            // Validate user is admin or has a role on the site.  Otherwise, redirect to logout
            if (($user->role == SystemRoles::SYSTEM_ADMIN) ||
                    ($user->siteRole->offsetExists($website->domain) &&
                    ($user->siteRole[$website->domain] != SiteRoles::NONE))) {
                // set the project context to user's default project
                $projectId = $user->getDefaultProjectId($website->domain);

                if ($projectId) {
                    $this->_session->set_userdata('projectId', $projectId);
                }

                $referer = $this->_session->userdata('referer_url');
                if ($referer && strpos($referer, "/app") !== false) {
                    $this->_session->unset_userdata('referer_url');

                    return static::result(self::LOGIN_SUCCESS, $referer, 'location');
                } elseif ($projectId) {
                    $project = ProjectModel::getById($projectId);
                    $url = "/app/" . $project->appName . "/$projectId";

                    return static::result(self::LOGIN_SUCCESS, $website->baseUrl() . $url, 'location');
                } else {
                    return static::result(self::LOGIN_SUCCESS, $website->baseUrl() . '/', 'location');
                }
            } else {
                //log out with error msg
                $logout = $this->_ion_auth->logout();
                $this->_session->set_flashdata('message', 'You are not authorized to use this site');

                return static::result(self::LOGIN_FAIL_USER_UNAUTHORIZED, '/auth/login', 'refresh');
            }
        } else {
            //if the login was un-successful
            //redirect them back to the login page
            $this->_session->set_flashdata('message', $this->_ion_auth->errors());

            return static::result(self::LOGIN_FAIL, '/auth/login', 'refresh');
        }
    }

    public function logout()
    {
        $this->_ion_auth->logout();
    }

    /**
     * @param string $status
     * @param string $uri
     * @param string $method
     */
    public static function result($status, $uri, $method = 'location')
    {
        return array(
            'status' => $status,
            'redirect' => array(
                'url' => $uri,
                'method' => $method
            )
        );
    }

}


text:
<!DOCTYPE html>

   	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
	<meta name="Content-Type" content="UTF-8">
	<meta name="Content-Language" content="fr">
	<meta name="description" content="Portfolio de Sylvain Guillot • Développeur web, Web Designer, Infographiste & Présent en Haute-Savoie & Annecy & Grenoble & Lyon." />
	<meta name="keywords" content="Sylain, Guillot, Portfolio, Webdesigner, Web, Designer, Infographiste, Annecy, Haute, Savoie, Grenoble, Rhône-Alpes, Créer, Site, Internet, Typographie, Illustration" />
	<meta name="Author" content="Sylvain Guillot">
	<meta name="Publisher" content="Sylvain Guillot">
	<meta name="Identifier-Url" content="www.sylvainguillot.com">
	<meta name="Robots" content="all">
	<meta name="Rating" content="general">
	<meta name="Distribution" content="global">
	<meta name="Category" content="internet">

<title>Sylvain Guillot • Web designer, Développeur Web & Infographiste en Haute-Savoie & Annecy & Grenoble & Lyon </title>

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

    <title>Sylvain Guillot</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="mobiletest.css" rel="stylesheet">
	<link rel="Stylesheet" type="text/css" href="css/animations.css" />

    <link href="font-awesome-4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href='http://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

	<link href="fonts/opificio_neue-regular-webfont.ttf" rel='stylesheet' type='text/css'>
	<link href="fonts/opificio_neue-regular-webfont.svg" rel='stylesheet' type='text/css'>
	<link href="fonts/opificio_neue-regular-webfont.eot" rel='stylesheet' type='text/css'>
	<link href="fonts/opificio_neue-regular-webfont.woff" rel='stylesheet' type='text/css'>

			Menu

Accueil

Services

Réalisations

A Propos

Contact


text:
package org.mycontroller.standalone.api.jaxrs;

import static javax.ws.rs.core.MediaType.APPLICATION_JSON;

import java.util.HashMap;
import java.util.List;

import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.mycontroller.standalone.api.jaxrs.mapper.Query;
import org.mycontroller.standalone.api.jaxrs.mapper.QueryResponse;
import org.mycontroller.standalone.api.jaxrs.utils.RestUtils;
import org.mycontroller.standalone.db.DaoUtils;
import org.mycontroller.standalone.db.tables.Firmware;
import org.mycontroller.standalone.db.tables.FirmwareType;
import org.mycontroller.standalone.db.tables.FirmwareVersion;
import org.mycontroller.standalone.mysensors.firmware.FirmwareUtils;

/**
 * @author Jeeva Kandasamy (jkandasa)
 * @since 0.0.1
 */

@Path("/rest/firmwares")
@Produces(APPLICATION_JSON)
@Consumes(APPLICATION_JSON)
@RolesAllowed({ "admin" })
public class FirmwareHandler {

    //Firmware type handler
    @GET
    @Path("/types")
    public Response getAllFirmwareTypes(
            @QueryParam(FirmwareType.KEY_NAME) List<String> name,
            @QueryParam(Query.PAGE_LIMIT) Long pageLimit,
            @QueryParam(Query.PAGE) Long page,
            @QueryParam(Query.ORDER_BY) String orderBy,
            @QueryParam(Query.ORDER) String order) {
        HashMap<String, Object> filters = new HashMap<String, Object>();

        filters.put(FirmwareType.KEY_NAME, name);

        QueryResponse queryResponse = DaoUtils.getFirmwareTypeDao().getAll(
                Query.builder()
                        .order(order != null ? order : Query.ORDER_ASC)
                        .orderBy(orderBy != null ? orderBy : FirmwareType.KEY_ID)
                        .filters(filters)
                        .pageLimit(pageLimit != null ? pageLimit : Query.MAX_ITEMS_PER_PAGE)
                        .page(page != null ? page : 1l)
                        .build());
        return RestUtils.getResponse(Status.OK, queryResponse);
    }

    @GET
    @Path("/types/{id}")
    public Response getFirmwareType(@PathParam("id") int id) {
        return RestUtils.getResponse(Status.OK, DaoUtils.getFirmwareTypeDao().getById(id));
    }

    @PUT
    @Path("/types")
    public Response updateFirmwareType(FirmwareType firmwareType) {
        DaoUtils.getFirmwareTypeDao().update(firmwareType);
        return RestUtils.getResponse(Status.OK);
    }

    @POST
    @Path("/types")
    public Response createFirmwareType(FirmwareType firmwareType) {
        DaoUtils.getFirmwareTypeDao().create(firmwareType);
        return RestUtils.getResponse(Status.CREATED);
    }

    @POST
    @Path("/types/delete")
    public Response deleteFirmwareType(List<Integer> ids) {
        for (Integer id : ids) {
            FirmwareUtils.deleteFirmwareType(id);
        }
        return RestUtils.getResponse(Status.OK);
    }

    //Firmware version handler

    @GET
    @Path("/versions")
    public Response getAllFirmwareVersions(
            @QueryParam(FirmwareVersion.KEY_VERSION) List<String> version,
            @QueryParam(Query.PAGE_LIMIT) Long pageLimit,
            @QueryParam(Query.PAGE) Long page,
            @QueryParam(Query.ORDER_BY) String orderBy,
            @QueryParam(Query.ORDER) String order) {
        HashMap<String, Object> filters = new HashMap<String, Object>();

        filters.put(FirmwareVersion.KEY_VERSION, version);

        QueryResponse queryResponse = DaoUtils.getFirmwareVersionDao().getAll(
                Query.builder()
                        .order(order != null ? order : Query.ORDER_ASC)
                        .orderBy(orderBy != null ? orderBy : FirmwareVersion.KEY_ID)
                        .filters(filters)
                        .pageLimit(pageLimit != null ? pageLimit : Query.MAX_ITEMS_PER_PAGE)
                        .page(page != null ? page : 1l)
                        .build());
        return RestUtils.getResponse(Status.OK, queryResponse);
    }

    @GET
    @Path("/versions/{id}")
    public Response getFirmwareVersion(@PathParam("id") int id) {
        return RestUtils.getResponse(Status.OK, DaoUtils.getFirmwareVersionDao().getById(id));
    }

    @PUT
    @Path("/versions")
    public Response updateFirmwareVersion(FirmwareVersion firmwareVersion) {
        DaoUtils.getFirmwareVersionDao().update(firmwareVersion);
        return RestUtils.getResponse(Status.OK);
    }

    @POST
    @Path("/versions")
    public Response createFirmwareVersion(FirmwareVersion firmwareVersion) {
        DaoUtils.getFirmwareVersionDao().create(firmwareVersion);
        return RestUtils.getResponse(Status.CREATED);
    }

    @POST
    @Path("/versions/delete")
    public Response deleteFirmwareVersion(List<Integer> ids) {
        for (Integer id : ids) {
            FirmwareUtils.deleteFirmwareVersion(id);
        }
        return RestUtils.getResponse(Status.OK);
    }

    //Firmware handler

    @GET
    @Path("/firmwares")
    public Response getAllFirmwares(
            @QueryParam(Firmware.KEY_TYPE_ID) Integer typeId,
            @QueryParam(Firmware.KEY_VERSION_ID) Integer versionId,
            @QueryParam(Query.PAGE_LIMIT) Long pageLimit,
            @QueryParam(Query.PAGE) Long page,
            @QueryParam(Query.ORDER_BY) String orderBy,
            @QueryParam(Query.ORDER) String order) {
        HashMap<String, Object> filters = new HashMap<String, Object>();

        filters.put(Firmware.KEY_TYPE_ID, typeId);
        filters.put(Firmware.KEY_VERSION_ID, versionId);

        QueryResponse queryResponse = DaoUtils.getFirmwareDao().getAll(
                Query.builder()
                        .order(order != null ? order : Query.ORDER_ASC)
                        .orderBy(orderBy != null ? orderBy : FirmwareVersion.KEY_ID)
                        .filters(filters)
                        .pageLimit(pageLimit != null ? pageLimit : Query.MAX_ITEMS_PER_PAGE)
                        .page(page != null ? page : 1l)
                        .build());
        return RestUtils.getResponse(Status.OK, queryResponse);
    }

    @GET
    @Path("/firmwares/{id}")
    public Response getFirmware(@QueryParam("withData") Boolean withData, @PathParam("id") int id) {
        Firmware firmware = DaoUtils.getFirmwareDao().getById(id);
        if (withData == null || !withData) {
            firmware.setData(null);
        }
        return RestUtils.getResponse(Status.OK, firmware);
    }

    @PUT
    @Path("/firmwares")
    public Response updateFirmware(Firmware firmware) {
        FirmwareUtils.updateFirmwareFromHexString(firmware);
        firmware.setTimestamp(System.currentTimeMillis());
        DaoUtils.getFirmwareDao().update(firmware);
        return RestUtils.getResponse(Status.OK);
    }

    @POST
    @Path("/firmwares")
    public Response createFirmware(Firmware firmware) {
        FirmwareUtils.createFirmware(firmware);
        return RestUtils.getResponse(Status.CREATED);
    }

    @POST
    @Path("/firmwares/delete")
    public Response deleteFirmware(List<Integer> ids) {
        for (Integer id : ids) {
            FirmwareUtils.deleteFirmware(id);
        }
        return RestUtils.getResponse(Status.OK);
    }

}


text:
/* tslint:disable:no-unused-variable */
import {async, ComponentFixture, TestBed} from '@angular/core/testing'
import {By} from '@angular/platform-browser'
import {DebugElement, Component, Input} from '@angular/core'
import {RouterTestingModule} from '@angular/router/testing'

import {DetailComponent} from './detail.component'
import {MockTranslatePipe} from '../../mocks/pipes/mock-translate.pipe'
import {UiInfoIconComponent} from '../ui-info-icon/ui-info-icon.component'
import {UiAddButtonComponent} from '../ui-add-button/ui-add-button.component'
import {UiDeleteIconComponent} from '../ui-delete-icon/ui-delete-icon.component'
import {AppActionsService} from '../../app-actions.service'
import {ProjectsActionsService} from '../../application/project/projects-actions.service'
import {AppDispatcherService} from '../../app-dispatcher.service'
import {ProjectsStoreService} from '../../application/project/projects-store.service'
import {AppStoreService} from '../../app-store.service'
import {MockProjectsStoreService} from '../../mocks/application/project/mock-projects-store.service'
import {MockAppStoreService} from '../../mocks/mock-app-store.service'
import {MockProjectsActionsService} from '../../mocks/application/project/mock-projects-actions.service'
import {MockAppActionsService} from '../../mocks/mock-app-actions.service'

@Component({
  selector: 'is-variables',
  template: '',
})
class MockVariablesComponent {
  @Input() observedVariables: any
  @Input() latentVariables: any
}

@Component({
  selector: 'is-models',
  template: '',
})
class MockModelsComponent {
  @Input() covariances: any
  @Input() intercepts: any
  @Input() latentVariableRelations: any
  @Input() regressions: any
}

describe('DetailComponent', () => {
  let component: DetailComponent
  let fixture: ComponentFixture<DetailComponent>

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
      ],
      declarations: [
        DetailComponent,
        MockTranslatePipe,
        MockVariablesComponent,
        MockModelsComponent,
        UiInfoIconComponent,
        UiAddButtonComponent,
        UiDeleteIconComponent
      ],
      providers: [
        {provide: AppActionsService, useClass: MockAppActionsService},
        {provide: ProjectsActionsService, useClass: MockProjectsActionsService},
        AppDispatcherService,
        {provide: ProjectsStoreService, useClass: MockProjectsStoreService},
        {provide: AppStoreService, useClass: MockAppStoreService},
      ]
    })
    .compileComponents()
  }))

  beforeEach(() => {
    fixture = TestBed.createComponent(DetailComponent)
    component = fixture.componentInstance
    fixture.detectChanges()
  })

  it('should create', () => {
    expect(component).toBeTruthy()
  })
})


text:
HTML_AJAX_IframeXHR_instances = new Object();
function HTML_AJAX_IframeXHR()
{
	this._id = 'HAXHR_iframe_' + new Date().getTime();
	HTML_AJAX_IframeXHR_instances[this._id] = this;
}
HTML_AJAX_IframeXHR.prototype = {
// Data not sent with text/xml Content-Type will only be available via the responseText property

	// properties available in safari/mozilla/IE xmlhttprequest object
	onreadystatechange: null, // Event handler for an event that fires at every state change
	readyState: 0, // Object status integer: 0 = uninitialized 1 = loading 2 = loaded 3 = interactive 4 = complete
	responseText: '', // String version of data returned from server process
	responseXML: null, // DOM-compatible document object of data returned from server process
	status: 0, // Numeric code returned by server, such as 404 for "Not Found" or 200 for "OK"
	statusText: '', // String message accompanying the status code
	iframe: true, // flag for iframe

	//these are private properties used internally to keep track of stuff
	_id: null, // iframe id, unique to object(hopefully)
	_url: null, // url sent by open
	_method: null, // get or post
	_async: null, // sync or async sent by open
	_headers: new Object(), //request headers to send, actually sent as form vars
	_response: new Object(), //response headers received
	_phpclass: null, //class to send
	_phpmethod: null, //method to send
	_history: null, // opera has to have history munging

	// Stops the current request
	abort: function()
	{
		var iframe = document.getElementById(this._id);
		if (iframe) {
			document.body.removeChild(iframe);
		}
		if (this._timeout) {
			window.clearTimeout(this._timeout);
		}
		this.readyState = 1;
		if (typeof(this.onreadystatechange) == "function") {
			this.onreadystatechange();
		}
	},

	// This will send all headers in this._response and will include lastModified and contentType if not already set
	getAllResponseHeaders: function()
	{
		var string = '';
		for (i in this._response) {
			string += i + ' : ' + this._response[i] + "\n";
		}
		return string;
	},

	// This will use lastModified and contentType if they're not set
	getResponseHeader: function(header)
	{
		return (this._response[header] ? this._response[header] : null);
	},

	// Assigns a label/value pair to the header to be sent with a request
	setRequestHeader: function(label, value) {
		this._headers[label] = value;
		return; },

	// Assigns destination URL, method, and other optional attributes of a pending request
	open: function(method, url, async, username, password)
	{
		if (!document.body) {
			throw('CANNOT_OPEN_SEND_IN_DOCUMENT_HEAD');
		}
		//exceptions for not enough arguments
		if (!method || !url) {
			throw('NOT_ENOUGH_ARGUMENTS:METHOD_URL_REQUIRED');
		}
		//get and post are only methods accepted
		this._method = (method.toUpperCase() == 'POST' ? 'POST' : 'GET');
		this._decodeUrl(url);
		this._async = async;
		if(!this._async && document.readyState && !window.opera) {
			throw('IE_DOES_NOT_SUPPORT_SYNC_WITH_IFRAMEXHR');
		}
		//set status to loading and call onreadystatechange
		this.readyState = 1;
		if(typeof(this.onreadystatechange) == "function") {
			this.onreadystatechange();
		}
	},

	// Transmits the request, optionally with postable string or DOM object data
	send: function(content)
	{
		//attempt opera history munging
		if (window.opera) {
			this._history = window.history.length;
		}
		//create a "form" for the contents of the iframe
		var form = '<form method="'
			+ (this._url.indexOf('px=') < 0 ? this._method : 'post')
			+ '" action="' + this._url + '">';
		//tell iframe unwrapper this IS an iframe
		form += '<input name="Iframe_XHR" value="1" />';
		//class and method
		if (this._phpclass != null) {
			form += '<input name="Iframe_XHR_class" value="' + this._phpclass + '" />';
		}
		if (this._phpmethod != null) {
			form += '<input name="Iframe_XHR_method" value="' + this._phpmethod + '" />';
		}
		// fake headers
		for (label in this._headers) {
			form += '<textarea name="Iframe_XHR_headers[]">' + label +':'+ this._headers[label] + '</textarea>';
		}
		// add id
		form += '<textarea name="Iframe_XHR_id">' + this._id + '</textarea>';
		if (content != null && content.length > 0) {
			form += '<textarea name="Iframe_XHR_data">' + content + '</textarea>';
		}
		form += '<input name="Iframe_XHR_HTTP_method" value="' + this._method + '" />';
		form += '<s'+'cript>document.forms[0].submit();</s'+'cript></form>';
		form = "javascript:document.write('" + form.replace(/\'/g,"\\'") + "');void(0);";
		this.readyState = 2;
		if (typeof(this.onreadystatechange) == "function") {
			this.onreadystatechange();
		}
		// try to create an iframe with createElement and append node
		try {
			var iframe = document.createElement('iframe');
			iframe.id = this._id;
			// display: none will fail on some browsers
			iframe.style.visibility = 'hidden';
			// for old browsers with crappy css
			iframe.style.border = '0';
			iframe.style.width = '0';
			iframe.style.height = '0';

			if (document.all) {
				// MSIE, opera
				iframe.src = form;
				document.body.appendChild(iframe);
			} else {
				document.body.appendChild(iframe);
				iframe.src = form;
			}
		} catch(exception) {
			// dom failed, write the sucker manually
			var html = '';
			document.body.innerHTML += html;
		}
		if (this._async == true) {
			//avoid race state if onload is called first
			if (this.readyState < 3) {
				this.readyState = 3;
				if(typeof(this.onreadystatechange) == "function") {
					this.onreadystatechange();
				}
			}
		} else {
			//we force a while loop for sync, it's ugly but hopefully it works
			while (this.readyState != 4) {
				//just check to see if we can up readyState
				if (this.readyState < 3) {
					this.readyState = 3;
					if(typeof(this.onreadystatechange) == "function") {
						this.onreadystatechange();
					}
				}
			}
		}
	},

	// attached as an onload function to the iframe to trigger when we're done
	isLoaded: function(headers, data)
	{
		this.readyState = 4;
		//set responseText, Status, StatusText
		this.status = 200;
		this.statusText = 'OK';
		this.responseText = data;
		this._response = headers;
		if (!this._response['Last-Modified']) {
			string += 'Last-Modified : ' + document.getElementById(this._id).lastModified + "\n";
		}
		if (!this._response['Content-Type']) {
			string += 'Content-Type : ' + document.getElementById(this._id).contentType + "\n";
		}
		// if this is xml populate responseXML accordingly
		if (this._response['Content-Type'] == 'application/xml')
		{
			return new DOMParser().parseFromString(this.responseText, 'application/xml');
		}
		//attempt opera history munging in opera 8+ - this is a REGRESSION IN OPERA
		if (window.opera && window.opera.version) {
			//go back current history - old history
			window.history.go(this._history - window.history.length);
		}
		if (typeof(this.onreadystatechange) == "function") {
			this.onreadystatechange();
		}
		document.body.removeChild(document.getElementById(this._id));
	},

	// strip off the c and m from the url send...yuck
	_decodeUrl: function(querystring)
	{
		//opera 7 is too stupid to do a relative url...go figure
		var url = unescape(location.href);
		url = url.substring(0, url.lastIndexOf("/") + 1);
		var item = querystring.split('?');
		//rip off any path info and append to path above <-  relative paths (../) WILL screw this
		this._url = url + item[0].substring(item[0].lastIndexOf("/") + 1,item[0].length);
		if(item[1]) {
			item = item[1].split('&');
			for (i in item) {
				var v = item[i].split('=');
				if (v[0] == 'c') {
					this._phpclass = v[1];
				} else if (v[0] == 'm') {
					this._phpmethod = v[1];
				}
			}
		}
		if (!this._phpclass || !this._phpmethod) {
			var cloc = window.location.href;
			this._url = cloc + (cloc.indexOf('?') >= 0 ? '&' : '?') + 'px=' + escape(HTML_AJAX_Util.absoluteURL(querystring));
		}
	}
}


text:
<md-toolbar class="md-table-toolbar md-default" ng-show="!options.rowSelection || !selected.length">

    Statistiques

    <md-button class="md-icon-button" ng-click="loadStuff()">
      <md-icon>refresh</md-icon>
    </md-button>
    <md-button class="md-icon-button">
      <md-icon>filter_list</md-icon>
    </md-button>
    <md-button class="md-icon-button">
      <md-icon>more_vert</md-icon>
    </md-button>

</md-toolbar>

<md-toolbar class="md-table-toolbar alternate" ng-show="options.rowSelection && selected.length">

    {{selected.length}} {{selected.length > 1 ? 'lignes sélectionnées' : 'ligne sélectionnée'}}

    <md-button class="md-icon-button">
      <md-icon>delete</md-icon>
    </md-button>

</md-toolbar>

<md-table-container>

        Collaborateur
        Email
        Sms

        {{stat.name}}
        {{stat.email}}
        {{stat.sms}}

</md-table-container>

<data-md-table-pagination md-limit="query.limit" md-limit-options="limitOptions" md-page="query.page" md-total="{{stats.count}}" md-on-paginate="onPaginate" md-page-select="options.pageSelect" md-boundary-links="options.boundaryLinks"></data-md-table-pagination>


text:
module Backend
  class InterfaceParamsController < ApplicationController
    before_action :set_interface_param, only: [:edit, :update, :destroy]
    before_action :find_interface, only: [:create]

    include ApplicationHelper

    def index
      q = params[:q]
      p = params[:page]
      if !q.blank?
        @interface_params = InterfaceParam.page(p).where(interface_id: params[:interface_id]).name_like(params[:q])
      else
        @interface_params = InterfaceParam.page(p).where(interface_id: params[:interface_id])
      end
    end

    def new
      @interface_param = InterfaceParam.new
    end

    def edit
    end

    def create
      @interface_param = @interface.interface_params.set_attribute interface_param_params
      respond_to do |format|
        if @interface_param.save
          format.html { redirect_to backend_interface_interface_params_url + append_param(params[:group_id]), notice: '新增成功!' }
        else
          format.html { render :new }
        end
      end
    end

    def update
      respond_to do |format|
        if @interface_param.update(interface_param_params)
          format.html { redirect_to backend_interface_interface_params_url+ append_param(params[:group_id]), notice: '修改成功!' }
        else
          format.html { render :edit }
        end
      end
    end

    def destroy
      InterfaceParam.delete(@interface_param)
      respond_to do |format|
        format.html { redirect_to backend_interface_interface_params_url+ append_param(params[:group_id]), notice: '删除成功!' }
      end
    end

    private
      def find_interface
        @interface = Interface.find(params[:interface_id])
      end
      def set_interface_param
        @interface_param = InterfaceParam.find(params[:id])
      end
      def interface_param_params
        params.require(:interface_param).permit(:param_name, :param_type, :param_must, :param_desc)
      end
  end
end


text:
namespace OpenQA.Selenite.Interfaces
{
    public interface IAlertDialog : IBlock
    {
        string Text { get; }

        TResult Accept<TResult>() where TResult : IBlock;

        TResult Dismiss<TResult>() where TResult : IBlock;

        IAlertDialog EnterText(string text);
    }
}


text:
require 'psych/helper'

module Psych
  module Visitors
    class TestEmitter < TestCase
      def setup
        super
        @io = StringIO.new
        @visitor = Visitors::Emitter.new @io
      end

      def test_options
        io = StringIO.new
        visitor = Visitors::Emitter.new io, :indentation => 3

        s       = Nodes::Stream.new
        doc     = Nodes::Document.new
        mapping = Nodes::Mapping.new
        m2      = Nodes::Mapping.new
        m2.children << Nodes::Scalar.new('a')
        m2.children << Nodes::Scalar.new('b')

        mapping.children << Nodes::Scalar.new('key')
        mapping.children << m2
        doc.children << mapping
        s.children << doc

        visitor.accept s
        assert_match(/^[ ]{3}a/, io.string)
      end

      def test_stream
        s = Nodes::Stream.new
        @visitor.accept s
        assert_equal '', @io.string
      end

      def test_document
        s       = Nodes::Stream.new
        doc     = Nodes::Document.new [1,1]
        scalar  = Nodes::Scalar.new 'hello world'

        doc.children << scalar
        s.children << doc

        @visitor.accept s

        assert_match(/1.1/, @io.string)
        assert_equal @io.string, s.yaml
      end

      def test_document_implicit_end
        s       = Nodes::Stream.new
        doc     = Nodes::Document.new
        mapping = Nodes::Mapping.new
        mapping.children << Nodes::Scalar.new('key')
        mapping.children << Nodes::Scalar.new('value')
        doc.children << mapping
        s.children << doc

        @visitor.accept s

        assert_match(/key: value/, @io.string)
        assert_equal @io.string, s.yaml
        assert(/\.\.\./ !~ s.yaml)
      end

      def test_scalar
        s       = Nodes::Stream.new
        doc     = Nodes::Document.new
        scalar  = Nodes::Scalar.new 'hello world'

        doc.children << scalar
        s.children << doc

        @visitor.accept s

        assert_match(/hello/, @io.string)
        assert_equal @io.string, s.yaml
      end

      def test_scalar_with_tag
        s       = Nodes::Stream.new
        doc     = Nodes::Document.new
        scalar  = Nodes::Scalar.new 'hello world', nil, '!str', false, false, 5

        doc.children << scalar
        s.children << doc

        @visitor.accept s

        assert_match(/str/, @io.string)
        assert_match(/hello/, @io.string)
        assert_equal @io.string, s.yaml
      end

      def test_sequence
        s       = Nodes::Stream.new
        doc     = Nodes::Document.new
        scalar  = Nodes::Scalar.new 'hello world'
        seq     = Nodes::Sequence.new

        seq.children << scalar
        doc.children << seq
        s.children << doc

        @visitor.accept s

        assert_match(/- hello/, @io.string)
        assert_equal @io.string, s.yaml
      end

      def test_mapping
        s       = Nodes::Stream.new
        doc     = Nodes::Document.new
        mapping = Nodes::Mapping.new
        mapping.children << Nodes::Scalar.new('key')
        mapping.children << Nodes::Scalar.new('value')
        doc.children << mapping
        s.children << doc

        @visitor.accept s

        assert_match(/key: value/, @io.string)
        assert_equal @io.string, s.yaml
      end

      def test_alias
        s       = Nodes::Stream.new
        doc     = Nodes::Document.new
        mapping = Nodes::Mapping.new
        mapping.children << Nodes::Scalar.new('key', 'A')
        mapping.children << Nodes::Alias.new('A')
        doc.children << mapping
        s.children << doc

        @visitor.accept s

        assert_match(/&A key: \*A/, @io.string)
        assert_equal @io.string, s.yaml
      end
    end
  end
end


text:
from django.shortcuts import render, get_object_or_404
from .models import Promotor, PracticasProductivas, EscalaPruebas
from empresas.models import Empresas, MejoraEmpresas, TipoEmpresa, TemasEmpresa, Mercados
from politicas.models import EspacioInnovacion, IniciativaInnovacion, TipoEspacio, \
                             PapelSimas, TipoIniciativa
from fortalecimiento.models import MediosFortalecimiento, TiposMedios
from servicios.models import Servicios, TiposServicio
from .forms import PromotorForm, PracticaForm
import json
from django.http import HttpResponse

def inicio(request, template="inicio.html"):
    choice_zonas=((1, 'Seca'),(2, 'Alta'),(3, 'Húmeda'),)
    promotores = Promotor.objects.count()
    #salidas graficos promotores por sexo
    h_promotor = Promotor.objects.filter(sexo=1).count()
    m_promotor = Promotor.objects.filter(sexo=2).count()
    #salidas graficos promotor por zona
    seca = Promotor.objects.filter(zona=1).count()
    alta = Promotor.objects.filter(zona=2).count()
    humeda = Promotor.objects.filter(zona=3).count()
    #salidas grafico de practicas
    practicas = PracticasProductivas.objects.count()

    #practicas por escala
    escala = []
    for obj in EscalaPruebas.objects.all():
        escala.append([obj.nombre,PracticasProductivas.objects.filter(escala_prueba=obj).count()])
    #numero de practicas por años
    years = []
    for en in PracticasProductivas.objects.order_by('anio').values_list('anio', flat=True):
        years.append(en)
    lista_years = list(set(years))
    numero_practica = []
    for year in lista_years:
        a = PracticasProductivas.objects.filter(anio=year).count()
        numero_practica.append([year,a])

    #salidas graficas sobre empresas
    empresas = Empresas.objects.count()
    #conteo de tipos de empresas registradas
    tipo_empresas = []
    for obj in TipoEmpresa.objects.all():
        tipo_empresas.append([obj.nombre,Empresas.objects.filter(tipo=obj).count()])
    #conteo de las empresas por zonas
    lista_empresas_zonas = []
    for obj in choice_zonas:
        lista_empresas_zonas.append([str(obj[1]), Empresas.objects.filter(zona=obj[0]).count()])

    #graficos de las mejoras de las empresas
    mejoras_empresa = MejoraEmpresas.objects.count()
    #grafica de los temas de mejoras en las empresas
    lista_mejora_empresa = []
    for obj in TemasEmpresa.objects.all():
        lista_mejora_empresa.append([obj.nombre,
                                    MejoraEmpresas.objects.filter(tema_prueba=obj).count()])

    #grafico de los mercados de las pruebas sobre mejora de las empresas
    lista_mercados = []
    for obj in Mercados.objects.all():
        lista_mercados.append([obj.nombre,
                               MejoraEmpresas.objects.filter(mercado_prueba=obj).count()])

    #graficos de los espacios
    espacios = EspacioInnovacion.objects.count()
    #graficos de tipos de espacios
    lista_espacios = []
    for obj in TipoEspacio.objects.all():
        lista_espacios.append([obj.nombre,
                             EspacioInnovacion.objects.filter(tipos=obj).count()])
    #grafico de papel de simas
    lista_papel_simas = []
    for obj in PapelSimas.objects.all():
        lista_papel_simas.append([obj.nombre,
                                 EspacioInnovacion.objects.filter(papel=obj).count()])
    #graficos de las iniciativas politicas
    iniciativas = IniciativaInnovacion.objects.count()
    #grafico de tipos de iniciativas
    lista_iniciativas = []
    for obj in TipoIniciativa.objects.all():
        lista_iniciativas.append([obj.nombre,
                                 IniciativaInnovacion.objects.filter(tipo=obj).count()])
    #grafico de numero de iniciativas por años
    lista_years = []
    for en in IniciativaInnovacion.objects.order_by('anio').values_list('anio', flat=True):
        lista_years.append(en)
    iniciativa_years = list(set(lista_years))
    numero_iniciativa = []
    for year in iniciativa_years:
        a = IniciativaInnovacion.objects.filter(anio=year).count()
        numero_iniciativa.append([year,a])

    #graficos de fortalecimiento
    fortalecimientos = MediosFortalecimiento.objects.count()
    tipo_medio = []
    for obj in TiposMedios.objects.all():
        tipo_medio.append([obj.nombre,
                           MediosFortalecimiento.objects.filter(tipo_medio=obj).count()])
    simas_fotalece = []
    for obj in PapelSimas.objects.all():
        simas_fotalece.append([obj.nombre,
                               MediosFortalecimiento.objects.filter(papel_simas=obj).count()])

    #gráficos de los servicios
    servicios = Servicios.objects.count()
    #grafico tipos de servicios
    tipo_servicios = []
    for obj in TiposServicio.objects.all():
        tipo_servicios.append([obj.nombre,
                              Servicios.objects.filter(tipos_servicios=obj).count()])

    #graficos de servicios por año
    servicios_anios = []
    anios = []
    for en in Servicios.objects.order_by('fecha').values_list('fecha', flat=True):
        anios.append(en)
    servicios_anios = list(set(anios))
    numero_servicios = []
    for year in servicios_anios:
        a = Servicios.objects.filter(fecha=year).count()
        numero_servicios.append([year,a])

    return render(request, template, locals())

def _queryset_filtrado(request):
    params = {}
    if request.session['zona']:
        params['zona'] = request.session['zona']
    if request.session['organizacion_civil']:
        params['organizacion_civil__in'] = request.session['organizacion_civil']
    if request.session['sexo']:
        params['sexo'] = request.session['sexo']
    if request.session['activo']:
        params['activo__in'] = request.session['activo']

    unvalid_keys = []
    for key in params:
        if not params[key]:
            unvalid_keys.append(key)

    for key in unvalid_keys:
        del params[key]

    return Promotor.objects.filter(**params)

def promotor_index(request, template="promotor/promotor.html"):
    if request.method == 'POST':
        form = PromotorForm(request.POST)
        if form.is_valid():
            request.session['zona'] = form.cleaned_data['zona']
            request.session['organizacion_civil'] = form.cleaned_data['organizacion_civil']
            request.session['sexo'] = form.cleaned_data['sexo']
            request.session['activo'] = form.cleaned_data['activo']
            request.session['bandera'] = 1
    else:
        form = PromotorForm()
        request.session['bandera'] = 0

    if request.session['bandera'] == 1:
        con = _queryset_filtrado(request)
    else:
        con = ''

    return render(request, template, {'form':form,
                                      'lista_promotor':con})

def promotor_pagina(request, id, template="promotor/ficha_promotor.html"):
    promotor = get_object_or_404(Promotor, id=id)
    return render(request, template, {'promotor':promotor})

def mapa_completo(request):
    if request.is_ajax():
        lista = []
        params = []
        if request.session['bandera'] == 1:
            params = _queryset_filtrado(request)
        else:
            params = Promotor.objects.all()

        for objeto in params:
            dicc = dict(nombre=objeto.nombre,
                        id=objeto.id,
                        identificador=objeto.identificador,
                        lon=float(objeto.gps.longitude) ,
                        lat=float(objeto.gps.latitude),
                        )
            lista.append(dicc)

        serializado = json.dumps(lista)
        return HttpResponse(serializado, mimetype='application/json')

#Esta mapa es el de la pagina principal al inicio del sistema

def mapa_completo_index(request):
    if request.is_ajax():
        lista = []
        for objeto in Promotor.objects.all():
            dicc = dict(nombre=objeto.nombre,
                        id=objeto.id,
                        identificador=objeto.identificador,
                        lon=float(objeto.gps.longitude) ,
                        lat=float(objeto.gps.latitude),
                        )
            lista.append(dicc)
        for obj in Empresas.objects.all():
            dicc = dict(nombre=obj.nombre,
                        id=obj.id,
                        identificador=obj.identificador,
                        lon=float(obj.gps.longitude),
                        lat=float(obj.gps.latitude),
                        )
            lista.append(dicc)

        for obj in EspacioInnovacion.objects.all():
            for objeto in obj.municipios_influye.all():
                dicc = dict(nombre=obj.nombre,
                            id=obj.id,
                            identificador=obj.identificador,
                            lon=float(objeto.longitud),
                            lat=float(objeto.latitud),
                        )
                lista.append(dicc)

        serializado = json.dumps(lista)
        return HttpResponse(serializado, mimetype='application/json')

#parte de la practicas del promotor

def _queryset_filtrado_practica(request):
    params = {}
    if 'zona' in request.session:
        params['promotor__zona'] = request.session['zona']
    if 'anio' in request.session:
        params['anio'] = request.session['anio']
    if 'tema_prueba' in request.session:
        params['tema_prueba'] = request.session['tema_prueba']
    if 'rubro_prueba' in request.session:
        params['rubro_prueba'] = request.session['rubro_prueba']
    if 'escala_prueba' in request.session:
        params['escala_prueba'] = request.session['escala_prueba']

    unvalid_keys = []
    for key in params:
        if not params[key]:
            unvalid_keys.append(key)

    for key in unvalid_keys:
        del params[key]

    return PracticasProductivas.objects.filter(**params)

def practicas_index(request, template="promotor/practica.html"):
    if request.method == 'POST':
        form = PracticaForm(request.POST)
        if form.is_valid():
            request.session['zona'] = form.cleaned_data['zona']
            request.session['anio'] = form.cleaned_data['anio']
            request.session['tema_prueba'] = form.cleaned_data['tema_prueba']
            request.session['rubro_prueba'] = form.cleaned_data['rubro_prueba']
            request.session['escala_prueba'] = form.cleaned_data['escala_prueba']
            request.session['bandera'] = 1
    else:
        form = PracticaForm()
        request.session['bandera'] = 0

    if request.session['bandera'] == 1:
        con = _queryset_filtrado_practica(request)
    else:
        con = ''

    return render(request, template, {'form':form,
                                      'lista_practica':con})

def mapa_completo_practica(request):
    if request.is_ajax():
        lista = []
        params = []
        if request.session['bandera'] == 1:
            params = _queryset_filtrado_practica(request)
        else:
            params = PracticasProductivas.objects.all()

        for objeto in params:
            dicc = dict(nombre=objeto.nombre_prueba,
                        id=objeto.id,
                        lon=float(objeto.promotor.gps.longitude) ,
                        lat=float(objeto.promotor.gps.latitude),
                        )
            lista.append(dicc)

        serializado = json.dumps(lista)
        return HttpResponse(serializado, mimetype='application/json')

def practica_pagina(request, id, template="promotor/ficha_practica.html"):
    practica = get_object_or_404(PracticasProductivas, id=id)
    return render(request, template, {'practica':practica})

    #Cambios elaborados por el equipo de Kronos Code

def gpromotor(request, template="gpromotor.html"):
    choice_zonas=((1, 'Seca'),(2, 'Alta'),(3, 'Húmeda'),)
    promotores = Promotor.objects.count()
    #salidas graficos promotores por sexo
    h_promotor = Promotor.objects.filter(sexo=1).count()
    m_promotor = Promotor.objects.filter(sexo=2).count()
    #salidas graficos promotor por zona
    seca = Promotor.objects.filter(zona=1).count()
    alta = Promotor.objects.filter(zona=2).count()
    humeda = Promotor.objects.filter(zona=3).count()
    #salidas grafico de practicas
    practicas = PracticasProductivas.objects.count()

    #practicas por escala
    escala = []
    for obj in EscalaPruebas.objects.all():
        escala.append([obj.nombre,PracticasProductivas.objects.filter(escala_prueba=obj).count()])
    #numero de practicas por años
    years = []
    for en in PracticasProductivas.objects.order_by('anio').values_list('anio', flat=True):
        years.append(en)
    lista_years = list(set(years))
    numero_practica = []
    for year in lista_years:
        a = PracticasProductivas.objects.filter(anio=year).count()
        numero_practica.append([year,a])
    return render(request,template, locals())

def gempresas(request, template="gempresas.html"):
    choice_zonas=((1, 'Seca'),(2, 'Alta'),(3, 'Húmeda'),)
     #salidas graficas sobre empresas
    empresas = Empresas.objects.count()
    #conteo de tipos de empresas registradas
    tipo_empresas = []
    for obj in TipoEmpresa.objects.all():
        tipo_empresas.append([obj.nombre,Empresas.objects.filter(tipo=obj).count()])
    #conteo de las empresas por zonas
    lista_empresas_zonas = []
    for obj in choice_zonas:
        lista_empresas_zonas.append([str(obj[1]), Empresas.objects.filter(zona=obj[0]).count()])

    #graficos de las mejoras de las empresas
    mejoras_empresa = MejoraEmpresas.objects.count()
    #grafica de los temas de mejoras en las empresas
    lista_mejora_empresa = []
    for obj in TemasEmpresa.objects.all():
        lista_mejora_empresa.append([obj.nombre,
                                    MejoraEmpresas.objects.filter(tema_prueba=obj).count()])

    #grafico de los mercados de las pruebas sobre mejora de las empresas
    lista_mercados = []
    for obj in Mercados.objects.all():
        lista_mercados.append([obj.nombre,
                               MejoraEmpresas.objects.filter(mercado_prueba=obj).count()])
    return render(request, template, locals())

def gespacios(request, template="gespacios.html"):
    choice_zonas=((1, 'Seca'),(2, 'Alta'),(3,'Húmeda'),)
    #graficos de los espacios
    espacios = EspacioInnovacion.objects.count()
    #graficos de tipos de espacios
    lista_espacios = []
    for obj in TipoEspacio.objects.all():
        lista_espacios.append([obj.nombre,
                             EspacioInnovacion.objects.filter(tipos=obj).count()])
    #grafico de papel de simas
    lista_papel_simas = []
    for obj in PapelSimas.objects.all():
        lista_papel_simas.append([obj.nombre,
                                 EspacioInnovacion.objects.filter(papel=obj).count()])
    #graficos de las iniciativas politicas
    iniciativas = IniciativaInnovacion.objects.count()
    #grafico de tipos de iniciativas
    lista_iniciativas = []
    for obj in TipoIniciativa.objects.all():
        lista_iniciativas.append([obj.nombre,
                                 IniciativaInnovacion.objects.filter(tipo=obj).count()])
    #grafico de numero de iniciativas por años
    lista_years = []
    for en in IniciativaInnovacion.objects.order_by('anio').values_list('anio', flat=True):
        lista_years.append(en)
    iniciativa_years = list(set(lista_years))
    numero_iniciativa = []
    for year in iniciativa_years:
        a = IniciativaInnovacion.objects.filter(anio=year).count()
        numero_iniciativa.append([year,a])
    return render(request, template, locals())

def gservicios(request, template="gservicios.html"):
    choice_zonas=((1, 'Seca'),(2, 'Alta'),(3,'Húmeda'),)
    #graficos de fortalecimiento
    fortalecimientos = MediosFortalecimiento.objects.count()
    tipo_medio = []
    for obj in TiposMedios.objects.all():
        tipo_medio.append([obj.nombre,
                           MediosFortalecimiento.objects.filter(tipo_medio=obj).count()])
    simas_fotalece = []
    for obj in PapelSimas.objects.all():
        simas_fotalece.append([obj.nombre,
                               MediosFortalecimiento.objects.filter(papel_simas=obj).count()])

    #gráficos de los servicios
    servicios = Servicios.objects.count()
    #grafico tipos de servicios
    tipo_servicios = []
    for obj in TiposServicio.objects.all():
        tipo_servicios.append([obj.nombre,
                              Servicios.objects.filter(tipos_servicios=obj).count()])

    #graficos de servicios por año
    servicios_anios = []
    anios = []
    for en in Servicios.objects.order_by('fecha').values_list('fecha', flat=True):
        anios.append(en)
    servicios_anios = list(set(anios))
    numero_servicios = []
    for year in servicios_anios:
        a = Servicios.objects.filter(fecha=year).count()
        numero_servicios.append([year,a])

    return render(request, template, locals())

def _queryset_filtrado(request):
    params = {}
    if 'zona' in request.session:
        params['zona'] = request.session['zona']
    if 'organizacion_civil' in request.session:
        params['organizacion_civil__in'] = request.session['organizacion_civil']
    if 'sexo' in request.session:
        params['sexo'] = request.session['sexo']
    if 'activo' in request.session:
        params['activo__in'] = request.session['activo']

    unvalid_keys = []
    for key in params:
        if not params[key]:
            unvalid_keys.append(key)

    for key in unvalid_keys:
        del params[key]

    return Promotor.objects.filter(**params)

def promotor(request, template="promotores.html"):
    if request.method == 'POST':
        form = PromotorForm(request.POST)
        if form.is_valid():
            request.session['zona'] = form.cleaned_data['zona']
            request.session['organizacion_civil'] = form.cleaned_data['organizacion_civil']
            request.session['sexo'] = form.cleaned_data['sexo']
            request.session['activo'] = form.cleaned_data['activo']
            request.session['bandera'] = 1
    else:
        form = PromotorForm()
        request.session['bandera'] = 0

    if request.session['bandera'] == 1:
        con = _queryset_filtrado(request)
    else:
        con = ''

    return render(request, template, {'form':form,
                                      'listar_promotor':con})

def fpromotor(request, id, template="fpromotor.html"):
    fpromotor = get_object_or_404(Promotor, id=id)
    year = request.GET.get('year', None)
    practicas_productivas_queryset = fpromotor.practicasproductivas_set.all()

    if year:
        practicas_productivas_queryset = practicas_productivas_queryset.filter(fecha_prueba__year=year)

    return render(request, template, locals())

def prueba(request, template="prueba.html"):
    if request.method == 'POST':
        form = PracticaForm(request.POST)
        if form.is_valid():
            request.session['zona'] = form.cleaned_data['zona']
            request.session['anio'] = form.cleaned_data['anio']
            request.session['tema_prueba'] = form.cleaned_data['tema_prueba']
            request.session['rubro_prueba'] = form.cleaned_data['rubro_prueba']
            request.session['escala_prueba'] = form.cleaned_data['escala_prueba']
            request.session['bandera'] = 1
    else:
        form = PracticaForm()
        request.session['bandera'] = 0

    if request.session['bandera'] == 1:
        con = _queryset_filtrado_practica(request)
    else:
        con = ''

    return render(request, template, {'form':form,
                                      'listar_prueba':con})

def fprueba(request, id, template="fprueba.html"):
    fprueba = get_object_or_404(PracticasProductivas, id=id)
    return render(request, template, {'fprueba':fprueba})