code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using beRemote.Core.Common.Helper;
using beRemote.Core.Definitions.Classes;
using beRemote.Core.StorageSystem.StorageBase;
namespace beRemote.GUI.Tabs.ManageCredential
{
/// <summary>
/// Interaction logic for ContentTabAbout.xaml
/// </summary>
public partial class TabManageCredential
{
public TabManageCredential()
{
InitializeComponent();
brdChangePassword.Visibility = Visibility.Hidden; //Hide Passwordchangegrid
//Load Credentiallist
List<UserCredential> credentialList = StorageCore.Core.GetUserCredentialsAll();
}
public DataRowView SelectedItem
{
get
{
Console.Beep();
Console.Beep();
return selectedItem;
}
set
{
Console.Beep();
selectedItem = value;
}
}
private DataRowView selectedItem;
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
if (txtDescription.Text.Length == 0)
{
MessageBox.Show("Your have to enter a name of this credential", "Missing data", MessageBoxButton.OK, MessageBoxImage.Stop);
return;
}
//Adding User-Credentials to Database
StorageCore.Core.AddUserCredentials(txtUsername.Text, Helper.EncryptStringToBytes(pbPassword.SecurePassword, Helper.GetHash1(StorageCore.Core.GetUserSalt1()), Encoding.UTF8.GetBytes(StorageCore.Core.GetDatabaseGuid().ToCharArray()), StorageCore.Core.GetUserSalt3()), txtDomain.Text, txtDescription.Text);
//Empty Textboxes
txtUsername.Clear();
txtDomain.Clear();
txtDescription.Clear();
pbPassword.Clear();
//Reload the DataGrid-Content
LoadDataGrid();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
//Load the content of the DataGrid
LoadDataGrid();
}
private List<UserCredentialGridInformation> getGridCredentials()
{
//Load Credentiallist
List<UserCredential> credentialList = StorageCore.Core.GetUserCredentialsAll();
//Information for the DataGrid
List<UserCredentialGridInformation> ret = new List<UserCredentialGridInformation>();
foreach (UserCredential uC in credentialList)
{
UserCredentialGridInformation ucgi = new UserCredentialGridInformation(uC);
if (ucgi.PasswordStatus == "yes")
ucgi.KeyImage = "pack://application:,,,/Images/key16.png";
ret.Add(ucgi);
}
return (ret);
}
private void LoadDataGrid()
{
Binding b = new Binding("") { Mode = BindingMode.OneTime, Source = getGridCredentials() };
dgExisting.SetBinding(DataGrid.ItemsSourceProperty, b);
if (dgExisting.Items.Count > 0)
dgExisting.Columns[getColumnId("Secure")].DisplayIndex = 5;
}
/// <summary>
/// Gets the Id of a Column identified by the columnheader of dgExisting
/// </summary>
/// <param name="columnHeader"></param>
/// <returns></returns>
private int getColumnId(string columnHeader)
{
for (int i = 0; i < dgExisting.Columns.Count; i++)
{
if (dgExisting.Columns[i].Header.ToString() == columnHeader)
return (i);
}
return (0);
}
private void btnDgRemove_Click(object sender, RoutedEventArgs e)
{
UserCredentialGridInformation myRow = (UserCredentialGridInformation)dgExisting.SelectedItem;
StorageCore.Core.DeleteUserCredential(myRow.Id);
LoadDataGrid();
}
private void btnDgChangePassword_Click(object sender, RoutedEventArgs e)
{
brdChangePassword.Margin = new Thickness(Mouse.GetPosition(this).X - 5, Mouse.GetPosition(this).Y - 5, 0, 0);
brdChangePassword.Visibility = Visibility.Visible;
pbChangePassword.Focus();
brdChangePassword.Focus();
//MessageBox.Show(dgExisting.SelectedIndex.ToString());
}
private void pbChangePassword_KeyUp(object sender, KeyEventArgs e)
{
//If Enter is pressed while the Grid was visible
if (e.Key == Key.Enter && brdChangePassword.Visibility == Visibility.Visible)
{
//Hide the grid
brdChangePassword.Visibility = Visibility.Hidden;
//Change the Password
changePassword();
}
}
/// <summary>
/// Changes the Password of a Credential, identified by ID
/// </summary>
private void changePassword()
{
var myRow = (UserCredentialGridInformation)dgExisting.SelectedItem;
//Save the new Password
StorageCore.Core.ModifyUserCredential(myRow.Id,
myRow.Username,
//Helper.GetPasswordHash(pbChangePassword.SecurePassword, StorageCore.Core.GetUserSalt1(), StorageCore.Core.GetUserSalt2()),
Helper.EncryptStringToBytes(
pbChangePassword.SecurePassword,
Helper.GetHash1(StorageCore.Core.GetUserSalt1()),
Encoding.UTF8.GetBytes(StorageCore.Core.GetDatabaseGuid().ToCharArray()),
StorageCore.Core.GetUserSalt3()),
myRow.Domain,
StorageCore.Core.GetUserId(),
myRow.Description);
//Clear Password-Box
pbChangePassword.Clear();
}
/// <summary>
/// Modifies a Credential, except Password, identified by ID
/// </summary>
private void modifyCredentials(string Columnname, string newValue)
{
UserCredentialGridInformation myRow = (UserCredentialGridInformation)dgExisting.SelectedItem;
Columnname = Columnname.ToLower();
//Save the new Usercredentials
StorageCore.Core.ModifyUserCredential(myRow.Id,
(Columnname == "username" ? newValue : myRow.Username),
(Columnname == "domain" ? newValue : myRow.Domain),
StorageCore.Core.GetUserId(),
(Columnname == "description" ? newValue : myRow.Description));
//Reload the DataGrid to get the Data consistent
//LoadDataGrid();
}
private void brdChangePassword_MouseMove(object sender, MouseEventArgs e)
{
//Hide the ChangePassword-Dialog if the mouse moved out of the Dialog-Area
if (Mouse.GetPosition(brdChangePassword).X > brdChangePassword.Width ||
Mouse.GetPosition(brdChangePassword).X < 0 ||
Mouse.GetPosition(brdChangePassword).Y > brdChangePassword.Height ||
Mouse.GetPosition(brdChangePassword).Y < 0)
{
brdChangePassword.Visibility = Visibility.Hidden;
}
}
private void btnChangePasswordClear(object sender, RoutedEventArgs e)
{
//Hide the grid
brdChangePassword.Visibility = Visibility.Hidden;
//Clear the PasswordField (because: Empty password)
pbChangePassword.Clear();
//change the Password
changePassword();
//Reload the grid to update the images
LoadDataGrid();
}
private void dgExisting_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
TextBox t = e.EditingElement as TextBox;
if (t != null)
{
string value = t.Text;
modifyCredentials(e.Column.Header.ToString(), value);
}
}
private void dgExisting_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
//Hide some columns
if (e.Column.Header.ToString() == "Id" ||
e.Column.Header.ToString() == "Password" ||
e.Column.Header.ToString() == "Owner" ||
e.Column.Header.ToString() == "PasswordStatus" ||
e.Column.Header.ToString() == "KeyImage")
e.Column.Visibility = Visibility.Hidden;
}
public override void Dispose()
{
base.Dispose();
SelectedItem = null;
}
}
}
|
Hunv/beRemote
|
GUI/v2/beRemote.GUI/Tabs/ManageCredential/TabManageCredential.xaml.cs
|
C#
|
mit
| 9,045
|
function animate() {
tail = tabCube.pop();
tail.position.x = tabCube[0].position.x;
tail.position.y = tabCube[0].position.y;
tail.position.z = tabCube[0].position.z;
if(direction[0] == 1) {
if(tabCube[0].position.x == (largeur*9)) {
tail.position.x = -(largeur*10);
} else {
tail.position.x += largeur;
}
}
if(direction[1] == 1) {
if(tabCube[0].position.y == (largeur*9)) {
tail.position.y = -(largeur*10);
} else {
tail.position.y += largeur;
}
}
if(direction[2] == 1) {
if(tabCube[0].position.z == (largeur*9)) {
tail.position.z = -(largeur*10);
} else {
tail.position.z += largeur;
}
}
if(direction[0] == -1) {
if(tabCube[0].position.x == -(largeur*10)) {
tail.position.x = (largeur*9);
} else {
tail.position.x -= largeur;
}
}
if(direction[1] == -1) {
if(tabCube[0].position.y == -(largeur*10)) {
tail.position.y = (largeur*9);
} else {
tail.position.y -= largeur;
}
}
if(direction[2] == -1) {
if(tabCube[0].position.z == -(largeur*10)) {
tail.position.z = (largeur*9);
} else {
tail.position.z -= largeur;
}
}
tabCube.unshift(tail);
if(snakeConfondBonbon()) {
ajoutCubeEnQueue(tail);
positionAleatoireBonbon();
document.getElementById("score").innerHTML++;
} else if(teteConfondSnake(tail)) {
if(confirm("Partie terminée! Recommencer?")) {
location.reload();
} else {
clearInterval(timer);
}
}
renderer.render(scene, camera);
}
function allouerDirection(e) {
/**
* KEYCODE
*
* gauche 37
* haut 38
* droite 39
* bas 40
* W 87
* Z 90
**/
if(e.keyCode == 37) {
if(direction[0] != 1) {
direction = new Array(0,0,0);
direction[0] = -1;
}
}
if(e.keyCode == 38) {
if(direction[1] != -1) {
direction = new Array(0,0,0);
direction[1] = 1;
}
}
if(e.keyCode == 39) {
if(direction[0] != -1) {
direction = new Array(0,0,0);
direction[0] = 1;
}
}
if(e.keyCode == 40) {
if(direction[1] != 1) {
direction = new Array(0,0,0);
direction[1] = -1;
}
}
if(e.keyCode == 87) {
if(direction[2] != -1) {
direction = new Array(0,0,0);
direction[2] = 1;
}
}
if(e.keyCode == 90) {
if(direction[2] != 1) {
direction = new Array(0,0,0);
direction[2] = -1;
}
}
}
function snakeConfondBonbon() {
if(tail.position.x == bonbon.position.x && tail.position.y == bonbon.position.y && tail.position.z == bonbon.position.z) {
return true;
} else {
return false;
}
}
function teteConfondSnake(head) {
for(i = 1; i < tabCube.length; i++) {
if(head.position.x == tabCube[i].position.x && head.position.y == tabCube[i].position.y && head.position.z == tabCube[i].position.z) {
return true;
}
}
return false;
}
function ajoutCubeEnQueue(tail) {
var l = tabCube.length;
tabCube.push(new THREE.Mesh(new THREE.CubeGeometry(largeur, largeur, largeur), new THREE.MeshNormalMaterial({color: 0x0000ff, wireframe: false})) );
tabCube[l].position.x = tail.position.x;
tabCube[l].position.y = tail.position.y;
tabCube[l].position.z = tail.position.z;
scene.add(tabCube[l]);
}
function aleatoire() {
var pos;
if(Math.random() > 0.5) {
pos = Math.floor(Math.random()*10)*largeur;
} else {
pos = -Math.ceil(Math.random()*10)*largeur;
}
return pos;
}
function positionAleatoireBonbon() {
var posX = aleatoire();
var posY = aleatoire();
var posZ = aleatoire();
for(i = 0; i < tabCube.length; i++) {
if(posX == tabCube[i].position.x && posY == tabCube[i].position.y && posZ == tabCube[i].position.z) {
positionAleatoireBonbon();
}
}
bonbon.position.x = posX;
bonbon.position.y = posY;
bonbon.position.z = posZ;
}
|
MajdiH/Academic
|
Projects/3DSnakeGame/public_html/assets/scripts/snake.js
|
JavaScript
|
mit
| 3,683
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CompleteSample.ConsoleHost")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Dev One")]
[assembly: AssemblyProduct("CompleteSample.ConsoleHost")]
[assembly: AssemblyCopyright("Copyright © Dev One 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("180ca7d1-7aa9-44fd-8ae3-30062219db93")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
fvilers/OWIN-Katana
|
CompleteSample/CompleteSample.ConsoleHost/Properties/AssemblyInfo.cs
|
C#
|
mit
| 1,403
|
:- module(util, [
new_database/0,
set_default_username/1, % +Username
set_no_auth/0,
default_user_id/1, % -Id
request_get/2, % +Path, -Dict
request_put/3, % +Path, +DictIn, -DictOut
request_del/2, % +Path, -Dict
request_post/3, % +Path, +DictIn, -DictOut
request_get_content/2, % +Path, -String
is_invalid_data/1 % +Response
]).
/** <module> Test utilities
The module contains utility predicates
for unit/integration testing.
*/
:- use_module(library(http/json)).
:- use_module(library(http/http_open)).
:- use_module(library(http/http_json)).
:- use_module(library(http/http_client)).
:- use_module(library(docstore)).
:- use_module(prolog/bc/bc_data).
:- use_module(prolog/bc/bc_data_user).
:- use_module(prolog/bc/bc_data_comment).
:- use_module(prolog/bc/bc_data_entry).
:- dynamic(default_username/1).
:- dynamic(no_auth/0).
% Recreates the test database.
% This also runs the initial migrations.
new_database:-
bc_data_close,
( exists_file('test.docstore')
-> delete_file('test.docstore')
; true),
bc_data_open('test.docstore'),
retractall(default_username(_)),
asserta(default_username('admin@example.com')),
retractall(no_auth).
% Sets default username.
% Call in the middle of test to
% set the user.
set_default_username(Username):-
retractall(default_username(_)),
asserta(default_username(Username)).
% Disables authentication for API calls.
set_no_auth:-
asserta(no_auth).
% Retrieves the default test user id.
default_user_id(UserId):-
default_username(Username),
ds_find(user, username=Username, [User]),
User.'$id' = UserId.
% Auth key for the test user.
test_auth_key(Key):-
default_username(Username),
ds_find(user, username=Username, [key], [User]),
User.key = Key.
request_get(Path, Dict):-
request_options(Options),
atom_concat('http://localhost:18008', Path, Url),
http_open(Url, Stream, Options),
json_read_dict(Stream, Dict),
close(Stream).
request_post(Path, In, Out):-
request_options(BaseOptions),
Options = [ post(json(In)) | BaseOptions ],
atom_concat('http://localhost:18008', Path, Url),
http_open(Url, Stream, Options),
json_read_dict(Stream, Out),
close(Stream).
request_put(Path, In, Out):-
request_options(BaseOptions),
Options = [ post(json(In)), method(put) | BaseOptions ],
atom_concat('http://localhost:18008', Path, Url),
http_open(Url, Stream, Options),
json_read_dict(Stream, Out),
close(Stream).
request_del(Path, Dict):-
request_options(BaseOptions),
Options = [ method(delete) | BaseOptions ],
atom_concat('http://localhost:18008', Path, Url),
http_open(Url, Stream, Options),
json_read_dict(Stream, Dict),
close(Stream).
request_options(Options):-
( no_auth
-> Options = []
; test_auth_key(Key),
Options = [ request_header('X-Key'=Key) ]).
request_get_content(Path, String):-
atom_concat('http://localhost:18008', Path, Url),
http_open(Url, Stream, [ status_code(_) ]),
read_string(Stream, _, String),
close(Stream).
% FIXME rename to is_response_invalid_data
is_invalid_data(Response):-
Response.status = "error",
sub_string(Response.message, 0, _, _, "Invalid input").
|
kalatestimine/blog-core
|
tests/util/util.pl
|
Perl
|
mit
| 3,341
|
<?php
namespace OG\Account\Test\Domain\Identity\Model;
use OG\Account\Domain\Identity\Model\ReminderCode;
class ReminderCodeTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function it_should_generate_new_codes()
{
$code = ReminderCode::generate();
$this->assertInstanceOf(ReminderCode::class, $code);
}
/**
* @test
*/
public function it_should_generate_valid_hexadecimals()
{
$code = ReminderCode::generate();
$pattern = '/^[a-f0-9]*$/';
$this->assertRegExp($pattern, (string) $code);
}
/**
* @test
*/
public function it_should_create_a_code_from_a_string()
{
$code = ReminderCode::fromString('441750964b8ca7b4b55b7a1f69a15275e7902c39e824d89ecbf674a12e4dd865');
$this->assertInstanceOf(ReminderCode::class, $code);
}
/**
* @test
*/
public function it_should_require_strings()
{
$this->setExpectedException('Assert\AssertionFailedException');
ReminderCode::fromString([]);
}
/**
* @test
*/
public function it_should_require_hexadecimals()
{
$this->setExpectedException('Assert\AssertionFailedException');
ReminderCode::fromString('invalid_hexadecimal_that_is_64_characters_long_aaaaaaaaaaaaaaaaa');
}
/**
* @test
*/
public function it_should_require_valid_code_lengths()
{
$this->setExpectedException('Assert\AssertionFailedException');
ReminderCode::fromString('441750964b8ca7b4b55b7a1f69a15275e7902c39e824d89ecbf674a12e4dd8');
}
/**
* @test
*/
public function it_should_require_valid_code_lengths_2()
{
$this->setExpectedException('Assert\AssertionFailedException');
ReminderCode::fromString('441750964b8ca7b4b55b7a1f69a15275e7902c39e824d89ecbf674a12e4dd86583');
}
/**
* @test
*/
public function it_should_allow_upper_case()
{
$code = ReminderCode::fromString('441750964B8CA7B4B55B7A1F69A15275E7902C39E824D89ECBF674A12E4DD865');
$this->assertEquals('441750964b8ca7b4b55b7a1f69a15275e7902c39e824d89ecbf674a12e4dd865', (string) $code);
}
/**
* @test
*/
public function it_should_return_as_string()
{
$code = ReminderCode::fromString('441750964b8ca7b4b55b7a1f69a15275e7902c39e824d89ecbf674a12e4dd865');
$this->assertEquals('441750964b8ca7b4b55b7a1f69a15275e7902c39e824d89ecbf674a12e4dd865', (string) $code);
$this->assertEquals('441750964b8ca7b4b55b7a1f69a15275e7902c39e824d89ecbf674a12e4dd865', $code->toString());
}
/**
* @test
*/
public function it_should_test_equality()
{
$one = ReminderCode::fromString('441750964b8ca7b4b55b7a1f69a15275e7902c39e824d89ecbf674a12e4dd865');
$two = ReminderCode::fromString('441750964b8ca7b4b55b7a1f69a15275e7902c39e824d89ecbf674a12e4dd865');
$three = ReminderCode::fromString('6e163a22ea8f4deee76d61a7c2f8192c8e5ab1d50741155e0f0b12e335cafa91');
$this->assertTrue($one->equals($two));
$this->assertFalse($one->equals($three));
}
}
|
olsthoorn-group/account-domain
|
tests/Identity/Model/ReminderCodeTest.php
|
PHP
|
mit
| 3,160
|
#include <iostream>
#include <unordered_map>
using namespace std;
class Solution {
public:
int countPrimes(int n) {
int *m = new int[n];
for(int i = 0; i < n; i++) m[i] = 0;
int res = 0;
int i = 2;
while(1) {
for(; m[i] == 1 && i < n; i++);
cout<<i<<endl;
if (i >= n) break;
res += 1;
for(int k = 1; i * k < n; k++) {
m[i * k] = 1;
}
}
delete [] m;
return res;
}
};
int main()
{
Solution s;
cout<<s.countPrimes(4);
return 0;
}
|
Crayzero/LeetCodeProgramming
|
Solutions/Count Primes/main.cpp
|
C++
|
mit
| 602
|
package simulation.eventing;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import controlLayer.eventing.AsynchronousEventReceiver;
import controlLayer.eventing.Event;
/**
* a very simple GUI to receive events. you can specify two arguments on the
* console. the first argument is the port number where to listen for incoming
* events the default port is port 9994.
* @author sawielan
*
*/
public class ListenForEvents extends JFrame implements Observer {
/** default serial version id.
*/
private static final long serialVersionUID = 3277964036504615895L;
/** text area which contains the results */
protected final JTextArea resultTextArea = new JTextArea(40, 40);
/** the default port where to listen to events. */
public static final int DEFAULT_PORT = 9994;
/** the port where to listen for incoming events. */
private int port = -1;
/**
* constructor.
* @param port the port where to listen for events.
*/
public ListenForEvents(int port) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
resultTextArea.setEditable(false);
add(resultTextArea);
setSize(500, 500);
setTitle("EventReceiver: port " + port);
setVisible(true);
this.port = port;
}
/**
* execute the event receiver.
* @throws Exception
*/
public void run() throws Exception {
AsynchronousEventReceiver receiver =
new AsynchronousEventReceiver(port);
new Thread(receiver).start();
int nport = receiver.waitAndGetPort(this);
if (nport == AsynchronousEventReceiver.ERROR_PORT) {
throw new Exception("no free port found!");
}
this.port = nport;
setTitle("EventReceiver: port " + port);
System.err.println("receiver thread started on port: " + port);
}
/**
* receive an update from the observable.
* @param o the observable.
* @param arg the changed argument.
*/
public void update(Observable o, Object arg) {
if (arg instanceof Event) {
Event event = (Event) arg;
// clear the text area...
if (resultTextArea.getText().length() > 65500) {
resultTextArea.setText("");
}
String text = event.toString()
+ resultTextArea.getText();
resultTextArea.setText(text);
}
}
/**
* @param args console arguments.
* @throws Exception something goes wrong...
*/
public static void main(String[] args) throws Exception {
int port = DEFAULT_PORT;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
}
new ListenForEvents(port).run();
}
}
|
andreaskami/homeweb
|
framework_code/src/simulation/eventing/ListenForEvents.java
|
Java
|
mit
| 2,524
|
// --------------------
// toposort extended
// Tests
// --------------------
// modules
var chai = require('chai'),
expect = chai.expect,
toposort = require('../lib/');
// init
chai.config.includeStack = true;
// tests
/* jshint expr: true */
/* global describe, it */
describe('toposort', function() {
it('sorts strings', function() {
var sorted = toposort([
['Ingredient', 'Shop'],
['Food', 'Ingredient']
]);
expect(sorted).to.deep.equal(['Food', 'Ingredient', 'Shop']);
});
it('sorts objects', function() {
var sorted = toposort([
[ { table: 'Ingredient' }, { table: 'Shop' } ],
[ { table: 'Food' }, { table: 'Ingredient' } ]
]);
expect(sorted).to.deep.equal([ { table: 'Food' }, { table: 'Ingredient' }, { table: 'Shop' } ]);
});
it('throws error on cyclic dependency', function() {
expect(function() {
toposort([
[ { table: 'Ingredient' }, { table: 'Shop' } ],
[ { table: 'Food' }, { table: 'Ingredient' } ],
[ { table: 'Shop' }, { table: 'Food' } ]
]);
}).to.throw(toposort.Error, 'Cyclic dependency: {"table":"Food"}');
});
});
describe('toposort.dependents', function() {
it('sorts strings', function() {
var sorted = toposort.dependents([
['Ingredient', 'Shop'],
['Food', 'Ingredient']
]);
expect(sorted).to.deep.equal(['Food', 'Ingredient']);
});
it('sorts objects', function() {
var sorted = toposort.dependents([
[ { table: 'Ingredient' }, { table: 'Shop' } ],
[ { table: 'Food' }, { table: 'Ingredient' } ]
]);
expect(sorted).to.deep.equal([ { table: 'Food' }, { table: 'Ingredient' } ]);
});
it('throws error on cyclic dependency', function() {
expect(function() {
toposort.dependents([
[ { table: 'Ingredient' }, { table: 'Shop' } ],
[ { table: 'Food' }, { table: 'Ingredient' } ],
[ { table: 'Shop' }, { table: 'Food' } ]
]);
}).to.throw(toposort.Error, 'Cyclic dependency: {"table":"Food"}');
});
});
|
overlookmotel/toposort-extended
|
test/all.test.js
|
JavaScript
|
mit
| 1,939
|
<ul class="breadcrumb">
<li><a href="#">Front End Template</a></li>
<li class="active">Home</li>
</ul>
|
Ali-Baba-Tajine/Ali-Baba-Tajine-Jekyll01
|
_includes/abtbreadcrumb.html
|
HTML
|
mit
| 105
|
namespace UCloudSDK.Models
{
/// <summary>
/// 获取防火墙组所绑定资源的外网IP
/// <para>
/// http://docs.ucloud.cn/api/unet/describe_security_group_resource.html
/// </para>
/// </summary>
public partial class DescribeSecurityGroupResourceRequest
{
/// <summary>
/// 默认Action名称
/// </summary>
private string _action = "DescribeSecurityGroupResource";
/// <summary>
/// API名称
/// <para>
/// DescribeSecurityGroupResource
/// </para>
/// </summary>
public string Action
{
get { return _action; }
set { _action = value; }
}
/// <summary>
/// 数据中心
/// <para>
/// 参见 数据中心列表
/// </para>
/// </summary>
public string Region { get; set; }
/// <summary>
/// 防火墙ID
/// </summary>
public string GroupId { get; set; }
/// <summary>
/// 实例化 <see cref="DescribeSecurityGroupResourceRequest" /> 类.
/// </summary>
/// <param name="region">数据中心</param>
/// <param name="groupid">防火墙ID.</param>
public DescribeSecurityGroupResourceRequest(string region, string groupid)
{
Region = region;
GroupId = groupid;
}
}
}
|
icyflash/ucloud-csharp-sdk
|
UCloudSDK/Models/UNet/DescribeSecurityGroupResourceRequest.cs
|
C#
|
mit
| 1,503
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Glimpse.Unity.Sample.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
|
dchaib/Glimpse.Unity
|
sample/Glimpse.Unity.Sample/Controllers/HomeController.cs
|
C#
|
mit
| 589
|
<?php
namespace Worldopole;
class QueryManagerMysqlMonocleAlternate extends QueryManagerMysql
{
public function __construct()
{
parent::__construct();
}
public function __destruct()
{
parent::__destruct();
}
///////////
// Tester
///////////
public function testTotalPokemon()
{
$req = 'SELECT COUNT(*) as total FROM sightings';
$result = $this->mysqli->query($req);
if (!is_object($result)) {
return 1;
} else {
$data = $result->fetch_object();
$total = $data->total;
if (0 == $total) {
return 2;
}
}
return 0;
}
public function testTotalGyms()
{
$req = 'SELECT COUNT(*) as total FROM forts';
$result = $this->mysqli->query($req);
if (!is_object($result)) {
return 1;
} else {
$data = $result->fetch_object();
$total = $data->total;
if (0 == $total) {
return 2;
}
}
return 0;
}
public function testTotalPokestops()
{
$req = 'SELECT COUNT(*) as total FROM pokestops';
$result = $this->mysqli->query($req);
if (!is_object($result)) {
return 1;
} else {
$data = $result->fetch_object();
$total = $data->total;
if (0 == $total) {
return 2;
}
}
return 0;
}
/////////////
// Homepage
/////////////
public function getTotalPokemon()
{
$req = 'SELECT COUNT(*) AS total FROM sightings WHERE expire_timestamp >= UNIX_TIMESTAMP()';
$result = $this->mysqli->query($req);
$data = $result->fetch_object();
return $data;
}
public function getTotalLures()
{
$data = (object) array('total' => 0);
return $data;
}
public function getTotalGyms()
{
$req = 'SELECT COUNT(*) AS total FROM forts';
$result = $this->mysqli->query($req);
$data = $result->fetch_object();
return $data;
}
public function getTotalRaids()
{
$req = 'SELECT COUNT(*) AS total FROM raids WHERE time_battle <= UNIX_TIMESTAMP() AND time_end >= UNIX_TIMESTAMP()';
$result = $this->mysqli->query($req);
$data = $result->fetch_object();
return $data;
}
public function getTotalGymsForTeam($team_id)
{
$req = "SELECT COUNT(*) AS total
FROM forts f
LEFT JOIN fort_sightings fs ON (fs.fort_id = f.id AND fs.last_modified = (SELECT MAX(last_modified) FROM fort_sightings fs2 WHERE fs2.fort_id=f.id))
WHERE team = '$team_id'";
$result = $this->mysqli->query($req);
$data = $result->fetch_object();
return $data;
}
public function getRecentAll()
{
$req = 'SELECT DISTINCT pokemon_id, encounter_id, FROM_UNIXTIME(expire_timestamp) AS disappear_time, FROM_UNIXTIME(updated) AS last_modified, FROM_UNIXTIME(expire_timestamp) AS disappear_time_real,
lat AS latitude, lon AS longitude, cp, atk_iv AS individual_attack, def_iv AS individual_defense, sta_iv AS individual_stamina
FROM sightings
ORDER BY updated DESC
LIMIT 0,12';
$result = $this->mysqli->query($req);
$data = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_object()) {
$data[] = $row;
}
}
return $data;
}
public function getRecentMythic($mythic_pokemon)
{
$req = 'SELECT pokemon_id, encounter_id, FROM_UNIXTIME(expire_timestamp) AS disappear_time, FROM_UNIXTIME(updated) AS last_modified, FROM_UNIXTIME(expire_timestamp) AS disappear_time_real,
lat AS latitude, lon AS longitude, cp, atk_iv AS individual_attack, def_iv AS individual_defense, sta_iv AS individual_stamina
FROM sightings
WHERE pokemon_id IN ('.implode(',', $mythic_pokemon).')
ORDER BY updated DESC
LIMIT 0,12';
$result = $this->mysqli->query($req);
$data = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_object()) {
$data[] = $row;
}
}
return $data;
}
///////////////////
// Single Pokemon
///////////////////
public function getGymsProtectedByPokemon($pokemon_id)
{
$req = "SELECT COUNT(f.id) AS total
FROM forts f
LEFT JOIN fort_sightings fs ON (fs.fort_id = f.id AND fs.last_modified = (SELECT MAX(last_modified) FROM fort_sightings fs2 WHERE fs2.fort_id=f.id))
WHERE guard_pokemon_id = '".$pokemon_id."'";
$result = $this->mysqli->query($req);
$data = $result->fetch_object();
return $data;
}
public function getPokemonLastSeen($pokemon_id)
{
$req = "SELECT FROM_UNIXTIME(expire_timestamp) AS expire_timestamp, FROM_UNIXTIME(expire_timestamp) AS disappear_time_real, lat AS latitude, lon AS longitude
FROM sightings
WHERE pokemon_id = '".$pokemon_id."'
ORDER BY expire_timestamp DESC
LIMIT 0,1";
$result = $this->mysqli->query($req);
$data = $result->fetch_object();
return $data;
}
public function getTop50Pokemon($pokemon_id, $top_order_by, $top_direction)
{
$req = "SELECT FROM_UNIXTIME(expire_timestamp) AS distime, pokemon_id as pokemon_id, FROM_UNIXTIME(expire_timestamp) as disappear_time, lat as latitude, lon as longitude,
cp, atk_iv as individual_attack, def_iv as individual_defense, sta_iv as individual_stamina,
ROUND(100*(atk_iv+def_iv+sta_iv)/45,1) AS IV, move_1 as move_1, move_2, form
FROM sightings
WHERE pokemon_id = '".$pokemon_id."' AND move_1 IS NOT NULL AND move_1 <> '0'
ORDER BY $top_order_by $top_direction, expire_timestamp DESC
LIMIT 0,50";
$result = $this->mysqli->query($req);
$top = array();
while ($data = $result->fetch_object()) {
$top[] = $data;
}
return $top;
}
public function getTop50Trainers($pokemon_id, $best_order_by, $best_direction)
{
$trainer_blacklist = '';
if (!empty(self::$config->system->trainer_blacklist)) {
$trainer_blacklist = " AND owner_name NOT IN ('".implode("','", self::$config->system->trainer_blacklist)."')";
}
$req = "SELECT owner_name as trainer_name, ROUND((100*((atk_iv)+(def_iv)+(sta_iv))/45),1) AS IV, move_1, move_2, cp as cp,
FROM_UNIXTIME(last_modified) AS lasttime, last_modified as last_seen
FROM gym_defenders
WHERE pokemon_id = '".$pokemon_id."'".$trainer_blacklist."
ORDER BY $best_order_by $best_direction, owner_name ASC
LIMIT 0,50";
$result = $this->mysqli->query($req);
$toptrainer = array();
while ($data = $result->fetch_object()) {
$toptrainer[] = $data;
}
return $toptrainer;
}
public function getPokemonHeatmap($pokemon_id, $start, $end)
{
$where = ' WHERE pokemon_id = '.$pokemon_id.' '
."AND FROM_UNIXTIME(expire_timestamp) BETWEEN '".$start."' AND '".$end."'";
$req = 'SELECT lat AS latitude, lon AS longitude FROM sightings'.$where.' LIMIT 100000';
$result = $this->mysqli->query($req);
$points = array();
while ($data = $result->fetch_object()) {
$points[] = $data;
}
return $points;
}
public function getPokemonGraph($pokemon_id)
{
$req = "SELECT COUNT(*) AS total, HOUR(disappear_time) AS disappear_hour
FROM (SELECT FROM_UNIXTIME(expire_timestamp) as disappear_time FROM sightings WHERE pokemon_id = '".$pokemon_id."' LIMIT 100000) AS pokemonFiltered
GROUP BY disappear_hour
ORDER BY disappear_hour";
$result = $this->mysqli->query($req);
$array = array_fill(0, 24, 0);
while ($result && $data = $result->fetch_object()) {
$array[$data->disappear_hour] = $data->total;
}
// shift array because AM/PM starts at 1AM not 0:00
$array[] = $array[0];
array_shift($array);
return $array;
}
public function getPokemonLive($pokemon_id, $ivMin, $ivMax, $inmap_pokemons)
{
$inmap_pkms_filter = '';
$where = ' WHERE expire_timestamp >= UNIX_TIMESTAMP() AND pokemon_id = '.$pokemon_id;
$reqTestIv = 'SELECT MAX(atk_iv) AS iv FROM sightings '.$where;
$resultTestIv = $this->mysqli->query($reqTestIv);
$testIv = $resultTestIv->fetch_object();
if (!is_null($inmap_pokemons) && ('' != $inmap_pokemons)) {
foreach ($inmap_pokemons as $inmap) {
$inmap_pkms_filter .= "'".$inmap."',";
}
$inmap_pkms_filter = rtrim($inmap_pkms_filter, ',');
$where .= ' AND encounter_id NOT IN ('.$inmap_pkms_filter.') ';
}
if (null != $testIv->iv && !is_null($ivMin) && ('' != $ivMin)) {
$where .= ' AND ((100/45)*(atk_iv + def_iv + sta_iv)) >= ('.$ivMin.') ';
}
if (null != $testIv->iv && !is_null($ivMax) && ('' != $ivMax)) {
$where .= ' AND ((100/45)*(atk_iv + def_iv + sta_iv)) <= ('.$ivMax.') ';
}
$req = 'SELECT pokemon_id, lat AS latitude, lon AS longitude,
FROM_UNIXTIME(expire_timestamp) AS disappear_time,
FROM_UNIXTIME(expire_timestamp) AS disappear_time_real,
atk_iv AS individual_attack, def_iv AS individual_defense, sta_iv AS individual_stamina,
move_1, move_2
FROM sightings '.$where.'
LIMIT 5000';
$result = $this->mysqli->query($req);
$spawns = array();
while ($data = $result->fetch_object()) {
$spawns[] = $data;
}
return $spawns;
}
public function getPokemonSliderMinMax()
{
$req = 'SELECT FROM_UNIXTIME(MIN(expire_timestamp)) AS min, FROM_UNIXTIME(MAX(expire_timestamp)) AS max FROM sightings';
$result = $this->mysqli->query($req);
$data = $result->fetch_object();
return $data;
}
public function getMapsCoords()
{
$req = 'SELECT MAX(lat) AS max_latitude, MIN(lat) AS min_latitude, MAX(lon) AS max_longitude, MIN(lon) as min_longitude FROM spawnpoints';
$result = $this->mysqli->query($req);
$data = $result->fetch_object();
return $data;
}
public function getPokemonCount($pokemon_id)
{
$req = 'SELECT count, last_seen, latitude, longitude
FROM pokemon_stats
WHERE pid = '.$pokemon_id;
$result = $this->mysqli->query($req);
$data = $result->fetch_object();
return $data;
}
public function getPokemonCountAll()
{
$req = 'SELECT pid as pokemon_id, count, last_seen, latitude, longitude
FROM pokemon_stats
GROUP BY pid';
$result = $this->mysqli->query($req);
$array = array();
while ($data = $result->fetch_object()) {
$array[] = $data;
}
return $array;
}
public function getRaidCount($pokemon_id)
{
$req = 'SELECT count, last_seen, latitude, longitude
FROM raid_stats
WHERE pid = '.$pokemon_id;
$result = $this->mysqli->query($req);
$data = $result->fetch_object();
return $data;
}
public function getRaidCountAll()
{
$req = 'SELECT pid as pokemon_id, count, last_seen, latitude, longitude
FROM raid_stats
GROUP BY pid';
$result = $this->mysqli->query($req);
$array = array();
while ($data = $result->fetch_object()) {
$array[] = $data;
}
return $array;
}
///////////////
// Pokestops
//////////////
public function getTotalPokestops()
{
$req = 'SELECT COUNT(*) as total FROM pokestops';
$result = $this->mysqli->query($req);
$data = $result->fetch_object();
return $data;
}
public function getAllPokestops()
{
$req = 'SELECT lat as latitude, lon as longitude, null AS lure_expiration, UNIX_TIMESTAMP() AS now, null AS lure_expiration_real FROM pokestops';
$result = $this->mysqli->query($req);
$pokestops = array();
while ($data = $result->fetch_object()) {
$pokestops[] = $data;
}
return $pokestops;
}
/////////
// Gyms
/////////
public function getTeamGuardians($team_id)
{
$req = "SELECT COUNT(*) AS total, guard_pokemon_id
FROM forts f
LEFT JOIN fort_sightings fs ON (fs.fort_id = f.id AND fs.last_modified = (SELECT MAX(last_modified) FROM fort_sightings fs2 WHERE fs2.fort_id=f.id))
WHERE team = '".$team_id."' GROUP BY guard_pokemon_id ORDER BY total DESC LIMIT 0,3";
$result = $this->mysqli->query($req);
$datas = array();
while ($data = $result->fetch_object()) {
$datas[] = $data;
}
return $datas;
}
public function getOwnedAndPoints($team_id)
{
$req = "SELECT COUNT(f.id) AS total, ROUND(AVG(fs.total_cp)) AS average_points
FROM forts f
LEFT JOIN fort_sightings fs ON (fs.fort_id = f.id AND fs.last_modified = (SELECT MAX(last_modified) FROM fort_sightings fs2 WHERE fs2.fort_id=f.id))
WHERE fs.team = '".$team_id."'";
$result = $this->mysqli->query($req);
$data = $result->fetch_object();
return $data;
}
public function getAllGyms()
{
$req = 'SELECT f.id as gym_id, team as team_id, f.lat as latitude, f.lon as longitude, updated as last_scanned, (6 - fs.slots_available) AS level
FROM forts f
LEFT JOIN fort_sightings fs ON (fs.fort_id = f.id AND fs.last_modified = (SELECT MAX(last_modified) FROM fort_sightings fs2 WHERE fs2.fort_id=f.id));';
$result = $this->mysqli->query($req);
$gyms = array();
while ($data = $result->fetch_object()) {
$gyms[] = $data;
}
return $gyms;
}
public function getGymData($gym_id)
{
$req = "SELECT f.name AS name, null AS description, f.url AS url, fs.team AS team, FROM_UNIXTIME(fs.updated) AS last_scanned, fs.guard_pokemon_id AS guard_pokemon_id, (6 - fs.slots_available) AS level, fs.total_cp
FROM forts f
LEFT JOIN fort_sightings fs ON (fs.fort_id = f.id AND fs.last_modified = (SELECT MAX(last_modified) FROM fort_sightings fs2 WHERE fs2.fort_id=f.id))
WHERE f.id ='".$gym_id."'";
$result = $this->mysqli->query($req);
$data = $result->fetch_object();
return $data;
}
public function getGymDefenders($gym_id)
{
$req = "SELECT external_id as pokemon_uid, pokemon_id, atk_iv as iv_attack, def_iv as iv_defense, sta_iv as iv_stamina, cp, fort_id as gym_id
FROM gym_defenders
WHERE fort_id='".$gym_id."'
ORDER BY deployment_time";
$result = $this->mysqli->query($req);
$defenders = array();
while ($data = $result->fetch_object()) {
$defenders[] = $data;
}
return $defenders;
}
///////////
// Raids
///////////
public function getAllRaids($page)
{
$limit = ' LIMIT '.($page * 10).',10';
$req = 'SELECT r.fort_id AS gym_id, r.level AS level, r.pokemon_id AS pokemon_id, r.cp AS cp, r.move_1 AS move_1, r.move_2 AS move_2, FROM_UNIXTIME(r.time_spawn) AS spawn, FROM_UNIXTIME(r.time_battle) AS start, FROM_UNIXTIME(r.time_end) AS end, FROM_UNIXTIME(fs.updated) AS last_scanned, f.name, f.lat AS latitude, f.lon as longitude
FROM forts f
LEFT JOIN fort_sightings fs ON (fs.fort_id = f.id AND fs.last_modified = (SELECT MAX(last_modified) FROM fort_sightings fs2 WHERE fs2.fort_id=f.id))
LEFT JOIN raids r ON (r.fort_id = f.id AND r.time_end >= UNIX_TIMESTAMP())
WHERE r.time_end > UNIX_TIMESTAMP()
ORDER BY r.level DESC, r.time_battle'.$limit;
$result = $this->mysqli->query($req);
$raids = array();
while ($data = $result->fetch_object()) {
$raids[] = $data;
}
return $raids;
}
////////////////
// Gym History
////////////////
public function getGymHistories($gym_name, $team, $page, $ranking)
{
$where = '';
if (isset($gym_name) && '' != $gym_name) {
$where = " WHERE name LIKE '%".$gym_name."%'";
}
if (isset($team) && '' != $team) {
$where .= ('' === $where ? ' WHERE' : ' AND').' fs.team = '.$team;
}
switch ($ranking) {
case 1:
$order = ' ORDER BY name, last_modified DESC';
break;
case 2:
$order = ' ORDER BY total_cp DESC, last_modified DESC';
break;
default:
$order = ' ORDER BY last_modified DESC, name';
}
$limit = ' LIMIT '.($page * 10).',10';
$req = 'SELECT f.id as gym_id, fs.total_cp, f.name, fs.team as team_id, (6 - slots_available) as pokemon_count, FROM_UNIXTIME(last_modified) AS last_modified
FROM forts f
LEFT JOIN fort_sightings fs ON (fs.fort_id = f.id AND fs.last_modified = (SELECT MAX(last_modified) FROM fort_sightings fs2 WHERE fs2.fort_id=f.id))
'.$where.$order.$limit;
$result = $this->mysqli->query($req);
$gym_history = array();
while ($data = $result->fetch_object()) {
$gym_history[] = $data;
}
return $gym_history;
}
public function getGymHistoriesPokemon($gym_id)
{
$req = "SELECT external_id AS pokemon_uid, pokemon_id, cp_now as cp, owner_name AS trainer_name
FROM gym_defenders
WHERE fort_id = '".$gym_id."'
ORDER BY deployment_time";
$result = $this->mysqli->query($req);
$pokemons = array();
while ($data = $result->fetch_object()) {
$pokemons[] = $data;
}
return $pokemons;
}
public function getHistoryForGym($page, $gym_id)
{
if (isset(self::$config->system->gymhistory_hide_cp_changes) && true === self::$config->system->gymhistory_hide_cp_changes) {
$pageSize = 25;
} else {
$pageSize = 10;
}
$req = "SELECT f.id as gym_id, fs.team as team_id, total_cp, FROM_UNIXTIME(fs.last_modified) as last_modified, last_modified as last_modified_real
FROM fort_sightings fs
LEFT JOIN forts f ON f.id = fs.fort_id
WHERE f.id = '".$gym_id."'
ORDER BY fs.last_modified DESC
LIMIT ".($page * $pageSize).','.($pageSize + 1);
$result = $this->mysqli->query($req);
$history = array();
$count = 0;
while ($data = $result->fetch_object()) {
++$count;
if (0 == $data->total_cp) {
$data->pokemon = array();
$data->pokemon_count = 0;
$data->pokemon_uids = '';
} else {
$data->pokemon = $this->getHistoryForGymPokemon($gym_id, $data->last_modified_real);
$data->pokemon_count = count($data->pokemon);
$data->pokemon_uids = implode(',', array_keys($data->pokemon));
}
if (0 === $data->total_cp || 0 !== $data->pokemon_count) {
$history[] = $data;
}
}
if ($count !== ($pageSize + 1)) {
$last_page = true;
} else {
$last_page = false;
}
return array('last_page' => $last_page, 'data' => $history);
}
private function getHistoryForGymPokemon($gym_id, $last_modified)
{
$req = "SELECT ghd.defender_id, gd.pokemon_id, ghd.cp, gd.owner_name as trainer_name
FROM gym_history_defenders ghd
JOIN gym_defenders gd ON ghd.defender_id = gd.external_id
WHERE ghd.fort_id = '".$gym_id."' AND date = '".$last_modified."'
ORDER BY gd.deployment_time";
$result = $this->mysqli->query($req);
$pokemons = array();
while ($data = $result->fetch_object()) {
$pokemons[$data->defender_id] = $data;
}
return $pokemons;
}
//////////////
// Trainers
//////////////
public function getTrainers($trainer_name, $team, $page, $rankingNumber)
{
$ranking = $this->getTrainerLevelRanking();
$where = '';
if (!empty(self::$config->system->trainer_blacklist)) {
$where .= " AND gd.owner_name NOT IN ('".implode("','", self::$config->system->trainer_blacklist)."')";
}
if ('' != $trainer_name) {
$where = " AND gd.owner_name LIKE '%".$trainer_name."%'";
}
if (0 != $team) {
$where .= ('' == $where ? ' HAVING' : ' AND').' team = '.$team;
}
switch ($rankingNumber) {
case 1:
$order = ' ORDER BY active DESC, level DESC';
break;
case 2:
$order = ' ORDER BY maxCp DESC, level DESC';
break;
default:
$order = ' ORDER BY level DESC, active DESC';
}
$order .= ', last_seen DESC, name ';
$limit = ' LIMIT '.($page * 10).',10 ';
$req = 'SELECT gd.owner_name AS name, MAX(owner_level) AS level, MAX(cp) AS maxCp, MAX(active) AS active, MAX(team) AS team, FROM_UNIXTIME(MAX(last_modified)) as last_seen
FROM gym_defenders gd
LEFT JOIN (
SELECT owner_name, COUNT(*) as active
FROM gym_defenders gd2
WHERE fort_id IS NOT NULL
GROUP BY owner_name
) active ON active.owner_name = gd.owner_name
WHERE gd.owner_level IS NOT NULL '.$where.'
GROUP BY gd.owner_name'.$order.$limit;
$result = $this->mysqli->query($req);
$trainers = array();
while ($data = $result->fetch_object()) {
$data->last_seen = date('Y-m-d', strtotime($data->last_seen));
if (is_null($data->active)) {
$data->active = 0;
}
$trainers[$data->name] = $data;
$pokemon = array_merge($this->getActivePokemon($data->name), $this->getInactivePokemon($data->name));
$trainers[$data->name]->gyms = $data->active;
$trainers[$data->name]->pokemons = $pokemon;
$trainers[$data->name]->rank = $ranking[$data->level];
}
return $trainers;
}
public function getTrainerLevelRanking()
{
$exclue = '';
if (!empty(self::$config->system->trainer_blacklist)) {
$exclue .= " AND owner_name NOT IN ('".implode("','", self::$config->system->trainer_blacklist)."')";
}
$req = 'SELECT COUNT(*) AS count, level FROM (SELECT MAX(owner_level) as level FROM gym_defenders WHERE owner_level IS NOT NULL '.$exclue.' GROUP BY owner_level, owner_name) x GROUP BY level';
$result = $this->mysqli->query($req);
$levelData = array();
while ($data = $result->fetch_object()) {
$levelData[$data->level] = $data->count;
}
for ($i = 5; $i <= 40; ++$i) {
if (!isset($levelData[$i])) {
$levelData[$i] = 0;
}
}
// sort array again
ksort($levelData);
return $levelData;
}
public function getActivePokemon($trainer_name)
{
$req = "SELECT pokemon_id, cp, atk_iv AS iv_attack, sta_iv AS iv_stamina, def_iv AS iv_defense, FROM_UNIXTIME(deployment_time) AS deployment_time, '1' AS active, fort_id as gym_id, FLOOR((UNIX_TIMESTAMP() - created) / 86400) AS last_scanned
FROM gym_defenders
WHERE owner_name = '".$trainer_name."' AND fort_id IS NOT NULL
ORDER BY deployment_time";
$result = $this->mysqli->query($req);
$pokemon = array();
while ($data = $result->fetch_object()) {
$pokemon[] = $data;
}
return $pokemon;
}
public function getInactivePokemon($trainer_name)
{
$req = "SELECT pokemon_id, cp, atk_iv AS iv_attack, sta_iv AS iv_stamina, def_iv AS iv_defense, NULL AS deployment_time, '0' AS active, fort_id as gym_id, FLOOR((UNIX_TIMESTAMP() - created) / 86400) AS last_scanned
FROM gym_defenders
WHERE owner_name = '".$trainer_name."' AND fort_id IS NULL
ORDER BY last_scanned";
$result = $this->mysqli->query($req);
$pokemon = array();
while ($data = $result->fetch_object()) {
$pokemon[] = $data;
}
return $pokemon;
}
public function getTrainerLevelCount($team_id)
{
$exclue = '';
if (!empty(self::$config->system->trainer_blacklist)) {
$exclue .= " AND owner_name NOT IN ('".implode("','", self::$config->system->trainer_blacklist)."')";
}
$req = "SELECT COUNT(*) AS count, level FROM (SELECT MAX(owner_level) as level FROM gym_defenders WHERE owner_level IS NOT NULL AND team = '".$team_id."' ".$exclue.' GROUP BY owner_level, owner_name) x GROUP BY level';
$result = $this->mysqli->query($req);
$levelData = array();
while ($data = $result->fetch_object()) {
$levelData[$data->level] = $data->count;
}
for ($i = 5; $i <= 40; ++$i) {
if (!isset($levelData[$i])) {
$levelData[$i] = 0;
}
}
// sort array again
ksort($levelData);
return $levelData;
}
/////////
// Cron
/////////
public function getPokemonCountsActive()
{
$req = 'SELECT pokemon_id, COUNT(*) as total FROM sightings WHERE expire_timestamp >= UNIX_TIMESTAMP() GROUP BY pokemon_id';
$result = $this->mysqli->query($req);
$counts = array();
while ($data = $result->fetch_object()) {
$counts[$data->pokemon_id] = $data->total;
}
return $counts;
}
public function getTotalPokemonIV()
{
$req = 'SELECT COUNT(*) as total FROM sightings WHERE expire_timestamp >= UNIX_TIMESTAMP() AND cp IS NOT NULL';
$result = $this->mysqli->query($req);
$data = $result->fetch_object();
return $data;
}
public function getPokemonCountsLastDay()
{
$req = 'SELECT pokemon_id, COUNT(*) AS spawns_last_day
FROM sightings
WHERE expire_timestamp >= (SELECT MAX(expire_timestamp) - 86400 FROM sightings)
GROUP BY pokemon_id
ORDER BY pokemon_id ASC';
$result = $this->mysqli->query($req);
$counts = array();
while ($data = $result->fetch_object()) {
$counts[$data->pokemon_id] = $data->spawns_last_day;
}
return $counts;
}
public function getCaptchaCount()
{
$req = ' SELECT COUNT(*) as total FROM accounts WHERE captchaed IS NOT NULL AND reason IS NULL';
$result = $this->mysqli->query($req);
$data = $result->fetch_object();
return $data;
}
public function getNestData($time, $minLatitude, $maxLatitude, $minLongitude, $maxLongitude)
{
$pokemon_exclude_sql = '';
if (!empty(self::$config->system->nest_exclude_pokemon)) {
$pokemon_exclude_sql = 'AND p.pokemon_id NOT IN ('.implode(',', self::$config->system->nest_exclude_pokemon).')';
}
$req = 'SELECT p.pokemon_id, MAX(p.lat) AS latitude, MAX(p.lon) AS longitude, count(p.pokemon_id) AS total_pokemon, MAX(s.updated) as latest_seen, coalesce(CASE WHEN MAX(duration) = 0 THEN NULL ELSE MAX(duration) END ,30)*60 as duration
FROM sightings p
INNER JOIN spawnpoints s ON (p.spawn_id = s.spawn_id)
WHERE p.expire_timestamp > UNIX_TIMESTAMP() - '.($time * 3600).'
AND p.lat >= '.$minLatitude.' AND p.lat < '.$maxLatitude.' AND p.lon >= '.$minLongitude.' AND p.lon < '.$maxLongitude.'
'.$pokemon_exclude_sql.'
GROUP BY p.spawn_id, p.pokemon_id
HAVING COUNT(p.pokemon_id) >= '.($time / 4).'
ORDER BY p.pokemon_id';
$result = $this->mysqli->query($req);
$nests = array();
while ($data = $result->fetch_object()) {
$nests[] = $data;
}
return $nests;
}
public function getSpawnpointCount($minLatitude, $maxLatitude, $minLongitude, $maxLongitude)
{
$req = 'SELECT COUNT(*) as total
FROM spawnpoints
WHERE lat >= '.$minLatitude.' AND lat < '.$maxLatitude.' AND lon >= '.$minLongitude.' AND lon < '.$maxLongitude;
$result = $this->mysqli->query($req);
$data = $result->fetch_object();
return $data;
}
}
|
brusselopole/Worldopole
|
core/process/queries/QueryManagerMysqlMonocleAlternate.php
|
PHP
|
mit
| 28,852
|
import Device from '@/interfaces/Device';
import mongoose from 'mongoose';
const device: Device = {
platform: 'testplatform',
userId: mongoose.Types.ObjectId('4ede40c86362e0fb12000003'),
tokens: ['nyht4ca81bGam26a'],
service: 'firebase',
};
export default device;
|
schulcloud/node-notification-service
|
test/data/device.ts
|
TypeScript
|
mit
| 270
|
/*
* Open Surge Engine
* loop.h - loop system
* Copyright (C) 2011 Alexandre Martins <alemartf(at)gmail(dot)com>
* http://opensnc.sourceforge.net
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef _LOOP_H
#define _LOOP_H
#include "../item.h"
/* public methods */
item_t* loopgreen_create();
item_t* loopyellow_create();
#endif
|
asirnayeef23/opensurge
|
src/entities/items/loop.h
|
C
|
mit
| 1,017
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DaownaMp3Library
{
//for managing selections and shared playlists/tracks
public class Jukebox
{
private int _userId;
private List<int> _publicPlaylistIds;
private List<int> _myPublicListIds;
private List<int> _sharedTrackIds;
private List<int> _mySharedTrackIds;
private Track _selectedTrack;
private Track _selectedSharedTrack;
private PlayList _mySelectedPlaylist;
public Jukebox(int id)
{
_userId = id;
_publicPlaylistIds = DataAccess.Instance.GetPublicPlaylistIds(id);
_myPublicListIds = DataAccess.Instance.GetMyPublicPlaylistIds(id);
_sharedTrackIds = DataAccess.Instance.GetSharedTrackIds(id);
_mySharedTrackIds = DataAccess.Instance.GetMySharedTrackIds(id);
}
public List<int> PublicPlayListIds
{
get { return _publicPlaylistIds; }
}
public List<int> MyPublicPlayListIds
{
get { return _myPublicListIds; }
}
public List<int> SharedTrackIds
{
get { return _sharedTrackIds; }
}
public List<int> MySharedTackIds
{
get { return _mySharedTrackIds; }
}
public Track SelectedTrack
{
get { return _selectedTrack; }
set { _selectedTrack = value; }
}
public Track SelectedSharedTrack
{
get { return _selectedSharedTrack; }
set { _selectedSharedTrack = value; }
}
public PlayList MySelectedPlayList
{
get { return _mySelectedPlaylist; }
set { _mySelectedPlaylist = value; }
}
public void ResetMySharedPlaylistIds()
{
_myPublicListIds = DataAccess.Instance.GetMyPublicPlaylistIds(_userId);
}
public List<string> SharedTrackNames()
{
string name;
List<string> trackNames = new List<string>(), trackArtists = new List<string>();
for (int i = 0; i < this.SharedTrackIds.Count; i++)
{
name = DataAccess.Instance.GetSongName(this.SharedTrackIds[i]);
trackNames.Add(name);
}
return trackNames;
}
public List<string> SharedTrackArtists()
{
string artist;
List<string> trackArtists = new List<string>();
for (int i = 0; i < this.SharedTrackIds.Count; i++)
{
artist = DataAccess.Instance.GetArtist(this.SharedTrackIds[i]);
trackArtists.Add(artist);
}
return trackArtists;
}
}
}
|
LimeyJohnson/DaownaMusic
|
DaownaMp3/DaownaMp3Library/Jukebox.cs
|
C#
|
mit
| 2,845
|
require 'rails_helper'
RSpec.describe Order::Written::EventsService do
# shared_examples 'receive email' do
# it 'email should be sent' do
# subject
# expect(ActionMailer::Base.deliveries.count).to eq(2)
# end
# end
let(:event_service) {Order::Written::EventsService.new order}
#
let(:ch_lang) {create :language, is_chinese: true}
let(:lang) {create :language}
#
# describe '#after_paid_order' do
#
# before(:each) do
# ActionMailer::Base.deliveries = []
# end
#
#
# subject{event_service.after_paid_order}
#
# context 'no translators with 5,6 hsk' do
# let!(:translator) {create :profile,
# services: [build(:service, written_approves: true, language: lang,
# written_translate_type: 'From-To Chinese')]}
# before(:each) {translator.profile_steps_service.update_attributes hsk_level: 4;
# translator.update_attributes state: 'approved'}
#
# context 'order not to ch' do
# let(:order) {create :order_written, original_language: ch_lang, translation_language: lang}
# include_examples 'receive email'
# end
#
# context 'no approved chinese translators' do
# let(:order) {create :order_written, original_language: lang, translation_language: ch_lang}
# include_examples 'receive email'
# end
# end
#
# end
# describe '#confirmation_order_in_30' do
#
# subject{event_service.confirmation_order_in_30}
#
# context 'when no assignee for 30 min' do
# context 'no translators with 5,6 hsk' do
# before(:each) {translator.profile_steps_service.update_attributes hsk_level: 4;
# translator.update_attributes state: 'approved'}
#
# let!(:translator) {create :profile, state: 'approved',
# services: [build(:service, written_approves: true, language: lang,
# written_translate_type: 'From-To Chinese')]}
# let(:order) {create :order_written, original_language: lang, translation_language: ch_lang}
#
#
# include_examples 'receive email'
# end
# end
# end
describe '#after_translate_order' do
subject{event_service.after_translate_order}
let!(:theme) {Support::Theme.create name: 'lol', theme_type: :order_written}
context 'order to ch' do
context 'translator is chinese' do
context 'need proofreadin' do
let(:china) {create :country, is_china: true}
let(:translator) {create :profile}
let(:order) {create :order_written, original_language: lang, translation_language: ch_lang,
assignee: translator, translation_type: 'translate_and_correct'}
before(:each) {translator.update_attribute :citizenship, china}
it{expect{subject}.to change{Support::Ticket.count}.by 1}
end
end
context 'translator not chinese' do
let(:translator) {create :profile}
let(:order) {create :order_written, original_language: lang, translation_language: ch_lang,
assignee: translator, translation_type: 'translate_and_correct'}
it{expect{subject}.to change{Support::Ticket.count}.by 1}
end
end
context 'order from ch' do
context 'order need proof read' do
# context 'assignee can proof read' do
# let(:order) {create :order_written, original_language: ch_lang, translation_language: lang,
# assignee: trans, translation_type: 'translate_and_correct', state: 'in_progress'}
# let!(:trans) {create(:profile,
# services: [build(:service, written_approves: true, language: lang,
# written_translate_type: 'From Chinese + Corrector')])}
# it 'assign translator as proof reader' do
# subject
# expect(order.proof_reader).to eq trans
# expect(order.state).to eq 'correcting'
# end
# end
context 'assignee cant proof read' do
let(:order) {create :order_written, original_language: ch_lang, translation_language: lang,
assignee: trans, translation_type: 'translate_and_correct', state: 'wait_corrector'}
let!(:trans) {create(:profile,
services: [build(:service, written_approves: true, language: lang,
written_translate_type: 'From Chinese')])}
it 'order wait corrector' do
subject
expect(order.state).to eq 'wait_corrector'
end
end
end
# context 'order dont need proof read' do
# let(:order) {create :order_written, original_language: ch_lang, translation_language: lang,
# assignee: trans, translation_type: 'translate', state: 'in_progress'}
# let(:trans) {create(:profile,
# services: [build(:service, written_approves: true, language: lang,
# written_translate_type: 'From Chinese')])}
# it 'order transition to quality_control' do
# subject
# expect(order.state).to eq 'quality_control'
# end
# end
end
end
end
|
max-konin/yufu_core
|
spec/services/order/written/events_service_spec.rb
|
Ruby
|
mit
| 5,463
|
<!DOCTYPE html>
<html>
<head>
<title>Doge Social Network</title>
</head>
<body style="background-color: skyblue">
<p style="font-size:30px; font-weight:bold">Doge Social Network</p>
<ul type="disc">
<li><a href="home.html"> Home</a></li>
<li><a href="profile.html">Profile</a></li>
<li><a href="friends.html">Friends</a></li>
</ul>
<hr />
<h2>Friends of Doge</h2>
<hr />
<em>
Such Friend<br />
best friend<br />
Many Friends<br />
unknown<br />
Wow<br />
yeah, right
</em>
</body>
</html>
|
fr0wsTyl/TelerikAcademy-2015
|
Telerik - HTML/Homework evaluation/01. 1/Problem 3/friends.html
|
HTML
|
mit
| 596
|
/*
* SonarScanner for .NET
* Copyright (C) 2016-2022 SonarSource SA
* mailto: info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
using System.IO;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SonarScanner.Integration.Tasks.IntegrationTests.TargetsTests;
using TestUtilities;
namespace SonarScanner.MSBuild.Tasks.IntegrationTest.TargetsTests
{
[TestClass]
public class ImportBeforeTargetsTests
{
public TestContext TestContext { get; set; }
/// <summary>
/// Name of the property to check for to determine whether or not
/// the targets have been imported or not
/// </summary>
private const string DummyAnalysisTargetsMarkerProperty = "DummyProperty";
[TestInitialize]
public void TestInitialize()
{
TestUtils.EnsureImportBeforeTargetsExists(TestContext);
}
#region Tests
[TestMethod]
[Description("Checks the properties are not set if SonarQubeTargetsPath is missing")]
public void ImportsBefore_SonarQubeTargetsPathNotSet()
{
// 1. Prebuild
// Arrange
var projectXml = @"
<PropertyGroup>
<SonarQubeTargetsPath />
<AGENT_BUILDDIRECTORY />
<TF_BUILD_BUILDDIRECTORY />
</PropertyGroup>
";
var projectFilePath = CreateProjectFile(projectXml);
var result = BuildRunner.BuildTargets(TestContext, projectFilePath);
result.AssertPropertyValue(TargetProperties.SonarQubeTargetFilePath, null);
AssertAnalysisTargetsAreNotImported(result);
result.AssertTargetSucceeded(TargetConstants.DefaultBuild);
result.AssertTargetNotExecuted(TargetConstants.ImportBeforeInfo);
result.AssertErrorCount(0);
}
[TestMethod]
[Description("Checks the properties are not set if the project is building inside Visual Studio")]
public void ImportsBefore_BuildingInsideVS_NotImported()
{
var dummySonarTargetsDir = EnsureDummyIntegrationTargetsFileExists();
var projectXml = $@"
<PropertyGroup>
<SonarQubeTempPath>{Path.GetTempPath()}</SonarQubeTempPath>
<SonarQubeTargetsPath>{Path.GetDirectoryName(dummySonarTargetsDir)}</SonarQubeTargetsPath>
<BuildingInsideVisualStudio>tRuE</BuildingInsideVisualStudio>
</PropertyGroup>
";
var projectFilePath = CreateProjectFile(projectXml);
var result = BuildRunner.BuildTargets(TestContext, projectFilePath);
result.AssertPropertyValue(TargetProperties.SonarQubeTargetFilePath, dummySonarTargetsDir);
AssertAnalysisTargetsAreNotImported(result);
result.AssertTargetSucceeded(TargetConstants.DefaultBuild);
result.AssertTargetNotExecuted(TargetConstants.ImportBeforeInfo);
result.AssertErrorCount(0);
}
[TestMethod]
[Description("Checks what happens if the analysis targets cannot be located")]
public void ImportsBefore_MissingAnalysisTargets()
{
var projectXml = @"
<PropertyGroup>
<SonarQubeTempPath>nonExistentPath</SonarQubeTempPath>
<MSBuildExtensionsPath>nonExistentPath</MSBuildExtensionsPath>
<AGENT_BUILDDIRECTORY />
<TF_BUILD_BUILDDIRECTORY />
</PropertyGroup>";
var projectFilePath = CreateProjectFile(projectXml);
var result = BuildRunner.BuildTargets(TestContext, projectFilePath);
AssertAnalysisTargetsAreNotImported(result); // Targets should not be imported
result.AssertPropertyValue(TargetProperties.SonarQubeTargetsPath, @"nonExistentPath\bin\targets");
result.AssertPropertyValue(TargetProperties.SonarQubeTargetFilePath, @"nonExistentPath\bin\targets\SonarQube.Integration.targets");
result.BuildSucceeded.Should().BeTrue();
result.AssertTargetExecuted(TargetConstants.ImportBeforeInfo);
result.AssertErrorCount(0);
var projectName = Path.GetFileName(projectFilePath);
result.Messages.Should().Contain($"Sonar: ({projectName}) SonarQube analysis targets imported: ");
result.Messages.Should().Contain($@"Sonar: ({projectName}) The analysis targets file not found: nonExistentPath\bin\targets\SonarQube.Integration.targets");
}
[TestMethod]
[Description("Checks that the targets are imported if the properties are set correctly and the targets can be found")]
public void ImportsBefore_TargetsExist()
{
var dummySonarTargetsDir = EnsureDummyIntegrationTargetsFileExists();
var projectXml = $@"
<PropertyGroup>
<SonarQubeTempPath>{Path.GetTempPath()}</SonarQubeTempPath>
<SonarQubeTargetsPath>{Path.GetDirectoryName(dummySonarTargetsDir)}</SonarQubeTargetsPath>
<AGENT_BUILDDIRECTORY />
<TF_BUILD_BUILDDIRECTORY />
</PropertyGroup>";
var projectFilePath = CreateProjectFile(projectXml);
var result = BuildRunner.BuildTargets(TestContext, projectFilePath);
result.AssertPropertyValue(TargetProperties.SonarQubeTargetFilePath, dummySonarTargetsDir);
AssertAnalysisTargetsAreImported(result);
result.AssertTargetSucceeded(TargetConstants.DefaultBuild);
result.AssertTargetExecuted(TargetConstants.ImportBeforeInfo);
result.AssertErrorCount(0);
}
#endregion Tests
#region Private methods
/// <summary>
/// Ensures that a dummy targets file with the name of the SonarQube analysis targets file exists.
/// Return the full path to the targets file.
/// </summary>
private string EnsureDummyIntegrationTargetsFileExists()
{
// This can't just be in the TestContext.DeploymentDirectory as this will
// be shared with other tests, and some of those tests might be deploying
// the real analysis targets to that location.
var testSpecificDir = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext);
var fullPath = Path.Combine(testSpecificDir, TargetConstants.AnalysisTargetFile);
if (!File.Exists(fullPath))
{
// To check whether the targets are imported or not we check for
// the existence of the DummyProperty, below.
var contents = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<DummyProperty>123</DummyProperty>
</PropertyGroup>
<Target Name='DummyTarget' />
</Project>
";
File.WriteAllText(fullPath, contents);
}
return fullPath;
}
private string CreateProjectFile(string testSpecificProjectXml)
{
var projectDirectory = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext);
var importsBeforeTargets = Path.Combine(projectDirectory, TargetConstants.ImportsBeforeFile);
// Locate the real "ImportsBefore" target file
File.Exists(importsBeforeTargets).Should().BeTrue("Test error: the SonarQube imports before target file does not exist. Path: {0}", importsBeforeTargets);
var projectData = Resources.ImportBeforeTargetTestsTemplate.Replace("SQ_IMPORTS_BEFORE", importsBeforeTargets).Replace("TEST_SPECIFIC_XML", testSpecificProjectXml);
return new TargetsTestsUtils(TestContext).CreateProjectFile(projectDirectory, projectData);
}
#endregion Private methods
#region Assertions
private static void AssertAnalysisTargetsAreNotImported(BuildLog result)
{
var propertyInstance = result.GetPropertyValue(DummyAnalysisTargetsMarkerProperty, true);
propertyInstance.Should().BeNull("SonarQube Analysis targets should not have been imported");
}
private static void AssertAnalysisTargetsAreImported(BuildLog result)
{
var propertyInstance = result.GetPropertyValue(DummyAnalysisTargetsMarkerProperty, true);
propertyInstance.Should().NotBeNull("Failed to import the SonarQube Analysis targets");
}
#endregion Assertions
}
}
|
SonarSource-DotNet/sonar-msbuild-runner
|
Tests/SonarScanner.MSBuild.Tasks.IntegrationTest/TargetsTests/ImportBeforeTargetsTests.cs
|
C#
|
mit
| 8,911
|
require 'spec_helper'
describe 'The version constants' do
describe 'VERSION_MAJOR' do
let(:version_major) { GMT::VERSION_MAJOR }
it 'is an integer' do
expect(version_major).to be_an Integer
end
it 'is non-negative' do
expect(version_major).to be >= 0
end
end
describe 'VERSION_MINOR' do
let(:version_minor) { GMT::VERSION_MINOR }
it 'is an integer' do
expect(version_minor).to be_an Integer
end
it 'is non-negative' do
expect(version_minor).to be >= 0
end
end
describe 'VERSION_RELEASE' do
let(:version_release) { GMT::VERSION_RELEASE }
it 'is an integer' do
expect(version_release).to be_an Integer
end
it 'is non-negative' do
expect(version_release).to be >= 0
end
end
describe '.version_at_least' do
context 'for the previous major version' do
let(:major_version) { GMT::VERSION_MAJOR - 1 }
it 'should be true' do
expect(GMT.version_at_least? major_version).to eq true
end
end
context 'for the next major version' do
let(:major_version) { GMT::VERSION_MAJOR + 1 }
it 'should be false' do
expect(GMT.version_at_least? major_version).to eq false
end
end
context 'for current major version' do
let(:major_version) { GMT::VERSION_MAJOR }
let(:result) do
GMT.version_at_least?(major_version, minor_version)
end
context 'for the previous minor version' do
let(:minor_version) { GMT::VERSION_MINOR - 1 }
it 'should be true' do
expect(result).to eq true
end
end
context 'for the next minor version' do
let(:minor_version) { GMT::VERSION_MINOR + 1 }
it 'should be false' do
expect(result).to eq false
end
end
context 'for current minor version' do
let(:minor_version) { GMT::VERSION_MINOR }
let(:result) do
GMT.version_at_least?(major_version, minor_version, release_version)
end
context 'for the previous release version' do
let(:release_version) { GMT::VERSION_RELEASE - 1 }
it 'should be true' do
expect(result).to eq true
end
end
context 'for the next release version' do
let(:release_version) { GMT::VERSION_RELEASE + 1 }
it 'should be false' do
expect(result).to eq false
end
end
context 'for the current release version' do
let(:release_version) { GMT::VERSION_RELEASE }
it 'should be true' do
expect(result).to eq true
end
end
end
end
end
end
|
jjgreen/ruby-gmt
|
spec/version_spec.rb
|
Ruby
|
mit
| 2,698
|
package ru.stqa.pft.addressbook.tests;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.GroupData;
public class GroupCreationTest extends TestBase {
@Test
public void testGroupCreation() {
app.gotoGroupPage();
app.initGroupCreation();
app.fillGroupForm(new GroupData("test1", "test2", "test3"));
app.submitGroupCreation();
app.returmToGroupPage();
}
}
|
vakulayo/java_pft
|
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/GroupCreationTest.java
|
Java
|
mit
| 435
|
<section data-ng-controller="CategoriesController">
<div class="container">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
</span>
<input type="text" id="firstName" name="firstName" class="form-control" placeholder="Enter Zip Code ...">
</div>
</div>
</div>
<div class="col-md-4"></div>
</div>
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-3">
<span class="glyphicon glyphicon-education alert-info" aria-hidden="true"></span>
<span>School Ressources</span>
<span class="glyphicon glyphicon-triangle-right" aria-hidden="true"></span>
</div>
<div class="col-md-3"></div>
<div class="col-md-3"></div>
</div>
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-3">
<span class="glyphicon glyphicon-header alert-danger" aria-hidden="true"></span>
<span>Health Ressources</span>
<span class="glyphicon glyphicon-triangle-right" aria-hidden="true"></span>
</div>
<div class="col-md-3"></div>
<div class="col-md-3"></div>
</div>
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-3">
<span class="glyphicon glyphicon-flash alert-success" aria-hidden="true"></span>
<span>Emergency Ressources</span>
<span class="glyphicon glyphicon-triangle-right" aria-hidden="true"></span>
</div>
<div class="col-md-3"></div>
<div class="col-md-3"></div>
</div>
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-3">
<span class="glyphicon glyphicon-home alert-warning" aria-hidden="true"></span>
<span>Home and Shelter Ressources</span>
<span class="glyphicon glyphicon-triangle-right" aria-hidden="true"></span>
</div>
<div class="col-md-3"></div>
<div class="col-md-3"></div>
</div>
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-3">
<span class="glyphicon glyphicon-cutlery alert-info" aria-hidden="true"></span>
<span>Food Ressources</span>
<span class="glyphicon glyphicon-triangle-right" aria-hidden="true"></span>
</div>
<div class="col-md-3"></div>
<div class="col-md-3"></div>
</div>
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-3">
<span class="glyphicon glyphicon-flag alert-danger" aria-hidden="true"></span>
<span>Other Ressources</span>
<span class="glyphicon glyphicon-triangle-right" aria-hidden="true"></span>
</div>
<div class="col-md-3"></div>
<div class="col-md-3"></div>
</div>
</div>
</section>
|
Highgalaxy3r1/metroApp
|
public/modules/categories/views/categories.client.view.html
|
HTML
|
mit
| 2,771
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Text.RegularExpressions;
using System.Web.Http;
namespace Cleangorod.Web
{
public class FileActionResult : IHttpActionResult
{
public FileActionResult(Stream stream, string fileName, string mediaType)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
_Stream = stream;
_FileName = fileName;
_MediaType = mediaType;
}
Stream _Stream;
string _FileName;
string _MediaType;
static readonly Regex _InternetExplorerRegex = new Regex(@"(?:\b(MS)?IE\s+|\bTrident\/7\.0;.*\s+rv:)(\d+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage();
response.Content = new StreamContent(_Stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue(_MediaType);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = _InternetExplorerRegex.IsMatch(HttpContext.Current.Request.UserAgent) ? Uri.EscapeDataString(_FileName) : _FileName
};
return Task.FromResult(response);
}
}
}
|
rgripper/cg-routes
|
Cleangorod/Cleangorod.Web/FileActionResult.cs
|
C#
|
mit
| 1,573
|
import { CSSProperties } from "react"
export let ulStyles: CSSProperties = {
display: "flex",
listStyle: "none"
}
export let liStyles: CSSProperties = {
padding: "0 10px"
}
export let activeLinkStyle: CSSProperties = {
fontWeight: "bold",
textDecoration: "none"
}
|
aalpgiray/react-hot-boilerplate-ts
|
src/components/navigator/style.tsx
|
TypeScript
|
mit
| 290
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Http.Headers;
namespace AzureLens.Areas.HelpPage
{
/// <summary>
/// This is used to identify the place where the sample should be applied.
/// </summary>
public class HelpPageSampleKey
{
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type.
/// </summary>
/// <param name="mediaType">The media type.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType)
{
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
ActionName = String.Empty;
ControllerName = String.Empty;
MediaType = mediaType;
ParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type and CLR type.
/// </summary>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The CLR type.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type)
: this(mediaType)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
ParameterType = type;
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on <see cref="SampleDirection"/>, controller name, action name and parameter names.
/// </summary>
/// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (controllerName == null)
{
throw new ArgumentNullException("controllerName");
}
if (actionName == null)
{
throw new ArgumentNullException("actionName");
}
if (parameterNames == null)
{
throw new ArgumentNullException("parameterNames");
}
ControllerName = controllerName;
ActionName = actionName;
ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
SampleDirection = sampleDirection;
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names.
/// </summary>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
: this(sampleDirection, controllerName, actionName, parameterNames)
{
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
MediaType = mediaType;
}
/// <summary>
/// Gets the name of the controller.
/// </summary>
/// <value>
/// The name of the controller.
/// </value>
public string ControllerName { get; private set; }
/// <summary>
/// Gets the name of the action.
/// </summary>
/// <value>
/// The name of the action.
/// </value>
public string ActionName { get; private set; }
/// <summary>
/// Gets the media type.
/// </summary>
/// <value>
/// The media type.
/// </value>
public MediaTypeHeaderValue MediaType { get; private set; }
/// <summary>
/// Gets the parameter names.
/// </summary>
public HashSet<string> ParameterNames { get; private set; }
public Type ParameterType { get; private set; }
/// <summary>
/// Gets the <see cref="SampleDirection"/>.
/// </summary>
public SampleDirection? SampleDirection { get; private set; }
public override bool Equals(object obj)
{
HelpPageSampleKey otherKey = obj as HelpPageSampleKey;
if (otherKey == null)
{
return false;
}
return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) &&
ParameterType == otherKey.ParameterType &&
SampleDirection == otherKey.SampleDirection &&
ParameterNames.SetEquals(otherKey.ParameterNames);
}
public override int GetHashCode()
{
int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode();
if (MediaType != null)
{
hashCode ^= MediaType.GetHashCode();
}
if (SampleDirection != null)
{
hashCode ^= SampleDirection.GetHashCode();
}
if (ParameterType != null)
{
hashCode ^= ParameterType.GetHashCode();
}
foreach (string parameterName in ParameterNames)
{
hashCode ^= parameterName.ToUpperInvariant().GetHashCode();
}
return hashCode;
}
}
}
|
MicrosoftDX/AzureLens
|
AzureLens/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs
|
C#
|
mit
| 6,645
|
---
layout: attachment
title: Is Everything Black and White?
categories: []
tags: []
status: inherit
type: attachment
published: false
meta:
_wp_attached_file: 2009/11/Goldberg_Invitation05.pdf
_wp_attachment_metadata: a:0:{}
---
|
nu-lts/jekyll-snippets
|
_attachments/2009-11-10-goldberg_invitation05.html
|
HTML
|
mit
| 235
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>callbacks.empty() | jQuery API 中文手册</title>
<meta name="author" content="jQuery 中文手册 - hemin.cn/jq/">
<meta name="description" content="jQuery中文手册(在线版),作者:hemin,在线手册:hemin.cn/jq/,下载:hemin.cn/jq/downloads/">
<link type="text/css" rel="stylesheet" href="style/style.css" tppabs="http://hemin.cn/jq/style/style.css" />
<script type="text/javascript" src="js/jquery.min.js" tppabs="http://hemin.cn/jq/js/jquery.min.js"></script>
<script type="text/javascript" src="js/js.js" tppabs="http://hemin.cn/jq/js/js.js"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-15318881-10', 'pandoraui.github.io');
ga('send', 'pageview');
</script>
</head>
<body id="split">
<div id="content" class="a2">
<div rel="callbacks.empty">
<h2><span>返回值:undefined</span>callbacks.empty()</h2>
<h3><em>V1.7</em>概述</h3>
<div class="desc">
<p> 从列表中删除所有的回调. </p>
<div class="longdesc">
<p></p>
</div>
</div>
<div class="example">
<h3>示例</h3>
<span id="f_ad2"></span>
<h4>描述:</h4>
<p> 使用 callbacks.empty() 清空回调列表: </p>
<h5>jQuery 代码:</h5>
<pre><code>// a sample logging function to be added to a callbacks list
var foo = function( value1, value2 ){
console.log( 'foo:' + value1 + ',' + value2 );
}
// another function to also be added to the list
var bar = function( value1, value2 ){
console.log( 'bar:' + value1 + ',' + value2 );
}
var callbacks = $.Callbacks();
// add the two functions
callbacks.add( foo );
callbacks.add( bar );
// empty the callbacks list
callbacks.empty();
// check to ensure all callbacks have been removed
console.log( callbacks.has( foo ) ); // false
console.log( callbacks.has( bar ) ); // false</code></pre>
</div>
</div>
</div>
</body>
</html>
|
pandoraui/jquery-chm
|
callbacks.empty.html
|
HTML
|
mit
| 2,237
|
package hipchat
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"path"
"sync/atomic"
"github.com/influxdata/kapacitor"
)
type Service struct {
configValue atomic.Value
logger *log.Logger
}
func NewService(c Config, l *log.Logger) *Service {
s := &Service{
logger: l,
}
s.configValue.Store(c)
return s
}
func (s *Service) Open() error {
return nil
}
func (s *Service) Close() error {
return nil
}
func (s *Service) config() Config {
return s.configValue.Load().(Config)
}
func (s *Service) Update(newConfig []interface{}) error {
if l := len(newConfig); l != 1 {
return fmt.Errorf("expected only one new config object, got %d", l)
}
if c, ok := newConfig[0].(Config); !ok {
return fmt.Errorf("expected config object to be of type %T, got %T", c, newConfig[0])
} else {
s.configValue.Store(c)
}
return nil
}
func (s *Service) Global() bool {
c := s.config()
return c.Global
}
func (s *Service) StateChangesOnly() bool {
c := s.config()
return c.StateChangesOnly
}
type testOptions struct {
Room string `json:"room"`
Message string `json:"message"`
Level kapacitor.AlertLevel `json:"level"`
}
func (s *Service) TestOptions() interface{} {
c := s.config()
return &testOptions{
Room: c.Room,
Message: "test hipchat message",
Level: kapacitor.CritAlert,
}
}
func (s *Service) Test(options interface{}) error {
o, ok := options.(*testOptions)
if !ok {
return fmt.Errorf("unexpected options type %T", options)
}
c := s.config()
return s.Alert(o.Room, c.Token, o.Message, o.Level)
}
func (s *Service) Alert(room, token, message string, level kapacitor.AlertLevel) error {
url, post, err := s.preparePost(room, token, message, level)
if err != nil {
return err
}
resp, err := http.Post(url, "application/json", post)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
type response struct {
Error string `json:"error"`
}
r := &response{Error: fmt.Sprintf("failed to understand HipChat response. code: %d content: %s", resp.StatusCode, string(body))}
b := bytes.NewReader(body)
dec := json.NewDecoder(b)
dec.Decode(r)
return errors.New(r.Error)
}
return nil
}
func (s *Service) preparePost(room, token, message string, level kapacitor.AlertLevel) (string, io.Reader, error) {
c := s.config()
if !c.Enabled {
return "", nil, errors.New("service is not enabled")
}
//Generate HipChat API URL including room and authentication token
if room == "" {
room = c.Room
}
if token == "" {
token = c.Token
}
u, err := url.Parse(c.URL)
if err != nil {
return "", nil, err
}
u.Path = path.Join(u.Path, room, "notification")
v := url.Values{}
v.Set("auth_token", token)
u.RawQuery = v.Encode()
var color string
switch level {
case kapacitor.WarnAlert:
color = "yellow"
case kapacitor.CritAlert:
color = "red"
default:
color = "green"
}
postData := make(map[string]interface{})
postData["from"] = kapacitor.Product
postData["color"] = color
postData["message"] = message
postData["notify"] = true
var post bytes.Buffer
enc := json.NewEncoder(&post)
err = enc.Encode(postData)
if err != nil {
return "", nil, err
}
return u.String(), &post, nil
}
|
titilambert/kapacitor
|
services/hipchat/service.go
|
GO
|
mit
| 3,425
|
HTPC Manager [](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=info@styxit.com&lc=US&item_name=HTPC-Manager&item_number=htpc-manager-donation&no_note=0¤cy_code=USD&bn=PP-DonationsBF:btn_donate_LG.gif:NonHostedGuest)
=====
A python based web application to manage the software on your Htpc. Htpc Manager combines all your favorite software into one slick interface. See [http://htpc.io](http://htpc.io).

## See full installation instructions at [htpc.io](http://htpc.io/)
Requires Python 2.7 or 2.6 with argeparse installed.
Start with ```python Htpc.py```
|
styxit/HTPC-Manager
|
README.md
|
Markdown
|
mit
| 713
|
require 'active_support/core_ext/string/filters'
class CodeTerminator::Html
def initialize(args = {})
@code = args[:code]
@source = args[:source]
@tags = Array.new
@elements = Array.new
args[:source_type] ||= "file"
@source_type = args[:source_type]
end
# Get html elements of a html file. Return a list of Nokogiri XML objects.
#
# Example:
# >> CodeTerminator::Html.get_elements("hola_mundo.html")
# => [#<Nokogiri::XML::Element:0x3fe3391547d8 name="h1" children=[#<Nokogiri::XML::Text:0x3fe33915474c "Hola Mundo!">]>, #<Nokogiri::XML::Text:0x3fe33915474c "Hola Mundo!">]
#
# Arguments:
# source: (String)
def get_elements(source)
@elements = Array.new
#How to read if is an url
if @source_type == "url"
reader = Nokogiri::HTML(open(source).read)
else
reader = Nokogiri::HTML(File.open(source))
end
#remove empty spaces from reader
reader = remove_empty_text(reader)
if reader.css('html').any?
node = Hash.new
node[:parent] = ""
node[:tag] = "html"
node[:pointer] = reader.css('html').first.pointer_id
@elements << node
end
#search elements from body section
if reader.at('body')
node = Hash.new
node[:parent] = "html"
node[:tag] = "body"
node[:pointer] = reader.css('body').first.pointer_id
node[:parent_pointer] = reader.css('html').first.pointer_id
@elements << node
reader.at('body').attribute_nodes.each do |element_attribute|
node = Hash.new
node[:parent] = "html"
node[:tag] = "body"
node[:attribute] = element_attribute.name if element_attribute.name
node[:value] = element_attribute.value if element_attribute.value
node[:pointer] = element_attribute.pointer_id
node[:parent_pointer] = reader.css('html').first.pointer_id
@elements << node
end
end
#end search
#search elements from head section
if reader.at('head')
node = Hash.new
node[:parent] = "html"
node[:tag] = "head"
node[:pointer] = reader.css('head').first.pointer_id
node[:parent_pointer] = reader.css('html').first.pointer_id
@elements << node
reader.at('head').children.each do |child|
if child.attribute_nodes.empty?
node = Hash.new
node[:parent] = "head"
node[:tag] = child.name
node[:content] = child.text if child.text or child.comment?
node[:pointer] = child.pointer_id
node[:parent_pointer] = child.parent.pointer_id
@elements << node
else
child.attribute_nodes.each do |element_attribute|
node = Hash.new
node[:parent] = "head"
if child.name == "#cdata-section"
node[:tag] = "text"
else
node[:tag] = child.name
end
node[:content] = child.text if child.text
node[:attribute] = element_attribute.name if element_attribute.name
node[:value] = element_attribute.value if element_attribute.value
node[:pointer] = element_attribute.pointer_id
node[:parent_pointer] = child.pointer_id
@elements << node
end
end
add_children(child) if child.children.any?
end
end
#end search elements
#search elements inside body (children)
if reader.at('body')
reader.at('body').children.each do |child|
if child.attribute_nodes.empty?
node = Hash.new
node[:parent] = "body"
node[:tag] = child.name
node[:content] = child.text if child.text? or child.comment?
node[:pointer] = child.pointer_id
node[:parent_pointer] = child.parent.pointer_id
@elements << node
else
node = Hash.new
node[:parent] = "body"
node[:tag] = child.name
node[:content] = child.text if child.text? or child.comment?
node[:pointer] = child.pointer_id
node[:parent_pointer] = child.parent.pointer_id
@elements << node
child.attribute_nodes.each do |element_attribute|
node = Hash.new
node[:parent] = "body"
node[:tag] = child.name
node[:attribute] = element_attribute.name if element_attribute.name
node[:value] = element_attribute.value if element_attribute.value
node[:pointer] = element_attribute.pointer_id
node[:parent_pointer] = child.pointer_id
@elements << node
end
end
add_children(child) if child.children.any?
end
end
#end search elements
@elements
end
# Match if the code have the same elements than the exercise. Return an array with the mismatches.
#
# Example:
#
# hola_mundo.html
# => <h1>Hola Mundo!</h1>
#
# >> CodeTerminator::Html.match("hola_mundo.html","<h2>Hola Mundo!</h2>")
# => ["h1 not exist"]
#
# Arguments:
# source: (String)
# code: (String)
def match(source, code)
@html_errors = Array.new
code = Nokogiri::HTML(code)
@elements = get_elements(source)
@elements.each do |e|
p css_string = build_css(e,'').strip
#search_attribute()
if e[:attribute]
# search_attribute = code.css(css_string).first
# if !search_attribute
# @html_errors << new_error(element: e, type: 334, description: "`<#{e[:tag]}>` should have an attribute named #{e[:attribute]} with the value #{e[:value]}")
# end
#search_text()
elsif e[:tag] == "text" || e[:tag] == "comment"
element_name = e[:tag]=="comment" ? "comment":e[:parent]
search_elements = code.css(css_string)
if e[:content].strip != ""
element = search_elements.select{|hash| hash.text.strip == e[:content].strip}
if element.empty?
@html_errors << new_error(element: e, type: 330, description: "The text inside `<#{element_name}>` should be #{e[:content]}")
end
end
#search_element()
else
search_element = code.css(css_string).first
if !search_element
@html_errors << new_error(element: e[:tag], type: 404, description: "Remember to add the `<#{e[:tag]}>` tag in " + css_string.chomp(e[:tag]))
# else
# if !are_all_elements(code,e[:tag], css_string)
# # @html_errors << new_error(element: e[:tag], type: 404, description: "Remember to add the `<#{e[:tag]}>` tag.")
# end
end
end
end
count_elements(code)
search_attribute_value(code)
p @html_errors
end
private
def build_css(element, css)
if !element[:parent].empty?
if !element[:attribute]
if element[:tag]=="comment"
css += "//comment()"
else
parent = @elements.select{|hash| hash[:pointer].to_s == element[:parent_pointer].to_s}.first
parent_css = parent[:tag].to_s if parent
css += parent_css
parent_attributes = @elements.select{|hash| hash[:parent_pointer].to_s == element[:parent_pointer].to_s && hash[:attribute]}
parent_attributes.each do |par_attr|
css += css_attribute_type(par_attr)
end
css += " "
css += element[:tag].to_s + " " if element[:tag] != "text"
end
else
search_attribute = @elements.select{|hash| hash[:parent_pointer].to_s == element[:parent_pointer].to_s && hash[:attribute].to_s == element[:attribute]}.first
css += search_attribute[:tag].to_s
attribute_css = css_attribute_type(search_attribute) if search_attribute
css += attribute_css
end
else
css += element[:tag].to_s + " " if element[:tag] != "text"
end
css
end
def css_attribute_type(element)
case element[:attribute]
when "id"
css_symbol = '#'
css = css_symbol.to_s + element[:value].to_s
when "class"
css_symbol = '.'
css = css_symbol.to_s + element[:value].to_s
when "src"
css_symbol = "[src]"
css = css_symbol.to_s
when "href"
css_symbol = "[href]"
css = css_symbol.to_s
when "alt"
css_symbol = "[alt]"
css = css_symbol.to_s
else
css_symbol = element[:attribute]
css = css_symbol.to_s
end
css
end
def are_all_elements(code, tag, css_string)
element_count = @elements.select{|hash| hash[:tag] == tag && !hash[:attribute]}.count
code_count = code.css(css_string).count
element_count > code_count ? false:true
end
def count_elements(code)
uniq_elements = @elements.group_by{|h| h[:tag]}
uniq_elements.each do |e|
if e[0] != "text"
# "element " + e[0].to_s
element_count = e[1].select{|hash| !hash[:attribute]}.count
if e[0] != "comment"
code_count = code.css(e[0]).count
else
code_count = code.css("//comment()").count
end
if element_count > code_count
@html_errors << new_error(element: e[0], type: 404, description: "Remember to add the `<#{e[0]}>` tag.")
end
end
end
end
# def search_comments(code)
# comment_elements = code.css('//comment()')
#
# end
def search_attribute_value(code)
uniq_elements = @elements.group_by{|h| h[:tag]}
uniq_elements.each do |e|
element_with_attributes = e[1].select{|hash| hash[:attribute]}
element_with_attributes.each do |ewa|
css_string = build_css(ewa, '')
if code.css(css_string).empty?
@html_errors << new_error(element: ewa, type: 334, description: "`<#{ewa[:tag]}>` should have an attribute named #{ewa[:attribute]}")
else
if ewa[:value] != "" && code.css(css_string).select{|x| x[ewa[:attribute]].to_s == ewa[:value].to_s}.empty?
@html_errors << new_error(element: ewa, type: 333, description: "Make sure that the attribute #{ewa[:attribute]} in `<#{ewa[:tag]}>` has the value #{ewa[:value]}")
end
if code.css(css_string).select{|x| x[ewa[:attribute]].to_s == ""}.any?
@html_errors << new_error(element: ewa, type: 335, description: "`<#{ewa[:attribute]}>` in `<#{ewa[:tag]}>` can't be empty")
end
end
end
end
end
def add_children(parent)
parent.children.each do |child|
if child.attribute_nodes.empty?
node = Hash.new
node[:parent] = parent.name
if child.name == "#cdata-section"
node[:tag] = "text"
else
node[:tag] = child.name
end
node[:content] = child.text.strip if child.text and child.class != Nokogiri::XML::Element
node[:pointer] = child.pointer_id
node[:parent_pointer] = child.parent.pointer_id
@elements << node
else
child.attribute_nodes.each do |element_attribute|
node = Hash.new
node[:parent] = parent.name
if element_attribute.name == "#cdata-section"
node[:tag] = "text"
else
node[:tag] = child.name
end
node[:attribute] = element_attribute.name if element_attribute.name
node[:value] = element_attribute.value if element_attribute.value
node[:pointer] = element_attribute.pointer_id
node[:parent_pointer] = child.pointer_id
@elements << node
end
end
add_children(child) if child.children.any?
end
end
def remove_empty_text (reader)
if reader.at('head')
reader.at('head').children.each do |child|
if child.text
child.remove if child.content.to_s.squish.empty? && child.class == Nokogiri::XML::Text
end
check_children(child) if child.children.any?
end
end
if reader.at('body')
reader.at('body').children.each do |child|
if child.text
child.remove if child.content.to_s.squish.empty? && child.class == Nokogiri::XML::Text
end
check_children(child) if child.children.any?
end
end
reader
end
def check_children(parent)
parent.children.each do |child|
if child.text
child.remove if child.content.to_s.squish.empty? && child.class == Nokogiri::XML::Text
end
check_children(child) if child.children.any?
end
end
def new_error(args = {})
element = args[:element]
type = args[:type]
description = args[:description]
node = Hash.new
node[:element] = element
node[:type] = type
node[:description] = description
node
end
end
|
eponce19/CodeTerminator
|
lib/code_terminator/html.rb
|
Ruby
|
mit
| 13,022
|
// +build functional
package cri_containerd
import (
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
"time"
runtime "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
)
// This test requires compiling a helper logging binary which can be found
// at test/cri-containerd/helpers/log.go. Copy log.exe as "sample-logging-driver.exe"
// to ContainerPlat install directory or set "TEST_BINARY_ROOT" environment variable,
// which this test will use to construct logPath for CreateContainerRequest and as
// the location of stdout artifacts created by the binary
func Test_Run_Container_With_Binary_Logger(t *testing.T) {
client := newTestRuntimeClient(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
binaryPath := requireBinary(t, "sample-logging-driver.exe")
logPath := "binary:///" + binaryPath
type config struct {
name string
containerName string
requiredFeatures []string
runtimeHandler string
sandboxImage string
containerImage string
cmd []string
expectedContent string
}
tests := []config{
{
name: "WCOW_Process",
containerName: t.Name() + "-Container-WCOW_Process",
requiredFeatures: []string{featureWCOWProcess},
runtimeHandler: wcowProcessRuntimeHandler,
sandboxImage: imageWindowsNanoserver,
containerImage: imageWindowsNanoserver,
cmd: []string{"ping", "-t", "127.0.0.1"},
expectedContent: "Pinging 127.0.0.1 with 32 bytes of data",
},
{
name: "WCOW_Hypervisor",
containerName: t.Name() + "-Container-WCOW_Hypervisor",
requiredFeatures: []string{featureWCOWHypervisor},
runtimeHandler: wcowHypervisorRuntimeHandler,
sandboxImage: imageWindowsNanoserver,
containerImage: imageWindowsNanoserver,
cmd: []string{"ping", "-t", "127.0.0.1"},
expectedContent: "Pinging 127.0.0.1 with 32 bytes of data",
},
{
name: "LCOW",
containerName: t.Name() + "-Container-LCOW",
requiredFeatures: []string{featureLCOW},
runtimeHandler: lcowRuntimeHandler,
sandboxImage: imageLcowK8sPause,
containerImage: imageLcowAlpine,
cmd: []string{"ash", "-c", "while true; do echo 'Hello, World!'; sleep 1; done"},
expectedContent: "Hello, World!",
},
}
// Positive tests
for _, test := range tests {
t.Run(test.name+"_Positive", func(t *testing.T) {
requireFeatures(t, test.requiredFeatures...)
requiredImages := []string{test.sandboxImage, test.containerImage}
if test.runtimeHandler == lcowRuntimeHandler {
pullRequiredLcowImages(t, requiredImages)
} else {
pullRequiredImages(t, requiredImages)
}
podReq := getRunPodSandboxRequest(t, test.runtimeHandler)
podID := runPodSandbox(t, client, ctx, podReq)
defer removePodSandbox(t, client, ctx, podID)
logFileName := fmt.Sprintf(`%s\stdout-%s.txt`, filepath.Dir(binaryPath), test.name)
conReq := getCreateContainerRequest(podID, test.containerName, test.containerImage, test.cmd, podReq.Config)
conReq.Config.LogPath = logPath + fmt.Sprintf("?%s", logFileName)
createAndRunContainer(t, client, ctx, conReq)
if _, err := os.Stat(logFileName); os.IsNotExist(err) {
t.Fatalf("log file was not created: %s", logFileName)
}
defer os.Remove(logFileName)
ok, err := assertFileContent(logFileName, test.expectedContent)
if err != nil {
t.Fatalf("failed to read log file: %s", err)
}
if !ok {
t.Fatalf("file content validation failed: %s", test.expectedContent)
}
})
}
// Negative tests
for _, test := range tests {
t.Run(test.name+"_Negative", func(t *testing.T) {
requireFeatures(t, test.requiredFeatures...)
requiredImages := []string{test.sandboxImage, test.containerImage}
if test.runtimeHandler == lcowRuntimeHandler {
pullRequiredLcowImages(t, requiredImages)
} else {
pullRequiredImages(t, requiredImages)
}
podReq := getRunPodSandboxRequest(t, test.runtimeHandler)
podID := runPodSandbox(t, client, ctx, podReq)
defer removePodSandbox(t, client, ctx, podID)
nonExistentPath := "/does/not/exist/log.txt"
conReq := getCreateContainerRequest(podID, test.containerName, test.containerImage, test.cmd, podReq.Config)
conReq.Config.LogPath = logPath + fmt.Sprintf("?%s", nonExistentPath)
containerID := createContainer(t, client, ctx, conReq)
defer removeContainer(t, client, ctx, containerID)
// This should fail, since the filepath doesn't exist
_, err := client.StartContainer(ctx, &runtime.StartContainerRequest{
ContainerId: containerID,
})
if err == nil {
t.Fatal("container start should fail")
}
if !strings.Contains(err.Error(), "failed to start binary logger") {
t.Fatalf("expected 'failed to start binary logger' error, got: %s", err)
}
})
}
}
func createAndRunContainer(t *testing.T, client runtime.RuntimeServiceClient, ctx context.Context, conReq *runtime.CreateContainerRequest) {
containerID := createContainer(t, client, ctx, conReq)
defer removeContainer(t, client, ctx, containerID)
startContainer(t, client, ctx, containerID)
defer stopContainer(t, client, ctx, containerID)
// Let stdio kick in
time.Sleep(time.Second * 1)
}
func assertFileContent(path string, content string) (bool, error) {
fileContent, err := ioutil.ReadFile(path)
if err != nil {
return false, err
}
return strings.Contains(string(fileContent), content), nil
}
|
Microsoft/hcsshim
|
test/cri-containerd/logging_binary_test.go
|
GO
|
mit
| 5,493
|
import 'bootstrap';
import '../../src/scss/index.scss';
import profile from '../../src/img/portrait-medium.jpg';
const img = document.getElementById('profile');
if (img) {
img.src = profile;
}
|
quantumtom/marcflennert
|
src/js/index.js
|
JavaScript
|
mit
| 199
|
---
title: Deer
is_name: false
---
Deer Park Mine
|
stokeclimsland/stokeclimsland
|
_cards/DEER.md
|
Markdown
|
mit
| 55
|
FROM laincloud/centos-lain
RUN mkdir -p $GOPATH/src/github.com/laincloud
ADD . $GOPATH/src/github.com/laincloud/deployd
RUN cd $GOPATH/src/github.com/laincloud/deployd && go build -v -a -tags netgo -installsuffix netgo -o deployd
RUN mv $GOPATH/src/github.com/laincloud/deployd/deployd /usr/bin/
|
laincloud/deployd
|
Dockerfile
|
Dockerfile
|
mit
| 320
|
<div>
<h3>{{$ctrl.firstname}} {{$ctrl.lastname}}</h3>
<p>Position: {{$ctrl.jobtitle}}</p>
<p>Email: {{$ctrl.email}}</p>
</div>
|
michaeldperez/teambuilder
|
client/components/member/member.html
|
HTML
|
mit
| 132
|
require 'rack-rescue'
require 'wrapt'
Pancake.before_build do
unless Pancake::StackMiddleware[:rescue] || Pancake::StackMiddleware[Rack::Rescue]
Pancake.stack(:rescue).use(Rack::Rescue)
end
unless Pancake::StackMiddleware[:layout] || Pancake::StackMiddleware[Wrapt]
Pancake.stack(:layout).use(Wrapt) do |wrapt|
wrapt.defer!
end
end
end
|
hassox/short_stack
|
lib/short_stack/middleware.rb
|
Ruby
|
mit
| 364
|
<?php
/**
* ServieContainer.php
* restfully
* Date: 17.09.17
*/
namespace AppBundle\Infrastructure;
use Components\Infrastructure\IContainer;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ServiceContainer implements IContainer
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* ServiceContainer constructor.
*
* @param ContainerInterface $container
*/
public function __construct(ContainerInterface $container) {
$this->container = $container;
}
/**
* @param $id
*
* @return object
*/
public function acquire($id)
{
return $this->container->get($id);
}
/**
* @param $id
*
* @return bool
*/
public function exists($id)
{
return $this->container->has($id);
}
}
|
avanzu/audiorama
|
src/AppBundle/Infrastructure/ServiceContainer.php
|
PHP
|
mit
| 851
|
namespace Contacts.WebUi.Models
{
public class Settings : ISettings
{
public string ApiRootUri { get; set; }
public string ApiScopeUri { get; set; }
public string AppInsightsKey { get; set; }
public string ContactBlobStorageAccount { get; set; }
public string ContactBlobStorageAccountName { get; set; }
public string ContactImageContainerName { get; set; }
public string ContactImageUrl { get; set; }
public string ContactThumbnailBlobStorageAccountName { get; set; }
public string ContactThumbnailImageContainerName { get; set; }
public string ThumbnailQueueName { get; set; }
public string ThumbnailQueueStorageAccount { get; set; }
public string ThumbnailQueueStorageAccountName { get; set; }
}
}
|
jguadagno/Contacts
|
src/Contacts.WebUi/Models/Settings.cs
|
C#
|
mit
| 809
|
import React, {
Component,
View,
StyleSheet,
Text,
TouchableHighlight,
PropTypes,
NativeModules,
DeviceEventEmitter
} from 'react-native';
import { login, logout, getCredentials, liEvents} from './util';
import styles from './theme/style';
const Icon = require('react-native-vector-icons/FontAwesome');
export default class LILoginMock extends Component {
constructor(props) {
super(props);
this.willUnmountSoon = false;
this.state = {
credentials: null,
subscriptions: []
};
}
handleLogin() {
login(this.props.appDetails).then((data) => {
if (!this.willUnmountSoon) this.setState({ credentials : data });
}).catch((err) => {
if (!this.willUnmountSoon) this.setState({ credentials : null });
})
}
handleLogout() {
logout().then((data) => {
if (!this.willUnmountSoon) this.setState({ credentials : null });
}).catch((err) => {
console.warn(err);
})
}
onPress() {
this.state.credentials
? this.handleLogout()
: this.handleLogin();
this.props.onPress && this.props.onPress();
}
invokeHandler(eventType, eventData) {
const eventHandler = this.props["on" + eventType];
if (typeof eventHandler === 'function') eventHandler(eventData);
}
componentWillMount() {
this.willUnmountSoon = false;
const subscriptions = this.state.subscriptions;
Object.keys(liEvents).forEach((eventType) => {
let sub = DeviceEventEmitter.addListener( liEvents[eventType], this.invokeHandler.bind(this, eventType) );
subscriptions.push(sub);
});
// Add listeners to state
this.setState({ subscriptions : subscriptions });
}
unSubscribeEvents(subscription) {
subscription.remove();
}
componentWillUnmount() {
this.willUnmountSoon = true;
this.state.subscriptions.forEach(this.unSubscribeEvents);
}
componentDidMount() {
getCredentials().then((data)=>{
this.setState({ credentials : data });
}).catch((err) =>{
this.setState({ credentials : null });
console.log('Request failed: ', err);
});
}
prepareStyle() {
const { style ={} } = this.props;
const LILMText = style.LILMText || styles.LILMText;
const LILMTextLoggedIn = style.LILMTextLoggedIn || styles.LILMTextLoggedIn;
const LILMTextLoggedOut = style.LILMTextLoggedOut || styles.LILMTextLoggedOut;
return {
LILMButton: style.LILMButton || styles.LILMButton,
LILMButtonContent: style.LILMButtonContent || styles.LILMButtonContent,
LILMIconWrap: style.LILMIconWrap || styles.LILMIconWrap,
LILMIcon: style.LILMIcon || styles.LILMIcon,
LILMTextWrap: style.LILMTextWrap || styles.LILMTextWrap,
LILMText: [LILMText, this.state.credentials ? LILMTextLoggedIn : LILMTextLoggedOut],
}
}
render() {
const { loginText = "Log in with Linkedin", logoutText = "Log out"} = this.props;
const text = this.state.credentials ? logoutText : loginText;
const { LILMButton, LILMButtonContent, LILMIconWrap, LILMIcon, LILMTextWrap, LILMText} = this.prepareStyle();
return (
<TouchableHighlight style={ LILMButton } onPress={this.onPress.bind(this)}>
<View style={LILMButtonContent}>
<View style={ LILMIconWrap }>
<Icon name="linkedin" style={ LILMIcon }/>
</View>
<View style={ LILMTextWrap }>
<Text style={ LILMText } numberOfLines={1}>{text}</Text>
</View>
<View style={ LILMIconWrap }></View>
</View>
</TouchableHighlight>
);
}
}
/**
*
* appDetails: {
* redirectUrl, // optional
* clientId, // client id
* clientSecret, // client secret
* state, // some unique string that is hard to guess
* scopes // an array of permissions / scores your app will request access to.
* }
*
*/
LILoginMock.propTypes = {
styleOverride: PropTypes.object,
appDetails: PropTypes.object,
loginText: PropTypes.string,
logoutText: PropTypes.string,
onPress: PropTypes.func,
onLogin: PropTypes.func,
onLoginError: PropTypes.func,
onRequestSucess: PropTypes.func,
onRequestError: PropTypes.func
};
|
yanivkalfa/react-native-linkedin-login-mock
|
src/index.ios.js
|
JavaScript
|
mit
| 4,162
|
title: 分类
date: 2016-04-25 23:42:51
type: "categories"
comments: false
---
|
zhaochunqi/zhaochunqi.github.io
|
source/categories/index.md
|
Markdown
|
mit
| 79
|
package uk.co.terminological.parser;
import static org.junit.Assert.*;
import java.util.Date;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import uk.co.terminological.mappers.StringCaster;
public class StringCasterTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() {
assertTrue(StringCaster.guessType("123.456").equals(Float.class));
assertTrue(StringCaster.guessType("22.8").equals(Float.class));
assertTrue(StringCaster.guessType("2/7/1974").equals(Date.class));
assertTrue(StringCaster.guessType("123").equals(Integer.class));
assertTrue(StringCaster.guessType("blah blah").equals(String.class));
assertTrue(StringCaster.guessType("").equals(Object.class));
}
}
|
terminological/exotic-datatypes
|
src/test/java/uk/co/terminological/parser/StringCasterTest.java
|
Java
|
mit
| 804
|
<!doctype html>
<html class="theme-next pisces use-motion">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />
<link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />
<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />
<meta name="keywords" content="Hexo, NexT" />
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />
<meta name="description" content="以在家上班为目标">
<meta property="og:type" content="website">
<meta property="og:title" content="WDBLOG">
<meta property="og:url" content="http://www.wdblog.xyz/categories/服务器/page/2/index.html">
<meta property="og:site_name" content="WDBLOG">
<meta property="og:description" content="以在家上班为目标">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="WDBLOG">
<meta name="twitter:description" content="以在家上班为目标">
<script type="text/javascript" id="hexo.configuration">
var NexT = window.NexT || {};
var CONFIG = {
scheme: 'Pisces',
sidebar: {"position":"left","display":"always"},
fancybox: true,
motion: true,
duoshuo: {
userId: 0,
author: '博主'
}
};
</script>
<title> 分类: 服务器 | WDBLOG </title>
</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
<div class="container one-collumn sidebar-position-left ">
<div class="headband"></div>
<header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
<div class="header-inner"><div class="site-meta ">
<div class="custom-logo-site-title">
<a href="/" class="brand" rel="start">
<span class="logo-line-before"><i></i></span>
<span class="site-title">WDBLOG</span>
<span class="logo-line-after"><i></i></span>
</a>
</div>
<p class="site-subtitle"></p>
</div>
<div class="site-nav-toggle">
<button>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
</button>
</div>
<nav class="site-nav">
<ul id="menu" class="menu">
<li class="menu-item menu-item-home">
<a href="/." rel="section">
<i class="menu-item-icon fa fa-fw fa-home"></i> <br />
首页
</a>
</li>
<li class="menu-item menu-item-categories">
<a href="/categories" rel="section">
<i class="menu-item-icon fa fa-fw fa-th"></i> <br />
分类
</a>
</li>
<li class="menu-item menu-item-about">
<a href="/about" rel="section">
<i class="menu-item-icon fa fa-fw fa-user"></i> <br />
关于
</a>
</li>
<li class="menu-item menu-item-archives">
<a href="/archives" rel="section">
<i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
归档
</a>
</li>
<li class="menu-item menu-item-tags">
<a href="/tags" rel="section">
<i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
标签
</a>
</li>
<li class="menu-item menu-item-notes">
<a href="/notes" rel="section">
<i class="menu-item-icon fa fa-fw fa-sticky-note"></i> <br />
便利贴
</a>
</li>
</ul>
</nav>
</div>
</header>
<main id="main" class="main">
<div class="main-inner">
<div class="content-wrap">
<div id="content" class="content">
<section id="posts" class="posts-collapse">
<div class="collection-title">
<h2 >
服务器
<small>分类</small>
</h2>
</div>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<header class="post-header">
<h1 class="post-title">
<a class="post-title-link" href="/2015/07/17/2015-07-17-08r2vm/" itemprop="url">
<span itemprop="name">Windows 08 R2 Virtualbox 64位系统</span>
</a>
</h1>
<div class="post-meta">
<time class="post-time" itemprop="dateCreated"
datetime="2015-07-17T19:11:52+08:00"
content="2015-07-17" >
07-17
</time>
</div>
</header>
</article>
</section>
<nav class="pagination">
<a class="extend prev" rel="prev" href="/categories/服务器/"><i class="fa fa-angle-left"></i></a><a class="page-number" href="/categories/服务器/">1</a><span class="page-number current">2</span>
</nav>
</div>
</div>
<div class="sidebar-toggle">
<div class="sidebar-toggle-line-wrap">
<span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
</div>
</div>
<aside id="sidebar" class="sidebar">
<div class="sidebar-inner">
<section class="site-overview sidebar-panel sidebar-panel-active ">
<div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
<img class="site-author-image" itemprop="image"
src="http://i.imgur.com/fMwQDsN.jpg"
alt="wudaown" />
<p class="site-author-name" itemprop="name">wudaown</p>
<p class="site-description motion-element" itemprop="description">以在家上班为目标</p>
</div>
<nav class="site-state motion-element">
<div class="site-state-item site-state-posts">
<a href="/archives">
<span class="site-state-item-count">27</span>
<span class="site-state-item-name">日志</span>
</a>
</div>
<div class="site-state-item site-state-categories">
<a href="/categories">
<span class="site-state-item-count">13</span>
<span class="site-state-item-name">分类</span>
</a>
</div>
<div class="site-state-item site-state-tags">
<a href="/tags">
<span class="site-state-item-count">56</span>
<span class="site-state-item-name">标签</span>
</a>
</div>
</nav>
<div class="links-of-author motion-element">
<span class="links-of-author-item">
<a href="https://github.com/wudaown" target="_blank" title="Github">
<i class="fa fa-fw fa-globe"></i>
Github
</a>
</span>
<span class="links-of-author-item">
<a href="https://twitter.com/wudaown" target="_blank" title="Twitter">
<i class="fa fa-fw fa-twitter"></i>
Twitter
</a>
</span>
</div>
</section>
</div>
</aside>
</div>
</main>
<footer id="footer" class="footer">
<div class="footer-inner">
<div class="copyright" >
© 2014 -
<span itemprop="copyrightYear">2017</span>
<span class="with-love">
<i class="fa fa-heart"></i>
</span>
<span class="author" itemprop="copyrightHolder">wudaown</span>
</div>
<div class="powered-by">
由 <a class="theme-link" href="http://hexo.io">Hexo</a> 强力驱动
</div>
<div class="theme-info">
主题 -
<a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
NexT.Pisces
</a>
</div>
</div>
</footer>
<div class="back-to-top">
<i class="fa fa-arrow-up"></i>
</div>
</div>
<script type="text/javascript">
if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
window.Promise = null;
}
</script>
<script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>
<script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
<script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
<script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>
<script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
<script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>
<script type="text/javascript">
var disqus_shortname = 'wudaown';
var disqus_identifier = 'categories/服务器/page/2/index.html';
var disqus_title = '';
var disqus_url = '';
function run_disqus_script(disqus_script){
var dsq = document.createElement('script');
dsq.type = 'text/javascript';
dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
}
run_disqus_script('count.js');
</script>
</body>
</html>
|
wudaown/wudaown.github.io
|
categories/服务器/page/2/index.html
|
HTML
|
mit
| 10,893
|
<?php
/**
* template for sidebar
* @link https://codex.wordpress.org/Template_Hierarchy
*/
?>
|
tajidyakub/wpthemes-skeleton
|
src/sidebar.php
|
PHP
|
mit
| 96
|
# Uses git's autocompletion for inner commands. Assumes an install of git's
# bash `git-completion` script at $completion below
completion='$(brew --prefix)/share/zsh/site-functions/_git'
if test -f $completion
then
source $completion
fi
|
kfaustino/dotfiles
|
git/completion.zsh
|
Shell
|
mit
| 241
|
using System;
using System.Security;
using Engine.Model.Client;
using Engine.Model.Common.Entities;
using ThirtyNineEighty.BinarySerializer;
namespace Engine.Api.Client.Voice
{
[SecurityCritical]
class ClientPlayVoiceCommand :
ClientCommand<ClientPlayVoiceCommand.MessageContent>
{
public static long CommandId = (long)ClientCommandId.PlayVoice;
public override long Id
{
[SecuritySafeCritical]
get { return CommandId; }
}
protected override bool IsPeerCommand
{
[SecuritySafeCritical]
get { return true; }
}
[SecuritySafeCritical]
protected override void OnRun(MessageContent content, CommandArgs args)
{
using (var client = ClientModel.Get())
{
var user = client.Chat.GetUser(args.ConnectionId);
if (user.IsVoiceActive())
ClientModel.Player.Enqueue(args.ConnectionId, content.Number, content.Pack);
}
}
[Serializable]
[BinType("ClientPlayVoice")]
public class MessageContent
{
[BinField("p")]
public SoundPack Pack;
[BinField("n")]
public long Number;
}
}
}
|
Nirklav/TCPChat
|
Engine/Api/Client/Voice/ClientPlayVoiceCommand.cs
|
C#
|
mit
| 1,137
|
# dps-oauth-login
Javascript library for logging into DPS apps using OAuth authentication with 6D's Entitlement Server. After setting up a 3rd party authentication method for your app at http://entitlement-server.6dglobalcloud.com, use this javascript class with a custom DPS library to enable seamless OAuth logins in your app.
## How to install
### Using bower
Use `bower install --save dps-oauth-login` to retrieve the javascript file, and add a script tag to your custom DPS library HTML document, for example:
```html
<script src="path/to/dps-oauth-login.js"></script>
```
### Manual Installation
Add dps-oauth-login.js somewhere accessible by your DPS app (a web server, for example), and add a script tag to your custom DPS library HTML document, for example:
```html
<script src="path/to/dps-oauth-login.js"></script>
```
## How to use
In the custom DPS library HTML document, or in some other javascript file loaded by your custom DPS library, include the following code, making replacements as necessary.
```javascript
var oauthLoginButton = new OAuthLogin({
redirectURI : "CUSTOMURI://oauth", // Replace CUSTOMURI the custom URI prefix for your app
clientId : "com.domain.adobeappid", // Replace this with your adobe app id
selector : "#buttonid", // Selector for elements that a click event will be added to.
service : "salesforce" // The OAuth provider name on 6D's entitlement server for your app.
});
```
Note that `redirectURI` and `clientId` are determined through the DPS App Builder. `selector` refers to a CSS selector in your HTML document. `service` should match the name of the authentication method to be used. The authentication method must first be set up for your app on http://entitlement-server.6dglobalcloud.com in your app's settings.
|
SixDimensions/dps-oauth-login
|
README.md
|
Markdown
|
mit
| 1,801
|
<div class="page-header">
<h1>Apply to be a listed Consultant</h1>
</div>
<p>The ownCloud community <a href="/consulting">offers a list of parties providing services to ownCoud users</a>. No endorsement is implied by these listings. If you would like to have your organization added to this page, please follow these instructions:
<ul>
<li>Entries <strong>must</strong> be factual and relevant to ownCloud. Generic services are not a good fit. Make sure that the link you submit contains references (and a link) to ownCloud.</li>
<li>Your organization and in particular the website at the link provided has to <strong>respect the <a href="/trademarks">ownCloud trademark policy</a></strong>.</li>
<li>Note that being listed does not apply approval, endorsement or affiliation with the ownCloud community or project or ownCloud GmbH and your website and/or description should not, incorrectly, claim so.</li>
<li>The <strong>description</strong> can be up to 135 characters (250 for partners). It should give an idea of the offered services so readers can quickly judge if an entry is of interest. Review the current list for the expected contents and format.</li>
<ul>
<li><strong>Good</strong>: “We offer deployment support, performance optimization of ownCloud, external storage integration and can develop custom apps”</li>
<li><strong>Bad</strong>: “Awesome, Inc. is a successful consulting firm founded on solid engineering principles and is a leading provider of open source solutions.”</li>
(this does not explain what you offer and gives no reason for a visitor to click to your website)
</ul>
<li>A <strong>logo</strong> has to be of the size of 290x70pixels in png format and use grayscale colors (partners color).</li>
<li>Entries with incorrect data (wrong image size, too many characters, invalid email addresses or web links) might be silently ignored.</li>
<li>Submit a new entry if you made a mistake or if something has to change.</li>
<li>Entries with invalid links may be removed. Please keep us informed about changes.</li>
<li>It can take up to 4 weeks to be listed, please understand that we do this as a courtesy to the ownCloud ecosystem. Please do not submit duplicate entries (unless there were changes). A new submission <strong>will delay being listed</strong> as we work from old to new.</li>
</ul>
<div class="row providers">
<div class="span12">
<p>To apply to be listed on the <a href="/consulting">ownCloud.org/consulting</a> webpage as an ownCloud
consultant, please complete the following form.</p>
<script src="//app-ab13.marketo.com/js/forms2/js/forms2.min.js"></script>
<form id="mktoForm_1249"></form>
<script>MktoForms2.loadForm("//app-ab13.marketo.com", "038-KRL-592", 1249);</script>
<p>If you are interested in partnering with
<a target="_blank" href="https://owncloud.com">ownCloud GmbH</a> you can find more information
<a target="_blank" href="https://owncloud.com/partner/">here</a>.</p>
</div>
</div>
|
lefherz/owncloud.org
|
page-apply2.php
|
PHP
|
mit
| 3,075
|
require_relative '../../../../spec_helper'
describe 'statsd', :type => :class do
context "graphite_hostname => graphite.example.com" do
let(:params) {{
:graphite_hostname => 'graphite.example.com',
}}
it { is_expected.to contain_package('statsd') }
it { is_expected.to contain_service('statsd') }
it { is_expected.to contain_file('/etc/statsd/config.js').with_content(/ graphiteHost: "graphite.example.com"$/) }
end
end
|
alphagov/govuk-puppet
|
modules/statsd/spec/classes/statsd_spec.rb
|
Ruby
|
mit
| 453
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>fcsl-pcm: 2 m 22 s 🏆</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.12.0 / fcsl-pcm - 1.3.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
fcsl-pcm
<small>
1.3.0
<span class="label label-success">2 m 22 s 🏆</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-03-02 09:40:27 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-02 09:40:27 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.12.0 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "FCSL <fcsl@software.imdea.org>"
homepage: "http://software.imdea.org/fcsl/"
bug-reports: "https://github.com/imdea-software/fcsl-pcm/issues"
dev-repo: "git+https://github.com/imdea-software/fcsl-pcm.git"
license: "Apache-2.0"
build: [ make "-j%{jobs}%" ]
install: [ make "install" ]
depends: [
"coq" {(>= "8.11" & < "8.13~") | (= "dev")}
"coq-mathcomp-ssreflect" {(>= "1.10.0" & < "1.12~") | (= "dev")}
]
tags: [
"keyword:separation logic"
"keyword:partial commutative monoid"
"category:Computer Science/Data Types and Data Structures"
"logpath:fcsl"
"date:2020-10-15"
]
authors: [
"Aleksandar Nanevski"
]
synopsis: "Partial Commutative Monoids"
description: """
The PCM library provides a formalisation of Partial Commutative Monoids (PCMs),
a common algebraic structure used in separation logic for verification of
pointer-manipulating sequential and concurrent programs.
The library provides lemmas for mechanised and automated reasoning about PCMs
in the abstract, but also supports concrete common PCM instances, such as heaps,
histories and mutexes.
This library relies on extensionality axioms: propositional and
functional extentionality."""
url {
src: "https://github.com/imdea-software/fcsl-pcm/archive/v1.3.0.tar.gz"
checksum: "sha256=3ac78341d681df1a35ad720a84b81089eec1bee30197b15d15b29a3d8c3cec85"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-fcsl-pcm.1.3.0 coq.8.12.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-fcsl-pcm.1.3.0 coq.8.12.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>1 m 48 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-fcsl-pcm.1.3.0 coq.8.12.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>2 m 22 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 11 M</p>
<ul>
<li>2 M <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/unionmap.vo</code></li>
<li>1 M <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/unionmap.glob</code></li>
<li>1 M <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/prelude.vo</code></li>
<li>1012 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/natmap.vo</code></li>
<li>856 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/natmap.glob</code></li>
<li>428 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/finmap.vo</code></li>
<li>427 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/morphism.vo</code></li>
<li>365 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/morphism.glob</code></li>
<li>365 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/prelude.glob</code></li>
<li>310 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/pcm.vo</code></li>
<li>260 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/finmap.glob</code></li>
<li>247 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/pred.vo</code></li>
<li>221 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/heap.vo</code></li>
<li>199 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/automap.vo</code></li>
<li>192 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/pcm.glob</code></li>
<li>190 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/unionmap.v</code></li>
<li>181 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/pred.glob</code></li>
<li>154 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/ordtype.vo</code></li>
<li>142 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/heap.glob</code></li>
<li>120 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/mutex.vo</code></li>
<li>113 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/natmap.v</code></li>
<li>112 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/ordtype.glob</code></li>
<li>111 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/rtc.vo</code></li>
<li>110 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/invertible.vo</code></li>
<li>100 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/automap.glob</code></li>
<li>82 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/seqperm.vo</code></li>
<li>76 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/lift.vo</code></li>
<li>62 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/mutex.glob</code></li>
<li>57 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/morphism.v</code></li>
<li>48 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/rtc.glob</code></li>
<li>44 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/finmap.v</code></li>
<li>42 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/pred.v</code></li>
<li>42 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/seqperm.glob</code></li>
<li>42 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/invertible.glob</code></li>
<li>35 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/pcm.v</code></li>
<li>30 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/axioms.vo</code></li>
<li>29 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/lift.glob</code></li>
<li>28 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/automap.v</code></li>
<li>24 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/heap.v</code></li>
<li>23 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/prelude.v</code></li>
<li>18 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/ordtype.v</code></li>
<li>13 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/axioms.glob</code></li>
<li>11 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/mutex.v</code></li>
<li>10 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/rtc.v</code></li>
<li>8 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/lift.v</code></li>
<li>8 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/seqperm.v</code></li>
<li>5 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/pcm/invertible.v</code></li>
<li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/core/axioms.v</code></li>
<li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/options.vo</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/options.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/fcsl/options.glob</code></li>
</ul>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-fcsl-pcm.1.3.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
coq-bench/coq-bench.github.io
|
clean/Linux-x86_64-4.05.0-2.0.1/released/8.12.0/fcsl-pcm/1.3.0.html
|
HTML
|
mit
| 12,835
|
<?php
namespace ZfrMail\Exception;
/**
* @author Michaël Gallego
*/
interface ExceptionInterface
{
}
|
zf-fr/zfr-mail
|
src/Exception/ExceptionInterface.php
|
PHP
|
mit
| 106
|
#![feature(core_intrinsics)]
#![feature(generators, generator_trait)]
pub mod structs;
pub mod traits;
pub mod operators;
pub mod closures;
pub mod iterators;
pub mod algorithms;
pub mod utils;
pub mod strings;
pub mod IO;
pub mod concurrency;
pub mod low_level;
pub mod macros;
pub mod unsafes;
pub mod ffi;
|
rockdragon/julia-programming
|
code/rust/data-struct/src/lib.rs
|
Rust
|
mit
| 309
|
# poo-java
projetos em java
|
lucassbarcelos/poo-java
|
README.md
|
Markdown
|
mit
| 28
|
# input lib
from pygame.locals import *
import pygame, string
class ConfigError(KeyError): pass
class Config:
""" A utility for configuration """
def __init__(self, options, *look_for):
assertions = []
for key in look_for:
if key[0] in options.keys(): exec('self.'+key[0]+' = options[\''+key[0]+'\']')
else: exec('self.'+key[0]+' = '+key[1])
assertions.append(key[0])
for key in options.keys():
if key not in assertions: raise ConfigError(key+' not expected as option')
class Input:
""" A text input for pygame apps """
def __init__(self, **options):
""" Options: x, y, font, color, restricted, maxlength, prompt """
self.options = Config(options, ['x', '0'], ['y', '0'], ['font', 'pygame.font.Font(None, 32)'],
['color', '(0,0,0)'], ['restricted', '\'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&\\\'()*+,-./:;<=>?@[\]^_`{|}~\''],
['maxlength', '-1'], ['prompt', '\'\''])
self.x = self.options.x; self.y = self.options.y
self.font = self.options.font
self.color = self.options.color
self.restricted = self.options.restricted
self.maxlength = self.options.maxlength
self.prompt = self.options.prompt; self.value = ''
self.shifted = False
def set_pos(self, x, y):
""" Set the position to x, y """
self.x = x
self.y = y
def set_font(self, font):
""" Set the font for the input """
self.font = font
def draw(self, surface):
""" Draw the text input to a surface """
text = self.font.render(self.prompt+self.value, 1, self.color)
surface.blit(text, (self.x, self.y))
def getText(self):
return self.value
def hasTyped(self):
if self.value =="":
return False
else:
return True
def update(self, events):
""" Update the input based on passed events """
for event in events:
if event.type == KEYUP:
if event.key == K_LSHIFT or event.key == K_RSHIFT: self.shifted = False
if event.type == KEYDOWN:
if event.key == K_BACKSPACE: self.value = self.value[:-1]
elif event.key == K_LSHIFT or event.key == K_RSHIFT: self.shifted = True
elif event.key == K_SPACE: self.value += ' '
if not self.shifted:
if event.key == K_a and 'a' in self.restricted: self.value += 'a'
elif event.key == K_b and 'b' in self.restricted: self.value += 'b'
elif event.key == K_c and 'c' in self.restricted: self.value += 'c'
elif event.key == K_d and 'd' in self.restricted: self.value += 'd'
elif event.key == K_e and 'e' in self.restricted: self.value += 'e'
elif event.key == K_f and 'f' in self.restricted: self.value += 'f'
elif event.key == K_g and 'g' in self.restricted: self.value += 'g'
elif event.key == K_h and 'h' in self.restricted: self.value += 'h'
elif event.key == K_i and 'i' in self.restricted: self.value += 'i'
elif event.key == K_j and 'j' in self.restricted: self.value += 'j'
elif event.key == K_k and 'k' in self.restricted: self.value += 'k'
elif event.key == K_l and 'l' in self.restricted: self.value += 'l'
elif event.key == K_m and 'm' in self.restricted: self.value += 'm'
elif event.key == K_n and 'n' in self.restricted: self.value += 'n'
elif event.key == K_o and 'o' in self.restricted: self.value += 'o'
elif event.key == K_p and 'p' in self.restricted: self.value += 'p'
elif event.key == K_q and 'q' in self.restricted: self.value += 'q'
elif event.key == K_r and 'r' in self.restricted: self.value += 'r'
elif event.key == K_s and 's' in self.restricted: self.value += 's'
elif event.key == K_t and 't' in self.restricted: self.value += 't'
elif event.key == K_u and 'u' in self.restricted: self.value += 'u'
elif event.key == K_v and 'v' in self.restricted: self.value += 'v'
elif event.key == K_w and 'w' in self.restricted: self.value += 'w'
elif event.key == K_x and 'x' in self.restricted: self.value += 'x'
elif event.key == K_y and 'y' in self.restricted: self.value += 'y'
elif event.key == K_z and 'z' in self.restricted: self.value += 'z'
elif event.key == K_0 and '0' in self.restricted: self.value += '0'
elif event.key == K_1 and '1' in self.restricted: self.value += '1'
elif event.key == K_2 and '2' in self.restricted: self.value += '2'
elif event.key == K_3 and '3' in self.restricted: self.value += '3'
elif event.key == K_4 and '4' in self.restricted: self.value += '4'
elif event.key == K_5 and '5' in self.restricted: self.value += '5'
elif event.key == K_6 and '6' in self.restricted: self.value += '6'
elif event.key == K_7 and '7' in self.restricted: self.value += '7'
elif event.key == K_8 and '8' in self.restricted: self.value += '8'
elif event.key == K_9 and '9' in self.restricted: self.value += '9'
elif event.key == K_BACKQUOTE and '`' in self.restricted: self.value += '`'
elif event.key == K_MINUS and '-' in self.restricted: self.value += '-'
elif event.key == K_EQUALS and '=' in self.restricted: self.value += '='
elif event.key == K_LEFTBRACKET and '[' in self.restricted: self.value += '['
elif event.key == K_RIGHTBRACKET and ']' in self.restricted: self.value += ']'
elif event.key == K_BACKSLASH and '\\' in self.restricted: self.value += '\\'
elif event.key == K_SEMICOLON and ';' in self.restricted: self.value += ';'
elif event.key == K_QUOTE and '\'' in self.restricted: self.value += '\''
elif event.key == K_COMMA and ',' in self.restricted: self.value += ','
elif event.key == K_PERIOD and '.' in self.restricted: self.value += '.'
elif event.key == K_SLASH and '/' in self.restricted: self.value += '/'
elif self.shifted:
if event.key == K_a and 'A' in self.restricted: self.value += 'A'
elif event.key == K_b and 'B' in self.restricted: self.value += 'B'
elif event.key == K_c and 'C' in self.restricted: self.value += 'C'
elif event.key == K_d and 'D' in self.restricted: self.value += 'D'
elif event.key == K_e and 'E' in self.restricted: self.value += 'E'
elif event.key == K_f and 'F' in self.restricted: self.value += 'F'
elif event.key == K_g and 'G' in self.restricted: self.value += 'G'
elif event.key == K_h and 'H' in self.restricted: self.value += 'H'
elif event.key == K_i and 'I' in self.restricted: self.value += 'I'
elif event.key == K_j and 'J' in self.restricted: self.value += 'J'
elif event.key == K_k and 'K' in self.restricted: self.value += 'K'
elif event.key == K_l and 'L' in self.restricted: self.value += 'L'
elif event.key == K_m and 'M' in self.restricted: self.value += 'M'
elif event.key == K_n and 'N' in self.restricted: self.value += 'N'
elif event.key == K_o and 'O' in self.restricted: self.value += 'O'
elif event.key == K_p and 'P' in self.restricted: self.value += 'P'
elif event.key == K_q and 'Q' in self.restricted: self.value += 'Q'
elif event.key == K_r and 'R' in self.restricted: self.value += 'R'
elif event.key == K_s and 'S' in self.restricted: self.value += 'S'
elif event.key == K_t and 'T' in self.restricted: self.value += 'T'
elif event.key == K_u and 'U' in self.restricted: self.value += 'U'
elif event.key == K_v and 'V' in self.restricted: self.value += 'V'
elif event.key == K_w and 'W' in self.restricted: self.value += 'W'
elif event.key == K_x and 'X' in self.restricted: self.value += 'X'
elif event.key == K_y and 'Y' in self.restricted: self.value += 'Y'
elif event.key == K_z and 'Z' in self.restricted: self.value += 'Z'
elif event.key == K_0 and ')' in self.restricted: self.value += ')'
elif event.key == K_1 and '!' in self.restricted: self.value += '!'
elif event.key == K_2 and '@' in self.restricted: self.value += '@'
elif event.key == K_3 and '#' in self.restricted: self.value += '#'
elif event.key == K_4 and '$' in self.restricted: self.value += '$'
elif event.key == K_5 and '%' in self.restricted: self.value += '%'
elif event.key == K_6 and '^' in self.restricted: self.value += '^'
elif event.key == K_7 and '&' in self.restricted: self.value += '&'
elif event.key == K_8 and '*' in self.restricted: self.value += '*'
elif event.key == K_9 and '(' in self.restricted: self.value += '('
elif event.key == K_BACKQUOTE and '~' in self.restricted: self.value += '~'
elif event.key == K_MINUS and '_' in self.restricted: self.value += '_'
elif event.key == K_EQUALS and '+' in self.restricted: self.value += '+'
elif event.key == K_LEFTBRACKET and '{' in self.restricted: self.value += '{'
elif event.key == K_RIGHTBRACKET and '}' in self.restricted: self.value += '}'
elif event.key == K_BACKSLASH and '|' in self.restricted: self.value += '|'
elif event.key == K_SEMICOLON and ':' in self.restricted: self.value += ':'
elif event.key == K_QUOTE and '"' in self.restricted: self.value += '"'
elif event.key == K_COMMA and '<' in self.restricted: self.value += '<'
elif event.key == K_PERIOD and '>' in self.restricted: self.value += '>'
elif event.key == K_SLASH and '?' in self.restricted: self.value += '?'
if len(self.value) > self.maxlength and self.maxlength >= 0: self.value = self.value[:-1]
|
antismap/MICshooter
|
sources/lib/eztext.py
|
Python
|
mit
| 11,212
|
(function(){
'use strict';
angular
.module('chat', [])
.controller('ChatCtrl', ['$rootScope', '$scope', 'restFulService', 'restFulSocketService', '$sailsSocket', function($rootScope, $scope, restFulService, restFulSocketService, $sailsSocket){
$scope.chats = [];
$scope.contacts = [];
$scope.chat = {
open: false,
focus: false,
name: null,
avatar: '',
logged: false,
existMoreMessages: false,
messages: [],
message: {
chatId: null,
from: null,
to: null,
msg: null
}
};
$scope.loaded = {
moreMessages: false
};
/*
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| Events
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
$scope.createChat = function(user)
{
var priv = 1;
var chatExist = false;
// Se busca el chat
$scope.chats.forEach(function(chat, index){
// Si el chat ya existe
if (chat.type == priv && chat.to[0].id == user.id) {
// Se cargan los mensajes
$scope.loadMessages(chat, index, user);
chatExist = true;
return false;
}
});
// Si el chat no existe
if (!chatExist) {
var participants = [$rootScope.user.id, user.id];
// Se crea el chat en la base de datos
restFulService.post('chat/createPrivate', participants)
.then(function(response){
// Se agrega el chat al array chats
$scope.chats.unshift(response.data);
// Se cargan los mensajes
$scope.loadMessages(response.data, 0, user);
});
}
};
$scope.loadMessages = function(chat, index, user)
{
$scope.chat.index = index;
$scope.chat.name = chat.to[0].name;
$scope.chat.avatar = user.avatar;
$scope.contacts.forEach(function(contact){
if (contact.id == chat.to[0].id) {
$scope.chat.logged = contact.logged;
}
});
$scope.chat.message.chatId = chat.id;
$scope.chat.message.from = $rootScope.user.id;
$scope.chat.message.to = [{userId: chat.to[0].id, read:false}];
// Se obtienen los mensajes del chat no leidos mas otros mas
restFulSocketService.post('chatMessage/messages', { id: chat.id, userId: $rootScope.user.id, noRead: chat.noRead })
.then(function(response){
$scope.chats[index].lastMessages = response.data;
$scope.chat.messages = response.data;
if (response.data.length == 15) {
$scope.chat.existMoreMessages = true;
} else {
$scope.chat.existMoreMessages = false;
}
$scope.chat.open = true;
$scope.chat.focus = true;
});
};
$scope.loadMoreMessages = function()
{
$scope.loaded.moreMessages = true;
// Se obtienen mas mensajes del chat seleccionado
restFulSocketService.post('chatMessage/moremessages', { id: $scope.chat.message.chatId, skip: $scope.chat.messages.length })
.then(function(response){
if (response.data.length) {
$scope.chat.messages = $scope.chat.messages.concat(response.data);
} else {
$scope.chat.existMoreMessages = false;
}
$scope.loaded.moreMessages = false;
});
};
$scope.sendMesssage = function()
{
if ($scope.chat.message.msg !== null && $scope.chat.message.msg !== '') {
restFulSocketService.post('chatMessage/create', $scope.chat.message)
.then(function(response){
$scope.chat.messages.unshift(response.data);
$scope.chat.message.msg = null;
});
}
$scope.chat.focus = true;
};
$scope.clearMessages = function()
{
$scope.chat.name = null;
$scope.chat.avatar = null;
$scope.chat.logged = false;
$scope.chat.message.chatId = null;
$scope.chat.message.to = null;
$scope.chat.messages = [];
$scope.chat.focus = false;
$scope.chat.open = false;
};
$scope.markReadMessages = function()
{
if ($scope.chats[$scope.chat.index].noRead > 0) {
// Se marcan los mensajes como leidos
restFulSocketService.post('chatMessage/markRead', { id: $scope.chat.message.chatId, userId: $rootScope.user.id })
.then(function(response){
$scope.chats[$scope.chat.index].noRead = 0;
$scope.$parent.notifications.chat--;
});
}
};
/**
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* Methods
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
function getChats()
{
restFulSocketService.get('chat/chats')
.then(function (response) {
$scope.chats = response.data;
$scope.$parent.notifications.chat = response.notifications;
});
}
function getChat(chatId)
{
restFulSocketService.get('chat/chat/' + chatId)
.then(function (response) {
$scope.chats.push(response.data);
$scope.$parent.notifications.chat++;
});
}
function getChatContacts()
{
restFulSocketService.get('user/chatContacts')
.then(function (response) {
$scope.contacts = response;
});
}
function play()
{
$("#audio")[0].play();
}
/**
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* Watch
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
$rootScope.$watch('user', function(newValue, oldValue) {
if (newValue) {
getChats();
getChatContacts();
}
});
// Se escucha el evento user_logged es el que nos avisa si un usuario se conecta o se desconecta
$sailsSocket.subscribe('user_logged', function(response){
// Se busca el id del usuario que se conecto o desconecto
$scope.contacts.forEach(function(v) {
if (v.id == response.id) {
// Se actualiza el status(logged) del usuario
v.logged = response.logged;
// Si el usuario con el que se esta platicando se conecto o desconecto
if ($scope.chat.message.to[0].userId == response.id) {
// Se se actualiza el el status(logged) del usuario
$scope.chat.logged = response.logged;
}
return false;
}
});
});
$sailsSocket.subscribe('privateMessage', function(response){
var chatExist = false;
// Si existen chats
if ($scope.chats.length) {
// Se suma la notificacion al chat que nos envio el mensaje
$scope.chats.forEach(function(chat) {
// Si el chat existe
if (chat.id == response.data.chatId) {
// Se inserta el mensaje en lastMessages
chat.lastMessages.unshift(response.data);
// Se suman un mensaje no leido
chat.noRead++;
// Si es el primer mensaje no leido
if (chat.noRead<=1) {
// Se suma un chat no leido a las notificaciones globales
$scope.$parent.notifications.chat++;
}
chatExist = true;
return false;
}
});
// Si el chat no existe
if (!chatExist) {
// Se obtiene el chat y se agrega en chats
getChat(response.data.chatId);
}
// Si no existen chats
} else {
// Se obtiene el chat y se agrega en chats
getChat(response.data.chatId);
}
play();
});
}]);
}());
|
modulr/modulr
|
app/app/modules/chat/chat.controller.js
|
JavaScript
|
mit
| 7,637
|
(function(){
'use strict';
angular
.module('users')
.controller('EmailChangeCtrl', ['$rootScope', '$scope', '$state', '$location', '$translate', 'restFulService', 'config', 'errorService', function($rootScope, $scope, $state, $location, $translate, restFulService, config, errorService){
$scope.show = {
message: false
};
// Si falta alguno de los 3 parametros
if ($state.params.token === '' || $state.params.tokenId === '' || $state.params.userId === '')
$location.path('error');
// Se valida que el token exista en la DB
restFulService.get('emailChange/validate/' + $state.params.token +'/'+ $state.params.tokenId +'/'+ $state.params.userId)
.then(function(response){
$scope.email = response.email;
$rootScope.user.email = response.email;
$scope.show.message = true;
})
.catch(function(err){
$location.path('error/' + err.status);
});
}]);
}());
|
modulr/modulr
|
app/app/modules/profile/emailChange.controller.js
|
JavaScript
|
mit
| 940
|
//
// TNTHttpConnection+SyntaticSugar.h
// NitroConnection
//
// Created by Daniel L. Alves on 05/08/14.
// Copyright (c) 2014 Daniel L. Alves. All rights reserved.
//
#import "TNTHttpConnection.h"
// NitroConnection
#import "TNTHttpMethods.h"
@interface TNTHttpConnection( SyntaticSugar )
/**
* @name HTTP GET Syntatic Sugar Methods
*/
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP GET managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP GET managed request.
*/
+( instancetype )get:( NSString * )url delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP GET managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP GET managed request.
*/
+( instancetype )get:( NSString * )url onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP GET managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its query string. All keys and
* values will be escaped. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP GET managed request.
*/
+( instancetype )get:( NSString * )url params:( NSDictionary * )params delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP GET managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its query string. All keys and
* values will be escaped. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP GET managed request.
*/
+( instancetype )get:( NSString * )url params:( NSDictionary * )params onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP GET managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP GET managed request.
*/
+( instancetype )get:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP GET managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP GET managed request.
*/
+( instancetype )get:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP GET managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP GET managed request.
*/
+( instancetype )get:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers delegate:( id< TNTHttpConnectionDelegate > )delegate;
/*
* Returns a new TNTHttpConnection with an already configured and started HTTP GET managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP GET managed request.
*/
+( instancetype )get:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP GET unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP GET unmanaged request.
*/
+( instancetype )unmanagedGet:( NSString * )url delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP GET unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP GET unmanaged request.
*/
+( instancetype )unmanagedGet:( NSString * )url onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP GET unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its query string. All keys and
* values will be escaped. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP GET unmanaged request.
*/
+( instancetype )unmanagedGet:( NSString * )url params:( NSDictionary * )params delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP GET unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its query string. All keys and
* values will be escaped. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP GET unmanaged request.
*/
+( instancetype )unmanagedGet:( NSString * )url params:( NSDictionary * )params onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP GET unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP GET unmanaged request.
*/
+( instancetype )unmanagedGet:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP GET unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP GET unmanaged request.
*/
+( instancetype )unmanagedGet:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP GET unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP GET unmanaged request.
*/
+( instancetype )unmanagedGet:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP GET unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP GET unmanaged request.
*/
+( instancetype )unmanagedGet:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* @name HTTP HEAD Syntatic Sugar Methods
*/
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP HEAD managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP HEAD managed request.
*/
+( instancetype )head:( NSString * )url delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP HEAD managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP HEAD managed request.
*/
+( instancetype )head:( NSString * )url onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP HEAD managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its query string. All keys and
* values will be escaped. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP HEAD managed request.
*/
+( instancetype )head:( NSString * )url params:( NSDictionary * )params delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP HEAD managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its query string. All keys and
* values will be escaped. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP HEAD managed request.
*/
+( instancetype )head:( NSString * )url params:( NSDictionary * )params onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP HEAD managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP HEAD managed request.
*/
+( instancetype )head:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP HEAD managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP HEAD managed request.
*/
+( instancetype )head:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP HEAD managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP HEAD managed request.
*/
+( instancetype )head:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers delegate:( id< TNTHttpConnectionDelegate > )delegate;
/*
* Returns a new TNTHttpConnection with an already configured and started HTTP HEAD managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP HEAD managed request.
*/
+( instancetype )head:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP HEAD unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP HEAD unmanaged request.
*/
+( instancetype )unmanagedHead:( NSString * )url delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP HEAD unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP HEAD unmanaged request.
*/
+( instancetype )unmanagedHead:( NSString * )url onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP HEAD unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its query string. All keys and
* values will be escaped. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP HEAD unmanaged request.
*/
+( instancetype )unmanagedHead:( NSString * )url params:( NSDictionary * )params delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP HEAD unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its query string. All keys and
* values will be escaped. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP HEAD unmanaged request.
*/
+( instancetype )unmanagedHead:( NSString * )url params:( NSDictionary * )params onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP HEAD unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP HEAD unmanaged request.
*/
+( instancetype )unmanagedHead:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP HEAD unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP HEAD unmanaged request.
*/
+( instancetype )unmanagedHead:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP HEAD unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP HEAD unmanaged request.
*/
+( instancetype )unmanagedHead:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP HEAD unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP HEAD unmanaged request.
*/
+( instancetype )unmanagedHead:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* @name HTTP DELETE Syntatic Sugar Methods
*/
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP DELETE managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP DELETE managed request.
*/
+( instancetype )delete:( NSString * )url delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP DELETE managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP DELETE managed request.
*/
+( instancetype )delete:( NSString * )url onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP DELETE managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its query string. All keys and
* values will be escaped. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP DELETE managed request.
*/
+( instancetype )delete:( NSString * )url params:( NSDictionary * )params delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP DELETE managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its query string. All keys and
* values will be escaped. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP DELETE managed request.
*/
+( instancetype )delete:( NSString * )url params:( NSDictionary * )params onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP DELETE managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP DELETE managed request.
*/
+( instancetype )delete:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP DELETE managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP DELETE managed request.
*/
+( instancetype )delete:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP DELETE managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP DELETE managed request.
*/
+( instancetype )delete:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers delegate:( id< TNTHttpConnectionDelegate > )delegate;
/*
* Returns a new TNTHttpConnection with an already configured and started HTTP DELETE managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP DELETE managed request.
*/
+( instancetype )delete:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP DELETE unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP DELETE unmanaged request.
*/
+( instancetype )unmanagedDelete:( NSString * )url delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP DELETE unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP DELETE unmanaged request.
*/
+( instancetype )unmanagedDelete:( NSString * )url onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP DELETE unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its query string. All keys and
* values will be escaped. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP DELETE unmanaged request.
*/
+( instancetype )unmanagedDelete:( NSString * )url params:( NSDictionary * )params delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP DELETE unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its query string. All keys and
* values will be escaped. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP DELETE unmanaged request.
*/
+( instancetype )unmanagedDelete:( NSString * )url params:( NSDictionary * )params onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP DELETE unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP DELETE unmanaged request.
*/
+( instancetype )unmanagedDelete:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP DELETE unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP DELETE unmanaged request.
*/
+( instancetype )unmanagedDelete:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP DELETE unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP DELETE unmanaged request.
*/
+( instancetype )unmanagedDelete:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP DELETE unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP DELETE unmanaged request.
*/
+( instancetype )unmanagedDelete:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* @name HTTP POST Syntatic Sugar Methods
*/
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP POST managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP POST managed request.
*/
+( instancetype )post:( NSString * )url delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP POST managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP POST managed request.
*/
+( instancetype )post:( NSString * )url onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP POST managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its body. All keys and
* values will be escaped. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP POST managed request.
*/
+( instancetype )post:( NSString * )url params:( NSDictionary * )params delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP POST managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its body. All keys and
* values will be escaped. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP POST managed request.
*/
+( instancetype )post:( NSString * )url params:( NSDictionary * )params onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP POST managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP POST managed request.
*/
+( instancetype )post:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP POST managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP POST managed request.
*/
+( instancetype )post:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP POST managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP POST managed request.
*/
+( instancetype )post:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers delegate:( id< TNTHttpConnectionDelegate > )delegate;
/*
* Returns a new TNTHttpConnection with an already configured and started HTTP POST managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP POST managed request.
*/
+( instancetype )post:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP POST unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP POST unmanaged request.
*/
+( instancetype )unmanagedPost:( NSString * )url delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP POST unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP POST unmanaged request.
*/
+( instancetype )unmanagedPost:( NSString * )url onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP POST unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its body. All keys and
* values will be escaped. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP POST unmanaged request.
*/
+( instancetype )unmanagedPost:( NSString * )url params:( NSDictionary * )params delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP POST unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its body. All keys and
* values will be escaped. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP POST unmanaged request.
*/
+( instancetype )unmanagedPost:( NSString * )url params:( NSDictionary * )params onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP POST unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP POST unmanaged request.
*/
+( instancetype )unmanagedPost:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP POST unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP POST unmanaged request.
*/
+( instancetype )unmanagedPost:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP POST unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP POST unmanaged request.
*/
+( instancetype )unmanagedPost:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP POST unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP POST unmanaged request.
*/
+( instancetype )unmanagedPost:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* @name HTTP PUT Syntatic Sugar Methods
*/
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PUT managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PUT managed request.
*/
+( instancetype )put:( NSString * )url delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PUT managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PUT managed request.
*/
+( instancetype )put:( NSString * )url onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PUT managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its body. All keys and
* values will be escaped. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PUT managed request.
*/
+( instancetype )put:( NSString * )url params:( NSDictionary * )params delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PUT managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its body. All keys and
* values will be escaped. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PUT managed request.
*/
+( instancetype )put:( NSString * )url params:( NSDictionary * )params onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PUT managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PUT managed request.
*/
+( instancetype )put:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PUT managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PUT managed request.
*/
+( instancetype )put:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PUT managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PUT managed request.
*/
+( instancetype )put:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers delegate:( id< TNTHttpConnectionDelegate > )delegate;
/*
* Returns a new TNTHttpConnection with an already configured and started HTTP PUT managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PUT managed request.
*/
+( instancetype )put:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PUT unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PUT unmanaged request.
*/
+( instancetype )unmanagedPut:( NSString * )url delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PUT unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PUT unmanaged request.
*/
+( instancetype )unmanagedPut:( NSString * )url onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PUT unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its body. All keys and
* values will be escaped. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PUT unmanaged request.
*/
+( instancetype )unmanagedPut:( NSString * )url params:( NSDictionary * )params delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PUT unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its body. All keys and
* values will be escaped. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PUT unmanaged request.
*/
+( instancetype )unmanagedPut:( NSString * )url params:( NSDictionary * )params onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PUT unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PUT unmanaged request.
*/
+( instancetype )unmanagedPut:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PUT unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PUT unmanaged request.
*/
+( instancetype )unmanagedPut:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PUT unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PUT unmanaged request.
*/
+( instancetype )unmanagedPut:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PUT unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PUT unmanaged request.
*/
+( instancetype )unmanagedPut:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* @name HTTP PATCH Syntatic Sugar Methods
*/
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PATCH managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PATCH managed request.
*/
+( instancetype )patch:( NSString * )url delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PATCH managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PATCH managed request.
*/
+( instancetype )patch:( NSString * )url onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PATCH managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its body. All keys and
* values will be escaped. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PATCH managed request.
*/
+( instancetype )patch:( NSString * )url params:( NSDictionary * )params delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PATCH managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its body. All keys and
* values will be escaped. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PATCH managed request.
*/
+( instancetype )patch:( NSString * )url params:( NSDictionary * )params onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PATCH managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PATCH managed request.
*/
+( instancetype )patch:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PATCH managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PATCH managed request.
*/
+( instancetype )patch:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PATCH managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PATCH managed request.
*/
+( instancetype )patch:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers delegate:( id< TNTHttpConnectionDelegate > )delegate;
/*
* Returns a new TNTHttpConnection with an already configured and started HTTP PATCH managed request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PATCH managed request.
*/
+( instancetype )patch:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PATCH unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PATCH unmanaged request.
*/
+( instancetype )unmanagedPatch:( NSString * )url delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PATCH unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PATCH unmanaged request.
*/
+( instancetype )unmanagedPatch:( NSString * )url onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PATCH unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its body. All keys and
* values will be escaped. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PATCH unmanaged request.
*/
+( instancetype )unmanagedPatch:( NSString * )url params:( NSDictionary * )params delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PATCH unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param params The parameters of the request which are sent in its body. All keys and
* values will be escaped. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PATCH unmanaged request.
*/
+( instancetype )unmanagedPatch:( NSString * )url params:( NSDictionary * )params onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PATCH unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PATCH unmanaged request.
*/
+( instancetype )unmanagedPatch:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PATCH unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PATCH unmanaged request.
*/
+( instancetype )unmanagedPatch:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PATCH unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param delegate The delegate of the connection. Its callbacks will be called in the same queue
* from which this method was called. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PATCH unmanaged request.
*/
+( instancetype )unmanagedPatch:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers delegate:( id< TNTHttpConnectionDelegate > )delegate;
/**
* Returns a new TNTHttpConnection with an already configured and started HTTP PATCH unmanaged request.
*
* @param url The URL of the request. If this parameter is nil, this method does nothing.
*
* @param queryString The request query string. All keys and values will be escaped. This parameter can be nil.
*
* @param body The request body data. This parameter can be nil.
*
* @param headers HTTP headers that should be added to the request HTTP header dictionary. In keeping with
* the HTTP RFC, HTTP header field names are case-insensitive. Values are added to header fields
* incrementally. If a value was previously set for the specified field, the supplied value is
* appended to the existing value using the HTTP field delimiter, a comma. Additionally, the
* length of the upload body is determined automatically, then the value of Content-Length is set
* for you. You should not modify the following headers: Authorization, Connection, Host and
* WWW-Authenticate. This parameter can be nil.
*
* @param didStartBlock The block that will be called when the request starts. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param successBlock The block that will be called if the request succeeds. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @param errorBlock The block that will be called if the request fails. The block will be called in the same queue
* from which the request was started. This parameter can be nil.
*
* @return A new TNTHttpConnection with an already configured and started HTTP PATCH unmanaged request.
*/
+( instancetype )unmanagedPatch:( NSString * )url queryString:( NSDictionary * )queryString body:( NSData * )body headers:( NSDictionary * )headers onDidStart:( TNTHttpConnectionDidStartBlock )didStartBlock onSuccess:( TNTHttpConnectionSuccessBlock )successBlock onError:( TNTHttpConnectionErrorBlock )errorBlock;
@end
|
danielalves/NitroConnection
|
NitroConnection/NitroConnection/TNTHttpConnection+SyntaticSugar.h
|
C
|
mit
| 122,437
|
# pivotal_lab
pivotal lab from the company.
|
chrisfauerbach/pivotal_lab
|
README.md
|
Markdown
|
mit
| 45
|
---
# DO NOT EDIT!
# This file is automatically generated by get-members. If you change it, bad
# things will happen.
layout: default
title: "Lord Teverson"
house: lords
---
<div class="row">
<div class="col-md-8">
{% include members/lord-teverson.html %}
<h3>What is Lord Teverson interested in?</h3>
<p>Lord Teverson hasn't said he is interested in anything! Why not <a href="http://www.writetothem.com">write to them</a> and ask?</p>
</div>
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Party</h3>
</div>
<div class="panel-body">
<p>Lord Teverson is part of the <b>Liberal Democrat</b> party.</p>
<p class="small"><a href="{{ site.baseurl }}/glossary.html#party">What is a party?</a><p>
</div>
</div>
</div>
</div>
|
JeniT/childs-guide-to-parliament
|
members/lord-teverson.html
|
HTML
|
mit
| 944
|
/*
* Generated by class-dump 3.3.4 (64 bit).
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard.
*/
#import "UIView.h"
#import "MPVolumeControllerDelegate-Protocol.h"
@class MPVolumeController, NSTimer, UISlider;
@interface MPUMediaControlsVolumeView : UIView <MPVolumeControllerDelegate>
{
UIView *_warningView;
_Bool _warningIndicatorBlinking;
NSTimer *_warningBlinkTimer;
NSTimer *_volumeCommitTimer;
long long _style;
UISlider *_slider;
MPVolumeController *_volumeController;
}
@property(readonly, nonatomic) MPVolumeController *volumeController; // @synthesize volumeController=_volumeController;
@property(readonly, nonatomic) UISlider *slider; // @synthesize slider=_slider;
@property(readonly, nonatomic) long long style; // @synthesize style=_style;
- (void).cxx_destruct;
- (void)_stopBlinkingWarningView;
- (void)_layoutVolumeWarningView;
- (void)_blinkWarningView;
- (void)_beginBlinkingWarningView;
- (id)_warningTrackImage;
- (id)_createVolumeSliderView;
- (void)_commitCurrentVolumeValue;
- (void)_stopVolumeCommitTimer;
- (void)_beginVolumeCommitTimer;
- (void)_volumeSliderStoppedChanging:(id)arg1;
- (void)_volumeSliderValueChanged:(id)arg1;
- (void)_volumeSliderBeganChanging:(id)arg1;
- (_Bool)_shouldStartBlinkingVolumeWarningIndicator;
- (void)volumeController:(id)arg1 volumeWarningStateDidChange:(long long)arg2;
- (void)volumeController:(id)arg1 EUVolumeLimitEnforcedDidChange:(_Bool)arg2;
- (void)volumeController:(id)arg1 EUVolumeLimitDidChange:(float)arg2;
- (void)volumeController:(id)arg1 volumeValueDidChange:(float)arg2;
- (struct CGSize)sizeThatFits:(struct CGSize)arg1;
- (void)layoutSubviews;
- (void)updateSystemVolumeLevel;
- (void)dealloc;
- (id)initWithFrame:(struct CGRect)arg1;
- (id)initWithStyle:(long long)arg1;
@end
|
matthewsot/CocoaSharp
|
Headers/PrivateFrameworks/MediaPlayerUI/MPUMediaControlsVolumeView.h
|
C
|
mit
| 1,837
|
export interface Gist {
url: string;
forks_url: string;
commits_url: string;
id: string;
node_id: string;
git_pull_url: string;
git_push_url: string;
html_url: string;
files: any;
public: boolean;
created_at: Date;
updated_at: Date;
description: string;
comments: number;
user?: any;
comments_url: string;
owner: Owner;
truncated: boolean;
}
export interface Owner {
login: string;
id: number;
node_id: string;
avatar_url: string;
gravatar_id: string;
url: string;
html_url: string;
followers_url: string;
following_url: string;
gists_url: string;
starred_url: string;
subscriptions_url: string;
organizations_url: string;
repos_url: string;
events_url: string;
received_events_url: string;
type: string;
site_admin: boolean;
}
|
atangeman/portfolio-angular
|
src/app/gists/gist.model.ts
|
TypeScript
|
mit
| 875
|
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES * * */
var disqus_shortname = 'gjdanis';
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments powered by Disqus.</a></noscript>
|
gjdanis/gjdanis.github.io
|
_includes/comments.html
|
HTML
|
mit
| 659
|
<?php
$title = get_sub_field('title');
global $b;
$id = $b - 1;
$image = get_sub_field('image');
$size = 'large';
$image_url = $image['sizes'][ $size ];
$type = get_sub_field('type');
$conditions = get_sub_field('conditions');
$crowd = get_sub_field('crowd');
$info = get_sub_field('info');
$post_object = get_sub_field('surf_spot');
?>
<article class="spots" id="<?php echo $id;?>" >
<?php if ($image):?>
<header class="image-box" style="background-image:url('<?php echo $image_url;?>')">
<section class="content" >
<h1 class="white"><?php echo $title ?></h1>
</section>
</header>
<?php else:?>
<header class="image-box image-box--noborder">
<section class="content" >
<h1 class="white"><?php echo $title ?></h1>
</section>
</header>
<?php endif;?>
<section class="meta">
<?php if ($type):?>
<h3 class="white">Type</h3>
<?php echo $type ?>
<?php endif;?>
</section>
<?php
if( $post_object ):
$post = $post_object;
setup_postdata( $post );
?>
<a class="spot-link" href="<?php the_permalink();?>" title="Olá Onda Ericeira - Surfspot Guide - <?php the_title();?>">
<h3 class="white">Want to know more?</h3>
<p>Read here</p>
</a>
<?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
<?php endif;?>
</article>
|
broezer/olaonda
|
templates/parts/spot.php
|
PHP
|
mit
| 1,374
|
// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/v8.h"
#include "src/accessors.h"
#include "src/api.h"
#include "src/base/platform/platform.h"
#include "src/bootstrapper.h"
#include "src/deoptimizer.h"
#include "src/execution.h"
#include "src/global-handles.h"
#include "src/ic-inl.h"
#include "src/natives.h"
#include "src/objects.h"
#include "src/runtime.h"
#include "src/serialize.h"
#include "src/snapshot.h"
#include "src/snapshot-source-sink.h"
#include "src/stub-cache.h"
#include "src/v8threads.h"
#include "src/version.h"
namespace v8 {
namespace internal {
// -----------------------------------------------------------------------------
// Coding of external references.
// The encoding of an external reference. The type is in the high word.
// The id is in the low word.
static uint32_t EncodeExternal(TypeCode type, uint16_t id) {
return static_cast<uint32_t>(type) << 16 | id;
}
static int* GetInternalPointer(StatsCounter* counter) {
// All counters refer to dummy_counter, if deserializing happens without
// setting up counters.
static int dummy_counter = 0;
return counter->Enabled() ? counter->GetInternalPointer() : &dummy_counter;
}
ExternalReferenceTable* ExternalReferenceTable::instance(Isolate* isolate) {
ExternalReferenceTable* external_reference_table =
isolate->external_reference_table();
if (external_reference_table == NULL) {
external_reference_table = new ExternalReferenceTable(isolate);
isolate->set_external_reference_table(external_reference_table);
}
return external_reference_table;
}
void ExternalReferenceTable::AddFromId(TypeCode type,
uint16_t id,
const char* name,
Isolate* isolate) {
Address address;
switch (type) {
case C_BUILTIN: {
ExternalReference ref(static_cast<Builtins::CFunctionId>(id), isolate);
address = ref.address();
break;
}
case BUILTIN: {
ExternalReference ref(static_cast<Builtins::Name>(id), isolate);
address = ref.address();
break;
}
case RUNTIME_FUNCTION: {
ExternalReference ref(static_cast<Runtime::FunctionId>(id), isolate);
address = ref.address();
break;
}
case IC_UTILITY: {
ExternalReference ref(IC_Utility(static_cast<IC::UtilityId>(id)),
isolate);
address = ref.address();
break;
}
default:
UNREACHABLE();
return;
}
Add(address, type, id, name);
}
void ExternalReferenceTable::Add(Address address,
TypeCode type,
uint16_t id,
const char* name) {
DCHECK_NE(NULL, address);
ExternalReferenceEntry entry;
entry.address = address;
entry.code = EncodeExternal(type, id);
entry.name = name;
DCHECK_NE(0, entry.code);
refs_.Add(entry);
if (id > max_id_[type]) max_id_[type] = id;
}
void ExternalReferenceTable::PopulateTable(Isolate* isolate) {
for (int type_code = 0; type_code < kTypeCodeCount; type_code++) {
max_id_[type_code] = 0;
}
// The following populates all of the different type of external references
// into the ExternalReferenceTable.
//
// NOTE: This function was originally 100k of code. It has since been
// rewritten to be mostly table driven, as the callback macro style tends to
// very easily cause code bloat. Please be careful in the future when adding
// new references.
struct RefTableEntry {
TypeCode type;
uint16_t id;
const char* name;
};
static const RefTableEntry ref_table[] = {
// Builtins
#define DEF_ENTRY_C(name, ignored) \
{ C_BUILTIN, \
Builtins::c_##name, \
"Builtins::" #name },
BUILTIN_LIST_C(DEF_ENTRY_C)
#undef DEF_ENTRY_C
#define DEF_ENTRY_C(name, ignored) \
{ BUILTIN, \
Builtins::k##name, \
"Builtins::" #name },
#define DEF_ENTRY_A(name, kind, state, extra) DEF_ENTRY_C(name, ignored)
BUILTIN_LIST_C(DEF_ENTRY_C)
BUILTIN_LIST_A(DEF_ENTRY_A)
BUILTIN_LIST_DEBUG_A(DEF_ENTRY_A)
#undef DEF_ENTRY_C
#undef DEF_ENTRY_A
// Runtime functions
#define RUNTIME_ENTRY(name, nargs, ressize) \
{ RUNTIME_FUNCTION, \
Runtime::k##name, \
"Runtime::" #name },
RUNTIME_FUNCTION_LIST(RUNTIME_ENTRY)
INLINE_OPTIMIZED_FUNCTION_LIST(RUNTIME_ENTRY)
#undef RUNTIME_ENTRY
#define INLINE_OPTIMIZED_ENTRY(name, nargs, ressize) \
{ RUNTIME_FUNCTION, \
Runtime::kInlineOptimized##name, \
"Runtime::" #name },
INLINE_OPTIMIZED_FUNCTION_LIST(INLINE_OPTIMIZED_ENTRY)
#undef INLINE_OPTIMIZED_ENTRY
// IC utilities
#define IC_ENTRY(name) \
{ IC_UTILITY, \
IC::k##name, \
"IC::" #name },
IC_UTIL_LIST(IC_ENTRY)
#undef IC_ENTRY
}; // end of ref_table[].
for (size_t i = 0; i < ARRAY_SIZE(ref_table); ++i) {
AddFromId(ref_table[i].type,
ref_table[i].id,
ref_table[i].name,
isolate);
}
// Stat counters
struct StatsRefTableEntry {
StatsCounter* (Counters::*counter)();
uint16_t id;
const char* name;
};
const StatsRefTableEntry stats_ref_table[] = {
#define COUNTER_ENTRY(name, caption) \
{ &Counters::name, \
Counters::k_##name, \
"Counters::" #name },
STATS_COUNTER_LIST_1(COUNTER_ENTRY)
STATS_COUNTER_LIST_2(COUNTER_ENTRY)
#undef COUNTER_ENTRY
}; // end of stats_ref_table[].
Counters* counters = isolate->counters();
for (size_t i = 0; i < ARRAY_SIZE(stats_ref_table); ++i) {
Add(reinterpret_cast<Address>(GetInternalPointer(
(counters->*(stats_ref_table[i].counter))())),
STATS_COUNTER,
stats_ref_table[i].id,
stats_ref_table[i].name);
}
// Top addresses
const char* AddressNames[] = {
#define BUILD_NAME_LITERAL(CamelName, hacker_name) \
"Isolate::" #hacker_name "_address",
FOR_EACH_ISOLATE_ADDRESS_NAME(BUILD_NAME_LITERAL)
NULL
#undef BUILD_NAME_LITERAL
};
for (uint16_t i = 0; i < Isolate::kIsolateAddressCount; ++i) {
Add(isolate->get_address_from_id((Isolate::AddressId)i),
TOP_ADDRESS, i, AddressNames[i]);
}
// Accessors
#define ACCESSOR_INFO_DECLARATION(name) \
Add(FUNCTION_ADDR(&Accessors::name##Getter), \
ACCESSOR, \
Accessors::k##name##Getter, \
"Accessors::" #name "Getter"); \
Add(FUNCTION_ADDR(&Accessors::name##Setter), \
ACCESSOR, \
Accessors::k##name##Setter, \
"Accessors::" #name "Setter");
ACCESSOR_INFO_LIST(ACCESSOR_INFO_DECLARATION)
#undef ACCESSOR_INFO_DECLARATION
StubCache* stub_cache = isolate->stub_cache();
// Stub cache tables
Add(stub_cache->key_reference(StubCache::kPrimary).address(),
STUB_CACHE_TABLE,
1,
"StubCache::primary_->key");
Add(stub_cache->value_reference(StubCache::kPrimary).address(),
STUB_CACHE_TABLE,
2,
"StubCache::primary_->value");
Add(stub_cache->map_reference(StubCache::kPrimary).address(),
STUB_CACHE_TABLE,
3,
"StubCache::primary_->map");
Add(stub_cache->key_reference(StubCache::kSecondary).address(),
STUB_CACHE_TABLE,
4,
"StubCache::secondary_->key");
Add(stub_cache->value_reference(StubCache::kSecondary).address(),
STUB_CACHE_TABLE,
5,
"StubCache::secondary_->value");
Add(stub_cache->map_reference(StubCache::kSecondary).address(),
STUB_CACHE_TABLE,
6,
"StubCache::secondary_->map");
// Runtime entries
Add(ExternalReference::delete_handle_scope_extensions(isolate).address(),
RUNTIME_ENTRY,
4,
"HandleScope::DeleteExtensions");
Add(ExternalReference::
incremental_marking_record_write_function(isolate).address(),
RUNTIME_ENTRY,
5,
"IncrementalMarking::RecordWrite");
Add(ExternalReference::store_buffer_overflow_function(isolate).address(),
RUNTIME_ENTRY,
6,
"StoreBuffer::StoreBufferOverflow");
// Miscellaneous
Add(ExternalReference::roots_array_start(isolate).address(),
UNCLASSIFIED,
3,
"Heap::roots_array_start()");
Add(ExternalReference::address_of_stack_limit(isolate).address(),
UNCLASSIFIED,
4,
"StackGuard::address_of_jslimit()");
Add(ExternalReference::address_of_real_stack_limit(isolate).address(),
UNCLASSIFIED,
5,
"StackGuard::address_of_real_jslimit()");
#ifndef V8_INTERPRETED_REGEXP
Add(ExternalReference::address_of_regexp_stack_limit(isolate).address(),
UNCLASSIFIED,
6,
"RegExpStack::limit_address()");
Add(ExternalReference::address_of_regexp_stack_memory_address(
isolate).address(),
UNCLASSIFIED,
7,
"RegExpStack::memory_address()");
Add(ExternalReference::address_of_regexp_stack_memory_size(isolate).address(),
UNCLASSIFIED,
8,
"RegExpStack::memory_size()");
Add(ExternalReference::address_of_static_offsets_vector(isolate).address(),
UNCLASSIFIED,
9,
"OffsetsVector::static_offsets_vector");
#endif // V8_INTERPRETED_REGEXP
Add(ExternalReference::new_space_start(isolate).address(),
UNCLASSIFIED,
10,
"Heap::NewSpaceStart()");
Add(ExternalReference::new_space_mask(isolate).address(),
UNCLASSIFIED,
11,
"Heap::NewSpaceMask()");
Add(ExternalReference::new_space_allocation_limit_address(isolate).address(),
UNCLASSIFIED,
14,
"Heap::NewSpaceAllocationLimitAddress()");
Add(ExternalReference::new_space_allocation_top_address(isolate).address(),
UNCLASSIFIED,
15,
"Heap::NewSpaceAllocationTopAddress()");
Add(ExternalReference::debug_break(isolate).address(),
UNCLASSIFIED,
16,
"Debug::Break()");
Add(ExternalReference::debug_step_in_fp_address(isolate).address(),
UNCLASSIFIED,
17,
"Debug::step_in_fp_addr()");
Add(ExternalReference::mod_two_doubles_operation(isolate).address(),
UNCLASSIFIED,
22,
"mod_two_doubles");
#ifndef V8_INTERPRETED_REGEXP
Add(ExternalReference::re_case_insensitive_compare_uc16(isolate).address(),
UNCLASSIFIED,
24,
"NativeRegExpMacroAssembler::CaseInsensitiveCompareUC16()");
Add(ExternalReference::re_check_stack_guard_state(isolate).address(),
UNCLASSIFIED,
25,
"RegExpMacroAssembler*::CheckStackGuardState()");
Add(ExternalReference::re_grow_stack(isolate).address(),
UNCLASSIFIED,
26,
"NativeRegExpMacroAssembler::GrowStack()");
Add(ExternalReference::re_word_character_map().address(),
UNCLASSIFIED,
27,
"NativeRegExpMacroAssembler::word_character_map");
#endif // V8_INTERPRETED_REGEXP
// Keyed lookup cache.
Add(ExternalReference::keyed_lookup_cache_keys(isolate).address(),
UNCLASSIFIED,
28,
"KeyedLookupCache::keys()");
Add(ExternalReference::keyed_lookup_cache_field_offsets(isolate).address(),
UNCLASSIFIED,
29,
"KeyedLookupCache::field_offsets()");
Add(ExternalReference::handle_scope_next_address(isolate).address(),
UNCLASSIFIED,
31,
"HandleScope::next");
Add(ExternalReference::handle_scope_limit_address(isolate).address(),
UNCLASSIFIED,
32,
"HandleScope::limit");
Add(ExternalReference::handle_scope_level_address(isolate).address(),
UNCLASSIFIED,
33,
"HandleScope::level");
Add(ExternalReference::new_deoptimizer_function(isolate).address(),
UNCLASSIFIED,
34,
"Deoptimizer::New()");
Add(ExternalReference::compute_output_frames_function(isolate).address(),
UNCLASSIFIED,
35,
"Deoptimizer::ComputeOutputFrames()");
Add(ExternalReference::address_of_min_int().address(),
UNCLASSIFIED,
36,
"LDoubleConstant::min_int");
Add(ExternalReference::address_of_one_half().address(),
UNCLASSIFIED,
37,
"LDoubleConstant::one_half");
Add(ExternalReference::isolate_address(isolate).address(),
UNCLASSIFIED,
38,
"isolate");
Add(ExternalReference::address_of_minus_zero().address(),
UNCLASSIFIED,
39,
"LDoubleConstant::minus_zero");
Add(ExternalReference::address_of_negative_infinity().address(),
UNCLASSIFIED,
40,
"LDoubleConstant::negative_infinity");
Add(ExternalReference::power_double_double_function(isolate).address(),
UNCLASSIFIED,
41,
"power_double_double_function");
Add(ExternalReference::power_double_int_function(isolate).address(),
UNCLASSIFIED,
42,
"power_double_int_function");
Add(ExternalReference::store_buffer_top(isolate).address(),
UNCLASSIFIED,
43,
"store_buffer_top");
Add(ExternalReference::address_of_canonical_non_hole_nan().address(),
UNCLASSIFIED,
44,
"canonical_nan");
Add(ExternalReference::address_of_the_hole_nan().address(),
UNCLASSIFIED,
45,
"the_hole_nan");
Add(ExternalReference::get_date_field_function(isolate).address(),
UNCLASSIFIED,
46,
"JSDate::GetField");
Add(ExternalReference::date_cache_stamp(isolate).address(),
UNCLASSIFIED,
47,
"date_cache_stamp");
Add(ExternalReference::address_of_pending_message_obj(isolate).address(),
UNCLASSIFIED,
48,
"address_of_pending_message_obj");
Add(ExternalReference::address_of_has_pending_message(isolate).address(),
UNCLASSIFIED,
49,
"address_of_has_pending_message");
Add(ExternalReference::address_of_pending_message_script(isolate).address(),
UNCLASSIFIED,
50,
"pending_message_script");
Add(ExternalReference::get_make_code_young_function(isolate).address(),
UNCLASSIFIED,
51,
"Code::MakeCodeYoung");
Add(ExternalReference::cpu_features().address(),
UNCLASSIFIED,
52,
"cpu_features");
Add(ExternalReference(Runtime::kAllocateInNewSpace, isolate).address(),
UNCLASSIFIED,
53,
"Runtime::AllocateInNewSpace");
Add(ExternalReference(Runtime::kAllocateInTargetSpace, isolate).address(),
UNCLASSIFIED,
54,
"Runtime::AllocateInTargetSpace");
Add(ExternalReference::old_pointer_space_allocation_top_address(
isolate).address(),
UNCLASSIFIED,
55,
"Heap::OldPointerSpaceAllocationTopAddress");
Add(ExternalReference::old_pointer_space_allocation_limit_address(
isolate).address(),
UNCLASSIFIED,
56,
"Heap::OldPointerSpaceAllocationLimitAddress");
Add(ExternalReference::old_data_space_allocation_top_address(
isolate).address(),
UNCLASSIFIED,
57,
"Heap::OldDataSpaceAllocationTopAddress");
Add(ExternalReference::old_data_space_allocation_limit_address(
isolate).address(),
UNCLASSIFIED,
58,
"Heap::OldDataSpaceAllocationLimitAddress");
Add(ExternalReference::allocation_sites_list_address(isolate).address(),
UNCLASSIFIED,
59,
"Heap::allocation_sites_list_address()");
Add(ExternalReference::address_of_uint32_bias().address(),
UNCLASSIFIED,
60,
"uint32_bias");
Add(ExternalReference::get_mark_code_as_executed_function(isolate).address(),
UNCLASSIFIED,
61,
"Code::MarkCodeAsExecuted");
Add(ExternalReference::is_profiling_address(isolate).address(),
UNCLASSIFIED,
62,
"CpuProfiler::is_profiling");
Add(ExternalReference::scheduled_exception_address(isolate).address(),
UNCLASSIFIED,
63,
"Isolate::scheduled_exception");
Add(ExternalReference::invoke_function_callback(isolate).address(),
UNCLASSIFIED,
64,
"InvokeFunctionCallback");
Add(ExternalReference::invoke_accessor_getter_callback(isolate).address(),
UNCLASSIFIED,
65,
"InvokeAccessorGetterCallback");
// Debug addresses
Add(ExternalReference::debug_after_break_target_address(isolate).address(),
UNCLASSIFIED,
66,
"Debug::after_break_target_address()");
Add(ExternalReference::debug_restarter_frame_function_pointer_address(
isolate).address(),
UNCLASSIFIED,
67,
"Debug::restarter_frame_function_pointer_address()");
// Add a small set of deopt entry addresses to encoder without generating the
// deopt table code, which isn't possible at deserialization time.
HandleScope scope(isolate);
for (int entry = 0; entry < kDeoptTableSerializeEntryCount; ++entry) {
Address address = Deoptimizer::GetDeoptimizationEntry(
isolate,
entry,
Deoptimizer::LAZY,
Deoptimizer::CALCULATE_ENTRY_ADDRESS);
Add(address, LAZY_DEOPTIMIZATION, entry, "lazy_deopt");
}
}
ExternalReferenceEncoder::ExternalReferenceEncoder(Isolate* isolate)
: encodings_(HashMap::PointersMatch),
isolate_(isolate) {
ExternalReferenceTable* external_references =
ExternalReferenceTable::instance(isolate_);
for (int i = 0; i < external_references->size(); ++i) {
Put(external_references->address(i), i);
}
}
uint32_t ExternalReferenceEncoder::Encode(Address key) const {
int index = IndexOf(key);
DCHECK(key == NULL || index >= 0);
return index >= 0 ?
ExternalReferenceTable::instance(isolate_)->code(index) : 0;
}
const char* ExternalReferenceEncoder::NameOfAddress(Address key) const {
int index = IndexOf(key);
return index >= 0 ? ExternalReferenceTable::instance(isolate_)->name(index)
: "<unknown>";
}
int ExternalReferenceEncoder::IndexOf(Address key) const {
if (key == NULL) return -1;
HashMap::Entry* entry =
const_cast<HashMap&>(encodings_).Lookup(key, Hash(key), false);
return entry == NULL
? -1
: static_cast<int>(reinterpret_cast<intptr_t>(entry->value));
}
void ExternalReferenceEncoder::Put(Address key, int index) {
HashMap::Entry* entry = encodings_.Lookup(key, Hash(key), true);
entry->value = reinterpret_cast<void*>(index);
}
ExternalReferenceDecoder::ExternalReferenceDecoder(Isolate* isolate)
: encodings_(NewArray<Address*>(kTypeCodeCount)),
isolate_(isolate) {
ExternalReferenceTable* external_references =
ExternalReferenceTable::instance(isolate_);
for (int type = kFirstTypeCode; type < kTypeCodeCount; ++type) {
int max = external_references->max_id(type) + 1;
encodings_[type] = NewArray<Address>(max + 1);
}
for (int i = 0; i < external_references->size(); ++i) {
Put(external_references->code(i), external_references->address(i));
}
}
ExternalReferenceDecoder::~ExternalReferenceDecoder() {
for (int type = kFirstTypeCode; type < kTypeCodeCount; ++type) {
DeleteArray(encodings_[type]);
}
DeleteArray(encodings_);
}
class CodeAddressMap: public CodeEventLogger {
public:
explicit CodeAddressMap(Isolate* isolate)
: isolate_(isolate) {
isolate->logger()->addCodeEventListener(this);
}
virtual ~CodeAddressMap() {
isolate_->logger()->removeCodeEventListener(this);
}
virtual void CodeMoveEvent(Address from, Address to) {
address_to_name_map_.Move(from, to);
}
virtual void CodeDisableOptEvent(Code* code, SharedFunctionInfo* shared) {
}
virtual void CodeDeleteEvent(Address from) {
address_to_name_map_.Remove(from);
}
const char* Lookup(Address address) {
return address_to_name_map_.Lookup(address);
}
private:
class NameMap {
public:
NameMap() : impl_(HashMap::PointersMatch) {}
~NameMap() {
for (HashMap::Entry* p = impl_.Start(); p != NULL; p = impl_.Next(p)) {
DeleteArray(static_cast<const char*>(p->value));
}
}
void Insert(Address code_address, const char* name, int name_size) {
HashMap::Entry* entry = FindOrCreateEntry(code_address);
if (entry->value == NULL) {
entry->value = CopyName(name, name_size);
}
}
const char* Lookup(Address code_address) {
HashMap::Entry* entry = FindEntry(code_address);
return (entry != NULL) ? static_cast<const char*>(entry->value) : NULL;
}
void Remove(Address code_address) {
HashMap::Entry* entry = FindEntry(code_address);
if (entry != NULL) {
DeleteArray(static_cast<char*>(entry->value));
RemoveEntry(entry);
}
}
void Move(Address from, Address to) {
if (from == to) return;
HashMap::Entry* from_entry = FindEntry(from);
DCHECK(from_entry != NULL);
void* value = from_entry->value;
RemoveEntry(from_entry);
HashMap::Entry* to_entry = FindOrCreateEntry(to);
DCHECK(to_entry->value == NULL);
to_entry->value = value;
}
private:
static char* CopyName(const char* name, int name_size) {
char* result = NewArray<char>(name_size + 1);
for (int i = 0; i < name_size; ++i) {
char c = name[i];
if (c == '\0') c = ' ';
result[i] = c;
}
result[name_size] = '\0';
return result;
}
HashMap::Entry* FindOrCreateEntry(Address code_address) {
return impl_.Lookup(code_address, ComputePointerHash(code_address), true);
}
HashMap::Entry* FindEntry(Address code_address) {
return impl_.Lookup(code_address,
ComputePointerHash(code_address),
false);
}
void RemoveEntry(HashMap::Entry* entry) {
impl_.Remove(entry->key, entry->hash);
}
HashMap impl_;
DISALLOW_COPY_AND_ASSIGN(NameMap);
};
virtual void LogRecordedBuffer(Code* code,
SharedFunctionInfo*,
const char* name,
int length) {
address_to_name_map_.Insert(code->address(), name, length);
}
NameMap address_to_name_map_;
Isolate* isolate_;
};
Deserializer::Deserializer(SnapshotByteSource* source)
: isolate_(NULL),
attached_objects_(NULL),
source_(source),
external_reference_decoder_(NULL) {
for (int i = 0; i < LAST_SPACE + 1; i++) {
reservations_[i] = kUninitializedReservation;
}
}
void Deserializer::FlushICacheForNewCodeObjects() {
PageIterator it(isolate_->heap()->code_space());
while (it.has_next()) {
Page* p = it.next();
CpuFeatures::FlushICache(p->area_start(), p->area_end() - p->area_start());
}
}
void Deserializer::Deserialize(Isolate* isolate) {
isolate_ = isolate;
DCHECK(isolate_ != NULL);
isolate_->heap()->ReserveSpace(reservations_, &high_water_[0]);
// No active threads.
DCHECK_EQ(NULL, isolate_->thread_manager()->FirstThreadStateInUse());
// No active handles.
DCHECK(isolate_->handle_scope_implementer()->blocks()->is_empty());
DCHECK_EQ(NULL, external_reference_decoder_);
external_reference_decoder_ = new ExternalReferenceDecoder(isolate);
isolate_->heap()->IterateSmiRoots(this);
isolate_->heap()->IterateStrongRoots(this, VISIT_ONLY_STRONG);
isolate_->heap()->RepairFreeListsAfterBoot();
isolate_->heap()->IterateWeakRoots(this, VISIT_ALL);
isolate_->heap()->set_native_contexts_list(
isolate_->heap()->undefined_value());
isolate_->heap()->set_array_buffers_list(
isolate_->heap()->undefined_value());
// The allocation site list is build during root iteration, but if no sites
// were encountered then it needs to be initialized to undefined.
if (isolate_->heap()->allocation_sites_list() == Smi::FromInt(0)) {
isolate_->heap()->set_allocation_sites_list(
isolate_->heap()->undefined_value());
}
isolate_->heap()->InitializeWeakObjectToCodeTable();
// Update data pointers to the external strings containing natives sources.
for (int i = 0; i < Natives::GetBuiltinsCount(); i++) {
Object* source = isolate_->heap()->natives_source_cache()->get(i);
if (!source->IsUndefined()) {
ExternalAsciiString::cast(source)->update_data_cache();
}
}
FlushICacheForNewCodeObjects();
// Issue code events for newly deserialized code objects.
LOG_CODE_EVENT(isolate_, LogCodeObjects());
LOG_CODE_EVENT(isolate_, LogCompiledFunctions());
}
void Deserializer::DeserializePartial(Isolate* isolate, Object** root) {
isolate_ = isolate;
for (int i = NEW_SPACE; i < kNumberOfSpaces; i++) {
DCHECK(reservations_[i] != kUninitializedReservation);
}
isolate_->heap()->ReserveSpace(reservations_, &high_water_[0]);
if (external_reference_decoder_ == NULL) {
external_reference_decoder_ = new ExternalReferenceDecoder(isolate);
}
DisallowHeapAllocation no_gc;
// Keep track of the code space start and end pointers in case new
// code objects were unserialized
OldSpace* code_space = isolate_->heap()->code_space();
Address start_address = code_space->top();
VisitPointer(root);
// There's no code deserialized here. If this assert fires
// then that's changed and logging should be added to notify
// the profiler et al of the new code.
CHECK_EQ(start_address, code_space->top());
}
Deserializer::~Deserializer() {
// TODO(svenpanne) Re-enable this assertion when v8 initialization is fixed.
// DCHECK(source_->AtEOF());
if (external_reference_decoder_) {
delete external_reference_decoder_;
external_reference_decoder_ = NULL;
}
if (attached_objects_) attached_objects_->Dispose();
}
// This is called on the roots. It is the driver of the deserialization
// process. It is also called on the body of each function.
void Deserializer::VisitPointers(Object** start, Object** end) {
// The space must be new space. Any other space would cause ReadChunk to try
// to update the remembered using NULL as the address.
ReadChunk(start, end, NEW_SPACE, NULL);
}
void Deserializer::RelinkAllocationSite(AllocationSite* site) {
if (isolate_->heap()->allocation_sites_list() == Smi::FromInt(0)) {
site->set_weak_next(isolate_->heap()->undefined_value());
} else {
site->set_weak_next(isolate_->heap()->allocation_sites_list());
}
isolate_->heap()->set_allocation_sites_list(site);
}
// Used to insert a deserialized internalized string into the string table.
class StringTableInsertionKey : public HashTableKey {
public:
explicit StringTableInsertionKey(String* string)
: string_(string), hash_(HashForObject(string)) {
DCHECK(string->IsInternalizedString());
}
virtual bool IsMatch(Object* string) {
// We know that all entries in a hash table had their hash keys created.
// Use that knowledge to have fast failure.
if (hash_ != HashForObject(string)) return false;
// We want to compare the content of two internalized strings here.
return string_->SlowEquals(String::cast(string));
}
virtual uint32_t Hash() V8_OVERRIDE { return hash_; }
virtual uint32_t HashForObject(Object* key) V8_OVERRIDE {
return String::cast(key)->Hash();
}
MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate)
V8_OVERRIDE {
return handle(string_, isolate);
}
String* string_;
uint32_t hash_;
};
HeapObject* Deserializer::ProcessNewObjectFromSerializedCode(HeapObject* obj) {
if (obj->IsString()) {
String* string = String::cast(obj);
// Uninitialize hash field as the hash seed may have changed.
string->set_hash_field(String::kEmptyHashField);
if (string->IsInternalizedString()) {
DisallowHeapAllocation no_gc;
HandleScope scope(isolate_);
StringTableInsertionKey key(string);
String* canonical = *StringTable::LookupKey(isolate_, &key);
string->SetForwardedInternalizedString(canonical);
return canonical;
}
}
return obj;
}
Object* Deserializer::ProcessBackRefInSerializedCode(Object* obj) {
if (obj->IsInternalizedString()) {
return String::cast(obj)->GetForwardedInternalizedString();
}
return obj;
}
// This routine writes the new object into the pointer provided and then
// returns true if the new object was in young space and false otherwise.
// The reason for this strange interface is that otherwise the object is
// written very late, which means the FreeSpace map is not set up by the
// time we need to use it to mark the space at the end of a page free.
void Deserializer::ReadObject(int space_number,
Object** write_back) {
int size = source_->GetInt() << kObjectAlignmentBits;
Address address = Allocate(space_number, size);
HeapObject* obj = HeapObject::FromAddress(address);
isolate_->heap()->OnAllocationEvent(obj, size);
Object** current = reinterpret_cast<Object**>(address);
Object** limit = current + (size >> kPointerSizeLog2);
if (FLAG_log_snapshot_positions) {
LOG(isolate_, SnapshotPositionEvent(address, source_->position()));
}
ReadChunk(current, limit, space_number, address);
// TODO(mvstanton): consider treating the heap()->allocation_sites_list()
// as a (weak) root. If this root is relocated correctly,
// RelinkAllocationSite() isn't necessary.
if (obj->IsAllocationSite()) RelinkAllocationSite(AllocationSite::cast(obj));
// Fix up strings from serialized user code.
if (deserializing_user_code()) obj = ProcessNewObjectFromSerializedCode(obj);
*write_back = obj;
#ifdef DEBUG
bool is_codespace = (space_number == CODE_SPACE);
DCHECK(obj->IsCode() == is_codespace);
#endif
}
void Deserializer::ReadChunk(Object** current,
Object** limit,
int source_space,
Address current_object_address) {
Isolate* const isolate = isolate_;
// Write barrier support costs around 1% in startup time. In fact there
// are no new space objects in current boot snapshots, so it's not needed,
// but that may change.
bool write_barrier_needed = (current_object_address != NULL &&
source_space != NEW_SPACE &&
source_space != CELL_SPACE &&
source_space != PROPERTY_CELL_SPACE &&
source_space != CODE_SPACE &&
source_space != OLD_DATA_SPACE);
while (current < limit) {
int data = source_->Get();
switch (data) {
#define CASE_STATEMENT(where, how, within, space_number) \
case where + how + within + space_number: \
STATIC_ASSERT((where & ~kPointedToMask) == 0); \
STATIC_ASSERT((how & ~kHowToCodeMask) == 0); \
STATIC_ASSERT((within & ~kWhereToPointMask) == 0); \
STATIC_ASSERT((space_number & ~kSpaceMask) == 0);
#define CASE_BODY(where, how, within, space_number_if_any) \
{ \
bool emit_write_barrier = false; \
bool current_was_incremented = false; \
int space_number = space_number_if_any == kAnyOldSpace \
? (data & kSpaceMask) \
: space_number_if_any; \
if (where == kNewObject && how == kPlain && within == kStartOfObject) { \
ReadObject(space_number, current); \
emit_write_barrier = (space_number == NEW_SPACE); \
} else { \
Object* new_object = NULL; /* May not be a real Object pointer. */ \
if (where == kNewObject) { \
ReadObject(space_number, &new_object); \
} else if (where == kRootArray) { \
int root_id = source_->GetInt(); \
new_object = isolate->heap()->roots_array_start()[root_id]; \
emit_write_barrier = isolate->heap()->InNewSpace(new_object); \
} else if (where == kPartialSnapshotCache) { \
int cache_index = source_->GetInt(); \
new_object = isolate->serialize_partial_snapshot_cache()[cache_index]; \
emit_write_barrier = isolate->heap()->InNewSpace(new_object); \
} else if (where == kExternalReference) { \
int skip = source_->GetInt(); \
current = reinterpret_cast<Object**>( \
reinterpret_cast<Address>(current) + skip); \
int reference_id = source_->GetInt(); \
Address address = external_reference_decoder_->Decode(reference_id); \
new_object = reinterpret_cast<Object*>(address); \
} else if (where == kBackref) { \
emit_write_barrier = (space_number == NEW_SPACE); \
new_object = GetAddressFromEnd(data & kSpaceMask); \
if (deserializing_user_code()) { \
new_object = ProcessBackRefInSerializedCode(new_object); \
} \
} else if (where == kBuiltin) { \
DCHECK(deserializing_user_code()); \
int builtin_id = source_->GetInt(); \
DCHECK_LE(0, builtin_id); \
DCHECK_LT(builtin_id, Builtins::builtin_count); \
Builtins::Name name = static_cast<Builtins::Name>(builtin_id); \
new_object = isolate->builtins()->builtin(name); \
emit_write_barrier = false; \
} else if (where == kAttachedReference) { \
DCHECK(deserializing_user_code()); \
int index = source_->GetInt(); \
new_object = attached_objects_->at(index); \
emit_write_barrier = isolate->heap()->InNewSpace(new_object); \
} else { \
DCHECK(where == kBackrefWithSkip); \
int skip = source_->GetInt(); \
current = reinterpret_cast<Object**>( \
reinterpret_cast<Address>(current) + skip); \
emit_write_barrier = (space_number == NEW_SPACE); \
new_object = GetAddressFromEnd(data & kSpaceMask); \
if (deserializing_user_code()) { \
new_object = ProcessBackRefInSerializedCode(new_object); \
} \
} \
if (within == kInnerPointer) { \
if (space_number != CODE_SPACE || new_object->IsCode()) { \
Code* new_code_object = reinterpret_cast<Code*>(new_object); \
new_object = \
reinterpret_cast<Object*>(new_code_object->instruction_start()); \
} else { \
DCHECK(space_number == CODE_SPACE); \
Cell* cell = Cell::cast(new_object); \
new_object = reinterpret_cast<Object*>(cell->ValueAddress()); \
} \
} \
if (how == kFromCode) { \
Address location_of_branch_data = reinterpret_cast<Address>(current); \
Assembler::deserialization_set_special_target_at( \
location_of_branch_data, \
Code::cast(HeapObject::FromAddress(current_object_address)), \
reinterpret_cast<Address>(new_object)); \
location_of_branch_data += Assembler::kSpecialTargetSize; \
current = reinterpret_cast<Object**>(location_of_branch_data); \
current_was_incremented = true; \
} else { \
*current = new_object; \
} \
} \
if (emit_write_barrier && write_barrier_needed) { \
Address current_address = reinterpret_cast<Address>(current); \
isolate->heap()->RecordWrite( \
current_object_address, \
static_cast<int>(current_address - current_object_address)); \
} \
if (!current_was_incremented) { \
current++; \
} \
break; \
}
// This generates a case and a body for the new space (which has to do extra
// write barrier handling) and handles the other spaces with 8 fall-through
// cases and one body.
#define ALL_SPACES(where, how, within) \
CASE_STATEMENT(where, how, within, NEW_SPACE) \
CASE_BODY(where, how, within, NEW_SPACE) \
CASE_STATEMENT(where, how, within, OLD_DATA_SPACE) \
CASE_STATEMENT(where, how, within, OLD_POINTER_SPACE) \
CASE_STATEMENT(where, how, within, CODE_SPACE) \
CASE_STATEMENT(where, how, within, CELL_SPACE) \
CASE_STATEMENT(where, how, within, PROPERTY_CELL_SPACE) \
CASE_STATEMENT(where, how, within, MAP_SPACE) \
CASE_BODY(where, how, within, kAnyOldSpace)
#define FOUR_CASES(byte_code) \
case byte_code: \
case byte_code + 1: \
case byte_code + 2: \
case byte_code + 3:
#define SIXTEEN_CASES(byte_code) \
FOUR_CASES(byte_code) \
FOUR_CASES(byte_code + 4) \
FOUR_CASES(byte_code + 8) \
FOUR_CASES(byte_code + 12)
#define COMMON_RAW_LENGTHS(f) \
f(1) \
f(2) \
f(3) \
f(4) \
f(5) \
f(6) \
f(7) \
f(8) \
f(9) \
f(10) \
f(11) \
f(12) \
f(13) \
f(14) \
f(15) \
f(16) \
f(17) \
f(18) \
f(19) \
f(20) \
f(21) \
f(22) \
f(23) \
f(24) \
f(25) \
f(26) \
f(27) \
f(28) \
f(29) \
f(30) \
f(31)
// We generate 15 cases and bodies that process special tags that combine
// the raw data tag and the length into one byte.
#define RAW_CASE(index) \
case kRawData + index: { \
byte* raw_data_out = reinterpret_cast<byte*>(current); \
source_->CopyRaw(raw_data_out, index * kPointerSize); \
current = \
reinterpret_cast<Object**>(raw_data_out + index * kPointerSize); \
break; \
}
COMMON_RAW_LENGTHS(RAW_CASE)
#undef RAW_CASE
// Deserialize a chunk of raw data that doesn't have one of the popular
// lengths.
case kRawData: {
int size = source_->GetInt();
byte* raw_data_out = reinterpret_cast<byte*>(current);
source_->CopyRaw(raw_data_out, size);
break;
}
SIXTEEN_CASES(kRootArrayConstants + kNoSkipDistance)
SIXTEEN_CASES(kRootArrayConstants + kNoSkipDistance + 16) {
int root_id = RootArrayConstantFromByteCode(data);
Object* object = isolate->heap()->roots_array_start()[root_id];
DCHECK(!isolate->heap()->InNewSpace(object));
*current++ = object;
break;
}
SIXTEEN_CASES(kRootArrayConstants + kHasSkipDistance)
SIXTEEN_CASES(kRootArrayConstants + kHasSkipDistance + 16) {
int root_id = RootArrayConstantFromByteCode(data);
int skip = source_->GetInt();
current = reinterpret_cast<Object**>(
reinterpret_cast<intptr_t>(current) + skip);
Object* object = isolate->heap()->roots_array_start()[root_id];
DCHECK(!isolate->heap()->InNewSpace(object));
*current++ = object;
break;
}
case kRepeat: {
int repeats = source_->GetInt();
Object* object = current[-1];
DCHECK(!isolate->heap()->InNewSpace(object));
for (int i = 0; i < repeats; i++) current[i] = object;
current += repeats;
break;
}
STATIC_ASSERT(kRootArrayNumberOfConstantEncodings ==
Heap::kOldSpaceRoots);
STATIC_ASSERT(kMaxRepeats == 13);
case kConstantRepeat:
FOUR_CASES(kConstantRepeat + 1)
FOUR_CASES(kConstantRepeat + 5)
FOUR_CASES(kConstantRepeat + 9) {
int repeats = RepeatsForCode(data);
Object* object = current[-1];
DCHECK(!isolate->heap()->InNewSpace(object));
for (int i = 0; i < repeats; i++) current[i] = object;
current += repeats;
break;
}
// Deserialize a new object and write a pointer to it to the current
// object.
ALL_SPACES(kNewObject, kPlain, kStartOfObject)
// Support for direct instruction pointers in functions. It's an inner
// pointer because it points at the entry point, not at the start of the
// code object.
CASE_STATEMENT(kNewObject, kPlain, kInnerPointer, CODE_SPACE)
CASE_BODY(kNewObject, kPlain, kInnerPointer, CODE_SPACE)
// Deserialize a new code object and write a pointer to its first
// instruction to the current code object.
ALL_SPACES(kNewObject, kFromCode, kInnerPointer)
// Find a recently deserialized object using its offset from the current
// allocation point and write a pointer to it to the current object.
ALL_SPACES(kBackref, kPlain, kStartOfObject)
ALL_SPACES(kBackrefWithSkip, kPlain, kStartOfObject)
#if defined(V8_TARGET_ARCH_MIPS) || V8_OOL_CONSTANT_POOL || \
defined(V8_TARGET_ARCH_MIPS64)
// Deserialize a new object from pointer found in code and write
// a pointer to it to the current object. Required only for MIPS or ARM
// with ool constant pool, and omitted on the other architectures because
// it is fully unrolled and would cause bloat.
ALL_SPACES(kNewObject, kFromCode, kStartOfObject)
// Find a recently deserialized code object using its offset from the
// current allocation point and write a pointer to it to the current
// object. Required only for MIPS or ARM with ool constant pool.
ALL_SPACES(kBackref, kFromCode, kStartOfObject)
ALL_SPACES(kBackrefWithSkip, kFromCode, kStartOfObject)
#endif
// Find a recently deserialized code object using its offset from the
// current allocation point and write a pointer to its first instruction
// to the current code object or the instruction pointer in a function
// object.
ALL_SPACES(kBackref, kFromCode, kInnerPointer)
ALL_SPACES(kBackrefWithSkip, kFromCode, kInnerPointer)
ALL_SPACES(kBackref, kPlain, kInnerPointer)
ALL_SPACES(kBackrefWithSkip, kPlain, kInnerPointer)
// Find an object in the roots array and write a pointer to it to the
// current object.
CASE_STATEMENT(kRootArray, kPlain, kStartOfObject, 0)
CASE_BODY(kRootArray, kPlain, kStartOfObject, 0)
// Find an object in the partial snapshots cache and write a pointer to it
// to the current object.
CASE_STATEMENT(kPartialSnapshotCache, kPlain, kStartOfObject, 0)
CASE_BODY(kPartialSnapshotCache,
kPlain,
kStartOfObject,
0)
// Find an code entry in the partial snapshots cache and
// write a pointer to it to the current object.
CASE_STATEMENT(kPartialSnapshotCache, kPlain, kInnerPointer, 0)
CASE_BODY(kPartialSnapshotCache,
kPlain,
kInnerPointer,
0)
// Find an external reference and write a pointer to it to the current
// object.
CASE_STATEMENT(kExternalReference, kPlain, kStartOfObject, 0)
CASE_BODY(kExternalReference,
kPlain,
kStartOfObject,
0)
// Find an external reference and write a pointer to it in the current
// code object.
CASE_STATEMENT(kExternalReference, kFromCode, kStartOfObject, 0)
CASE_BODY(kExternalReference,
kFromCode,
kStartOfObject,
0)
// Find a builtin and write a pointer to it to the current object.
CASE_STATEMENT(kBuiltin, kPlain, kStartOfObject, 0)
CASE_BODY(kBuiltin, kPlain, kStartOfObject, 0)
// Find a builtin and write a pointer to it in the current code object.
CASE_STATEMENT(kBuiltin, kFromCode, kInnerPointer, 0)
CASE_BODY(kBuiltin, kFromCode, kInnerPointer, 0)
// Find an object in the attached references and write a pointer to it to
// the current object.
CASE_STATEMENT(kAttachedReference, kPlain, kStartOfObject, 0)
CASE_BODY(kAttachedReference, kPlain, kStartOfObject, 0)
#undef CASE_STATEMENT
#undef CASE_BODY
#undef ALL_SPACES
case kSkip: {
int size = source_->GetInt();
current = reinterpret_cast<Object**>(
reinterpret_cast<intptr_t>(current) + size);
break;
}
case kNativesStringResource: {
int index = source_->Get();
Vector<const char> source_vector = Natives::GetRawScriptSource(index);
NativesExternalStringResource* resource =
new NativesExternalStringResource(isolate->bootstrapper(),
source_vector.start(),
source_vector.length());
*current++ = reinterpret_cast<Object*>(resource);
break;
}
case kSynchronize: {
// If we get here then that indicates that you have a mismatch between
// the number of GC roots when serializing and deserializing.
UNREACHABLE();
}
default:
UNREACHABLE();
}
}
DCHECK_EQ(limit, current);
}
Serializer::Serializer(Isolate* isolate, SnapshotByteSink* sink)
: isolate_(isolate),
sink_(sink),
external_reference_encoder_(new ExternalReferenceEncoder(isolate)),
root_index_wave_front_(0),
code_address_map_(NULL) {
// The serializer is meant to be used only to generate initial heap images
// from a context in which there is only one isolate.
for (int i = 0; i <= LAST_SPACE; i++) {
fullness_[i] = 0;
}
}
Serializer::~Serializer() {
delete external_reference_encoder_;
if (code_address_map_ != NULL) delete code_address_map_;
}
void StartupSerializer::SerializeStrongReferences() {
Isolate* isolate = this->isolate();
// No active threads.
CHECK_EQ(NULL, isolate->thread_manager()->FirstThreadStateInUse());
// No active or weak handles.
CHECK(isolate->handle_scope_implementer()->blocks()->is_empty());
CHECK_EQ(0, isolate->global_handles()->NumberOfWeakHandles());
CHECK_EQ(0, isolate->eternal_handles()->NumberOfHandles());
// We don't support serializing installed extensions.
CHECK(!isolate->has_installed_extensions());
isolate->heap()->IterateSmiRoots(this);
isolate->heap()->IterateStrongRoots(this, VISIT_ONLY_STRONG);
}
void PartialSerializer::Serialize(Object** object) {
this->VisitPointer(object);
Pad();
}
bool Serializer::ShouldBeSkipped(Object** current) {
Object** roots = isolate()->heap()->roots_array_start();
return current == &roots[Heap::kStoreBufferTopRootIndex]
|| current == &roots[Heap::kStackLimitRootIndex]
|| current == &roots[Heap::kRealStackLimitRootIndex];
}
void Serializer::VisitPointers(Object** start, Object** end) {
Isolate* isolate = this->isolate();;
for (Object** current = start; current < end; current++) {
if (start == isolate->heap()->roots_array_start()) {
root_index_wave_front_ =
Max(root_index_wave_front_, static_cast<intptr_t>(current - start));
}
if (ShouldBeSkipped(current)) {
sink_->Put(kSkip, "Skip");
sink_->PutInt(kPointerSize, "SkipOneWord");
} else if ((*current)->IsSmi()) {
sink_->Put(kRawData + 1, "Smi");
for (int i = 0; i < kPointerSize; i++) {
sink_->Put(reinterpret_cast<byte*>(current)[i], "Byte");
}
} else {
SerializeObject(*current, kPlain, kStartOfObject, 0);
}
}
}
// This ensures that the partial snapshot cache keeps things alive during GC and
// tracks their movement. When it is called during serialization of the startup
// snapshot nothing happens. When the partial (context) snapshot is created,
// this array is populated with the pointers that the partial snapshot will
// need. As that happens we emit serialized objects to the startup snapshot
// that correspond to the elements of this cache array. On deserialization we
// therefore need to visit the cache array. This fills it up with pointers to
// deserialized objects.
void SerializerDeserializer::Iterate(Isolate* isolate,
ObjectVisitor* visitor) {
if (isolate->serializer_enabled()) return;
for (int i = 0; ; i++) {
if (isolate->serialize_partial_snapshot_cache_length() <= i) {
// Extend the array ready to get a value from the visitor when
// deserializing.
isolate->PushToPartialSnapshotCache(Smi::FromInt(0));
}
Object** cache = isolate->serialize_partial_snapshot_cache();
visitor->VisitPointers(&cache[i], &cache[i + 1]);
// Sentinel is the undefined object, which is a root so it will not normally
// be found in the cache.
if (cache[i] == isolate->heap()->undefined_value()) {
break;
}
}
}
int PartialSerializer::PartialSnapshotCacheIndex(HeapObject* heap_object) {
Isolate* isolate = this->isolate();
for (int i = 0;
i < isolate->serialize_partial_snapshot_cache_length();
i++) {
Object* entry = isolate->serialize_partial_snapshot_cache()[i];
if (entry == heap_object) return i;
}
// We didn't find the object in the cache. So we add it to the cache and
// then visit the pointer so that it becomes part of the startup snapshot
// and we can refer to it from the partial snapshot.
int length = isolate->serialize_partial_snapshot_cache_length();
isolate->PushToPartialSnapshotCache(heap_object);
startup_serializer_->VisitPointer(reinterpret_cast<Object**>(&heap_object));
// We don't recurse from the startup snapshot generator into the partial
// snapshot generator.
DCHECK(length == isolate->serialize_partial_snapshot_cache_length() - 1);
return length;
}
int Serializer::RootIndex(HeapObject* heap_object, HowToCode from) {
Heap* heap = isolate()->heap();
if (heap->InNewSpace(heap_object)) return kInvalidRootIndex;
for (int i = 0; i < root_index_wave_front_; i++) {
Object* root = heap->roots_array_start()[i];
if (!root->IsSmi() && root == heap_object) {
#if defined(V8_TARGET_ARCH_MIPS) || V8_OOL_CONSTANT_POOL || \
defined(V8_TARGET_ARCH_MIPS64)
if (from == kFromCode) {
// In order to avoid code bloat in the deserializer we don't have
// support for the encoding that specifies a particular root should
// be written from within code.
return kInvalidRootIndex;
}
#endif
return i;
}
}
return kInvalidRootIndex;
}
// Encode the location of an already deserialized object in order to write its
// location into a later object. We can encode the location as an offset from
// the start of the deserialized objects or as an offset backwards from the
// current allocation pointer.
void Serializer::SerializeReferenceToPreviousObject(
int space,
int address,
HowToCode how_to_code,
WhereToPoint where_to_point,
int skip) {
int offset = CurrentAllocationAddress(space) - address;
// Shift out the bits that are always 0.
offset >>= kObjectAlignmentBits;
if (skip == 0) {
sink_->Put(kBackref + how_to_code + where_to_point + space, "BackRefSer");
} else {
sink_->Put(kBackrefWithSkip + how_to_code + where_to_point + space,
"BackRefSerWithSkip");
sink_->PutInt(skip, "BackRefSkipDistance");
}
sink_->PutInt(offset, "offset");
}
void StartupSerializer::SerializeObject(
Object* o,
HowToCode how_to_code,
WhereToPoint where_to_point,
int skip) {
CHECK(o->IsHeapObject());
HeapObject* heap_object = HeapObject::cast(o);
int root_index;
if ((root_index = RootIndex(heap_object, how_to_code)) != kInvalidRootIndex) {
PutRoot(root_index, heap_object, how_to_code, where_to_point, skip);
return;
}
if (address_mapper_.IsMapped(heap_object)) {
int space = SpaceOfObject(heap_object);
int address = address_mapper_.MappedTo(heap_object);
SerializeReferenceToPreviousObject(space,
address,
how_to_code,
where_to_point,
skip);
} else {
if (skip != 0) {
sink_->Put(kSkip, "FlushPendingSkip");
sink_->PutInt(skip, "SkipDistance");
}
// Object has not yet been serialized. Serialize it here.
ObjectSerializer object_serializer(this,
heap_object,
sink_,
how_to_code,
where_to_point);
object_serializer.Serialize();
}
}
void StartupSerializer::SerializeWeakReferences() {
// This phase comes right after the partial serialization (of the snapshot).
// After we have done the partial serialization the partial snapshot cache
// will contain some references needed to decode the partial snapshot. We
// add one entry with 'undefined' which is the sentinel that the deserializer
// uses to know it is done deserializing the array.
Object* undefined = isolate()->heap()->undefined_value();
VisitPointer(&undefined);
isolate()->heap()->IterateWeakRoots(this, VISIT_ALL);
Pad();
}
void Serializer::PutRoot(int root_index,
HeapObject* object,
SerializerDeserializer::HowToCode how_to_code,
SerializerDeserializer::WhereToPoint where_to_point,
int skip) {
if (how_to_code == kPlain &&
where_to_point == kStartOfObject &&
root_index < kRootArrayNumberOfConstantEncodings &&
!isolate()->heap()->InNewSpace(object)) {
if (skip == 0) {
sink_->Put(kRootArrayConstants + kNoSkipDistance + root_index,
"RootConstant");
} else {
sink_->Put(kRootArrayConstants + kHasSkipDistance + root_index,
"RootConstant");
sink_->PutInt(skip, "SkipInPutRoot");
}
} else {
if (skip != 0) {
sink_->Put(kSkip, "SkipFromPutRoot");
sink_->PutInt(skip, "SkipFromPutRootDistance");
}
sink_->Put(kRootArray + how_to_code + where_to_point, "RootSerialization");
sink_->PutInt(root_index, "root_index");
}
}
void PartialSerializer::SerializeObject(
Object* o,
HowToCode how_to_code,
WhereToPoint where_to_point,
int skip) {
CHECK(o->IsHeapObject());
HeapObject* heap_object = HeapObject::cast(o);
if (heap_object->IsMap()) {
// The code-caches link to context-specific code objects, which
// the startup and context serializes cannot currently handle.
DCHECK(Map::cast(heap_object)->code_cache() ==
heap_object->GetHeap()->empty_fixed_array());
}
int root_index;
if ((root_index = RootIndex(heap_object, how_to_code)) != kInvalidRootIndex) {
PutRoot(root_index, heap_object, how_to_code, where_to_point, skip);
return;
}
if (ShouldBeInThePartialSnapshotCache(heap_object)) {
if (skip != 0) {
sink_->Put(kSkip, "SkipFromSerializeObject");
sink_->PutInt(skip, "SkipDistanceFromSerializeObject");
}
int cache_index = PartialSnapshotCacheIndex(heap_object);
sink_->Put(kPartialSnapshotCache + how_to_code + where_to_point,
"PartialSnapshotCache");
sink_->PutInt(cache_index, "partial_snapshot_cache_index");
return;
}
// Pointers from the partial snapshot to the objects in the startup snapshot
// should go through the root array or through the partial snapshot cache.
// If this is not the case you may have to add something to the root array.
DCHECK(!startup_serializer_->address_mapper()->IsMapped(heap_object));
// All the internalized strings that the partial snapshot needs should be
// either in the root table or in the partial snapshot cache.
DCHECK(!heap_object->IsInternalizedString());
if (address_mapper_.IsMapped(heap_object)) {
int space = SpaceOfObject(heap_object);
int address = address_mapper_.MappedTo(heap_object);
SerializeReferenceToPreviousObject(space,
address,
how_to_code,
where_to_point,
skip);
} else {
if (skip != 0) {
sink_->Put(kSkip, "SkipFromSerializeObject");
sink_->PutInt(skip, "SkipDistanceFromSerializeObject");
}
// Object has not yet been serialized. Serialize it here.
ObjectSerializer serializer(this,
heap_object,
sink_,
how_to_code,
where_to_point);
serializer.Serialize();
}
}
void Serializer::ObjectSerializer::Serialize() {
int space = Serializer::SpaceOfObject(object_);
int size = object_->Size();
sink_->Put(kNewObject + reference_representation_ + space,
"ObjectSerialization");
sink_->PutInt(size >> kObjectAlignmentBits, "Size in words");
if (serializer_->code_address_map_) {
const char* code_name =
serializer_->code_address_map_->Lookup(object_->address());
LOG(serializer_->isolate_,
CodeNameEvent(object_->address(), sink_->Position(), code_name));
LOG(serializer_->isolate_,
SnapshotPositionEvent(object_->address(), sink_->Position()));
}
// Mark this object as already serialized.
int offset = serializer_->Allocate(space, size);
serializer_->address_mapper()->AddMapping(object_, offset);
// Serialize the map (first word of the object).
serializer_->SerializeObject(object_->map(), kPlain, kStartOfObject, 0);
// Serialize the rest of the object.
CHECK_EQ(0, bytes_processed_so_far_);
bytes_processed_so_far_ = kPointerSize;
object_->IterateBody(object_->map()->instance_type(), size, this);
OutputRawData(object_->address() + size);
}
void Serializer::ObjectSerializer::VisitPointers(Object** start,
Object** end) {
Object** current = start;
while (current < end) {
while (current < end && (*current)->IsSmi()) current++;
if (current < end) OutputRawData(reinterpret_cast<Address>(current));
while (current < end && !(*current)->IsSmi()) {
HeapObject* current_contents = HeapObject::cast(*current);
int root_index = serializer_->RootIndex(current_contents, kPlain);
// Repeats are not subject to the write barrier so there are only some
// objects that can be used in a repeat encoding. These are the early
// ones in the root array that are never in new space.
if (current != start &&
root_index != kInvalidRootIndex &&
root_index < kRootArrayNumberOfConstantEncodings &&
current_contents == current[-1]) {
DCHECK(!serializer_->isolate()->heap()->InNewSpace(current_contents));
int repeat_count = 1;
while (current < end - 1 && current[repeat_count] == current_contents) {
repeat_count++;
}
current += repeat_count;
bytes_processed_so_far_ += repeat_count * kPointerSize;
if (repeat_count > kMaxRepeats) {
sink_->Put(kRepeat, "SerializeRepeats");
sink_->PutInt(repeat_count, "SerializeRepeats");
} else {
sink_->Put(CodeForRepeats(repeat_count), "SerializeRepeats");
}
} else {
serializer_->SerializeObject(
current_contents, kPlain, kStartOfObject, 0);
bytes_processed_so_far_ += kPointerSize;
current++;
}
}
}
}
void Serializer::ObjectSerializer::VisitEmbeddedPointer(RelocInfo* rinfo) {
// Out-of-line constant pool entries will be visited by the ConstantPoolArray.
if (FLAG_enable_ool_constant_pool && rinfo->IsInConstantPool()) return;
int skip = OutputRawData(rinfo->target_address_address(),
kCanReturnSkipInsteadOfSkipping);
HowToCode how_to_code = rinfo->IsCodedSpecially() ? kFromCode : kPlain;
Object* object = rinfo->target_object();
serializer_->SerializeObject(object, how_to_code, kStartOfObject, skip);
bytes_processed_so_far_ += rinfo->target_address_size();
}
void Serializer::ObjectSerializer::VisitExternalReference(Address* p) {
int skip = OutputRawData(reinterpret_cast<Address>(p),
kCanReturnSkipInsteadOfSkipping);
sink_->Put(kExternalReference + kPlain + kStartOfObject, "ExternalRef");
sink_->PutInt(skip, "SkipB4ExternalRef");
Address target = *p;
sink_->PutInt(serializer_->EncodeExternalReference(target), "reference id");
bytes_processed_so_far_ += kPointerSize;
}
void Serializer::ObjectSerializer::VisitExternalReference(RelocInfo* rinfo) {
int skip = OutputRawData(rinfo->target_address_address(),
kCanReturnSkipInsteadOfSkipping);
HowToCode how_to_code = rinfo->IsCodedSpecially() ? kFromCode : kPlain;
sink_->Put(kExternalReference + how_to_code + kStartOfObject, "ExternalRef");
sink_->PutInt(skip, "SkipB4ExternalRef");
Address target = rinfo->target_reference();
sink_->PutInt(serializer_->EncodeExternalReference(target), "reference id");
bytes_processed_so_far_ += rinfo->target_address_size();
}
void Serializer::ObjectSerializer::VisitRuntimeEntry(RelocInfo* rinfo) {
int skip = OutputRawData(rinfo->target_address_address(),
kCanReturnSkipInsteadOfSkipping);
HowToCode how_to_code = rinfo->IsCodedSpecially() ? kFromCode : kPlain;
sink_->Put(kExternalReference + how_to_code + kStartOfObject, "ExternalRef");
sink_->PutInt(skip, "SkipB4ExternalRef");
Address target = rinfo->target_address();
sink_->PutInt(serializer_->EncodeExternalReference(target), "reference id");
bytes_processed_so_far_ += rinfo->target_address_size();
}
void Serializer::ObjectSerializer::VisitCodeTarget(RelocInfo* rinfo) {
// Out-of-line constant pool entries will be visited by the ConstantPoolArray.
if (FLAG_enable_ool_constant_pool && rinfo->IsInConstantPool()) return;
int skip = OutputRawData(rinfo->target_address_address(),
kCanReturnSkipInsteadOfSkipping);
Code* object = Code::GetCodeFromTargetAddress(rinfo->target_address());
serializer_->SerializeObject(object, kFromCode, kInnerPointer, skip);
bytes_processed_so_far_ += rinfo->target_address_size();
}
void Serializer::ObjectSerializer::VisitCodeEntry(Address entry_address) {
int skip = OutputRawData(entry_address, kCanReturnSkipInsteadOfSkipping);
Code* object = Code::cast(Code::GetObjectFromEntryAddress(entry_address));
serializer_->SerializeObject(object, kPlain, kInnerPointer, skip);
bytes_processed_so_far_ += kPointerSize;
}
void Serializer::ObjectSerializer::VisitCell(RelocInfo* rinfo) {
// Out-of-line constant pool entries will be visited by the ConstantPoolArray.
if (FLAG_enable_ool_constant_pool && rinfo->IsInConstantPool()) return;
int skip = OutputRawData(rinfo->pc(), kCanReturnSkipInsteadOfSkipping);
Cell* object = Cell::cast(rinfo->target_cell());
serializer_->SerializeObject(object, kPlain, kInnerPointer, skip);
}
void Serializer::ObjectSerializer::VisitExternalAsciiString(
v8::String::ExternalAsciiStringResource** resource_pointer) {
Address references_start = reinterpret_cast<Address>(resource_pointer);
OutputRawData(references_start);
for (int i = 0; i < Natives::GetBuiltinsCount(); i++) {
Object* source =
serializer_->isolate()->heap()->natives_source_cache()->get(i);
if (!source->IsUndefined()) {
ExternalAsciiString* string = ExternalAsciiString::cast(source);
typedef v8::String::ExternalAsciiStringResource Resource;
const Resource* resource = string->resource();
if (resource == *resource_pointer) {
sink_->Put(kNativesStringResource, "NativesStringResource");
sink_->PutSection(i, "NativesStringResourceEnd");
bytes_processed_so_far_ += sizeof(resource);
return;
}
}
}
// One of the strings in the natives cache should match the resource. We
// can't serialize any other kinds of external strings.
UNREACHABLE();
}
static Code* CloneCodeObject(HeapObject* code) {
Address copy = new byte[code->Size()];
MemCopy(copy, code->address(), code->Size());
return Code::cast(HeapObject::FromAddress(copy));
}
static void WipeOutRelocations(Code* code) {
int mode_mask =
RelocInfo::kCodeTargetMask |
RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT) |
RelocInfo::ModeMask(RelocInfo::EXTERNAL_REFERENCE) |
RelocInfo::ModeMask(RelocInfo::RUNTIME_ENTRY);
for (RelocIterator it(code, mode_mask); !it.done(); it.next()) {
if (!(FLAG_enable_ool_constant_pool && it.rinfo()->IsInConstantPool())) {
it.rinfo()->WipeOut();
}
}
}
int Serializer::ObjectSerializer::OutputRawData(
Address up_to, Serializer::ObjectSerializer::ReturnSkip return_skip) {
Address object_start = object_->address();
int base = bytes_processed_so_far_;
int up_to_offset = static_cast<int>(up_to - object_start);
int to_skip = up_to_offset - bytes_processed_so_far_;
int bytes_to_output = to_skip;
bytes_processed_so_far_ += to_skip;
// This assert will fail if the reloc info gives us the target_address_address
// locations in a non-ascending order. Luckily that doesn't happen.
DCHECK(to_skip >= 0);
bool outputting_code = false;
if (to_skip != 0 && code_object_ && !code_has_been_output_) {
// Output the code all at once and fix later.
bytes_to_output = object_->Size() + to_skip - bytes_processed_so_far_;
outputting_code = true;
code_has_been_output_ = true;
}
if (bytes_to_output != 0 &&
(!code_object_ || outputting_code)) {
#define RAW_CASE(index) \
if (!outputting_code && bytes_to_output == index * kPointerSize && \
index * kPointerSize == to_skip) { \
sink_->PutSection(kRawData + index, "RawDataFixed"); \
to_skip = 0; /* This insn already skips. */ \
} else /* NOLINT */
COMMON_RAW_LENGTHS(RAW_CASE)
#undef RAW_CASE
{ /* NOLINT */
// We always end up here if we are outputting the code of a code object.
sink_->Put(kRawData, "RawData");
sink_->PutInt(bytes_to_output, "length");
}
// To make snapshots reproducible, we need to wipe out all pointers in code.
if (code_object_) {
Code* code = CloneCodeObject(object_);
WipeOutRelocations(code);
// We need to wipe out the header fields *after* wiping out the
// relocations, because some of these fields are needed for the latter.
code->WipeOutHeader();
object_start = code->address();
}
const char* description = code_object_ ? "Code" : "Byte";
for (int i = 0; i < bytes_to_output; i++) {
sink_->PutSection(object_start[base + i], description);
}
if (code_object_) delete[] object_start;
}
if (to_skip != 0 && return_skip == kIgnoringReturn) {
sink_->Put(kSkip, "Skip");
sink_->PutInt(to_skip, "SkipDistance");
to_skip = 0;
}
return to_skip;
}
int Serializer::SpaceOfObject(HeapObject* object) {
for (int i = FIRST_SPACE; i <= LAST_SPACE; i++) {
AllocationSpace s = static_cast<AllocationSpace>(i);
if (object->GetHeap()->InSpace(object, s)) {
DCHECK(i < kNumberOfSpaces);
return i;
}
}
UNREACHABLE();
return 0;
}
int Serializer::Allocate(int space, int size) {
CHECK(space >= 0 && space < kNumberOfSpaces);
int allocation_address = fullness_[space];
fullness_[space] = allocation_address + size;
return allocation_address;
}
int Serializer::SpaceAreaSize(int space) {
if (space == CODE_SPACE) {
return isolate_->memory_allocator()->CodePageAreaSize();
} else {
return Page::kPageSize - Page::kObjectStartOffset;
}
}
void Serializer::Pad() {
// The non-branching GetInt will read up to 3 bytes too far, so we need
// to pad the snapshot to make sure we don't read over the end.
for (unsigned i = 0; i < sizeof(int32_t) - 1; i++) {
sink_->Put(kNop, "Padding");
}
}
void Serializer::InitializeCodeAddressMap() {
isolate_->InitializeLoggingAndCounters();
code_address_map_ = new CodeAddressMap(isolate_);
}
ScriptData* CodeSerializer::Serialize(Isolate* isolate,
Handle<SharedFunctionInfo> info,
Handle<String> source) {
// Serialize code object.
List<byte> payload;
ListSnapshotSink list_sink(&payload);
CodeSerializer cs(isolate, &list_sink, *source);
DisallowHeapAllocation no_gc;
Object** location = Handle<Object>::cast(info).location();
cs.VisitPointer(location);
cs.Pad();
SerializedCodeData data(&payload, &cs);
return data.GetScriptData();
}
void CodeSerializer::SerializeObject(Object* o, HowToCode how_to_code,
WhereToPoint where_to_point, int skip) {
CHECK(o->IsHeapObject());
HeapObject* heap_object = HeapObject::cast(o);
// The code-caches link to context-specific code objects, which
// the startup and context serializes cannot currently handle.
DCHECK(!heap_object->IsMap() ||
Map::cast(heap_object)->code_cache() ==
heap_object->GetHeap()->empty_fixed_array());
int root_index;
if ((root_index = RootIndex(heap_object, how_to_code)) != kInvalidRootIndex) {
PutRoot(root_index, heap_object, how_to_code, where_to_point, skip);
return;
}
// TODO(yangguo) wire up stubs from stub cache.
// TODO(yangguo) wire up global object.
// TODO(yangguo) We cannot deal with different hash seeds yet.
DCHECK(!heap_object->IsHashTable());
if (address_mapper_.IsMapped(heap_object)) {
int space = SpaceOfObject(heap_object);
int address = address_mapper_.MappedTo(heap_object);
SerializeReferenceToPreviousObject(space, address, how_to_code,
where_to_point, skip);
return;
}
if (heap_object->IsCode()) {
Code* code_object = Code::cast(heap_object);
if (code_object->kind() == Code::BUILTIN) {
SerializeBuiltin(code_object, how_to_code, where_to_point, skip);
return;
}
// TODO(yangguo) figure out whether other code kinds can be handled smarter.
}
if (heap_object == source_) {
SerializeSourceObject(how_to_code, where_to_point, skip);
return;
}
if (heap_object->IsScript()) {
// The wrapper cache uses a Foreign object to point to a global handle.
// However, the object visitor expects foreign objects to point to external
// references. Clear the cache to avoid this issue.
Script::cast(heap_object)->ClearWrapperCache();
}
if (skip != 0) {
sink_->Put(kSkip, "SkipFromSerializeObject");
sink_->PutInt(skip, "SkipDistanceFromSerializeObject");
}
// Object has not yet been serialized. Serialize it here.
ObjectSerializer serializer(this, heap_object, sink_, how_to_code,
where_to_point);
serializer.Serialize();
}
void CodeSerializer::SerializeBuiltin(Code* builtin, HowToCode how_to_code,
WhereToPoint where_to_point, int skip) {
if (skip != 0) {
sink_->Put(kSkip, "SkipFromSerializeBuiltin");
sink_->PutInt(skip, "SkipDistanceFromSerializeBuiltin");
}
DCHECK((how_to_code == kPlain && where_to_point == kStartOfObject) ||
(how_to_code == kFromCode && where_to_point == kInnerPointer));
int builtin_index = builtin->builtin_index();
DCHECK_LT(builtin_index, Builtins::builtin_count);
DCHECK_LE(0, builtin_index);
sink_->Put(kBuiltin + how_to_code + where_to_point, "Builtin");
sink_->PutInt(builtin_index, "builtin_index");
}
void CodeSerializer::SerializeSourceObject(HowToCode how_to_code,
WhereToPoint where_to_point,
int skip) {
if (skip != 0) {
sink_->Put(kSkip, "SkipFromSerializeSourceObject");
sink_->PutInt(skip, "SkipDistanceFromSerializeSourceObject");
}
DCHECK(how_to_code == kPlain && where_to_point == kStartOfObject);
sink_->Put(kAttachedReference + how_to_code + where_to_point, "Source");
sink_->PutInt(kSourceObjectIndex, "kSourceObjectIndex");
}
Handle<SharedFunctionInfo> CodeSerializer::Deserialize(Isolate* isolate,
ScriptData* data,
Handle<String> source) {
base::ElapsedTimer timer;
if (FLAG_profile_deserialization) timer.Start();
SerializedCodeData scd(data, *source);
SnapshotByteSource payload(scd.Payload(), scd.PayloadLength());
Deserializer deserializer(&payload);
STATIC_ASSERT(NEW_SPACE == 0);
for (int i = NEW_SPACE; i <= PROPERTY_CELL_SPACE; i++) {
deserializer.set_reservation(i, scd.GetReservation(i));
}
// Prepare and register list of attached objects.
Vector<Object*> attached_objects = Vector<Object*>::New(1);
attached_objects[kSourceObjectIndex] = *source;
deserializer.SetAttachedObjects(&attached_objects);
Object* root;
deserializer.DeserializePartial(isolate, &root);
deserializer.FlushICacheForNewCodeObjects();
if (FLAG_profile_deserialization) {
double ms = timer.Elapsed().InMillisecondsF();
int length = data->length();
PrintF("[Deserializing from %d bytes took %0.3f ms]\n", length, ms);
}
return Handle<SharedFunctionInfo>(SharedFunctionInfo::cast(root), isolate);
}
SerializedCodeData::SerializedCodeData(List<byte>* payload, CodeSerializer* cs)
: owns_script_data_(true) {
DisallowHeapAllocation no_gc;
int data_length = payload->length() + kHeaderEntries * kIntSize;
byte* data = NewArray<byte>(data_length);
DCHECK(IsAligned(reinterpret_cast<intptr_t>(data), kPointerAlignment));
CopyBytes(data + kHeaderEntries * kIntSize, payload->begin(),
static_cast<size_t>(payload->length()));
script_data_ = new ScriptData(data, data_length);
script_data_->AcquireDataOwnership();
SetHeaderValue(kCheckSumOffset, CheckSum(cs->source()));
STATIC_ASSERT(NEW_SPACE == 0);
for (int i = NEW_SPACE; i <= PROPERTY_CELL_SPACE; i++) {
SetHeaderValue(kReservationsOffset + i, cs->CurrentAllocationAddress(i));
}
}
bool SerializedCodeData::IsSane(String* source) {
return GetHeaderValue(kCheckSumOffset) == CheckSum(source) &&
PayloadLength() >= SharedFunctionInfo::kSize;
}
int SerializedCodeData::CheckSum(String* string) {
int checksum = Version::Hash();
#ifdef DEBUG
uint32_t seed = static_cast<uint32_t>(checksum);
checksum = static_cast<int>(IteratingStringHasher::Hash(string, seed));
#endif // DEBUG
return checksum;
}
} } // namespace v8::internal
|
aspectron/jsx
|
extern/v8/src/serialize.cc
|
C++
|
mit
| 77,251
|
<?php
namespace SturentsLib\Api\Requests;
use SturentsLib\Api\Models\SwaggerModel;
/**
* Update a contract on a property
*/
class PatchContract extends SwaggerRequest
{
const URI = '/api/contract';
const METHOD = 'PATCH';
/**
* The property ID provided by the initial creation
* or a GET /properties request
*
*
* @var string
*/
public $property_id;
/**
* The contract ID provided by the initial creation
* or a GET /contracts/{property_id} request
*
*
* @var string
*/
public $contract_id;
protected static $path_params = ['property_id', 'contract_id'];
/**
* @param \SturentsLib\Api\Models\ContractCreation $contract
*/
public function setBody(\SturentsLib\Api\Models\ContractCreation $contract)
{
$this->body = json_encode($contract);
}
public function __construct($property_id, $contract_id)
{
$this->property_id = $property_id;
$this->contract_id = $contract_id;
}
/**
* @param SwaggerClient $client
* @return SwaggerModel
*/
public function sendWith(SwaggerClient $client)
{
return $client->make($this, [
'200' => \SturentsLib\Api\Models\ContractSaved::class,
'400' => \SturentsLib\Api\Models\SendDataError::class,
'401' => \SturentsLib\Api\Models\AuthError::class,
'404' => \SturentsLib\Api\Models\Error::class,
'default' => \SturentsLib\Api\Models\Error::class
]);
}
}
|
sturents/api-php
|
src/Requests/PatchContract.php
|
PHP
|
mit
| 1,366
|
package geoip_test
import (
"net"
"testing"
"github.com/sevein/nfdmp2rds/geoip"
)
func TestLookup(t *testing.T) {
var tests = []struct {
input string
expec string
}{
{"142.58.103.21", "CA"},
{"217.12.24.33", "ES"},
}
for _, tt := range tests {
ip := net.ParseIP(tt.input)
r, err := geoip.Geo(ip)
if err != nil {
t.Error(err)
}
actual := r.Country.IsoCode
if actual != tt.expec {
t.Errorf("lookup: expected %s, actual %s", tt.expec, actual)
}
}
}
|
sevein/nfdmp2rds
|
geoip/geoip_test.go
|
GO
|
mit
| 485
|
<?php
/**
* SocialPlus - A light and agile social network
*
* @author Paras Dahal <shree5paras@gmail.com>
* @copyright 2015 Paras Dahal
* @link http://www.github.com/parasdahal/socialplus
* @license MIT licence
* @version 1.0
* @package socialplus
*
* MIT LICENSE
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace socialplus\core;
require_once('DB.php');
class Post
{
private $user_id;
private $DB;
public function __construct(User $user)
{
$this->user_id=$_SESSION['id'];
//Establish connection to the database
$this->DB= DB::getInstance();
}
public function UserFeed()
{
$posts=$this->DB->GetUserFeedPosts($this->user_id);
$feed=array();
$count=0;
foreach($posts as $post)
{
$feed[$count]['post']=$post;
//get user for this post
$user=$this->DB->GetUserMeta($post['user_id']);
$username=$this->DB->GetUsernameById($post['user_id']);
//get votes for this post
$votes=$this->DB->GetPostVotes($post['id']);
//get comments for this post
$comments=$this->DB->GetPostComments($post['id']);
//add user to feed posts
if($user!=false){
$feed[$count]['usermeta']=$user;
$feed[$count]['usermeta']['username']=$username['username'];
}
else
$feed[$count]['usermeta']=array();
//add votes to feed posts
if($votes!=false)
{
$feed[$count]['votes']=$votes;
$counter=0;
foreach($feed[$count]['votes'] as $vote)
{
$meta=$this->DB->GetUserMeta($vote['vote_owner_id']);
$name=$this->DB->GetUsernameById($vote['vote_owner_id']);
$feed[$count]['votes'][$counter]['usermeta']=$meta;
$feed[$count]['votes'][$counter]['usermeta']['username']=$name['username'];
$counter++;
}
}
else
$feed[$count]['votes']=array();
//add comments to feed votes
if($comments!=false){
$feed[$count]['comments']=$comments;
$counter=0;
foreach($feed[$count]['comments'] as $comment)
{
$meta=$this->DB->GetUserMeta($comment['comment_owner_id']);
$name=$this->DB->GetUsernameById($comment['comment_owner_id']);
$feed[$count]['comments'][$counter]['usermeta']=$meta;
$feed[$count]['comments'][$counter]['usermeta']['username']=$name['username'];
$counter++;
}
}
else
$feed[$count]['comments']=array();
$count++;
}
return $feed;
}
public function UserTimeline()
{
$posts=$this->DB->GetUserTimelinePosts($this->user_id);
$feed=array();
$count=0;
foreach($posts as $post)
{
$feed[$count]['post']=$post;
//get user for this post
$user=$this->DB->GetUserMeta($post['user_id']);
$username=$this->DB->GetUsernameById($post['user_id']);
//get votes for this post
$votes=$this->DB->GetPostVotes($post['id']);
//get comments for this post
$comments=$this->DB->GetPostComments($post['id']);
//add user to feed posts
if($user!=false){
$feed[$count]['usermeta']=$user;
$feed[$count]['usermeta']['username']=$username['username'];
}
else
$feed[$count]['usermeta']=array();
//add votes to feed posts
if($votes!=false)
{
$feed[$count]['votes']=$votes;
$counter=0;
foreach($feed[$count]['votes'] as $vote)
{
$meta=$this->DB->GetUserMeta($vote['vote_owner_id']);
$name=$this->DB->GetUsernameById($vote['vote_owner_id']);
$feed[$count]['votes'][$counter]['usermeta']=$meta;
$feed[$count]['votes'][$counter]['usermeta']['username']=$name['username'];
$counter++;
}
}
else
$feed[$count]['votes']=array();
//add comments to feed votes
if($comments!=false){
$feed[$count]['comments']=$comments;
$counter=0;
foreach($feed[$count]['comments'] as $comment)
{
$meta=$this->DB->GetUserMeta($comment['comment_owner_id']);
$name=$this->DB->GetUsernameById($comment['comment_owner_id']);
$feed[$count]['comments'][$counter]['usermeta']=$meta;
$feed[$count]['comments'][$counter]['usermeta']['username']=$name['username'];
$counter++;
}
}
else
$feed[$count]['comments']=array();
$count++;
}
return $feed;
}
}
?>
|
parasdahal/reactive
|
core/Posts.php
|
PHP
|
mit
| 5,196
|
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
namespace PointAndControl.Devices
{
/// <summary>
/// This class specializes the device class to the class LCDTV
/// It contains all information as well as functions available for a LCDTV.
/// Follwing functions are available:
/// "on"
/// "off"
/// Volume (raise ("volup"), lower("voldown"), mute ("mute"))
/// Sources ("source")(VGA ("1"), RGB ("2"), DVI "3", HDMI "4", Video1 "5", Video2 "6", S-Video "7", DVD HD1 "12", DVD HD2 "14", HDMI (VESA STD) "17")
/// Audio Input ("audio")(Audio 1 PC ("1"), Audio 2 "2", Audio 3 "3", HDMI "4")
/// @author Christopher Baumgärtner
/// </summary>
public class NecLcdMonitorMultiSyncV421 : NativeTransmittingDevice
{
/// <summary>
/// Constructor of a LCDTV object.
/// <param name="id">ID of the object for identifying it</param>
/// <param name="name">Userdefined name of the device</param>
/// <param name="form">Shape of the device in the room</param>
/// <param name = "path" > The Path to communicate with the device</param>
/// </summary>
public NecLcdMonitorMultiSyncV421(String name, String id, String path, List<Ball> form)
: base(name, id, path, form)
{
String[] ipAndPort = splitPathToIPAndPort();
connection = new Tcp(Convert.ToInt32(ipAndPort[1]), ipAndPort[0]);
}
/// <summary>
/// The Transmit method is responsible for the correct invocation of a function of the LCDTV
/// which is implicated by the "commandID"
/// <param name="cmdId">
/// With the commandID the Transmit-method recieves which command
/// should be send to the device (LCDTV)
/// </param>
/// <param name="value">
/// The value belonging to the command
/// </param>
/// <returns>
/// If execution was successful
/// </returns>
/// </summary>
public override String Transmit(String cmdId, String value)
{
switch (cmdId)
{
case "on":
return Power(0x31);
case "off":
return Power(0x34);
case "volup":
return Vol(1);
case "voldown":
return Vol(-1);
case "mute":
return Mute();
case "source":
return Input((byte)(0x30 + Convert.ToInt32(value)));
case "audio":
return Audio((byte)(0x30 + Convert.ToInt32(value)));
}
return Properties.Resources.InvalidCommand;
}
private String Power(byte b)
{
byte[] msg = new byte[21];
byte[] message = new byte[] { 0x01, 0x30, 0x41, 0x30, 0x41, 0x30, 0x43, 0x02, 0x43, 0x32, 0x30, 0x33, 0x44, 0x36, 0x30, 0x30, 0x30, b, 0x03 }; //Message
message.CopyTo(msg, 0);
msg[19] = CalcBcc(msg);
msg[20] = 0x0D;
return connection.Send(Encoding.ASCII.GetString(msg));
}
private String Vol(int i)
{
byte[] msg = new byte[15];
byte[] message = new byte[] { 0x01, 0x30, 0x41, 0x30, 0x43, 0x30, 0x36, 0x02, 0x30, 0x30, 0x36, 0x32, 0x03 };
//Message
message.CopyTo(msg, 0);
msg[13] = CalcBcc(msg);
msg[14] = 0x0D;
byte[] response;
try
{
response = Encoding.ASCII.GetBytes
(connection.Send(Encoding.ASCII.GetString(msg)));
}
catch (SocketException e)
{
throw e;
}
byte newValue = (byte)(response[23] + i);
msg = new byte[15];
message = new byte[] { 0x01, 0x30, 0x41, 0x30, 0x45, 0x30, 0x3A, 0x02, 0x30, 0x30, 0x36, newValue, 0x03 };
//Message
message.CopyTo(msg, 0);
msg[13] = CalcBcc(msg);
msg[14] = 0x0D;
return connection.Send(Encoding.ASCII.GetString(msg));
}
private String Mute()
{
byte[] msg = new byte[15];
byte[] message = new byte[] { 0x01, 0x30, 0x41, 0x30, 0x43, 0x30, 0x36, 0x02, 0x30, 0x30, 0x38, 0x3D, 0x03 };
//Message
message.CopyTo(msg, 0);
msg[13] = CalcBcc(msg);
msg[14] = 0x0D;
byte[] response;
try
{
response = Encoding.ASCII.GetBytes
(connection.Send(Encoding.ASCII.GetString(msg)));
}
catch (SocketException e)
{
throw e;
}
byte newValue = response[16];
if (newValue == 0x31)
{
newValue = 0x30;
}
else
{
newValue = 0x31;
}
msg = new byte[19];
message = new byte[]
{
0x01, 0x30, 0x41, 0x30, 0x45, 0x30, 0x3A, 0x02, 0x30, 0x30, 0x38, 0x3D, 0x30, 0x30, 0x30, newValue,
0x03
}; //Message
message.CopyTo(msg, 0);
msg[17] = CalcBcc(msg);
msg[18] = 0x0D;
return connection.Send(Encoding.ASCII.GetString(msg));
}
private String Input(byte b)
{
byte[] msg = new byte[19];
byte[] message = new byte[] { 0x01, 0x30, 0x41, 0x30, 0x45, 0x30, 0x3A, 0x02, 0x30, 0x30, 0x36, 0x30, 0x30, 0x30, 0x30, b, 0x03 };
//Message
message.CopyTo(msg, 0);
msg[17] = CalcBcc(msg);
msg[18] = 0x0D;
return connection.Send(Encoding.ASCII.GetString(msg));
}
private String Audio(byte b)
{
byte[] msg = new byte[19];
byte[] message = new byte[] { 0x01, 0x30, 0x41, 0x30, 0x45, 0x30, 0x3A, 0x02, 0x30, 0x32, 0x32, 0x3E, 0x30, 0x30, 0x30, b, 0x03 };
//Message
message.CopyTo(msg, 0);
msg[17] = CalcBcc(msg);
msg[18] = 0x0D;
return connection.Send(Encoding.ASCII.GetString(msg));
}
private static byte CalcBcc(byte[] command)
{
byte temp = command[1];
for (int i = 2; i < command.Length; i++)
{
temp ^= command[i];
}
return temp;
}
}
}
|
teco-kit/PointAndControl
|
IGS/Devices/NECLCDmonitorMultiSyncV421.cs
|
C#
|
mit
| 6,942
|
package org.scalajs.openui5.sap.m
import scala.scalajs.js
import scala.scalajs.js.annotation.JSName
/** The [[ActionListItem]] can be used like a button to fire actions when
* pressed.
*
* @note The inherited selected property of the [[ListItemBase]] is not
* supported.
*/
@JSName("sap.m.ActionListItem")
@js.native
class ActionListItem(id: String = js.native,
settings: js.Dynamic = js.native)
extends ListItemBase {
}
|
lastsys/scalajs-openui5
|
src/main/scala/org/scalajs/openui5/sap/m/ActionListItem.scala
|
Scala
|
mit
| 463
|
package API.amazon.mws.feeds.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://mws.amazonaws.com/doc/2009-01-01/}RequestReportResult"/>
* <element ref="{http://mws.amazonaws.com/doc/2009-01-01/}ResponseMetadata"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
* Generated by AWS Code Generator
* <p/>
* Wed Feb 18 13:28:59 PST 2009
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"requestReportResult",
"responseMetadata"
})
@XmlRootElement(name = "RequestReportResponse")
public class RequestReportResponse {
@XmlElement(name = "RequestReportResult", required = true)
protected RequestReportResult requestReportResult;
@XmlElement(name = "ResponseMetadata", required = true)
protected ResponseMetadata responseMetadata;
/**
* Default constructor
*
*/
public RequestReportResponse() {
super();
}
/**
* Value constructor
*
*/
public RequestReportResponse(final RequestReportResult requestReportResult, final ResponseMetadata responseMetadata) {
this.requestReportResult = requestReportResult;
this.responseMetadata = responseMetadata;
}
/**
* Gets the value of the requestReportResult property.
*
* @return
* possible object is
* {@link RequestReportResult }
*
*/
public RequestReportResult getRequestReportResult() {
return requestReportResult;
}
/**
* Sets the value of the requestReportResult property.
*
* @param value
* allowed object is
* {@link RequestReportResult }
*
*/
public void setRequestReportResult(RequestReportResult value) {
this.requestReportResult = value;
}
public boolean isSetRequestReportResult() {
return (this.requestReportResult!= null);
}
/**
* Gets the value of the responseMetadata property.
*
* @return
* possible object is
* {@link ResponseMetadata }
*
*/
public ResponseMetadata getResponseMetadata() {
return responseMetadata;
}
/**
* Sets the value of the responseMetadata property.
*
* @param value
* allowed object is
* {@link ResponseMetadata }
*
*/
public void setResponseMetadata(ResponseMetadata value) {
this.responseMetadata = value;
}
public boolean isSetResponseMetadata() {
return (this.responseMetadata!= null);
}
/**
* Sets the value of the RequestReportResult property.
*
* @param value
* @return
* this instance
*/
public RequestReportResponse withRequestReportResult(RequestReportResult value) {
setRequestReportResult(value);
return this;
}
/**
* Sets the value of the ResponseMetadata property.
*
* @param value
* @return
* this instance
*/
public RequestReportResponse withResponseMetadata(ResponseMetadata value) {
setResponseMetadata(value);
return this;
}
@javax.xml.bind.annotation.XmlTransient
private ResponseHeaderMetadata responseHeaderMetadata;
public boolean isSetResponseHeaderMetadata() {
return this.responseHeaderMetadata != null;
}
public void setResponseHeaderMetadata(ResponseHeaderMetadata responseHeaderMetadata) {
this.responseHeaderMetadata = responseHeaderMetadata;
}
public ResponseHeaderMetadata getResponseHeaderMetadata() {
return responseHeaderMetadata;
}
/**
*
* XML string representation of this object
*
* @return XML String
*/
public String toXML() {
StringBuffer xml = new StringBuffer();
xml.append("<RequestReportResponse xmlns=\"http://mws.amazonaws.com/doc/2009-01-01/\">");
if (isSetRequestReportResult()) {
RequestReportResult requestReportResult = getRequestReportResult();
xml.append("<RequestReportResult>");
xml.append(requestReportResult.toXMLFragment());
xml.append("</RequestReportResult>");
}
if (isSetResponseMetadata()) {
ResponseMetadata responseMetadata = getResponseMetadata();
xml.append("<ResponseMetadata>");
xml.append(responseMetadata.toXMLFragment());
xml.append("</ResponseMetadata>");
}
xml.append("</RequestReportResponse>");
return xml.toString();
}
/**
*
* Escape XML special characters
*/
private String escapeXML(String string) {
StringBuffer sb = new StringBuffer();
int length = string.length();
for (int i = 0; i < length; ++i) {
char c = string.charAt(i);
switch (c) {
case '&':
sb.append("&");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '\'':
sb.append("'");
break;
case '"':
sb.append(""");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
/**
*
* JSON string representation of this object
*
* @return JSON String
*/
public String toJSON() {
StringBuffer json = new StringBuffer();
json.append("{\"RequestReportResponse\" : {");
json.append(quoteJSON("@xmlns"));
json.append(" : ");
json.append(quoteJSON("http://mws.amazonaws.com/doc/2009-01-01/"));
boolean first = true;
json.append(", ");
if (isSetRequestReportResult()) {
if (!first) json.append(", ");
json.append("\"RequestReportResult\" : {");
RequestReportResult requestReportResult = getRequestReportResult();
json.append(requestReportResult.toJSONFragment());
json.append("}");
first = false;
}
if (isSetResponseMetadata()) {
if (!first) json.append(", ");
json.append("\"ResponseMetadata\" : {");
ResponseMetadata responseMetadata = getResponseMetadata();
json.append(responseMetadata.toJSONFragment());
json.append("}");
first = false;
}
json.append("}");
json.append("}");
return json.toString();
}
/**
*
* Quote JSON string
*/
private String quoteJSON(String string) {
StringBuffer sb = new StringBuffer();
sb.append("\"");
int length = string.length();
for (int i = 0; i < length; ++i) {
char c = string.charAt(i);
switch (c) {
case '"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '/':
sb.append("\\/");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
default:
if (c < ' ') {
sb.append("\\u" + String.format("%03x", Integer.valueOf(c)));
} else {
sb.append(c);
}
}
}
sb.append("\"");
return sb.toString();
}
}
|
VDuda/SyncRunner-Pub
|
src/API/amazon/mws/feeds/model/RequestReportResponse.java
|
Java
|
mit
| 8,423
|
<?php
$user = $_POST['b'];
if(!empty($user)) {
comprobar($user);
}
function comprobar($b) {
$con = new mysqli("localhost", "comercl4_admin", "constantinopla2301", "comercl4_helpdesk");
$sql = mysqli_query($con, "SELECT * FROM ticket WHERE status = '1'");
$contar = $sql->num_rows;
if($contar > $b)
echo "<script type=\"text/javascript\"> $(document).attr(\"title\", \"(".(int)($contar-$b).") HelpDesk - Solicitudes pendientes\") </script>";
}
?>
|
elafrikano/HelpDesk
|
scripts/scriptAutoRefresh.php
|
PHP
|
mit
| 643
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace AutoProxy.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Rules.mdf;Integrated" +
" Security=True")]
public string RulesConnectionString {
get {
return ((string)(this["RulesConnectionString"]));
}
}
}
}
|
Tanjoodo/autoproxy
|
AutoProxy/Properties/Settings.Designer.cs
|
C#
|
mit
| 1,683
|
package hk.ust.gmission;
import android.accounts.AccountsException;
import android.app.Activity;
import java.io.IOException;
import hk.ust.gmission.services.BootstrapService;
import retrofit.RestAdapter;
/**
* Provider for a {@link BootstrapService} instance
*/
public class BootstrapServiceProvider {
private RestAdapter restAdapter;
public BootstrapServiceProvider(RestAdapter restAdapter) {
this.restAdapter = restAdapter;
}
/**
* Get service for configured key provider
* <p/>
* This method gets an auth key and so it blocks and shouldn't be called on the main thread.
*
* @return bootstrap service
* @throws IOException
* @throws AccountsException
*/
public BootstrapService getService(final Activity activity){
// TODO: See how that affects the bootstrap service.
return new BootstrapService(restAdapter);
}
}
|
gmission/gmission_reborn_android
|
gmission/src/main/java/hk/ust/gmission/BootstrapServiceProvider.java
|
Java
|
mit
| 915
|
<?php
/*
Safe sample
input : get the field UserData from the variable $_POST
sanitize : use of the function addslashes
construction : interpretation with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$tainted = $_POST['UserData'];
$tainted = addslashes($tainted);
$query = "SELECT lastname, firstname FROM drivers, vehicles WHERE drivers.id = vehicles.ownerid AND vehicles.tag=' $tainted '";
$conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password)
mysql_select_db('dbname') ;
echo "query : ". $query ."<br /><br />" ;
$res = mysql_query($query); //execution
while($data =mysql_fetch_array($res)){
print_r($data) ;
echo "<br />" ;
}
mysql_close($conn);
?>
|
stivalet/PHP-Vulnerability-test-suite
|
Injection/CWE_89/safe/CWE_89__POST__func_addslashes__join-interpretation_simple_quote.php
|
PHP
|
mit
| 1,611
|
Grapnel
==========
#### The first (started in 2010!) Client/Server-Side JavaScript Router with Named Parameters, HTML5 pushState, and Middleware support.
## Download/Installation
**Download Source:**
- [Production](https://raw.githubusercontent.com/baseprime/grapnel/master/dist/grapnel.min.js)
- [Development](https://raw.githubusercontent.com/baseprime/grapnel/development/dist/grapnel.js)
**Install with npm**
```bash
npm install grapnel
```
**Or by using bower:**
```bash
bower install grapnel
```
**Server only:** (with HTTP methods added, [more info](https://github.com/baseprime/grapnel-server))
```bash
npm install grapnel-server
```
# Grapnel Features
- Supports routing using `pushState` or `hashchange` concurrently
- Supports Named Parameters similar to Express, Sinatra, and Restify
- Middleware Support
- Works on the client or server side
- RegExp Support
- Supports `#` or `#!` for `hashchange` routing
- Unobtrusive, supports multiple routers on the same page
- No dependencies
## Basic Router
```javascript
const router = new Grapnel();
router.get('products/:category/:id?', function(req) {
let id = req.params.id;
let category = req.params.category;
// GET http://mysite.com/#products/widgets/134
console.log(category, id);
// => widgets 134
});
```
## Using HTML5 pushState
```javascript
const router = new Grapnel({ pushState : true });
router.get('/products/:category/:id?', function(req) {
let id = req.params.id;
let category = req.params.category;
console.log(category, id);
});
router.navigate('/products/widgets/134');
// => widgets 134
```
## Named Parameters
Grapnel supports regex style routes similar to Sinatra, Restify, and Express. The properties are mapped to the parameters in the request.
```javascript
router.get('products/:id?', function(req) {
// GET /file.html#products/134
console.log(req.params.id);
// => 134
});
router.get('products/*', function(req) {
// The wildcard/asterisk will match anything after that point in the URL
// Parameters are provided req.params using req.params[n], where n is the nth capture
});
```
## Middleware Support
Grapnel also supports middleware:
```javascript
let auth = function(req, event, next) {
user.auth(function(err) {
req.user = this;
next();
});
}
router.get('/*', auth, function(req) {
console.log(req.user);
});
```
## Route Context
You can add context to a route and even use it with middleware:
```javascript
let usersRoute = router.context('/user/:id', getUser, getFollowers); // Middleware can be used here
usersRoute('/', function(req, event) {
console.log('Profile', req.params.id);
});
usersRoute('/followers', otherMiddleware, function(req, event) { // Middleware can be used here too
console.log('Followers', req.params.id);
});
router.navigate('/user/13589');
// => Profile 13589
router.navigate('/user/13589/followers');
// => Followers 13589
```
## Works as a server-side router
```javascript
import { createServer } from 'http';
import Grapnel from 'grapnel';
const app = new Grapnel();
app.get('/', function(req, route) {
route.res.end('Hello World!', 200);
});
createServer(function(req, res) {
app.once('match', function(route) {
route.res = res;
}).navigate(req.url);
}).listen(3000);
```
**This is now simplified as a separate package** ([more info](https://github.com/baseprime/grapnel/tree/server-router))
```bash
npm install grapnel-server
```
## Declaring Multiple Routes
```javascript
let routes = {
'products' : function(req) {
// GET /file.html#products
},
'products/:category/:id?' : function(req) {
// GET /file.html#products/widgets/35
console.log(req.params.category);
// => widgets
}
}
Grapnel.listen(routes);
```
## Event Handling
```javascript
const router = new Grapnel({ pushState : true, root : '/' });
router.on('navigate', function(event){
// GET /foo/bar
console.log('URL changed to %s', this.path());
// => URL changed to /foo/bar
});
```
## RegExp Support
Grapnel allows RegEx when defining a route:
```javascript
const router = new Grapnel();
let expression = /^food\/tacos\/(.*)$/i;
router.get(expression, function(req, event){
// GET http://mysite.com/page#food/tacos/good
console.log('I think tacos are %s.', req.params[0]);
// => "He thinks tacos are good."
});
```
***
# Usage & Tips
## Basic Configuration
```javascript
const router = new Grapnel();
```
## Enabling PushState
```javascript
const router = new Grapnel({ pushState : true });
```
You can also specify a root URL by setting it as an option:
```javascript
const router = new Grapnel({ root : '/app', pushState : true });
```
The root may require a beginning slash and a trailing slash depending on how you set up your routes.
## Middleware
Grapnel uses middleware similar to how Express uses middleware. Middleware has access to the `req` object, `route` object, and the next middleware in the call stack (commonly denoted as `next`). Middleware must call `next()` to pass control to the next middleware, otherwise the router will stop.
For more information about how middleware works, see [Using Middleware](http://expressjs.com/guide/using-middleware.html).
```javascript
let user = function(req, route, next) {
user.get(function(err) {
req.user = this;
next();
});
}
router.get('/user/*', user, function(req) {
console.log(req.user);
});
```
## Declaring your routes with an object literal:
```javascript
Grapnel.listen({
'products/:id' : function(req) {
// Handler
}
});
```
When declaring routes with a literal object, router options can be passed as the first parameter:
```javascript
let opts = { pushState : true };
Grapnel.listen(opts, routes);
```
## Navigation
If pushState is enabled, you can navigate through your application with `router.navigate`:
```javascript
router.navigate('/products/123');
```
## Stopping a Route Event
```javascript
router.on('match', function(routeEvent) {
routeEvent.preventDefault(); // Stops event handler
});
```
## Stopping Event Propagation
```javascript
router.get('/products/:id', function(req, routeEvent) {
routeEvent.stopPropagation(); // Stops propagation of the event
});
router.get('/products/widgets', function(req, routeEvent) {
// This will not be executed
});
router.navigate('/products/widgets');
```
## 404 Pages
You can specify a route that only uses a wildcard `*` as your final route, then use `route.parent()` which returns `false` if the call stack doesn't have any other routes to run.
```javascript
let routes = {
'/' : function(req, route) {
// Handle route
},
'/store/products/:id' : function(req, route) {
// Handle route
},
'/category/:id' : function(req, route) {
// Handle route
},
'/*' : function(req, route) {
if(!route.parent()){
// Handle 404
}
}
}
Grapnel.listen({ pushState : true }, routes);
```
## Setting window state
```javascript
router.navigate('/', {
state: { ...windowState }
});
```
***
# Documentation
##### `get` Adds a listeners and middleware for routes
```javascript
/**
* @param {String|RegExp} path
* @param {Function} [[middleware], callback]
*/
router.get('/store/:category/:id?', function(req, route){
let category = req.params.category;
let id = req.params.id;
console.log('Product #%s in %s', id, category);
});
```
##### `navigate` Navigate through application
```javascript
/**
* @param {String} path relative to root
* @param {Object} options navigation options
*/
router.navigate('/products/123', ...options);
```
##### `on` Adds a new event listener
```javascript
/**
* @param {String} event name (multiple events can be called when separated by a space " ")
* @param {Function} callback
*/
router.on('myevent', function(event) {
console.log('Grapnel works!');
});
```
##### `once` A version of `on` except its handler will only be called once
```javascript
/**
* @param {String} event name (multiple events can be called when separated by a space " ")
* @param {Function} callback
*/
router.once('init', function() {
console.log('This will only be executed once');
});
```
##### `emit` Triggers an event
```javascript
/**
* @param {String} event name
* @param {...Mixed} attributes Parameters that will be applied to event handler
*/
router.emit('event', eventArg1, eventArg2, ...etc);
```
##### `context` Returns a function that can be called with a specific route in context.
Both the `router.context` method and the function it returns can accept middleware. **Note: when calling `route.context`, you should omit the trailing slash.**
```javascript
/**
* @param {String} Route context (without trailing slash)
* @param {[Function]} Middleware (optional)
* @return {Function} Adds route to context
*/
let usersRoute = router.context('/user/:id');
usersRoute('/followers', function(req, route) {
console.log('Followers', req.params.id);
});
router.navigate('/user/13589/followers');
// => Followers 13589
```
##### `path`
* `router.path('string')` Sets a new path or hash
* `router.path()` Gets path or hash
* `router.path(false)` Clears the path or hash
##### `bind` An alias of `on`
##### `trigger` An alias of `emit`
##### `add` An alias of `get`
## Options
* `pushState` Enable pushState, allowing manipulation of browser history instead of using the `#` and `hashchange` event
* `root` Root of your app, all navigation will be relative to this
* `target` Target object where the router will apply its changes (default: `window`)
* `hashBang` Enable `#!` as the anchor of a `hashchange` router instead of using just a `#`
## Events
* `navigate` Fires when router navigates through history
* `match` Fires when a new match is found, but before the handler is called
* `hashchange` Fires when hashtag is changed
## License
##### [MIT License](http://opensource.org/licenses/MIT)
|
bytecipher/grapnel
|
README.md
|
Markdown
|
mit
| 10,042
|
import Vue from 'vue'
import * as types from './mutation-types'
export default {
[types.PUT] (state, { key, value }) {
Vue.set(state, key, value)
},
[types.REMOVE] (state, { key }) {
Vue.delete(state, key)
},
[types.SYNC] (state, { records }) {
// Delete existing keys - Cognito datastore is the source of truth
for (const key in state) {
Vue.delete(state, key)
}
// Assign keys from Cognito datastore
for (const record of records) {
if (!record.value) continue
Vue.set(state, record.key, record.value)
}
}
}
|
LightmakerCanada/vuex-cognito-sync
|
src/mutations.js
|
JavaScript
|
mit
| 574
|
/*
* Generated by class-dump 3.3.3 (64 bit).
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2010 by Steve Nygard.
*/
#import "Assistant.h"
@class ActivityMonitor, NSButton, NSProgressIndicator, NSTextField, NSTimer, NSView;
@interface LibraryImportAssistant : Assistant
{
NSView *_introView;
NSView *_patienceView;
NSView *_doneView;
NSView *_errorView;
NSView *_recoveryIntroView;
NSTextField *_mailboxStatusField;
NSTextField *_messageStatusField;
NSTextField *_timeRemainingField;
NSProgressIndicator *_progressBar;
NSButton *_showNewFeaturesButton;
NSTextField *_newFeaturesTextField;
ActivityMonitor *_activityMonitor;
NSTimer *_updateTimer;
long long _state;
BOOL _importWasSuccessful;
BOOL _accountsAreNewlyCreated;
}
- (id)initWithAssistentManager:(id)arg1;
- (void)dealloc;
- (void)setAccountsAreNewlyCreated:(BOOL)arg1;
- (void)start;
- (void)stop;
- (void)_permissionErrorSheetDone:(id)arg1 returnCode:(long long)arg2 contextInfo:(void *)arg3;
- (BOOL)_checkAccountDirectoryPermissions;
- (void)goForward;
- (id)windowTitle;
- (void)updateProgress:(id)arg1;
- (double)runningAverageWithNewValue:(double)arg1;
- (id)formattedTimeForSeconds:(double)arg1;
- (void)synchronouslyDoTheImport;
- (void)showNewFeatures:(id)arg1;
@end
|
w-i-n-s/SimplePlugin
|
MailHeaders/Lion/Mail/LibraryImportAssistant.h
|
C
|
mit
| 1,331
|
<?php
/*
Unsafe sample
input : get the field userData from the variable $_GET via an object, which store it in a array
Uses a full_special_chars_filter via filter_var function
construction : use of sprintf via a %s with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
class Input{
private $input;
public function getInput(){
return $this->input['realOne'];
}
public function __construct(){
$this->input = array();
$this->input['test']= 'safe' ;
$this->input['realOne']= $_GET['UserData'] ;
$this->input['trap']= 'safe' ;
}
}
$temp = new Input();
$tainted = $temp->getInput();
$sanitized = filter_var($tainted, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$tainted = $sanitized ;
$query = sprintf("ls '%s'", $tainted);
//flaw
$ret = system($query);
?>
|
stivalet/PHP-Vulnerability-test-suite
|
Injection/CWE_78/unsafe/CWE_78__object-indexArray__func_FILTER-CLEANING-full_special_chars_filter__ls-sprintf_%s_simple_quote.php
|
PHP
|
mit
| 1,669
|
using Xamarin.Forms;
namespace AppShell.Mobile.Views
{
[ContentProperty("ShellContent")]
public partial class ShellView : ContentView
{
public static readonly BindableProperty ShellContentProperty = BindableProperty.Create("ShellContent", typeof(View), typeof(ShellView), null, propertyChanged: ShellContentPropertyChanged);
public static readonly BindableProperty HasNavigationBarProperty = BindableProperty.Create("HasNavigationBar", typeof(bool), typeof(ShellView), true, propertyChanged: OnHasNavigationBarChanged);
public View ShellContent { get { return (View)GetValue(ShellContentProperty); } set { SetValue(ShellContentProperty, value); } }
public bool HasNavigationBar { get { return (bool)GetValue(HasNavigationBarProperty); } set { SetValue(HasNavigationBarProperty, value); } }
public static void ShellContentPropertyChanged(BindableObject bindableObject, object oldValue, object newValue)
{
ShellView shellView = (ShellView)bindableObject;
View newView = (View)newValue;
shellView.ShellContentView.Content = newView;
}
private static void OnHasNavigationBarChanged(BindableObject bindableObject, object oldValue, object newValue)
{
ShellView shellView = (ShellView)bindableObject;
bool newHasNavigationBar = (bool)newValue;
NavigationPage.SetHasNavigationBar(shellView, newHasNavigationBar);
if (!newHasNavigationBar)
shellView.Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0);
}
public ShellView()
{
InitializeComponent();
SetBinding(HasNavigationBarProperty, new Binding("HasNavigationBar"));
}
}
}
|
cschwarz/AppShell
|
src/AppShell.Mobile/Views/ShellView.xaml.cs
|
C#
|
mit
| 1,784
|
# -*- coding:utf-8 -*-
from setuptools import setup
setup(
name = "mobileclick",
description = "mobileclick provides baseline methods and utility scripts for the NTCIR-12 MobileClick-2 task",
author = "Makoto P. Kato",
author_email = "kato@dl.kuis.kyoto-u.ac.jp",
license = "MIT License",
url = "https://github.com/mpkato/mobileclick",
version='0.2.0',
packages=[
'mobileclick',
'mobileclick.nlp',
'mobileclick.methods',
'mobileclick.scripts'
],
install_requires = [
'BeautifulSoup',
'nltk>=3.1',
'numpy'],
entry_points = {
'console_scripts': [
'mobileclick_download_training_data=mobileclick.scripts.mobileclick_download_training_data:main',
'mobileclick_download_test_data=mobileclick.scripts.mobileclick_download_test_data:main',
'mobileclick_random_ranking_method=mobileclick.scripts.mobileclick_random_ranking_method:main',
'mobileclick_lang_model_ranking_method=mobileclick.scripts.mobileclick_lang_model_ranking_method:main',
'mobileclick_random_summarization_method=mobileclick.scripts.mobileclick_random_summarization_method:main',
'mobileclick_lang_model_summarization_method=mobileclick.scripts.mobileclick_lang_model_summarization_method:main',
'mobileclick_lang_model_two_layer_summarization_method=mobileclick.scripts.mobileclick_lang_model_two_layer_summarization_method:main',
],
},
tests_require=['nose']
)
|
mpkato/mobileclick
|
setup.py
|
Python
|
mit
| 1,565
|
'use strict';
describe('Service: scenarioFactory', function () {
// load the service's module
beforeEach(module('testerApp'));
// instantiate service
var scenarioFactory;
beforeEach(inject(function (_scenarioFactory_) {
scenarioFactory = _scenarioFactory_;
}));
it('should do something', function () {
expect(!!scenarioFactory).toBe(true);
});
});
|
dmzubr/testing-store
|
test/spec/services/scenariofactory.js
|
JavaScript
|
mit
| 377
|
<?php
namespace ORMiny;
use DBTiny\Driver\Statement;
use Traversable;
/**
* Class StatementIterator
*
* @package ORMiny
*/
class StatementIterator implements \IteratorAggregate
{
private $statement;
private $pkField;
private $offset = 0;
private $limit = PHP_INT_MAX;
public function __construct(Statement $statement, $pkField, $offset, $limit)
{
$this->statement = $statement;
$this->pkField = $pkField;
$this->offset = (int)$offset;
if ($limit !== null) {
$this->limit = (int)$limit;
}
}
/**
* Retrieve an external iterator
*
* @link http://php.net/manual/en/iteratoraggregate.getiterator.php
* @return Traversable An instance of an object implementing <b>Iterator</b> or
* <b>Traversable</b>
* @since 5.0.0
*/
public function getIterator()
{
if ($this->offset > 0) {
$key = null;
$index = 0;
//Skip the first N
while (false !== ($record = $this->statement->fetch())) {
if ($key === $record[ $this->pkField ]) {
continue;
}
$key = $record[ $this->pkField ];
if ($index++ === $this->offset) {
break;
}
}
$current = $record;
} else {
$current = $this->statement->fetch();
}
$currentKey = $current[ $this->pkField ];
$fetchedRecordCount = 1;
do {
yield $currentKey => $current;
$current = $this->statement->fetch();
if (empty($current)) {
break;
}
if ($currentKey !== $current[ $this->pkField ]) {
$currentKey = $current[ $this->pkField ];
$fetchedRecordCount++;
}
} while ($fetchedRecordCount <= $this->limit);
$this->statement->closeCursor();
}
}
|
bugadani/ORMiny
|
src/StatementIterator.php
|
PHP
|
mit
| 1,997
|
<!doctype html>
<!--[if lt IE 7 ]> <html lang="en" class="no-js ie6"> <![endif]-->
<!--[if IE 7 ]> <html lang="en" class="no-js ie7"> <![endif]-->
<!--[if IE 8 ]> <html lang="en" class="no-js ie8"> <![endif]-->
<!--[if IE 9 ]> <html lang="en" class="no-js ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html lang="en" class="no-js"><!--<![endif]-->
<head>
<title>FLEET Example Search</title>
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-touch-fullscreen" content="yes">
<meta charset="UTF-8" />
<link rel="stylesheet" type="text/css" href="css/all.css">
</head>
<body>
<!--[if lt IE 7]>
<p class="chromeframe" style="background:#eee; padding:10px; width:100%">Your browser is <em>ancient!</em> <a href="http://browsehappy.com/">Upgrade to a different browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to experience this site.</p>
<![endif]-->
<div class="flakes-frame">
<div class="flakes-navigation">
<a href="landing.html" class="logo">
<img src="img/logo.png" width="120">
</a>
<ul>
<li class="title">Menu</li>
<li><a href="patient-search.html">Patient Record Search</a></li>
<li><a href="custom-search.html">Custom Search Feature</a></li>
</ul>
<p class="foot">
Hello <b>Bobby Admin</b><br>
<a href="shs-user.html">SHS User Account</a> • <a href="home.html">Logout</a>
</p>
</div>
<div class="flakes-content">
<div class="flakes-mobile-top-bar">
<a href="" class="logo-wrap">
<img src="img/logo.png" height="30px">
</a>
<a href="" class="navigation-expand-target">
<img src="img/site-wide/navigation-expand-target.png" height="26px">
</a>
</div>
<div class="view-wrap">
<div style="height: 1167px;" class="flakes-content">
<h2>Search Demo</h2>
<h3>Patient-Level Search</h3>
<p><b>Search</b> at the patient-level by name or <b>MRN</b>.</p>
<p>If you don't have the patient name, you can search by other factors listed.</p>
<h4>Patient Search</h4>
<div id="inventory-search">
<div class="flakes-search">
<input class="search-box search" placeholder="Search Patients" autofocus="">
</div>
<div class="flakes-actions-bar">
<a class="action button-gray smaller right" href="">Clear</a>
</div>
<table class="flakes-table">
<colgroup>
<col style="width:20px" span="1">
<col style="width:40%" span="1">
</colgroup>
<thead>
<tr>
<td><input type="checkbox"></td>
<td class="company">Patient Name</td>
<td class="contact">MRN</td>
<td class="city">City</td>
<td class="name">Primary Contact</td>
</tr>
</thead>
<tbody class="list"><tr>
<td><input type="checkbox"></td>
<td class="company"><a href="patient-report.html">Dave Folscomb</a></td>
<td class="contact">6541816</td>
<td class="city">Efland</td>
<td class="name">Dana Parks</td>
</tr><tr>
<td><input type="checkbox"></td>
<td class="company"><a href="patient-report.html">Ed Seth Pellen</a></td>
<td class="contact">9375793</td>
<td class="city">MaCalley</td>
<td class="name">Michelle Kirkland</td>
</tr><tr>
<td><input type="checkbox"></td>
<td class="company"><a href="patient-report.html">Mac Smith</a></td>
<td class="contact">6829676</td>
<td class="city">Ballerton</td>
<td class="name">Warren Morales</td>
</tr><tr>
<td><input type="checkbox"></td>
<td class="company"><a href="patient-report.html">August Potter</a></td>
<td class="contact">3891087</td>
<td class="city">Litchford</td>
<td class="name">Steven Madden</td>
</tr><tr>
<td><input type="checkbox"></td>
<td class="company"><a href="patient-report.html">Daphne Sanders</a></td>
<td class="contact">8937857</td>
<td class="city">Framingham</td>
<td class="name">Sierra Morton</td>
</tr><tr>
<td><input type="checkbox"></td>
<td class="company"><a href="patient-report.html">Elford Brimley</a></td>
<td class="contact">9678521</td>
<td class="city">Martinsville</td>
<td class="name">Maya Ayers</td>
</tr><tr>
<td><input type="checkbox"></td>
<td class="company"><a href="patient-report.html">Tim Cooper</a></td>
<td class="contact">4867965</td>
<td class="city">Mallerton</td>
<td class="name">Ruth Lee</td>
</tr><tr>
<td><input type="checkbox"></td>
<td class="company"><a href="patient-report.html">Edward Alford Boggs</a></td>
<td class="contact">4622201</td>
<td class="city">Mimpton</td>
<td class="name">Noel Langley</td>
</tr><tr>
<td><input type="checkbox"></td>
<td class="company"><a href="patient-report.html">Dave Fanning</a></td>
<td class="contact">6541816</td>
<td class="city">Erberville</td>
<td class="name">Dane Pantella</td>
</tr><tr>
<td><input type="checkbox"></td>
<td class="company"><a href="patient-report.html">Sam Papkon</a></td>
<td class="contact">9375793</td>
<td class="city">Mitreville</td>
<td class="name">Michael Papkon</td>
</tr><tr>
<td><input type="checkbox"></td>
<td class="company"><a href="patient-report.html">Michael Macntyre</a></td>
<td class="contact">6829676</td>
<td class="city">Wilforton</td>
<td class="name">Wally Newten</td>
</tr><tr>
<td><input type="checkbox"></td>
<td class="company"><a href="patient-report.html">Allan Portman</a></td>
<td class="contact">3891087</td>
<td class="city">Luxemton</td>
<td class="name">Steven Madson</td>
</tr><tr>
<td><input type="checkbox"></td>
<td class="company"><a href="patient-report.html">Daria Miller</a></td>
<td class="contact">8937857</td>
<td class="city">Fitch Fork</td>
<td class="name">Sally Morton</td>
</tr><tr>
<td><input type="checkbox"></td>
<td class="company"><a href="patient-report.html">Eric Miller</a></td>
<td class="contact">9678521</td>
<td class="city">Mayberry</td>
<td class="name">Malina Ayers</td>
</tr><tr>
<td><input type="checkbox"></td>
<td class="company"><a href="patient-report.html">Tina Dobson</a></td>
<td class="contact">4867965</td>
<td class="city">Moxton</td>
<td class="name">Ruth Lee</td>
</tr><tr>
<td><input type="checkbox"></td>
<td class="company"><a href="patient-report.html">Gilbert Gillingham</a></td>
<td class="contact">4622201</td>
<td class="city">Mullberry</td>
<td class="name">Noel Langley</td>
</tr></tbody>
</table>
<div class="flakes-pagination right">
<a href="">Prev</a> <input value="1"> <i>of</i> 1 <a href="">Next</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<link rel="stylesheet" type="text/css" href="css/prism.css">
<link rel="stylesheet" type="text/css" href="css/gridforms.css">
<script src="js/jquery.js"></script>
<script src="js/snap.js"></script>
<script src="js/responsive-elements.js"></script>
<script src="js/gridforms.js"></script>
<script src="js/prism.js"></script>
<script src="js/base.js"></script>
<script src="js/list.js"></script>
<script type="text/javascript" src="http://getflakes.com/static/js/preview.js"></script>
</body>
</html>
|
FleetDemo/demo
|
patient-search.html
|
HTML
|
mit
| 7,874
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CertiPay.Services.PDF")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CertiPay.Services.PDF")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("27715950-f3f3-447c-a3bb-9e7dbad901bb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("0.3.1")]
[assembly: AssemblyVersion("0.3.1")]
[assembly: AssemblyFileVersion("0.3.1")]
|
kylebjones/CertiPay.Services.PDF
|
CertiPay.Services.PDF/Properties/AssemblyInfo.cs
|
C#
|
mit
| 1,410
|
const _ = require('lodash');
module.exports = () => (hook) => {
const sequelize = hook.app.get('sequelize');
const eventId = hook.result.id;
const quotasToAdd = hook.data.quota.map(quota => _.merge(quota, { eventId }));
const quotaModel = hook.app.get('models').quota;
return sequelize.transaction(t => {
return quotaModel.destroy({
where: { eventId }
}, { transaction: t }).then(() => {
return quotaModel.bulkCreate(quotasToAdd, { updateOnDuplicate: true }, { transaction: t })
.then(() => {
return quotaModel.findAll({
where: {
eventId,
deletedAt: null
},
order: [
['sortId', 'ASC'],
],
include: [{
attributes: ['firstName', 'lastName', 'email', 'createdAt'],
model: sequelize.models.signup,
required: false
}]
}, { transaction: t });
});
});
}).then((quota) => {
hook.result.dataValues.quota = quota;
return hook;
}).catch((error => {
throw new Error('Quota update failed:', error);
}));
};
|
athenekilta/ilmomasiina
|
server/services/admin/events/hooks/updateQuotas.js
|
JavaScript
|
mit
| 1,143
|
<head>
%include templates/parts/head.html
<script type="text/x-mathjax-config">
MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
</script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/mathjs/3.1.0/math.min.js"></script>
<script src='https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML'></script>
</head>
<body>
<!-- Navigation Bar -->
%include templates/parts/navBar.html
<div class="container">
<!-- Header -->
<div class="row">
<div class="col-sm-12">
<div id="pageHeader">
<h1>
A Titanic Probability
</h1>
<p>
Thanks to Kaggle and encyclopedia-titanica for the dataset.
</p>
</div>
<hr/>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p>
This is a question of <a href="{{pathToRoot}}psets/pset5.html">Problem set 5</a>. In this problem you will use real data from the Titanic to calculate conditional probabilities and expectations.
</p>
<p>
<div class="row">
<div class="col-sm-6">
<iframe width="100%" height="250" src="https://www.youtube.com/embed/3lyiZMeTKIo" frameborder="0" allowfullscreen></iframe>
</div>
<div class="col-sm-6">
<iframe width="100%" height="250" src="https://www.youtube.com/embed/ItjXTieWKyI" frameborder="0" allowfullscreen></iframe>
</div>
</div>
<center><i>tldr: the ship sinks</i></center>
</p>
<div class="row">
<div class="col-sm-9">
<p>
On April 15, 1912, the largest passenger liner ever made collided with an iceberg during her maiden voyage. When the Titanic sank it killed 1502 out of 2224 passengers and crew. This sensational tragedy shocked the international community and led to better safety regulations for ships.
One of the reasons that the shipwreck resulted in such loss of life was that there were not enough lifeboats for the passengers and crew. Although there was some element of luck involved in surviving the sinking, some groups of people were more likely to survive than others.
</p>
<p>
The <a href="stuff/titanic.csv">titanic.csv</a> file contains data for 887 of the real Titanic passengers. Each row represents one person. The columns describe different attributes about the person including whether they survived ($S$), their age ($A$), their passenger-class ($C$), their sex ($G$) and the fare they paid ($X$).
</p>
<p>
[Quetion12] Write a program that <b>reads the data file</b> and finds the answers to the following questions:
</p>
<p>
<ol type="a">
<li>Calculate the conditional probability that a person survives given their sex and passenger-class:<br/>
$P(S=\text{ true | } G = \text{female}, C = 1)$<br/>
$P(S=\text{ true | } G = \text{female}, C = 2)$<br/>
$P(S=\text{ true | } G = \text{female}, C = 3)$<br/>
$P(S=\text{ true | } G = \text{male}, C = 1)$<br/>
$P(S=\text{ true | } G = \text{male}, C = 2)$<br/>
$P(S=\text{ true | } G = \text{male}, C = 3)$</li>
<li>What is the probability that a child who is in third class and is 10 years old or younger survives? Since the number of data points that satisfy the condition is small use the "bayesian" approach and represent your probability as a beta distribution. Calculate a belief distribution for: <br/>$S=\text{ true | } A ≤ 10, C = 3$<br/>. Report the prior belief that you used and your final answer as parameterized distributions.</li>
<li>How much did people pay to be on the ship? Calculate the expectation of fare conditioned on passenger-class:<br/>
$E[X \text{ | } C = 1]$<br/>
$E[X \text{ | } C = 2]$<br/>
$E[X \text{ | } C = 3]$</li>
</ol>
</p>
<p>
You only have to submit your answers, not your program.
<p>
Aside: In making this problem I learned that there were somewhere between 80 and 153 passengers from present day Lebanon (then Ottoman Empire) on the Titanic. That would be 7% of the people aboard.
</p>
</div>
<div class="col-sm-3">
<center>
<a href="stuff/titanic.csv">Titanic Dataset<br/><span class="glyphicon glyphicon-save-file" aria-hidden="true" style="font-size: 5em;margin-left:5px"></span>
</a>
</center>
<br/><br/>
Dataset columns:
<ul class="list-group">
<li class="list-group-item">0: Survived Indicator</li>
<li class="list-group-item">1: Passenger Class</li>
<li class="list-group-item">2: Name</li>
<li class="list-group-item">3: Sex</li>
<li class="list-group-item">4: Age</li>
<li class="list-group-item">5: Siblings Aboard</li>
<li class="list-group-item">6: Parents Aboard</li>
<li class="list-group-item">7: Fare paid in £s</li>
</ul>
</div>
</div>
<hr/>
<h3>Extensions?</h3>
<p>See if you can find something suprising in the dataset. Can you predict p? Can you find interesting correlations?</p>
</div>
</div>
%include templates/parts/footer.html
</div>
</body>
|
chrispiech/cs109-2017-spr
|
templates/titanic.html
|
HTML
|
mit
| 5,079
|
'''
charlie.py
---class for controlling charlieplexed SparkFun 8x7 LED Array with the Raspberry Pi
Relies upon RPi.GPIO written by Ben Croston
The MIT License (MIT)
Copyright (c) 2016 Amanda Cole
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''
import RPi.GPIO as GPIO, time, random
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
class Charlie:
'''
Class for control of the charlieplexed SparkFun 8x7 LED Array.
'''
def __init__(self, pins):
'''
pins: type 'list', list of ints for array pins a-h, in order [a,b,c,d,e,f,g,h]
'''
if len(pins) != 8:
print("You must specify eight, and only eight, pins.")
raise ValueError
for pin in pins:
if type(pin) != int:
print("Pins must be of type int.")
raise TypeError
GPIO.setup(pin, GPIO.OUT, initial = False)
a = pins[0]
b = pins[1]
c = pins[2]
d = pins[3]
e = pins[4]
f = pins[5]
g = pins[6]
h = pins[7]
self.array = [[[h,g],[g,h],[f,h],[e,h],[d,h],[c,h],[b,h],[a,h]], \
[[h,f],[g,f],[f,g],[e,g],[d,g],[c,g],[b,g],[a,g]], \
[[h,e],[g,e],[f,e],[e,f],[d,f],[c,f],[b,f],[a,f]], \
[[h,d],[g,d],[f,d],[e,d],[d,e],[c,e],[b,e],[a,e]], \
[[h,c],[g,c],[f,c],[e,c],[d,c],[c,d],[b,d],[a,d]], \
[[h,b],[g,b],[f,b],[e,b],[d,b],[c,b],[b,c],[a,c]], \
[[h,a],[g,a],[f,a],[e,a],[d,a],[c,a],[b,a],[a,b]]]
self.ALL_PINS = [a,b,c,d,e,f,g,h]
def switchOrigin(self):
'''
Places origin [0,0] in the diagonally opposite corner of where its current position.
'''
switched_array = self.array
switched_array.reverse()
for i in switched_array:
i.reverse()
self.array = switched_array
def clearDisplay(self):
'''
Clears display.
'''
GPIO.setup(self.ALL_PINS, GPIO.IN)
def displayPoint(self, coord):
'''
coord: type 'list', coordinates of single pixel to be lit
Lights a single pixel.
'''
self.clearDisplay()
GPIO.setup(self.array[coord[0]][coord[1]][0], GPIO.OUT, initial = 1)
GPIO.setup(self.array[coord[0]][coord[1]][1], GPIO.OUT, initial = 0)
def test(self):
'''
Displays all pixels in array, one at a time, starting with [0,0] and ending with [6,7].
'''
x = 0
y = 0
while y < 8:
self.displayPoint([x,y])
time.sleep(0.1)
x += 1
if x >= 7:
x = 0
y += 1
self.clearDisplay()
def display(self, pixels, duration):
'''
pixels: type 'list', list of pixels to be lit each in coordinate form [x,y]
duration: type 'int', duration to display coordinates
Lights specified pixels in array
'''
positives = []
for coord in pixels:
if self.array[coord[0]][coord[1]][0] not in positives:
positives.append([self.array[coord[0]][coord[1]][0],[]])
for i in positives: #[[a,[]],[b,[]],[h,[]]]
for coord in pixels:
if self.array[coord[0]][coord[1]][0] == i[0]:
if self.array[coord[0]][coord[1]][1] not in i[1]:
i[1].append(self.array[coord[0]][coord[1]][1])
t = 0
pause = 0.02/len(positives)
while t < duration:
for i in range(0, len(positives)):
self.clearDisplay()
GPIO.setup(positives[i][0], GPIO.OUT, initial = True)
GPIO.setup(positives[i][1], GPIO.OUT, initial = False)
time.sleep(pause)
t += pause
self.clearDisplay()
def screensaver(self, duration, fill = .5):
'''
duration: type 'int', duration to keep screensaver on
fill: type 'float', proportion of array to fill with pixels at any given time
Randomly displays pixels on array.
'''
if fill > 1 or fill < 0:
print("fill must be of type 'float' between 0 and 1...using default value instead.")
fill = 0.5
t = 0
while t < duration:
coords = []
while len(coords) < fill*56:
coord = [random.randint(0,6), random.randint(0,7)]
if coord not in coords:
coords.append(coord)
self.display(coords, 0.15)
t += 0.1
|
mandyRae/pythonic-charlieplex
|
charlie.py
|
Python
|
mit
| 5,714
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.3082
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Example.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Example.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
|
graphnode/imgtagger
|
AutoUpdater/Example/Properties/Resources.Designer.cs
|
C#
|
mit
| 2,772
|
package com.github.lg198.codefray.util;
public class TimeFormatter {
public static String format(long seconds) {
if (seconds < 60) {
return pluralSeconds(seconds);
}
int minutes = (int) (seconds / 60.0);
return pluralMinutes(minutes) + " and " + pluralSeconds(seconds % 60);
}
public static String pluralSeconds(long i) {
if (i == 1) {
return i + " second";
}
return i + " seconds";
}
public static String pluralMinutes(long i) {
if (i == 1) {
return i + " minute";
}
return i + " minutes";
}
}
|
lg198/CodeFray
|
src/com/github/lg198/codefray/util/TimeFormatter.java
|
Java
|
mit
| 639
|
package org.webjars.urlprotocols;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.regex.Pattern;
import org.webjars.CloseQuietly;
public class JarUrlProtocolHandler implements UrlProtocolHandler {
@Override
public boolean accepts(String protocol) {
return "jar".equals(protocol);
}
@Override
public Set<String> getAssetPaths(URL url, Pattern filterExpr, ClassLoader... classLoaders) {
HashSet<String> assetPaths = new HashSet<String>();
String[] segments = url.getPath().split(".jar!/");
JarFile jarFile = null;
JarInputStream jarInputStream = null;
try {
for (int i = 0; i < segments.length - 1; i++) {
String segment = segments[i] + ".jar";
if (jarFile == null) {
File file = new File(URI.create(segment));
jarFile = new JarFile(file);
if (i == segments.length - 2) {
jarInputStream = new JarInputStream(new FileInputStream(file));
}
} else {
jarInputStream = new JarInputStream(jarFile.getInputStream(jarFile.getEntry(segment)));
}
}
JarEntry jarEntry = jarInputStream.getNextJarEntry();
while (jarEntry !=null) {
String assetPathCandidate = jarEntry.getName();
if (!jarEntry.isDirectory() && filterExpr.matcher(assetPathCandidate).matches()) {
assetPaths.add(assetPathCandidate);
}
jarEntry = jarInputStream.getNextJarEntry();
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
CloseQuietly.closeQuietly(jarFile);
CloseQuietly.closeQuietly(jarInputStream);
}
return assetPaths;
}
}
|
mwanji/webjars-locator-core
|
src/main/java/org/webjars/urlprotocols/JarUrlProtocolHandler.java
|
Java
|
mit
| 2,152
|
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => env('DB_DSN', 'mysql:host=localhost;dbname=dbmain'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
];
|
ertrade/yii2-app-basic
|
app/config/db.php
|
PHP
|
mit
| 234
|
@section('main')
@include('hack::input.edit.'.$type['type'])
@parent
@stop
|
Thorazine/hack
|
src/resources/views/cms/positions/edit/main.blade.php
|
PHP
|
mit
| 76
|
module Perican
module Resource
class Document < Base
def initialize(document)
@document = document
end
def uid
@document[:inode]
end
def date
@document[:atime]
end
def summary
@document[:path]
end
def description
nil
end
def originator
nil
end
def recipients
[]
end
def source
@document
end
end # class Document
end # module Resource
end # module Perican
|
nomlab/perican
|
lib/perican/resource/document.rb
|
Ruby
|
mit
| 534
|
<?php
namespace App\ContactBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Contact
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="App\ContactBundle\Entity\ContactRepository")
*/
class Contact
{
public function __construct(){
$this->created_at = new \Datetime();
}
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="nom", type="string", length=255)
*/
private $nom;
/**
* @var string
*
* @ORM\Column(name="email", type="string", length=255)
*/
private $email;
/**
* @var string
*
* @ORM\Column(name="pays", type="string", length=255, nullable=true)
*/
private $pays;
/**
* @var string
*
* @ORM\Column(name="tel", type="string", length=255, nullable=true)
*/
private $tel;
/**
* @var string
*
* @ORM\Column(name="message", type="text")
*/
private $message;
/**
*
* @ORM\Column(name="created_at", type="date")
*/
private $created_at;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
* @return Contact
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* @return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set email
*
* @param string $email
* @return Contact
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set country
*
* @param string $country
* @return Contact
*/
public function setPays($pays)
{
$this->pays = $pays;
return $this;
}
/**
* Get pays
*
* @return string
*/
public function getPays()
{
return $this->pays;
}
/**
* Set tel
*
* @param string $tel
* @return Contact
*/
public function setTel($tel)
{
$this->tel = $tel;
return $this;
}
/**
* Get tel
*
* @return string
*/
public function getTel()
{
return $this->tel;
}
/**
* Set message
*
* @param string $message
* @return Contact
*/
public function setMessage($message)
{
$this->message = $message;
return $this;
}
/**
* Get message
*
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
* Set created_at
*
* @param \DateTime $createdAt
* @return Contact
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
return $this;
}
/**
* Get created_at
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->created_at;
}
}
|
KhalidSookia/kns
|
src/App/ContactBundle/Entity/Contact.php
|
PHP
|
mit
| 3,327
|
'use strict';
/**
* @ngdoc function
* @name teamDjApp.controller:AboutCtrl
* @description
* # AboutCtrl
* Controller of the teamDjApp
*/
angular.module('teamDjApp')
.controller('AboutCtrl', function ($rootScope) {
$rootScope.activetab = 'about';
});
|
thenarruc/team-dj
|
app/scripts/controllers/about.js
|
JavaScript
|
mit
| 264
|
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInitb7d78871a17da8cabc66e42282b3b1ac::getLoader();
|
ArcherSys/ArcherSys
|
webmail/vendor/autoload.php
|
PHP
|
mit
| 178
|
namespace _07.Equality_Logic.Interfaces
{
public interface IPerson
{
string Name { get; }
int Age { get; }
}
}
|
HristoSpasov/C-Sharp-Advanced
|
06. Exercise Iterators and Comparators/07. Equality Logic/Interfaces/IPerson.cs
|
C#
|
mit
| 142
|
module("Unit - Party",{
setup: function(){
var mod = this;
Ember.run(this,function(){
var appController = App.__container__.lookup("controller:application") ;
mod.appC = appController ;
mod.store = appController.store ;
resetTests(mod.store).then(function(){
mod.baseParty = mod.store.createRecord('party',{
name: 'baseparty',
size: 2,
phone_number: '3125551212',
time_taken: '2013-11-05T20:15:15'
}) ;
}) ;
}) ;
wait() ;
},
teardown: function(){
destroy(this.store, this.appC) ;
return wait() ;
}
}) ;
asyncTest("party.notified", 2, function() {
var party = this.baseParty;
equal(false, party.get('notified'), "initially, party.notified should be false") ;
Ember.run(function(){
party.set('time_notified', '2013-11-05T20:35:15') ;
equal(true, party.get('notified'), "after setting time_notified, party.notified should be true") ;
start() ;
});
});
asyncTest("party.seated", 2, function() {
var party = this.baseParty;
equal(false, party.get('seated'), "initially, party.seated should be false") ;
Ember.run(function(){
party.set('time_seated', '2013-11-05T20:35:15') ;
equal(true, party.get('seated'), "after setting time_seated, party.seated should be true") ;
start() ;
});
});
asyncTest("party.waiting depends on party.time_seated", 3, function() {
var party = this.baseParty;
equal(true, party.get('waiting'), "initially, party.waiting should be true") ;
Ember.run(function(){
party.set('time_seated', '2013-11-05T20:35:15') ;
equal(false, party.get('waiting'), "after setting time_seated, party.waiting should be false") ;
party.set('time_seated', null) ;
equal(true, party.get('waiting'), "after setting time_seated to null, party.waiting should be true") ;
start() ;
});
});
asyncTest("party.waiting depends on party.time_cancelled", function() {
var party = this.baseParty;
equal(party.get('waiting'), true, "initially, party.waiting should be true") ;
Ember.run(function(){
party.set('time_cancelled', '2013-11-05T20:35:15') ;
equal(party.get('waiting'), false, "after setting time_cancelled, party.waiting should be false") ;
party.set('time_cancelled', null) ;
equal(party.get('waiting'), true, "after setting time_cancelled to null, party.waiting should be true") ;
start() ;
});
});
asyncTest("party.waiting depends on party.time_cancelled and party.time_seated", function() {
var party = this.baseParty;
equal(party.get('waiting'), true, "initially, party.waiting should be true") ;
Ember.run(function(){
party.set('time_seated', '2013-11-05T20:35:15') ;
equal(party.get('waiting'), false, "after setting time_seated, party.waiting should be false") ;
party.set('time_cancelled', '2013-11-05T20:40:15') ;
equal(party.get('waiting'), false, "after setting time_cancelled, party.waiting should still be false") ;
party.set('time_cancelled', null) ;
equal(party.get('waiting'), false, "after setting time_cancelled to null, party.waiting should still be false") ;
party.set('time_seated', null) ;
equal(party.get('waiting'), true, "after setting time_seated and time_cancelled to null, party.waiting should be true") ;
start() ;
});
});
asyncTest("party.countdown should count down seconds", function(){
var party = this.baseParty ;
var now = moment() ;
Ember.run(function(){
party.set('time_notified',now.subtract('minute',1).format("YYYY-MM-DDTHH:mm:ss")) ;
var rem = Math.round(party.get('countdown')/1000) ;
ok(Math.abs(rem-(4*60)) <= 1, "countdown should equal 4 min give or take a second") ;
start() ;
});
}) ;
asyncTest("party.countdown should count up if negative", function(){
var party = this.baseParty ;
Ember.run(function(){
var now = moment() ;
party.set('time_notified',now.subtract('minute',7).format("YYYY-MM-DDTHH:mm:ss")) ;
var rem = Math.round(party.get('countdown')/1000) ;
ok(Math.abs(rem-(2*60)) <= 1, "countup should equal 2 min give or take a second") ;
});
Ember.run(function(){
var now = moment() ;
party.set('time_notified',now.subtract('minute',9).format("YYYY-MM-DDTHH:mm:ss")) ;
var rem = Math.round(party.get('countdown')/1000) ;
ok(Math.abs(rem-(4*60)) <= 1, "countup should equal 4 min give or take a second") ;
start() ;
});
}) ;
asyncTest("party.overdue", function(){
var party = this.baseParty ;
var now = moment() ;
equal(party.get('overdue'), false, "Party should not be initially overdue") ;
Ember.run(function(){
party.set('time_notified',now.subtract('minute',3).format("YYYY-MM-DDTHH:mm:ss")) ;
equal(party.get('overdue'), false, "Party should not be overdue at 3 min") ;
});
Ember.run(function(){
party.set('time_notified',now.subtract('minute',7).format("YYYY-MM-DDTHH:mm:ss")) ;
equal(party.get('overdue'), true, "Party should be overdue at 7 min") ;
start() ;
});
}) ;
|
benwilhelm/tbt-client
|
app/tests/unit/party.js
|
JavaScript
|
mit
| 5,035
|
#include <boost/test/unit_test.hpp>
#include "types/ds/hash_functions.hpp"
#include <limits>
#include <iostream>
BOOST_AUTO_TEST_SUITE(TestHashFunctions)
BOOST_AUTO_TEST_CASE(hash_division_method_m_is_power_of_2)
{
const size_t num_of_buckets = 16;
Types::DS::HashModulo hash_func(num_of_buckets);
std::vector<size_t> stat(num_of_buckets, 0);
const auto max = static_cast<size_t>(std::numeric_limits<uint8_t>::max());
for (size_t i = 0; i < max; ++i) {
++stat[hash_func(i)];
}
// std::cout << "Test of hash function that uses division method. Num of buckets is " <<
// "power of 2: " << num_of_buckets << std::endl;
// std::cout << "Here is statistics that shows how many numbers [0, max(uchar)] would be " <<
// "assigned to the same bucket" << std::endl;
// for (size_t i = 0; i < stat.size(); ++i) {
// std::cout << i << ": " << stat[i] << std::endl;
// }
}
BOOST_AUTO_TEST_CASE(hash_multiplication_method)
{
const size_t num_of_buckets = 16;
Types::DS::HashMultiplication hash_func(num_of_buckets);
std::vector<size_t> stat(num_of_buckets, 0);
const auto max = static_cast<size_t>(std::numeric_limits<uint8_t>::max());
for (size_t i = 0; i < max; ++i) {
++stat[hash_func(i)];
}
// std::cout << "Test of hash function that uses multiplication method. Num of buckets is " <<
// "power of 2: " << num_of_buckets << std::endl;
// std::cout << "Here is statistics that shows how many numbers [0, max(uchar)] would be " <<
// "assigned to the same bucket" << std::endl;
// for (size_t i = 0; i < stat.size(); ++i) {
// std::cout << i << ": " << stat[i] << std::endl;
// }
}
BOOST_AUTO_TEST_CASE(hash_multiply_shift_method)
{
const size_t num_of_buckets = 16;
Types::DS::HashMultiplyShift hash_func(num_of_buckets);
std::vector<size_t> stat(num_of_buckets, 0);
const auto max = static_cast<int32_t>(std::numeric_limits<uint8_t>::max());
for (int32_t i = 1; i < max; ++i) {
++stat[hash_func(i)];
}
// std::cout << "Test of hash function that uses multiply-shift method. Num of buckets is " <<
// "power of 2: " << num_of_buckets << std::endl;
// std::cout << "Here is statistics that shows how many numbers [0, max(uchar)] would be " <<
// "assigned to the same bucket" << std::endl;
// for (size_t i = 0; i < stat.size(); ++i) {
// std::cout << i << ": " << stat[i] << std::endl;
// }
}
BOOST_AUTO_TEST_CASE(hash_multiply_add_shift_method)
{
const size_t num_of_buckets = 16;
Types::DS::HashMultiplyAddShift hash_func(num_of_buckets);
std::vector<size_t> stat(num_of_buckets, 0);
const auto max = static_cast<int32_t>(std::numeric_limits<uint8_t>::max());
for (int32_t i = 1; i < max; ++i) {
++stat[hash_func(i)];
}
// std::cout << "Test of hash function that uses multiply-add-shift method. Num of buckets is " <<
// "power of 2: " << num_of_buckets << std::endl;
// std::cout << "Here is statistics that shows how many numbers [0, max(uchar)] would be " <<
// "assigned to the same bucket" << std::endl;
// for (size_t i = 0; i < stat.size(); ++i) {
// std::cout << i << ": " << stat[i] << std::endl;
// }
}
BOOST_AUTO_TEST_CASE(hash_vector)
{
const size_t num_of_buckets = 16;
Types::DS::HashVector hash_func(num_of_buckets);
std::vector<size_t> stat(num_of_buckets, 0);
Types::DS::helpers::RandomGenerator size_generator(10);
Types::DS::helpers::RandomGenerator num_generator(8);
for (size_t i = 0; i < 100; ++i) {
std::vector<int32_t> v(size_generator.generate(), 0);
std::generate(
v.begin(), v.end(), [&num_generator](){ return num_generator.generate(); });
++stat[hash_func(v)];
}
// std::cout << "Test of hash function for vectors. Num of buckets is " <<
// "power of 2: " << num_of_buckets << std::endl;
// std::cout << "Here is statistics that shows how many vectors would be " <<
// "assigned to the same bucket" << std::endl;
// for (size_t i = 0; i < stat.size(); ++i) {
// std::cout << i << ": " << stat[i] << std::endl;
// }
}
BOOST_AUTO_TEST_CASE(hash_string)
{
const size_t num_of_buckets = 16;
Types::DS::HashString<char> hash_func(num_of_buckets);
std::vector<size_t> stat(num_of_buckets, 0);
Types::DS::helpers::RandomGenerator size_generator(10);
Types::DS::helpers::RandomGenerator char_generator(1, 127);
for (size_t i = 0; i < 100; ++i) {
std::string s(size_generator.generate(), '0');
std::generate(
s.begin(), s.end(), [&char_generator](){ return char_generator.generate(); });
++stat[hash_func(s)];
}
// std::cout << "Test of hash function for vectors. Num of buckets is " <<
// "power of 2: " << num_of_buckets << std::endl;
// std::cout << "Here is statistics that shows how many vectors would be " <<
// "assigned to the same bucket" << std::endl;
// for (size_t i = 0; i < stat.size(); ++i) {
// std::cout << i << ": " << stat[i] << std::endl;
// }
}
BOOST_AUTO_TEST_SUITE_END()
|
iamantony/CppNotes
|
test/types/ds/test_hash_functions.cpp
|
C++
|
mit
| 5,680
|
using System;
namespace _02CirclePerimeter
{
class Program
{
static void Main()
{
double radius = double.Parse(Console.ReadLine());
Console.WriteLine("{0:f12}", 2 * Math.PI * radius);
}
}
}
|
Avarea/Programming-Fundamentals
|
IntegerAndRealNumbers/02CirclePerimeter/Program.cs
|
C#
|
mit
| 255
|
---
layout: post
title: "Wagrant という Web 系の勉強会用の Vagrant 環境を作りました。"
date: 2016-12-19
author: "Takayuki Miyauchi"
header-img: "img/2016-12-19-wagrant.png"
---
Wacker では言語や技術を問わず、毎回いろいろなジャンルの勉強会を行っていますが、開発環境の構築に費やす時間がどうしてもそれなりに発生してしまうので、WEB 系の勉強会を想定した汎用的な Vagrant 環境をつくりました。
[https://github.com/wakayama-hacker/wagrant](https://github.com/wakayama-hacker/wagrant)
インストールされているものは以下のような感じです。
* Ubuntu 16.04 Xenial64
* Apache
* MySQL
* PHP 7
* Ruby 2.3
* Node.js 6.x
## 特徴
たいした特徴はなにもありませんが(むしろそれを重視)、以下のようにあらかじめパスが通ってたりします。
```.bash_profile
export COMPOSER_HOME=$HOME/.composer
export PATH=$HOME/.composer/vendor/bin:$PATH
export PATH=$HOME/.npm-packages/bin:$PATH
if which ruby >/dev/null && which gem >/dev/null; then
PATH="$(ruby -rubygems -e 'puts Gem.user_dir')/bin:$PATH"
fi
```
あと、`.gemrc` にあらかじめ `gem: --user-install` って書いてあったり、`.npmrc` に `prefix = ${HOME}/.npm-packages` と書いてあったりします。
## 使い方
1. [VirtualBox](https://www.virtualbox.org/) および [Vagrant](https://www.vagrantup.com/) をあらかじめインストールしてください。
2. [最新版](https://github.com/wakayama-hacker/wagrant/releases)を任意のディレクトリにダウンロードしてください。
3. ダウンロードしたファイルを任意のディレクトリに解凍してください。
つづけてコマンドラインで以下のように操作してください。
```
$ cd ~/Desktop/wagrant
$ vagrant up
```
`vagrant` についてはドキュメントをご覧になってください。
[https://www.vagrantup.com/docs/](https://www.vagrantup.com/docs/)
ハンズオンや勉強会で使用する際には、参加者にかならず `vagrant destroy` をしてもらいましょう。
|
wakayama-hacker/wacker.io
|
_posts/2016-12-19-we-released-wagrant.md
|
Markdown
|
mit
| 2,187
|
// <copyright file="SingleObservableIntegration.cs" company="Kyubisation">
// Copyright (c) Kyubisation. All rights reserved.
// </copyright>
// ReSharper disable once CheckNamespace
namespace FluentRestBuilder
{
using Microsoft.AspNetCore.Mvc;
public static class SingleObservableIntegration
{
/// <summary>
/// Create an observable which emits the given value.
/// </summary>
/// <typeparam name="TSource">The type of the given value.</typeparam>
/// <param name="controller">The MVC controller.</param>
/// <param name="value">The value.</param>
/// <returns>An instance of <see cref="IProviderObservable{T}"/>.</returns>
public static IProviderObservable<TSource> CreateSingle<TSource>(
this ControllerBase controller, TSource value)
{
Check.IsNull(controller, nameof(controller));
return Observable.Single(value, controller.HttpContext.RequestServices);
}
}
}
|
kyubisation/FluentRestBuilder
|
src/FluentRestBuilder/Observables/SingleObservableIntegration.cs
|
C#
|
mit
| 1,002
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.