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.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("11. NumbersInIntervalDividableByGivenNumber")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("11. NumbersInIntervalDividableByGivenNumber")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[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("60f28021-942d-487a-9635-168035faf923")]
// 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")]
|
petyodelta/CSharp-PartOne-Homework
|
ConsoleInputOutputHomework/11. NumbersInIntervalDividableByGivenNumber/Properties/AssemblyInfo.cs
|
C#
|
mit
| 1,480
|
/* */
module.exports = function(hljs) {
return {
contains: [
{
begin: /[^\u2401\u0001]+/,
end: /[\u2401\u0001]/,
excludeEnd: true,
returnBegin: true,
returnEnd: false,
contains: [
{
begin: /([^\u2401\u0001=]+)/,
end: /=([^\u2401\u0001=]+)/,
returnEnd: true,
returnBegin: false,
className: 'attribute'
},
{
begin: /=/,
end: /([\u2401\u0001])/,
excludeEnd: true,
excludeBegin: true,
className: 'string'
}]
}],
case_insensitive: true
};
};
|
Imms/imms.github.io
|
jspm_packages/npm/highlight.js@8.9.1/lib/languages/fix.js
|
JavaScript
|
mit
| 597
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package co.edu.uniandes.ecos.tarea6.util;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Daniel
*/
public class CalcularTest {
private Double x;
private Double dof;
private Double xi;
private Double delta;
public CalcularTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
x = new Double("1.1");
dof = new Double("9");
xi = new Double("0.22");
delta = new Double("0.1");
}
@After
public void tearDown() {
}
/**
* Test of promedio method, of class Calcular.
*/
@Test
public void testFuncionX() {
System.out.println("funcionX");
Double expResult = new Double("0.37");
Double result = Calcular.funcionX(xi,dof);
assertEquals(expResult, result, delta);
}
/**
* Test of varianza method, of class Calcular.
*/
@Test
public void testFactorial() {
System.out.println("factorial");
Double expResult = new Double("24");
Double result = Calcular.factorial(new Double("4"));
assertEquals(expResult, result);
}
/**
* Test of desviacionEstandar method, of class Calcular.
*/
@Test
public void testValorIntermedio() {
System.out.println("desviacionEstandar");
Double expResult = new Double("0.0277");
Double result = Calcular.valorIntermedio(new Double("0.11"), new Double(2), new Double("0.37777"));
assertEquals(expResult, result, delta);
}
}
|
darevalor/Ecos-Tarea6
|
src/test/java/co/edu/uniandes/ecos/tarea6/util/CalcularTest.java
|
Java
|
mit
| 1,932
|
// Copyright © 2018-2021 Wei Shen <shenwei356@gmail.com>
//
// 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.
package sketches
var base2bit = [256]uint64{
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 0, 1, 1, 0, 4, 4, 2, 0, 4, 4, 2, 4, 0, 0, 4,
4, 4, 0, 1, 3, 3, 0, 0, 4, 1, 4, 4, 4, 4, 4, 4,
4, 0, 1, 1, 0, 4, 4, 2, 0, 4, 4, 2, 4, 0, 0, 4,
4, 4, 0, 1, 3, 3, 0, 0, 4, 1, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
}
var bit2base = [4]byte{'A', 'C', 'G', 'T'}
|
shenwei356/bio
|
sketches/kmers.go
|
GO
|
mit
| 2,010
|
<?php
declare(strict_types=1);
namespace BrowscapPHP;
use BrowscapPHP\Parser\ParserInterface;
use stdClass;
/**
* Browscap.ini parsing class with caching and update capabilities
*/
interface BrowscapInterface
{
/**
* Set theformatter instance to use for the getBrowser() result
*
* @throws void
*
* @no-named-arguments
*/
public function setFormatter(Formatter\FormatterInterface $formatter): void;
/**
* Sets the parser instance to use
*
* @throws void
*
* @no-named-arguments
*/
public function setParser(ParserInterface $parser): void;
/**
* returns an instance of the used parser class
*
* @throws void
*
* @no-named-arguments
*/
public function getParser(): ParserInterface;
/**
* parses the given user agent to get the information about the browser
*
* if no user agent is given, it uses {@see \BrowscapPHP\Helper\Support} to get it
*
* @param string $userAgent the user agent string
*
* @return stdClass the object containing the browsers details.
*
* @throws Exception
*
* @no-named-arguments
*/
public function getBrowser(?string $userAgent = null): stdClass;
}
|
browscap/browscap-php
|
src/BrowscapInterface.php
|
PHP
|
mit
| 1,262
|
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour
{
public GameObject player;
private Vector3 offset;
// Use this for initialization
void Start ()
{
offset = transform.position;
}
// Update is called once per frame
void LateUpdate ()
{
transform.position = player.transform.position + offset;
}
}
|
HakonHesselberg/gamedev
|
Roll-a-Ball/Assets/Scripts/CameraController.cs
|
C#
|
mit
| 372
|
class A extends B {
X() {
return super[1];
}
}
|
harc/ohm
|
examples/ecmascript/test/data/esprima/ES6/super-property/super_computed.js
|
JavaScript
|
mit
| 55
|
# IPFilter Updater
Downloads IP Filter lists for use in Bit Torrent clients.
## Features
* Provides choice of list providers
* Automatically decompresses lists that are in Gzip or Zip format
* Can automatically schedule itself to update the list silently
* Auto-updating
## Requirements
* Microsoft Windows XP+
* .NET Framework 4 or greater
## FAQ
### What is IPFilter Updater?
It's a small Windows application that will download and update an ipfilter list for use in Bit Torrent clients.
### What Bit Torrent clients are supported?
Currently uTorrent, BitTorrent and qBittorrent are supported out of the box, but you can also configure other applications to pick up the downloaded list.
### What is an ipfilter?
An ipfilter list is a simple (but usually very large) list of addresses and ranges of malicious peers that will transmit junk data (i.e. anti-P2P) or peers that may be intrusive on your net privacy.
### Why do I need an ipfilter?
For privacy and more reliable peers
### Why do I need IPFilter Updater?
It will make it easier to download a list, and keep it up to date
### Where does the list come from?
I do not maintain any of the lists.
I try to keep a variety of third party list options available, but the availability and quality of free, up to date lists seems to be dwindling.
|
DavidMoore/ipfilter
|
README.md
|
Markdown
|
mit
| 1,317
|
<div class="commune_descr limited">
<p>
Iville est
un village
localisé dans le département de l'Eure en Haute-Normandie. Elle comptait 452 habitants en 2008.</p>
<p>À proximité de Iville sont positionnées géographiquement les villes de
<a href="{{VLROOT}}/immobilier/fouqueville_27261/">Fouqueville</a> située à 4 km, 409 habitants,
<a href="{{VLROOT}}/immobilier/marbeuf_27389/">Marbeuf</a> à 4 km, 340 habitants,
<a href="{{VLROOT}}/immobilier/epegard_27219/">Épégard</a> localisée à 3 km, 415 habitants,
<a href="{{VLROOT}}/immobilier/crosville-la-vieille_27192/">Crosville-la-Vieille</a> située à 2 km, 555 habitants,
<a href="{{VLROOT}}/immobilier/crestot_27185/">Crestot</a> située à 4 km, 368 habitants,
<a href="{{VLROOT}}/immobilier/amfreville-la-campagne_27011/">Amfreville-la-Campagne</a> située à 4 km, 896 habitants,
entre autres. De plus, Iville est située à seulement 26 km de <a href="{{VLROOT}}/immobilier/saint-pierre_97416/">Saint-Pierre</a>.</p>
<p>Si vous pensez venir habiter à Iville, vous pourrez facilement trouver une maison à acheter. </p>
<p>Le parc de logements, à Iville, se décomposait en 2011 en quatre appartements et 182 maisons soit
un marché plutôt équilibré.</p>
</div>
|
donaldinou/frontend
|
src/Viteloge/CoreBundle/Resources/descriptions/27354.html
|
HTML
|
mit
| 1,289
|
<?php
namespace Sherlock\responses;
/**
* Class DeleteResponse
* @package Sherlock\responses
*/
class DeleteResponse extends Response
{
/**
* @var bool
*/
public $found;
/**
* @param \Sherlock\common\tmp\RollingCurl\Request $response
*/
public function __construct($response)
{
parent::__construct($response);
if (isset($this->responseData['found'])) {
$this->ok = $this->responseData['found'];
}
}
}
|
polyfractal/sherlock
|
src/Sherlock/responses/DeleteResponse.php
|
PHP
|
mit
| 491
|
require 'spec_helper'
describe Gliffy::Document do
before :each do
Gliffy::Document.clear_cache
end
let(:api) { double(Gliffy::API::Facade) }
let(:owner) do
owner = double(Gliffy::Account)
owner.stub(:api).and_return(api)
owner
end
let(:document_id) { 1000002 }
let(:document_name) { 'SNPP Domain Model' }
let(:response) do
Gliffy::API::Response.new(fixture(
"document",
:document_id => document_id,
:document_name => document_name
)
)
end
let(:document) do
Gliffy::Document.load(owner, response.node("//g:document"))
end
it "has an id" do
expect(document).to respond_to :id
expect(document.id).to eq document_id
end
it "has a name" do
expect(document).to respond_to :name
expect(document.name).to eq document_name
end
it "has 'public access' flag" do
expect(document).to respond_to :public?
expect(document.public?).to eq(true)
end
it "has a version number" do
expect(document).to respond_to :versions
expect(document.versions).to eq(5)
end
it "has a modification date" do
expect(document).to respond_to :modified
expect(document.modified).to eq(DateTime.new(2008, 7, 8, 17, 31, 23))
end
it "has a creation date" do
expect(document).to respond_to :created
expect(document.created).to eq(DateTime.new(2008, 7, 8, 17, 31, 24))
end
it "has a publication date" do
expect(document).to respond_to :published
expect(document.published).to eq(DateTime.new(2008, 7, 8, 17, 31, 25))
end
it "has an owner" do
expect(document).to respond_to :owner
expect(document.owner).to be(owner)
end
it "has a link to gliffy editor" do
return_url = "sample/url"
return_text = "RETURN TEXT"
api.should_receive(
:web
).with(
"/gliffy/",
hash_including(
:launchDiagramId => document_id,
:returnURL => return_url,
:returnButtonText => return_text
)
).and_return(
"http://www.gliffy.com/gliffy/?launchDiagramId=#{document.id}&returnURL=#{return_url}&returnButtonText=#{return_text}"
)
link = document.editor(return_url, return_text)
expect(link).to match '/gliffy/'
expect(link).to match 'launchDiagramId='
expect(link).to match document.id.to_s
expect(link).to match 'returnURL='
expect(link).to match return_url
expect(link).to match 'returnButtonText='
expect(link).to match return_text
end
it "has an PNG image" do
expect(document).to respond_to :png
expect(document.png).to be_instance_of Gliffy::Document::Presentation::PNG
end
it "has SVG representation" do
expect(document).to respond_to :svg
expect(document.svg).to be_instance_of Gliffy::Document::Presentation::SVG
end
it "has XML representation" do
expect(document).to respond_to :xml
expect(document.xml).to be_instance_of Gliffy::Document::Presentation::XML
end
it "has singleton-life behavior" do
doc1 = Gliffy::Document.load(owner, response.node("//g:document"))
expect(doc1).to be document
end
it "can be renamed" do
expect(document).to respond_to :rename
end
context "when renamed" do
let(:new_name) { "NEW DOCUMENT NAME" }
before :each do
api.stub(:update_document_metadata)
document.rename new_name
end
it "changes the name to the new value" do
expect(document.name).to eq new_name
end
it "calls rename method of the REST API" do
expect(api).to have_received(:update_document_metadata)
.with(document_id, new_name, nil)
end
end
it "can be made public or private" do
expect(document).to respond_to :public=
end
context "when public state changes" do
let(:new_shared) { false }
before :each do
api.stub(:update_document_metadata)
document.public = new_shared
end
it "calls REST API" do
expect(api).to have_received(:update_document_metadata)
.with(document_id, nil, new_shared)
end
it "updates local object" do
expect(document.public?).to eq new_shared
end
end
it "can be moved" do
expect(document).to respond_to :move
end
context "when moved" do
let(:observer) { double(Object, :update => nil) }
let(:folder) do
double(Gliffy::Folder,
:path => "ROOT/FOLDER/SUBFOLDER",
:update => nil)
end
before :each do
api.stub(:move_document)
document.add_observer(observer)
document.move(folder)
end
it "calls REST API" do
expect(api).to have_received(:move_document)
.with(document.id, folder.path)
end
it "notifies observers" do
expect(observer).to have_received(:update)
.with(:document_removed, document)
end
it "notifies new parent" do
expect(folder).to have_received(:update)
.with(:document_added, document)
end
end
it "can be deleted" do
expect(document).to respond_to :delete
end
it "has flag indicating whether this object has been deleted" do
expect(document).to respond_to :deleted?
end
context "when not deleted" do
it "knows it" do
expect(document.deleted?).to be_false
end
end
context "when deleted" do
let(:observer) { double(Object) }
before :each do
api.stub(:delete_document)
observer.stub(:update)
document.add_observer(observer)
document.delete
end
it "calls REST API" do
expect(api).to have_received(:delete_document)
.with(document_id)
end
it "knows it" do
expect(document.deleted?).to be_true
end
it "notifies observers" do
expect(observer).to have_received(:update).with(:document_deleted, document)
end
end
end
|
bkon/gliffy
|
spec/lib/gliffy/document_spec.rb
|
Ruby
|
mit
| 5,763
|
package org.inventivetalent.nbt;
import com.google.gson.JsonPrimitive;
import org.inventivetalent.nbt.stream.NBTInputStream;
import org.inventivetalent.nbt.stream.NBTOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class StringTag extends NBTTag<String> {
private String value;
public StringTag() {
this("");
}
public StringTag(String name) {
super(name);
this.value = "";
}
public StringTag(String name, String value) {
super(name);
this.value = value;
}
@Override
public String getValue() {
return value;
}
@Override
public void setValue(String value) {
this.value = value;
}
@Override
public String getAsString() {
return value;
}
@Override
public byte getAsByte() {
return Byte.parseByte(value);
}
@Override
public short getAsShort() {
return Short.parseShort(value);
}
@Override
public int getAsInt() {
return Integer.parseInt(value);
}
@Override
public long getAsLong() {
return Long.parseLong(value);
}
@Override
public float getAsFloat() {
return Float.parseFloat(value);
}
@Override
public double getAsDouble() {
return Double.parseDouble(value);
}
@Override
public JsonPrimitive asJson() {
return new JsonPrimitive(value);
}
@Override
public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException {
byte[] bytes = new byte[in.readShort()];
in.readFully(bytes);
value = new String(bytes, NBTInputStream.UTF_8);
}
@Override
public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException {
byte[] bytes = value.getBytes(NBTOutputStream.UTF_8);
out.writeShort(bytes.length);
out.write(bytes);
}
@Override
public int getTypeId() {
return TagID.TAG_STRING;
}
@Override
public String getTypeName() {
return "TAG_String";
}
@Override
public String getNMSClass() {
return "NBTTagString";
}
@Override
public boolean equals(Object o) {
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; }
StringTag stringTag = (StringTag) o;
return value != null ? value.equals(stringTag.value) : stringTag.value == null;
}
@Override
public int hashCode() {
return value != null ? value.hashCode() : 0;
}
}
|
InventivetalentDev/NBTLibrary
|
src/main/java/org/inventivetalent/nbt/StringTag.java
|
Java
|
mit
| 2,287
|
import json
import datetime
import threading
from base_plugin import *
import base_plugin
#=============================================Messaging===================================
def send_message(recipient, message, mtype='chat'):
'''
Send a message to recipient.
:param recipient: The To field of your message.
:param message: the message string to send.
:para mtype: The message type to send, supports public/private and xmpp style chat/groupchat.
'''
if mtype == 'private':
mtype = 'chat'
if mtype == 'public':
mtype = 'groupchat'
base_plugin.PluginContext.client.send_message(mto=recipient, mbody=message, mtype=mtype)
#=============================================FILTERS=====================================
#FIXME: this seems broken.
def self_message(event, plugin):
'''
filter for self generated events.
:param event: the event being filtered
:param plugin: the plugin hosting the filter
returns - true if not self generated event, false otherwise.
'''
if msg.From_Nick != plugin.client.nick and plugin.client.nick in msg.Body:
return True
return False
def on_message(event, plugin):
'''
filter for group chat events.
:param event: the event being filtered
:param plugin: the plugin hosting the filter
returns - true if a group chat event, false otherwise.
'''
if event.Type in ["groupchat"]:
return True
return False
def on_private_message(event, plugin):
'''
filter for private message events.
:param event: the event being filtered
:param plugin: the plugin hosting the filter
returns - true if a private message event, false otherwise.
'''
if not event.Room:
return True
return False
def on_presence(event, plugin):
'''
filter for join/part type events.
:param event: the event being filtered
:param plugin: the plugin hosting the filter
returns - true if a presence event, false otherwise.
'''
if event.Type in ["available", "unavailable"]:
return True
return False
#=============================================FILE OPERATORS=====================================
def put_object_to_file(item, path):
'''
Syntactic sugar, write jsonified object to file.
:param item: Any json-able item.
:param path: path to log file.
'''
with open(path, 'w+') as f:
f.write(json.dumps(item))
def get_object_from_file(path):
'''
Syntactic sugar, read jsonified object from file.
:param path: path to log file where item is stored.
Returns - json expanded item from log file.
'''
with open(path, 'r') as f:
item_str = f.read()
return json.loads(item_str)
def append_to_file(string, path):
'''
Syntactic sugar, append string to file.
:param item: Any json-able item.
:param path: path to log file.
'''
with open(path, 'a') as f:
f.write(string)
def write_to_file(string, path):
'''
Syntactic sugar, write string to file.
:param item: Any json-able item.
:param path: path to log file.
'''
with open(path, 'w+') as f:
f.write(string)
def read_from_file(path):
'''
Syntactic sugar, read from file.
:param path: path to log file where item is stored.
Returns - string contents of log file.
'''
with open(path, 'r') as f:
return f.read()
def read_lines_from_file(path):
'''
Read lines from file, as seperated by newline/enter.
:param path: path to log file
Returns - list of lines
'''
return read_from_file(path).split('\n')
#===========================================TIMED EVENTS=====================================
def schedule_event_by_delay(delay, event, args=[]):
'''
Schedule an event by a delay in seconds.
:param delay: number of seconds until event triggers.
:param event: the action to be triggered.
:param args: the arguments to pass when the event is called. (default [])
'''
threading.Timer(delay, call_function_with_variable_arguments, [event, args]).start()
def schedule_event(time, event, args=[]):
'''
Schedule an event by an absolute time
:param time: the datetime object representing the trigger time.
:param event: the action to be triggered.
:param args: the arguments to pass when the event is called. (default [])
'''
delta = time - datetime.datetime.now()
threading.Timer(delta.total_seconds(), call_function_with_variable_arguments, [event, args]).start()
def schedule_event(year, month, day, hour, minute, second, event, args=[]):
'''
Schedule an event by an absolute time
:param year: year of the event
:param month: month of the event
:param day: day of the event
:param hour: hour of the event
:param minute: minute of the event
:param second: second of the event
:param event: the action to be triggered.
:param args: the arguments to pass when the event is called. (default [])
'''
time = datetime.datetime(year, month, day, hour, minute, second)
delta = time - datetime.datetime.now()
threading.Timer(delta.total_seconds(), call_function_with_variable_arguments, [event, args]).start()
#==========================================HERE THERE BE DRAGONS=================================================
def call_function_with_variable_arguments(function, arguments):
'''
Takes functions, takes arguments, makes it fit.
:param function: The function to call
:param arguments: The argument list to make fit.
'''
iterator = len(arguments)
while True:
real_exception = None
try:
function(*(arguments[:iterator]))
return
except Exception as e:
if not real_exception or "takes exactly" not in str(e) or "arguments" not in str(e):
real_exception = e
iterator -= 1
if iterator < 0:
raise real_exception
|
Gehn/JustAChatBot
|
plugin_utils.py
|
Python
|
mit
| 5,651
|
def cheese_and_crackers(cheese_count,boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
print "We can just give the function numbers directly:"
cheese_and_crackers(20,30)
print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese,amount_of_crackers)
print "We can even do math inside too."
cheese_and_crackers(10+20,5+6)
print "And we can combine the two,variables and math:"
cheese_and_crackers(amount_of_cheese+100,amount_of_crackers+1000)
|
BeeBubble/SnakeRace
|
LPTHW/ex019.py
|
Python
|
mit
| 673
|
/*
* backward.hpp
* Copyright 2013 Google Inc. All Rights Reserved.
*
* 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.
*/
#ifndef H_6B9572DA_A64B_49E6_B234_051480991C89
#define H_6B9572DA_A64B_49E6_B234_051480991C89
#ifndef __cplusplus
#error "It's not going to compile without a C++ compiler..."
#endif
#if defined(BACKWARD_CXX11)
#elif defined(BACKWARD_CXX98)
#else
#if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1800)
#define BACKWARD_CXX11
#define BACKWARD_ATLEAST_CXX11
#define BACKWARD_ATLEAST_CXX98
#if __cplusplus >= 201703L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
#define BACKWARD_ATLEAST_CXX17
#endif
#else
#define BACKWARD_CXX98
#define BACKWARD_ATLEAST_CXX98
#endif
#endif
// You can define one of the following (or leave it to the auto-detection):
//
// #define BACKWARD_SYSTEM_LINUX
// - specialization for linux
//
// #define BACKWARD_SYSTEM_DARWIN
// - specialization for Mac OS X 10.5 and later.
//
// #define BACKWARD_SYSTEM_WINDOWS
// - specialization for Windows (Clang 9 and MSVC2017)
//
// #define BACKWARD_SYSTEM_UNKNOWN
// - placebo implementation, does nothing.
//
#if defined(BACKWARD_SYSTEM_LINUX)
#elif defined(BACKWARD_SYSTEM_DARWIN)
#elif defined(BACKWARD_SYSTEM_UNKNOWN)
#elif defined(BACKWARD_SYSTEM_WINDOWS)
#else
#if defined(__linux) || defined(__linux__)
#define BACKWARD_SYSTEM_LINUX
#elif defined(__APPLE__)
#define BACKWARD_SYSTEM_DARWIN
#elif defined(_WIN32)
#define BACKWARD_SYSTEM_WINDOWS
#else
#define BACKWARD_SYSTEM_UNKNOWN
#endif
#endif
#define NOINLINE __attribute__((noinline))
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <new>
#include <sstream>
#include <streambuf>
#include <string>
#include <vector>
#include <exception>
#include <iterator>
#if defined(BACKWARD_SYSTEM_LINUX)
// On linux, backtrace can back-trace or "walk" the stack using the following
// libraries:
//
// #define BACKWARD_HAS_UNWIND 1
// - unwind comes from libgcc, but I saw an equivalent inside clang itself.
// - with unwind, the stacktrace is as accurate as it can possibly be, since
// this is used by the C++ runtine in gcc/clang for stack unwinding on
// exception.
// - normally libgcc is already linked to your program by default.
//
// #define BACKWARD_HAS_LIBUNWIND 1
// - libunwind provides, in some cases, a more accurate stacktrace as it knows
// to decode signal handler frames and lets us edit the context registers when
// unwinding, allowing stack traces over bad function references.
//
// #define BACKWARD_HAS_BACKTRACE == 1
// - backtrace seems to be a little bit more portable than libunwind, but on
// linux, it uses unwind anyway, but abstract away a tiny information that is
// sadly really important in order to get perfectly accurate stack traces.
// - backtrace is part of the (e)glib library.
//
// The default is:
// #define BACKWARD_HAS_UNWIND == 1
//
// Note that only one of the define should be set to 1 at a time.
//
#if BACKWARD_HAS_UNWIND == 1
#elif BACKWARD_HAS_LIBUNWIND == 1
#elif BACKWARD_HAS_BACKTRACE == 1
#else
#undef BACKWARD_HAS_UNWIND
#define BACKWARD_HAS_UNWIND 1
#undef BACKWARD_HAS_LIBUNWIND
#define BACKWARD_HAS_LIBUNWIND 0
#undef BACKWARD_HAS_BACKTRACE
#define BACKWARD_HAS_BACKTRACE 0
#endif
// On linux, backward can extract detailed information about a stack trace
// using one of the following libraries:
//
// #define BACKWARD_HAS_DW 1
// - libdw gives you the most juicy details out of your stack traces:
// - object filename
// - function name
// - source filename
// - line and column numbers
// - source code snippet (assuming the file is accessible)
// - variable names (if not optimized out)
// - variable values (not supported by backward-cpp)
// - You need to link with the lib "dw":
// - apt-get install libdw-dev
// - g++/clang++ -ldw ...
//
// #define BACKWARD_HAS_BFD 1
// - With libbfd, you get a fair amount of details:
// - object filename
// - function name
// - source filename
// - line numbers
// - source code snippet (assuming the file is accessible)
// - You need to link with the lib "bfd":
// - apt-get install binutils-dev
// - g++/clang++ -lbfd ...
//
// #define BACKWARD_HAS_DWARF 1
// - libdwarf gives you the most juicy details out of your stack traces:
// - object filename
// - function name
// - source filename
// - line and column numbers
// - source code snippet (assuming the file is accessible)
// - variable names (if not optimized out)
// - variable values (not supported by backward-cpp)
// - You need to link with the lib "dwarf":
// - apt-get install libdwarf-dev
// - g++/clang++ -ldwarf ...
//
// #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
// - backtrace provides minimal details for a stack trace:
// - object filename
// - function name
// - backtrace is part of the (e)glib library.
//
// The default is:
// #define BACKWARD_HAS_BACKTRACE_SYMBOL == 1
//
// Note that only one of the define should be set to 1 at a time.
//
#if BACKWARD_HAS_DW == 1
#elif BACKWARD_HAS_BFD == 1
#elif BACKWARD_HAS_DWARF == 1
#elif BACKWARD_HAS_BACKTRACE_SYMBOL == 1
#else
#undef BACKWARD_HAS_DW
#define BACKWARD_HAS_DW 0
#undef BACKWARD_HAS_BFD
#define BACKWARD_HAS_BFD 0
#undef BACKWARD_HAS_DWARF
#define BACKWARD_HAS_DWARF 0
#undef BACKWARD_HAS_BACKTRACE_SYMBOL
#define BACKWARD_HAS_BACKTRACE_SYMBOL 1
#endif
#include <cxxabi.h>
#include <fcntl.h>
#ifdef __ANDROID__
// Old Android API levels define _Unwind_Ptr in both link.h and
// unwind.h Rename the one in link.h as we are not going to be using
// it
#define _Unwind_Ptr _Unwind_Ptr_Custom
#include <link.h>
#undef _Unwind_Ptr
#else
#include <link.h>
#endif
#if defined(__ppc__) || defined(__powerpc) || defined(__powerpc__) || \
defined(__POWERPC__)
// Linux kernel header required for the struct pt_regs definition
// to access the NIP (Next Instruction Pointer) register value
#include <asm/ptrace.h>
#endif
#include <signal.h>
#include <sys/stat.h>
#include <syscall.h>
#include <unistd.h>
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#include <dlfcn.h>
#undef _GNU_SOURCE
#else
#include <dlfcn.h>
#endif
#if BACKWARD_HAS_BFD == 1
// NOTE: defining PACKAGE{,_VERSION} is required before including
// bfd.h on some platforms, see also:
// https://sourceware.org/bugzilla/show_bug.cgi?id=14243
#ifndef PACKAGE
#define PACKAGE
#endif
#ifndef PACKAGE_VERSION
#define PACKAGE_VERSION
#endif
#include <bfd.h>
#endif
#if BACKWARD_HAS_DW == 1
#include <dwarf.h>
#include <elfutils/libdw.h>
#include <elfutils/libdwfl.h>
#endif
#if BACKWARD_HAS_DWARF == 1
#include <algorithm>
#include <libdwarf/dwarf.h>
#include <libdwarf/libdwarf.h>
#include <libelf.h>
#include <map>
#endif
#if (BACKWARD_HAS_BACKTRACE == 1) || (BACKWARD_HAS_BACKTRACE_SYMBOL == 1)
// then we shall rely on backtrace
#include <execinfo.h>
#endif
#endif // defined(BACKWARD_SYSTEM_LINUX)
#if defined(BACKWARD_SYSTEM_DARWIN)
// On Darwin, backtrace can back-trace or "walk" the stack using the following
// libraries:
//
// #define BACKWARD_HAS_UNWIND 1
// - unwind comes from libgcc, but I saw an equivalent inside clang itself.
// - with unwind, the stacktrace is as accurate as it can possibly be, since
// this is used by the C++ runtine in gcc/clang for stack unwinding on
// exception.
// - normally libgcc is already linked to your program by default.
//
// #define BACKWARD_HAS_LIBUNWIND 1
// - libunwind comes from clang, which implements an API compatible version.
// - libunwind provides, in some cases, a more accurate stacktrace as it knows
// to decode signal handler frames and lets us edit the context registers when
// unwinding, allowing stack traces over bad function references.
//
// #define BACKWARD_HAS_BACKTRACE == 1
// - backtrace is available by default, though it does not produce as much
// information as another library might.
//
// The default is:
// #define BACKWARD_HAS_UNWIND == 1
//
// Note that only one of the define should be set to 1 at a time.
//
#if BACKWARD_HAS_UNWIND == 1
#elif BACKWARD_HAS_BACKTRACE == 1
#elif BACKWARD_HAS_LIBUNWIND == 1
#else
#undef BACKWARD_HAS_UNWIND
#define BACKWARD_HAS_UNWIND 1
#undef BACKWARD_HAS_BACKTRACE
#define BACKWARD_HAS_BACKTRACE 0
#undef BACKWARD_HAS_LIBUNWIND
#define BACKWARD_HAS_LIBUNWIND 0
#endif
// On Darwin, backward can extract detailed information about a stack trace
// using one of the following libraries:
//
// #define BACKWARD_HAS_BACKTRACE_SYMBOL 1
// - backtrace provides minimal details for a stack trace:
// - object filename
// - function name
//
// The default is:
// #define BACKWARD_HAS_BACKTRACE_SYMBOL == 1
//
#if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
#else
#undef BACKWARD_HAS_BACKTRACE_SYMBOL
#define BACKWARD_HAS_BACKTRACE_SYMBOL 1
#endif
#include <cxxabi.h>
#include <fcntl.h>
#include <pthread.h>
#include <signal.h>
#include <sys/stat.h>
#include <unistd.h>
#if (BACKWARD_HAS_BACKTRACE == 1) || (BACKWARD_HAS_BACKTRACE_SYMBOL == 1)
#include <execinfo.h>
#endif
#endif // defined(BACKWARD_SYSTEM_DARWIN)
#if defined(BACKWARD_SYSTEM_WINDOWS)
#include <condition_variable>
#include <mutex>
#include <thread>
#include <basetsd.h>
typedef SSIZE_T ssize_t;
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <winnt.h>
#include <psapi.h>
#include <signal.h>
#ifndef __clang__
#undef NOINLINE
#define NOINLINE __declspec(noinline)
#endif
#ifdef _MSC_VER
#pragma comment(lib, "psapi.lib")
#pragma comment(lib, "dbghelp.lib")
#endif
// Comment / packing is from stackoverflow:
// https://stackoverflow.com/questions/6205981/windows-c-stack-trace-from-a-running-app/28276227#28276227
// Some versions of imagehlp.dll lack the proper packing directives themselves
// so we need to do it.
#pragma pack(push, before_imagehlp, 8)
#include <imagehlp.h>
#pragma pack(pop, before_imagehlp)
// TODO maybe these should be undefined somewhere else?
#undef BACKWARD_HAS_UNWIND
#undef BACKWARD_HAS_BACKTRACE
#if BACKWARD_HAS_PDB_SYMBOL == 1
#else
#undef BACKWARD_HAS_PDB_SYMBOL
#define BACKWARD_HAS_PDB_SYMBOL 1
#endif
#endif
#if BACKWARD_HAS_UNWIND == 1
#include <unwind.h>
// while gcc's unwind.h defines something like that:
// extern _Unwind_Ptr _Unwind_GetIP (struct _Unwind_Context *);
// extern _Unwind_Ptr _Unwind_GetIPInfo (struct _Unwind_Context *, int *);
//
// clang's unwind.h defines something like this:
// uintptr_t _Unwind_GetIP(struct _Unwind_Context* __context);
//
// Even if the _Unwind_GetIPInfo can be linked to, it is not declared, worse we
// cannot just redeclare it because clang's unwind.h doesn't define _Unwind_Ptr
// anyway.
//
// Luckily we can play on the fact that the guard macros have a different name:
#ifdef __CLANG_UNWIND_H
// In fact, this function still comes from libgcc (on my different linux boxes,
// clang links against libgcc).
#include <inttypes.h>
extern "C" uintptr_t _Unwind_GetIPInfo(_Unwind_Context *, int *);
#endif
#endif // BACKWARD_HAS_UNWIND == 1
#if BACKWARD_HAS_LIBUNWIND == 1
#define UNW_LOCAL_ONLY
#include <libunwind.h>
#endif // BACKWARD_HAS_LIBUNWIND == 1
#ifdef BACKWARD_ATLEAST_CXX11
#include <unordered_map>
#include <utility> // for std::swap
namespace backward {
namespace details {
template <typename K, typename V> struct hashtable {
typedef std::unordered_map<K, V> type;
};
using std::move;
} // namespace details
} // namespace backward
#else // NOT BACKWARD_ATLEAST_CXX11
#define nullptr NULL
#define override
#include <map>
namespace backward {
namespace details {
template <typename K, typename V> struct hashtable {
typedef std::map<K, V> type;
};
template <typename T> const T &move(const T &v) { return v; }
template <typename T> T &move(T &v) { return v; }
} // namespace details
} // namespace backward
#endif // BACKWARD_ATLEAST_CXX11
namespace backward {
namespace details {
#if defined(BACKWARD_SYSTEM_WINDOWS)
const char kBackwardPathDelimiter[] = ";";
#else
const char kBackwardPathDelimiter[] = ":";
#endif
} // namespace details
} // namespace backward
namespace backward {
namespace system_tag {
struct linux_tag; // seems that I cannot call that "linux" because the name
// is already defined... so I am adding _tag everywhere.
struct darwin_tag;
struct windows_tag;
struct unknown_tag;
#if defined(BACKWARD_SYSTEM_LINUX)
typedef linux_tag current_tag;
#elif defined(BACKWARD_SYSTEM_DARWIN)
typedef darwin_tag current_tag;
#elif defined(BACKWARD_SYSTEM_WINDOWS)
typedef windows_tag current_tag;
#elif defined(BACKWARD_SYSTEM_UNKNOWN)
typedef unknown_tag current_tag;
#else
#error "May I please get my system defines?"
#endif
} // namespace system_tag
namespace trace_resolver_tag {
#if defined(BACKWARD_SYSTEM_LINUX)
struct libdw;
struct libbfd;
struct libdwarf;
struct backtrace_symbol;
#if BACKWARD_HAS_DW == 1
typedef libdw current;
#elif BACKWARD_HAS_BFD == 1
typedef libbfd current;
#elif BACKWARD_HAS_DWARF == 1
typedef libdwarf current;
#elif BACKWARD_HAS_BACKTRACE_SYMBOL == 1
typedef backtrace_symbol current;
#else
#error "You shall not pass, until you know what you want."
#endif
#elif defined(BACKWARD_SYSTEM_DARWIN)
struct backtrace_symbol;
#if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
typedef backtrace_symbol current;
#else
#error "You shall not pass, until you know what you want."
#endif
#elif defined(BACKWARD_SYSTEM_WINDOWS)
struct pdb_symbol;
#if BACKWARD_HAS_PDB_SYMBOL == 1
typedef pdb_symbol current;
#else
#error "You shall not pass, until you know what you want."
#endif
#endif
} // namespace trace_resolver_tag
namespace details {
template <typename T> struct rm_ptr { typedef T type; };
template <typename T> struct rm_ptr<T *> { typedef T type; };
template <typename T> struct rm_ptr<const T *> { typedef const T type; };
template <typename R, typename T, R (*F)(T)> struct deleter {
template <typename U> void operator()(U &ptr) const { (*F)(ptr); }
};
template <typename T> struct default_delete {
void operator()(T &ptr) const { delete ptr; }
};
template <typename T, typename Deleter = deleter<void, void *, &::free> >
class handle {
struct dummy;
T _val;
bool _empty;
#ifdef BACKWARD_ATLEAST_CXX11
handle(const handle &) = delete;
handle &operator=(const handle &) = delete;
#endif
public:
~handle() {
if (!_empty) {
Deleter()(_val);
}
}
explicit handle() : _val(), _empty(true) {}
explicit handle(T val) : _val(val), _empty(false) {
if (!_val)
_empty = true;
}
#ifdef BACKWARD_ATLEAST_CXX11
handle(handle &&from) : _empty(true) { swap(from); }
handle &operator=(handle &&from) {
swap(from);
return *this;
}
#else
explicit handle(const handle &from) : _empty(true) {
// some sort of poor man's move semantic.
swap(const_cast<handle &>(from));
}
handle &operator=(const handle &from) {
// some sort of poor man's move semantic.
swap(const_cast<handle &>(from));
return *this;
}
#endif
void reset(T new_val) {
handle tmp(new_val);
swap(tmp);
}
void update(T new_val) {
_val = new_val;
_empty = !static_cast<bool>(new_val);
}
operator const dummy *() const {
if (_empty) {
return nullptr;
}
return reinterpret_cast<const dummy *>(_val);
}
T get() { return _val; }
T release() {
_empty = true;
return _val;
}
void swap(handle &b) {
using std::swap;
swap(b._val, _val); // can throw, we are safe here.
swap(b._empty, _empty); // should not throw: if you cannot swap two
// bools without throwing... It's a lost cause anyway!
}
T &operator->() { return _val; }
const T &operator->() const { return _val; }
typedef typename rm_ptr<T>::type &ref_t;
typedef const typename rm_ptr<T>::type &const_ref_t;
ref_t operator*() { return *_val; }
const_ref_t operator*() const { return *_val; }
ref_t operator[](size_t idx) { return _val[idx]; }
// Watch out, we've got a badass over here
T *operator&() {
_empty = false;
return &_val;
}
};
// Default demangler implementation (do nothing).
template <typename TAG> struct demangler_impl {
static std::string demangle(const char *funcname) { return funcname; }
};
#if defined(BACKWARD_SYSTEM_LINUX) || defined(BACKWARD_SYSTEM_DARWIN)
template <> struct demangler_impl<system_tag::current_tag> {
demangler_impl() : _demangle_buffer_length(0) {}
std::string demangle(const char *funcname) {
using namespace details;
char *result = abi::__cxa_demangle(funcname, _demangle_buffer.get(),
&_demangle_buffer_length, nullptr);
if (result) {
_demangle_buffer.update(result);
return result;
}
return funcname;
}
private:
details::handle<char *> _demangle_buffer;
size_t _demangle_buffer_length;
};
#endif // BACKWARD_SYSTEM_LINUX || BACKWARD_SYSTEM_DARWIN
struct demangler : public demangler_impl<system_tag::current_tag> {};
// Split a string on the platform's PATH delimiter. Example: if delimiter
// is ":" then:
// "" --> []
// ":" --> ["",""]
// "::" --> ["","",""]
// "/a/b/c" --> ["/a/b/c"]
// "/a/b/c:/d/e/f" --> ["/a/b/c","/d/e/f"]
// etc.
inline std::vector<std::string> split_source_prefixes(const std::string &s) {
std::vector<std::string> out;
size_t last = 0;
size_t next = 0;
size_t delimiter_size = sizeof(kBackwardPathDelimiter) - 1;
while ((next = s.find(kBackwardPathDelimiter, last)) != std::string::npos) {
out.push_back(s.substr(last, next - last));
last = next + delimiter_size;
}
if (last <= s.length()) {
out.push_back(s.substr(last));
}
return out;
}
} // namespace details
/*************** A TRACE ***************/
struct Trace {
void *addr;
size_t idx;
Trace() : addr(nullptr), idx(0) {}
explicit Trace(void *_addr, size_t _idx) : addr(_addr), idx(_idx) {}
};
struct ResolvedTrace : public Trace {
struct SourceLoc {
std::string function;
std::string filename;
unsigned line;
unsigned col;
SourceLoc() : line(0), col(0) {}
bool operator==(const SourceLoc &b) const {
return function == b.function && filename == b.filename &&
line == b.line && col == b.col;
}
bool operator!=(const SourceLoc &b) const { return !(*this == b); }
};
// In which binary object this trace is located.
std::string object_filename;
// The function in the object that contain the trace. This is not the same
// as source.function which can be an function inlined in object_function.
std::string object_function;
// The source location of this trace. It is possible for filename to be
// empty and for line/col to be invalid (value 0) if this information
// couldn't be deduced, for example if there is no debug information in the
// binary object.
SourceLoc source;
// An optionals list of "inliners". All the successive sources location
// from where the source location of the trace (the attribute right above)
// is inlined. It is especially useful when you compiled with optimization.
typedef std::vector<SourceLoc> source_locs_t;
source_locs_t inliners;
ResolvedTrace() : Trace() {}
ResolvedTrace(const Trace &mini_trace) : Trace(mini_trace) {}
};
/*************** STACK TRACE ***************/
// default implemention.
template <typename TAG> class StackTraceImpl {
public:
size_t size() const { return 0; }
Trace operator[](size_t) const { return Trace(); }
size_t load_here(size_t = 0) { return 0; }
size_t load_from(void *, size_t = 0, void * = nullptr, void * = nullptr) {
return 0;
}
size_t thread_id() const { return 0; }
void skip_n_firsts(size_t) {}
};
class StackTraceImplBase {
public:
StackTraceImplBase()
: _thread_id(0), _skip(0), _context(nullptr), _error_addr(nullptr) {}
size_t thread_id() const { return _thread_id; }
void skip_n_firsts(size_t n) { _skip = n; }
protected:
void load_thread_info() {
#ifdef BACKWARD_SYSTEM_LINUX
#ifndef __ANDROID__
_thread_id = static_cast<size_t>(syscall(SYS_gettid));
#else
_thread_id = static_cast<size_t>(gettid());
#endif
if (_thread_id == static_cast<size_t>(getpid())) {
// If the thread is the main one, let's hide that.
// I like to keep little secret sometimes.
_thread_id = 0;
}
#elif defined(BACKWARD_SYSTEM_DARWIN)
_thread_id = reinterpret_cast<size_t>(pthread_self());
if (pthread_main_np() == 1) {
// If the thread is the main one, let's hide that.
_thread_id = 0;
}
#endif
}
void set_context(void *context) { _context = context; }
void *context() const { return _context; }
void set_error_addr(void *error_addr) { _error_addr = error_addr; }
void *error_addr() const { return _error_addr; }
size_t skip_n_firsts() const { return _skip; }
private:
size_t _thread_id;
size_t _skip;
void *_context;
void *_error_addr;
};
class StackTraceImplHolder : public StackTraceImplBase {
public:
size_t size() const {
return (_stacktrace.size() >= skip_n_firsts())
? _stacktrace.size() - skip_n_firsts()
: 0;
}
Trace operator[](size_t idx) const {
if (idx >= size()) {
return Trace();
}
return Trace(_stacktrace[idx + skip_n_firsts()], idx);
}
void *const *begin() const {
if (size()) {
return &_stacktrace[skip_n_firsts()];
}
return nullptr;
}
protected:
std::vector<void *> _stacktrace;
};
#if BACKWARD_HAS_UNWIND == 1
namespace details {
template <typename F> class Unwinder {
public:
size_t operator()(F &f, size_t depth) {
_f = &f;
_index = -1;
_depth = depth;
_Unwind_Backtrace(&this->backtrace_trampoline, this);
return static_cast<size_t>(_index);
}
private:
F *_f;
ssize_t _index;
size_t _depth;
static _Unwind_Reason_Code backtrace_trampoline(_Unwind_Context *ctx,
void *self) {
return (static_cast<Unwinder *>(self))->backtrace(ctx);
}
_Unwind_Reason_Code backtrace(_Unwind_Context *ctx) {
if (_index >= 0 && static_cast<size_t>(_index) >= _depth)
return _URC_END_OF_STACK;
int ip_before_instruction = 0;
uintptr_t ip = _Unwind_GetIPInfo(ctx, &ip_before_instruction);
if (!ip_before_instruction) {
// calculating 0-1 for unsigned, looks like a possible bug to sanitiziers,
// so let's do it explicitly:
if (ip == 0) {
ip = std::numeric_limits<uintptr_t>::max(); // set it to 0xffff... (as
// from casting 0-1)
} else {
ip -= 1; // else just normally decrement it (no overflow/underflow will
// happen)
}
}
if (_index >= 0) { // ignore first frame.
(*_f)(static_cast<size_t>(_index), reinterpret_cast<void *>(ip));
}
_index += 1;
return _URC_NO_REASON;
}
};
template <typename F> size_t unwind(F f, size_t depth) {
Unwinder<F> unwinder;
return unwinder(f, depth);
}
} // namespace details
template <>
class StackTraceImpl<system_tag::current_tag> : public StackTraceImplHolder {
public:
NOINLINE
size_t load_here(size_t depth = 32, void *context = nullptr,
void *error_addr = nullptr) {
load_thread_info();
set_context(context);
set_error_addr(error_addr);
if (depth == 0) {
return 0;
}
_stacktrace.resize(depth);
size_t trace_cnt = details::unwind(callback(*this), depth);
_stacktrace.resize(trace_cnt);
skip_n_firsts(0);
return size();
}
size_t load_from(void *addr, size_t depth = 32, void *context = nullptr,
void *error_addr = nullptr) {
load_here(depth + 8, context, error_addr);
for (size_t i = 0; i < _stacktrace.size(); ++i) {
if (_stacktrace[i] == addr) {
skip_n_firsts(i);
break;
}
}
_stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
return size();
}
private:
struct callback {
StackTraceImpl &self;
callback(StackTraceImpl &_self) : self(_self) {}
void operator()(size_t idx, void *addr) { self._stacktrace[idx] = addr; }
};
};
#elif BACKWARD_HAS_LIBUNWIND == 1
template <>
class StackTraceImpl<system_tag::current_tag> : public StackTraceImplHolder {
public:
__attribute__((noinline)) size_t load_here(size_t depth = 32,
void *_context = nullptr,
void *_error_addr = nullptr) {
set_context(_context);
set_error_addr(_error_addr);
load_thread_info();
if (depth == 0) {
return 0;
}
_stacktrace.resize(depth + 1);
int result = 0;
unw_context_t ctx;
size_t index = 0;
// Add the tail call. If the Instruction Pointer is the crash address it
// means we got a bad function pointer dereference, so we "unwind" the
// bad pointer manually by using the return address pointed to by the
// Stack Pointer as the Instruction Pointer and letting libunwind do
// the rest
if (context()) {
ucontext_t *uctx = reinterpret_cast<ucontext_t *>(context());
#ifdef REG_RIP // x86_64
if (uctx->uc_mcontext.gregs[REG_RIP] ==
reinterpret_cast<greg_t>(error_addr())) {
uctx->uc_mcontext.gregs[REG_RIP] =
*reinterpret_cast<size_t *>(uctx->uc_mcontext.gregs[REG_RSP]);
}
_stacktrace[index] =
reinterpret_cast<void *>(uctx->uc_mcontext.gregs[REG_RIP]);
++index;
ctx = *reinterpret_cast<unw_context_t *>(uctx);
#elif defined(REG_EIP) // x86_32
if (uctx->uc_mcontext.gregs[REG_EIP] ==
reinterpret_cast<greg_t>(error_addr())) {
uctx->uc_mcontext.gregs[REG_EIP] =
*reinterpret_cast<size_t *>(uctx->uc_mcontext.gregs[REG_ESP]);
}
_stacktrace[index] =
reinterpret_cast<void *>(uctx->uc_mcontext.gregs[REG_EIP]);
++index;
ctx = *reinterpret_cast<unw_context_t *>(uctx);
#elif defined(__arm__)
// libunwind uses its own context type for ARM unwinding.
// Copy the registers from the signal handler's context so we can
// unwind
unw_getcontext(&ctx);
ctx.regs[UNW_ARM_R0] = uctx->uc_mcontext.arm_r0;
ctx.regs[UNW_ARM_R1] = uctx->uc_mcontext.arm_r1;
ctx.regs[UNW_ARM_R2] = uctx->uc_mcontext.arm_r2;
ctx.regs[UNW_ARM_R3] = uctx->uc_mcontext.arm_r3;
ctx.regs[UNW_ARM_R4] = uctx->uc_mcontext.arm_r4;
ctx.regs[UNW_ARM_R5] = uctx->uc_mcontext.arm_r5;
ctx.regs[UNW_ARM_R6] = uctx->uc_mcontext.arm_r6;
ctx.regs[UNW_ARM_R7] = uctx->uc_mcontext.arm_r7;
ctx.regs[UNW_ARM_R8] = uctx->uc_mcontext.arm_r8;
ctx.regs[UNW_ARM_R9] = uctx->uc_mcontext.arm_r9;
ctx.regs[UNW_ARM_R10] = uctx->uc_mcontext.arm_r10;
ctx.regs[UNW_ARM_R11] = uctx->uc_mcontext.arm_fp;
ctx.regs[UNW_ARM_R12] = uctx->uc_mcontext.arm_ip;
ctx.regs[UNW_ARM_R13] = uctx->uc_mcontext.arm_sp;
ctx.regs[UNW_ARM_R14] = uctx->uc_mcontext.arm_lr;
ctx.regs[UNW_ARM_R15] = uctx->uc_mcontext.arm_pc;
// If we have crashed in the PC use the LR instead, as this was
// a bad function dereference
if (reinterpret_cast<unsigned long>(error_addr()) ==
uctx->uc_mcontext.arm_pc) {
ctx.regs[UNW_ARM_R15] =
uctx->uc_mcontext.arm_lr - sizeof(unsigned long);
}
_stacktrace[index] = reinterpret_cast<void *>(ctx.regs[UNW_ARM_R15]);
++index;
#elif defined(__APPLE__) && defined(__x86_64__)
unw_getcontext(&ctx);
// OS X's implementation of libunwind uses its own context object
// so we need to convert the passed context to libunwind's format
// (information about the data layout taken from unw_getcontext.s
// in Apple's libunwind source
ctx.data[0] = uctx->uc_mcontext->__ss.__rax;
ctx.data[1] = uctx->uc_mcontext->__ss.__rbx;
ctx.data[2] = uctx->uc_mcontext->__ss.__rcx;
ctx.data[3] = uctx->uc_mcontext->__ss.__rdx;
ctx.data[4] = uctx->uc_mcontext->__ss.__rdi;
ctx.data[5] = uctx->uc_mcontext->__ss.__rsi;
ctx.data[6] = uctx->uc_mcontext->__ss.__rbp;
ctx.data[7] = uctx->uc_mcontext->__ss.__rsp;
ctx.data[8] = uctx->uc_mcontext->__ss.__r8;
ctx.data[9] = uctx->uc_mcontext->__ss.__r9;
ctx.data[10] = uctx->uc_mcontext->__ss.__r10;
ctx.data[11] = uctx->uc_mcontext->__ss.__r11;
ctx.data[12] = uctx->uc_mcontext->__ss.__r12;
ctx.data[13] = uctx->uc_mcontext->__ss.__r13;
ctx.data[14] = uctx->uc_mcontext->__ss.__r14;
ctx.data[15] = uctx->uc_mcontext->__ss.__r15;
ctx.data[16] = uctx->uc_mcontext->__ss.__rip;
// If the IP is the same as the crash address we have a bad function
// dereference The caller's address is pointed to by %rsp, so we
// dereference that value and set it to be the next frame's IP.
if (uctx->uc_mcontext->__ss.__rip ==
reinterpret_cast<__uint64_t>(error_addr())) {
ctx.data[16] =
*reinterpret_cast<__uint64_t *>(uctx->uc_mcontext->__ss.__rsp);
}
_stacktrace[index] = reinterpret_cast<void *>(ctx.data[16]);
++index;
#elif defined(__APPLE__)
unw_getcontext(&ctx)
// TODO: Convert the ucontext_t to libunwind's unw_context_t like
// we do in 64 bits
if (ctx.uc_mcontext->__ss.__eip ==
reinterpret_cast<greg_t>(error_addr())) {
ctx.uc_mcontext->__ss.__eip = ctx.uc_mcontext->__ss.__esp;
}
_stacktrace[index] =
reinterpret_cast<void *>(ctx.uc_mcontext->__ss.__eip);
++index;
#endif
}
unw_cursor_t cursor;
if (context()) {
#if defined(UNW_INIT_SIGNAL_FRAME)
result = unw_init_local2(&cursor, &ctx, UNW_INIT_SIGNAL_FRAME);
#else
result = unw_init_local(&cursor, &ctx);
#endif
} else {
unw_getcontext(&ctx);
;
result = unw_init_local(&cursor, &ctx);
}
if (result != 0)
return 1;
unw_word_t ip = 0;
while (index <= depth && unw_step(&cursor) > 0) {
result = unw_get_reg(&cursor, UNW_REG_IP, &ip);
if (result == 0) {
_stacktrace[index] = reinterpret_cast<void *>(--ip);
++index;
}
}
--index;
_stacktrace.resize(index + 1);
skip_n_firsts(0);
return size();
}
size_t load_from(void *addr, size_t depth = 32, void *context = nullptr,
void *error_addr = nullptr) {
load_here(depth + 8, context, error_addr);
for (size_t i = 0; i < _stacktrace.size(); ++i) {
if (_stacktrace[i] == addr) {
skip_n_firsts(i);
_stacktrace[i] = (void *)((uintptr_t)_stacktrace[i]);
break;
}
}
_stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
return size();
}
};
#elif defined(BACKWARD_HAS_BACKTRACE)
template <>
class StackTraceImpl<system_tag::current_tag> : public StackTraceImplHolder {
public:
NOINLINE
size_t load_here(size_t depth = 32, void *context = nullptr,
void *error_addr = nullptr) {
set_context(context);
set_error_addr(error_addr);
load_thread_info();
if (depth == 0) {
return 0;
}
_stacktrace.resize(depth + 1);
size_t trace_cnt = backtrace(&_stacktrace[0], _stacktrace.size());
_stacktrace.resize(trace_cnt);
skip_n_firsts(1);
return size();
}
size_t load_from(void *addr, size_t depth = 32, void *context = nullptr,
void *error_addr = nullptr) {
load_here(depth + 8, context, error_addr);
for (size_t i = 0; i < _stacktrace.size(); ++i) {
if (_stacktrace[i] == addr) {
skip_n_firsts(i);
_stacktrace[i] = (void *)((uintptr_t)_stacktrace[i] + 1);
break;
}
}
_stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
return size();
}
};
#elif defined(BACKWARD_SYSTEM_WINDOWS)
template <>
class StackTraceImpl<system_tag::current_tag> : public StackTraceImplHolder {
public:
// We have to load the machine type from the image info
// So we first initialize the resolver, and it tells us this info
void set_machine_type(DWORD machine_type) { machine_type_ = machine_type; }
void set_context(CONTEXT *ctx) { ctx_ = ctx; }
void set_thread_handle(HANDLE handle) { thd_ = handle; }
NOINLINE
size_t load_here(size_t depth = 32, void *context = nullptr,
void *error_addr = nullptr) {
set_context(static_cast<CONTEXT*>(context));
set_error_addr(error_addr);
CONTEXT localCtx; // used when no context is provided
if (depth == 0) {
return 0;
}
if (!ctx_) {
ctx_ = &localCtx;
RtlCaptureContext(ctx_);
}
if (!thd_) {
thd_ = GetCurrentThread();
}
HANDLE process = GetCurrentProcess();
STACKFRAME64 s;
memset(&s, 0, sizeof(STACKFRAME64));
// TODO: 32 bit context capture
s.AddrStack.Mode = AddrModeFlat;
s.AddrFrame.Mode = AddrModeFlat;
s.AddrPC.Mode = AddrModeFlat;
#ifdef _M_X64
s.AddrPC.Offset = ctx_->Rip;
s.AddrStack.Offset = ctx_->Rsp;
s.AddrFrame.Offset = ctx_->Rbp;
#else
s.AddrPC.Offset = ctx_->Eip;
s.AddrStack.Offset = ctx_->Esp;
s.AddrFrame.Offset = ctx_->Ebp;
#endif
if (!machine_type_) {
#ifdef _M_X64
machine_type_ = IMAGE_FILE_MACHINE_AMD64;
#else
machine_type_ = IMAGE_FILE_MACHINE_I386;
#endif
}
for (;;) {
// NOTE: this only works if PDBs are already loaded!
SetLastError(0);
if (!StackWalk64(machine_type_, process, thd_, &s, ctx_, NULL,
SymFunctionTableAccess64, SymGetModuleBase64, NULL))
break;
if (s.AddrReturn.Offset == 0)
break;
_stacktrace.push_back(reinterpret_cast<void *>(s.AddrPC.Offset));
if (size() >= depth)
break;
}
return size();
}
size_t load_from(void *addr, size_t depth = 32, void *context = nullptr,
void *error_addr = nullptr) {
load_here(depth + 8, context, error_addr);
for (size_t i = 0; i < _stacktrace.size(); ++i) {
if (_stacktrace[i] == addr) {
skip_n_firsts(i);
break;
}
}
_stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth));
return size();
}
private:
DWORD machine_type_ = 0;
HANDLE thd_ = 0;
CONTEXT *ctx_ = nullptr;
};
#endif
class StackTrace : public StackTraceImpl<system_tag::current_tag> {};
/*************** TRACE RESOLVER ***************/
class TraceResolverImplBase {
public:
virtual ~TraceResolverImplBase() {}
virtual void load_addresses(void *const*addresses, int address_count) {
(void)addresses;
(void)address_count;
}
template <class ST> void load_stacktrace(ST &st) {
load_addresses(st.begin(), (int)st.size());
}
virtual ResolvedTrace resolve(ResolvedTrace t) { return t; }
protected:
std::string demangle(const char *funcname) {
return _demangler.demangle(funcname);
}
private:
details::demangler _demangler;
};
template <typename TAG> class TraceResolverImpl;
#ifdef BACKWARD_SYSTEM_UNKNOWN
template <> class TraceResolverImpl<system_tag::unknown_tag>
: public TraceResolverImplBase {};
#endif
#ifdef BACKWARD_SYSTEM_LINUX
class TraceResolverLinuxBase : public TraceResolverImplBase {
public:
TraceResolverLinuxBase()
: argv0_(get_argv0()), exec_path_(read_symlink("/proc/self/exe")) {}
std::string resolve_exec_path(Dl_info &symbol_info) const {
// mutates symbol_info.dli_fname to be filename to open and returns filename
// to display
if (symbol_info.dli_fname == argv0_) {
// dladdr returns argv[0] in dli_fname for symbols contained in
// the main executable, which is not a valid path if the
// executable was found by a search of the PATH environment
// variable; In that case, we actually open /proc/self/exe, which
// is always the actual executable (even if it was deleted/replaced!)
// but display the path that /proc/self/exe links to.
// However, this right away reduces probability of successful symbol
// resolution, because libbfd may try to find *.debug files in the
// same dir, in case symbols are stripped. As a result, it may try
// to find a file /proc/self/<exe_name>.debug, which obviously does
// not exist. /proc/self/exe is a last resort. First load attempt
// should go for the original executable file path.
symbol_info.dli_fname = "/proc/self/exe";
return exec_path_;
} else {
return symbol_info.dli_fname;
}
}
private:
std::string argv0_;
std::string exec_path_;
static std::string get_argv0() {
std::string argv0;
std::ifstream ifs("/proc/self/cmdline");
std::getline(ifs, argv0, '\0');
return argv0;
}
static std::string read_symlink(std::string const &symlink_path) {
std::string path;
path.resize(100);
while (true) {
ssize_t len =
::readlink(symlink_path.c_str(), &*path.begin(), path.size());
if (len < 0) {
return "";
}
if (static_cast<size_t>(len) == path.size()) {
path.resize(path.size() * 2);
} else {
path.resize(static_cast<std::string::size_type>(len));
break;
}
}
return path;
}
};
template <typename STACKTRACE_TAG> class TraceResolverLinuxImpl;
#if BACKWARD_HAS_BACKTRACE_SYMBOL == 1
template <>
class TraceResolverLinuxImpl<trace_resolver_tag::backtrace_symbol>
: public TraceResolverLinuxBase {
public:
void load_addresses(void *const*addresses, int address_count) override {
if (address_count == 0) {
return;
}
_symbols.reset(backtrace_symbols(addresses, address_count));
}
ResolvedTrace resolve(ResolvedTrace trace) override {
char *filename = _symbols[trace.idx];
char *funcname = filename;
while (*funcname && *funcname != '(') {
funcname += 1;
}
trace.object_filename.assign(filename,
funcname); // ok even if funcname is the ending
// \0 (then we assign entire string)
if (*funcname) { // if it's not end of string (e.g. from last frame ip==0)
funcname += 1;
char *funcname_end = funcname;
while (*funcname_end && *funcname_end != ')' && *funcname_end != '+') {
funcname_end += 1;
}
*funcname_end = '\0';
trace.object_function = this->demangle(funcname);
trace.source.function = trace.object_function; // we cannot do better.
}
return trace;
}
private:
details::handle<char **> _symbols;
};
#endif // BACKWARD_HAS_BACKTRACE_SYMBOL == 1
#if BACKWARD_HAS_BFD == 1
template <>
class TraceResolverLinuxImpl<trace_resolver_tag::libbfd>
: public TraceResolverLinuxBase {
public:
TraceResolverLinuxImpl() : _bfd_loaded(false) {}
ResolvedTrace resolve(ResolvedTrace trace) override {
Dl_info symbol_info;
// trace.addr is a virtual address in memory pointing to some code.
// Let's try to find from which loaded object it comes from.
// The loaded object can be yourself btw.
if (!dladdr(trace.addr, &symbol_info)) {
return trace; // dat broken trace...
}
// Now we get in symbol_info:
// .dli_fname:
// pathname of the shared object that contains the address.
// .dli_fbase:
// where the object is loaded in memory.
// .dli_sname:
// the name of the nearest symbol to trace.addr, we expect a
// function name.
// .dli_saddr:
// the exact address corresponding to .dli_sname.
if (symbol_info.dli_sname) {
trace.object_function = demangle(symbol_info.dli_sname);
}
if (!symbol_info.dli_fname) {
return trace;
}
trace.object_filename = resolve_exec_path(symbol_info);
bfd_fileobject *fobj;
// Before rushing to resolution need to ensure the executable
// file still can be used. For that compare inode numbers of
// what is stored by the executable's file path, and in the
// dli_fname, which not necessarily equals to the executable.
// It can be a shared library, or /proc/self/exe, and in the
// latter case has drawbacks. See the exec path resolution for
// details. In short - the dli object should be used only as
// the last resort.
// If inode numbers are equal, it is known dli_fname and the
// executable file are the same. This is guaranteed by Linux,
// because if the executable file is changed/deleted, it will
// be done in a new inode. The old file will be preserved in
// /proc/self/exe, and may even have inode 0. The latter can
// happen if the inode was actually reused, and the file was
// kept only in the main memory.
//
struct stat obj_stat;
struct stat dli_stat;
if (stat(trace.object_filename.c_str(), &obj_stat) == 0 &&
stat(symbol_info.dli_fname, &dli_stat) == 0 &&
obj_stat.st_ino == dli_stat.st_ino) {
// The executable file, and the shared object containing the
// address are the same file. Safe to use the original path.
// this is preferable. Libbfd will search for stripped debug
// symbols in the same directory.
fobj = load_object_with_bfd(trace.object_filename);
} else{
// The original object file was *deleted*! The only hope is
// that the debug symbols are either inside the shared
// object file, or are in the same directory, and this is
// not /proc/self/exe.
fobj = nullptr;
}
if (fobj == nullptr || !fobj->handle) {
fobj = load_object_with_bfd(symbol_info.dli_fname);
if (!fobj->handle) {
return trace;
}
}
find_sym_result *details_selected; // to be filled.
// trace.addr is the next instruction to be executed after returning
// from the nested stack frame. In C++ this usually relate to the next
// statement right after the function call that leaded to a new stack
// frame. This is not usually what you want to see when printing out a
// stacktrace...
find_sym_result details_call_site =
find_symbol_details(fobj, trace.addr, symbol_info.dli_fbase);
details_selected = &details_call_site;
#if BACKWARD_HAS_UNWIND == 0
// ...this is why we also try to resolve the symbol that is right
// before the return address. If we are lucky enough, we will get the
// line of the function that was called. But if the code is optimized,
// we might get something absolutely not related since the compiler
// can reschedule the return address with inline functions and
// tail-call optimisation (among other things that I don't even know
// or cannot even dream about with my tiny limited brain).
find_sym_result details_adjusted_call_site = find_symbol_details(
fobj, (void *)(uintptr_t(trace.addr) - 1), symbol_info.dli_fbase);
// In debug mode, we should always get the right thing(TM).
if (details_call_site.found && details_adjusted_call_site.found) {
// Ok, we assume that details_adjusted_call_site is a better estimation.
details_selected = &details_adjusted_call_site;
trace.addr = (void *)(uintptr_t(trace.addr) - 1);
}
if (details_selected == &details_call_site && details_call_site.found) {
// we have to re-resolve the symbol in order to reset some
// internal state in BFD... so we can call backtrace_inliners
// thereafter...
details_call_site =
find_symbol_details(fobj, trace.addr, symbol_info.dli_fbase);
}
#endif // BACKWARD_HAS_UNWIND
if (details_selected->found) {
if (details_selected->filename) {
trace.source.filename = details_selected->filename;
}
trace.source.line = details_selected->line;
if (details_selected->funcname) {
// this time we get the name of the function where the code is
// located, instead of the function were the address is
// located. In short, if the code was inlined, we get the
// function correspoding to the code. Else we already got in
// trace.function.
trace.source.function = demangle(details_selected->funcname);
if (!symbol_info.dli_sname) {
// for the case dladdr failed to find the symbol name of
// the function, we might as well try to put something
// here.
trace.object_function = trace.source.function;
}
}
// Maybe the source of the trace got inlined inside the function
// (trace.source.function). Let's see if we can get all the inlined
// calls along the way up to the initial call site.
trace.inliners = backtrace_inliners(fobj, *details_selected);
#if 0
if (trace.inliners.size() == 0) {
// Maybe the trace was not inlined... or maybe it was and we
// are lacking the debug information. Let's try to make the
// world better and see if we can get the line number of the
// function (trace.source.function) now.
//
// We will get the location of where the function start (to be
// exact: the first instruction that really start the
// function), not where the name of the function is defined.
// This can be quite far away from the name of the function
// btw.
//
// If the source of the function is the same as the source of
// the trace, we cannot say if the trace was really inlined or
// not. However, if the filename of the source is different
// between the function and the trace... we can declare it as
// an inliner. This is not 100% accurate, but better than
// nothing.
if (symbol_info.dli_saddr) {
find_sym_result details = find_symbol_details(fobj,
symbol_info.dli_saddr,
symbol_info.dli_fbase);
if (details.found) {
ResolvedTrace::SourceLoc diy_inliner;
diy_inliner.line = details.line;
if (details.filename) {
diy_inliner.filename = details.filename;
}
if (details.funcname) {
diy_inliner.function = demangle(details.funcname);
} else {
diy_inliner.function = trace.source.function;
}
if (diy_inliner != trace.source) {
trace.inliners.push_back(diy_inliner);
}
}
}
}
#endif
}
return trace;
}
private:
bool _bfd_loaded;
typedef details::handle<bfd *,
details::deleter<bfd_boolean, bfd *, &bfd_close> >
bfd_handle_t;
typedef details::handle<asymbol **> bfd_symtab_t;
struct bfd_fileobject {
bfd_handle_t handle;
bfd_vma base_addr;
bfd_symtab_t symtab;
bfd_symtab_t dynamic_symtab;
};
typedef details::hashtable<std::string, bfd_fileobject>::type fobj_bfd_map_t;
fobj_bfd_map_t _fobj_bfd_map;
bfd_fileobject *load_object_with_bfd(const std::string &filename_object) {
using namespace details;
if (!_bfd_loaded) {
using namespace details;
bfd_init();
_bfd_loaded = true;
}
fobj_bfd_map_t::iterator it = _fobj_bfd_map.find(filename_object);
if (it != _fobj_bfd_map.end()) {
return &it->second;
}
// this new object is empty for now.
bfd_fileobject *r = &_fobj_bfd_map[filename_object];
// we do the work temporary in this one;
bfd_handle_t bfd_handle;
int fd = open(filename_object.c_str(), O_RDONLY);
bfd_handle.reset(bfd_fdopenr(filename_object.c_str(), "default", fd));
if (!bfd_handle) {
close(fd);
return r;
}
if (!bfd_check_format(bfd_handle.get(), bfd_object)) {
return r; // not an object? You lose.
}
if ((bfd_get_file_flags(bfd_handle.get()) & HAS_SYMS) == 0) {
return r; // that's what happen when you forget to compile in debug.
}
ssize_t symtab_storage_size = bfd_get_symtab_upper_bound(bfd_handle.get());
ssize_t dyn_symtab_storage_size =
bfd_get_dynamic_symtab_upper_bound(bfd_handle.get());
if (symtab_storage_size <= 0 && dyn_symtab_storage_size <= 0) {
return r; // weird, is the file is corrupted?
}
bfd_symtab_t symtab, dynamic_symtab;
ssize_t symcount = 0, dyn_symcount = 0;
if (symtab_storage_size > 0) {
symtab.reset(static_cast<bfd_symbol **>(
malloc(static_cast<size_t>(symtab_storage_size))));
symcount = bfd_canonicalize_symtab(bfd_handle.get(), symtab.get());
}
if (dyn_symtab_storage_size > 0) {
dynamic_symtab.reset(static_cast<bfd_symbol **>(
malloc(static_cast<size_t>(dyn_symtab_storage_size))));
dyn_symcount = bfd_canonicalize_dynamic_symtab(bfd_handle.get(),
dynamic_symtab.get());
}
if (symcount <= 0 && dyn_symcount <= 0) {
return r; // damned, that's a stripped file that you got there!
}
r->handle = move(bfd_handle);
r->symtab = move(symtab);
r->dynamic_symtab = move(dynamic_symtab);
return r;
}
struct find_sym_result {
bool found;
const char *filename;
const char *funcname;
unsigned int line;
};
struct find_sym_context {
TraceResolverLinuxImpl *self;
bfd_fileobject *fobj;
void *addr;
void *base_addr;
find_sym_result result;
};
find_sym_result find_symbol_details(bfd_fileobject *fobj, void *addr,
void *base_addr) {
find_sym_context context;
context.self = this;
context.fobj = fobj;
context.addr = addr;
context.base_addr = base_addr;
context.result.found = false;
bfd_map_over_sections(fobj->handle.get(), &find_in_section_trampoline,
static_cast<void *>(&context));
return context.result;
}
static void find_in_section_trampoline(bfd *, asection *section, void *data) {
find_sym_context *context = static_cast<find_sym_context *>(data);
context->self->find_in_section(
reinterpret_cast<bfd_vma>(context->addr),
reinterpret_cast<bfd_vma>(context->base_addr), context->fobj, section,
context->result);
}
void find_in_section(bfd_vma addr, bfd_vma base_addr, bfd_fileobject *fobj,
asection *section, find_sym_result &result) {
if (result.found)
return;
#ifdef bfd_get_section_flags
if ((bfd_get_section_flags(fobj->handle.get(), section) & SEC_ALLOC) == 0)
#else
if ((bfd_section_flags(section) & SEC_ALLOC) == 0)
#endif
return; // a debug section is never loaded automatically.
#ifdef bfd_get_section_vma
bfd_vma sec_addr = bfd_get_section_vma(fobj->handle.get(), section);
#else
bfd_vma sec_addr = bfd_section_vma(section);
#endif
#ifdef bfd_get_section_size
bfd_size_type size = bfd_get_section_size(section);
#else
bfd_size_type size = bfd_section_size(section);
#endif
// are we in the boundaries of the section?
if (addr < sec_addr || addr >= sec_addr + size) {
addr -= base_addr; // oups, a relocated object, lets try again...
if (addr < sec_addr || addr >= sec_addr + size) {
return;
}
}
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
#endif
if (!result.found && fobj->symtab) {
result.found = bfd_find_nearest_line(
fobj->handle.get(), section, fobj->symtab.get(), addr - sec_addr,
&result.filename, &result.funcname, &result.line);
}
if (!result.found && fobj->dynamic_symtab) {
result.found = bfd_find_nearest_line(
fobj->handle.get(), section, fobj->dynamic_symtab.get(),
addr - sec_addr, &result.filename, &result.funcname, &result.line);
}
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
}
ResolvedTrace::source_locs_t
backtrace_inliners(bfd_fileobject *fobj, find_sym_result previous_result) {
// This function can be called ONLY after a SUCCESSFUL call to
// find_symbol_details. The state is global to the bfd_handle.
ResolvedTrace::source_locs_t results;
while (previous_result.found) {
find_sym_result result;
result.found = bfd_find_inliner_info(fobj->handle.get(), &result.filename,
&result.funcname, &result.line);
if (result
.found) /* and not (
cstrings_eq(previous_result.filename,
result.filename) and
cstrings_eq(previous_result.funcname, result.funcname)
and result.line == previous_result.line
)) */
{
ResolvedTrace::SourceLoc src_loc;
src_loc.line = result.line;
if (result.filename) {
src_loc.filename = result.filename;
}
if (result.funcname) {
src_loc.function = demangle(result.funcname);
}
results.push_back(src_loc);
}
previous_result = result;
}
return results;
}
bool cstrings_eq(const char *a, const char *b) {
if (!a || !b) {
return false;
}
return strcmp(a, b) == 0;
}
};
#endif // BACKWARD_HAS_BFD == 1
#if BACKWARD_HAS_DW == 1
template <>
class TraceResolverLinuxImpl<trace_resolver_tag::libdw>
: public TraceResolverLinuxBase {
public:
TraceResolverLinuxImpl() : _dwfl_handle_initialized(false) {}
ResolvedTrace resolve(ResolvedTrace trace) override {
using namespace details;
Dwarf_Addr trace_addr = (Dwarf_Addr)trace.addr;
if (!_dwfl_handle_initialized) {
// initialize dwfl...
_dwfl_cb.reset(new Dwfl_Callbacks);
_dwfl_cb->find_elf = &dwfl_linux_proc_find_elf;
_dwfl_cb->find_debuginfo = &dwfl_standard_find_debuginfo;
_dwfl_cb->debuginfo_path = 0;
_dwfl_handle.reset(dwfl_begin(_dwfl_cb.get()));
_dwfl_handle_initialized = true;
if (!_dwfl_handle) {
return trace;
}
// ...from the current process.
dwfl_report_begin(_dwfl_handle.get());
int r = dwfl_linux_proc_report(_dwfl_handle.get(), getpid());
dwfl_report_end(_dwfl_handle.get(), NULL, NULL);
if (r < 0) {
return trace;
}
}
if (!_dwfl_handle) {
return trace;
}
// find the module (binary object) that contains the trace's address.
// This is not using any debug information, but the addresses ranges of
// all the currently loaded binary object.
Dwfl_Module *mod = dwfl_addrmodule(_dwfl_handle.get(), trace_addr);
if (mod) {
// now that we found it, lets get the name of it, this will be the
// full path to the running binary or one of the loaded library.
const char *module_name = dwfl_module_info(mod, 0, 0, 0, 0, 0, 0, 0);
if (module_name) {
trace.object_filename = module_name;
}
// We also look after the name of the symbol, equal or before this
// address. This is found by walking the symtab. We should get the
// symbol corresponding to the function (mangled) containing the
// address. If the code corresponding to the address was inlined,
// this is the name of the out-most inliner function.
const char *sym_name = dwfl_module_addrname(mod, trace_addr);
if (sym_name) {
trace.object_function = demangle(sym_name);
}
}
// now let's get serious, and find out the source location (file and
// line number) of the address.
// This function will look in .debug_aranges for the address and map it
// to the location of the compilation unit DIE in .debug_info and
// return it.
Dwarf_Addr mod_bias = 0;
Dwarf_Die *cudie = dwfl_module_addrdie(mod, trace_addr, &mod_bias);
#if 1
if (!cudie) {
// Sadly clang does not generate the section .debug_aranges, thus
// dwfl_module_addrdie will fail early. Clang doesn't either set
// the lowpc/highpc/range info for every compilation unit.
//
// So in order to save the world:
// for every compilation unit, we will iterate over every single
// DIEs. Normally functions should have a lowpc/highpc/range, which
// we will use to infer the compilation unit.
// note that this is probably badly inefficient.
while ((cudie = dwfl_module_nextcu(mod, cudie, &mod_bias))) {
Dwarf_Die die_mem;
Dwarf_Die *fundie =
find_fundie_by_pc(cudie, trace_addr - mod_bias, &die_mem);
if (fundie) {
break;
}
}
}
#endif
//#define BACKWARD_I_DO_NOT_RECOMMEND_TO_ENABLE_THIS_HORRIBLE_PIECE_OF_CODE
#ifdef BACKWARD_I_DO_NOT_RECOMMEND_TO_ENABLE_THIS_HORRIBLE_PIECE_OF_CODE
if (!cudie) {
// If it's still not enough, lets dive deeper in the shit, and try
// to save the world again: for every compilation unit, we will
// load the corresponding .debug_line section, and see if we can
// find our address in it.
Dwarf_Addr cfi_bias;
Dwarf_CFI *cfi_cache = dwfl_module_eh_cfi(mod, &cfi_bias);
Dwarf_Addr bias;
while ((cudie = dwfl_module_nextcu(mod, cudie, &bias))) {
if (dwarf_getsrc_die(cudie, trace_addr - bias)) {
// ...but if we get a match, it might be a false positive
// because our (address - bias) might as well be valid in a
// different compilation unit. So we throw our last card on
// the table and lookup for the address into the .eh_frame
// section.
handle<Dwarf_Frame *> frame;
dwarf_cfi_addrframe(cfi_cache, trace_addr - cfi_bias, &frame);
if (frame) {
break;
}
}
}
}
#endif
if (!cudie) {
return trace; // this time we lost the game :/
}
// Now that we have a compilation unit DIE, this function will be able
// to load the corresponding section in .debug_line (if not already
// loaded) and hopefully find the source location mapped to our
// address.
Dwarf_Line *srcloc = dwarf_getsrc_die(cudie, trace_addr - mod_bias);
if (srcloc) {
const char *srcfile = dwarf_linesrc(srcloc, 0, 0);
if (srcfile) {
trace.source.filename = srcfile;
}
int line = 0, col = 0;
dwarf_lineno(srcloc, &line);
dwarf_linecol(srcloc, &col);
trace.source.line = line;
trace.source.col = col;
}
deep_first_search_by_pc(cudie, trace_addr - mod_bias,
inliners_search_cb(trace));
if (trace.source.function.size() == 0) {
// fallback.
trace.source.function = trace.object_function;
}
return trace;
}
private:
typedef details::handle<Dwfl *, details::deleter<void, Dwfl *, &dwfl_end> >
dwfl_handle_t;
details::handle<Dwfl_Callbacks *, details::default_delete<Dwfl_Callbacks *> >
_dwfl_cb;
dwfl_handle_t _dwfl_handle;
bool _dwfl_handle_initialized;
// defined here because in C++98, template function cannot take locally
// defined types... grrr.
struct inliners_search_cb {
void operator()(Dwarf_Die *die) {
switch (dwarf_tag(die)) {
const char *name;
case DW_TAG_subprogram:
if ((name = dwarf_diename(die))) {
trace.source.function = name;
}
break;
case DW_TAG_inlined_subroutine:
ResolvedTrace::SourceLoc sloc;
Dwarf_Attribute attr_mem;
if ((name = dwarf_diename(die))) {
sloc.function = name;
}
if ((name = die_call_file(die))) {
sloc.filename = name;
}
Dwarf_Word line = 0, col = 0;
dwarf_formudata(dwarf_attr(die, DW_AT_call_line, &attr_mem), &line);
dwarf_formudata(dwarf_attr(die, DW_AT_call_column, &attr_mem), &col);
sloc.line = (unsigned)line;
sloc.col = (unsigned)col;
trace.inliners.push_back(sloc);
break;
};
}
ResolvedTrace &trace;
inliners_search_cb(ResolvedTrace &t) : trace(t) {}
};
static bool die_has_pc(Dwarf_Die *die, Dwarf_Addr pc) {
Dwarf_Addr low, high;
// continuous range
if (dwarf_hasattr(die, DW_AT_low_pc) && dwarf_hasattr(die, DW_AT_high_pc)) {
if (dwarf_lowpc(die, &low) != 0) {
return false;
}
if (dwarf_highpc(die, &high) != 0) {
Dwarf_Attribute attr_mem;
Dwarf_Attribute *attr = dwarf_attr(die, DW_AT_high_pc, &attr_mem);
Dwarf_Word value;
if (dwarf_formudata(attr, &value) != 0) {
return false;
}
high = low + value;
}
return pc >= low && pc < high;
}
// non-continuous range.
Dwarf_Addr base;
ptrdiff_t offset = 0;
while ((offset = dwarf_ranges(die, offset, &base, &low, &high)) > 0) {
if (pc >= low && pc < high) {
return true;
}
}
return false;
}
static Dwarf_Die *find_fundie_by_pc(Dwarf_Die *parent_die, Dwarf_Addr pc,
Dwarf_Die *result) {
if (dwarf_child(parent_die, result) != 0) {
return 0;
}
Dwarf_Die *die = result;
do {
switch (dwarf_tag(die)) {
case DW_TAG_subprogram:
case DW_TAG_inlined_subroutine:
if (die_has_pc(die, pc)) {
return result;
}
};
bool declaration = false;
Dwarf_Attribute attr_mem;
dwarf_formflag(dwarf_attr(die, DW_AT_declaration, &attr_mem),
&declaration);
if (!declaration) {
// let's be curious and look deeper in the tree,
// function are not necessarily at the first level, but
// might be nested inside a namespace, structure etc.
Dwarf_Die die_mem;
Dwarf_Die *indie = find_fundie_by_pc(die, pc, &die_mem);
if (indie) {
*result = die_mem;
return result;
}
}
} while (dwarf_siblingof(die, result) == 0);
return 0;
}
template <typename CB>
static bool deep_first_search_by_pc(Dwarf_Die *parent_die, Dwarf_Addr pc,
CB cb) {
Dwarf_Die die_mem;
if (dwarf_child(parent_die, &die_mem) != 0) {
return false;
}
bool branch_has_pc = false;
Dwarf_Die *die = &die_mem;
do {
bool declaration = false;
Dwarf_Attribute attr_mem;
dwarf_formflag(dwarf_attr(die, DW_AT_declaration, &attr_mem),
&declaration);
if (!declaration) {
// let's be curious and look deeper in the tree, function are
// not necessarily at the first level, but might be nested
// inside a namespace, structure, a function, an inlined
// function etc.
branch_has_pc = deep_first_search_by_pc(die, pc, cb);
}
if (!branch_has_pc) {
branch_has_pc = die_has_pc(die, pc);
}
if (branch_has_pc) {
cb(die);
}
} while (dwarf_siblingof(die, &die_mem) == 0);
return branch_has_pc;
}
static const char *die_call_file(Dwarf_Die *die) {
Dwarf_Attribute attr_mem;
Dwarf_Word file_idx = 0;
dwarf_formudata(dwarf_attr(die, DW_AT_call_file, &attr_mem), &file_idx);
if (file_idx == 0) {
return 0;
}
Dwarf_Die die_mem;
Dwarf_Die *cudie = dwarf_diecu(die, &die_mem, 0, 0);
if (!cudie) {
return 0;
}
Dwarf_Files *files = 0;
size_t nfiles;
dwarf_getsrcfiles(cudie, &files, &nfiles);
if (!files) {
return 0;
}
return dwarf_filesrc(files, file_idx, 0, 0);
}
};
#endif // BACKWARD_HAS_DW == 1
#if BACKWARD_HAS_DWARF == 1
template <>
class TraceResolverLinuxImpl<trace_resolver_tag::libdwarf>
: public TraceResolverLinuxBase {
public:
TraceResolverLinuxImpl() : _dwarf_loaded(false) {}
ResolvedTrace resolve(ResolvedTrace trace) override {
// trace.addr is a virtual address in memory pointing to some code.
// Let's try to find from which loaded object it comes from.
// The loaded object can be yourself btw.
Dl_info symbol_info;
int dladdr_result = 0;
#if defined(__GLIBC__)
link_map *link_map;
// We request the link map so we can get information about offsets
dladdr_result =
dladdr1(trace.addr, &symbol_info, reinterpret_cast<void **>(&link_map),
RTLD_DL_LINKMAP);
#else
// Android doesn't have dladdr1. Don't use the linker map.
dladdr_result = dladdr(trace.addr, &symbol_info);
#endif
if (!dladdr_result) {
return trace; // dat broken trace...
}
// Now we get in symbol_info:
// .dli_fname:
// pathname of the shared object that contains the address.
// .dli_fbase:
// where the object is loaded in memory.
// .dli_sname:
// the name of the nearest symbol to trace.addr, we expect a
// function name.
// .dli_saddr:
// the exact address corresponding to .dli_sname.
//
// And in link_map:
// .l_addr:
// difference between the address in the ELF file and the address
// in memory
// l_name:
// absolute pathname where the object was found
if (symbol_info.dli_sname) {
trace.object_function = demangle(symbol_info.dli_sname);
}
if (!symbol_info.dli_fname) {
return trace;
}
trace.object_filename = resolve_exec_path(symbol_info);
dwarf_fileobject &fobj = load_object_with_dwarf(symbol_info.dli_fname);
if (!fobj.dwarf_handle) {
return trace; // sad, we couldn't load the object :(
}
#if defined(__GLIBC__)
// Convert the address to a module relative one by looking at
// the module's loading address in the link map
Dwarf_Addr address = reinterpret_cast<uintptr_t>(trace.addr) -
reinterpret_cast<uintptr_t>(link_map->l_addr);
#else
Dwarf_Addr address = reinterpret_cast<uintptr_t>(trace.addr);
#endif
if (trace.object_function.empty()) {
symbol_cache_t::iterator it = fobj.symbol_cache.lower_bound(address);
if (it != fobj.symbol_cache.end()) {
if (it->first != address) {
if (it != fobj.symbol_cache.begin()) {
--it;
}
}
trace.object_function = demangle(it->second.c_str());
}
}
// Get the Compilation Unit DIE for the address
Dwarf_Die die = find_die(fobj, address);
if (!die) {
return trace; // this time we lost the game :/
}
// libdwarf doesn't give us direct access to its objects, it always
// allocates a copy for the caller. We keep that copy alive in a cache
// and we deallocate it later when it's no longer required.
die_cache_entry &die_object = get_die_cache(fobj, die);
if (die_object.isEmpty())
return trace; // We have no line section for this DIE
die_linemap_t::iterator it = die_object.line_section.lower_bound(address);
if (it != die_object.line_section.end()) {
if (it->first != address) {
if (it == die_object.line_section.begin()) {
// If we are on the first item of the line section
// but the address does not match it means that
// the address is below the range of the DIE. Give up.
return trace;
} else {
--it;
}
}
} else {
return trace; // We didn't find the address.
}
// Get the Dwarf_Line that the address points to and call libdwarf
// to get source file, line and column info.
Dwarf_Line line = die_object.line_buffer[it->second];
Dwarf_Error error = DW_DLE_NE;
char *filename;
if (dwarf_linesrc(line, &filename, &error) == DW_DLV_OK) {
trace.source.filename = std::string(filename);
dwarf_dealloc(fobj.dwarf_handle.get(), filename, DW_DLA_STRING);
}
Dwarf_Unsigned number = 0;
if (dwarf_lineno(line, &number, &error) == DW_DLV_OK) {
trace.source.line = number;
} else {
trace.source.line = 0;
}
if (dwarf_lineoff_b(line, &number, &error) == DW_DLV_OK) {
trace.source.col = number;
} else {
trace.source.col = 0;
}
std::vector<std::string> namespace_stack;
deep_first_search_by_pc(fobj, die, address, namespace_stack,
inliners_search_cb(trace, fobj, die));
dwarf_dealloc(fobj.dwarf_handle.get(), die, DW_DLA_DIE);
return trace;
}
public:
static int close_dwarf(Dwarf_Debug dwarf) {
return dwarf_finish(dwarf, NULL);
}
private:
bool _dwarf_loaded;
typedef details::handle<int, details::deleter<int, int, &::close> >
dwarf_file_t;
typedef details::handle<Elf *, details::deleter<int, Elf *, &elf_end> >
dwarf_elf_t;
typedef details::handle<Dwarf_Debug,
details::deleter<int, Dwarf_Debug, &close_dwarf> >
dwarf_handle_t;
typedef std::map<Dwarf_Addr, int> die_linemap_t;
typedef std::map<Dwarf_Off, Dwarf_Off> die_specmap_t;
struct die_cache_entry {
die_specmap_t spec_section;
die_linemap_t line_section;
Dwarf_Line *line_buffer;
Dwarf_Signed line_count;
Dwarf_Line_Context line_context;
inline bool isEmpty() {
return line_buffer == NULL || line_count == 0 || line_context == NULL ||
line_section.empty();
}
die_cache_entry() : line_buffer(0), line_count(0), line_context(0) {}
~die_cache_entry() {
if (line_context) {
dwarf_srclines_dealloc_b(line_context);
}
}
};
typedef std::map<Dwarf_Off, die_cache_entry> die_cache_t;
typedef std::map<uintptr_t, std::string> symbol_cache_t;
struct dwarf_fileobject {
dwarf_file_t file_handle;
dwarf_elf_t elf_handle;
dwarf_handle_t dwarf_handle;
symbol_cache_t symbol_cache;
// Die cache
die_cache_t die_cache;
die_cache_entry *current_cu;
};
typedef details::hashtable<std::string, dwarf_fileobject>::type
fobj_dwarf_map_t;
fobj_dwarf_map_t _fobj_dwarf_map;
static bool cstrings_eq(const char *a, const char *b) {
if (!a || !b) {
return false;
}
return strcmp(a, b) == 0;
}
dwarf_fileobject &load_object_with_dwarf(const std::string &filename_object) {
if (!_dwarf_loaded) {
// Set the ELF library operating version
// If that fails there's nothing we can do
_dwarf_loaded = elf_version(EV_CURRENT) != EV_NONE;
}
fobj_dwarf_map_t::iterator it = _fobj_dwarf_map.find(filename_object);
if (it != _fobj_dwarf_map.end()) {
return it->second;
}
// this new object is empty for now
dwarf_fileobject &r = _fobj_dwarf_map[filename_object];
dwarf_file_t file_handle;
file_handle.reset(open(filename_object.c_str(), O_RDONLY));
if (file_handle.get() < 0) {
return r;
}
// Try to get an ELF handle. We need to read the ELF sections
// because we want to see if there is a .gnu_debuglink section
// that points to a split debug file
dwarf_elf_t elf_handle;
elf_handle.reset(elf_begin(file_handle.get(), ELF_C_READ, NULL));
if (!elf_handle) {
return r;
}
const char *e_ident = elf_getident(elf_handle.get(), 0);
if (!e_ident) {
return r;
}
// Get the number of sections
// We use the new APIs as elf_getshnum is deprecated
size_t shdrnum = 0;
if (elf_getshdrnum(elf_handle.get(), &shdrnum) == -1) {
return r;
}
// Get the index to the string section
size_t shdrstrndx = 0;
if (elf_getshdrstrndx(elf_handle.get(), &shdrstrndx) == -1) {
return r;
}
std::string debuglink;
// Iterate through the ELF sections to try to get a gnu_debuglink
// note and also to cache the symbol table.
// We go the preprocessor way to avoid having to create templated
// classes or using gelf (which might throw a compiler error if 64 bit
// is not supported
#define ELF_GET_DATA(ARCH) \
Elf_Scn *elf_section = 0; \
Elf_Data *elf_data = 0; \
Elf##ARCH##_Shdr *section_header = 0; \
Elf_Scn *symbol_section = 0; \
size_t symbol_count = 0; \
size_t symbol_strings = 0; \
Elf##ARCH##_Sym *symbol = 0; \
const char *section_name = 0; \
\
while ((elf_section = elf_nextscn(elf_handle.get(), elf_section)) != NULL) { \
section_header = elf##ARCH##_getshdr(elf_section); \
if (section_header == NULL) { \
return r; \
} \
\
if ((section_name = elf_strptr(elf_handle.get(), shdrstrndx, \
section_header->sh_name)) == NULL) { \
return r; \
} \
\
if (cstrings_eq(section_name, ".gnu_debuglink")) { \
elf_data = elf_getdata(elf_section, NULL); \
if (elf_data && elf_data->d_size > 0) { \
debuglink = \
std::string(reinterpret_cast<const char *>(elf_data->d_buf)); \
} \
} \
\
switch (section_header->sh_type) { \
case SHT_SYMTAB: \
symbol_section = elf_section; \
symbol_count = section_header->sh_size / section_header->sh_entsize; \
symbol_strings = section_header->sh_link; \
break; \
\
/* We use .dynsyms as a last resort, we prefer .symtab */ \
case SHT_DYNSYM: \
if (!symbol_section) { \
symbol_section = elf_section; \
symbol_count = section_header->sh_size / section_header->sh_entsize; \
symbol_strings = section_header->sh_link; \
} \
break; \
} \
} \
\
if (symbol_section && symbol_count && symbol_strings) { \
elf_data = elf_getdata(symbol_section, NULL); \
symbol = reinterpret_cast<Elf##ARCH##_Sym *>(elf_data->d_buf); \
for (size_t i = 0; i < symbol_count; ++i) { \
int type = ELF##ARCH##_ST_TYPE(symbol->st_info); \
if (type == STT_FUNC && symbol->st_value > 0) { \
r.symbol_cache[symbol->st_value] = std::string( \
elf_strptr(elf_handle.get(), symbol_strings, symbol->st_name)); \
} \
++symbol; \
} \
}
if (e_ident[EI_CLASS] == ELFCLASS32) {
ELF_GET_DATA(32)
} else if (e_ident[EI_CLASS] == ELFCLASS64) {
// libelf might have been built without 64 bit support
#if __LIBELF64
ELF_GET_DATA(64)
#endif
}
if (!debuglink.empty()) {
// We have a debuglink section! Open an elf instance on that
// file instead. If we can't open the file, then return
// the elf handle we had already opened.
dwarf_file_t debuglink_file;
debuglink_file.reset(open(debuglink.c_str(), O_RDONLY));
if (debuglink_file.get() > 0) {
dwarf_elf_t debuglink_elf;
debuglink_elf.reset(elf_begin(debuglink_file.get(), ELF_C_READ, NULL));
// If we have a valid elf handle, return the new elf handle
// and file handle and discard the original ones
if (debuglink_elf) {
elf_handle = move(debuglink_elf);
file_handle = move(debuglink_file);
}
}
}
// Ok, we have a valid ELF handle, let's try to get debug symbols
Dwarf_Debug dwarf_debug;
Dwarf_Error error = DW_DLE_NE;
dwarf_handle_t dwarf_handle;
int dwarf_result = dwarf_elf_init(elf_handle.get(), DW_DLC_READ, NULL, NULL,
&dwarf_debug, &error);
// We don't do any special handling for DW_DLV_NO_ENTRY specially.
// If we get an error, or the file doesn't have debug information
// we just return.
if (dwarf_result != DW_DLV_OK) {
return r;
}
dwarf_handle.reset(dwarf_debug);
r.file_handle = move(file_handle);
r.elf_handle = move(elf_handle);
r.dwarf_handle = move(dwarf_handle);
return r;
}
die_cache_entry &get_die_cache(dwarf_fileobject &fobj, Dwarf_Die die) {
Dwarf_Error error = DW_DLE_NE;
// Get the die offset, we use it as the cache key
Dwarf_Off die_offset;
if (dwarf_dieoffset(die, &die_offset, &error) != DW_DLV_OK) {
die_offset = 0;
}
die_cache_t::iterator it = fobj.die_cache.find(die_offset);
if (it != fobj.die_cache.end()) {
fobj.current_cu = &it->second;
return it->second;
}
die_cache_entry &de = fobj.die_cache[die_offset];
fobj.current_cu = &de;
Dwarf_Addr line_addr;
Dwarf_Small table_count;
// The addresses in the line section are not fully sorted (they might
// be sorted by block of code belonging to the same file), which makes
// it necessary to do so before searching is possible.
//
// As libdwarf allocates a copy of everything, let's get the contents
// of the line section and keep it around. We also create a map of
// program counter to line table indices so we can search by address
// and get the line buffer index.
//
// To make things more difficult, the same address can span more than
// one line, so we need to keep the index pointing to the first line
// by using insert instead of the map's [ operator.
// Get the line context for the DIE
if (dwarf_srclines_b(die, 0, &table_count, &de.line_context, &error) ==
DW_DLV_OK) {
// Get the source lines for this line context, to be deallocated
// later
if (dwarf_srclines_from_linecontext(de.line_context, &de.line_buffer,
&de.line_count,
&error) == DW_DLV_OK) {
// Add all the addresses to our map
for (int i = 0; i < de.line_count; i++) {
if (dwarf_lineaddr(de.line_buffer[i], &line_addr, &error) !=
DW_DLV_OK) {
line_addr = 0;
}
de.line_section.insert(std::pair<Dwarf_Addr, int>(line_addr, i));
}
}
}
// For each CU, cache the function DIEs that contain the
// DW_AT_specification attribute. When building with -g3 the function
// DIEs are separated in declaration and specification, with the
// declaration containing only the name and parameters and the
// specification the low/high pc and other compiler attributes.
//
// We cache those specifications so we don't skip over the declarations,
// because they have no pc, and we can do namespace resolution for
// DWARF function names.
Dwarf_Debug dwarf = fobj.dwarf_handle.get();
Dwarf_Die current_die = 0;
if (dwarf_child(die, ¤t_die, &error) == DW_DLV_OK) {
for (;;) {
Dwarf_Die sibling_die = 0;
Dwarf_Half tag_value;
dwarf_tag(current_die, &tag_value, &error);
if (tag_value == DW_TAG_subprogram ||
tag_value == DW_TAG_inlined_subroutine) {
Dwarf_Bool has_attr = 0;
if (dwarf_hasattr(current_die, DW_AT_specification, &has_attr,
&error) == DW_DLV_OK) {
if (has_attr) {
Dwarf_Attribute attr_mem;
if (dwarf_attr(current_die, DW_AT_specification, &attr_mem,
&error) == DW_DLV_OK) {
Dwarf_Off spec_offset = 0;
if (dwarf_formref(attr_mem, &spec_offset, &error) ==
DW_DLV_OK) {
Dwarf_Off spec_die_offset;
if (dwarf_dieoffset(current_die, &spec_die_offset, &error) ==
DW_DLV_OK) {
de.spec_section[spec_offset] = spec_die_offset;
}
}
}
dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
}
}
}
int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
if (result == DW_DLV_ERROR) {
break;
} else if (result == DW_DLV_NO_ENTRY) {
break;
}
if (current_die != die) {
dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
current_die = 0;
}
current_die = sibling_die;
}
}
return de;
}
static Dwarf_Die get_referenced_die(Dwarf_Debug dwarf, Dwarf_Die die,
Dwarf_Half attr, bool global) {
Dwarf_Error error = DW_DLE_NE;
Dwarf_Attribute attr_mem;
Dwarf_Die found_die = NULL;
if (dwarf_attr(die, attr, &attr_mem, &error) == DW_DLV_OK) {
Dwarf_Off offset;
int result = 0;
if (global) {
result = dwarf_global_formref(attr_mem, &offset, &error);
} else {
result = dwarf_formref(attr_mem, &offset, &error);
}
if (result == DW_DLV_OK) {
if (dwarf_offdie(dwarf, offset, &found_die, &error) != DW_DLV_OK) {
found_die = NULL;
}
}
dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
}
return found_die;
}
static std::string get_referenced_die_name(Dwarf_Debug dwarf, Dwarf_Die die,
Dwarf_Half attr, bool global) {
Dwarf_Error error = DW_DLE_NE;
std::string value;
Dwarf_Die found_die = get_referenced_die(dwarf, die, attr, global);
if (found_die) {
char *name;
if (dwarf_diename(found_die, &name, &error) == DW_DLV_OK) {
if (name) {
value = std::string(name);
}
dwarf_dealloc(dwarf, name, DW_DLA_STRING);
}
dwarf_dealloc(dwarf, found_die, DW_DLA_DIE);
}
return value;
}
// Returns a spec DIE linked to the passed one. The caller should
// deallocate the DIE
static Dwarf_Die get_spec_die(dwarf_fileobject &fobj, Dwarf_Die die) {
Dwarf_Debug dwarf = fobj.dwarf_handle.get();
Dwarf_Error error = DW_DLE_NE;
Dwarf_Off die_offset;
if (fobj.current_cu &&
dwarf_die_CU_offset(die, &die_offset, &error) == DW_DLV_OK) {
die_specmap_t::iterator it =
fobj.current_cu->spec_section.find(die_offset);
// If we have a DIE that completes the current one, check if
// that one has the pc we are looking for
if (it != fobj.current_cu->spec_section.end()) {
Dwarf_Die spec_die = 0;
if (dwarf_offdie(dwarf, it->second, &spec_die, &error) == DW_DLV_OK) {
return spec_die;
}
}
}
// Maybe we have an abstract origin DIE with the function information?
return get_referenced_die(fobj.dwarf_handle.get(), die,
DW_AT_abstract_origin, true);
}
static bool die_has_pc(dwarf_fileobject &fobj, Dwarf_Die die, Dwarf_Addr pc) {
Dwarf_Addr low_pc = 0, high_pc = 0;
Dwarf_Half high_pc_form = 0;
Dwarf_Form_Class return_class;
Dwarf_Error error = DW_DLE_NE;
Dwarf_Debug dwarf = fobj.dwarf_handle.get();
bool has_lowpc = false;
bool has_highpc = false;
bool has_ranges = false;
if (dwarf_lowpc(die, &low_pc, &error) == DW_DLV_OK) {
// If we have a low_pc check if there is a high pc.
// If we don't have a high pc this might mean we have a base
// address for the ranges list or just an address.
has_lowpc = true;
if (dwarf_highpc_b(die, &high_pc, &high_pc_form, &return_class, &error) ==
DW_DLV_OK) {
// We do have a high pc. In DWARF 4+ this is an offset from the
// low pc, but in earlier versions it's an absolute address.
has_highpc = true;
// In DWARF 2/3 this would be a DW_FORM_CLASS_ADDRESS
if (return_class == DW_FORM_CLASS_CONSTANT) {
high_pc = low_pc + high_pc;
}
// We have low and high pc, check if our address
// is in that range
return pc >= low_pc && pc < high_pc;
}
} else {
// Reset the low_pc, in case dwarf_lowpc failing set it to some
// undefined value.
low_pc = 0;
}
// Check if DW_AT_ranges is present and search for the PC in the
// returned ranges list. We always add the low_pc, as it not set it will
// be 0, in case we had a DW_AT_low_pc and DW_AT_ranges pair
bool result = false;
Dwarf_Attribute attr;
if (dwarf_attr(die, DW_AT_ranges, &attr, &error) == DW_DLV_OK) {
Dwarf_Off offset;
if (dwarf_global_formref(attr, &offset, &error) == DW_DLV_OK) {
Dwarf_Ranges *ranges;
Dwarf_Signed ranges_count = 0;
Dwarf_Unsigned byte_count = 0;
if (dwarf_get_ranges_a(dwarf, offset, die, &ranges, &ranges_count,
&byte_count, &error) == DW_DLV_OK) {
has_ranges = ranges_count != 0;
for (int i = 0; i < ranges_count; i++) {
if (ranges[i].dwr_addr1 != 0 &&
pc >= ranges[i].dwr_addr1 + low_pc &&
pc < ranges[i].dwr_addr2 + low_pc) {
result = true;
break;
}
}
dwarf_ranges_dealloc(dwarf, ranges, ranges_count);
}
}
}
// Last attempt. We might have a single address set as low_pc.
if (!result && low_pc != 0 && pc == low_pc) {
result = true;
}
// If we don't have lowpc, highpc and ranges maybe this DIE is a
// declaration that relies on a DW_AT_specification DIE that happens
// later. Use the specification cache we filled when we loaded this CU.
if (!result && (!has_lowpc && !has_highpc && !has_ranges)) {
Dwarf_Die spec_die = get_spec_die(fobj, die);
if (spec_die) {
result = die_has_pc(fobj, spec_die, pc);
dwarf_dealloc(dwarf, spec_die, DW_DLA_DIE);
}
}
return result;
}
static void get_type(Dwarf_Debug dwarf, Dwarf_Die die, std::string &type) {
Dwarf_Error error = DW_DLE_NE;
Dwarf_Die child = 0;
if (dwarf_child(die, &child, &error) == DW_DLV_OK) {
get_type(dwarf, child, type);
}
if (child) {
type.insert(0, "::");
dwarf_dealloc(dwarf, child, DW_DLA_DIE);
}
char *name;
if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
type.insert(0, std::string(name));
dwarf_dealloc(dwarf, name, DW_DLA_STRING);
} else {
type.insert(0, "<unknown>");
}
}
static std::string get_type_by_signature(Dwarf_Debug dwarf, Dwarf_Die die) {
Dwarf_Error error = DW_DLE_NE;
Dwarf_Sig8 signature;
Dwarf_Bool has_attr = 0;
if (dwarf_hasattr(die, DW_AT_signature, &has_attr, &error) == DW_DLV_OK) {
if (has_attr) {
Dwarf_Attribute attr_mem;
if (dwarf_attr(die, DW_AT_signature, &attr_mem, &error) == DW_DLV_OK) {
if (dwarf_formsig8(attr_mem, &signature, &error) != DW_DLV_OK) {
return std::string("<no type signature>");
}
}
dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
}
}
Dwarf_Unsigned next_cu_header;
Dwarf_Sig8 tu_signature;
std::string result;
bool found = false;
while (dwarf_next_cu_header_d(dwarf, 0, 0, 0, 0, 0, 0, 0, &tu_signature, 0,
&next_cu_header, 0, &error) == DW_DLV_OK) {
if (strncmp(signature.signature, tu_signature.signature, 8) == 0) {
Dwarf_Die type_cu_die = 0;
if (dwarf_siblingof_b(dwarf, 0, 0, &type_cu_die, &error) == DW_DLV_OK) {
Dwarf_Die child_die = 0;
if (dwarf_child(type_cu_die, &child_die, &error) == DW_DLV_OK) {
get_type(dwarf, child_die, result);
found = !result.empty();
dwarf_dealloc(dwarf, child_die, DW_DLA_DIE);
}
dwarf_dealloc(dwarf, type_cu_die, DW_DLA_DIE);
}
}
}
if (found) {
while (dwarf_next_cu_header_d(dwarf, 0, 0, 0, 0, 0, 0, 0, 0, 0,
&next_cu_header, 0, &error) == DW_DLV_OK) {
// Reset the cu header state. Unfortunately, libdwarf's
// next_cu_header API keeps its own iterator per Dwarf_Debug
// that can't be reset. We need to keep fetching elements until
// the end.
}
} else {
// If we couldn't resolve the type just print out the signature
std::ostringstream string_stream;
string_stream << "<0x" << std::hex << std::setfill('0');
for (int i = 0; i < 8; ++i) {
string_stream << std::setw(2) << std::hex
<< (int)(unsigned char)(signature.signature[i]);
}
string_stream << ">";
result = string_stream.str();
}
return result;
}
struct type_context_t {
bool is_const;
bool is_typedef;
bool has_type;
bool has_name;
std::string text;
type_context_t()
: is_const(false), is_typedef(false), has_type(false), has_name(false) {
}
};
// Types are resolved from right to left: we get the variable name first
// and then all specifiers (like const or pointer) in a chain of DW_AT_type
// DIEs. Call this function recursively until we get a complete type
// string.
static void set_parameter_string(dwarf_fileobject &fobj, Dwarf_Die die,
type_context_t &context) {
char *name;
Dwarf_Error error = DW_DLE_NE;
// typedefs contain also the base type, so we skip it and only
// print the typedef name
if (!context.is_typedef) {
if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
if (!context.text.empty()) {
context.text.insert(0, " ");
}
context.text.insert(0, std::string(name));
dwarf_dealloc(fobj.dwarf_handle.get(), name, DW_DLA_STRING);
}
} else {
context.is_typedef = false;
context.has_type = true;
if (context.is_const) {
context.text.insert(0, "const ");
context.is_const = false;
}
}
bool next_type_is_const = false;
bool is_keyword = true;
Dwarf_Half tag = 0;
Dwarf_Bool has_attr = 0;
if (dwarf_tag(die, &tag, &error) == DW_DLV_OK) {
switch (tag) {
case DW_TAG_structure_type:
case DW_TAG_union_type:
case DW_TAG_class_type:
case DW_TAG_enumeration_type:
context.has_type = true;
if (dwarf_hasattr(die, DW_AT_signature, &has_attr, &error) ==
DW_DLV_OK) {
// If we have a signature it means the type is defined
// in .debug_types, so we need to load the DIE pointed
// at by the signature and resolve it
if (has_attr) {
std::string type =
get_type_by_signature(fobj.dwarf_handle.get(), die);
if (context.is_const)
type.insert(0, "const ");
if (!context.text.empty())
context.text.insert(0, " ");
context.text.insert(0, type);
}
// Treat enums like typedefs, and skip printing its
// base type
context.is_typedef = (tag == DW_TAG_enumeration_type);
}
break;
case DW_TAG_const_type:
next_type_is_const = true;
break;
case DW_TAG_pointer_type:
context.text.insert(0, "*");
break;
case DW_TAG_reference_type:
context.text.insert(0, "&");
break;
case DW_TAG_restrict_type:
context.text.insert(0, "restrict ");
break;
case DW_TAG_rvalue_reference_type:
context.text.insert(0, "&&");
break;
case DW_TAG_volatile_type:
context.text.insert(0, "volatile ");
break;
case DW_TAG_typedef:
// Propagate the const-ness to the next type
// as typedefs are linked to its base type
next_type_is_const = context.is_const;
context.is_typedef = true;
context.has_type = true;
break;
case DW_TAG_base_type:
context.has_type = true;
break;
case DW_TAG_formal_parameter:
context.has_name = true;
break;
default:
is_keyword = false;
break;
}
}
if (!is_keyword && context.is_const) {
context.text.insert(0, "const ");
}
context.is_const = next_type_is_const;
Dwarf_Die ref =
get_referenced_die(fobj.dwarf_handle.get(), die, DW_AT_type, true);
if (ref) {
set_parameter_string(fobj, ref, context);
dwarf_dealloc(fobj.dwarf_handle.get(), ref, DW_DLA_DIE);
}
if (!context.has_type && context.has_name) {
context.text.insert(0, "void ");
context.has_type = true;
}
}
// Resolve the function return type and parameters
static void set_function_parameters(std::string &function_name,
std::vector<std::string> &ns,
dwarf_fileobject &fobj, Dwarf_Die die) {
Dwarf_Debug dwarf = fobj.dwarf_handle.get();
Dwarf_Error error = DW_DLE_NE;
Dwarf_Die current_die = 0;
std::string parameters;
bool has_spec = true;
// Check if we have a spec DIE. If we do we use it as it contains
// more information, like parameter names.
Dwarf_Die spec_die = get_spec_die(fobj, die);
if (!spec_die) {
has_spec = false;
spec_die = die;
}
std::vector<std::string>::const_iterator it = ns.begin();
std::string ns_name;
for (it = ns.begin(); it < ns.end(); ++it) {
ns_name.append(*it).append("::");
}
if (!ns_name.empty()) {
function_name.insert(0, ns_name);
}
// See if we have a function return type. It can be either on the
// current die or in its spec one (usually true for inlined functions)
std::string return_type =
get_referenced_die_name(dwarf, die, DW_AT_type, true);
if (return_type.empty()) {
return_type = get_referenced_die_name(dwarf, spec_die, DW_AT_type, true);
}
if (!return_type.empty()) {
return_type.append(" ");
function_name.insert(0, return_type);
}
if (dwarf_child(spec_die, ¤t_die, &error) == DW_DLV_OK) {
for (;;) {
Dwarf_Die sibling_die = 0;
Dwarf_Half tag_value;
dwarf_tag(current_die, &tag_value, &error);
if (tag_value == DW_TAG_formal_parameter) {
// Ignore artificial (ie, compiler generated) parameters
bool is_artificial = false;
Dwarf_Attribute attr_mem;
if (dwarf_attr(current_die, DW_AT_artificial, &attr_mem, &error) ==
DW_DLV_OK) {
Dwarf_Bool flag = 0;
if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) {
is_artificial = flag != 0;
}
dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
}
if (!is_artificial) {
type_context_t context;
set_parameter_string(fobj, current_die, context);
if (parameters.empty()) {
parameters.append("(");
} else {
parameters.append(", ");
}
parameters.append(context.text);
}
}
int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
if (result == DW_DLV_ERROR) {
break;
} else if (result == DW_DLV_NO_ENTRY) {
break;
}
if (current_die != die) {
dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
current_die = 0;
}
current_die = sibling_die;
}
}
if (parameters.empty())
parameters = "(";
parameters.append(")");
// If we got a spec DIE we need to deallocate it
if (has_spec)
dwarf_dealloc(dwarf, spec_die, DW_DLA_DIE);
function_name.append(parameters);
}
// defined here because in C++98, template function cannot take locally
// defined types... grrr.
struct inliners_search_cb {
void operator()(Dwarf_Die die, std::vector<std::string> &ns) {
Dwarf_Error error = DW_DLE_NE;
Dwarf_Half tag_value;
Dwarf_Attribute attr_mem;
Dwarf_Debug dwarf = fobj.dwarf_handle.get();
dwarf_tag(die, &tag_value, &error);
switch (tag_value) {
char *name;
case DW_TAG_subprogram:
if (!trace.source.function.empty())
break;
if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
trace.source.function = std::string(name);
dwarf_dealloc(dwarf, name, DW_DLA_STRING);
} else {
// We don't have a function name in this DIE.
// Check if there is a referenced non-defining
// declaration.
trace.source.function =
get_referenced_die_name(dwarf, die, DW_AT_abstract_origin, true);
if (trace.source.function.empty()) {
trace.source.function =
get_referenced_die_name(dwarf, die, DW_AT_specification, true);
}
}
// Append the function parameters, if available
set_function_parameters(trace.source.function, ns, fobj, die);
// If the object function name is empty, it's possible that
// there is no dynamic symbol table (maybe the executable
// was stripped or not built with -rdynamic). See if we have
// a DWARF linkage name to use instead. We try both
// linkage_name and MIPS_linkage_name because the MIPS tag
// was the unofficial one until it was adopted in DWARF4.
// Old gcc versions generate MIPS_linkage_name
if (trace.object_function.empty()) {
details::demangler demangler;
if (dwarf_attr(die, DW_AT_linkage_name, &attr_mem, &error) !=
DW_DLV_OK) {
if (dwarf_attr(die, DW_AT_MIPS_linkage_name, &attr_mem, &error) !=
DW_DLV_OK) {
break;
}
}
char *linkage;
if (dwarf_formstring(attr_mem, &linkage, &error) == DW_DLV_OK) {
trace.object_function = demangler.demangle(linkage);
dwarf_dealloc(dwarf, linkage, DW_DLA_STRING);
}
dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
}
break;
case DW_TAG_inlined_subroutine:
ResolvedTrace::SourceLoc sloc;
if (dwarf_diename(die, &name, &error) == DW_DLV_OK) {
sloc.function = std::string(name);
dwarf_dealloc(dwarf, name, DW_DLA_STRING);
} else {
// We don't have a name for this inlined DIE, it could
// be that there is an abstract origin instead.
// Get the DW_AT_abstract_origin value, which is a
// reference to the source DIE and try to get its name
sloc.function =
get_referenced_die_name(dwarf, die, DW_AT_abstract_origin, true);
}
set_function_parameters(sloc.function, ns, fobj, die);
std::string file = die_call_file(dwarf, die, cu_die);
if (!file.empty())
sloc.filename = file;
Dwarf_Unsigned number = 0;
if (dwarf_attr(die, DW_AT_call_line, &attr_mem, &error) == DW_DLV_OK) {
if (dwarf_formudata(attr_mem, &number, &error) == DW_DLV_OK) {
sloc.line = number;
}
dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
}
if (dwarf_attr(die, DW_AT_call_column, &attr_mem, &error) ==
DW_DLV_OK) {
if (dwarf_formudata(attr_mem, &number, &error) == DW_DLV_OK) {
sloc.col = number;
}
dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
}
trace.inliners.push_back(sloc);
break;
};
}
ResolvedTrace &trace;
dwarf_fileobject &fobj;
Dwarf_Die cu_die;
inliners_search_cb(ResolvedTrace &t, dwarf_fileobject &f, Dwarf_Die c)
: trace(t), fobj(f), cu_die(c) {}
};
static Dwarf_Die find_fundie_by_pc(dwarf_fileobject &fobj,
Dwarf_Die parent_die, Dwarf_Addr pc,
Dwarf_Die result) {
Dwarf_Die current_die = 0;
Dwarf_Error error = DW_DLE_NE;
Dwarf_Debug dwarf = fobj.dwarf_handle.get();
if (dwarf_child(parent_die, ¤t_die, &error) != DW_DLV_OK) {
return NULL;
}
for (;;) {
Dwarf_Die sibling_die = 0;
Dwarf_Half tag_value;
dwarf_tag(current_die, &tag_value, &error);
switch (tag_value) {
case DW_TAG_subprogram:
case DW_TAG_inlined_subroutine:
if (die_has_pc(fobj, current_die, pc)) {
return current_die;
}
};
bool declaration = false;
Dwarf_Attribute attr_mem;
if (dwarf_attr(current_die, DW_AT_declaration, &attr_mem, &error) ==
DW_DLV_OK) {
Dwarf_Bool flag = 0;
if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) {
declaration = flag != 0;
}
dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
}
if (!declaration) {
// let's be curious and look deeper in the tree, functions are
// not necessarily at the first level, but might be nested
// inside a namespace, structure, a function, an inlined
// function etc.
Dwarf_Die die_mem = 0;
Dwarf_Die indie = find_fundie_by_pc(fobj, current_die, pc, die_mem);
if (indie) {
result = die_mem;
return result;
}
}
int res = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
if (res == DW_DLV_ERROR) {
return NULL;
} else if (res == DW_DLV_NO_ENTRY) {
break;
}
if (current_die != parent_die) {
dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
current_die = 0;
}
current_die = sibling_die;
}
return NULL;
}
template <typename CB>
static bool deep_first_search_by_pc(dwarf_fileobject &fobj,
Dwarf_Die parent_die, Dwarf_Addr pc,
std::vector<std::string> &ns, CB cb) {
Dwarf_Die current_die = 0;
Dwarf_Debug dwarf = fobj.dwarf_handle.get();
Dwarf_Error error = DW_DLE_NE;
if (dwarf_child(parent_die, ¤t_die, &error) != DW_DLV_OK) {
return false;
}
bool branch_has_pc = false;
bool has_namespace = false;
for (;;) {
Dwarf_Die sibling_die = 0;
Dwarf_Half tag;
if (dwarf_tag(current_die, &tag, &error) == DW_DLV_OK) {
if (tag == DW_TAG_namespace || tag == DW_TAG_class_type) {
char *ns_name = NULL;
if (dwarf_diename(current_die, &ns_name, &error) == DW_DLV_OK) {
if (ns_name) {
ns.push_back(std::string(ns_name));
} else {
ns.push_back("<unknown>");
}
dwarf_dealloc(dwarf, ns_name, DW_DLA_STRING);
} else {
ns.push_back("<unknown>");
}
has_namespace = true;
}
}
bool declaration = false;
Dwarf_Attribute attr_mem;
if (tag != DW_TAG_class_type &&
dwarf_attr(current_die, DW_AT_declaration, &attr_mem, &error) ==
DW_DLV_OK) {
Dwarf_Bool flag = 0;
if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) {
declaration = flag != 0;
}
dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
}
if (!declaration) {
// let's be curious and look deeper in the tree, function are
// not necessarily at the first level, but might be nested
// inside a namespace, structure, a function, an inlined
// function etc.
branch_has_pc = deep_first_search_by_pc(fobj, current_die, pc, ns, cb);
}
if (!branch_has_pc) {
branch_has_pc = die_has_pc(fobj, current_die, pc);
}
if (branch_has_pc) {
cb(current_die, ns);
}
int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error);
if (result == DW_DLV_ERROR) {
return false;
} else if (result == DW_DLV_NO_ENTRY) {
break;
}
if (current_die != parent_die) {
dwarf_dealloc(dwarf, current_die, DW_DLA_DIE);
current_die = 0;
}
if (has_namespace) {
has_namespace = false;
ns.pop_back();
}
current_die = sibling_die;
}
if (has_namespace) {
ns.pop_back();
}
return branch_has_pc;
}
static std::string die_call_file(Dwarf_Debug dwarf, Dwarf_Die die,
Dwarf_Die cu_die) {
Dwarf_Attribute attr_mem;
Dwarf_Error error = DW_DLE_NE;
Dwarf_Unsigned file_index;
std::string file;
if (dwarf_attr(die, DW_AT_call_file, &attr_mem, &error) == DW_DLV_OK) {
if (dwarf_formudata(attr_mem, &file_index, &error) != DW_DLV_OK) {
file_index = 0;
}
dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR);
if (file_index == 0) {
return file;
}
char **srcfiles = 0;
Dwarf_Signed file_count = 0;
if (dwarf_srcfiles(cu_die, &srcfiles, &file_count, &error) == DW_DLV_OK) {
if (file_count > 0 && file_index <= static_cast<Dwarf_Unsigned>(file_count)) {
file = std::string(srcfiles[file_index - 1]);
}
// Deallocate all strings!
for (int i = 0; i < file_count; ++i) {
dwarf_dealloc(dwarf, srcfiles[i], DW_DLA_STRING);
}
dwarf_dealloc(dwarf, srcfiles, DW_DLA_LIST);
}
}
return file;
}
Dwarf_Die find_die(dwarf_fileobject &fobj, Dwarf_Addr addr) {
// Let's get to work! First see if we have a debug_aranges section so
// we can speed up the search
Dwarf_Debug dwarf = fobj.dwarf_handle.get();
Dwarf_Error error = DW_DLE_NE;
Dwarf_Arange *aranges;
Dwarf_Signed arange_count;
Dwarf_Die returnDie;
bool found = false;
if (dwarf_get_aranges(dwarf, &aranges, &arange_count, &error) !=
DW_DLV_OK) {
aranges = NULL;
}
if (aranges) {
// We have aranges. Get the one where our address is.
Dwarf_Arange arange;
if (dwarf_get_arange(aranges, arange_count, addr, &arange, &error) ==
DW_DLV_OK) {
// We found our address. Get the compilation-unit DIE offset
// represented by the given address range.
Dwarf_Off cu_die_offset;
if (dwarf_get_cu_die_offset(arange, &cu_die_offset, &error) ==
DW_DLV_OK) {
// Get the DIE at the offset returned by the aranges search.
// We set is_info to 1 to specify that the offset is from
// the .debug_info section (and not .debug_types)
int dwarf_result =
dwarf_offdie_b(dwarf, cu_die_offset, 1, &returnDie, &error);
found = dwarf_result == DW_DLV_OK;
}
dwarf_dealloc(dwarf, arange, DW_DLA_ARANGE);
}
}
if (found)
return returnDie; // The caller is responsible for freeing the die
// The search for aranges failed. Try to find our address by scanning
// all compilation units.
Dwarf_Unsigned next_cu_header;
Dwarf_Half tag = 0;
returnDie = 0;
while (!found &&
dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
&next_cu_header, 0, &error) == DW_DLV_OK) {
if (returnDie)
dwarf_dealloc(dwarf, returnDie, DW_DLA_DIE);
if (dwarf_siblingof(dwarf, 0, &returnDie, &error) == DW_DLV_OK) {
if ((dwarf_tag(returnDie, &tag, &error) == DW_DLV_OK) &&
tag == DW_TAG_compile_unit) {
if (die_has_pc(fobj, returnDie, addr)) {
found = true;
}
}
}
}
if (found) {
while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
&next_cu_header, 0, &error) == DW_DLV_OK) {
// Reset the cu header state. Libdwarf's next_cu_header API
// keeps its own iterator per Dwarf_Debug that can't be reset.
// We need to keep fetching elements until the end.
}
}
if (found)
return returnDie;
// We couldn't find any compilation units with ranges or a high/low pc.
// Try again by looking at all DIEs in all compilation units.
Dwarf_Die cudie;
while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
&next_cu_header, 0, &error) == DW_DLV_OK) {
if (dwarf_siblingof(dwarf, 0, &cudie, &error) == DW_DLV_OK) {
Dwarf_Die die_mem = 0;
Dwarf_Die resultDie = find_fundie_by_pc(fobj, cudie, addr, die_mem);
if (resultDie) {
found = true;
break;
}
}
}
if (found) {
while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0,
&next_cu_header, 0, &error) == DW_DLV_OK) {
// Reset the cu header state. Libdwarf's next_cu_header API
// keeps its own iterator per Dwarf_Debug that can't be reset.
// We need to keep fetching elements until the end.
}
}
if (found)
return cudie;
// We failed.
return NULL;
}
};
#endif // BACKWARD_HAS_DWARF == 1
template <>
class TraceResolverImpl<system_tag::linux_tag>
: public TraceResolverLinuxImpl<trace_resolver_tag::current> {};
#endif // BACKWARD_SYSTEM_LINUX
#ifdef BACKWARD_SYSTEM_DARWIN
template <typename STACKTRACE_TAG> class TraceResolverDarwinImpl;
template <>
class TraceResolverDarwinImpl<trace_resolver_tag::backtrace_symbol>
: public TraceResolverImplBase {
public:
void load_addresses(void *const*addresses, int address_count) override {
if (address_count == 0) {
return;
}
_symbols.reset(backtrace_symbols(addresses, address_count));
}
ResolvedTrace resolve(ResolvedTrace trace) override {
// parse:
// <n> <file> <addr> <mangled-name> + <offset>
char *filename = _symbols[trace.idx];
// skip "<n> "
while (*filename && *filename != ' ')
filename++;
while (*filename == ' ')
filename++;
// find start of <mangled-name> from end (<file> may contain a space)
char *p = filename + strlen(filename) - 1;
// skip to start of " + <offset>"
while (p > filename && *p != ' ')
p--;
while (p > filename && *p == ' ')
p--;
while (p > filename && *p != ' ')
p--;
while (p > filename && *p == ' ')
p--;
char *funcname_end = p + 1;
// skip to start of "<manged-name>"
while (p > filename && *p != ' ')
p--;
char *funcname = p + 1;
// skip to start of " <addr> "
while (p > filename && *p == ' ')
p--;
while (p > filename && *p != ' ')
p--;
while (p > filename && *p == ' ')
p--;
// skip "<file>", handling the case where it contains a
char *filename_end = p + 1;
if (p == filename) {
// something went wrong, give up
filename_end = filename + strlen(filename);
funcname = filename_end;
}
trace.object_filename.assign(
filename, filename_end); // ok even if filename_end is the ending \0
// (then we assign entire string)
if (*funcname) { // if it's not end of string
*funcname_end = '\0';
trace.object_function = this->demangle(funcname);
trace.object_function += " ";
trace.object_function += (funcname_end + 1);
trace.source.function = trace.object_function; // we cannot do better.
}
return trace;
}
private:
details::handle<char **> _symbols;
};
template <>
class TraceResolverImpl<system_tag::darwin_tag>
: public TraceResolverDarwinImpl<trace_resolver_tag::current> {};
#endif // BACKWARD_SYSTEM_DARWIN
#ifdef BACKWARD_SYSTEM_WINDOWS
// Load all symbol info
// Based on:
// https://stackoverflow.com/questions/6205981/windows-c-stack-trace-from-a-running-app/28276227#28276227
struct module_data {
std::string image_name;
std::string module_name;
void *base_address;
DWORD load_size;
};
class get_mod_info {
HANDLE process;
static const int buffer_length = 4096;
public:
get_mod_info(HANDLE h) : process(h) {}
module_data operator()(HMODULE module) {
module_data ret;
char temp[buffer_length];
MODULEINFO mi;
GetModuleInformation(process, module, &mi, sizeof(mi));
ret.base_address = mi.lpBaseOfDll;
ret.load_size = mi.SizeOfImage;
GetModuleFileNameExA(process, module, temp, sizeof(temp));
ret.image_name = temp;
GetModuleBaseNameA(process, module, temp, sizeof(temp));
ret.module_name = temp;
std::vector<char> img(ret.image_name.begin(), ret.image_name.end());
std::vector<char> mod(ret.module_name.begin(), ret.module_name.end());
SymLoadModule64(process, 0, &img[0], &mod[0], (DWORD64)ret.base_address,
ret.load_size);
return ret;
}
};
template <> class TraceResolverImpl<system_tag::windows_tag>
: public TraceResolverImplBase {
public:
TraceResolverImpl() {
HANDLE process = GetCurrentProcess();
std::vector<module_data> modules;
DWORD cbNeeded;
std::vector<HMODULE> module_handles(1);
SymInitialize(process, NULL, false);
DWORD symOptions = SymGetOptions();
symOptions |= SYMOPT_LOAD_LINES | SYMOPT_UNDNAME;
SymSetOptions(symOptions);
EnumProcessModules(process, &module_handles[0],
module_handles.size() * sizeof(HMODULE), &cbNeeded);
module_handles.resize(cbNeeded / sizeof(HMODULE));
EnumProcessModules(process, &module_handles[0],
module_handles.size() * sizeof(HMODULE), &cbNeeded);
std::transform(module_handles.begin(), module_handles.end(),
std::back_inserter(modules), get_mod_info(process));
void *base = modules[0].base_address;
IMAGE_NT_HEADERS *h = ImageNtHeader(base);
image_type = h->FileHeader.Machine;
}
static const int max_sym_len = 255;
struct symbol_t {
SYMBOL_INFO sym;
char buffer[max_sym_len];
} sym;
DWORD64 displacement;
ResolvedTrace resolve(ResolvedTrace t) override {
HANDLE process = GetCurrentProcess();
char name[256];
memset(&sym, 0, sizeof(sym));
sym.sym.SizeOfStruct = sizeof(SYMBOL_INFO);
sym.sym.MaxNameLen = max_sym_len;
if (!SymFromAddr(process, (ULONG64)t.addr, &displacement, &sym.sym)) {
// TODO: error handling everywhere
char* lpMsgBuf;
DWORD dw = GetLastError();
if (FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(char*)&lpMsgBuf, 0, NULL)) {
std::fprintf(stderr, "%s\n", lpMsgBuf);
LocalFree(lpMsgBuf);
}
// abort();
}
UnDecorateSymbolName(sym.sym.Name, (PSTR)name, 256, UNDNAME_COMPLETE);
DWORD offset = 0;
IMAGEHLP_LINE line;
if (SymGetLineFromAddr(process, (ULONG64)t.addr, &offset, &line)) {
t.object_filename = line.FileName;
t.source.filename = line.FileName;
t.source.line = line.LineNumber;
t.source.col = offset;
}
t.source.function = name;
t.object_filename = "";
t.object_function = name;
return t;
}
DWORD machine_type() const { return image_type; }
private:
DWORD image_type;
};
#endif
class TraceResolver : public TraceResolverImpl<system_tag::current_tag> {};
/*************** CODE SNIPPET ***************/
class SourceFile {
public:
typedef std::vector<std::pair<unsigned, std::string> > lines_t;
SourceFile() {}
SourceFile(const std::string &path) {
// 1. If BACKWARD_CXX_SOURCE_PREFIXES is set then assume it contains
// a colon-separated list of path prefixes. Try prepending each
// to the given path until a valid file is found.
const std::vector<std::string> &prefixes = get_paths_from_env_variable();
for (size_t i = 0; i < prefixes.size(); ++i) {
// Double slashes (//) should not be a problem.
std::string new_path = prefixes[i] + '/' + path;
_file.reset(new std::ifstream(new_path.c_str()));
if (is_open())
break;
}
// 2. If no valid file found then fallback to opening the path as-is.
if (!_file || !is_open()) {
_file.reset(new std::ifstream(path.c_str()));
}
}
bool is_open() const { return _file->is_open(); }
lines_t &get_lines(unsigned line_start, unsigned line_count, lines_t &lines) {
using namespace std;
// This function make uses of the dumbest algo ever:
// 1) seek(0)
// 2) read lines one by one and discard until line_start
// 3) read line one by one until line_start + line_count
//
// If you are getting snippets many time from the same file, it is
// somewhat a waste of CPU, feel free to benchmark and propose a
// better solution ;)
_file->clear();
_file->seekg(0);
string line;
unsigned line_idx;
for (line_idx = 1; line_idx < line_start; ++line_idx) {
std::getline(*_file, line);
if (!*_file) {
return lines;
}
}
// think of it like a lambda in C++98 ;)
// but look, I will reuse it two times!
// What a good boy am I.
struct isspace {
bool operator()(char c) { return std::isspace(c); }
};
bool started = false;
for (; line_idx < line_start + line_count; ++line_idx) {
getline(*_file, line);
if (!*_file) {
return lines;
}
if (!started) {
if (std::find_if(line.begin(), line.end(), not_isspace()) == line.end())
continue;
started = true;
}
lines.push_back(make_pair(line_idx, line));
}
lines.erase(
std::find_if(lines.rbegin(), lines.rend(), not_isempty()).base(),
lines.end());
return lines;
}
lines_t get_lines(unsigned line_start, unsigned line_count) {
lines_t lines;
return get_lines(line_start, line_count, lines);
}
// there is no find_if_not in C++98, lets do something crappy to
// workaround.
struct not_isspace {
bool operator()(char c) { return !std::isspace(c); }
};
// and define this one here because C++98 is not happy with local defined
// struct passed to template functions, fuuuu.
struct not_isempty {
bool operator()(const lines_t::value_type &p) {
return !(std::find_if(p.second.begin(), p.second.end(), not_isspace()) ==
p.second.end());
}
};
void swap(SourceFile &b) { _file.swap(b._file); }
#ifdef BACKWARD_ATLEAST_CXX11
SourceFile(SourceFile &&from) : _file(nullptr) { swap(from); }
SourceFile &operator=(SourceFile &&from) {
swap(from);
return *this;
}
#else
explicit SourceFile(const SourceFile &from) {
// some sort of poor man's move semantic.
swap(const_cast<SourceFile &>(from));
}
SourceFile &operator=(const SourceFile &from) {
// some sort of poor man's move semantic.
swap(const_cast<SourceFile &>(from));
return *this;
}
#endif
private:
details::handle<std::ifstream *, details::default_delete<std::ifstream *> >
_file;
std::vector<std::string> get_paths_from_env_variable_impl() {
std::vector<std::string> paths;
const char *prefixes_str = std::getenv("BACKWARD_CXX_SOURCE_PREFIXES");
if (prefixes_str && prefixes_str[0]) {
paths = details::split_source_prefixes(prefixes_str);
}
return paths;
}
const std::vector<std::string> &get_paths_from_env_variable() {
static std::vector<std::string> paths = get_paths_from_env_variable_impl();
return paths;
}
#ifdef BACKWARD_ATLEAST_CXX11
SourceFile(const SourceFile &) = delete;
SourceFile &operator=(const SourceFile &) = delete;
#endif
};
class SnippetFactory {
public:
typedef SourceFile::lines_t lines_t;
lines_t get_snippet(const std::string &filename, unsigned line_start,
unsigned context_size) {
SourceFile &src_file = get_src_file(filename);
unsigned start = line_start - context_size / 2;
return src_file.get_lines(start, context_size);
}
lines_t get_combined_snippet(const std::string &filename_a, unsigned line_a,
const std::string &filename_b, unsigned line_b,
unsigned context_size) {
SourceFile &src_file_a = get_src_file(filename_a);
SourceFile &src_file_b = get_src_file(filename_b);
lines_t lines =
src_file_a.get_lines(line_a - context_size / 4, context_size / 2);
src_file_b.get_lines(line_b - context_size / 4, context_size / 2, lines);
return lines;
}
lines_t get_coalesced_snippet(const std::string &filename, unsigned line_a,
unsigned line_b, unsigned context_size) {
SourceFile &src_file = get_src_file(filename);
using std::max;
using std::min;
unsigned a = min(line_a, line_b);
unsigned b = max(line_a, line_b);
if ((b - a) < (context_size / 3)) {
return src_file.get_lines((a + b - context_size + 1) / 2, context_size);
}
lines_t lines = src_file.get_lines(a - context_size / 4, context_size / 2);
src_file.get_lines(b - context_size / 4, context_size / 2, lines);
return lines;
}
private:
typedef details::hashtable<std::string, SourceFile>::type src_files_t;
src_files_t _src_files;
SourceFile &get_src_file(const std::string &filename) {
src_files_t::iterator it = _src_files.find(filename);
if (it != _src_files.end()) {
return it->second;
}
SourceFile &new_src_file = _src_files[filename];
new_src_file = SourceFile(filename);
return new_src_file;
}
};
/*************** PRINTER ***************/
namespace ColorMode {
enum type { automatic, never, always };
}
class cfile_streambuf : public std::streambuf {
public:
cfile_streambuf(FILE *_sink) : sink(_sink) {}
int_type underflow() override { return traits_type::eof(); }
int_type overflow(int_type ch) override {
if (traits_type::not_eof(ch) && fputc(ch, sink) != EOF) {
return ch;
}
return traits_type::eof();
}
std::streamsize xsputn(const char_type *s, std::streamsize count) override {
return static_cast<std::streamsize>(
fwrite(s, sizeof *s, static_cast<size_t>(count), sink));
}
#ifdef BACKWARD_ATLEAST_CXX11
public:
cfile_streambuf(const cfile_streambuf &) = delete;
cfile_streambuf &operator=(const cfile_streambuf &) = delete;
#else
private:
cfile_streambuf(const cfile_streambuf &);
cfile_streambuf &operator=(const cfile_streambuf &);
#endif
private:
FILE *sink;
std::vector<char> buffer;
};
#ifdef BACKWARD_SYSTEM_LINUX
namespace Color {
enum type { yellow = 33, purple = 35, reset = 39 };
} // namespace Color
class Colorize {
public:
Colorize(std::ostream &os) : _os(os), _reset(false), _enabled(false) {}
void activate(ColorMode::type mode) { _enabled = mode == ColorMode::always; }
void activate(ColorMode::type mode, FILE *fp) { activate(mode, fileno(fp)); }
void set_color(Color::type ccode) {
if (!_enabled)
return;
// I assume that the terminal can handle basic colors. Seriously I
// don't want to deal with all the termcap shit.
_os << "\033[" << static_cast<int>(ccode) << "m";
_reset = (ccode != Color::reset);
}
~Colorize() {
if (_reset) {
set_color(Color::reset);
}
}
private:
void activate(ColorMode::type mode, int fd) {
activate(mode == ColorMode::automatic && isatty(fd) ? ColorMode::always
: mode);
}
std::ostream &_os;
bool _reset;
bool _enabled;
};
#else // ndef BACKWARD_SYSTEM_LINUX
namespace Color {
enum type { yellow = 0, purple = 0, reset = 0 };
} // namespace Color
class Colorize {
public:
Colorize(std::ostream &) {}
void activate(ColorMode::type) {}
void activate(ColorMode::type, FILE *) {}
void set_color(Color::type) {}
};
#endif // BACKWARD_SYSTEM_LINUX
class Printer {
public:
bool snippet;
ColorMode::type color_mode;
bool address;
bool object;
int inliner_context_size;
int trace_context_size;
Printer()
: snippet(true), color_mode(ColorMode::automatic), address(false),
object(false), inliner_context_size(5), trace_context_size(7) {}
template <typename ST> FILE *print(ST &st, FILE *fp = stderr) {
cfile_streambuf obuf(fp);
std::ostream os(&obuf);
Colorize colorize(os);
colorize.activate(color_mode, fp);
print_stacktrace(st, os, colorize);
return fp;
}
template <typename ST> std::ostream &print(ST &st, std::ostream &os) {
Colorize colorize(os);
colorize.activate(color_mode);
print_stacktrace(st, os, colorize);
return os;
}
template <typename IT>
FILE *print(IT begin, IT end, FILE *fp = stderr, size_t thread_id = 0) {
cfile_streambuf obuf(fp);
std::ostream os(&obuf);
Colorize colorize(os);
colorize.activate(color_mode, fp);
print_stacktrace(begin, end, os, thread_id, colorize);
return fp;
}
template <typename IT>
std::ostream &print(IT begin, IT end, std::ostream &os,
size_t thread_id = 0) {
Colorize colorize(os);
colorize.activate(color_mode);
print_stacktrace(begin, end, os, thread_id, colorize);
return os;
}
TraceResolver const &resolver() const { return _resolver; }
private:
TraceResolver _resolver;
SnippetFactory _snippets;
template <typename ST>
void print_stacktrace(ST &st, std::ostream &os, Colorize &colorize) {
print_header(os, st.thread_id());
_resolver.load_stacktrace(st);
for (size_t trace_idx = st.size(); trace_idx > 0; --trace_idx) {
print_trace(os, _resolver.resolve(st[trace_idx - 1]), colorize);
}
}
template <typename IT>
void print_stacktrace(IT begin, IT end, std::ostream &os, size_t thread_id,
Colorize &colorize) {
print_header(os, thread_id);
for (; begin != end; ++begin) {
print_trace(os, *begin, colorize);
}
}
void print_header(std::ostream &os, size_t thread_id) {
os << "Stack trace (most recent call last)";
if (thread_id) {
os << " in thread " << thread_id;
}
os << ":\n";
}
void print_trace(std::ostream &os, const ResolvedTrace &trace,
Colorize &colorize) {
os << "#" << std::left << std::setw(2) << trace.idx << std::right;
bool already_indented = true;
if (!trace.source.filename.size() || object) {
os << " Object \"" << trace.object_filename << "\", at " << trace.addr
<< ", in " << trace.object_function << "\n";
already_indented = false;
}
for (size_t inliner_idx = trace.inliners.size(); inliner_idx > 0;
--inliner_idx) {
if (!already_indented) {
os << " ";
}
const ResolvedTrace::SourceLoc &inliner_loc =
trace.inliners[inliner_idx - 1];
print_source_loc(os, " | ", inliner_loc);
if (snippet) {
print_snippet(os, " | ", inliner_loc, colorize, Color::purple,
inliner_context_size);
}
already_indented = false;
}
if (trace.source.filename.size()) {
if (!already_indented) {
os << " ";
}
print_source_loc(os, " ", trace.source, trace.addr);
if (snippet) {
print_snippet(os, " ", trace.source, colorize, Color::yellow,
trace_context_size);
}
}
}
void print_snippet(std::ostream &os, const char *indent,
const ResolvedTrace::SourceLoc &source_loc,
Colorize &colorize, Color::type color_code,
int context_size) {
using namespace std;
typedef SnippetFactory::lines_t lines_t;
lines_t lines = _snippets.get_snippet(source_loc.filename, source_loc.line,
static_cast<unsigned>(context_size));
for (lines_t::const_iterator it = lines.begin(); it != lines.end(); ++it) {
if (it->first == source_loc.line) {
colorize.set_color(color_code);
os << indent << ">";
} else {
os << indent << " ";
}
os << std::setw(4) << it->first << ": " << it->second << "\n";
if (it->first == source_loc.line) {
colorize.set_color(Color::reset);
}
}
}
void print_source_loc(std::ostream &os, const char *indent,
const ResolvedTrace::SourceLoc &source_loc,
void *addr = nullptr) {
os << indent << "Source \"" << source_loc.filename << "\", line "
<< source_loc.line << ", in " << source_loc.function;
if (address && addr != nullptr) {
os << " [" << addr << "]";
}
os << "\n";
}
};
/*************** SIGNALS HANDLING ***************/
#if defined(BACKWARD_SYSTEM_LINUX) || defined(BACKWARD_SYSTEM_DARWIN)
class SignalHandling {
public:
static std::vector<int> make_default_signals() {
const int posix_signals[] = {
// Signals for which the default action is "Core".
SIGABRT, // Abort signal from abort(3)
SIGBUS, // Bus error (bad memory access)
SIGFPE, // Floating point exception
SIGILL, // Illegal Instruction
SIGIOT, // IOT trap. A synonym for SIGABRT
SIGQUIT, // Quit from keyboard
SIGSEGV, // Invalid memory reference
SIGSYS, // Bad argument to routine (SVr4)
SIGTRAP, // Trace/breakpoint trap
SIGXCPU, // CPU time limit exceeded (4.2BSD)
SIGXFSZ, // File size limit exceeded (4.2BSD)
#if defined(BACKWARD_SYSTEM_DARWIN)
SIGEMT, // emulation instruction executed
#endif
};
return std::vector<int>(posix_signals,
posix_signals +
sizeof posix_signals / sizeof posix_signals[0]);
}
SignalHandling(const std::vector<int> &posix_signals = make_default_signals())
: _loaded(false) {
bool success = true;
const size_t stack_size = 1024 * 1024 * 8;
_stack_content.reset(static_cast<char *>(malloc(stack_size)));
if (_stack_content) {
stack_t ss;
ss.ss_sp = _stack_content.get();
ss.ss_size = stack_size;
ss.ss_flags = 0;
if (sigaltstack(&ss, nullptr) < 0) {
success = false;
}
} else {
success = false;
}
for (size_t i = 0; i < posix_signals.size(); ++i) {
struct sigaction action;
memset(&action, 0, sizeof action);
action.sa_flags =
static_cast<int>(SA_SIGINFO | SA_ONSTACK | SA_NODEFER | SA_RESETHAND);
sigfillset(&action.sa_mask);
sigdelset(&action.sa_mask, posix_signals[i]);
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
#endif
action.sa_sigaction = &sig_handler;
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
int r = sigaction(posix_signals[i], &action, nullptr);
if (r < 0)
success = false;
}
_loaded = success;
}
bool loaded() const { return _loaded; }
static void handleSignal(int, siginfo_t *info, void *_ctx) {
ucontext_t *uctx = static_cast<ucontext_t *>(_ctx);
StackTrace st;
void *error_addr = nullptr;
#ifdef REG_RIP // x86_64
error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.gregs[REG_RIP]);
#elif defined(REG_EIP) // x86_32
error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.gregs[REG_EIP]);
#elif defined(__arm__)
error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.arm_pc);
#elif defined(__aarch64__)
#if defined(__APPLE__)
error_addr = reinterpret_cast<void *>(uctx->uc_mcontext->__ss.__pc);
#else
error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.pc);
#endif
#elif defined(__mips__)
error_addr = reinterpret_cast<void *>(
reinterpret_cast<struct sigcontext *>(&uctx->uc_mcontext)->sc_pc);
#elif defined(__ppc__) || defined(__powerpc) || defined(__powerpc__) || \
defined(__POWERPC__)
error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.regs->nip);
#elif defined(__riscv)
error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.__gregs[REG_PC]);
#elif defined(__s390x__)
error_addr = reinterpret_cast<void *>(uctx->uc_mcontext.psw.addr);
#elif defined(__APPLE__) && defined(__x86_64__)
error_addr = reinterpret_cast<void *>(uctx->uc_mcontext->__ss.__rip);
#elif defined(__APPLE__)
error_addr = reinterpret_cast<void *>(uctx->uc_mcontext->__ss.__eip);
#else
#warning ":/ sorry, ain't know no nothing none not of your architecture!"
#endif
if (error_addr) {
st.load_from(error_addr, 32, reinterpret_cast<void *>(uctx),
info->si_addr);
} else {
st.load_here(32, reinterpret_cast<void *>(uctx), info->si_addr);
}
Printer printer;
printer.address = true;
printer.print(st, stderr);
#if _XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
psiginfo(info, nullptr);
#else
(void)info;
#endif
}
private:
details::handle<char *> _stack_content;
bool _loaded;
#ifdef __GNUC__
__attribute__((noreturn))
#endif
static void
sig_handler(int signo, siginfo_t *info, void *_ctx) {
handleSignal(signo, info, _ctx);
// try to forward the signal.
raise(info->si_signo);
// terminate the process immediately.
puts("watf? exit");
_exit(EXIT_FAILURE);
}
};
#endif // BACKWARD_SYSTEM_LINUX || BACKWARD_SYSTEM_DARWIN
#ifdef BACKWARD_SYSTEM_WINDOWS
class SignalHandling {
public:
SignalHandling(const std::vector<int> & = std::vector<int>())
: reporter_thread_([]() {
/* We handle crashes in a utility thread:
backward structures and some Windows functions called here
need stack space, which we do not have when we encounter a
stack overflow.
To support reporting stack traces during a stack overflow,
we create a utility thread at startup, which waits until a
crash happens or the program exits normally. */
{
std::unique_lock<std::mutex> lk(mtx());
cv().wait(lk, [] { return crashed() != crash_status::running; });
}
if (crashed() == crash_status::crashed) {
handle_stacktrace(skip_recs());
}
{
std::unique_lock<std::mutex> lk(mtx());
crashed() = crash_status::ending;
}
cv().notify_one();
}) {
SetUnhandledExceptionFilter(crash_handler);
signal(SIGABRT, signal_handler);
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
std::set_terminate(&terminator);
#ifndef BACKWARD_ATLEAST_CXX17
std::set_unexpected(&terminator);
#endif
_set_purecall_handler(&terminator);
_set_invalid_parameter_handler(&invalid_parameter_handler);
}
bool loaded() const { return true; }
~SignalHandling() {
{
std::unique_lock<std::mutex> lk(mtx());
crashed() = crash_status::normal_exit;
}
cv().notify_one();
reporter_thread_.join();
}
private:
static CONTEXT *ctx() {
static CONTEXT data;
return &data;
}
enum class crash_status { running, crashed, normal_exit, ending };
static crash_status &crashed() {
static crash_status data;
return data;
}
static std::mutex &mtx() {
static std::mutex data;
return data;
}
static std::condition_variable &cv() {
static std::condition_variable data;
return data;
}
static HANDLE &thread_handle() {
static HANDLE handle;
return handle;
}
std::thread reporter_thread_;
// TODO: how not to hardcode these?
static const constexpr int signal_skip_recs =
#ifdef __clang__
// With clang, RtlCaptureContext also captures the stack frame of the
// current function Below that, there ar 3 internal Windows functions
4
#else
// With MSVC cl, RtlCaptureContext misses the stack frame of the current
// function The first entries during StackWalk are the 3 internal Windows
// functions
3
#endif
;
static int &skip_recs() {
static int data;
return data;
}
static inline void terminator() {
crash_handler(signal_skip_recs);
abort();
}
static inline void signal_handler(int) {
crash_handler(signal_skip_recs);
abort();
}
static inline void __cdecl invalid_parameter_handler(const wchar_t *,
const wchar_t *,
const wchar_t *,
unsigned int,
uintptr_t) {
crash_handler(signal_skip_recs);
abort();
}
NOINLINE static LONG WINAPI crash_handler(EXCEPTION_POINTERS *info) {
// The exception info supplies a trace from exactly where the issue was,
// no need to skip records
crash_handler(0, info->ContextRecord);
return EXCEPTION_CONTINUE_SEARCH;
}
NOINLINE static void crash_handler(int skip, CONTEXT *ct = nullptr) {
if (ct == nullptr) {
RtlCaptureContext(ctx());
} else {
memcpy(ctx(), ct, sizeof(CONTEXT));
}
DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
GetCurrentProcess(), &thread_handle(), 0, FALSE,
DUPLICATE_SAME_ACCESS);
skip_recs() = skip;
{
std::unique_lock<std::mutex> lk(mtx());
crashed() = crash_status::crashed;
}
cv().notify_one();
{
std::unique_lock<std::mutex> lk(mtx());
cv().wait(lk, [] { return crashed() != crash_status::crashed; });
}
}
static void handle_stacktrace(int skip_frames = 0) {
// printer creates the TraceResolver, which can supply us a machine type
// for stack walking. Without this, StackTrace can only guess using some
// macros.
// StackTrace also requires that the PDBs are already loaded, which is done
// in the constructor of TraceResolver
Printer printer;
StackTrace st;
st.set_machine_type(printer.resolver().machine_type());
st.set_thread_handle(thread_handle());
st.load_here(32 + skip_frames, ctx());
st.skip_n_firsts(skip_frames);
printer.address = true;
printer.print(st, std::cerr);
}
};
#endif // BACKWARD_SYSTEM_WINDOWS
#ifdef BACKWARD_SYSTEM_UNKNOWN
class SignalHandling {
public:
SignalHandling(const std::vector<int> & = std::vector<int>()) {}
bool init() { return false; }
bool loaded() { return false; }
};
#endif // BACKWARD_SYSTEM_UNKNOWN
} // namespace backward
#endif /* H_GUARD */
|
CloudI/CloudI
|
src/external/backward-cpp/backward.hpp
|
C++
|
mit
| 141,330
|
<!doctype html>
<html>
<head>
<title>D-Kapstory</title>
<meta charset="utf-8">
<script src="./vendor/three.js/three.min.js"></script>
<script src="./js/dk.js"></script>
<link href="css/main.css" rel="stylesheet" />
</head>
<body>
<div id="container" width="512" height="512"></div>
<script type="text/javascript">
/*global THREE getClass DFK*/
// this factory hold some 3D Objects
var factory = new DFK.Factory();
factory.add("mesh::caps", function()
{
var material = new THREE.MeshLambertMaterial({ color: 0xFC0C20 });
var geometry;
if(!factory.contains("geom::caps"))
{
geometry = new THREE.CylinderGeometry(6, 6.2, 2);
factory.add("geom::caps", geometry);
}
var caps = new THREE.Mesh(factory.create("geom::caps"), material);
caps.castShadow = true;
return caps;
});
factory.add("mesh::bottle", function()
{
var baseradius = 10;
var topradius = 5;
var baseheight = 30;
var topheight = 10;
var ringheight = 2;
var ringradius = 5.5;
var base, top, ring;
var material = new THREE.MeshLambertMaterial({ color: 0xCCFCC0 });
var bottle = new THREE.Object3D();
base = new THREE.Mesh(new THREE.CylinderGeometry(baseradius, baseradius, baseheight, 10, 10), material);
base.position.y = baseheight / 2;
top = new THREE.Mesh(new THREE.CylinderGeometry(topradius, baseradius, topheight, 10, 10), material);
top.position.y = baseheight + topheight / 2;
ring = new THREE.Mesh(new THREE.CylinderGeometry(ringradius, ringradius, ringheight, 10, 10), material);
ring.position.y = baseheight + topheight + ringheight / 2;
base.castShadow = true;
top.castShadow = true;
ring.castShadow = true;
base.receiveShadow = true;
top.receiveShadow = true;
ring.receiveShadow = true;
bottle.add(top);
bottle.add(base);
bottle.add(ring);
return bottle;
});
factory.add("mesh::floor", function(floorRadius){
var geometry = new THREE.CylinderGeometry(floorRadius, floorRadius, 0.1, 20, 8);
var material = new THREE.MeshPhongMaterial({ color: 0x42AF33 });
var mesh = new THREE.Mesh(geometry, material);
mesh.receiveShadow = true;
return mesh;
});
// create a simple gravity particule system with capsCount elements centered on pos
function df_caps_animator(capsCount, pos) {
var d = {};
d.obj = new THREE.Object3D();
d.particules = [];
for (var i = 0; i < capsCount; ++i) {
d.obj.add(factory.create("mesh::caps")());
// create the physics engine for each particule
var part = new DFK.particule(
0.32,
DFK.P,
{
onDie : function (part) {
var min = 5;
if (part.v.y < min) // Full reset
part.reset(DFK.v3(pos.x + DFK.rnd(-1, 1),
pos.y + DFK.rnd(0, 1),
pos.z),
DFK.v3(Math.sin(DFK.rnd(-3.1415, 3.1415)),
4 + DFK.rnd(-1, 1.5),
Math.cos(DFK.rnd(-3.1415, 3.1415))));
else // bounce
{
part.p.y = min;
part.reset(part.p, DFK.v3(2*part.v.x,
0.7*part.v.y,
2*part.v.z));
}
},
shouldDie : function(p, v) { return p.y < 0; }
});
d.particules.push(part);
}
d.animate = function (dt) {
for (var i = 0; i < d.particules.length; ++i) {
// get the new particule position
var new_pos = d.particules[i].next(dt);
var mesh = d.obj.children[i];
//update the mesh position and little hack on the rotation
mesh.position.set(new_pos.x, new_pos.y, new_pos.z);
mesh.rotation.x = new_pos.z / 10;
mesh.rotation.z = new_pos.y / 10;
}
}
return d;
}
// create a light and mak sure the the floor kept in the fustrum
function df_dlight(lightPos, lightTarget, floorRadius) {
var dist = DFK.v3dist(lightPos, lightTarget);
var light = new THREE.DirectionalLight(0x444444);
light.position.set(lightPos.x, lightPos.y, lightPos.z);
light.target.position.set(lightTarget.x, lightTarget.y, lightTarget.z);
light.castShadow = true;
light.shadowDarkness = 0.5;
light.shadowCameraNear = dist - floorRadius;
light.shadowCameraFar = dist + floorRadius;
light.shadowCameraLeft = -floorRadius;
light.shadowCameraRight = floorRadius;
light.shadowCameraTop = floorRadius;
light.shadowCameraBottom = -floorRadius;
return light;
}
var renderer, scene, camera, animator;
init();
animate();
function init() {
var width = 512;
var height = 512;
// on initialise le moteur de rendu
renderer = new THREE.WebGLRenderer();
// si WebGL ne fonctionne pas sur votre navigateur vous pouvez utiliser le moteur de rendu Canvas à la place
//renderer = new THREE.CanvasRenderer();
renderer.setSize(width, height);//window.innerWidth, window.innerHeight);
document.getElementById('container').appendChild(renderer.domElement);
// on initialise la scène
scene = new THREE.Scene();
// setting up the camera
camera = new THREE.PerspectiveCamera(50, width / height, 1, 1000);
camera.position.set(0, 150, 250);
camera.lookAt(new THREE.Vector3(0.0, 50.0, 0.0));
scene.add(camera);
// add a bottle first
scene.add(factory.create("mesh::bottle")());
// then create 500 animated caps on top of the bottle
animator = new df_caps_animator(500, new THREE.Vector3(0, 48, 0));
// and add them to the scene
scene.add(animator.obj);
// Finally add a floor to don't lost the others 3D objects in the space
var floorRadius = 200;
scene.add(factory.create("mesh::floor")(200));
// adding 4 lights around the bottle
var lightPos = DFK.v3(floorRadius + 50, 2*floorRadius, 0.5*floorRadius + 50);
scene.add(df_dlight(lightPos, DFK.v3(0, 30, 0), floorRadius));
lightPos.x *= -1;
scene.add(df_dlight(lightPos, DFK.v3(0, 30, 0), floorRadius));
lightPos.z *= -1;
scene.add(df_dlight(lightPos, DFK.v3(0, 30, 0), floorRadius));
lightPos.x *= -1;
scene.add(df_dlight(lightPos, DFK.v3(0, 30, 0), floorRadius));
// Enabling the shadow
renderer.shadowMapEnabled = true;
renderer.shadowMapSoft = true;
renderer.shadowCameraNear = camera.near;
renderer.shadowCameraFar = camera.far;
renderer.shadowCameraFov = 50;
renderer.shadowMapBias = 0.0039;
renderer.shadowMapDarkness = 0.5;
renderer.shadowMapWidth = 1024;
renderer.shadowMapHeight = 1024;
// on effectue le rendu de la scène
//renderer.render( scene, camera );
}
var gt = 0; // a global timer
function animate() {
requestAnimationFrame(animate);
// updating the caps
animator.animate(0.10510);
gt += 0.01;//0.02510;
camera.position.set((150 + 50*Math.cos(gt/3))*Math.sin(gt), 150 + 100*(1+Math.sin(gt)), (250 + 50*Math.sin(gt/3))*Math.cos(gt));
camera.lookAt(new THREE.Vector3(0.0, 50.0, 0.0));
render();
}
function render() {
renderer.setClearColor(0);
renderer.render(scene, camera);
}
</script>
</body>
</html>
|
twxs/dkapstory.js
|
index.html
|
HTML
|
mit
| 9,609
|
package ru.mail.park.database.kgulyy.controllers;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ru.mail.park.database.kgulyy.domains.Post;
import ru.mail.park.database.kgulyy.domains.Thread;
import ru.mail.park.database.kgulyy.domains.Vote;
import ru.mail.park.database.kgulyy.services.PostService;
import ru.mail.park.database.kgulyy.services.ThreadService;
import java.util.List;
/**
* @author Konstantin Gulyy
*/
@RestController
@RequestMapping("/api/thread/{slugOrId}")
public class ThreadController {
private final ThreadService threadService;
private final PostService postService;
ThreadController(ThreadService threadService, PostService postService) {
this.threadService = threadService;
this.postService = postService;
}
@PostMapping("/create")
ResponseEntity<List<Post>> createPosts(@PathVariable String slugOrId, @RequestBody List<Post> listOfPosts) {
return postService.createPosts(slugOrId, listOfPosts);
}
@GetMapping("/details")
ResponseEntity<Thread> getThreadDetails(@PathVariable String slugOrId) {
return threadService.getThreadDetails(slugOrId);
}
@PostMapping("/vote")
ResponseEntity<Thread> voteThread(@PathVariable String slugOrId, @RequestBody Vote vote) {
return threadService.voteThread(slugOrId, vote);
}
@GetMapping("/posts")
ResponseEntity<List<Post>> getThreadPosts(
@PathVariable String slugOrId,
@RequestParam Long limit,
@RequestParam(required = false) Long since,
@RequestParam(required = false, defaultValue = "false") Boolean desc,
@RequestParam(required = false, defaultValue = "flat") String sort
) {
return postService.getThreadPosts(slugOrId, limit, since, desc, sort);
}
@PostMapping("/details")
ResponseEntity<Thread> updateThread(@PathVariable String slugOrId, @RequestBody Thread updatedThread) {
return threadService.updateThread(slugOrId, updatedThread);
}
}
|
kgulyy/database-forum-api
|
src/main/java/ru/mail/park/database/kgulyy/controllers/ThreadController.java
|
Java
|
mit
| 2,072
|
/**
* Rooms
* Pokemon Showdown - http://pokemonshowdown.com/
*
* Every chat room and battle is a room, and what they do is done in
* rooms.js. There's also a global room which every user is in, and
* handles miscellaneous things like welcoming the user.
*
* @license MIT license
*/
const TIMEOUT_EMPTY_DEALLOCATE = 10 * 60 * 1000;
const TIMEOUT_INACTIVE_DEALLOCATE = 40 * 60 * 1000;
const REPORT_USER_STATS_INTERVAL = 1000 * 60 * 10;
var fs = require('fs');
/* global Rooms: true */
var Rooms = module.exports = getRoom;
var rooms = Rooms.rooms = Object.create(null);
var aliases = Object.create(null);
var Room = (function () {
function Room(roomid, title) {
this.id = roomid;
this.title = (title || roomid);
this.users = Object.create(null);
this.log = [];
this.bannedUsers = Object.create(null);
this.bannedIps = Object.create(null);
}
Room.prototype.title = "";
Room.prototype.type = 'chat';
Room.prototype.lastUpdate = 0;
Room.prototype.log = null;
Room.prototype.users = null;
Room.prototype.userCount = 0;
Room.prototype.send = function (message, errorArgument) {
if (errorArgument) throw new Error("Use Room#sendUser");
if (this.id !== 'lobby') message = '>' + this.id + '\n' + message;
Sockets.channelBroadcast(this.id, message);
};
Room.prototype.sendAuth = function (message) {
for (var i in this.users) {
var user = this.users[i];
if (user.connected && user.can('staff', this)) {
user.sendTo(this, message);
}
}
};
Room.prototype.sendUser = function (user, message) {
user.sendTo(this, message);
};
Room.prototype.add = function (message) {
if (typeof message !== 'string') throw new Error("Deprecated message type");
this.logEntry(message);
if (this.logTimes && message.substr(0, 3) === '|c|') {
message = '|c:|' + (~~(Date.now() / 1000)) + '|' + message.substr(3);
}
this.log.push(message);
};
Room.prototype.logEntry = function () {};
Room.prototype.addRaw = function (message) {
this.add('|raw|' + message);
};
Room.prototype.getLogSlice = function (amount) {
var log = this.log.slice(amount);
log.unshift('|:|' + (~~(Date.now() / 1000)));
return log;
};
Room.prototype.chat = function (user, message, connection) {
// Battle actions are actually just text commands that are handled in
// parseCommand(), which in turn often calls Simulator.prototype.sendFor().
// Sometimes the call to sendFor is done indirectly, by calling
// room.decision(), where room.constructor === BattleRoom.
message = CommandParser.parse(message, this, user, connection);
if (message) {
if (Spamroom.isSpamroomed(user)) {
Spamroom.room.add('|c|' + user.getIdentity() + "|__(To " + this.id + ")__ " + message);
Spamroom.room.update();
connection.sendTo(this, '|c|' + user.getIdentity(this.id) + '|' + message);
} else {
this.add('|c|' + user.getIdentity(this.id) + '|' + message, true);
}
}
this.update();
};
return Room;
})();
var GlobalRoom = (function () {
function GlobalRoom(roomid) {
this.id = roomid;
// init battle rooms
this.battleCount = 0;
this.searchers = [];
// Never do any other file IO synchronously
// but this is okay to prevent race conditions as we start up PS
this.lastBattle = 0;
try {
this.lastBattle = parseInt(fs.readFileSync('logs/lastbattle.txt')) || 0;
} catch (e) {} // file doesn't exist [yet]
this.chatRoomData = [];
try {
this.chatRoomData = JSON.parse(fs.readFileSync('config/chatrooms.json'));
if (!Array.isArray(this.chatRoomData)) this.chatRoomData = [];
} catch (e) {} // file doesn't exist [yet]
if (!this.chatRoomData.length) {
this.chatRoomData = [{
title: 'Lobby',
isOfficial: true,
autojoin: true
}, {
title: 'Staff',
isPrivate: true,
staffRoom: true,
staffAutojoin: true
}];
}
this.chatRooms = [];
this.autojoin = []; // rooms that users autojoin upon connecting
this.staffAutojoin = []; // rooms that staff autojoin upon connecting
for (var i = 0; i < this.chatRoomData.length; i++) {
if (!this.chatRoomData[i] || !this.chatRoomData[i].title) {
console.log('ERROR: Room number ' + i + ' has no data.');
continue;
}
var id = toId(this.chatRoomData[i].title);
console.log("NEW CHATROOM: " + id);
var room = Rooms.createChatRoom(id, this.chatRoomData[i].title, this.chatRoomData[i]);
if (room.aliases) {
for (var a = 0; a < room.aliases.length; a++) {
aliases[room.aliases[a]] = room;
}
}
this.chatRooms.push(room);
if (room.autojoin) this.autojoin.push(id);
if (room.staffAutojoin) this.staffAutojoin.push(id);
}
// this function is complex in order to avoid several race conditions
var self = this;
this.writeNumRooms = (function () {
var writing = false;
var lastBattle; // last lastBattle to be written to file
var finishWriting = function () {
writing = false;
if (lastBattle < self.lastBattle) {
self.writeNumRooms();
}
};
return function () {
if (writing) return;
// batch writing lastbattle.txt for every 10 battles
if (lastBattle >= self.lastBattle) return;
lastBattle = self.lastBattle + 10;
writing = true;
fs.writeFile('logs/lastbattle.txt.0', '' + lastBattle, function () {
// rename is atomic on POSIX, but will throw an error on Windows
fs.rename('logs/lastbattle.txt.0', 'logs/lastbattle.txt', function (err) {
if (err) {
// This should only happen on Windows.
fs.writeFile('logs/lastbattle.txt', '' + lastBattle, finishWriting);
return;
}
finishWriting();
});
});
};
})();
this.writeChatRoomData = (function () {
var writing = false;
var writePending = false; // whether or not a new write is pending
var finishWriting = function () {
writing = false;
if (writePending) {
writePending = false;
self.writeChatRoomData();
}
};
return function () {
if (writing) {
writePending = true;
return;
}
writing = true;
var data = JSON.stringify(self.chatRoomData).replace(/\{"title"\:/g, '\n{"title":').replace(/\]$/, '\n]');
fs.writeFile('config/chatrooms.json.0', data, function () {
// rename is atomic on POSIX, but will throw an error on Windows
fs.rename('config/chatrooms.json.0', 'config/chatrooms.json', function (err) {
if (err) {
// This should only happen on Windows.
fs.writeFile('config/chatrooms.json', data, finishWriting);
return;
}
finishWriting();
});
});
};
})();
// init users
this.users = {};
this.userCount = 0; // cache of `Object.size(this.users)`
this.maxUsers = 0;
this.maxUsersDate = 0;
this.reportUserStatsInterval = setInterval(
this.reportUserStats.bind(this),
REPORT_USER_STATS_INTERVAL
);
}
GlobalRoom.prototype.type = 'global';
GlobalRoom.prototype.formatListText = '|formats';
GlobalRoom.prototype.reportUserStats = function () {
if (this.maxUsersDate) {
LoginServer.request('updateuserstats', {
date: this.maxUsersDate,
users: this.maxUsers
}, function () {});
this.maxUsersDate = 0;
}
LoginServer.request('updateuserstats', {
date: Date.now(),
users: this.userCount
}, function () {});
};
GlobalRoom.prototype.getFormatListText = function () {
var formatListText = '|formats';
var curSection = '';
for (var i in Tools.data.Formats) {
var format = Tools.data.Formats[i];
if (!format.challengeShow && !format.searchShow) continue;
var section = format.section;
if (section === undefined) section = format.mod;
if (!section) section = '';
if (section !== curSection) {
curSection = section;
formatListText += '|,' + (format.column || 1) + '|' + section;
}
formatListText += '|' + format.name;
if (!format.challengeShow) formatListText += ',,';
else if (!format.searchShow) formatListText += ',';
if (format.team) formatListText += ',#';
}
return formatListText;
};
GlobalRoom.prototype.getRoomList = function (filter) {
var roomList = {};
var total = 0;
var skipCount = 0;
if (this.battleCount > 150) {
skipCount = this.battleCount - 150;
}
for (var i in Rooms.rooms) {
var room = Rooms.rooms[i];
if (!room || !room.active || room.isPrivate) continue;
if (filter && filter !== room.format && filter !== true) continue;
if (skipCount && skipCount--) continue;
var roomData = {};
if (room.active && room.battle) {
if (room.battle.players[0]) roomData.p1 = room.battle.players[0].getIdentity();
if (room.battle.players[1]) roomData.p2 = room.battle.players[1].getIdentity();
}
if (!roomData.p1 || !roomData.p2) continue;
roomList[room.id] = roomData;
total++;
if (total >= 100) break;
}
return roomList;
};
GlobalRoom.prototype.getRooms = function () {
var roomsData = {official:[], chat:[], userCount: this.userCount, battleCount: this.battleCount};
for (var i = 0; i < this.chatRooms.length; i++) {
var room = this.chatRooms[i];
if (!room) continue;
if (room.isPrivate) continue;
(room.isOfficial ? roomsData.official : roomsData.chat).push({
title: room.title,
desc: room.desc,
userCount: room.userCount
});
}
return roomsData;
};
GlobalRoom.prototype.cancelSearch = function (user) {
var success = false;
user.cancelChallengeTo();
for (var i = 0; i < this.searchers.length; i++) {
var search = this.searchers[i];
var searchUser = Users.get(search.userid);
if (!searchUser.connected) {
this.searchers.splice(i, 1);
i--;
continue;
}
if (searchUser === user) {
this.searchers.splice(i, 1);
i--;
if (!success) {
searchUser.send('|updatesearch|' + JSON.stringify({searching: false}));
success = true;
}
continue;
}
}
return success;
};
GlobalRoom.prototype.searchBattle = function (user, formatid) {
if (!user.connected) return;
formatid = toId(formatid);
user.prepBattle(formatid, 'search', null, this.finishSearchBattle.bind(this, user, formatid));
};
GlobalRoom.prototype.finishSearchBattle = function (user, formatid, result) {
if (!result) return;
// tell the user they've started searching
var newSearchData = {
format: formatid
};
user.send('|updatesearch|' + JSON.stringify({searching: newSearchData}));
// get the user's rating before actually starting to search
var newSearch = {
userid: user.userid,
formatid: formatid,
team: user.team,
rating: 1000,
time: new Date().getTime()
};
var self = this;
user.doWithMMR(formatid, function (mmr, error) {
if (error) {
user.popup("Connection to ladder server failed with error: " + error + "; please try again later");
return;
}
newSearch.rating = mmr;
self.addSearch(newSearch, user);
});
};
GlobalRoom.prototype.matchmakingOK = function (search1, search2, user1, user2) {
// users must be different
if (user1 === user2) return false;
// users must have different IPs
if (user1.latestIp === user2.latestIp) return false;
// users must not have been matched immediately previously
if (user1.lastMatch === user2.userid || user2.lastMatch === user1.userid) return false;
// search must be within range
var searchRange = 100, formatid = search1.formatid, elapsed = Math.abs(search1.time - search2.time);
if (formatid === 'ou' || formatid === 'oucurrent' || formatid === 'randombattle') searchRange = 50;
searchRange += elapsed / 300; // +1 every .3 seconds
if (searchRange > 300) searchRange = 300;
if (Math.abs(search1.rating - search2.rating) > searchRange) return false;
user1.lastMatch = user2.userid;
user2.lastMatch = user1.userid;
return true;
};
GlobalRoom.prototype.addSearch = function (newSearch, user) {
if (!user.connected) return;
for (var i = 0; i < this.searchers.length; i++) {
var search = this.searchers[i];
var searchUser = Users.get(search.userid);
if (!searchUser || !searchUser.connected) {
this.searchers.splice(i, 1);
i--;
continue;
}
if (newSearch.formatid === search.formatid && searchUser === user) return; // only one search per format
if (newSearch.formatid === search.formatid && this.matchmakingOK(search, newSearch, searchUser, user)) {
this.cancelSearch(user, true);
this.cancelSearch(searchUser, true);
user.send('|updatesearch|' + JSON.stringify({searching: false}));
this.startBattle(searchUser, user, search.formatid, search.team, newSearch.team, {rated: true});
return;
}
}
this.searchers.push(newSearch);
};
GlobalRoom.prototype.send = function (message, user) {
if (user) {
user.sendTo(this, message);
} else {
Sockets.channelBroadcast(this.id, message);
}
};
GlobalRoom.prototype.sendAuth = function (message) {
for (var i in this.users) {
var user = this.users[i];
if (user.connected && user.can('staff')) {
user.sendTo(this, message);
}
}
};
GlobalRoom.prototype.add = function (message) {
if (rooms.lobby) rooms.lobby.add(message);
};
GlobalRoom.prototype.addRaw = function (message) {
if (rooms.lobby) rooms.lobby.addRaw(message);
};
GlobalRoom.prototype.addChatRoom = function (title) {
var id = toId(title);
if (rooms[id]) return false;
var chatRoomData = {
title: title
};
var room = Rooms.createChatRoom(id, title, chatRoomData);
this.chatRoomData.push(chatRoomData);
this.chatRooms.push(room);
this.writeChatRoomData();
return true;
};
GlobalRoom.prototype.deregisterChatRoom = function (id) {
id = toId(id);
var room = rooms[id];
if (!room) return false; // room doesn't exist
if (!room.chatRoomData) return false; // room isn't registered
// deregister from global chatRoomData
// looping from the end is a pretty trivial optimization, but the
// assumption is that more recently added rooms are more likely to
// be deleted
for (var i = this.chatRoomData.length - 1; i >= 0; i--) {
if (id === toId(this.chatRoomData[i].title)) {
this.chatRoomData.splice(i, 1);
this.writeChatRoomData();
break;
}
}
delete room.chatRoomData;
return true;
};
GlobalRoom.prototype.delistChatRoom = function (id) {
id = toId(id);
if (!rooms[id]) return false; // room doesn't exist
for (var i = this.chatRooms.length - 1; i >= 0; i--) {
if (id === this.chatRooms[i].id) {
this.chatRooms.splice(i, 1);
break;
}
}
};
GlobalRoom.prototype.removeChatRoom = function (id) {
id = toId(id);
var room = rooms[id];
if (!room) return false; // room doesn't exist
room.destroy();
return true;
};
GlobalRoom.prototype.autojoinRooms = function (user, connection) {
// we only autojoin regular rooms if the client requests it with /autojoin
// note that this restriction doesn't apply to staffAutojoin
for (var i = 0; i < this.autojoin.length; i++) {
user.joinRoom(this.autojoin[i], connection);
}
};
GlobalRoom.prototype.checkAutojoin = function (user, connection) {
for (var i = 0; i < this.staffAutojoin.length; i++) {
var room = Rooms.get(this.staffAutojoin[i]);
if (!room) {
this.staffAutojoin.splice(i, 1);
i--;
continue;
}
if (room.staffAutojoin === true && user.can('staff') ||
typeof room.staffAutojoin === 'string' && room.staffAutojoin.indexOf(user.group) >= 0) {
// if staffAutojoin is true: autojoin if isStaff
// if staffAutojoin is String: autojoin if user.group in staffAutojoin
user.joinRoom(room.id, connection);
}
}
};
GlobalRoom.prototype.onJoinConnection = function (user, connection) {
var initdata = '|updateuser|' + user.name + '|' + (user.named ? '1' : '0') + '|' + user.avatar + '\n';
connection.send(initdata + this.formatListText);
if (this.chatRooms.length > 2) connection.send('|queryresponse|rooms|null'); // should display room list
};
GlobalRoom.prototype.onJoin = function (user, connection, merging) {
if (!user) return false; // ???
if (this.users[user.userid]) return user;
this.users[user.userid] = user;
if (++this.userCount > this.maxUsers) {
this.maxUsers = this.userCount;
this.maxUsersDate = Date.now();
}
if (!merging) {
var initdata = '|updateuser|' + user.name + '|' + (user.named ? '1' : '0') + '|' + user.avatar + '\n';
connection.send(initdata + this.formatListText);
if (this.chatRooms.length > 2) connection.send('|queryresponse|rooms|null'); // should display room list
}
return user;
};
GlobalRoom.prototype.onRename = function (user, oldid, joining) {
delete this.users[oldid];
this.users[user.userid] = user;
return user;
};
GlobalRoom.prototype.onUpdateIdentity = function () {};
GlobalRoom.prototype.onLeave = function (user) {
if (!user) return; // ...
delete this.users[user.userid];
--this.userCount;
this.cancelSearch(user, true);
};
GlobalRoom.prototype.startBattle = function (p1, p2, format, p1team, p2team, options) {
var newRoom;
p1 = Users.get(p1);
p2 = Users.get(p2);
if (!p1 || !p2) {
// most likely, a user was banned during the battle start procedure
this.cancelSearch(p1, true);
this.cancelSearch(p2, true);
return;
}
if (p1 === p2) {
this.cancelSearch(p1, true);
this.cancelSearch(p2, true);
p1.popup("You can't battle your own account. Please use something like Private Browsing to battle yourself.");
return;
}
if (this.lockdown === true) {
this.cancelSearch(p1, true);
this.cancelSearch(p2, true);
p1.popup("The server is shutting down. Battles cannot be started at this time.");
p2.popup("The server is shutting down. Battles cannot be started at this time.");
return;
}
//console.log('BATTLE START BETWEEN: ' + p1.userid + ' ' + p2.userid);
var i = this.lastBattle + 1;
var formaturlid = format.toLowerCase().replace(/[^a-z0-9]+/g, '');
while (rooms['battle-' + formaturlid + i]) {
i++;
}
this.lastBattle = i;
rooms.global.writeNumRooms();
newRoom = this.addRoom('battle-' + formaturlid + '-' + i, format, p1, p2, options);
p1.joinRoom(newRoom);
p2.joinRoom(newRoom);
newRoom.joinBattle(p1, p1team);
newRoom.joinBattle(p2, p2team);
this.cancelSearch(p1, true);
this.cancelSearch(p2, true);
if (Config.reportBattles && rooms.lobby) {
rooms.lobby.add('|b|' + newRoom.id + '|' + p1.getIdentity() + '|' + p2.getIdentity());
}
if (Config.logladderip && options.rated) {
if (!this.ladderIpLog) {
this.ladderIpLog = fs.createWriteStream('logs/ladderip/ladderip.txt', {flags: 'a'});
}
this.ladderIpLog.write(p1.userid + ': ' + p1.latestIp + '\n');
this.ladderIpLog.write(p2.userid + ': ' + p2.latestIp + '\n');
}
return newRoom;
};
GlobalRoom.prototype.addRoom = function (room, format, p1, p2, options) {
room = Rooms.createBattle(room, format, p1, p2, options);
return room;
};
GlobalRoom.prototype.chat = function (user, message, connection) {
if (rooms.lobby) return rooms.lobby.chat(user, message, connection);
message = CommandParser.parse(message, this, user, connection);
if (message) {
connection.sendPopup("You can't send messages directly to the server.");
}
};
return GlobalRoom;
})();
var BattleRoom = (function () {
function BattleRoom(roomid, format, p1, p2, options) {
Room.call(this, roomid, "" + p1.name + " vs. " + p2.name);
this.modchat = (Config.modchat.battle || false);
format = '' + (format || '');
this.format = format;
this.auth = {};
//console.log("NEW BATTLE");
var formatid = toId(format);
// Sometimes we might allow BattleRooms to have no options
if (!options) {
options = {};
}
var rated;
if (options.rated && Tools.getFormat(formatid).rated !== false) {
rated = {
p1: p1.userid,
p2: p2.userid,
format: format
};
} else {
rated = false;
}
if (options.tour) {
this.tour = {
p1: p1.userid,
p2: p2.userid,
format: format,
tour: options.tour
};
} else {
this.tour = false;
}
this.rated = rated;
this.battle = Simulator.create(this.id, format, rated, this);
this.p1 = p1 || '';
this.p2 = p2 || '';
this.sideTicksLeft = [21, 21];
if (!rated) this.sideTicksLeft = [28, 28];
this.sideTurnTicks = [0, 0];
this.disconnectTickDiff = [0, 0];
if (Config.forceTimer) this.requestKickInactive(false);
}
BattleRoom.prototype = Object.create(Room.prototype);
BattleRoom.prototype.type = 'battle';
BattleRoom.prototype.resetTimer = null;
BattleRoom.prototype.resetUser = '';
BattleRoom.prototype.expireTimer = null;
BattleRoom.prototype.active = false;
BattleRoom.prototype.push = function (message) {
if (typeof message === 'string') {
this.log.push(message);
} else {
this.log = this.log.concat(message);
}
};
BattleRoom.prototype.win = function (winner) {
// Declare variables here in case we need them for non-rated battles logging.
var p1score = 0.5;
var winnerid = toId(winner);
// Check if the battle was rated to update the ladder, return its response, and log the battle.
if (this.rated) {
var rated = this.rated;
this.rated = false;
if (winnerid === rated.p1) {
p1score = 1;
} else if (winnerid === rated.p2) {
p1score = 0;
}
var p1 = rated.p1;
if (Users.getExact(rated.p1)) p1 = Users.getExact(rated.p1).name;
var p2 = rated.p2;
if (Users.getExact(rated.p2)) p2 = Users.getExact(rated.p2).name;
//update.updates.push('[DEBUG] uri: ' + Config.loginServer.uri + 'action.php?act=ladderupdate&serverid=' + Config.serverId + '&p1=' + encodeURIComponent(p1) + '&p2=' + encodeURIComponent(p2) + '&score=' + p1score + '&format=' + toId(rated.format) + '&servertoken=[token]');
if (!rated.p1 || !rated.p2) {
this.push('|raw|ERROR: Ladder not updated: a player does not exist');
} else {
winner = Users.get(winnerid);
if (winner && !winner.authenticated) {
this.sendUser(winner, '|askreg|' + winner.userid);
}
var p1rating, p2rating;
// update rankings
this.push('|raw|Ladder updating...');
var self = this;
LoginServer.request('ladderupdate', {
p1: p1,
p2: p2,
score: p1score,
format: toId(rated.format)
}, function (data, statusCode, error) {
if (!self.battle) {
console.log('room expired before ladder update was received');
return;
}
if (!data) {
self.addRaw('Ladder (probably) updated, but score could not be retrieved (' + error + ').');
// log the battle anyway
if (!Tools.getFormat(self.format).noLog) {
self.logBattle(p1score);
}
return;
} else if (data.errorip) {
self.addRaw("This server's request IP " + data.errorip + " is not a registered server.");
return;
} else {
try {
p1rating = data.p1rating;
p2rating = data.p2rating;
//self.add("Ladder updated.");
var oldacre = Math.round(data.p1rating.oldacre);
var acre = Math.round(data.p1rating.acre);
var reasons = '' + (acre - oldacre) + ' for ' + (p1score > 0.99 ? 'winning' : (p1score < 0.01 ? 'losing' : 'tying'));
if (reasons.substr(0, 1) !== '-') reasons = '+' + reasons;
self.addRaw(Tools.escapeHTML(p1) + '\'s rating: ' + oldacre + ' → <strong>' + acre + '</strong><br />(' + reasons + ')');
oldacre = Math.round(data.p2rating.oldacre);
acre = Math.round(data.p2rating.acre);
reasons = '' + (acre - oldacre) + ' for ' + (p1score > 0.99 ? 'losing' : (p1score < 0.01 ? 'winning' : 'tying'));
if (reasons.substr(0, 1) !== '-') reasons = '+' + reasons;
self.addRaw(Tools.escapeHTML(p2) + '\'s rating: ' + oldacre + ' → <strong>' + acre + '</strong><br />(' + reasons + ')');
Users.get(p1).cacheMMR(rated.format, data.p1rating);
Users.get(p2).cacheMMR(rated.format, data.p2rating);
self.update();
} catch (e) {
self.addRaw('There was an error calculating rating changes.');
self.update();
}
if (!Tools.getFormat(self.format).noLog) {
self.logBattle(p1score, p1rating, p2rating);
}
}
});
}
} else if (Config.logChallenges) {
// Log challenges if the challenge logging config is enabled.
if (winnerid === this.p1.userid) {
p1score = 1;
} else if (winnerid === this.p2.userid) {
p1score = 0;
}
this.update();
this.logBattle(p1score);
}
if (this.tour) {
var winnerid = toId(winner);
winner = Users.get(winner);
var tour = this.tour.tour;
tour.onBattleWin(this, winner);
}
rooms.global.battleCount += 0 - (this.active ? 1 : 0);
this.active = false;
this.update();
};
// logNum = 0 : spectator log
// logNum = 1, 2 : player log
// logNum = 3 : replay log
BattleRoom.prototype.getLog = function (logNum) {
var log = [];
for (var i = 0; i < this.log.length; ++i) {
var line = this.log[i];
if (line === '|split') {
log.push(this.log[i + logNum + 1]);
i += 4;
} else {
log.push(line);
}
}
return log;
};
BattleRoom.prototype.getLogForUser = function (user) {
var logNum = this.battle.getSlot(user) + 1;
if (logNum < 0) logNum = 0;
return this.getLog(logNum);
};
BattleRoom.prototype.update = function (excludeUser) {
if (this.log.length <= this.lastUpdate) return;
Sockets.subchannelBroadcast(this.id, '>' + this.id + '\n\n' + this.log.slice(this.lastUpdate).join('\n'));
this.lastUpdate = this.log.length;
// empty rooms time out after ten minutes
var hasUsers = false;
for (var i in this.users) {
hasUsers = true;
break;
}
if (!hasUsers) {
if (this.expireTimer) clearTimeout(this.expireTimer);
this.expireTimer = setTimeout(this.tryExpire.bind(this), TIMEOUT_EMPTY_DEALLOCATE);
} else {
if (this.expireTimer) clearTimeout(this.expireTimer);
this.expireTimer = setTimeout(this.tryExpire.bind(this), TIMEOUT_INACTIVE_DEALLOCATE);
}
};
BattleRoom.prototype.logBattle = function (p1score, p1rating, p2rating) {
var logData = this.battle.logData;
logData.p1rating = p1rating;
logData.p2rating = p2rating;
logData.endType = this.battle.endType;
if (!p1rating) logData.ladderError = true;
logData.log = BattleRoom.prototype.getLog.call(logData, 3); // replay log (exact damage)
var date = new Date();
var logfolder = date.format('{yyyy}-{MM}');
var logsubfolder = date.format('{yyyy}-{MM}-{dd}');
var curpath = 'logs/' + logfolder;
var self = this;
fs.mkdir(curpath, '0755', function () {
var tier = self.format.toLowerCase().replace(/[^a-z0-9]+/g, '');
curpath += '/' + tier;
fs.mkdir(curpath, '0755', function () {
curpath += '/' + logsubfolder;
fs.mkdir(curpath, '0755', function () {
fs.writeFile(curpath + '/' + self.id + '.log.json', JSON.stringify(logData));
});
});
}); // asychronicity
//console.log(JSON.stringify(logData));
};
BattleRoom.prototype.tryExpire = function () {
this.expire();
};
BattleRoom.prototype.getInactiveSide = function () {
if (this.battle.players[0] && !this.battle.players[1]) return 1;
if (this.battle.players[1] && !this.battle.players[0]) return 0;
return this.battle.inactiveSide;
};
BattleRoom.prototype.forfeit = function (user, message, side) {
if (!this.battle || this.battle.ended || !this.battle.started) return false;
if (!message) message = ' forfeited.';
if (side === undefined) {
if (user && user.userid === this.battle.playerids[0]) side = 0;
if (user && user.userid === this.battle.playerids[1]) side = 1;
}
if (side === undefined) return false;
var ids = ['p1', 'p2'];
var otherids = ['p2', 'p1'];
var name = 'Player ' + (side + 1);
if (user) {
name = user.name;
} else if (this.rated) {
name = this.rated[ids[side]];
}
this.add('|-message|' + name + message);
this.battle.endType = 'forfeit';
this.battle.send('win', otherids[side]);
rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0);
this.active = this.battle.active;
this.update();
return true;
};
BattleRoom.prototype.sendPlayer = function (num, message) {
var player = this.battle.getPlayer(num);
if (!player) return false;
this.sendUser(player, message);
};
BattleRoom.prototype.kickInactive = function () {
clearTimeout(this.resetTimer);
this.resetTimer = null;
if (!this.battle || this.battle.ended || !this.battle.started) return false;
var inactiveSide = this.getInactiveSide();
var ticksLeft = [0, 0];
if (inactiveSide !== 1) {
// side 0 is inactive
this.sideTurnTicks[0]--;
this.sideTicksLeft[0]--;
}
if (inactiveSide !== 0) {
// side 1 is inactive
this.sideTurnTicks[1]--;
this.sideTicksLeft[1]--;
}
ticksLeft[0] = Math.min(this.sideTurnTicks[0], this.sideTicksLeft[0]);
ticksLeft[1] = Math.min(this.sideTurnTicks[1], this.sideTicksLeft[1]);
if (ticksLeft[0] && ticksLeft[1]) {
if (inactiveSide === 0 || inactiveSide === 1) {
// one side is inactive
var inactiveTicksLeft = ticksLeft[inactiveSide];
var inactiveUser = this.battle.getPlayer(inactiveSide);
if (inactiveTicksLeft % 3 === 0 || inactiveTicksLeft <= 4) {
this.send('|inactive|' + (inactiveUser ? inactiveUser.name : 'Player ' + (inactiveSide + 1)) + ' has ' + (inactiveTicksLeft * 10) + ' seconds left.');
}
} else {
// both sides are inactive
var inactiveUser0 = this.battle.getPlayer(0);
if (inactiveUser0 && (ticksLeft[0] % 3 === 0 || ticksLeft[0] <= 4)) {
this.sendUser(inactiveUser0, '|inactive|' + inactiveUser0.name + ' has ' + (ticksLeft[0] * 10) + ' seconds left.');
}
var inactiveUser1 = this.battle.getPlayer(1);
if (inactiveUser1 && (ticksLeft[1] % 3 === 0 || ticksLeft[1] <= 4)) {
this.sendUser(inactiveUser1, '|inactive|' + inactiveUser1.name + ' has ' + (ticksLeft[1] * 10) + ' seconds left.');
}
}
this.resetTimer = setTimeout(this.kickInactive.bind(this), 10 * 1000);
return;
}
if (inactiveSide < 0) {
if (ticksLeft[0]) inactiveSide = 1;
else if (ticksLeft[1]) inactiveSide = 0;
}
this.forfeit(this.battle.getPlayer(inactiveSide), ' lost due to inactivity.', inactiveSide);
this.resetUser = '';
};
BattleRoom.prototype.requestKickInactive = function (user, force) {
if (this.resetTimer) {
if (user) this.sendUser(user, '|inactive|The inactivity timer is already counting down.');
return false;
}
if (user) {
if (!force && this.battle.getSlot(user) < 0) return false;
this.resetUser = user.userid;
this.send('|inactive|Battle timer is now ON: inactive players will automatically lose when time\'s up. (requested by ' + user.name + ')');
} else if (user === false) {
this.resetUser = '~';
this.add('|inactive|Battle timer is ON: inactive players will automatically lose when time\'s up.');
}
// a tick is 10 seconds
var maxTicksLeft = 15; // 2 minutes 30 seconds
if (!this.battle.p1 || !this.battle.p2) {
// if a player has left, don't wait longer than 6 ticks (1 minute)
maxTicksLeft = 6;
}
if (!this.rated) maxTicksLeft = 30;
this.sideTurnTicks = [maxTicksLeft, maxTicksLeft];
var inactiveSide = this.getInactiveSide();
if (inactiveSide < 0) {
// add 10 seconds to bank if they're below 160 seconds
if (this.sideTicksLeft[0] < 16) this.sideTicksLeft[0]++;
if (this.sideTicksLeft[1] < 16) this.sideTicksLeft[1]++;
}
this.sideTicksLeft[0]++;
this.sideTicksLeft[1]++;
if (inactiveSide !== 1) {
// side 0 is inactive
var ticksLeft0 = Math.min(this.sideTicksLeft[0] + 1, maxTicksLeft);
this.sendPlayer(0, '|inactive|You have ' + (ticksLeft0 * 10) + ' seconds to make your decision.');
}
if (inactiveSide !== 0) {
// side 1 is inactive
var ticksLeft1 = Math.min(this.sideTicksLeft[1] + 1, maxTicksLeft);
this.sendPlayer(1, '|inactive|You have ' + (ticksLeft1 * 10) + ' seconds to make your decision.');
}
this.resetTimer = setTimeout(this.kickInactive.bind(this), 10 * 1000);
return true;
};
BattleRoom.prototype.nextInactive = function () {
if (this.resetTimer) {
this.update();
clearTimeout(this.resetTimer);
this.resetTimer = null;
this.requestKickInactive();
}
};
BattleRoom.prototype.stopKickInactive = function (user, force) {
if (!force && user && user.userid !== this.resetUser) return false;
if (this.resetTimer) {
clearTimeout(this.resetTimer);
this.resetTimer = null;
this.send('|inactiveoff|Battle timer is now OFF.');
return true;
}
return false;
};
BattleRoom.prototype.kickInactiveUpdate = function () {
if (!this.rated) return false;
if (this.resetTimer) {
var inactiveSide = this.getInactiveSide();
var changed = false;
if ((!this.battle.p1 || !this.battle.p2) && !this.disconnectTickDiff[0] && !this.disconnectTickDiff[1]) {
if ((!this.battle.p1 && inactiveSide === 0) || (!this.battle.p2 && inactiveSide === 1)) {
var inactiveUser = this.battle.getPlayer(inactiveSide);
if (!this.battle.p1 && inactiveSide === 0 && this.sideTurnTicks[0] > 7) {
this.disconnectTickDiff[0] = this.sideTurnTicks[0] - 7;
this.sideTurnTicks[0] = 7;
changed = true;
} else if (!this.battle.p2 && inactiveSide === 1 && this.sideTurnTicks[1] > 7) {
this.disconnectTickDiff[1] = this.sideTurnTicks[1] - 7;
this.sideTurnTicks[1] = 7;
changed = true;
}
if (changed) {
this.send('|inactive|' + (inactiveUser ? inactiveUser.name : 'Player ' + (inactiveSide + 1)) + ' disconnected and has a minute to reconnect!');
return true;
}
}
} else if (this.battle.p1 && this.battle.p2) {
// Only one of the following conditions should happen, but do
// them both since you never know...
if (this.disconnectTickDiff[0]) {
this.sideTurnTicks[0] = this.sideTurnTicks[0] + this.disconnectTickDiff[0];
this.disconnectTickDiff[0] = 0;
changed = 0;
}
if (this.disconnectTickDiff[1]) {
this.sideTurnTicks[1] = this.sideTurnTicks[1] + this.disconnectTickDiff[1];
this.disconnectTickDiff[1] = 0;
changed = 1;
}
if (changed !== false) {
var user = this.battle.getPlayer(changed);
this.send('|inactive|' + (user ? user.name : 'Player ' + (changed + 1)) + ' reconnected and has ' + (this.sideTurnTicks[changed] * 10) + ' seconds left!');
return true;
}
}
}
return false;
};
BattleRoom.prototype.decision = function (user, choice, data) {
this.battle.sendFor(user, choice, data);
if (this.active !== this.battle.active) {
rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0);
this.active = this.battle.active;
}
this.update();
};
// This function is only called when the user is already in the room (with another connection).
// First-time join calls this.onJoin() below instead.
BattleRoom.prototype.onJoinConnection = function (user, connection) {
this.sendUser(connection, '|init|battle\n|title|' + this.title + '\n' + this.getLogForUser(user).join('\n'));
// this handles joining a battle in which a user is a participant,
// where the user has already identified before attempting to join
// the battle
this.battle.resendRequest(connection);
};
BattleRoom.prototype.onJoin = function (user, connection) {
if (!user) return false;
if (this.users[user.userid]) return user;
this.users[user.userid] = user;
this.userCount++;
this.sendUser(connection, '|init|battle\n|title|' + this.title + '\n' + this.getLogForUser(user).join('\n'));
if (user.named) {
if (Config.reportBattleJoins) {
this.add('|join|' + user.name);
} else {
this.add('|J|' + user.name);
}
this.update();
}
return user;
};
BattleRoom.prototype.onRename = function (user, oldid, joining) {
if (joining) {
if (Config.reportBattleJoins) {
this.add('|join|' + user.name);
} else {
this.add('|J|' + user.name);
}
}
var resend = joining || !this.battle.playerTable[oldid];
if (this.battle.playerTable[oldid]) {
if (this.rated) {
this.add('|message|' + user.name + ' forfeited by changing their name.');
this.battle.lose(oldid);
this.battle.leave(oldid);
resend = false;
} else {
this.battle.rename();
}
}
delete this.users[oldid];
this.users[user.userid] = user;
this.update();
if (resend) {
// this handles a named user renaming themselves into a user in the
// battle (i.e. by using /nick)
this.battle.resendRequest(user);
}
return user;
};
BattleRoom.prototype.onUpdateIdentity = function () {};
BattleRoom.prototype.onLeave = function (user) {
if (!user) return; // ...
if (user.battles[this.id]) {
this.battle.leave(user);
rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0);
this.active = this.battle.active;
} else if (!user.named) {
delete this.users[user.userid];
return;
}
delete this.users[user.userid];
this.userCount--;
if (Config.reportBattleJoins) {
this.add('|leave|' + user.name);
} else {
this.add('|L|' + user.name);
}
if (Object.isEmpty(this.users)) {
rooms.global.battleCount += 0 - (this.active ? 1 : 0);
this.active = false;
}
this.update();
this.kickInactiveUpdate();
};
BattleRoom.prototype.joinBattle = function (user, team) {
var slot;
if (this.rated) {
if (this.rated.p1 === user.userid) {
slot = 0;
} else if (this.rated.p2 === user.userid) {
slot = 1;
} else {
user.popup("This is a rated battle; your username must be " + this.rated.p1 + " or " + this.rated.p2 + " to join.");
return false;
}
}
if (this.tour) {
if (this.tour.p1 === user.userid) {
slot = 0;
} else if (this.tour.p2 === user.userid) {
slot = 1;
} else {
user.popup("This is a tournament battle; your username must be " + this.tour.p1 + " or " + this.tour.p2 + " to join.");
return false;
}
}
if (this.battle.active) {
user.popup("This battle already has two players.");
return false;
}
this.auth[user.userid] = Users.getGroupsThatCan('roompromote', Users.getGroupsThatCan('joinbattle', this)[0], this)[0];
this.battle.join(user, slot, team);
rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0);
this.active = this.battle.active;
if (this.active) {
this.title = "" + this.battle.p1 + " vs. " + this.battle.p2;
this.send('|title|' + this.title);
}
this.update();
this.kickInactiveUpdate();
};
BattleRoom.prototype.leaveBattle = function (user) {
if (!user) return false; // ...
if (user.battles[this.id]) {
this.battle.leave(user);
} else {
return false;
}
this.auth[user.userid] = Users.getGroupsThatCan('joinbattle', this)[0];
rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0);
this.active = this.battle.active;
this.update();
this.kickInactiveUpdate();
return true;
};
BattleRoom.prototype.expire = function () {
this.send('|expire|');
this.destroy();
};
BattleRoom.prototype.destroy = function () {
// deallocate ourself
// remove references to ourself
for (var i in this.users) {
this.users[i].leaveRoom(this);
delete this.users[i];
}
this.users = null;
// deallocate children and get rid of references to them
if (this.battle) {
this.battle.destroy();
}
this.battle = null;
if (this.resetTimer) {
clearTimeout(this.resetTimer);
}
this.resetTimer = null;
if (this.expireTimer) {
clearTimeout(this.expireTimer);
}
this.expireTimer = null;
// get rid of some possibly-circular references
delete rooms[this.id];
};
return BattleRoom;
})();
var ChatRoom = (function () {
function ChatRoom(roomid, title, options) {
Room.call(this, roomid, title);
if (options) {
this.chatRoomData = options;
Object.merge(this, options);
}
this.logTimes = true;
this.logFile = null;
this.logFilename = '';
this.destroyingLog = false;
if (!this.modchat) this.modchat = (Config.modchat.chat || false);
if (Config.logChat) {
this.rollLogFile(true);
this.logEntry = function (entry, date) {
var timestamp = (new Date()).format('{HH}:{mm}:{ss} ');
this.logFile.write(timestamp + entry + '\n');
};
this.logEntry('NEW CHATROOM: ' + this.id);
if (Config.logUserStats) {
setInterval(this.logUserStats.bind(this), Config.logUserStats);
}
}
if (Config.reportJoinsPeriod) {
this.userList = this.getUserList();
this.reportJoinsQueue = [];
}
}
ChatRoom.prototype = Object.create(Room.prototype);
ChatRoom.prototype.type = 'chat';
ChatRoom.prototype.reportRecentJoins = function () {
delete this.reportJoinsInterval;
if (this.reportJoinsQueue.length === 0) {
// nothing to report
return;
}
if (Config.reportJoinsPeriod) {
this.userList = this.getUserList();
}
this.send(this.reportJoinsQueue.join('\n'));
this.reportJoinsQueue.length = 0;
};
ChatRoom.prototype.rollLogFile = function (sync) {
var mkdir = sync ? function (path, mode, callback) {
try {
fs.mkdirSync(path, mode);
} catch (e) {} // directory already exists
callback();
} : fs.mkdir;
var date = new Date();
var basepath = 'logs/chat/' + this.id + '/';
var self = this;
mkdir(basepath, '0755', function () {
var path = date.format('{yyyy}-{MM}');
mkdir(basepath + path, '0755', function () {
if (self.destroyingLog) return;
path += '/' + date.format('{yyyy}-{MM}-{dd}') + '.txt';
if (path !== self.logFilename) {
self.logFilename = path;
if (self.logFile) self.logFile.destroySoon();
self.logFile = fs.createWriteStream(basepath + path, {flags: 'a'});
// Create a symlink to today's lobby log.
// These operations need to be synchronous, but it's okay
// because this code is only executed once every 24 hours.
var link0 = basepath + 'today.txt.0';
try {
fs.unlinkSync(link0);
} catch (e) {} // file doesn't exist
try {
fs.symlinkSync(path, link0); // `basepath` intentionally not included
try {
fs.renameSync(link0, basepath + 'today.txt');
} catch (e) {} // OS doesn't support atomic rename
} catch (e) {} // OS doesn't support symlinks
}
var timestamp = +date;
date.advance('1 hour').reset('minutes').advance('1 second');
setTimeout(self.rollLogFile.bind(self), +date - timestamp);
});
});
};
ChatRoom.prototype.destroyLog = function (initialCallback, finalCallback) {
this.destroyingLog = true;
initialCallback();
if (this.logFile) {
this.logEntry = function () { };
this.logFile.on('close', finalCallback);
this.logFile.destroySoon();
} else {
finalCallback();
}
};
ChatRoom.prototype.logUserStats = function () {
var total = 0;
var guests = 0;
var groups = {};
Config.groups.byRank.forEach(function (group) {
groups[group] = 0;
});
for (var i in this.users) {
var user = this.users[i];
++total;
if (!user.named) {
++guests;
}
++groups[user.group];
}
var entry = '|userstats|total:' + total + '|guests:' + guests;
for (var i in groups) {
entry += '|' + i + ':' + groups[i];
}
this.logEntry(entry);
};
ChatRoom.prototype.getUserList = function () {
var buffer = '';
var counter = 0;
for (var i in this.users) {
if (!this.users[i].named) {
continue;
}
counter++;
buffer += ',' + this.users[i].getIdentity(this.id);
}
var msg = '|users|' + counter + buffer;
return msg;
};
ChatRoom.prototype.reportJoin = function (entry) {
if (Config.reportJoinsPeriod) {
if (!this.reportJoinsInterval) {
this.reportJoinsInterval = setTimeout(
this.reportRecentJoins.bind(this), Config.reportJoinsPeriod
);
}
this.reportJoinsQueue.push(entry);
} else {
this.send(entry);
}
this.logEntry(entry);
};
ChatRoom.prototype.update = function () {
if (this.log.length <= this.lastUpdate) return;
var entries = this.log.slice(this.lastUpdate);
if (this.reportJoinsQueue && this.reportJoinsQueue.length) {
clearTimeout(this.reportJoinsInterval);
delete this.reportJoinsInterval;
Array.prototype.unshift.apply(entries, this.reportJoinsQueue);
this.reportJoinsQueue.length = 0;
this.userList = this.getUserList();
}
var update = entries.join('\n');
if (this.log.length > 100) {
this.log.splice(0, this.log.length - 100);
}
this.lastUpdate = this.log.length;
this.send(update);
};
ChatRoom.prototype.getIntroMessage = function () {
var html = this.introMessage || '';
if (this.modchat) {
if (html) html += '<br /><br />';
html += '<div class="broadcast-red">';
html += 'Must be rank ' + this.modchat + ' or higher to talk right now.';
html += '</div>';
}
if (html) return '\n|raw|<div class="infobox">' + html + '</div>';
return '';
};
ChatRoom.prototype.onJoinConnection = function (user, connection) {
var userList = this.userList ? this.userList : this.getUserList();
this.sendUser(connection, '|init|chat\n|title|' + this.title + '\n' + userList + '\n' + this.getLogSlice(-25).join('\n') + this.getIntroMessage());
if (global.Tournaments && Tournaments.get(this.id)) {
Tournaments.get(this.id).updateFor(user, connection);
}
};
ChatRoom.prototype.onJoin = function (user, connection, merging) {
if (!user) return false; // ???
if (this.users[user.userid]) return user;
this.users[user.userid] = user;
this.userCount++;
if (!merging) {
var userList = this.userList ? this.userList : this.getUserList();
this.sendUser(connection, '|init|chat\n|title|' + this.title + '\n' + userList + '\n' + this.getLogSlice(-100).join('\n') + this.getIntroMessage());
};
if (user.named && Config.reportJoins) {
this.add('|j|' + user.getIdentity(this.id));
this.update();
} else if (user.named) {
var entry = '|J|' + user.getIdentity(this.id);
this.reportJoin(entry);
}
if (global.Tournaments && Tournaments.get(this.id)) {
Tournaments.get(this.id).updateFor(user, connection);
}
return user;
};
ChatRoom.prototype.onRename = function (user, oldid, joining) {
delete this.users[oldid];
this.users[user.userid] = user;
var entry;
if (joining) {
if (Config.reportJoins) {
entry = '|j|' + user.getIdentity(this.id);
} else {
entry = '|J|' + user.getIdentity(this.id);
}
} else if (!user.named) {
entry = '|L| ' + oldid;
} else {
entry = '|N|' + user.getIdentity(this.id) + '|' + oldid;
}
if (Config.reportJoins) {
this.add(entry);
} else {
this.reportJoin(entry);
}
if (this.bannedUsers && (user.userid in this.bannedUsers || user.autoconfirmed in this.bannedUsers)) {
this.bannedUsers[oldid] = true;
for (var ip in user.ips) this.bannedIps[ip] = true;
user.leaveRoom(this);
var alts = user.getAlts();
for (var i = 0; i < alts.length; ++i) {
this.bannedUsers[toId(alts[i])] = true;
Users.getExact(alts[i]).leaveRoom(this);
}
return;
}
if (global.Tournaments && Tournaments.get(this.id)) {
Tournaments.get(this.id).updateFor(user);
}
return user;
};
/**
* onRename, but without a userid change
*/
ChatRoom.prototype.onUpdateIdentity = function (user) {
if (user && user.connected && user.named) {
if (!this.users[user.userid]) return false;
var entry = '|N|' + user.getIdentity(this.id) + '|' + user.userid;
this.reportJoin(entry);
}
};
ChatRoom.prototype.onLeave = function (user) {
if (!user) return; // ...
delete this.users[user.userid];
this.userCount--;
if (user.named && Config.reportJoins) {
this.add('|l|' + user.getIdentity(this.id));
} else if (user.named) {
var entry = '|L|' + user.getIdentity(this.id);
this.reportJoin(entry);
}
};
ChatRoom.prototype.destroy = function () {
// deallocate ourself
// remove references to ourself
for (var i in this.users) {
this.users[i].leaveRoom(this);
delete this.users[i];
}
this.users = null;
rooms.global.deregisterChatRoom(this.id);
rooms.global.delistChatRoom(this.id);
// get rid of some possibly-circular references
delete rooms[this.id];
};
return ChatRoom;
})();
// to make sure you don't get null returned, pass the second argument
function getRoom(roomid, fallback) {
if (roomid && roomid.id) return roomid;
if (!roomid) roomid = 'default';
if (!rooms[roomid] && fallback) {
return rooms.global;
}
return rooms[roomid];
}
Rooms.get = getRoom;
Rooms.search = function (name, fallback) {
return getRoom(name) || getRoom(toId(name)) || Rooms.aliases[toId(name)] || (fallback ? rooms.global : undefined);
};
Rooms.createBattle = function (roomid, format, p1, p2, options) {
if (roomid && roomid.id) return roomid;
if (!p1 || !p2) return false;
if (!roomid) roomid = 'default';
if (!rooms[roomid]) {
// console.log("NEW BATTLE ROOM: " + roomid);
ResourceMonitor.countBattle(p1.latestIp, p1.name);
ResourceMonitor.countBattle(p2.latestIp, p2.name);
rooms[roomid] = new BattleRoom(roomid, format, p1, p2, options);
}
return rooms[roomid];
};
Rooms.createChatRoom = function (roomid, title, data) {
var room;
if ((room = rooms[roomid])) return room;
room = rooms[roomid] = new ChatRoom(roomid, title, data);
return room;
};
console.log("NEW GLOBAL: global");
rooms.global = new GlobalRoom('global');
Rooms.GlobalRoom = GlobalRoom;
Rooms.BattleRoom = BattleRoom;
Rooms.ChatRoom = ChatRoom;
Rooms.global = rooms.global;
Rooms.lobby = rooms.lobby;
Rooms.aliases = aliases;
|
Raina4uberz/Light-server
|
rooms.js
|
JavaScript
|
mit
| 49,287
|
using System;
using System.IO;
using Simpler;
namespace Library.Scripts.Tasks
{
public class RunScripts : InTask<RunScripts.Input>
{
public class Input
{
public string ConnectionName { get; set; }
public Script[] Scripts { get; set; }
}
public RunSql RunSql { get; set; }
public RunProcess RunProcess { get; set; }
public override void Execute()
{
foreach (var script in In.Scripts)
{
var fileName = Path.GetFileName(script.FileName);
var fileNameWithoutPath = Path.GetFileName(fileName);
if (fileNameWithoutPath == null) throw new RunException(String.Format("{0} is not a file.", fileName));
var extension = Path.GetExtension(fileNameWithoutPath);
if (String.Compare(extension, ".sql", StringComparison.OrdinalIgnoreCase) == 0)
{
RunSql.In.ConnectionName = In.ConnectionName;
RunSql.In.Sql = script;
RunSql.Execute();
}
else if (String.Compare(extension, ".py", StringComparison.OrdinalIgnoreCase) == 0)
{
RunProcess.In.FileName = "python";
RunProcess.In.Arguments = GetPythonArguments(script.FileName);
RunProcess.Execute();
}
else
{
throw new RunException(String.Format("Don't know how to run {0}.", fileName));
}
}
}
private string GetPythonArguments(string fileName)
{
if (Config.PythonMode == PythonMode.Script) return fileName;
var extension = Path.GetExtension(fileName);
return String.Format("-m {0}", fileName.Replace("\\", ".").Substring(0, fileName.Length - extension.Length));
}
}
}
|
gregoryjscott/please
|
app/Library/Scripts/Tasks/RunScripts.cs
|
C#
|
mit
| 1,948
|
(function ($, window, document, undefined)
{
var defaults = {
};
//var fr = new FileReader();
//var img = new Image();
var canvas;
var URL = window.webkitURL || window.URL;
function Plugin(element, options)
{
this.w = $(document);
this.el = $(element);
this.options = $.extend({}, defaults, options);
this.init(element);
}
Plugin.prototype = {
// инициализация плагина
init: function (params) {
var list = $(params),
thiss = this;
this.start(params);
},
start: function (params)
{
var thiss = this;
$(document).on("input", ".natura", function (e) {
var cont = $(this).closest(".grup");
var item = $(this).closest(".dd-item");
var result = cont.find(".result");
if (result.length){
if (item.find(">label input:checked").length){
result.val(thiss.get_translit($(this).val()));
}
}
});
console.log("start");
},
get_translit: function (str) {
var entoru = [[['а'], ['a']],
[['б'], ['b']],
[['в'], ['v']],
[['г'], ['g']],
[['д'], ['d']],
[['е'], ['e']],
[['ё'], ['yo']],
[['ж'], ['zh']],
[['з'], ['z']],
[['и'], ['i']],
[['й'], ['j']],
[['к'], ['k']],
[['л'], ['l']],
[['м'], ['m']],
[['н'], ['n']],
[['о'], ['o']],
[['п'], ['p']],
[['р'], ['r']],
[['с'], ['s']],
[['т'], ['t']],
[['у'], ['u']],
[['ф'], ['f']],
[['х'], ['h']],
[['ц'], ['c']],
[['ч'], ['ch']],
[['ш'], ['sh']],
[['щ'], ['shch']],
[['ъ'], ['']],
[['ы'], ['y']],
[['ь'], ['']],
[['э'], ['e']],
[['ю'], ['yu']],
[['я'], ['ya']],
[['і'], ['i']],
[['ї'], ['i']],
[['є'], ['e']],
[['А'], ['A']],
[['Б'], ['B']],
[['В'], ['V']],
[['Г'], ['G']],
[['Д'], ['D']],
[['Е'], ['E']],
[['Ё'], ['Yo']],
[['Ж'], ['Zh']],
[['З'], ['Z']],
[['И'], ['I']],
[['Й'], ['J']],
[['К'], ['K']],
[['Л'], ['L']],
[['М'], ['M']],
[['Н'], ['N']],
[['О'], ['O']],
[['П'], ['P']],
[['Р'], ['R']],
[['С'], ['S']],
[['Т'], ['T']],
[['У'], ['U']],
[['Ф'], ['F']],
[['Х'], ['H']],
[['Ц'], ['C']],
[['Ч'], ['Ch']],
[['Ш'], ['Sh']],
[['Щ'], ['Shch']],
[['Ъ'], ['']],
[['Ы'], ['Y']],
[['Ь'], ['']],
[['Э'], ['E']],
[['Ю'], ['Yu']],
[['Я'], ['Ya']],
[[' '], ['-']],
[['І'], ['I']],
[['Ї'], ['I']],
[['Є'], ['E']]];
var nameVal = trim(str);
var trans = new String();
for (i = 0; i < entoru.length; i++) {
var regex = new RegExp(entoru[i][0][0], "g");
nameVal = nameVal.replace(regex, entoru[i][1][0]);
}
return nameVal.toLowerCase();
}//,resetFile
};
$.fn.transfer = function (params)
{
var lists = this,
retval = this;
lists.each(function ()
{
var plugin = $(this).data("transfer");
if (!plugin) {
$(this).data("transfer", new Plugin(this, params));
$(this).data("transfer-id", new Date().getTime());
} else {
if (typeof params === 'string' && typeof plugin[params] === 'function') {
retval = plugin[params]();
}
}
});
return retval || lists;
}
;
})(window.jQuery || window.Zepto, window, document);
|
sereg/mebel
|
files/site/admin/js/transfer.js
|
JavaScript
|
mit
| 4,662
|
# Filesystem / Cloud Storage
- [Introduction](#introduction)
- [Configuration](#configuration)
- [Basic Usage](#basic-usage)
- [Custom Filesystems](#custom-filesystems)
<a name="introduction"></a>
## Introduction
Laravel provides a wonderful filesystem abstraction thanks to the [Flysystem](https://github.com/thephpleague/flysystem) PHP package by Frank de Jonge. The Laravel Flysystem integration provides simple to use drivers for working with local filesystems, Amazon S3, and Rackspace Cloud Storage. Even better, it's amazingly simple to switch between these storage options as the API remains the same for each system!
<a name="configuration"></a>
## Configuration
The filesystem configuration file is located at `config/filesystems.php`. Within this file you may configure all of your "disks". Each disk represents a particular storage driver and storage location. Example configurations for each supported driver is included in the configuration file. So, simply modify the configuration to reflect your storage preferences and credentials!
Before using the S3 or Rackspace drivers, you will need to install the appropriate package via Composer:
- Amazon S3: `league/flysystem-aws-s3-v2 ~1.0`
- Rackspace: `league/flysystem-rackspace ~1.0`
Of course, you may configure as many disks as you like, and may even have multiple disks that use the same driver.
When using the `local` driver, note that all file operations are relative to the `root` directory defined in your configuration file. By default, this value is set to the `storage/app` directory. Therefore, the following method would store a file in `storage/app/file.txt`:
Storage::disk('local')->put('file.txt', 'Contents');
<a name="basic-usage"></a>
## Basic Usage
The `Storage` facade may be used to interact with any of your configured disks. Alternatively, you may type-hint the `Illuminate\Contracts\Filesystem\Factory` contract on any class that is resolved via the Laravel [service container](/docs/5.0/container).
#### Retrieving A Particular Disk
$disk = Storage::disk('s3');
$disk = Storage::disk('local');
#### Determining If A File Exists
$exists = Storage::disk('s3')->exists('file.jpg');
#### Calling Methods On The Default Disk
if (Storage::exists('file.jpg'))
{
//
}
#### Retrieving A File's Contents
$contents = Storage::get('file.jpg');
#### Setting A File's Contents
Storage::put('file.jpg', $contents);
#### Prepend To A File
Storage::prepend('file.log', 'Prepended Text');
#### Append To A File
Storage::append('file.log', 'Appended Text');
#### Delete A File
Storage::delete('file.jpg');
Storage::delete(['file1.jpg', 'file2.jpg']);
#### Copy A File To A New Location
Storage::copy('old/file1.jpg', 'new/file1.jpg');
#### Move A File To A New Location
Storage::move('old/file1.jpg', 'new/file1.jpg');
#### Get File Size
$size = Storage::size('file1.jpg');
#### Get The Last Modification Time (UNIX)
$time = Storage::lastModified('file1.jpg');
#### Get All Files Within A Directory
$files = Storage::files($directory);
// Recursive...
$files = Storage::allFiles($directory);
#### Get All Directories Within A Directory
$directories = Storage::directories($directory);
// Recursive...
$directories = Storage::allDirectories($directory);
#### Create A Directory
Storage::makeDirectory($directory);
#### Delete A Directory
Storage::deleteDirectory($directory);
<a name="custom-filesystems"></a>
## Custom Filesystems
Laravel's Flysystem integration provides drivers for several "drivers" out of the box; however, Flysystem is not limited to these and has adapters for many other storage systems. You can create a custom driver if you want to use one of these additional adapters in your Laravel application. Don't worry, it's not too hard!
In order to set up the custom filesystem you will need to create a service provider such as `DropboxFilesystemServiceProvider`. In the provider's `boot` method, you can inject an instance of the `Illuminate\Contracts\Filesystem\Factory` contract and call the `extend` method of the injected instance. Alternatively, You may use the `Disk` facade's `extend` method.
The first argument of the `extend` method is the name of the driver and the second is a Closure that receives the `$app` and `$config` variables. The resolver Closure must return an instance of `League\Flysystem\Filesystem`.
> **Note:** The $config variable will already contain the values defined in `config/filesystems.php` for the specified disk.
#### Dropbox Example
<?php namespace App\Providers;
use Disk;
use League\Flysystem\Filesystem;
use Dropbox\Client as DropboxClient;
use League\Flysystem\Dropbox\DropboxAdapter;
class DropboxFilesystemServiceProvider {
public function boot()
{
Disk::extend('dropbox', function($app, $config)
{
$client = new DropboxClient($config['accessToken'], $config['clientIdentifier']);
return new Filesystem(new DropboxAdapter($client));
});
}
}
|
adamgoose/docs
|
filesystem.md
|
Markdown
|
mit
| 4,992
|
<?xml version="1.0" ?><!DOCTYPE TS><TS language="pl" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="14"/>
<source>About Kickasscoin</source>
<translation>O Kickasscoin</translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="53"/>
<source><b>Kickasscoin</b> version</source>
<translation>Wersja <b>Kickasscoin</b></translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="97"/>
<source>Copyright © 2009-2012 Bitcoin Developers
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file license.txt or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation>Copyright © 2009-2012 Bitcoin Developers
Oprogramowanie eksperymentalne.
Distributed under the MIT/X11 software license, see the accompanying file license.txt or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.
Pomóż w tłumaczeniu:
www.transifex.net/projects/p/bitcoin/</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="14"/>
<source>Address Book</source>
<translation>Książka Adresowa</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="20"/>
<source>These are your Kickasscoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Tutaj znajdują się twoje adresy Kickasscoin do odbioru płatności. Możesz nadać oddzielne adresy dla każdego z wysyłających monety, żeby śledzić oddzielnie ich opłaty.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="36"/>
<source>Double-click to edit address or label</source>
<translation>Kliknij dwukrotnie, aby edytować adres lub etykietę</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="63"/>
<source>Create a new address</source>
<translation>Utwórz nowy adres</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="77"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Skopiuj aktualnie wybrany adres do schowka</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="66"/>
<source>&New Address</source>
<translation>&Nowy Adres</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="80"/>
<source>&Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="91"/>
<source>Show &QR Code</source>
<translation>Pokaż Kod &QR</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="102"/>
<source>Sign a message to prove you own this address</source>
<translation>Podpisz wiadomość aby dowieść, że ten adres jest twój</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="105"/>
<source>&Sign Message</source>
<translation>Podpi&sz Wiadomość</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="116"/>
<source>Delete the currently selected address from the list. Only sending addresses can be deleted.</source>
<translation>Usuń aktualnie wybrany adres z listy. Tylko adresy nadawcze mogą być usunięte.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="119"/>
<source>&Delete</source>
<translation>&Usuń</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="63"/>
<source>Copy &Label</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../addressbookpage.cpp" line="65"/>
<source>&Edit</source>
<translation>&Edytuj</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="292"/>
<source>Export Address Book Data</source>
<translation>Eksportuj książkę adresową</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="293"/>
<source>Comma separated file (*.csv)</source>
<translation>Plik *.CSV (rozdzielany przecinkami)</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="306"/>
<source>Error exporting</source>
<translation>Błąd podczas eksportowania</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="306"/>
<source>Could not write to file %1.</source>
<translation>Błąd zapisu do pliku %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="142"/>
<source>Label</source>
<translation>Etykieta</translation>
</message>
<message>
<location filename="../addresstablemodel.cpp" line="142"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location filename="../addresstablemodel.cpp" line="178"/>
<source>(no label)</source>
<translation>(bez etykiety)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="47"/>
<source>Enter passphrase</source>
<translation>Wpisz hasło</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="61"/>
<source>New passphrase</source>
<translation>Nowe hasło</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="75"/>
<source>Repeat new passphrase</source>
<translation>Powtórz nowe hasło</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Wprowadź nowe hasło dla portfela.<br/>Proszę użyć hasła składającego się z <b>10 lub więcej losowych znaków</b> lub <b>ośmiu lub więcej słów</b>.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="34"/>
<source>Encrypt wallet</source>
<translation>Zaszyfruj portfel</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="37"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Ta operacja wymaga hasła do portfela ażeby odblokować portfel.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="42"/>
<source>Unlock wallet</source>
<translation>Odblokuj portfel</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="45"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Ta operacja wymaga hasła do portfela ażeby odszyfrować portfel.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="50"/>
<source>Decrypt wallet</source>
<translation>Odszyfruj portfel</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="53"/>
<source>Change passphrase</source>
<translation>Zmień hasło</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="54"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Podaj stare i nowe hasło do portfela.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="100"/>
<source>Confirm wallet encryption</source>
<translation>Potwierdź szyfrowanie portfela</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="101"/>
<source>WARNING: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!
Are you sure you wish to encrypt your wallet?</source>
<translation>OSTRZEŻENIE: Jeśli zaszyfrujesz portfel i zgubisz hasło, wtedy <b>STRACISZ WSZYSTKIE SWOJE BITMONETY</b>
Czy na pewno chcesz zaszyfrować swój portfel?</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="110"/>
<location filename="../askpassphrasedialog.cpp" line="159"/>
<source>Wallet encrypted</source>
<translation>Portfel zaszyfrowany</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="111"/>
<source>Kickasscoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source>
<translation>Program Kickasscoin zamknie się aby dokończyć proces szyfrowania. Pamiętaj, że szyfrowanie portfela nie zabezpiecza w pełni Twoich bitcoinów przed kradzieżą przez wirusy lub trojany mogące zainfekować Twój komputer.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="207"/>
<location filename="../askpassphrasedialog.cpp" line="231"/>
<source>Warning: The Caps Lock key is on.</source>
<translation>Ostrzeżenie: Caps Lock jest włączony.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="116"/>
<location filename="../askpassphrasedialog.cpp" line="123"/>
<location filename="../askpassphrasedialog.cpp" line="165"/>
<location filename="../askpassphrasedialog.cpp" line="171"/>
<source>Wallet encryption failed</source>
<translation>Szyfrowanie portfela nie powiodło się</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="117"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Szyfrowanie portfela nie powiodło się z powodu wewnętrznego błędu. Twój portfel nie został zaszyfrowany.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="124"/>
<location filename="../askpassphrasedialog.cpp" line="172"/>
<source>The supplied passphrases do not match.</source>
<translation>Podane hasła nie są takie same.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="135"/>
<source>Wallet unlock failed</source>
<translation>Odblokowanie portfela nie powiodło się</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="136"/>
<location filename="../askpassphrasedialog.cpp" line="147"/>
<location filename="../askpassphrasedialog.cpp" line="166"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Wprowadzone hasło do odszyfrowania portfela jest niepoprawne.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="146"/>
<source>Wallet decryption failed</source>
<translation>Odszyfrowywanie portfela nie powiodło się</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="160"/>
<source>Wallet passphrase was succesfully changed.</source>
<translation>Hasło do portfela zostało pomyślnie zmienione.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="73"/>
<source>Kickasscoin Wallet</source>
<translation>Portfel Kickasscoin</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="215"/>
<source>Sign &message...</source>
<translation>Podpisz wiado&mość...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="248"/>
<source>Show/Hide &Kickasscoin</source>
<translation>Pokaż/Ukryj &Kickasscoin</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="515"/>
<source>Synchronizing with network...</source>
<translation>Synchronizacja z siecią...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="185"/>
<source>&Overview</source>
<translation>P&odsumowanie</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="186"/>
<source>Show general overview of wallet</source>
<translation>Pokazuje ogólny zarys portfela</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="191"/>
<source>&Transactions</source>
<translation>&Transakcje</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="192"/>
<source>Browse transaction history</source>
<translation>Przeglądaj historię transakcji</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="197"/>
<source>&Address Book</source>
<translation>Książka &adresowa</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="198"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Edytuj listę zapisanych adresów i i etykiet</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="203"/>
<source>&Receive coins</source>
<translation>Odbie&rz monety</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="204"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Pokaż listę adresów do otrzymywania płatności</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="209"/>
<source>&Send coins</source>
<translation>Wy&syłka monet</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="216"/>
<source>Prove you control an address</source>
<translation>Udowodnij, że kontrolujesz adres</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="235"/>
<source>E&xit</source>
<translation>&Zakończ</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="236"/>
<source>Quit application</source>
<translation>Zamknij program</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="239"/>
<source>&About %1</source>
<translation>&O %1</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="240"/>
<source>Show information about Kickasscoin</source>
<translation>Pokaż informację o Kickasscoin</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="242"/>
<source>About &Qt</source>
<translation>O &Qt</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="243"/>
<source>Show information about Qt</source>
<translation>Pokazuje informacje o Qt</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="245"/>
<source>&Options...</source>
<translation>&Opcje...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="252"/>
<source>&Encrypt Wallet...</source>
<translation>Zaszyfruj Portf&el</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="255"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="257"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="517"/>
<source>~%n block(s) remaining</source>
<translation><numerusform>pozostał ~%n blok</numerusform><numerusform>pozostało ~%n bloki</numerusform><numerusform>pozostało ~%n bloków</numerusform></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="528"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="250"/>
<source>&Export...</source>
<translation>&Eksportuj...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="210"/>
<source>Send coins to a Kickasscoin address</source>
<translation>Wyślij monety na adres Kickasscoin</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="246"/>
<source>Modify configuration options for Kickasscoin</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="249"/>
<source>Show or hide the Kickasscoin window</source>
<translation>Pokaż lub ukryj okno Kickasscoin</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="251"/>
<source>Export the data in the current tab to a file</source>
<translation>Eksportuj dane z aktywnej karty do pliku</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="253"/>
<source>Encrypt or decrypt wallet</source>
<translation>Zaszyfruj lub odszyfruj portfel</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="256"/>
<source>Backup wallet to another location</source>
<translation>Zapasowy portfel w innej lokalizacji</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="258"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Zmień hasło użyte do szyfrowania portfela</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="259"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="260"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="261"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="262"/>
<source>Verify a message signature</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="286"/>
<source>&File</source>
<translation>&Plik</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="296"/>
<source>&Settings</source>
<translation>P&referencje</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="302"/>
<source>&Help</source>
<translation>Pomo&c</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="311"/>
<source>Tabs toolbar</source>
<translation>Pasek zakładek</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="322"/>
<source>Actions toolbar</source>
<translation>Pasek akcji</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="334"/>
<location filename="../bitcoingui.cpp" line="343"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="343"/>
<location filename="../bitcoingui.cpp" line="399"/>
<source>Kickasscoin client</source>
<translation>Kickasscoin klient</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="492"/>
<source>%n active connection(s) to Kickasscoin network</source>
<translation><numerusform>%n aktywne połączenie do sieci Kickasscoin</numerusform><numerusform>%n aktywne połączenia do sieci Kickasscoin</numerusform><numerusform>%n aktywnych połączeń do sieci Kickasscoin</numerusform></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="540"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation>Pobrano %1 bloków z historią transakcji.</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="555"/>
<source>%n second(s) ago</source>
<translation><numerusform>%n sekundę temu</numerusform><numerusform>%n sekundy temu</numerusform><numerusform>%n sekund temu</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="559"/>
<source>%n minute(s) ago</source>
<translation><numerusform>%n minutę temu</numerusform><numerusform>%n minuty temu</numerusform><numerusform>%n minut temu</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="563"/>
<source>%n hour(s) ago</source>
<translation><numerusform>%n godzinę temu</numerusform><numerusform>%n godziny temu</numerusform><numerusform>%n godzin temu</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="567"/>
<source>%n day(s) ago</source>
<translation><numerusform>%n dzień temu</numerusform><numerusform>%n dni temu</numerusform><numerusform>%n dni temu</numerusform></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="573"/>
<source>Up to date</source>
<translation>Aktualny</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="580"/>
<source>Catching up...</source>
<translation>Łapanie bloków...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="590"/>
<source>Last received block was generated %1.</source>
<translation>Ostatnio otrzymany blok została wygenerowany %1.</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="649"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>Transakcja przekracza limit. Możesz wysłać ją płacąc prowizję %1, która zostaje przekazana do węzłów, które ją prześlą i pomoże wspierać sieć Kickasscoin. Czy chcesz zapłacić prowizję?</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="654"/>
<source>Confirm transaction fee</source>
<translation>Potwierdź prowizję transakcyjną</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="681"/>
<source>Sent transaction</source>
<translation>Transakcja wysłana</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="682"/>
<source>Incoming transaction</source>
<translation>Transakcja przychodząca</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="683"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Data: %1
Kwota: %2
Typ: %3
Adres: %4
</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="804"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Portfel jest <b>zaszyfrowany</b> i obecnie <b>niezablokowany</b></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="812"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Portfel jest <b>zaszyfrowany</b> i obecnie <b>zablokowany</b></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="835"/>
<source>Backup Wallet</source>
<translation>Kopia Zapasowa Portfela</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="835"/>
<source>Wallet Data (*.dat)</source>
<translation>Dane Portfela (*.dat)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="838"/>
<source>Backup Failed</source>
<translation>Kopia Zapasowa Nie Została Wykonana</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="838"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Wystąpił błąd podczas próby zapisu portfela do nowej lokalizacji.</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="112"/>
<source>A fatal error occured. Kickasscoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="84"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>DisplayOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="246"/>
<source>Display</source>
<translation>Wyświetlanie</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="257"/>
<source>default</source>
<translation>domyślny</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="263"/>
<source>The user interface language can be set here. This setting will only take effect after restarting Kickasscoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="252"/>
<source>User Interface &Language:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="273"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="277"/>
<source>Choose the default subdivision unit to show in the interface, and when sending coins</source>
<translation>Wybierz podział jednostki pokazywany w interfejsie oraz podczas wysyłania monet</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="284"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="285"/>
<source>Whether to show Kickasscoin addresses in the transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="303"/>
<source>Warning</source>
<translation>Ostrzeżenie</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="303"/>
<source>This setting will take effect after restarting Kickasscoin.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="14"/>
<source>Edit Address</source>
<translation>Edytuj adres</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="25"/>
<source>&Label</source>
<translation>&Etykieta</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="35"/>
<source>The label associated with this address book entry</source>
<translation>Etykieta skojarzona z tym wpisem w książce adresowej</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="42"/>
<source>&Address</source>
<translation>&Adres</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="52"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Ten adres jest skojarzony z wpisem w książce adresowej. Może być zmodyfikowany jedynie dla adresów wysyłających.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="20"/>
<source>New receiving address</source>
<translation>Nowy adres odbiorczy</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="24"/>
<source>New sending address</source>
<translation>Nowy adres wysyłania</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="27"/>
<source>Edit receiving address</source>
<translation>Edytuj adres odbioru</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="31"/>
<source>Edit sending address</source>
<translation>Edytuj adres wysyłania</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="91"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Wprowadzony adres "%1" już istnieje w książce adresowej.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="96"/>
<source>The entered address "%1" is not a valid Kickasscoin address.</source>
<translation>Wprowadzony adres "%1" nie jest poprawnym adresem Kickasscoin.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="101"/>
<source>Could not unlock wallet.</source>
<translation>Nie można było odblokować portfela.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="106"/>
<source>New key generation failed.</source>
<translation>Tworzenie nowego klucza nie powiodło się.</translation>
</message>
</context>
<context>
<name>HelpMessageBox</name>
<message>
<location filename="../bitcoin.cpp" line="133"/>
<location filename="../bitcoin.cpp" line="143"/>
<source>Kickasscoin-Qt</source>
<translation>Kickasscoin-Qt</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="133"/>
<source>version</source>
<translation>wersja</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="135"/>
<source>Usage:</source>
<translation>Użycie:</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="136"/>
<source>options</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="138"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="139"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Ustaw Język, na przykład "pl_PL" (domyślnie: systemowy)</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="140"/>
<source>Start minimized</source>
<translation>Uruchom zminimalizowany</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="141"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Pokazuj okno powitalne przy starcie (domyślnie: 1)</translation>
</message>
</context>
<context>
<name>MainOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="227"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="212"/>
<source>Pay transaction &fee</source>
<translation>Płać prowizję za t&ransakcje</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="204"/>
<source>Main</source>
<translation>Główny</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="206"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation>Opcjonalna prowizja za transakcje za kB, wspomaga ona szybkość przebiegu transakcji. Większość transakcji jest 1 kB. Zalecana prowizja 0.01 .</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="222"/>
<source>&Start Kickasscoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="223"/>
<source>Automatically start Kickasscoin after logging in to the system</source>
<translation>Automatycznie uruchom Kickasscoin po zalogowaniu do systemu</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="226"/>
<source>&Detach databases at shutdown</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>MessagePage</name>
<message>
<location filename="../forms/messagepage.ui" line="14"/>
<source>Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/messagepage.ui" line="20"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Możesz podpisywać wiadomości swoimi adresami aby udowodnić, że jesteś ich właścicielem. Uważaj, aby nie podpisywać niczego co wzbudza Twoje podejrzenia, ponieważ ktoś może stosować phishing próbując nakłonić Cię do ich podpisania. Akceptuj i podpisuj tylko w pełni zrozumiałe komunikaty i wiadomości.</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="38"/>
<source>The address to sign the message with (e.g. FShM3UpgFZnXzJ5zux1AWQvAE36rFJKMs7)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/messagepage.ui" line="48"/>
<source>Choose adress from address book</source>
<translation>Wybierz adres z książki adresowej</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="58"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="71"/>
<source>Paste address from clipboard</source>
<translation>Wklej adres ze schowka</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="81"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="93"/>
<source>Enter the message you want to sign here</source>
<translation>Wprowadź wiadomość, którą chcesz podpisać, tutaj</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="128"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/messagepage.ui" line="131"/>
<source>&Copy Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/messagepage.ui" line="142"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/messagepage.ui" line="145"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../messagepage.cpp" line="31"/>
<source>Click "Sign Message" to get signature</source>
<translation>Kliknij "Podpisz Wiadomość" żeby uzyskać podpis</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="114"/>
<source>Sign a message to prove you own this address</source>
<translation>Podpisz wiadomość aby dowieść, że ten adres jest twój</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="117"/>
<source>&Sign Message</source>
<translation>Podpi&sz Wiadomość</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="30"/>
<source>Enter a Kickasscoin address (e.g. FShM3UpgFZnXzJ5zux1AWQvAE36rFJKMs7)</source>
<translation>Wprowadź adres Kickasscoin (np. FShM3UpgFZnXzJ5zux1AWQvAE36rFJKMs7)</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="83"/>
<location filename="../messagepage.cpp" line="90"/>
<location filename="../messagepage.cpp" line="105"/>
<location filename="../messagepage.cpp" line="117"/>
<source>Error signing</source>
<translation>Błąd podpisywania</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="83"/>
<source>%1 is not a valid address.</source>
<translation>%1 nie jest poprawnym adresem.</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="90"/>
<source>%1 does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../messagepage.cpp" line="105"/>
<source>Private key for %1 is not available.</source>
<translation>Klucz prywatny dla %1 jest niedostępny.</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="117"/>
<source>Sign failed</source>
<translation>Podpisywanie nie powiodło się.</translation>
</message>
</context>
<context>
<name>NetworkOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="345"/>
<source>Network</source>
<translation>Sieć</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="347"/>
<source>Map port using &UPnP</source>
<translation>Mapuj port używając &UPnP</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="348"/>
<source>Automatically open the Kickasscoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Automatycznie otwiera port klienta Kickasscoin na routerze. Ta opcja dzieła tylko jeśli twój router wspiera UPnP i jest ono włączone.</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="351"/>
<source>&Connect through SOCKS4 proxy:</source>
<translation>Połącz przez proxy SO&CKS4:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="352"/>
<source>Connect to the Bitcon network through a SOCKS4 proxy (e.g. when connecting through Tor)</source>
<translation>Łączy się z siecią Kickasscoin przez proxy SOCKS4 (np. kiedy łączysz się przez Tor)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="357"/>
<source>Proxy &IP:</source>
<translation>Proxy &IP: </translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="366"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="363"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Adres IP serwera proxy (np. 127.0.0.1)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="372"/>
<source>Port of the proxy (e.g. 1234)</source>
<translation>Port proxy (np. 1234)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../optionsdialog.cpp" line="135"/>
<source>Options</source>
<translation>Opcje</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="14"/>
<source>Form</source>
<translation>Formularz</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="47"/>
<location filename="../forms/overviewpage.ui" line="204"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Kickasscoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="89"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="147"/>
<source>Number of transactions:</source>
<translation>Liczba transakcji:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="118"/>
<source>Unconfirmed:</source>
<translation>Niepotwierdzony:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="40"/>
<source>Wallet</source>
<translation>Portfel</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="197"/>
<source><b>Recent transactions</b></source>
<translation><b>Ostatnie transakcje</b></translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="105"/>
<source>Your current balance</source>
<translation>Twoje obecne saldo</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="134"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Suma transakcji, które nie zostały jeszcze potwierdzone, i które nie zostały wliczone do twojego obecnego salda</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="154"/>
<source>Total number of transactions in wallet</source>
<translation>Całkowita liczba transakcji w portfelu</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="110"/>
<location filename="../overviewpage.cpp" line="111"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="14"/>
<source>QR Code Dialog</source>
<translation>Okno Dialogowe Kodu QR</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="32"/>
<source>QR Code</source>
<translation>Kod QR</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="55"/>
<source>Request Payment</source>
<translation>Prośba o płatność</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="70"/>
<source>Amount:</source>
<translation>Kwota:</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="105"/>
<source>KIK</source>
<translation>KIK</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="121"/>
<source>Label:</source>
<translation>Etykieta:</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="144"/>
<source>Message:</source>
<translation>Wiadomość:</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="186"/>
<source>&Save As...</source>
<translation>Zapi&sz jako...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="45"/>
<source>Error encoding URI into QR Code.</source>
<translation>Błąd kodowania URI w Kodzie QR.</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="63"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="120"/>
<source>Save QR Code</source>
<translation>Zapisz Kod QR</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="120"/>
<source>PNG Images (*.png)</source>
<translation>Obraz PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="14"/>
<source>Kickasscoin debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="46"/>
<source>Client name</source>
<translation>Nazwa klienta</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="56"/>
<location filename="../forms/rpcconsole.ui" line="79"/>
<location filename="../forms/rpcconsole.ui" line="102"/>
<location filename="../forms/rpcconsole.ui" line="125"/>
<location filename="../forms/rpcconsole.ui" line="161"/>
<location filename="../forms/rpcconsole.ui" line="214"/>
<location filename="../forms/rpcconsole.ui" line="237"/>
<location filename="../forms/rpcconsole.ui" line="260"/>
<location filename="../rpcconsole.cpp" line="245"/>
<source>N/A</source>
<translation>NIEDOSTĘPNE</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="69"/>
<source>Client version</source>
<translation>Wersja klienta</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="24"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="39"/>
<source>Client</source>
<translation>Klient</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="115"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="144"/>
<source>Network</source>
<translation>Sieć</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="151"/>
<source>Number of connections</source>
<translation>Liczba połączeń</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="174"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="197"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="204"/>
<source>Current number of blocks</source>
<translation>Aktualna liczba bloków</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="227"/>
<source>Estimated total blocks</source>
<translation>Szacowana ilość bloków</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="250"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="292"/>
<source>Debug logfile</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="299"/>
<source>Open the Kickasscoin debug logfile from the current data directory. This can take a few seconds for large logfiles.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="302"/>
<source>&Open</source>
<translation>&Otwórz</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="323"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="92"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="372"/>
<source>Clear console</source>
<translation>Wyczyść konsole</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="212"/>
<source>Welcome to the Kickasscoin RPC console.</source>
<translation>Witam w konsoli Kickasscoin RPC</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="213"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="214"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="14"/>
<location filename="../sendcoinsdialog.cpp" line="122"/>
<location filename="../sendcoinsdialog.cpp" line="127"/>
<location filename="../sendcoinsdialog.cpp" line="132"/>
<location filename="../sendcoinsdialog.cpp" line="137"/>
<location filename="../sendcoinsdialog.cpp" line="143"/>
<location filename="../sendcoinsdialog.cpp" line="148"/>
<location filename="../sendcoinsdialog.cpp" line="153"/>
<source>Send Coins</source>
<translation>Wyślij płatność</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="64"/>
<source>Send to multiple recipients at once</source>
<translation>Wyślij do wielu odbiorców na raz</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="67"/>
<source>&Add Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="84"/>
<source>Remove all transaction fields</source>
<translation>Wyczyść wszystkie pola transakcji</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="87"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="106"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="113"/>
<source>123.456 KIK</source>
<translation>123.456 KIK</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="144"/>
<source>Confirm the send action</source>
<translation>Potwierdź akcję wysyłania</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="147"/>
<source>&Send</source>
<translation>Wy&syłka</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="94"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> do %2 (%3)</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="99"/>
<source>Confirm send coins</source>
<translation>Potwierdź wysyłanie monet</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="100"/>
<source>Are you sure you want to send %1?</source>
<translation>Czy na pewno chcesz wysłać %1?</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="100"/>
<source> and </source>
<translation> i </translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="123"/>
<source>The recepient address is not valid, please recheck.</source>
<translation>Adres odbiorcy jest niepoprawny, proszę go sprawdzić.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="128"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Kwota do zapłacenie musi być większa od 0.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="133"/>
<source>The amount exceeds your balance.</source>
<translation>Kwota przekracza twoje saldo.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="138"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="144"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="149"/>
<source>Error: Transaction creation failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="154"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="14"/>
<source>Form</source>
<translation>Formularz</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="29"/>
<source>A&mount:</source>
<translation>Su&ma:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="42"/>
<source>Pay &To:</source>
<translation>Płać &Do:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="66"/>
<location filename="../sendcoinsentry.cpp" line="25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Wprowadź etykietę dla tego adresu by dodać go do książki adresowej</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="75"/>
<source>&Label:</source>
<translation>&Etykieta:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="93"/>
<source>The address to send the payment to (e.g. FShM3UpgFZnXzJ5zux1AWQvAE36rFJKMs7)</source>
<translation>Adres do wysłania należności do (np. FShM3UpgFZnXzJ5zux1AWQvAE36rFJKMs7)</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="103"/>
<source>Choose address from address book</source>
<translation>Wybierz adres z książki adresowej</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="113"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="120"/>
<source>Paste address from clipboard</source>
<translation>Wklej adres ze schowka</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="130"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="137"/>
<source>Remove this recipient</source>
<translation>Usuń tego odbiorce</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="26"/>
<source>Enter a Kickasscoin address (e.g. FShM3UpgFZnXzJ5zux1AWQvAE36rFJKMs7)</source>
<translation>Wprowadź adres Kickasscoin (np. FShM3UpgFZnXzJ5zux1AWQvAE36rFJKMs7)</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="21"/>
<source>Open for %1 blocks</source>
<translation>Otwórz dla %1 bloków</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="23"/>
<source>Open until %1</source>
<translation>Otwórz do %1</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="29"/>
<source>%1/offline?</source>
<translation>%1/offline?</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="31"/>
<source>%1/unconfirmed</source>
<translation>%1/niezatwierdzone</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="33"/>
<source>%1 confirmations</source>
<translation>%1 potwierdzeń</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="51"/>
<source><b>Status:</b> </source>
<translation><b>Status:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="56"/>
<source>, has not been successfully broadcast yet</source>
<translation>, nie został jeszcze pomyślnie wyemitowany</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="58"/>
<source>, broadcast through %1 node</source>
<translation>, emitowany przez %1 węzeł</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="60"/>
<source>, broadcast through %1 nodes</source>
<translation>, emitowany przez %1 węzły</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="64"/>
<source><b>Date:</b> </source>
<translation><b>Data:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="71"/>
<source><b>Source:</b> Generated<br></source>
<translation><b>Źródło:</b> Wygenerowano<br></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="77"/>
<location filename="../transactiondesc.cpp" line="94"/>
<source><b>From:</b> </source>
<translation><b>Od:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="94"/>
<source>unknown</source>
<translation>nieznany</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="95"/>
<location filename="../transactiondesc.cpp" line="118"/>
<location filename="../transactiondesc.cpp" line="178"/>
<source><b>To:</b> </source>
<translation><b>Do:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="98"/>
<source> (yours, label: </source>
<translation> (twoje, etykieta: </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="100"/>
<source> (yours)</source>
<translation> (twoje)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="136"/>
<location filename="../transactiondesc.cpp" line="150"/>
<location filename="../transactiondesc.cpp" line="195"/>
<location filename="../transactiondesc.cpp" line="212"/>
<source><b>Credit:</b> </source>
<translation><b>Przypisy:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="138"/>
<source>(%1 matures in %2 more blocks)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../transactiondesc.cpp" line="142"/>
<source>(not accepted)</source>
<translation>(niezaakceptowane)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="186"/>
<location filename="../transactiondesc.cpp" line="194"/>
<location filename="../transactiondesc.cpp" line="209"/>
<source><b>Debit:</b> </source>
<translation><b>Debet:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="200"/>
<source><b>Transaction fee:</b> </source>
<translation><b>Prowizja transakcyjna:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="216"/>
<source><b>Net amount:</b> </source>
<translation><b>Kwota netto:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="222"/>
<source>Message:</source>
<translation>Wiadomość:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="224"/>
<source>Comment:</source>
<translation>Komentarz:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="226"/>
<source>Transaction ID:</source>
<translation>ID transakcji:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="229"/>
<source>Generated coins must wait 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, it will change to "not accepted" and not be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Wygenerowane monety muszą zaczekać 120 bloków zanim będzie można je wydać. Kiedy wygenerowałeś ten blok, został on wyemitowany do sieci, aby dodać go do łańcucha bloków. Jeśli to się nie powiedzie nie zostanie on zaakceptowany i wygenerowanych monet nie będzie można wysyłać. Może się to czasami zdarzyć jeśli inny węzeł wygeneruje blok tuż przed tobą.</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="14"/>
<source>Transaction details</source>
<translation>Szczegóły transakcji</translation>
</message>
<message>
<location filename="../forms/transactiondescdialog.ui" line="20"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Ten panel pokazuje szczegółowy opis transakcji</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="226"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="226"/>
<source>Type</source>
<translation>Typ</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="226"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="226"/>
<source>Amount</source>
<translation>Kwota</translation>
</message>
<message numerus="yes">
<location filename="../transactiontablemodel.cpp" line="281"/>
<source>Open for %n block(s)</source>
<translation><numerusform>Otwórz dla %n bloku</numerusform><numerusform>Otwórz dla %n bloków</numerusform><numerusform>Otwórz dla %n bloków</numerusform></translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="284"/>
<source>Open until %1</source>
<translation>Otwórz do %1</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="287"/>
<source>Offline (%1 confirmations)</source>
<translation>Offline (%1 potwierdzeń)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="290"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Niezatwierdzony (%1 z %2 potwierdzeń)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="293"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Zatwierdzony (%1 potwierdzeń)</translation>
</message>
<message numerus="yes">
<location filename="../transactiontablemodel.cpp" line="301"/>
<source>Mined balance will be available in %n more blocks</source>
<translation><numerusform>Wydobyta kwota będzie dostępna za %n blok</numerusform><numerusform>Wydobyta kwota będzie dostępna za %n bloków</numerusform><numerusform>Wydobyta kwota będzie dostępna za %n bloki</numerusform></translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="307"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Ten blok nie został odebrany przez jakikolwiek inny węzeł i prawdopodobnie nie zostanie zaakceptowany!</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="310"/>
<source>Generated but not accepted</source>
<translation>Wygenerowano ale nie zaakceptowano</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="353"/>
<source>Received with</source>
<translation>Otrzymane przez</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="355"/>
<source>Received from</source>
<translation>Odebrano od</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="358"/>
<source>Sent to</source>
<translation>Wysłano do</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="360"/>
<source>Payment to yourself</source>
<translation>Płatność do siebie</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="362"/>
<source>Mined</source>
<translation>Wydobyto</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="400"/>
<source>(n/a)</source>
<translation>(brak)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="599"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Status transakcji. Najedź na pole, aby zobaczyć liczbę potwierdzeń.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="601"/>
<source>Date and time that the transaction was received.</source>
<translation>Data i czas odebrania transakcji.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="603"/>
<source>Type of transaction.</source>
<translation>Rodzaj transakcji.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="605"/>
<source>Destination address of transaction.</source>
<translation>Adres docelowy transakcji.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="607"/>
<source>Amount removed from or added to balance.</source>
<translation>Kwota usunięta z lub dodana do konta.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="55"/>
<location filename="../transactionview.cpp" line="71"/>
<source>All</source>
<translation>Wszystko</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="56"/>
<source>Today</source>
<translation>Dzisiaj</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="57"/>
<source>This week</source>
<translation>W tym tygodniu</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="58"/>
<source>This month</source>
<translation>W tym miesiącu</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="59"/>
<source>Last month</source>
<translation>W zeszłym miesiącu</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="60"/>
<source>This year</source>
<translation>W tym roku</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="61"/>
<source>Range...</source>
<translation>Zakres...</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="72"/>
<source>Received with</source>
<translation>Otrzymane przez</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="74"/>
<source>Sent to</source>
<translation>Wysłano do</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="76"/>
<source>To yourself</source>
<translation>Do siebie</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="77"/>
<source>Mined</source>
<translation>Wydobyto</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="78"/>
<source>Other</source>
<translation>Inne</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="85"/>
<source>Enter address or label to search</source>
<translation>Wprowadź adres albo etykietę żeby wyszukać</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="92"/>
<source>Min amount</source>
<translation>Min suma</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="126"/>
<source>Copy address</source>
<translation>Kopiuj adres</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="127"/>
<source>Copy label</source>
<translation>Kopiuj etykietę</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="128"/>
<source>Copy amount</source>
<translation>Kopiuj kwotę</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="129"/>
<source>Edit label</source>
<translation>Edytuj etykietę</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="130"/>
<source>Show transaction details</source>
<translation>Pokaż szczegóły transakcji</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="270"/>
<source>Export Transaction Data</source>
<translation>Eksportuj Dane Transakcyjne</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="271"/>
<source>Comma separated file (*.csv)</source>
<translation>CSV (rozdzielany przecinkami)</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="279"/>
<source>Confirmed</source>
<translation>Potwierdzony</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="280"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="281"/>
<source>Type</source>
<translation>Typ</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="282"/>
<source>Label</source>
<translation>Etykieta</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="283"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="284"/>
<source>Amount</source>
<translation>Kwota</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="285"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="289"/>
<source>Error exporting</source>
<translation>Błąd podczas eksportowania</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="289"/>
<source>Could not write to file %1.</source>
<translation>Błąd zapisu do pliku %1.</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="384"/>
<source>Range:</source>
<translation>Zakres:</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="392"/>
<source>to</source>
<translation>do</translation>
</message>
</context>
<context>
<name>VerifyMessageDialog</name>
<message>
<location filename="../forms/verifymessagedialog.ui" line="14"/>
<source>Verify Signed Message</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="20"/>
<source>Enter the message and signature below (be careful to correctly copy newlines, spaces, tabs and other invisible characters) to obtain the Kickasscoin address used to sign the message.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="62"/>
<source>Verify a message and obtain the Kickasscoin address used to sign the message</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="65"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="79"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Skopiuj aktualnie wybrany adres do schowka</translation>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="82"/>
<source>&Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="93"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/verifymessagedialog.ui" line="96"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="28"/>
<source>Enter Kickasscoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="29"/>
<source>Click "Verify Message" to obtain address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="55"/>
<location filename="../verifymessagedialog.cpp" line="62"/>
<source>Invalid Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="55"/>
<source>The signature could not be decoded. Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="62"/>
<source>The signature did not match the message digest. Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="72"/>
<source>Address not found in address book.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../verifymessagedialog.cpp" line="72"/>
<source>Address found in address book: %1</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="158"/>
<source>Sending...</source>
<translation>Wysyłanie...</translation>
</message>
</context>
<context>
<name>WindowOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="313"/>
<source>Window</source>
<translation>Okno</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="316"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimalizuj do paska przy zegarku zamiast do paska zadań</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="317"/>
<source>Show only a tray icon after minimizing the window</source>
<translation>Pokazuje tylko ikonę przy zegarku po zminimalizowaniu okna</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="320"/>
<source>M&inimize on close</source>
<translation>M&inimalizuj przy zamknięciu</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="321"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Minimalizuje zamiast zakończyć działanie programu przy zamykaniu okna. Kiedy ta opcja jest włączona, program zakończy działanie po wybieraniu Zamknij w menu.</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="43"/>
<source>Kickasscoin version</source>
<translation>Wersja Kickasscoin</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="44"/>
<source>Usage:</source>
<translation>Użycie:</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="45"/>
<source>Send command to -server or bitcoind</source>
<translation>Wyślij polecenie do -server lub bitcoind</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="46"/>
<source>List commands</source>
<translation>Lista poleceń</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="47"/>
<source>Get help for a command</source>
<translation>Uzyskaj pomoc do polecenia</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="49"/>
<source>Options:</source>
<translation>Opcje:</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="50"/>
<source>Specify configuration file (default: bitcoin.conf)</source>
<translation>Wskaż plik konfiguracyjny (domyślnie: bitcoin.conf)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="51"/>
<source>Specify pid file (default: bitcoind.pid)</source>
<translation>Wskaż plik pid (domyślnie: bitcoin.pid)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="52"/>
<source>Generate coins</source>
<translation>Generuj monety</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="53"/>
<source>Don't generate coins</source>
<translation>Nie generuj monet</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="54"/>
<source>Specify data directory</source>
<translation>Wskaż folder danych</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="55"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="56"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="57"/>
<source>Specify connection timeout (in milliseconds)</source>
<translation>Wskaż czas oczekiwania bezczynności połączenia (w milisekundach)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="63"/>
<source>Listen for connections on <port> (default: 8333 or testnet: 18333)</source>
<translation>Nasłuchuj połączeń na <port> (domyślnie: 8333 lub testnet: 18333)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="64"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Utrzymuj maksymalnie <n> połączeń z peerami (domyślnie: 125)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="66"/>
<source>Connect only to the specified node</source>
<translation>Łącz tylko do wskazanego węzła</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="67"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="68"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="69"/>
<source>Only connect to nodes in network <net> (IPv4 or IPv6)</source>
<translation>Łącz tylko z węzłami w sieci <net> (IPv4 lub IPv6)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="70"/>
<source>Try to discover public IP address (default: 1)</source>
<translation>Próbuj odkryć publiczny adres IP (domyślnie: 1)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="73"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="75"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="76"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="79"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)</source>
<translation>Maksymalny bufor odbioru na połączenie, <n>*1000 bajtów (domyślnie: 10000)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="80"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)</source>
<translation>Maksymalny bufor wysyłu na połączenie, <n>*1000 bajtów (domyślnie: 10000)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="83"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="86"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Akceptuj linię poleceń oraz polecenia JSON-RPC</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="87"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Uruchom w tle jako daemon i przyjmuj polecenia</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="88"/>
<source>Use the test network</source>
<translation>Użyj sieci testowej</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="89"/>
<source>Output extra debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="90"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="91"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Wyślij informację/raport do konsoli zamiast do pliku debug.log.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="92"/>
<source>Send trace/debug info to debugger</source>
<translation>Wyślij informację/raport do debuggera.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="93"/>
<source>Username for JSON-RPC connections</source>
<translation>Nazwa użytkownika dla połączeń JSON-RPC</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="94"/>
<source>Password for JSON-RPC connections</source>
<translation>Hasło do połączeń JSON-RPC</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="95"/>
<source>Listen for JSON-RPC connections on <port> (default: 8332)</source>
<translation>Nasłuchuj połączeń JSON-RPC na <port> (domyślnie: 8332)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="96"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Przyjmuj połączenia JSON-RPC ze wskazanego adresu IP</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="97"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Wysyłaj polecenia do węzła działającego na <ip> (domyślnie: 127.0.0.1)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="98"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="101"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="102"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Ustaw rozmiar puli kluczy na <n> (domyślnie: 100)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="103"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Przeskanuj blok łańcuchów żeby znaleźć zaginione transakcje portfela</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="104"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="105"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="106"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="108"/>
<source>
SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>
opcje SSL: (sprawdź Bitcoin Wiki dla instrukcje konfiguracji SSL)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="111"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Użyj OpenSSL (https) do połączeń JSON-RPC</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="112"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Plik certyfikatu serwera (domyślnie: server.cert)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="113"/>
<source>Server private key (default: server.pem)</source>
<translation>Klucz prywatny serwera (domyślnie: server.pem)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="114"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Aceptowalne szyfry (domyślnie: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="145"/>
<source>Warning: Disk space is low</source>
<translation>Ostrzeżenie: mało miejsca na dysku</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="107"/>
<source>This help message</source>
<translation>Ta wiadomość pomocy</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="121"/>
<source>Cannot obtain a lock on data directory %s. Kickasscoin is probably already running.</source>
<translation>Nie można zablokować folderu danych %s. Kickasscoin prawdopodobnie już działa.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="48"/>
<source>Kickasscoin</source>
<translation>Kickasscoin</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="30"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="58"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="59"/>
<source>Select the version of socks proxy to use (4 or 5, 5 is default)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="60"/>
<source>Do not use proxy for connections to network <net> (IPv4 or IPv6)</source>
<translation>Nie używaj proxy do połączeń z siecią <net> (IPv4 lub IPv6)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="61"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="62"/>
<source>Pass DNS requests to (SOCKS5) proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="142"/>
<source>Loading addresses...</source>
<translation>Wczytywanie adresów...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="132"/>
<source>Error loading blkindex.dat</source>
<translation>Błąd ładownia blkindex.dat</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="134"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Błąd ładowania wallet.dat: Uszkodzony portfel</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="135"/>
<source>Error loading wallet.dat: Wallet requires newer version of Kickasscoin</source>
<translation>Błąd ładowania wallet.dat: Portfel wymaga nowszej wersji Kickasscoin</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="136"/>
<source>Wallet needed to be rewritten: restart Kickasscoin to complete</source>
<translation>Portfel wymaga przepisania: zrestartuj Kickasscoina żeby ukończyć</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="137"/>
<source>Error loading wallet.dat</source>
<translation>Błąd ładowania wallet.dat</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="124"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="125"/>
<source>Unknown network specified in -noproxy: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="127"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="126"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="128"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="129"/>
<source>Not listening on any port</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="130"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="117"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Nieprawidłowa kwota dla -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="143"/>
<source>Error: could not start node</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="31"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="32"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="35"/>
<source>Error: Transaction creation failed </source>
<translation>Błąd: Tworzenie transakcji nie powiodło się </translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="36"/>
<source>Sending...</source>
<translation>Wysyłanie...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="37"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Błąd: transakcja została odrzucona. Może się to zdarzyć, gdy monety z Twojego portfela zostały już wydane, na przykład gdy używałeś kopii wallet.dat i bitcoiny które tam wydałeś nie zostały jeszcze odjęte z portfela z którego teraz korzystasz.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="41"/>
<source>Invalid amount</source>
<translation>Nieprawidłowa kwota</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="42"/>
<source>Insufficient funds</source>
<translation>Niewystarczające środki</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="131"/>
<source>Loading block index...</source>
<translation>Ładowanie indeksu bloku...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="65"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="28"/>
<source>Unable to bind to %s on this computer. Kickasscoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="71"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="72"/>
<source>Accept connections from outside (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="74"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="81"/>
<source>Use Universal Plug and Play to map the listening port (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="82"/>
<source>Use Universal Plug and Play to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="85"/>
<source>Fee per KB to add to transactions you send</source>
<translation>
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="118"/>
<source>Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="133"/>
<source>Loading wallet...</source>
<translation>Wczytywanie portfela...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="138"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="139"/>
<source>Cannot initialize keypool</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="140"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="141"/>
<source>Rescanning...</source>
<translation>Ponowne skanowanie...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="144"/>
<source>Done loading</source>
<translation>Wczytywanie zakończone</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="8"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="9"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=bitcoinrpc
rpcpassword=%s
(you do not need to remember this password)
If the file does not exist, create it with owner-readable-only file permissions.
</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="18"/>
<source>Error</source>
<translation>Błąd</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="19"/>
<source>An error occured while setting up the RPC port %i for listening: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="20"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="25"/>
<source>Warning: Please check that your computer's date and time are correct. If your clock is wrong Kickasscoin will not work properly.</source>
<translation>Ostrzeżenie: Proszę sprawdzić poprawność czasu i daty na tym komputerze. Jeśli czas jest zły Kickasscoin może nie działać prawidłowo.</translation>
</message>
</context>
</TS>
|
KickAssCoin/KIK
|
src/qt/locale/bitcoin_pl.ts
|
TypeScript
|
mit
| 109,835
|
## Apollo Client 3.5.10 (2022-02-24)
### Improvements
- Add `GraphQLWsLink` in `@apollo/client/link/subscriptions`. This link is similar to the existing `WebSocketLink` in `@apollo/client/link/ws`, but uses the newer [`graphql-ws`](https://www.npmjs.com/package/graphql-ws) package and protocol instead of the older `subscriptions-transport-ws` implementation. <br/>
[@glasser](https://github.com/glasser) in [#9369](https://github.com/apollographql/apollo-client/pull/9369)
> Note from [@benjamn](https://github.com/benjamn): since `GraphQLWsLink` is new functionality, we would normally wait for the next minor version (v3.6), but we were asked to expedite this release. These changes are strictly additive/opt-in/backwards-compatible, so shipping them in a patch release (3.5.10) seems safe, if unusual.
## Apollo Client 3.5.9 (2022-02-15)
### Improvements
- Interpret `keyFields: [...]` and `keyArgs: [...]` configurations in `InMemoryCache` type/field policies as `ReadonlyArray`s, since they are never mutated internally. <br/>
[@julienfouilhe](https://github.com/julienfouilhe) in [#9339](https://github.com/apollographql/apollo-client/pull/9339)
- Avoid declaring a global type for the `__DEV__` constant, to avoid conflict with other such global declarations. <br/>
[@benjamn](https://github.com/benjamn) in [#9386](https://github.com/apollographql/apollo-client/pull/9386)
### Bug Fixes
- Fix `useSubscription` executing `skip`ped subscription when input changes. <br/>
[@levrik](https://github.com/levrik) in [#9299](https://github.com/apollographql/apollo-client/pull/9299)
- Fix partial data appearing in `useQuery().data` when `notifyOnNetworkStatusChange: true`. <br/>
[@brainkim](https://github.com/brainkim) in [#9367](https://github.com/apollographql/apollo-client/pull/9367)
- Prevent `Promise`s returned by `useLazyQuery` execute functions from causing unhandled `Promise` rejection errors if uncaught. <br/>
[@brainkim](https://github.com/brainkim) in [#9380](https://github.com/apollographql/apollo-client/pull/9380)
## Apollo Client 3.5.8 (2022-01-24)
### Bug Fixes
- Fix the type of the `called` property returned by `useQuery()` and `useLazyQuery()`. <br/>
[@sztadii](https://github.com/sztadii) in [#9304](https://github.com/apollographql/apollo-client/pull/9304)
### Bug Fixes (by [@brainkim](https://github.com/brainkim) in [#9328](https://github.com/apollographql/apollo-client/pull/9328))
- Fix `refetch()` not being called when `skip` is true.
- Fix the promise returned from the `useLazyQuery()` execution function having stale variables.
- Fix the promise returned from the `useLazyQuery()` execution function not rejecting when a query errors.
## Apollo Client 3.5.7 (2022-01-10)
### Bug Fixes
- Fix regression that prevented calling `onError` or `onCompleted` in some cases when using `useQuery`. <br/>
[@mmahalwy](https://github.com/mmahalwy) in [#9226](https://github.com/apollographql/apollo-client/pull/9226)
- Make `useQuery` respect `defaultOptions.watchQuery.fetchPolicy`. <br/>
[@yasharzolmajdi](https://github.com/yasharzolmajdi) in [#9210](https://github.com/apollographql/apollo-client/pull/9210)
## Apollo Client 3.5.6 (2021-12-07)
### Bug Fixes (by [@brainkim](https://github.com/brainkim) in [#9144](https://github.com/apollographql/apollo-client/pull/9144))
- Restores old behavior where the callback passed to `useMutation()` is constant.
- Fix `useMutation()` callbacks having stale closures.
- Fix `useQuery()` variables being out of date.
## Apollo Client 3.5.5 (2021-11-23)
### Bug Fixes
- Remove `printer: Printer` positional parameter from publicly-exported `selectHttpOptionsAndBody` function, whose addition in [#8699](https://github.com/apollographql/apollo-client/pull/8699) was a breaking change (starting in Apollo Client 3.5.0) for direct consumers of `selectHttpOptionsAndBody`. <br/>
[@benjamn](https://github.com/benjamn) in [#9103](https://github.com/apollographql/apollo-client/pull/9103)
## Apollo Client 3.5.4 (2021-11-19)
### Notices
- [Relevant if you use Apollo Client with React Native] Since Apollo Client v3.5.0, CommonJS bundles provided by `@apollo/client` use a `.cjs` file extension rather than `.cjs.js`, so Node.js won't interpret them as ECMAScript modules. While this change should be an implementation detail, it may cause problems for the [Metro bundler](https://facebook.github.io/metro/) used by React Native, whose [`resolver.sourceExts`](https://facebook.github.io/metro/docs/configuration#sourceexts) configuration does not include the `cjs` extension by default.
As a workaround until [this issue](https://github.com/facebook/metro/issues/535) is resolved, you can configure Metro to understand the `.cjs` file extension by creating a `metro.config.js` file in the root of your React Native project:
```js
const { getDefaultConfig } = require("metro-config");
const { resolver: defaultResolver } = getDefaultConfig.getDefaultValues();
exports.resolver = {
...defaultResolver,
sourceExts: [
...defaultResolver.sourceExts,
"cjs",
],
};
```
### Improvements
- Restore the ability to pass `onError()` and `onCompleted()` to the mutation execution function. <br/> [@brainkim](https://github.com/brainkim) in [#9076](https://github.com/apollographql/apollo-client/pull/9076)
- Work around webpack 5 errors of the form
```
The request 'ts-invariant/process' failed to resolve only because it was resolved as fully specified
```
by ensuring `import ... from 'ts-invariant/process'` is internally written to `import ... from 'ts-invariant/process/index.js'`. <br/>
[@benjamn](https://github.com/benjamn) in [#9083](https://github.com/apollographql/apollo-client/pull/9083)
## Apollo Client 3.5.3 (2021-11-17)
- Avoid rewriting non-relative imported module specifiers in `config/rewriteModuleIds.ts` script, thereby allowing bundlers to resolve those imports as they see fit. <br/>
[@benjamn](https://github.com/benjamn) in [#9073](https://github.com/apollographql/apollo-client/pull/9073)
- Ensure only current file is matched when running VSCode debugger. <br/>
[@eps1lon](https://github.com/eps1lon) in [#9050](https://github.com/apollographql/apollo-client/pull/9050)
## Apollo Client 3.5.2 (2021-11-10)
- Fix useMutation execute function returning non-identical execution functions when passing similar options. <br/>
[@brainkim](https://github.com/brainkim) in [#9093](https://github.com/apollographql/apollo-client/pull/9037)
## Apollo Client 3.5.1 (2021-11-09)
- Remove npm from dependencies, and avoid referencing graphql-js enum value. <br/>
[@brainkim](https://github.com/brainkim) in [#9030](https://github.com/apollographql/apollo-client/pull/9030)
## Apollo Client 3.5.0 (2021-11-08)
### Improvements
- Add `updateQuery` and `updateFragment` methods to `ApolloCache`, simplifying common `readQuery`/`writeQuery` cache update patterns. <br/>
[@wassim-k](https://github.com/wassim-k) in [#8382](https://github.com/apollographql/apollo-client/pull/8382)
- Field directives and their arguments can now be included along with field argument names when using [field policy `keyArgs: [...]` notation](https://www.apollographql.com/docs/react/pagination/key-args/). For example, if you have a `Query.feed` field that takes an argument called `type` and uses a `@connection(key:...)` directive to keep `feed` data from different queries separate within the cache, you might configure both using the following `InMemoryCache` field policy:
```ts
new InMemoryCache({
typePolicies: {
Query: {
fields: {
feed: {
keyArgs: ["type", "@connection", ["key"]],
},
},
},
},
})
```
[@benjamn](https://github.com/benjamn) in [#8678](https://github.com/apollographql/apollo-client/pull/8678)
- Report single `MissingFieldError` instead of a potentially very large `MissingFieldError[]` array for incomplete cache reads, improving performance and memory usage. <br/>
[@benjamn](https://github.com/benjamn) in [#8734](https://github.com/apollographql/apollo-client/pull/8734)
- When writing results into `InMemoryCache`, each written object is now identified using `policies.identify` _after_ traversing the fields of the object (rather than before), simplifying identification and reducing duplicate work. If you have custom `keyFields` functions, they still receive the raw result object as their first parameter, but the `KeyFieldsContext` parameter now provides `context.storeObject` (the `StoreObject` just processed by `processSelectionSet`) and `context.readField` (a helper function for reading fields from `context.storeObject` and any `Reference`s it might contain, similar to `readField` for `read`, `merge`, and `cache.modify` functions). <br/>
[@benjamn](https://github.com/benjamn) in [#8996](https://github.com/apollographql/apollo-client/pull/8996)
- Ensure `cache.identify` never throws when primary key fields are missing, and include the source object in the error message when `keyFields` processing fails. <br/>
[@benjamn](https://github.com/benjamn) in [#8679](https://github.com/apollographql/apollo-client/pull/8679)
- The `HttpLink` constructor now accepts an optional `print` function that can be used to customize how GraphQL `DocumentNode` objects are transformed back into strings before they are sent over the network. <br/>
[@sarahgp](https://github.com/sarahgp) in [#8699](https://github.com/apollographql/apollo-client/pull/8699)
- Make `@apollo/client/testing` a fully-fledged, independent entry point, instead of re-exporting `@apollo/client/utilities/testing` (which was never an entry point and no longer exists). <br/>
[@benjamn](https://github.com/benjamn) in [#8769](https://github.com/apollographql/apollo-client/pull/8769)
- A new nested entry point called `@apollo/client/testing/core` has been created. Importing from this entry point instead of `@apollo/client/testing` excludes any React-related dependencies. <br/>
[@wassim-k](https://github.com/wassim-k) in [#8687](https://github.com/apollographql/apollo-client/pull/8687)
- Make `cache.batch` return the result of calling the `options.update` function. <br/>
[@benjamn](https://github.com/benjamn) in [#8696](https://github.com/apollographql/apollo-client/pull/8696)
- The `NetworkError` and `ErrorResponse` types have been changed to align more closely. <br/>
[@korywka](https://github.com/korywka) in [#8424](https://github.com/apollographql/apollo-client/pull/8424)
- Include `graphql@16` in peer deps. <br/>
[@brainkim](https://github.com/brainkim) in [#8997](https://github.com/apollographql/apollo-client/pull/8997)
- Update `zen-observable-ts` to eliminate transitive dependency on `@types/zen-observable`. <br/>
[@benjamn](https://github.com/benjamn) in [#8695](https://github.com/apollographql/apollo-client/pull/8695)
### React Refactoring
#### Improvements (due to [@brainkim](https://github.com/brainkim) in [#8875](https://github.com/apollographql/apollo-client/pull/8875)):
- The `useLazyQuery` function now returns a promise with the result.
- The `useMutation` result now exposes a method which can be reset.
#### Bug Fixes (due to [@brainkim](https://github.com/brainkim) in [#8596](https://github.com/apollographql/apollo-client/pull/8596)):
- The `useQuery` and `useLazyQuery` hooks will now have `ObservableQuery` methods defined consistently.
- Calling `useLazyQuery` methods like `startPolling` will start the query.
- Calling the `useLazyQuery` execution function will now behave more like `refetch`. `previousData` will be preserved.
- `standby` fetchPolicies will now act like `skip: true` more consistently.
- Calling `refetch` on a skipped query will have no effect (issue [#8270](https://github.com/apollographql/apollo-client/issues/8270)).
- Prevent `onError` and `onCompleted` functions from firing continuously, and improving their polling behavior.
## Apollo Client 3.4.17 (2021-11-08)
### Improvements
- Allow `TOptions extends FieldFunctionOptions` to be passed as final (optional) type parameter of `FieldPolicy` type. <br/>
[@VictorGaiva](https://github.com/VictorGaiva) in [#9000](https://github.com/apollographql/apollo-client/pull/9000)
## Apollo Client 3.4.16
### Improvements
- Prevent webpack from misresolving the `graphql` package as the local `@apollo/client/utilities/globals/graphql.js` module when `module.exports.resolve.preferRelative` is enabled in `webpack.config.js`.
> Note: if you encounter strange module resolution errors like `export 'isType' (imported as 'isType') was not found in 'graphql' (possible exports: removeTemporaryGlobals)` please try removing `preferRelative: true` from your `webpack.config.js` file, or find a way to disable that resolution behavior for packages within `node_modules`.
[@benjamn](https://github.com/benjamn) in [#8862](https://github.com/apollographql/apollo-client/pull/8862)
- Avoid importing `isType` from the `graphql` package internally, to prevent bundlers from including as much as 3.4kB of unnecessary code. <br/>
[@benjamn](https://github.com/benjamn) in [#8891](https://github.com/apollographql/apollo-client/pull/8891)
- Make `client.resetStore` and `client.clearStore` pass appropriate `discardWatches` option to `cache.reset`. <br/>
[@benjamn](https://github.com/benjamn) in [#8873](https://github.com/apollographql/apollo-client/pull/8873)
## Apollo Client 3.4.15
### Bug Fixes
- Require calling `cache.reset({ discardWatches: true })` to make `cache.reset` discard `cache.watches`, restoring behavior broken in v3.4.14 by [#8826](https://github.com/apollographql/apollo-client/pull/8826). <br/>
[@benjamn](https://github.com/benjamn) in [#8852](https://github.com/apollographql/apollo-client/pull/8852)
## Apollo Client 3.4.14
### Bug Fixes
- Disable `InMemoryCache` [result object canonization](https://github.com/apollographql/apollo-client/pull/7439) by default, to prevent unexpected memory growth and/or reuse of object references, with multiple ways to reenable it (per-cache, per-query, or a mixture of both). <br/>
[@benjamn](https://github.com/benjamn) in [#8822](https://github.com/apollographql/apollo-client/pull/8822)
- Clear `InMemoryCache` `watches` set when `cache.reset()` called. <br/>
[@benjamn](https://github.com/benjamn) in [#8826](https://github.com/apollographql/apollo-client/pull/8826)
- Stop excluding observerless queries from `refetchQueries: [...]` selection. <br/>
[@benjamn](https://github.com/benjamn) in [#8825](https://github.com/apollographql/apollo-client/pull/8825)
- Prevent optimistic cache evictions from evicting non-optimistic data. <br/>
[@benjamn](https://github.com/benjamn) in [#8829](https://github.com/apollographql/apollo-client/pull/8829)
- Ensure `cache.broadcastWatch` passes all relevant `WatchOptions` to `cache.diff` as `DiffOptions`. <br/>
[@benjamn](https://github.com/benjamn) in [#8832](https://github.com/apollographql/apollo-client/pull/8832)
## Apollo Client 3.4.13
### Bug Fixes
- Fix `componentDidUpate` typo in `withSubscription` higher-order component. <br/>
[@YarBez](https://github.com/YarBez) in [#7506](https://github.com/apollographql/apollo-client/pull/7506)
- Fix internal `canUseSymbol` import within `@apollo/client/utilities` to avoid breaking bundlers/builds. <br/>
[@benjamn](https://github.com/benjamn) in [#8817](https://github.com/apollographql/apollo-client/pull/8817)
- Tolerate unfreezable objects like `Uint8Array` and `Buffer` in `maybeDeepFreeze`. <br/>
[@geekuillaume](https://github.com/geekuillaume) and [@benjamn](https://github.com/benjamn) in [#8813](https://github.com/apollographql/apollo-client/pull/8813)
## Apollo Client 3.4.12
### Bug Fixes
- Improve handling of falsy `existing` and/or `incoming` parameters in `relayStylePagination` field policy helper function. <br/>
[@bubba](https://github.com/bubba) and [@benjamn](https://github.com/benjamn) in [#8733](https://github.com/apollographql/apollo-client/pull/8733)
- Associate Apollo context with `React.createContext` (instead of using a local `WeakMap`) again, so multiple copies of `@apollo/client` (uncommon) can share the same context. <br/>
[@benjamn](https://github.com/benjamn) in [#8798](https://github.com/apollographql/apollo-client/pull/8798)
## Apollo Client 3.4.11
### Bug Fixes
- Fix [Vite](https://vitejs.dev) tree-shaking by calling the `checkDEV()` function (at least once) in the module that exports it, `@apollo/client/utilities/globals/index.ts`. <br/>
[@benjamn](https://github.com/benjamn) in [#8767](https://github.com/apollographql/apollo-client/pull/8767)
### Improvements
- Export `PersistedQueryLink` namespace from `@apollo/client/link/persisted-queries`. <br/>
[@vedrani](https://github.com/vedrani) in [#8761](https://github.com/apollographql/apollo-client/pull/8761)
### Documentation
- Upgrade docs theme for new Algolia-powered search experience. <br/>
[@trevorblades](https://github.com/trevorblades) in [#8768](https://github.com/apollographql/apollo-client/pull/8768)
## Apollo Client 3.4.10
### Improvements
- Warn when calling `refetch({ variables })` instead of `refetch(variables)`, except for queries that declare a variable named `$variables` (uncommon). <br/>
[@benjamn](https://github.com/benjamn) in [#8702](https://github.com/apollographql/apollo-client/pull/8702)
### Bug Fixes
- Fix `ObservableQuery.getCurrentResult()` returning cached `data` with certain fetch policies. <br/>
[@brainkim](https://github.com/brainkim) in [#8718](https://github.com/apollographql/apollo-client/pull/8718)
- Prevent `ssrMode`/`ssrForceFetchDelay` from causing queries to hang. <br/>
[@brainkim](https://github.com/brainkim) in [#8709](https://github.com/apollographql/apollo-client/pull/8709)
- Import `@apollo/client/utilities/globals` internally wherever `__DEV__` is used, not just in `@apollo/client/**/index.js` entry points. <br/>
[@benjamn](https://github.com/benjamn) in [#8720](https://github.com/apollographql/apollo-client/pull/8720)
## Apollo Client 3.4.9
### Bug Fixes
- Fix unhandled `Promise` rejection warnings/errors whose message is `Observable cancelled prematurely`. <br/>
[@benjamn](https://github.com/benjamn) in [#8676](https://github.com/apollographql/apollo-client/pull/8676)
- Enforce that `__DEV__` is polyfilled by every `@apollo/client/*` entry point that uses it. This build step considers not only explicit `__DEV__` usage but also `__DEV__` references injected near `invariant(...)` and `new InvariantError(...)` expressions. <br/>
[@benjamn](https://github.com/benjamn) in [#8689](https://github.com/apollographql/apollo-client/pull/8689)
## Apollo Client 3.4.8
### Bug Fixes
- Fix error thrown by nested `keyFields: ["a", ["b", "c"], "d"]` type policies when writing results into the cache where any of the key fields (`.a`, `.a.b`, `.a.c`, or `.d`) have been renamed by query field alias syntax. <br/>
[@benjamn](https://github.com/benjamn) in [#8643](https://github.com/apollographql/apollo-client/pull/8643)
- Fix regression from PR [#8422](https://github.com/apollographql/apollo-client/pull/8422) (first released in `@apollo/client@3.4.0-rc.15`) that caused `result.data` to be set to undefined in some cases after `ObservableQuery#getCurrentResult` reads an incomplete result from the cache. <br/>
[@benjamn](https://github.com/benjamn) in [#8642](https://github.com/apollographql/apollo-client/pull/8642)
## Apollo Client 3.4.7
### Bug Fixes
- Fix accidental reuse of recycled `MergeTree` objects in `StoreWriter` class used by `InMemoryCache`. <br/>
[@benjamn](https://github.com/benjamn) in [#8618](https://github.com/apollographql/apollo-client/pull/8618)
## Apollo Client 3.4.6
### Improvements
- Reevaluate `window.fetch` each time `HttpLink` uses it, if not configured using `options.fetch`. This change enables a variety of strategies for instrumenting `window.fetch`, without requiring those strategies to run before `@apollo/client/link/http` is first imported. <br/>
[@benjamn](https://github.com/benjamn) in [#8603](https://github.com/apollographql/apollo-client/pull/8603)
- Clarify mutation `fetchPolicy` options (`"network-only"` or `"no-cache"`) using [`MutationFetchPolicy`](https://github.com/apollographql/apollo-client/blob/fa52875341ab33f3e8192ded90af5e2c208e0f75/src/core/watchQueryOptions.ts#L33-L37) union type. <br/>
[@benjamn](https://github.com/benjamn) in [#8602](https://github.com/apollographql/apollo-client/pull/8602)
### Bug Fixes
- Restore full `@apollo/client/apollo-client.cjs.js` CommonJS bundle for older bundlers.
> Note that Node.js and CommonJS bundlers typically use the bundles specified by `"main"` fields in our generated `package.json` files, which are all independent and non-overlapping CommonJS modules. However, `apollo-client.cjs.js` is just one big bundle, so mixing imports of `apollo-client.cjs.js` with the other CommonJS bundles is discouraged, as it could trigger the [dual package hazard](https://nodejs.org/api/packages.html#packages_dual_commonjs_es_module_packages). In other words, please don't start using `apollo-client.cjs.js` if you're not already. <br/>
[@benjamn](https://github.com/benjamn) in [#8592](https://github.com/apollographql/apollo-client/pull/8592)
- Log `MissingFieldError`s in `ObservableQuery#getCurrentResult` using `invariant.debug`, rather than reporting them via `result.error`. <br/>
[@benjamn](https://github.com/benjamn) in [#8604](https://github.com/apollographql/apollo-client/pull/8604)
## Apollo Client 3.4.5
### Bug Fixes
- Fix double registration bug for mutation `refetchQueries` specified using legacy one-time `refetchQueries: [{ query, variables }]` style. Though the bug is fixed, we recommend using `refetchQueries: [query]` instead (when possible) to refetch an existing query using its `DocumentNode`, rather than creating, executing, and then deleting a new query, as the legacy `{ query, variables }` style unfortunately does. <br/>
[@benjamn](https://github.com/benjamn) in [#8586](https://github.com/apollographql/apollo-client/pull/8586)
- Fix `useQuery`/`useLazyQuery` stalling when clients or queries change. <br/>
[@brainkim](https://github.com/brainkim) in [#8589](https://github.com/apollographql/apollo-client/pull/8589)
## Apollo Client 3.4.4
### Bug Fixes
- Revert accidental addition of `engines.npm` section to published version of `@apollo/client/package.json`. <br/>
[@benjamn](https://github.com/benjamn) in [#8578](https://github.com/apollographql/apollo-client/pull/8578)
## Apollo Client 3.4.3
### Bug Fixes
- Fix `{ ssr: false }` causing queries to hang on the client. <br/>
[@brainkim](https://github.com/brainkim) in [#8574](https://github.com/apollographql/apollo-client/pull/8574)
## Apollo Client 3.4.2
### Bug Fixes
- Use more default type parameters for mutation-related types in `react/types/types.ts`, to provide smoother backwards compatibility for code using those types explicitly. <br/>
[@benjamn](https://github.com/benjamn) in [#8573](https://github.com/apollographql/apollo-client/pull/8573)
## Apollo Client 3.4.1
### Bug Fixes
- Initialize `stringifyCanon` lazily, when `canonicalStringify` is first called, fixing `Uncaught ReferenceError: __DEV__ is not defined` errors due to usage of `__DEV__` before declaration. <br/>
[@benjamn](https://github.com/benjamn) in [#8557](https://github.com/apollographql/apollo-client/pull/8557)
## Apollo Client 3.4.0
### New documentation
- [**Refetching queries**](https://www.apollographql.com/docs/react/data/refetching/) with `client.refetchQueries`. <br/>
[@StephenBarlow](https://github.com/StephenBarlow) and [@benjamn](https://github.com/benjamn) in [#8265](https://github.com/apollographql/apollo-client/pull/8265)
### Improvements
- `InMemoryCache` now _guarantees_ that any two result objects returned by the cache (from `readQuery`, `readFragment`, etc.) will be referentially equal (`===`) if they are deeply equal. Previously, `===` equality was often achievable for results for the same query, on a best-effort basis. Now, equivalent result objects will be automatically shared among the result trees of completely different queries. This guarantee is important for taking full advantage of optimistic updates that correctly guess the final data, and for "pure" UI components that can skip re-rendering when their input data are unchanged. <br/>
[@benjamn](https://github.com/benjamn) in [#7439](https://github.com/apollographql/apollo-client/pull/7439)
- Mutations now accept an optional callback function called `onQueryUpdated`, which will be passed the `ObservableQuery` and `Cache.DiffResult` objects for any queries invalidated by cache writes performed by the mutation's final `update` function. Using `onQueryUpdated`, you can override the default `FetchPolicy` of the query, by (for example) calling `ObservableQuery` methods like `refetch` to force a network request. This automatic detection of invalidated queries provides an alternative to manually enumerating queries using the `refetchQueries` mutation option. Also, if you return a `Promise` from `onQueryUpdated`, the mutation will automatically await that `Promise`, rendering the `awaitRefetchQueries` option unnecessary. <br/>
[@benjamn](https://github.com/benjamn) in [#7827](https://github.com/apollographql/apollo-client/pull/7827)
- Support `client.refetchQueries` as an imperative way to refetch queries, without having to pass `options.refetchQueries` to `client.mutate`. <br/>
[@dannycochran](https://github.com/dannycochran) in [#7431](https://github.com/apollographql/apollo-client/pull/7431)
- Improve standalone `client.refetchQueries` method to support automatic detection of queries needing to be refetched. <br/>
[@benjamn](https://github.com/benjamn) in [#8000](https://github.com/apollographql/apollo-client/pull/8000)
- Fix remaining barriers to loading [`@apollo/client/core`](https://cdn.jsdelivr.net/npm/@apollo/client@3.4.0/core/+esm) as native ECMAScript modules from a CDN like [esm.run](https://www.jsdelivr.com/esm). Importing `@apollo/client` from a CDN will become possible once we move all React-related dependencies into `@apollo/client/react` in Apollo Client 4. <br/>
[@benjamn](https://github.com/benjamn) in [#8266](https://github.com/apollographql/apollo-client/issues/8266)
- `InMemoryCache` supports a new method called `batch`, which is similar to `performTransaction` but takes named options rather than positional parameters. One of these named options is an `onDirty(watch, diff)` callback, which can be used to determine which watched queries were invalidated by the `batch` operation. <br/>
[@benjamn](https://github.com/benjamn) in [#7819](https://github.com/apollographql/apollo-client/pull/7819)
- Allow `merge: true` field policy to merge `Reference` objects with non-normalized objects, and vice-versa. <br/>
[@benjamn](https://github.com/benjamn) in [#7778](https://github.com/apollographql/apollo-client/pull/7778)
- Allow identical subscriptions to be deduplicated by default, like queries. <br/>
[@jkossis](https://github.com/jkossis) in [#6910](https://github.com/apollographql/apollo-client/pull/6910)
- Always use `POST` request when falling back to sending full query with `@apollo/client/link/persisted-queries`. <br/>
[@rieset](https://github.com/rieset) in [#7456](https://github.com/apollographql/apollo-client/pull/7456)
- The `FetchMoreQueryOptions` type now takes two instead of three type parameters (`<TVariables, TData>`), thanks to using `Partial<TVariables>` instead of `K extends typeof TVariables` and `Pick<TVariables, K>`. <br/>
[@ArnaudBarre](https://github.com/ArnaudBarre) in [#7476](https://github.com/apollographql/apollo-client/pull/7476)
- Pass `variables` and `context` to a mutation's `update` function. **Note:** The type of the `update` function is now named `MutationUpdaterFunction` rather than `MutationUpdaterFn`, since the older type was [broken beyond repair](https://github.com/apollographql/apollo-client/issues/8506#issuecomment-881706613). If you are using `MutationUpdaterFn` in your own code, please use `MutationUpdaterFunction` instead. <br/>
[@jcreighton](https://github.com/jcreighton) in [#7902](https://github.com/apollographql/apollo-client/pull/7902)
- A `resultCacheMaxSize` option may be passed to the `InMemoryCache` constructor to limit the number of result objects that will be retained in memory (to speed up repeated reads), and calling `cache.reset()` now releases all such memory. <br/>
[@SofianHn](https://github.com/SofianHn) in [#8107](https://github.com/apollographql/apollo-client/pull/8107)
- Fully remove result cache entries from LRU dependency system when the corresponding entities are removed from `InMemoryCache` by eviction, or by any other means. <br/>
[@sofianhn](https://github.com/sofianhn) and [@benjamn](https://github.com/benjamn) in [#8147](https://github.com/apollographql/apollo-client/pull/8147)
- Expose missing field errors in results. <br/>
[@brainkim](github.com/brainkim) in [#8262](https://github.com/apollographql/apollo-client/pull/8262)
- Add expected/received `variables` to `No more mocked responses...` error messages generated by `MockLink`. <br/>
[@markneub](github.com/markneub) in [#8340](https://github.com/apollographql/apollo-client/pull/8340)
- The `InMemoryCache` version of the `cache.gc` method now supports additional options for removing non-essential (recomputable) result caching data. <br/>
[@benjamn](https://github.com/benjamn) in [#8421](https://github.com/apollographql/apollo-client/pull/8421)
- Suppress noisy `Missing cache result fields...` warnings by default unless `setLogVerbosity("debug")` called. <br/>
[@benjamn](https://github.com/benjamn) in [#8489](https://github.com/apollographql/apollo-client/pull/8489)
- Improve interaction between React hooks and React Fast Refresh in development. <br/>
[@andreialecu](https://github.com/andreialecu) in [#7952](https://github.com/apollographql/apollo-client/pull/7952)
### Potentially disruptive changes
- To avoid retaining sensitive information from mutation root field arguments, Apollo Client v3.4 automatically clears any `ROOT_MUTATION` fields from the cache after each mutation finishes. If you need this information to remain in the cache, you can prevent the removal by passing the `keepRootFields: true` option to `client.mutate`. `ROOT_MUTATION` result data are also passed to the mutation `update` function, so we recommend obtaining the results that way, rather than using `keepRootFields: true`, if possible. <br/>
[@benjamn](https://github.com/benjamn) in [#8280](https://github.com/apollographql/apollo-client/pull/8280)
- Internally, Apollo Client now controls the execution of development-only code using the `__DEV__` global variable, rather than `process.env.NODE_ENV`. While this change should not cause any visible differences in behavior, it will increase your minified+gzip bundle size by more than 3.5kB, unless you configure your minifier to replace `__DEV__` with a `true` or `false` constant, the same way you already replace `process.env.NODE_ENV` with a string literal like `"development"` or `"production"`. For an example of configuring a Create React App project without ejecting, see this pull request for our [React Apollo reproduction template](https://github.com/apollographql/react-apollo-error-template/pull/51). <br/>
[@benjamn](https://github.com/benjamn) in [#8347](https://github.com/apollographql/apollo-client/pull/8347)
- Internally, Apollo Client now uses namespace syntax (e.g. `import * as React from "react"`) for imports whose types are re-exported (and thus may appear in `.d.ts` files). This change should remove any need to configure `esModuleInterop` or `allowSyntheticDefaultImports` in `tsconfig.json`, but might require updating bundler configurations that specify named exports of the `react` and `prop-types` packages, to include exports like `createContext` and `createElement` ([example](https://github.com/apollographql/apollo-client/commit/16b08e1af9ba9934041298496e167aafb128c15d)). <br/>
[@devrelm](https://github.com/devrelm) in [#7742](https://github.com/apollographql/apollo-client/pull/7742)
- Respect `no-cache` fetch policy (by not reading any `data` from the cache) for `loading: true` results triggered by `notifyOnNetworkStatusChange: true`. <br />
[@jcreighton](https://github.com/jcreighton) in [#7761](https://github.com/apollographql/apollo-client/pull/7761)
- The TypeScript return types of the `getLastResult` and `getLastError` methods of `ObservableQuery` now correctly include the possibility of returning `undefined`. If you happen to be calling either of these methods directly, you may need to adjust how the calling code handles the methods' possibly-`undefined` results. <br/>
[@benjamn](https://github.com/benjamn) in [#8394](https://github.com/apollographql/apollo-client/pull/8394)
- Log non-fatal `invariant.error` message when fields are missing from result objects written into `InMemoryCache`, rather than throwing an exception. While this change relaxes an exception to be merely an error message, which is usually a backwards-compatible change, the error messages are logged in more cases now than the exception was previously thrown, and those new error messages may be worth investigating to discover potential problems in your application. The errors are not displayed for `@client`-only fields, so adding `@client` is one way to handle/hide the errors for local-only fields. Another general strategy is to use a more precise query to write specific subsets of data into the cache, rather than reusing a larger query that contains fields not present in the written `data`. <br/>
[@benjamn](https://github.com/benjamn) in [#8416](https://github.com/apollographql/apollo-client/pull/8416)
- The [`nextFetchPolicy`](https://github.com/apollographql/apollo-client/pull/6893) option for `client.watchQuery` and `useQuery` will no longer be removed from the `options` object after it has been applied, and instead will continue to be applied any time `options.fetchPolicy` is reset to another value, until/unless the `options.nextFetchPolicy` property is removed from `options`. <br/>
[@benjamn](https://github.com/benjamn) in [#8465](https://github.com/apollographql/apollo-client/pull/8465)
- The `fetchMore`, `subscribeToMore`, and `updateQuery` functions returned from the `useQuery` hook may now return undefined in edge cases where the functions are called when the component is unmounted <br/> [@noghartt](https://github.com/noghartt) in [#7980](https://github.com/apollographql/apollo-client/pull/7980).
### Bug fixes
- In Apollo Client 2.x, a `refetch` operation would always replace existing data in the cache. With the introduction of field policy `merge` functions in Apollo Client 3, existing field values could be inappropriately combined with incoming field values by a custom `merge` function that does not realize a `refetch` has happened.
To give you more control over this behavior, we have introduced an `overwrite?: boolean = false` option for `cache.writeQuery` and `cache.writeFragment`, and an option called `refetchWritePolicy?: "merge" | "overwrite"` for `client.watchQuery`, `useQuery`, and other functions that accept `WatchQueryOptions`. You can use these options to make sure any `merge` functions involved in cache writes for `refetch` operations get invoked with `undefined` as their first argument, which simulates the absence of any existing data, while still giving the `merge` function a chance to determine the internal representation of the incoming data.
The default behaviors are `overwrite: true` and `refetchWritePolicy: "overwrite"`, which restores the Apollo Client 2.x behavior, but (if this change causes any problems for your application) you can easily recover the previous merging behavior by setting a default value for `refetchWritePolicy` in `defaultOptions.watchQuery`:
```ts
new ApolloClient({
defaultOptions: {
watchQuery: {
refetchWritePolicy: "merge",
},
},
})
```
[@benjamn](https://github.com/benjamn) in [#7810](https://github.com/apollographql/apollo-client/pull/7810)
- Make sure the `MockedResponse` `ResultFunction` type is re-exported. <br/>
[@hwillson](https://github.com/hwillson) in [#8315](https://github.com/apollographql/apollo-client/pull/8315)
- Fix polling when used with `skip`. <br/>
[@brainkim](https://github.com/brainkim) in [#8346](https://github.com/apollographql/apollo-client/pull/8346)
- `InMemoryCache` now coalesces `EntityStore` updates to guarantee only one `store.merge(id, fields)` call per `id` per cache write. <br/>
[@benjamn](https://github.com/benjamn) in [#8372](https://github.com/apollographql/apollo-client/pull/8372)
- Fix polling when used with `<React.StrictMode>`. <br/>
[@brainkim](https://github.com/brainkim) in [#8414](https://github.com/apollographql/apollo-client/pull/8414)
- Fix the React integration logging `Warning: Can't perform a React state update on an unmounted component`. <br/>
[@wuarmin](https://github.com/wuarmin) in [#7745](https://github.com/apollographql/apollo-client/pull/7745)
- Make `ObservableQuery#getCurrentResult` always call `queryInfo.getDiff()`. <br/>
[@benjamn](https://github.com/benjamn) in [#8422](https://github.com/apollographql/apollo-client/pull/8422)
- Make `readField` default to reading from current object only when the `from` option/argument is actually omitted, not when `from` is passed to `readField` with an undefined value. A warning will be printed when this situation occurs. <br/>
[@benjamn](https://github.com/benjamn) in [#8508](https://github.com/apollographql/apollo-client/pull/8508)
- The `fetchMore`, `subscribeToMore`, and `updateQuery` functions no longer throw `undefined` errors <br/> [@noghartt](https://github.com/noghartt) in [#7980](https://github.com/apollographql/apollo-client/pull/7980).
## Apollo Client 3.3.21
### Bug fixes
- Fix race condition in `@apollo/client/link/context` that could leak subscriptions if the subscription is cancelled before `operation.setContext` is called. <br/>
[@sofianhn](https://github.com/sofianhn) in [#8399](https://github.com/apollographql/apollo-client/pull/8399)
- Prefer `existing.pageInfo.startCursor` and `endCursor` (if defined) in `read` function of `relayStylePagination` policies. <br/>
[@benjamn](https://github.com/benjamn) in [#8438](https://github.com/apollographql/apollo-client/pull/8438)
### Improvements
- Normalize user-provided `HttpLink` headers by lower-casing their names. <br/>
[@benjamn](https://github.com/benjamn) in [#8449](https://github.com/apollographql/apollo-client/pull/8449)
## Apollo Client 3.3.20
### Bug fixes
- Fix policy merging bug when calling `cache.policies.addTypePolicies` multiple times for the same type policy. <br/>
[@Banou26](https://github.com/Banou26) in [#8361](https://github.com/apollographql/apollo-client/pull/8361)
## Apollo Client 3.3.19
### Bug fixes
- Use `export ... from` syntax to re-export `graphql-tag` named exports, making tree-shaking easier for some bundlers. <br/>
[@benjamn](https://github.com/benjamn) in [#8221](https://github.com/apollographql/apollo-client/pull/8221)
### Documentation
- Replace Spectrum references with [community.apollographql.com](https://community.apollographql.com). <br/>
[@hwillson](https://github.com/hwillson) in [#8238](https://github.com/apollographql/apollo-client/pull/8238)
## Apollo Client 3.3.18
### Bug fixes
- Add `"sideEffects": false` to all generated/published `package.json` files, to improve dead code elimination for nested entry points like `@apollo/client/cache`. <br/>
[@benjamn](https://github.com/benjamn) in [#8213](https://github.com/apollographql/apollo-client/pull/8213)
## Apollo Client 3.3.17
### Bug fixes
- Make `useReactiveVar(rv)` recheck the latest `rv()` value in its `useEffect` callback, and immediately update state if the value has already changed, rather than calling `rv.onNextChange(setValue)` to listen for future changes. <br/>
[@benjamn](https://github.com/benjamn) in [#8135](https://github.com/apollographql/apollo-client/pull/8135)
## Apollo Client 3.3.16
### Bug fixes
- Prevent `undefined` mutation result in `useMutation`. <br/>
[@jcreighton](https://github.com/jcreighton) in [#8018](https://github.com/apollographql/apollo-client/pull/8018)
- Fix `useReactiveVar` not rerendering for successive synchronous calls. <br/>
[@brainkim](https://github.com/brainkim) in [#8022](https://github.com/apollographql/apollo-client/pull/8022)
- Support `batchDebounce` option for `BatchLink` and `BatchHttpLink`. <br/>
[@dannycochran](https://github.com/dannycochran) in [#8024](https://github.com/apollographql/apollo-client/pull/8024)
## Apollo Client 3.3.15
- Increment `queryInfo.lastRequestId` only when making a network request through the `ApolloLink` chain, rather than every time `fetchQueryByPolicy` is called. <br/>
[@dannycochran](https://github.com/dannycochran) in [#7956](https://github.com/apollographql/apollo-client/pull/7956)
- During server-side rendering, allow initial `useQuery` calls to return final `{ loading: false, data }` results when the cache already contains the necessary data. <br/>
[@benjamn](https://github.com/benjamn) in [#7983](https://github.com/apollographql/apollo-client/pull/7983)
## Apollo Client 3.3.14
### Improvements
- Adjust TypeScript types to allow `keyFields` and `keyArgs` functions to return `false`. <br/>
[@CarsonF](https://github.com/CarsonF) and [@benjamn](https://github.com/benjamn) in [#7900](https://github.com/apollographql/apollo-client/pull/7900)
### Bug fixes
- Prevent `RenderPromises` memory leak by calling `renderPromises.clear()` after `getMarkupFromTree` finishes. <br/>
[@benjamn](https://github.com/benjamn) in [#7943](https://github.com/apollographql/apollo-client/pull/7943)
- Cancel pending notify timeout when stopping a `QueryInfo` object. <br/>
[@hollandThomas](https://github.com/hollandThomas) in [#7935](https://github.com/apollographql/apollo-client/pull/7935)
- Fix infinite rendering bug related to `useSubscription`. <br/>
[@brainkim](https://github.com/brainkim) in [#7917](https://github.com/apollographql/apollo-client/pull/7917)
## Apollo Client 3.3.13
### Improvements
- Add missing `context` option to `useSubscription`. <br />
[@jcreighton](https://github.com/jcreighton) in [#7860](https://github.com/apollographql/apollo-client/pull/7860)
- Remove unnecessary TypeScript global `Observable<T>["@@observable"]` method declaration. <br/>
[@benjamn](https://github.com/benjamn) in [#7888](https://github.com/apollographql/apollo-client/pull/7888)
- Prevent skipped/observerless `ObservableQuery`s from being refetched by `refetchQueries`. <br/>
[@dannycochran](https://github.com/dannycochran) in [#7877](https://github.com/apollographql/apollo-client/pull/7877)
## Apollo Client 3.3.12
### Bug fixes
- Maintain serial ordering of `asyncMap` mapping function calls, and prevent potential unhandled `Promise` rejection errors. <br/>
[@benjamn](https://github.com/benjamn) in [#7818](https://github.com/apollographql/apollo-client/pull/7818)
- Relax incompatible `children?: React.ReactElement` field type in `MockedProviderProps` interface. <br/>
[@kevinperaza](https://github.com/kevinperaza) in [#7833](https://github.com/apollographql/apollo-client/pull/7833)
## Apollo Client 3.3.11
### Bug fixes
- Fix `useLazyQuery` `forceUpdate` loop regression introduced by [#7655](https://github.com/apollographql/apollo-client/pull/7655) in version 3.3.10. <br/>
[@benjamn](https://github.com/benjamn) in [#7715](https://github.com/apollographql/apollo-client/pull/7715)
## Apollo Client 3.3.10
### Bug fixes
- Revert PR [#7276](https://github.com/apollographql/apollo-client/pull/7276), but test that garbage collection reclaims torn-down `ObservableQuery` objects. <br/>
[@benjamn](https://github.com/benjamn) in [#7695](https://github.com/apollographql/apollo-client/pull/7695)
- Reset `QueryInfo.diff` and `QueryInfo.dirty` after canceling notify timeout in `QueryInfo.markResult` and `QueryInfo.markError`. <br/>
[@jcreighton](https://github.com/jcreighton) in [#7696](https://github.com/apollographql/apollo-client/pull/7696)
### Improvements
- Avoid calling `forceUpdate` when component is unmounted. <br/>
[@DylanVann](https://github.com/DylanVann) in [#7655](https://github.com/apollographql/apollo-client/pull/7655)
- The `codemods/` top-level directory has been moved into the `scripts/` directory. <br/>
[@benjamn](https://github.com/benjamn) in [#7675](https://github.com/apollographql/apollo-client/pull/7675)
## Apollo Client 3.3.9
### Bug Fixes
- Prevent reactive variables from retaining otherwise unreachable `InMemoryCache` objects. <br/>
[@benjamn](https://github.com/benjamn) in [#7661](https://github.com/apollographql/apollo-client/pull/7661)
### Improvements
- The [`graphql-tag`](https://www.npmjs.com/package/graphql-tag) dependency has been updated to version 2.12.0, after converting its repository to use TypeScript and ECMAScript module syntax. There should be no visible changes in behavior, though the internal changes seemed significant enough to mention here. <br/>
[@abdonrd](https://github.com/abdonrd) in [graphql-tag#273](https://github.com/apollographql/graphql-tag/pull/273) and
[@PowerKiKi](https://github.com/PowerKiKi) in [graphql-tag#325](https://github.com/apollographql/graphql-tag/pull/325)
## Apollo Client 3.3.8
### Bug Fixes
- Catch updates in `useReactiveVar` with an additional check. <br/>
[@jcreighton](https://github.com/jcreighton) in [#7652](https://github.com/apollographql/apollo-client/pull/7652)
- Reactivate forgotten reactive variables whenever `InMemoryCache` acquires its first watcher. <br/>
[@benjamn](https://github.com/benjamn) in [#7657](https://github.com/apollographql/apollo-client/pull/7657)
- Backport `Symbol.species` fix for `Concast` and `ObservableQuery` from [`release-3.4`](https://github.com/apollographql/apollo-client/pull/7399), fixing subscriptions in React Native Android when the Hermes JavaScript engine is enabled (among other benefits). <br/>
[@benjamn](https://github.com/benjamn) in [#7403](https://github.com/apollographql/apollo-client/pull/7403) and [#7660](https://github.com/apollographql/apollo-client/pull/7660)
## Apollo Client 3.3.7
### Bug Fixes
- Fix a regression due to [#7310](https://github.com/apollographql/apollo-client/pull/7310) that caused `loading` always to be `true` for `skip: true` results during server-side rendering. <br/>
[@rgrove](https://github.com/rgrove) in [#7567](https://github.com/apollographql/apollo-client/pull/7567)
- Avoid duplicate `useReactiveVar` listeners when rendering in `React.StrictMode`. <br/>
[@jcreighton](https://github.com/jcreighton) in [#7581](https://github.com/apollographql/apollo-client/pull/7581)
### Improvements
- Set `displayName` on `ApolloContext` objects for easier debugging. <br/>
[@dulmandakh](https://github.com/dulmandakh) in [#7550](https://github.com/apollographql/apollo-client/pull/7550)
## Apollo Client 3.3.6
### Bug Fixes
- Immediately apply `queryType: true`, `mutationType: true`, and `subscriptionType: true` type policies, rather than waiting for the first time the policy is used, fixing a [regression](https://github.com/apollographql/apollo-client/issues/7443) introduced by [#7065](https://github.com/apollographql/apollo-client/pull/7065). <br/>
[@benjamn](https://github.com/benjamn) in [#7463](https://github.com/apollographql/apollo-client/pull/7463)
- Check that `window` is defined even when `connectToDevTools` is `true`. <br/>
[@yasupeke](https://github.com/yasupeke) in [#7434](https://github.com/apollographql/apollo-client/pull/7434)
### Improvements
- Replace stray `console.debug` (undefined in React Native) with `invariant.log`. <br/>
[@benjamn](https://github.com/benjamn) in [#7454](https://github.com/apollographql/apollo-client/pull/7454)
- Suggest Firefox Apollo DevTools as well as the Chrome extension. <br/>
[@benjamn](https://github.com/benjamn) in [#7461](https://github.com/apollographql/apollo-client/pull/7461)
## Apollo Client 3.3.5
### Improvements
- Restore `client.version` property, reflecting the current `@apollo/client` version from `package.json`. <br/>
[@benjamn](https://github.com/benjamn) in [#7448](https://github.com/apollographql/apollo-client/pull/7448)
## Apollo Client 3.3.4
### Improvements
- Update `ts-invariant` to avoid potential [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)-violating `Function` fallback, thanks to [a clever new `globalThis` polyfill technique](https://mathiasbynens.be/notes/globalthis). <br/>
[@benjamn](https://github.com/benjamn) in [#7414](https://github.com/apollographql/apollo-client/pull/7414)
## Apollo Client 3.3.3
### Bug fixes
- Make the `observer` parameter of `ApolloLink#onError` optional, fixing an unnecessary breaking change for any code that called `onError` directly. <br/>
[@benjamn](https://github.com/benjamn) in [#7407](https://github.com/apollographql/apollo-client/pull/7407)
## Apollo Client 3.3.2
> ⚠️ **Note:** This version of `@apollo/client` contains no behavioral changes since version 3.3.1
### Documentation
- The [Pagination](https://www.apollographql.com/docs/react/pagination/overview/) article has been completely rewritten (and split into multiple pages) to cover Apollo Client 3 field policies. <br/>
[@benjamn](https://github.com/benjamn) and [@StephenBarlow](https://github.com/StephenBarlow) in [#7175](https://github.com/apollographql/apollo-client/pull/7175)
- Revamp [local state tutorial chapter](https://www.apollographql.com/docs/tutorial/local-state/) for Apollo Client 3, including reactive variables. <br/>
[@StephenBarlow](https://github.com/StephenBarlow) in [`apollographql@apollo#1050`](https://github.com/apollographql/apollo/pull/1050)
- Add examples of using `ApolloLink` to modify response data asynchronously. <br/>
[@alichry](https://github.com/alichry) in [#7332](https://github.com/apollographql/apollo-client/pull/7332)
- Consolidate separate v2.4, v2.5, and v2.6 documentation versions into one v2 version. <br/>
[@jgarrow](https://github.com/jgarrow) in [#7378](https://github.com/apollographql/apollo-client/pull/7378)
## Apollo Client 3.3.1
### Bug Fixes
- Revert back to `default`-importing `React` internally, rather than using a namespace import. <br/>
[@benjamn](https://github.com/benjamn) in [113475b1](https://github.com/apollographql/apollo-client/commit/113475b163a19a40a67465c11e8e6f48a1de7e76)
## Apollo Client 3.3.0
### Bug Fixes
- Update `@wry/equality` to consider undefined properties equivalent to missing properties. <br/>
[@benjamn](https://github.com/benjamn) in [#7108](https://github.com/apollographql/apollo-client/pull/7108)
- Prevent memory leaks involving unused `onBroadcast` function closure created in `ApolloClient` constructor. <br/>
[@kamilkisiela](https://github.com/kamilkisiela) in [#7161](https://github.com/apollographql/apollo-client/pull/7161)
- Provide default empty cache object for root IDs like `ROOT_QUERY`, to avoid differences in behavior before/after `ROOT_QUERY` data has been written into `InMemoryCache`. <br/>
[@benjamn](https://github.com/benjamn) in [#7100](https://github.com/apollographql/apollo-client/pull/7100)
- Cancel `queryInfo.notifyTimeout` in `QueryInfo#markResult` to prevent unnecessary network requests when using a `FetchPolicy` of `cache-and-network` or `network-only` in a React component with multiple `useQuery` calls. <br/>
[@benjamn](https://github.com/benjamn) in [#7347](https://github.com/apollographql/apollo-client/pull/7347)
### Potentially breaking changes
- Ensure `cache.readQuery` and `cache.readFragment` always return `TData | null`, instead of throwing `MissingFieldError` exceptions when missing fields are encountered. <br/>
[@benjamn](https://github.com/benjamn) in [#7098](https://github.com/apollographql/apollo-client/pull/7098)
> Since this change converts prior exceptions to `null` returns, and since `null` was already a possible return value according to the `TData | null` return type, we are confident this change will be backwards compatible (as long as `null` was properly handled before).
- `HttpLink` will now automatically strip any unused `variables` before sending queries to the GraphQL server, since those queries are very likely to fail validation, according to the [All Variables Used](https://spec.graphql.org/draft/#sec-All-Variables-Used) rule in the GraphQL specification. If you depend on the preservation of unused variables, you can restore the previous behavior by passing `includeUnusedVariables: true` to the `HttpLink` constructor (which is typically passed as `options.link` to the `ApolloClient` constructor). <br/>
[@benjamn](https://github.com/benjamn) in [#7127](https://github.com/apollographql/apollo-client/pull/7127)
- Ensure `MockLink` (used by `MockedProvider`) returns mock configuration errors (e.g. `No more mocked responses for the query ...`) through the Link's `Observable`, instead of throwing them. These errors are now available through the `error` property of a result. <br/>
[@hwillson](https://github.com/hwillson) in [#7110](https://github.com/apollographql/apollo-client/pull/7110)
> Returning mock configuration errors through the Link's `Observable` was the default behavior in Apollo Client 2.x. We changed it for 3, but the change has been problematic for those looking to migrate from 2.x to 3. We've decided to change this back with the understanding that not many people want or are relying on `MockLink`'s throwing exception approach. If you want to change this functionality, you can define custom error handling through `MockLink.setOnError`.
- Unsubscribing the last observer from an `ObservableQuery` will once again unsubscribe from the underlying network `Observable` in all cases, as in Apollo Client 2.x, allowing network requests to be cancelled by unsubscribing. <br/>
[@javier-garcia-meteologica](https://github.com/javier-garcia-meteologica) in [#7165](https://github.com/apollographql/apollo-client/pull/7165) and [#7170](https://github.com/apollographql/apollo-client/pull/7170).
- The independent `QueryBaseOptions` and `ModifiableWatchQueryOptions` interface supertypes have been eliminated, and their fields are now defined by `QueryOptions`. <br/>
[@DCtheTall](https://github.com/DCtheTall) in [#7136](https://github.com/apollographql/apollo-client/pull/7136)
- Internally, Apollo Client now avoids nested imports from the `graphql` package, importing everything from the top-level package instead. For example,
```ts
import { visit } from "graphql/language/visitor"
```
is now just
```ts
import { visit } from "graphql"
```
Since the `graphql` package uses `.mjs` modules, your bundler may need to be configured to recognize `.mjs` files as ECMAScript modules rather than CommonJS modules. <br/>
[@benjamn](https://github.com/benjamn) in [#7185](https://github.com/apollographql/apollo-client/pull/7185)
### Improvements
- Support inheritance of type and field policies, according to `possibleTypes`. <br/>
[@benjamn](https://github.com/benjamn) in [#7065](https://github.com/apollographql/apollo-client/pull/7065)
- Allow configuring custom `merge` functions, including the `merge: true` and `merge: false` shorthands, in type policies as well as field policies. <br/>
[@benjamn](https://github.com/benjamn) in [#7070](https://github.com/apollographql/apollo-client/pull/7070)
- The verbosity of Apollo Client console messages can be globally adjusted using the `setLogVerbosity` function:
```ts
import { setLogVerbosity } from "@apollo/client";
setLogVerbosity("log"); // display all messages
setLogVerbosity("warn"); // display only warnings and errors (default)
setLogVerbosity("error"); // display only errors
setLogVerbosity("silent"); // hide all console messages
```
Remember that all logs, warnings, and errors are hidden in production. <br/>
[@benjamn](https://github.com/benjamn) in [#7226](https://github.com/apollographql/apollo-client/pull/7226)
- Modifying `InMemoryCache` fields that have `keyArgs` configured will now invalidate only the field value with matching key arguments, rather than invalidating all field values that share the same field name. If `keyArgs` has not been configured, the cache must err on the side of invalidating by field name, as before. <br/>
[@benjamn](https://github.com/benjamn) in [#7351](https://github.com/apollographql/apollo-client/pull/7351)
- Shallow-merge `options.variables` when combining existing or default options with newly-provided options, so new variables do not completely overwrite existing variables. <br/>
[@amannn](https://github.com/amannn) in [#6927](https://github.com/apollographql/apollo-client/pull/6927)
- Avoid displaying `Cache data may be lost...` warnings for scalar field values that happen to be objects, such as JSON data. <br/>
[@benjamn](https://github.com/benjamn) in [#7075](https://github.com/apollographql/apollo-client/pull/7075)
- In addition to the `result.data` property, `useQuery` and `useLazyQuery` will now provide a `result.previousData` property, which can be useful when a network request is pending and `result.data` is undefined, since `result.previousData` can be rendered instead of rendering an empty/loading state. <br/>
[@hwillson](https://github.com/hwillson) in [#7082](https://github.com/apollographql/apollo-client/pull/7082)
- Passing `validate: true` to the `SchemaLink` constructor will enable validation of incoming queries against the local schema before execution, returning validation errors in `result.errors`, just like a non-local GraphQL endpoint typically would. <br/>
[@amannn](https://github.com/amannn) in [#7094](https://github.com/apollographql/apollo-client/pull/7094)
- Allow optional arguments in `keyArgs: [...]` arrays for `InMemoryCache` field policies. <br/>
[@benjamn](https://github.com/benjamn) in [#7109](https://github.com/apollographql/apollo-client/pull/7109)
- Avoid registering `QueryPromise` when `skip` is `true` during server-side rendering. <br/>
[@izumin5210](https://github.com/izumin5210) in [#7310](https://github.com/apollographql/apollo-client/pull/7310)
- `ApolloCache` objects (including `InMemoryCache`) may now be associated with or disassociated from individual reactive variables by calling `reactiveVar.attachCache(cache)` and/or `reactiveVar.forgetCache(cache)`. <br/>
[@benjamn](https://github.com/benjamn) in [#7350](https://github.com/apollographql/apollo-client/pull/7350)
## Apollo Client 3.2.9
### Bug Fixes
- Revert back to `default`-importing `React` internally, rather than using a namespace import. <br/>
[@benjamn](https://github.com/benjamn) in [113475b1](https://github.com/apollographql/apollo-client/commit/113475b163a19a40a67465c11e8e6f48a1de7e76)
## Apollo Client 3.2.8
### Bug Fixes
- Ensure `sourcesContent` array is properly defined in `.js.map` files generated by `tsc`. <br/>
[@benjamn](https://github.com/benjamn) in [#7371](https://github.com/apollographql/apollo-client/pull/7371)
- Avoid relying on global `Symbol` properties in `ApolloContext.ts`. <br/>
[@benjamn](https://github.com/benjamn) in [#7371](https://github.com/apollographql/apollo-client/pull/7371)
## Apollo Client 3.2.7
### Bug Fixes
- Revert updating `symbol-observable` from version 2.x to version 3, which caused TypeScript errors with some `@types/node` versions, especially in Angular applications. <br/>
[@benjamn](https://github.com/benjamn) in [#7340](https://github.com/apollographql/apollo-client/pull/7340)
## Apollo Client 3.2.6
### Bug Fixes
- Always consider singleton IDs like `ROOT_QUERY` and `ROOT_MUTATION` to be root IDs during `cache.gc` garbage collection, regardless of whether they have been retained or released. <br/>
[@benjamn](https://github.com/benjamn) in [#7333](https://github.com/apollographql/apollo-client/pull/7333)
- Use optional chaining syntax (`this.currentObservable?.refetch`) in React `refetch` wrapper function to avoid crashing when an unmounted component is accidentally refetched. <br/>
[@tm1000](https://github.com/tm1000) in [#6314](https://github.com/apollographql/apollo-client/pull/6314) and
[@linmic](https://github.com/linmic) in [#7186](https://github.com/apollographql/apollo-client/pull/7186)
### Improvements
- Handle older `react-apollo` package in `codemods/ac2-to-ac3/imports.js` migration script. <br/>
[@tm1000](https://github.com/tm1000) in [#7216](https://github.com/apollographql/apollo-client/pull/7216)
- Ensure `relayStylePagination` preserves `pageInfo.{start,end}Cursor` if `edges` is missing or empty. <br/>
[@beaucollins](https://github.com/beaucollins) in [#7224](https://github.com/apollographql/apollo-client/pull/7224)
## Apollo Client 3.2.5
### Improvements
- Move `terser` dependency from `dependencies` to `devDependencies`. <br/>
[@SimenB](https://github.com/SimenB) in [#7188](https://github.com/apollographql/apollo-client/pull/7188)
- Avoid all sub-package imports from the `graphql` npm package. <br/>
[@stoically](https://github.com/stoically) in [#7185](https://github.com/apollographql/apollo-client/pull/7185)
## Apollo Client 3.2.4
### Improvements
- Update the `optimism` npm dependency to version 0.13.0 in order to use the new `optimistic.forget` method to fix a potential `cache.watch` memory leak. <br/>
[@benjamn](https://github.com/benjamn) in [#7157](https://github.com/apollographql/apollo-client/pull/7157)
- Consider `cache.reset` a destructive method, like `cache.evict` and `cache.modify`. <br/>
[@joshjg](https://github.com/joshjg) in [#7150](https://github.com/apollographql/apollo-client/pull/7150)
- Avoid refetching observerless queries with `reFetchObservableQueries`. <br/>
[@joshjg](https://github.com/joshjg) in [#7146](https://github.com/apollographql/apollo-client/pull/7146)
## Apollo Client 3.2.3
### Improvements
- Default `args.offset` to zero in `offsetLimitPagination`. <br/>
[@benjamn](https://github.com/benjamn) in [#7141](https://github.com/apollographql/apollo-client/pull/7141)
## Apollo Client 3.2.2
### Bug Fixes
- Undo `TEdgeWrapper` approach for `relayStylePagination`, introduced by [f41e9efc](https://github.com/apollographql/apollo-client/commit/f41e9efc9e061b80fe5019456c049a3c56661e87) in [#7023](https://github.com/apollographql/apollo-client/pull/7023), since it was an unintended breaking change for existing code that used `cache.modify` to interact with field data managed by `relayStylePagination`. <br/>
[@benjamn](https://github.com/benjamn) in [#7103](https://github.com/apollographql/apollo-client/pull/7103)
## Apollo Client 3.2.1
### Bug Fixes
- Fix `relayStylePagination` to handle the possibility that edges might be normalized `Reference` objects (uncommon). <br/>
[@anark](https://github.com/anark) and [@benjamn](https://github.com/benjamn) in [#7023](https://github.com/apollographql/apollo-client/pull/7023)
- Disable "Missing cache result fields" warnings when `returnPartialData` is `true`. <br/>
[@hwillson](https://github.com/hwillson) in [#7055](https://github.com/apollographql/apollo-client/pull/7055)
### Improvements
- Mark `subscriptions-transport-ws` `peerDependency` as optional. <br/>
[@MasterOdin](https://github.com/MasterOdin) in [#7047](https://github.com/apollographql/apollo-client/pull/7047)
## Apollo Client 3.2.0
### Bug Fixes
- Use `options.nextFetchPolicy` internally to restore original `FetchPolicy` after polling with `fetchPolicy: "network-only"`, so that polling does not interfere with normal query watching. <br/>
[@benjamn](https://github.com/benjamn) in [#6893](https://github.com/apollographql/apollo-client/pull/6893)
- Initialize `ObservableQuery` in `updateObservableQuery` even if `skip` is `true`. <br/>
[@mu29](https://github.com/mu29) in [#6999](https://github.com/apollographql/apollo-client/pull/6999)
- Prevent full reobservation of queries affected by optimistic mutation updates, while still delivering results from the cache. <br/>
[@benjamn](https://github.com/benjamn) in [#6854](https://github.com/apollographql/apollo-client/pull/6854)
### Improvements
- In TypeScript, all APIs that take `DocumentNode` parameters now may alternatively take `TypeDocumentNode<Data, Variables>`. This type has the same JavaScript representation but allows the APIs to infer the data and variable types instead of requiring you to specify types explicitly at the call site. <br/>
[@dotansimha](https://github.com/dotansimha) in [#6720](https://github.com/apollographql/apollo-client/pull/6720)
- Bring back an improved form of heuristic fragment matching, by allowing `possibleTypes` to specify subtype regular expression strings, which count as matches if the written result object has all the fields expected for the fragment. <br/>
[@benjamn](https://github.com/benjamn) in [#6901](https://github.com/apollographql/apollo-client/pull/6901)
- Allow `options.nextFetchPolicy` to be a function that takes the current `FetchPolicy` and returns a new (or the same) `FetchPolicy`, making `nextFetchPolicy` more suitable for global use in `defaultOptions.watchQuery`. <br/>
[@benjamn](https://github.com/benjamn) in [#6893](https://github.com/apollographql/apollo-client/pull/6893)
- Implement `useReactiveVar` hook for consuming reactive variables in React components. <br/>
[@benjamn](https://github.com/benjamn) in [#6867](https://github.com/apollographql/apollo-client/pull/6867)
- Move `apollo-link-persisted-queries` implementation to `@apollo/client/link/persisted-queries`. Try running our [automated imports transform](https://github.com/apollographql/apollo-client/tree/main/scripts/codemods/ac2-to-ac3) to handle this conversion, if you're using `apollo-link-persisted-queries`. <br/>
[@hwillson](https://github.com/hwillson) in [#6837](https://github.com/apollographql/apollo-client/pull/6837)
- Disable feud-stopping logic after any `cache.evict` or `cache.modify` operation. <br/>
[@benjamn](https://github.com/benjamn) in
[#6817](https://github.com/apollographql/apollo-client/pull/6817) and
[#6898](https://github.com/apollographql/apollo-client/pull/6898)
- Throw if `writeFragment` cannot identify `options.data` when no `options.id` provided. <br/>
[@jcreighton](https://github.com/jcreighton) in [#6859](https://github.com/apollographql/apollo-client/pull/6859)
- Provide `options.storage` object to `cache.modify` functions, as provided to `read` and `merge` functions. <br/>
[@benjamn](https://github.com/benjamn) in [#6991](https://github.com/apollographql/apollo-client/pull/6991)
- Allow `cache.modify` functions to return `details.INVALIDATE` (similar to `details.DELETE`) to invalidate the current field, causing affected queries to rerun, even if the field's value is unchanged. <br/>
[@benjamn](https://github.com/benjamn) in [#6991](https://github.com/apollographql/apollo-client/pull/6991)
- Support non-default `ErrorPolicy` values (that is, `"ignore"` and `"all"`, in addition to the default value `"none"`) for mutations and subscriptions, like we do for queries. <br/>
[@benjamn](https://github.com/benjamn) in [#7003](https://github.com/apollographql/apollo-client/pull/7003)
- Remove invariant forbidding a `FetchPolicy` of `cache-only` in `ObservableQuery#refetch`. <br/>
[@benjamn](https://github.com/benjamn) in [ccb0a79a](https://github.com/apollographql/apollo-client/pull/6774/commits/ccb0a79a588721f08bf87a131c31bf37fa3238e5), fixing [#6702](https://github.com/apollographql/apollo-client/issues/6702)
## Apollo Client 3.1.5
### Bug Fixes
- Make `ApolloQueryResult.data` field non-optional again. <br/>
[@benjamn](https://github.com/benjamn) in [#6997](https://github.com/apollographql/apollo-client/pull/6997)
### Improvements
- Allow querying `Connection` metadata without `args` in `relayStylePagination`. <br/>
[@anark](https://github.com/anark) in [#6935](https://github.com/apollographql/apollo-client/pull/6935)
## Apollo Client 3.1.4
### Bug Fixes
- Restrict root object identification to `ROOT_QUERY` (the ID corresponding to the root `Query` object), allowing `Mutation` and `Subscription` as user-defined types. <br/>
[@benjamn](https://github.com/benjamn) in [#6914](https://github.com/apollographql/apollo-client/pull/6914)
- Prevent crash when `pageInfo` and empty `edges` are received by `relayStylePagination`. <br/>
[@fracmak](https://github.com/fracmak) in [#6918](https://github.com/apollographql/apollo-client/pull/6918)
## Apollo Client 3.1.3
### Bug Fixes
- Consider only `result.data` (rather than all properties of `result`) when settling cache feuds. <br/>
[@danReynolds](https://github.com/danReynolds) in [#6777](https://github.com/apollographql/apollo-client/pull/6777)
### Improvements
- Provide [jscodeshift](https://www.npmjs.com/package/jscodeshift) transform for automatically converting Apollo Client 2.x `import` declarations to use Apollo Client 3.x packages. [Instructions](https://github.com/apollographql/apollo-client/tree/main/scripts/codemods/ac2-to-ac3). <br/>
[@dminkovsky](https://github.com/dminkovsky) and [@jcreighton](https://github.com/jcreighton) in [#6486](https://github.com/apollographql/apollo-client/pull/6486)
## Apollo Client 3.1.2
### Bug Fixes
- Avoid making network requests when `skip` is `true`. <br/>
[@hwillson](https://github.com/hwillson) in [#6752](https://github.com/apollographql/apollo-client/pull/6752)
### Improvements
- Allow `SchemaLink.Options.context` function to be `async` (or return a `Promise`). <br/>
[@benjamn](https://github.com/benjamn) in [#6735](https://github.com/apollographql/apollo-client/pull/6735)
## Apollo Client 3.1.1
### Bug Fixes
- Re-export cache types from `@apollo/client/core` (and thus also `@apollo/client`), again. <br/>
[@benjamn](https://github.com/benjamn) in [#6725](https://github.com/apollographql/apollo-client/pull/6725)
## Apollo Client 3.1.0
### Bug Fixes
- Rework interdependencies between `@apollo/client/*` entry points, so that CommonJS and ESM modules are supported equally well, without any duplication of shared code. <br/>
[@benjamn](https://github.com/benjamn) in [#6656](https://github.com/apollographql/apollo-client/pull/6656) and
[#6657](https://github.com/apollographql/apollo-client/pull/6657)
- Tolerate `!==` callback functions (like `onCompleted` and `onError`) in `useQuery` options, since those functions are almost always freshly evaluated each time `useQuery` is called. <br/>
[@hwillson](https://github.com/hwillson) and [@benjamn](https://github.com/benjamn) in [#6588](https://github.com/apollographql/apollo-client/pull/6588)
- Respect `context.queryDeduplication` if provided, and otherwise fall back to `client.deduplication` (as before). <br/>
[@igaloly](https://github.com/igaloly) in [#6261](https://github.com/apollographql/apollo-client/pull/6261) and
[@Kujawadl](https://github.com/Kujawadl) in [#6526](https://github.com/apollographql/apollo-client/pull/6526)
- Refactor `ObservableQuery#getCurrentResult` to reenable immediate delivery of warm cache results. As part of this refactoring, the `ApolloCurrentQueryResult` type was eliminated in favor of `ApolloQueryResult`. <br/>
[@benjamn](https://github.com/benjamn) in [#6710](https://github.com/apollographql/apollo-client/pull/6710)
- Avoid clobbering `defaultOptions` with `undefined` values. <br/>
[@benjamn](https://github.com/benjamn) in [#6715](https://github.com/apollographql/apollo-client/pull/6715)
### Improvements
- Apollo Client will no longer modify `options.fetchPolicy` unless you pass `options.nextFetchPolicy` to request an explicit change in `FetchPolicy` after the current request. Although this is technically a breaking change, `options.nextFieldPolicy` makes it easy to restore the old behavior (by passing `cache-first`). <br/>
[@benjamn](https://github.com/benjamn) in [#6712](https://github.com/apollographql/apollo-client/pull/6712), reverting [#6353](https://github.com/apollographql/apollo-client/pull/6353)
- Errors of the form `Invariant Violation: 42` thrown in production can now be looked up much more easily, by consulting the auto-generated `@apollo/client/invariantErrorCodes.js` file specific to your `@apollo/client` version. <br/>
[@benjamn](https://github.com/benjamn) in [#6665](https://github.com/apollographql/apollo-client/pull/6665)
- Make the `client` field of the `MutationResult` type non-optional, since it is always provided. <br/>
[@glasser](https://github.com/glasser) in [#6617](https://github.com/apollographql/apollo-client/pull/6617)
- Allow passing an asynchronous `options.renderFunction` to `getMarkupFromTree`. <br/>
[@richardscarrott](https://github.com/richardscarrott) in [#6576](https://github.com/apollographql/apollo-client/pull/6576)
- Ergonomic improvements for `merge` and `keyArgs` functions in cache field policies. <br/>
[@benjamn](https://github.com/benjamn) in [#6714](https://github.com/apollographql/apollo-client/pull/6714)
## Apollo Client 3.0.2
### Bug Fixes
- Avoid duplicating `graphql/execution/execute` dependency in CommonJS bundle for `@apollo/client/link/schema`, fixing `instanceof` errors reported in [#6621](https://github.com/apollographql/apollo-client/issues/6621) and [#6614](https://github.com/apollographql/apollo-client/issues/6614). <br/>
[@benjamn](https://github.com/benjamn) in [#6624](https://github.com/apollographql/apollo-client/pull/6624)
## Apollo Client 3.0.1
### Bug Fixes
- Make sure `useQuery` `onCompleted` is not fired when `skip` is `true`. <br/>
[@hwillson](https://github.com/hwillson) in [#6589](https://github.com/apollographql/apollo-client/pull/6589)
- Revert changes to `peerDependencies` in `package.json` ([#6594](https://github.com/apollographql/apollo-client/pull/6594)), which would have allowed using incompatible future versions of `graphql` and/or `react` due to overly-permissive `>=` version constraints. <br/>
[@hwillson](https://github.com/hwillson) in [#6605](https://github.com/apollographql/apollo-client/pull/6605)
# Apollo Client 3.0.0
## Improvements
> ⚠️ **Note:** As of 3.0.0, Apollo Client uses a new package name: [`@apollo/client`](https://www.npmjs.com/package/@apollo/client)
### `ApolloClient`
- **[BREAKING]** `ApolloClient` is now only available as a named export. The default `ApolloClient` export has been removed. <br/>
[@hwillson](https://github.com/hwillson) in [#5425](https://github.com/apollographql/apollo-client/pull/5425)
- **[BREAKING]** The `queryManager` property of `ApolloClient` instances is now marked as `private`, paving the way for a more aggressive redesign of its API.
- **[BREAKING]** Apollo Client will no longer deliver "stale" results to `ObservableQuery` consumers, but will instead log more helpful errors about which cache fields were missing. <br/>
[@benjamn](https://github.com/benjamn) in [#6058](https://github.com/apollographql/apollo-client/pull/6058)
- **[BREAKING]** `ApolloError`'s thrown by Apollo Client no longer prefix error messages with `GraphQL error:` or `Network error:`. To differentiate between GraphQL/network errors, refer to `ApolloError`'s public `graphQLErrors` and `networkError` properties. <br/>
[@lorensr](https://github.com/lorensr) in [#3892](https://github.com/apollographql/apollo-client/pull/3892)
- **[BREAKING]** Support for the `@live` directive has been removed, but might be restored in the future if a more thorough implementation is proposed. <br/>
[@benjamn](https://github.com/benjamn) in [#6221](https://github.com/apollographql/apollo-client/pull/6221)
- **[BREAKING]** Apollo Client 2.x allowed `@client` fields to be passed into the `link` chain if `resolvers` were not set in the constructor. This allowed `@client` fields to be passed into Links like `apollo-link-state`. Apollo Client 3 enforces that `@client` fields are local only, meaning they are no longer passed into the `link` chain, under any circumstances. <br/>
[@hwillson](https://github.com/hwillson) in [#5982](https://github.com/apollographql/apollo-client/pull/5982)
- **[BREAKING?]** Refactor `QueryManager` to make better use of observables and enforce `fetchPolicy` more reliably. <br/>
[@benjamn](https://github.com/benjamn) in [#6221](https://github.com/apollographql/apollo-client/pull/6221)
- The `updateQuery` function previously required by `fetchMore` has been deprecated with a warning, and will be removed in the next major version of Apollo Client. Please consider using a `merge` function to handle incoming data instead of relying on `updateQuery`. <br/>
[@benjamn](https://github.com/benjamn) in [#6464](https://github.com/apollographql/apollo-client/pull/6464)
- Helper functions for generating common pagination-related field policies may be imported from `@apollo/client/utilities`. The most basic helper is `concatPagination`, which emulates the concatenation behavior of typical `updateQuery` functions. A more sophisticated helper is `offsetLimitPagination`, which implements offset/limit-based pagination. If you are consuming paginated data from a Relay-friendly API, use `relayStylePagination`. Feel free to use [these helper functions](https://github.com/apollographql/apollo-client/blob/main/src/utilities/policies/pagination.ts) as inspiration for your own field policies, and/or modify them to suit your needs. <br/>
[@benjamn](https://github.com/benjamn) in [#6465](https://github.com/apollographql/apollo-client/pull/6465)
- Updated to work with `graphql@15`. <br/>
[@durchanek](https://github.com/durchanek) in [#6194](https://github.com/apollographql/apollo-client/pull/6194) and [#6279](https://github.com/apollographql/apollo-client/pull/6279) <br/>
[@hagmic](https://github.com/hagmic) in [#6328](https://github.com/apollographql/apollo-client/pull/6328)
- Apollo Link core and HTTP related functionality has been merged into `@apollo/client`. Functionality that was previously available through the `apollo-link`, `apollo-link-http-common` and `apollo-link-http` packages is now directly available from `@apollo/client` (e.g. `import { HttpLink } from '@apollo/client'`). The `ApolloClient` constructor has also been updated to accept new `uri`, `headers` and `credentials` options. If `uri` is specified, Apollo Client will take care of creating the necessary `HttpLink` behind the scenes. <br/>
[@hwillson](https://github.com/hwillson) in [#5412](https://github.com/apollographql/apollo-client/pull/5412)
- The `gql` template tag should now be imported from the `@apollo/client` package, rather than the `graphql-tag` package. Although the `graphql-tag` package still works for now, future versions of `@apollo/client` may change the implementation details of `gql` without a major version bump. <br/>
[@hwillson](https://github.com/hwillson) in [#5451](https://github.com/apollographql/apollo-client/pull/5451)
- `@apollo/client/core` can be used to import the Apollo Client core, which includes everything the main `@apollo/client` package does, except for all React related functionality. <br/>
[@kamilkisiela](https://github.com/kamilkisiela) in [#5541](https://github.com/apollographql/apollo-client/pull/5541)
- Several deprecated methods have been fully removed:
- `ApolloClient#initQueryManager`
- `QueryManager#startQuery`
- `ObservableQuery#currentResult`
- Apollo Client now supports setting a new `ApolloLink` (or link chain) after `new ApolloClient()` has been called, using the `ApolloClient#setLink` method. <br/>
[@hwillson](https://github.com/hwillson) in [#6193](https://github.com/apollographql/apollo-client/pull/6193)
- The final time a mutation `update` function is called, it can no longer accidentally read optimistic data from other concurrent mutations, which ensures the use of optimistic updates has no lasting impact on the state of the cache after mutations have finished. <br/>
[@benjamn](https://github.com/benjamn) in [#6551](https://github.com/apollographql/apollo-client/pull/6551)
- Apollo links that were previously maintained in https://github.com/apollographql/apollo-link have been merged into the Apollo Client project. They should be accessed using the new entry points listed in the [migration guide](./docs/source/migrating/apollo-client-3-migration.md). <br/>
[@hwillson](https://github.com/hwillson) in [#](TODO)
### `InMemoryCache`
> ⚠️ **Note:** `InMemoryCache` has been significantly redesigned and rewritten in Apollo Client 3.0. Please consult the [migration guide](https://www.apollographql.com/docs/react/v3.0-beta/migrating/apollo-client-3-migration/#cache-improvements) and read the new [documentation](https://www.apollographql.com/docs/react/v3.0-beta/caching/cache-configuration/) to understand everything that has been improved.
- The `InMemoryCache` constructor should now be imported directly from `@apollo/client`, rather than from a separate package. The `apollo-cache-inmemory` package is no longer supported.
> The `@apollo/client/cache` entry point can be used to import `InMemoryCache` without importing other parts of the Apollo Client codebase. <br/>
[@hwillson](https://github.com/hwillson) in [#5577](https://github.com/apollographql/apollo-client/pull/5577)
- **[BREAKING]** `FragmentMatcher`, `HeuristicFragmentMatcher`, and `IntrospectionFragmentMatcher` have all been removed. We now recommend using `InMemoryCache`’s `possibleTypes` option instead. For more information see the [Defining `possibleTypes` manually](https://www.apollographql.com/docs/react/v3.0-beta/data/fragments/#defining-possibletypes-manually) section of the docs. <br/>
[@benjamn](https://github.com/benjamn) in [#5073](https://github.com/apollographql/apollo-client/pull/5073)
- **[BREAKING]** As promised in the [Apollo Client 2.6 blog post](https://blog.apollographql.com/whats-new-in-apollo-client-2-6-b3acf28ecad1), all cache results are now frozen/immutable. <br/>
[@benjamn](https://github.com/benjamn) in [#5153](https://github.com/apollographql/apollo-client/pull/5153)
- **[BREAKING]** Eliminate "generated" cache IDs to avoid normalizing objects with no meaningful ID, significantly reducing cache memory usage. This might be a backwards-incompatible change if your code depends on the precise internal representation of normalized data in the cache. <br/>
[@benjamn](https://github.com/benjamn) in [#5146](https://github.com/apollographql/apollo-client/pull/5146)
- **[BREAKING]** `InMemoryCache` will no longer merge the fields of written objects unless the objects are known to have the same identity, and the values of fields with the same name will not be recursively merged unless a custom `merge` function is defined by a field policy for that field, within a type policy associated with the `__typename` of the parent object. <br/>
[@benjamn](https://github.com/benjamn) in [#5603](https://github.com/apollographql/apollo-client/pull/5603)
- **[BREAKING]** `InMemoryCache` now _throws_ when data with missing or undefined query fields is written into the cache, rather than just warning in development. <br/>
[@benjamn](https://github.com/benjamn) in [#6055](https://github.com/apollographql/apollo-client/pull/6055)
- **[BREAKING]** `client|cache.writeData` have been fully removed. `writeData` usage is one of the easiest ways to turn faulty assumptions about how the cache represents data internally, into cache inconsistency and corruption. `client|cache.writeQuery`, `client|cache.writeFragment`, and/or `cache.modify` can be used to update the cache. <br/>
[@benjamn](https://github.com/benjamn) in [#5923](https://github.com/apollographql/apollo-client/pull/5923)
- `InMemoryCache` now supports tracing garbage collection and eviction. Note that the signature of the `evict` method has been simplified in a potentially backwards-incompatible way. <br/>
[@benjamn](https://github.com/benjamn) in [#5310](https://github.com/apollographql/apollo-client/pull/5310)
- **[beta-BREAKING]** Please note that the `cache.evict` method now requires `Cache.EvictOptions`, though it previously supported positional arguments as well. <br/>
[@danReynolds](https://github.com/danReynolds) in [#6141](https://github.com/apollographql/apollo-client/pull/6141)
[@benjamn](https://github.com/benjamn) in [#6364](https://github.com/apollographql/apollo-client/pull/6364)
- Removing an entity object using the `cache.evict` method does not automatically remove dangling references to that entity elsewhere in the cache, but dangling references will be automatically filtered from lists whenever those lists are read from the cache. You can define a custom field `read` function to customize this behavior. See [#6412](https://github.com/apollographql/apollo-client/pull/6412), [#6425](https://github.com/apollographql/apollo-client/pull/6425), and [#6454](https://github.com/apollographql/apollo-client/pull/6454) for further explanation.
- Cache methods that would normally trigger a broadcast, like `cache.evict`, `cache.writeQuery`, and `cache.writeFragment`, can now be called with a named options object, which supports a `broadcast: boolean` property that can be used to silence the broadcast, for situations where you want to update the cache multiple times without triggering a broadcast each time. <br/>
[@benjamn](https://github.com/benjamn) in [#6288](https://github.com/apollographql/apollo-client/pull/6288)
- `InMemoryCache` now `console.warn`s in development whenever non-normalized data is dangerously overwritten, with helpful links to documentation about normalization and custom `merge` functions. <br/>
[@benjamn](https://github.com/benjamn) in [#6372](https://github.com/apollographql/apollo-client/pull/6372)
- The result caching system (introduced in [#3394](https://github.com/apollographql/apollo-client/pull/3394)) now tracks dependencies at the field level, rather than at the level of whole entity objects, allowing the cache to return identical (`===`) results much more often than before. <br/>
[@benjamn](https://github.com/benjamn) in [#5617](https://github.com/apollographql/apollo-client/pull/5617)
- `InMemoryCache` now has a method called `modify` which can be used to update the value of a specific field within a specific entity object:
```ts
cache.modify({
id: cache.identify(post),
fields: {
comments(comments: Reference[], { readField }) {
return comments.filter(comment => idToRemove !== readField("id", comment));
},
},
});
```
This API gracefully handles cases where multiple field values are associated with a single field name, and also removes the need for updating the cache by reading a query or fragment, modifying the result, and writing the modified result back into the cache. Behind the scenes, the `cache.evict` method is now implemented in terms of `cache.modify`. <br/>
[@benjamn](https://github.com/benjamn) in [#5909](https://github.com/apollographql/apollo-client/pull/5909)
and [#6178](https://github.com/apollographql/apollo-client/pull/6178)
- `InMemoryCache` provides a new API for storing client state that can be updated from anywhere:
```ts
import { makeVar } from "@apollo/client"
const v = makeVar(123)
console.log(v()) // 123
console.log(v(v() + 1)) // 124
console.log(v()) // 124
v("asdf") // TS type error
```
These variables are _reactive_ in the sense that updating their values invalidates any previously cached query results that depended on the old values. <br/>
[@benjamn](https://github.com/benjamn) in
[#5799](https://github.com/apollographql/apollo-client/pull/5799),
[#5976](https://github.com/apollographql/apollo-client/pull/5976), and
[#6512](https://github.com/apollographql/apollo-client/pull/6512)
- Various cache read and write performance optimizations, cutting read and write times by more than 50% in larger benchmarks. <br/>
[@benjamn](https://github.com/benjamn) in [#5948](https://github.com/apollographql/apollo-client/pull/5948)
- The `cache.readQuery` and `cache.writeQuery` methods now accept an `options.id` string, which eliminates most use cases for `cache.readFragment` and `cache.writeFragment`, and skips the implicit conversion of fragment documents to query documents performed by `cache.{read,write}Fragment`. <br/>
[@benjamn](https://github.com/benjamn) in [#5930](https://github.com/apollographql/apollo-client/pull/5930)
- Support `cache.identify(entity)` for easily computing entity ID strings. <br/>
[@benjamn](https://github.com/benjamn) in [#5642](https://github.com/apollographql/apollo-client/pull/5642)
- Support eviction of specific entity fields using `cache.evict(id, fieldName)`. <br/>
[@benjamn](https://github.com/benjamn) in [#5643](https://github.com/apollographql/apollo-client/pull/5643)
- Make `InMemoryCache#evict` remove data from all `EntityStore` layers. <br/>
[@benjamn](https://github.com/benjamn) in [#5773](https://github.com/apollographql/apollo-client/pull/5773)
- Stop paying attention to `previousResult` in `InMemoryCache`. <br/>
[@benjamn](https://github.com/benjamn) in [#5644](https://github.com/apollographql/apollo-client/pull/5644)
- Improve optimistic update performance by limiting cache key diversity. <br/>
[@benjamn](https://github.com/benjamn) in [#5648](https://github.com/apollographql/apollo-client/pull/5648)
- Custom field `read` functions can read from neighboring fields using the `readField(fieldName)` helper, and may also read fields from other entities by calling `readField(fieldName, objectOrReference)`. <br/>
[@benjamn](https://github.com/benjamn) in [#5651](https://github.com/apollographql/apollo-client/pull/5651)
- Expose cache `modify` and `identify` to the mutate `update` function. <br/>
[@hwillson](https://github.com/hwillson) in [#5956](https://github.com/apollographql/apollo-client/pull/5956)
- Add a default `gc` implementation to `ApolloCache`. <br/>
[@justinwaite](https://github.com/justinwaite) in [#5974](https://github.com/apollographql/apollo-client/pull/5974)
### React
- **[BREAKING]** The `QueryOptions`, `MutationOptions`, and `SubscriptionOptions` React Apollo interfaces have been renamed to `QueryDataOptions`, `MutationDataOptions`, and `SubscriptionDataOptions` (to avoid conflicting with similarly named and exported Apollo Client interfaces).
- **[BREAKING]** Results with `loading: true` will no longer redeliver previous data, though they may provide partial data from the cache, when available. <br/>
[@benjamn](https://github.com/benjamn) in [#6566](https://github.com/apollographql/apollo-client/pull/6566)
- **[BREAKING?]** Remove `fixPolyfills.ts`, except when bundling for React Native. If you have trouble with `Map` or `Set` operations due to frozen key objects in React Native, either update React Native to version 0.59.0 (or 0.61.x, if possible) or investigate why `fixPolyfills.native.js` is not included in your bundle. <br/>
[@benjamn](https://github.com/benjamn) in [#5962](https://github.com/apollographql/apollo-client/pull/5962)
- The contents of the `@apollo/react-hooks` package have been merged into `@apollo/client`, enabling the following all-in-one `import`:
```ts
import { ApolloClient, ApolloProvider, useQuery } from '@apollo/client';
```
[@hwillson](https://github.com/hwillson) in [#5357](https://github.com/apollographql/apollo-client/pull/5357)
- React SSR features (previously accessed via `@apollo/react-ssr`) can now be accessed from the separate Apollo Client entry point of `@apollo/client/react/ssr`. These features are not included in the default `@apollo/client` bundle. <br/>
[@hwillson](https://github.com/hwillson) in [#6499](https://github.com/apollographql/apollo-client/pull/6499)
### General
- **[BREAKING]** Removed `graphql-anywhere` since it's no longer used by Apollo Client. <br/>
[@hwillson](https://github.com/hwillson) in [#5159](https://github.com/apollographql/apollo-client/pull/5159)
- **[BREAKING]** Removed `apollo-boost` since Apollo Client 3.0 provides a boost like getting started experience out of the box. <br/>
[@hwillson](https://github.com/hwillson) in [#5217](https://github.com/apollographql/apollo-client/pull/5217)
- **[BREAKING]** We are no longer exporting certain (intended to be) internal utilities. If you are depending on some of the lesser known exports from `apollo-cache`, `apollo-cache-inmemory`, or `apollo-utilities`, they may no longer be available from `@apollo/client`. <br/>
[@hwillson](https://github.com/hwillson) in [#5437](https://github.com/apollographql/apollo-client/pull/5437) and [#5514](https://github.com/apollographql/apollo-client/pull/5514)
> Utilities that were previously externally available through the `apollo-utilities` package are now only available by importing from `@apollo/client/utilities`. <br/>
[@hwillson](https://github.com/hwillson) in [#5683](https://github.com/apollographql/apollo-client/pull/5683)
- Make sure all `graphql-tag` public exports are re-exported. <br/>
[@hwillson](https://github.com/hwillson) in [#5861](https://github.com/apollographql/apollo-client/pull/5861)
- Fully removed `prettier`. The Apollo Client team has decided to no longer automatically enforce code formatting across the codebase. In most cases existing code styles should be followed as much as possible, but this is not a hard and fast rule. <br/>
[@hwillson](https://github.com/hwillson) in [#5227](https://github.com/apollographql/apollo-client/pull/5227)
- Make sure `ApolloContext` plays nicely with IE11 when storing the shared context. <br/>
[@ms](https://github.com/ms) in [#5840](https://github.com/apollographql/apollo-client/pull/5840)
- Migrated React Apollo HOC and Components functionality into Apollo Client, making it accessible from `@apollo/client/react/components` and `@apollo/client/react/hoc` entry points. <br/>
[@hwillson](https://github.com/hwillson) in [#6558](https://github.com/apollographql/apollo-client/pull/6558)
- Support passing a `context` object through the link execution chain when using subscriptions. <br/>
[@sgtpepper43](https://github.com/sgtpepper43) in [#4925](https://github.com/apollographql/apollo-client/pull/4925)
- `MockSubscriptionLink` now supports multiple subscriptions. <br/>
[@dfrankland](https://github.com/dfrankland) in [#6081](https://github.com/apollographql/apollo-client/pull/6081)
### Bug Fixes
- `useMutation` adjustments to help avoid an infinite loop / too many renders issue, caused by unintentionally modifying the `useState` based mutation result directly. <br/>
[@hwillson](https://github/com/hwillson) in [#5770](https://github.com/apollographql/apollo-client/pull/5770)
- Missing `__typename` fields no longer cause the `InMemoryCache#diff` result to be marked `complete: false`, if those fields were added by `InMemoryCache#transformDocument` (which calls `addTypenameToDocument`). <br/>
[@benjamn](https://github.com/benjamn) in [#5787](https://github.com/apollographql/apollo-client/pull/5787)
- Fixed an issue that allowed `@client @export` based queries to lead to extra unnecessary network requests being fired. <br/>
[@hwillson](https://github.com/hwillson) in [#5946](https://github.com/apollographql/apollo-client/pull/5946)
- Refined `useLazyQuery` types to help prevent runtime errors. <br/>
[@benmosher](https://github.com/benmosher) in [#5935](https://github.com/apollographql/apollo-client/pull/5935)
- Make sure `@client @export` variables used in watched queries are updated each time the query receives new data that changes the value of the `@export` variable. <br/>
[@hwillson](https://github.com/hwillson) in [#5986](https://github.com/apollographql/apollo-client/pull/5986)
- Ensure `useMutation` passes a defined `errorPolicy` option into its underlying `ApolloClient.mutate()` call. <br/>
[@jamesreggio](https://github.com/jamesreggio) in [#5863](https://github.com/apollographql/apollo-client/pull/5863)
- `useQuery`: Prevent new data re-render attempts during an existing render. This helps avoid React 16.13.0's "Cannot update a component from inside the function body of a different component" warning (https://github.com/facebook/react/pull/17099). <br/>
[@hwillson](https://github.com/hwillson) in [#6107](https://github.com/apollographql/apollo-client/pull/6107)
- Expand `ApolloError` typings to include `ServerError` and `ServerParseError`. <br/>
[@dmarkow](https://github.com/dmarkow) in [#6319](https://github.com/apollographql/apollo-client/pull/6319)
- Fast responses received over the link chain will no longer conflict with `skip` settings. <br/>
[@hwillson](https://github.com/hwillson) in [#6587](https://github.com/apollographql/apollo-client/pull/6587)
## Apollo Client 2.6.8
### Apollo Client (2.6.8)
- Update the `fetchMore` type signature to accept `context`. <br/>
[@koenpunt](https://github.com/koenpunt) in [#5147](https://github.com/apollographql/apollo-client/pull/5147)
- Fix type for `Resolver` and use it in the definition of `Resolvers`. <br />
[@peoplenarthax](https://github.com/peoplenarthax) in [#4943](https://github.com/apollographql/apollo-client/pull/4943)
- Local state resolver functions now receive a `fragmentMap: FragmentMap`
object, in addition to the `field: FieldNode` object, via the `info`
parameter. <br/>
[@mjlyons](https://github.com/mjlyons) in [#5388](https://github.com/apollographql/apollo-client/pull/5388)
- Documentation updates. <br/>
[@tomquirk](https://github.com/tomquirk) in [#5645](https://github.com/apollographql/apollo-client/pull/5645) <br/>
[@Sequoia](https://github.com/Sequoia) in [#5641](https://github.com/apollographql/apollo-client/pull/5641) <br/>
[@phryneas](https://github.com/phryneas) in [#5628](https://github.com/apollographql/apollo-client/pull/5628) <br/>
[@AryanJ-NYC](https://github.com/AryanJ-NYC) in [#5560](https://github.com/apollographql/apollo-client/pull/5560)
### GraphQL Anywhere (4.2.6)
- Fix `filter` edge case involving `null`. <br/>
[@lifeiscontent](https://github.com/lifeiscontent) in [#5110](https://github.com/apollographql/apollo-client/pull/5110)
### Apollo Boost (0.4.7)
- Replace `GlobalFetch` reference with `WindowOrWorkerGlobalScope`. <br/>
[@abdonrd](https://github.com/abdonrd) in [#5373](https://github.com/apollographql/apollo-client/pull/5373)
- Add `assumeImmutableResults` typing to apollo boost `PresetConfig` interface. <br/>
[@bencoullie](https://github.com/bencoullie) in [#5571](https://github.com/apollographql/apollo-client/pull/5571)
## Apollo Client (2.6.4)
### Apollo Client (2.6.4)
- Modify `ObservableQuery` to allow queries with `notifyOnNetworkStatusChange`
to be notified when loading after an error occurs. <br />
[@jasonpaulos](https://github.com/jasonpaulos) in [#4992](https://github.com/apollographql/apollo-client/pull/4992)
- Add `graphql` as a `peerDependency` of `apollo-cache` and
`graphql-anywhere`. <br/>
[@ssalbdivad](https://github.com/ssalbdivad) in [#5081](https://github.com/apollographql/apollo-client/pull/5081)
- Documentation updates. </br>
[@raibima](https://github.com/raibima) in [#5132](https://github.com/apollographql/apollo-client/pull/5132) <br/>
[@hwillson](https://github.com/hwillson) in [#5141](https://github.com/apollographql/apollo-client/pull/5141)
## Apollo Client (2.6.3)
### Apollo Client (2.6.3)
- A new `ObservableQuery.resetQueryStoreErrors()` method is now available that
can be used to clear out `ObservableQuery` query store errors. <br/>
[@hwillson](https://github.com/hwillson) in [#4941](https://github.com/apollographql/apollo-client/pull/4941)
- Documentation updates. <br/>
[@michael-watson](https://github.com/michael-watson) in [#4940](https://github.com/apollographql/apollo-client/pull/4940) <br/>
[@hwillson](https://github.com/hwillson) in [#4969](https://github.com/apollographql/apollo-client/pull/4969)
## Apollo Client (2.6.1)
### Apollo Utilities 1.3.2
- Reimplement `isEqual` without pulling in massive `lodash.isequal`. <br/>
[@benjamn](https://github.com/benjamn) in [#4924](https://github.com/apollographql/apollo-client/pull/4924)
## Apollo Client (2.6.1)
- In all Apollo Client packages, the compilation of `lib/bundle.esm.js` to `lib/bundle.cjs.js` and `lib/bundle.umd.js` now uses Babel instead of Rollup, since Babel correctly compiles some [edge cases](https://github.com/apollographql/apollo-client/issues/4843#issuecomment-495717720) that neither Rollup nor TypeScript compile correctly. <br/>
[@benjamn](https://github.com/benjamn) in [#4911](https://github.com/apollographql/apollo-client/pull/4911)
### Apollo Cache In-Memory 1.6.1
- Pretend that `__typename` exists on the root Query when matching fragments. <br/>
[@benjamn](https://github.com/benjamn) in [#4853](https://github.com/apollographql/apollo-client/pull/4853)
### Apollo Utilities 1.3.1
- The `isEqual` function has been reimplemented using the `lodash.isequal` npm package, to better support circular references. Since the `lodash.isequal` package is already used by `react-apollo`, this change is likely to decrease total bundle size. <br/>
[@capaj](https://github.com/capaj) in [#4915](https://github.com/apollographql/apollo-client/pull/4915)
## Apollo Client (2.6.0)
- In production, `invariant(condition, message)` failures will now include
a unique error code that can be used to trace the error back to the
point of failure. <br/>
[@benjamn](https://github.com/benjamn) in [#4521](https://github.com/apollographql/apollo-client/pull/4521)
### Apollo Client 2.6.0
- If you can be sure your application code does not modify cache result objects (see `freezeResults` note below), you can unlock substantial performance improvements by communicating this assumption via
```ts
new ApolloClient({ assumeImmutableResults: true })
```
which allows the client to avoid taking defensive snapshots of past results using `cloneDeep`, as explained by [@benjamn](https://github.com/benjamn) in [#4543](https://github.com/apollographql/apollo-client/pull/4543).
- Identical overlapping queries are now deduplicated internally by `apollo-client`, rather than using the `apollo-link-dedup` package. <br/>
[@benjamn](https://github.com/benjamn) in commit [7cd8479f](https://github.com/apollographql/apollo-client/pull/4586/commits/7cd8479f27ce38930f122e4f703c4081a75a63a7)
- The `FetchPolicy` type has been split into two types, so that passing `cache-and-network` to `ApolloClient#query` is now forbidden at the type level, whereas previously it was forbidden by a runtime `invariant` assertion:
```ts
export type FetchPolicy =
| 'cache-first'
| 'network-only'
| 'cache-only'
| 'no-cache'
| 'standby';
export type WatchQueryFetchPolicy =
| FetchPolicy
| 'cache-and-network';
```
The exception thrown if you ignore the type error has also been improved to explain the motivation behind this restriction. <br/>
[Issue #3130 (comment)](https://github.com/apollographql/apollo-client/issues/3130#issuecomment-478409066) and commit [cf069bc7](github.com/apollographql/apollo-client/commit/cf069bc7ee6577092234b0eb0ac32e05d50f5a1c)
- Avoid updating (and later invalidating) cache watches when `fetchPolicy` is `'no-cache'`. <br/>
[@bradleyayers](https://github.com/bradleyayers) in [PR #4573](https://github.com/apollographql/apollo-client/pull/4573), part of [issue #3452](https://github.com/apollographql/apollo-client/issues/3452)
- Remove temporary `queryId` after `fetchMore` completes. <br/>
[@doomsower](https://github.com/doomsower) in [#4440](https://github.com/apollographql/apollo-client/pull/4440)
- Call `clearStore` callbacks after clearing store. <br/>
[@ds8k](https://github.com/ds8k) in [#4695](https://github.com/apollographql/apollo-client/pull/4695)
- Perform all `DocumentNode` transforms once, and cache the results. <br/>
[@benjamn](https://github.com/benjamn) in [#4601](https://github.com/apollographql/apollo-client/pull/4601)
- Accommodate `@client @export` variable changes in `ObservableQuery`. <br/>
[@hwillson](https://github.com/hwillson) in [#4604](https://github.com/apollographql/apollo-client/pull/4604)
- Support the `returnPartialData` option for watched queries again. <br/>
[@benjamn](https://github.com/benjamn) in [#4743](https://github.com/apollographql/apollo-client/pull/4743)
- Preserve `networkStatus` for incomplete `cache-and-network` queries. <br/>
[@benjamn](https://github.com/benjamn) in [#4765](https://github.com/apollographql/apollo-client/pull/4765)
- Preserve `cache-and-network` `fetchPolicy` when refetching. <br/>
[@benjamn](https://github.com/benjamn) in [#4840](https://github.com/apollographql/apollo-client/pull/4840)
- Update the React Native docs to remove the request for external example apps that we can link to. We're no longer going to manage a list of external example apps. <br />
[@hwillson](https://github.com/hwillson) in [#4531](https://github.com/apollographql/apollo-client/pull/4531)
- Polling queries are no longer batched together, so their scheduling should be more predictable. <br/>
[@benjamn](https://github.com/benjamn) in [#4800](https://github.com/apollographql/apollo-client/pull/4800)
### Apollo Cache In-Memory 1.6.0
- Support `new InMemoryCache({ freezeResults: true })` to help enforce immutability. <br/>
[@benjamn](https://github.com/benjamn) in [#4514](https://github.com/apollographql/apollo-client/pull/4514)
- Allow `IntrospectionFragmentMatcher` to match fragments against the root `Query`, as `HeuristicFragmentMatcher` does. <br/>
[@rynobax](https://github.com/rynobax) in [#4620](https://github.com/apollographql/apollo-client/pull/4620)
- Rerential identity (`===`) of arrays in cache results will now be preserved for unchanged data. <br/>
[@benjamn](https://github.com/benjamn) in commit [f3091d6a](https://github.com/apollographql/apollo-client/pull/4586/commits/f3091d6a7e91be98549baea58903282cc540f460)
- Avoid adding `__typename` field to `@client` selection sets that have been `@export`ed as input variables. <br/>
[@benjamn](https://github.com/benjamn) in [#4784](https://github.com/apollographql/apollo-client/pull/4784)
### GraphQL Anywhere 4.2.2
- The `graphql` function can now be configured to ignore `@include` and
`@skip` directives (useful when walking a fragment to generate prop types
or filter result data). <br/>
[@GreenGremlin](https://github.com/GreenGremlin) in [#4373](https://github.com/apollographql/apollo-client/pull/4373)
## Apollo Client 2.5.1
### apollo-client 2.5.1
- Fixes `A tuple type element list cannot be empty` issue. <br/>
[@benjamn](https://github.com/benjamn) in [#4502](https://github.com/apollographql/apollo-client/pull/4502)
### graphql-anywhere 4.2.1
- Adds back the missing `graphql-anywhere/lib/async` entry point. <br/>
[@benjamn](https://github.com/benjamn) in [#4503](https://github.com/apollographql/apollo-client/pull/4503)
## Apollo Client (2.5.0)
### Apollo Client (2.5.0)
- Introduces new local state management features (client-side schema
and local resolver / `@client` support) and many overall code improvements,
to help reduce the Apollo Client bundle size. <br/>
[#4361](https://github.com/apollographql/apollo-client/pull/4361)
- Revamped CJS and ESM bundling approach with Rollup. <br/>
[@rosskevin](https://github.com/rosskevin) in [#4261](https://github.com/apollographql/apollo-client/pull/4261)
- Fixes an issue where the `QueryManager` was accidentally returning cached
data for `network-only` queries. <br/>
[@danilobuerger](https://github.com/danilobuerger) in [#4352](https://github.com/apollographql/apollo-client/pull/4352)
- Fixed an issue in the repo `.gitattributes` that was causing binary files
to have their line endings adjusted, and cleaned up corrupted documentation
images (ref: https://github.com/apollographql/apollo-client/pull/4232). <br/>
[@rajington](https://github.com/rajington) in [#4438](https://github.com/apollographql/apollo-client/pull/4438)
- Improve (and shorten) query polling implementation. <br/>
[PR #4337](https://github.com/apollographql/apollo-client/pull/4337)
## Apollo Client (2.4.13)
### Apollo Client (2.4.13)
- Resolve "invalidate" -> "invalidated" typo in `QueryManager`. <br/>
[@quazzie](https://github.com/quazzie) in [#4041](https://github.com/apollographql/apollo-client/pull/4041)
- Properly type `setQuery` and fix now typed callers. <br/>
[@danilobuerger](https://github.com/danilobuerger) in [#4369](https://github.com/apollographql/apollo-client/pull/4369)
- Align with the React Apollo decision that result `data` should be
`TData | undefined` instead of `TData | {}`. <br/>
[@danilobuerger](https://github.com/danilobuerger) in [#4356](https://github.com/apollographql/apollo-client/pull/4356)
- Documentation updates. <br/>
[@danilobuerger](https://github.com/danilobuerger) in [#4340](https://github.com/apollographql/apollo-client/pull/4340) <br />
[@justyn-clark](https://github.com/justyn-clark) in [#4383](https://github.com/apollographql/apollo-client/pull/4383) <br />
[@jtassin](https://github.com/jtassin) in [#4287](https://github.com/apollographql/apollo-client/pull/4287) <br />
[@Gongreg](https://github.com/Gongreg) in [#4386](https://github.com/apollographql/apollo-client/pull/4386) <br />
[@davecardwell](https://github.com/davecardwell) in [#4399](https://github.com/apollographql/apollo-client/pull/4399) <br />
[@michaelknoch](https://github.com/michaelknoch) in [#4384](https://github.com/apollographql/apollo-client/pull/4384) <br />
## Apollo Client (2.4.12)
### Apollo Client (2.4.12)
- Support `ApolloClient#stop` method for safe client disposal. <br/>
[PR #4336](https://github.com/apollographql/apollo-client/pull/4336)
## Apollo Client (2.4.11)
- Added explicit dependencies on the
[`tslib`](https://www.npmjs.com/package/tslib) package to all client
packages to fix
[Issue #4332](https://github.com/apollographql/apollo-client/issues/4332).
### Apollo Client (2.4.11)
- Reverted some breaking changes accidentally released in a patch version
(2.4.10). [PR #4334](https://github.com/apollographql/apollo-client/pull/4334)
## Apollo Client (2.4.10)
### Apollo Client (2.4.10)
- The `apollo-client` package no longer exports a `printAST` function from
`graphql/language/printer`. If you need this functionality, import it
directly: `import { print } from "graphql/language/printer"`
- Query polling now uses a simpler scheduling strategy based on a single
`setTimeout` interval rather than multiple `setInterval` timers. The new
timer fires at the rate of the fastest polling interval, and queries
with longer polling intervals fire whenever the time elapsed since they
last fired exceeds their desired interval. <br/>
[PR #4243](https://github.com/apollographql/apollo-client/pull/4243)
### Apollo Cache In-Memory (1.4.1)
- The `optimism` npm package has been updated to a version (0.6.9) that
provides its own TypeScript declarations, which should fix problems like
[Issue #4327](https://github.com/apollographql/apollo-client/issues/4327). <br/>
[PR #4331](https://github.com/apollographql/apollo-client/pull/4331)
- Error messages involving GraphQL queries now print the queries using
`JSON.stringify` instead of the `print` function exported by the
`graphql` package, to avoid pulling unnecessary printing logic into your
JavaScript bundle. <br/>
[PR #4234](https://github.com/apollographql/apollo-client/pull/4234)
- The `QueryKeyMaker` abstraction has been removed, meaning that cache
results for non-identical queries (or sub-queries) with equivalent
structure will no longer be cached together. This feature was a nice
optimization in certain specific use cases, but it was not worth the
additional complexity or bundle size. <br/>
[PR #4245](https://github.com/apollographql/apollo-client/pull/4245)
### Apollo Utilities (1.1.1)
- The `flattenSelections` helper function is no longer exported from
`apollo-utilities`, since `getDirectiveNames` has been reimplemented
without using `flattenSelections`, and `flattenSelections` has no clear
purpose now. If you need the old functionality, use a visitor:
```ts
import { visit } from "graphql/language/visitor";
function flattenSelections(selection: SelectionNode) {
const selections: SelectionNode[] = [];
visit(selection, {
SelectionSet(ss) {
selections.push(...ss.selections);
}
});
return selections;
}
```
## Apollo Client (2.4.9)
### Apollo Client (2.4.9)
- Apollo Client has been updated to use `graphql` 14.x as a dev dependency. <br/>
[@hwillson](https://github.com/hwillson) in [#4233](https://github.com/apollographql/apollo-client/pull/4233)
- The `onClearStore` function can now be used to register callbacks that should
be triggered when calling `clearStore`. <br/>
[@joe-re](https://github.com/joe-re) in [#4082](https://github.com/apollographql/apollo-client/pull/4082)
- Make `isApolloError` available for external use. <br/>
[@FredyC](https://github.com/FredyC) in [#4223](https://github.com/apollographql/apollo-client/pull/4223)
- The `QueryManager` now calls `complete` on the observables used by
Apollo Client's Subscription handling. This gives finite subscriptions a
chance to handle cleanup. <br/>
[@sujeetsr](https://github.com/sujeetsr) in [#4290](https://github.com/apollographql/apollo-client/pull/4290)
- Documentation updates. <br/>
[@lifedup](https://github.com/lifedup) in [#3931](https://github.com/apollographql/apollo-client/pull/3931) <br />
[@Dem0n3D](https://github.com/Dem0n3D) in [#4008](https://github.com/apollographql/apollo-client/pull/4008) <br />
[@anand-sundaram-zocdoc](https://github.com/anand-sundaram-zocdoc) in [#4009](https://github.com/apollographql/apollo-client/pull/4009) <br />
[@mattphoto](https://github.com/mattphoto) in [#4026](https://github.com/apollographql/apollo-client/pull/4026) <br />
[@birge](https://github.com/birge) in [#4029](https://github.com/apollographql/apollo-client/pull/4029) <br />
[@mxstbr](https://github.com/mxstbr) in [#4127](https://github.com/apollographql/apollo-client/pull/4127) <br/>
[@Caerbannog](https://github.com/Caerbannog) in [#4140](https://github.com/apollographql/apollo-client/pull/4140) <br/>
[@jedwards1211](https://github.com/jedwards1211) in [#4179](https://github.com/apollographql/apollo-client/pull/4179) <br/>
[@nutboltu](https://github.com/nutboltu) in [#4182](https://github.com/apollographql/apollo-client/pull/4182) <br/>
[@CarloPalinckx](https://github.com/CarloPalinckx) in [#4189](https://github.com/apollographql/apollo-client/pull/4189) <br/>
[@joebernard](https://github.com/joebernard) in [#4206](https://github.com/apollographql/apollo-client/pull/4206) <br/>
[@evans](https://github.com/evans) in [#4213](https://github.com/apollographql/apollo-client/pull/4213) <br/>
[@danilobuerger](https://github.com/danilobuerger) in [#4214](https://github.com/apollographql/apollo-client/pull/4214) <br/>
[@stubailo](https://github.com/stubailo) in [#4220](https://github.com/apollographql/apollo-client/pull/4220) <br/>
[@haysclark](https://github.com/haysclark) in [#4255](https://github.com/apollographql/apollo-client/pull/4255) <br/>
[@shelmire](https://github.com/shelmire) in [#4266](https://github.com/apollographql/apollo-client/pull/4266) <br/>
[@peggyrayzis](https://github.com/peggyrayzis) in [#4280](https://github.com/apollographql/apollo-client/pull/4280) <br/>
[@caydie-tran](https://github.com/caydie-tran) in [#4300](https://github.com/apollographql/apollo-client/pull/4300)
### Apollo Utilities (1.1.0)
- Transformation utilities have been refactored to work with `graphql` 14.x.
GraphQL AST's are no longer being directly modified. <br/>
[@hwillson](https://github.com/hwillson) in [#4233](https://github.com/apollographql/apollo-client/pull/4233)
### Apollo Cache In-Memory (1.4.0)
- The speed and memory usage of optimistic reads and writes has been
improved dramatically using a new layering technique that does not
require copying the non-optimistic contents of the cache. <br/>
[PR #4319](https://github.com/apollographql/apollo-client/pull/4319/)
- The `RecordingCache` abstraction has been removed, and thus is no longer
exported from `apollo-cache-inmemory`. <br/>
[PR #4319](https://github.com/apollographql/apollo-client/pull/4319/)
- Export the optimism `wrap` function using ES2015 export syntax, instead of
CommonJS. <br/>
[@ardatan](https://github.com/ardatan) in [#4158](https://github.com/apollographql/apollo-client/pull/4158)
## Apollo Client (2.4.8)
### Apollo Client (2.4.8)
- Documentation and config updates. <br/>
[@justinanastos](https://github.com/justinanastos) in [#4187](https://github.com/apollographql/apollo-client/pull/4187) <br/>
[@PowerKiKi](https://github.com/PowerKiKi) in [#3693](https://github.com/apollographql/apollo-client/pull/3693) <br/>
[@nandito](https://github.com/nandito) in [#3865](https://github.com/apollographql/apollo-client/pull/3865)
- Schema/AST tranformation utilities have been updated to work properly with
`@client` directives. <br/>
[@justinmakaila](https://github.com/justinmakaila) in [#3482](https://github.com/apollographql/apollo-client/pull/3482)
### Apollo Cache In-Memory (1.3.12)
- Avoid using `DepTrackingCache` for optimistic reads.
[PR #4521](https://github.com/apollographql/apollo-client/pull/4251)
- When creating an `InMemoryCache` object, it's now possible to disable the
result caching behavior introduced in [#3394](https://github.com/apollographql/apollo-client/pull/3394),
either for diagnostic purposes or because the benefit of caching repeated
reads is not worth the extra memory usage in your application:
```ts
new InMemoryCache({
resultCaching: false
})
```
Part of [PR #4521](https://github.com/apollographql/apollo-client/pull/4251).
## Apollo Client (2.4.7)
### Apollo Client (2.4.7)
- The `ApolloClient` constructor has been updated to accept `name` and
`version` params, that can be used to support Apollo Server [Client Awareness](https://www.apollographql.com/docs/apollo-server/v2/features/metrics.html#Client-Awareness)
functionality. These client awareness properties are passed into the
defined Apollo Link chain, and are then ultimately sent out as custom
headers with outgoing requests. <br/>
[@hwillson](https://github.com/hwillson) in [#4154](https://github.com/apollographql/apollo-client/pull/4154)
### Apollo Boost (0.1.22)
- No changes.
### Apollo Cache (1.1.21)
- No changes.
### Apollo Cache In-Memory (1.3.11)
- No changes.
### Apollo Utilities (1.0.26)
- No changes.
### Graphql Anywhere (4.1.23)
- No changes.
## Apollo Client (2.4.6)
### Apollo Cache In-Memory (1.3.10)
- Added some `return`s to prevent errors with `noImplicitReturns`
TypeScript rule.
[PR #4137](https://github.com/apollographql/apollo-client/pull/4137)
- Exclude the `src/` directory when publishing `apollo-cache-inmemory`.
[Issue #4083](https://github.com/apollographql/apollo-client/issues/4083)
## Apollo Client (2.4.5)
- Optimistic tests cleanup.
[PR #3834](https://github.com/apollographql/apollo-client/pull/3834) by
[@joshribakoff](https://github.com/joshribakoff)
- Documentation updates.
[PR #3840](https://github.com/apollographql/apollo-client/pull/3840) by
[@chentsulin](https://github.com/chentsulin) and
[PR #3844](https://github.com/apollographql/apollo-client/pull/3844) by
[@lorensr](https://github.com/lorensr)
- Implement `ObservableQuery#isDifferentFromLastResult` to fix
[Issue #4054](https://github.com/apollographql/apollo-client/issues/4054) and
[Issue #4031](https://github.com/apollographql/apollo-client/issues/4031).
[PR #4069](https://github.com/apollographql/apollo-client/pull/4069)
### Apollo Cache (1.1.20)
- Add `readQuery` test to make sure options aren't mutated.
[@CarloPalinckx](https://github.com/CarloPalinckx) in
[#3838](https://github.com/apollographql/apollo-client/pull/3838)
### Apollo Cache In-Memory (1.3.9)
- Avoid modifying source objects when merging cache results.
[Issue #4081](https://github.com/apollographql/apollo-client/issues/4081)
[PR #4089](https://github.com/apollographql/apollo-client/pull/4089)
### Apollo Utilities (1.0.25)
- Fix `apollo-utilities` `isEqual` bug due to missing `hasOwnProperty`
check. [PR #4072](https://github.com/apollographql/apollo-client/pull/4072)
by [@samkline](https://github.com/samkline)
## Apollo Client (2.4.4)
### Apollo Utilities (1.0.24)
- Discard property accessor functions in `cloneDeep` helper, to fix
[issue #4034](https://github.com/apollographql/apollo-client/issues/4034).
- Unconditionally remove `cloneDeep` property accessors.
[PR #4039](https://github.com/apollographql/apollo-client/pull/4039)
- Avoid copying non-enumerable and/or `Symbol` keys in `cloneDeep`.
[PR #4052](https://github.com/apollographql/apollo-client/pull/4052)
### Apollo Cache In-Memory (1.3.7)
- Throw when querying non-scalar objects without a selection set.
[Issue #4025](https://github.com/apollographql/apollo-client/issues/4025)
[PR #4038](https://github.com/apollographql/apollo-client/pull/4038)
- Work around spec non-compliance of `Map#set` and `Set#add` in IE11.
[Issue #4024](https://github.com/apollographql/apollo-client/issues/4024)
[PR #4012](https://github.com/apollographql/apollo-client/pull/4012)
## Apollo Client (2.4.3)
- Add additional checks to make sure we don't try to set the network status
of queries in the store, when the store doesn't exist. <br/>
[@i6mi6](https://github.com/i6mi6) in [#3914](https://github.com/apollographql/apollo-client/pull/3914)
- Documentation updates. <br/>
[@shanonvl](https://github.com/shanonvl) in [#3925](https://github.com/apollographql/apollo-client/pull/3925) <br/>
[@ojh102](https://github.com/ojh102) in [#3920](https://github.com/apollographql/apollo-client/pull/3920) <br/>
[@Bkucera](https://github.com/Bkucera) in [#3919](https://github.com/apollographql/apollo-client/pull/3919) <br/>
[@j4chou](https://github.com/j4chou) in [#3915](https://github.com/apollographql/apollo-client/pull/3915) <br/>
[@billfienberg](https://github.com/billfienberg) in [#3886](https://github.com/apollographql/apollo-client/pull/3886) <br/>
[@TLadd](https://github.com/TLadd) in [#3884](https://github.com/apollographql/apollo-client/pull/3884)
- The `ObservableQuery` class now makes a deep clone of `lastResult` when
first received, so that the `isDifferentResult` logic will not be
confused if the result object is modified later.
[Issue #3992](https://github.com/apollographql/apollo-client/issues/3992)
[PR #4032](https://github.com/apollographql/apollo-client/pull/4032/commits/e66027c5341dc7aaf71ee7ffcba1305b9a553525)
### Apollo Cache In-Memory (1.3.6)
- Optimize repeated `apollo-cache-inmemory` reads by caching partial query
results, for substantial performance improvements. As a consequence, watched
queries will not be rebroadcast unless the data have changed.
[PR #3394](https://github.com/apollographql/apollo-client/pull/3394)
- Include root ID and fragment matcher function in cache keys computed by
`StoreReader#executeStoreQuery` and `executeSelectionSet`, and work
around bugs in the React Native `Map` and `Set` polyfills.
[PR #3964](https://github.com/apollographql/apollo-client/pull/3964)
[React Native PR #21492 (pending)](https://github.com/facebook/react-native/pull/21492)
- The `apollo-cache-inmemory` package now allows `graphql@^14.0.0` as a
peer dependency.
[Issue #3978](https://github.com/apollographql/apollo-client/issues/3978)
- The `apollo-cache-inmemory` package now correctly broadcasts changes
even when the new data is `===` to the old data, since the contents of
the data object may have changed.
[Issue #3992](https://github.com/apollographql/apollo-client/issues/3992)
[PR #4032](https://github.com/apollographql/apollo-client/pull/4032/commits/d6a673fbc1444e115e90cc9e4c7fa3fc67bb7e56)
### Apollo GraphQL Anywhere (4.1.20)
- Make `graphql-anywhere` `filter` function generic (typescript). <br/>
[@minznerjosh](https://github.com/minznerjosh) in [#3929](https://github.com/apollographql/apollo-client/pull/3929)
### Apollo Utilities (1.0.22)
- The `fclone` package has been replaced with a custom `cloneDeep`
implementation that is tolerant of cycles, symbol properties, and
non-enumerable properties.
[PR #4032](https://github.com/apollographql/apollo-client/pull/4032/commits/78e2ad89f950da2829f49c7876f968adb2bc1302)
### Apollo Boost (0.1.17)
- Remove duplicate InMemoryCache export for Babel 6 compatibility.
[Issue #3910](https://github.com/apollographql/apollo-client/issues/3910)
[PR #3932](https://github.com/apollographql/apollo-client/pull/3932)
### Apollo Cache (1.1.18)
- No changes.
## Apollo Client (2.4.2)
### Apollo Client (2.4.2)
- Apollo Client no longer deep freezes query results.
[@hwillson](https://github.com/hwillson) in [#3883](https://github.com/apollographql/apollo-client/pull/3883)
- A new `clearStore` method has been added, that will remove all data from
the store. Unlike `resetStore`, it will not refetch active queries after
removing store data.
[@hwillson](https://github.com/hwillson) in [#3885](https://github.com/apollographql/apollo-client/pull/3885)
### Apollo Utilities (1.0.21)
- Replace the custom `cloneDeep` implementation with
[`fclone`](https://www.npmjs.com/package/fclone), to avoid crashing when
encountering circular references. <br/>
[@hwillson](https://github.com/hwillson) in [#3881](https://github.com/apollographql/apollo-client/pull/3881)
### Apollo Boost (0.1.16)
- No changes.
### Apollo Cache (1.1.17)
- No changes.
### Apollo Cache In-Memory (1.2.10)
- No changes.
### Apollo GraphQL Anywhere (4.1.19)
- No changes.
## 2.4.1 (August 26, 2018)
### Apollo Client (2.4.1)
- `mutate`'s `refetchQueries` option now allows queries to include a custom
`context` option. This `context` will be used when refetching the query.
For example:
```js
context = {
headers: {
token: 'some auth token',
},
};
client.mutate({
mutation: UPDATE_CUSTOMER_MUTATION,
variables: {
userId: user.id,
firstName,
...
},
refetchQueries: [{
query: CUSTOMER_MESSAGES_QUERY,
variables: { userId: user.id },
context,
}],
context,
});
```
The `CUSTOMER_MESSAGES_QUERY` above will be refetched using `context`.
Normally queries are refetched using the original context they were first
started with, but this provides a way to override the context, if needed. <br/>
[@hwillson](https://github.com/hwillson) in [#3852](https://github.com/apollographql/apollo-client/pull/3852)
- Documentation updates. <br/>
[@hwillson](https://github.com/hwillson) in [#3841](https://github.com/apollographql/apollo-client/pull/3841)
### Apollo Boost (0.1.15)
- Various internal infrastructure changes related to building, bundling,
testing, etc.
[@hwillson](https://github.com/hwillson) in [#3817](https://github.com/apollographql/apollo-client/pull/3817)
### Apollo Cache (1.1.16)
- Various internal infrastructure changes related to building, bundling,
testing, etc.
[@hwillson](https://github.com/hwillson) in [#3817](https://github.com/apollographql/apollo-client/pull/3817)
### Apollo Cache In-Memory (1.2.9)
- Various internal infrastructure changes related to building, bundling,
testing, etc.
[@hwillson](https://github.com/hwillson) in [#3817](https://github.com/apollographql/apollo-client/pull/3817)
### Apollo Utilities (1.0.20)
- Various internal infrastructure changes related to building, bundling,
testing, etc.
[@hwillson](https://github.com/hwillson) in [#3817](https://github.com/apollographql/apollo-client/pull/3817)
### Apollo GraphQL Anywhere (4.1.18)
- Various internal infrastructure changes related to building, bundling,
testing, etc.
[@hwillson](https://github.com/hwillson) in [#3817](https://github.com/apollographql/apollo-client/pull/3817)
## 2.4.0 (August 17, 2018)
### Apollo Client (2.4.0)
- Add proper error handling for subscriptions. If you have defined an `error`
handler on your subscription observer, it will now be called when an error
comes back in a result, and the `next` handler will be skipped (similar to
how we're handling errors with mutations). Previously, the error was
just passed in the result to the `next` handler. If you don't have an
`error` handler defined, the previous functionality is maintained, meaning
the error is passed in the result, giving the next handler a chance to deal
with it. This should help address backwards compatibility (and is the reason
for the minor version bumo in this release). <br/>
[@clayne11](https://github.com/clayne11) in [#3800](https://github.com/apollographql/apollo-client/pull/3800)
- Allow an `optimistic` param to be passed into `ApolloClient.readQuery` and
`ApolloClient.readFragment`, that when set to `true`, will allow
optimistic results to be returned. Is `false` by default. <br/>
[@jay1337](https://github.com/jay1337) in [#2429](https://github.com/apollographql/apollo-client/pull/2429)
- Optimistic tests cleanup. <br/>
[@joshribakoff](https://github.com/joshribakoff) in [#3713](https://github.com/apollographql/apollo-client/pull/3713)
- Make sure each package has its own `.npmignore`, so they're taken into
consideration when publishing via lerna. <br/>
[@hwillson](https://github.com/hwillson) in [#3828](https://github.com/apollographql/apollo-client/pull/3828)
- Documentation updates. <br/>
[@toolness](https://github.com/toolness) in [#3804](https://github.com/apollographql/apollo-client/pull/3804) <br/>
[@pungggi](https://github.com/pungggi) in [#3798](https://github.com/apollographql/apollo-client/pull/3798) <br/>
[@lorensr](https://github.com/lorensr) in [#3748](https://github.com/apollographql/apollo-client/pull/3748) <br/>
[@joshribakoff](https://github.com/joshribakoff) in [#3730](https://github.com/apollographql/apollo-client/pull/3730) <br/>
[@yalamber](https://github.com/yalamber) in [#3819](https://github.com/apollographql/apollo-client/pull/3819) <br/>
[@pschreibs85](https://github.com/pschreibs85) in [#3812](https://github.com/apollographql/apollo-client/pull/3812) <br/>
[@msreekm](https://github.com/msreekm) in [#3808](https://github.com/apollographql/apollo-client/pull/3808) <br/>
[@kamaltmo](https://github.com/kamaltmo) in [#3806](https://github.com/apollographql/apollo-client/pull/3806) <br/>
[@lorensr](https://github.com/lorensr) in [#3739](https://github.com/apollographql/apollo-client/pull/3739) <br/>
[@brainkim](https://github.com/brainkim) in [#3680](https://github.com/apollographql/apollo-client/pull/3680)
### Apollo Cache In-Memory (1.2.8)
- Fix typo in `console.warn` regarding fragment matching error message. <br/>
[@combizs](https://github.com/combizs) in [#3701](https://github.com/apollographql/apollo-client/pull/3701)
### Apollo Boost (0.1.14)
- No changes.
### Apollo Cache (1.1.15)
- No changes.
### Apollo Utilities (1.0.19)
- No changes.
### Apollo GraphQL Anywhere (4.1.17)
- No changes.
## 2.3.8 (August 9, 2018)
### Apollo Client (2.3.8)
- Adjusted the `graphql` peer dependency to cover explicit minor ranges.
Since the ^ operator only covers any minor version if the major version
is not 0 (since a major version of 0 is technically considered development by
semver 2), the current ^0.11.0 || ^14.0.0 graphql range doesn't cover
0.12.* or 0.13.*. This fixes the `apollo-client@X has incorrect peer
dependency "graphql@^0.11.0 || ^14.0.0"` errors that people might have
seen using `graphql` 0.12.x or 0.13.x. <br/>
[@hwillson](https://github.com/hwillson) in [#3746](https://github.com/apollographql/apollo-client/pull/3746)
- Document `setVariables` internal API status. <br/>
[@PowerKiKi](https://github.com/PowerKiKi) in [#3692](https://github.com/apollographql/apollo-client/pull/3692)
- Corrected `ApolloClient.queryManager` typing as it may be `undefined`. <br/>
[@danilobuerger](https://github.com/danilobuerger) in [#3661](https://github.com/apollographql/apollo-client/pull/3661)
- Make sure using a `no-cache` fetch policy with subscriptions prevents data
from being cached. <br/>
[@hwillson](https://github.com/hwillson) in [#3773](https://github.com/apollographql/apollo-client/pull/3773)
- Fixed an issue that sometimes caused empty query results, when using the
`no-cache` fetch policy. <br/>
[@hwillson](https://github.com/hwillson) in [#3777](https://github.com/apollographql/apollo-client/pull/3777)
- Documentation updates. <br/>
[@hwillson](https://github.com/hwillson) in [#3750](https://github.com/apollographql/apollo-client/pull/3750) <br/>
[@hwillson](https://github.com/hwillson) in [#3754](https://github.com/apollographql/apollo-client/pull/3754) <br/>
[@TheMightyPenguin](https://github.com/TheMightyPenguin) in [#3725](https://github.com/apollographql/apollo-client/pull/3725) <br/>
[@bennypowers](https://github.com/bennypowers) in [#3668](https://github.com/apollographql/apollo-client/pull/3668) <br/>
[@hwillson](https://github.com/hwillson) in [#3762](https://github.com/apollographql/apollo-client/pull/3762) <br/>
[@chentsulin](https://github.com/chentsulin) in [#3688](https://github.com/apollographql/apollo-client/pull/3688) <br/>
[@chentsulin](https://github.com/chentsulin) in [#3687](https://github.com/apollographql/apollo-client/pull/3687) <br/>
[@ardouglass](https://github.com/ardouglass) in [#3645](https://github.com/apollographql/apollo-client/pull/3645) <br/>
[@hwillson](https://github.com/hwillson) in [#3764](https://github.com/apollographql/apollo-client/pull/3764) <br/>
[@hwillson](https://github.com/hwillson) in [#3767](https://github.com/apollographql/apollo-client/pull/3767) <br/>
[@hwillson](https://github.com/hwillson) in [#3774](https://github.com/apollographql/apollo-client/pull/3774) <br/>
[@hwillson](https://github.com/hwillson) in [#3779](https://github.com/apollographql/apollo-client/pull/3779)
### Apollo Boost (0.1.13)
- No changes.
### Apollo Cache In-Memory (1.2.7)
- No changes.
### Apollo Cache (1.1.14)
- No changes.
### Apollo Utilities (1.0.18)
- No changes.
### Apollo GraphQL Anywhere (4.1.16)
- No changes.
## 2.3.7 (July 24, 2018)
### Apollo Client (2.3.7)
- Release 2.3.6 broke Typescript compilation. `QueryManager`'s
`getQueryWithPreviousResult` method included an invalid `variables` return
type in the auto-generated `core/QueryManager.d.ts` declaration file. The
type definition had a locally referenced path, that appears to have been
caused by the typescript compiler getting confused at compile/publish time.
`getQueryWithPreviousResult` return types are now excplicity identified,
which helps Typescript avoid the local type reference. For more details,
see https://github.com/apollographql/apollo-client/issues/3729. <br/>
[@hwillson](https://github.com/hwillson) in [#3731](https://github.com/apollographql/apollo-client/pull/3731)
### Apollo Boost (0.1.12)
- No changes.
## 2.3.6 (July 24, 2018)
### Apollo Client (2.3.6)
- Documentation updates. <br/>
[@ananth99](https://github.com/ananth99) in [#3599](https://github.com/apollographql/apollo-client/pull/3599) <br/>
[@hwillson](https://github.com/hwillson) in [#3635](https://github.com/apollographql/apollo-client/pull/3635) <br/>
[@JakeDawkins](https://github.com/JakeDawkins) in [#3642](https://github.com/apollographql/apollo-client/pull/3642) <br/>
[@hwillson](https://github.com/hwillson) in [#3644](https://github.com/apollographql/apollo-client/pull/3644) <br/>
[@gbau](https://github.com/gbau) in [#3644](https://github.com/apollographql/apollo-client/pull/3600) <br/>
[@chentsulin](https://github.com/chentsulin) in [#3608](https://github.com/apollographql/apollo-client/pull/3608) <br/>
[@MikaelCarpenter](https://github.com/MikaelCarpenter) in [#3609](https://github.com/apollographql/apollo-client/pull/3609) <br/>
[@Gamezpedia](https://github.com/Gamezpedia) in [#3612](https://github.com/apollographql/apollo-client/pull/3612) <br/>
[@jinxac](https://github.com/jinxac) in [#3647](https://github.com/apollographql/apollo-client/pull/3647) <br/>
[@abernix](https://github.com/abernix) in [#3705](https://github.com/apollographql/apollo-client/pull/3705) <br/>
[@dandv](https://github.com/dandv) in [#3703](https://github.com/apollographql/apollo-client/pull/3703) <br/>
[@hwillson](https://github.com/hwillson) in [#3580](https://github.com/apollographql/apollo-client/pull/3580) <br/>
- Updated `graphql` `peerDependencies` to handle 14.x versions. <br/>
[@ivank](https://github.com/ivank) in [#3598](https://github.com/apollographql/apollo-client/pull/3598)
- Add optional generic type params for variables on low level methods. <br/>
[@mvestergaard](https://github.com/mvestergaard) in [#3588](https://github.com/apollographql/apollo-client/pull/3588)
- Add a new `awaitRefetchQueries` config option to the Apollo Client
`mutate` function, that when set to `true` will wait for all
`refetchQueries` to be fully refetched, before resolving the mutation
call. `awaitRefetchQueries` is `false` by default. <br/>
[@jzimmek](https://github.com/jzimmek) in [#3169](https://github.com/apollographql/apollo-client/pull/3169)
### Apollo Boost (0.1.11)
- Allow `fetch` to be given as a configuration option to `ApolloBoost`. <br/>
[@mbaranovski](https://github.com/mbaranovski) in [#3590](https://github.com/apollographql/apollo-client/pull/3590)
- The `apollo-boost` `ApolloClient` constructor now warns about unsupported
options. <br/>
[@quentin-](https://github.com/quentin-) in [#3551](https://github.com/apollographql/apollo-client/pull/3551)
### Apollo Cache (1.1.13)
- No changes.
### Apollo Cache In-Memory (1.2.6)
- Add `__typename` and `id` properties to `dataIdFromObject` parameter
(typescript) <br/>
[@jfurler](https://github.com/jfurler) in [#3641](https://github.com/apollographql/apollo-client/pull/3641)
- Fixed an issue caused by `dataIdFromObject` considering returned 0 values to
be falsy, instead of being a valid ID, which lead to the store not being
updated properly in some cases. <br/>
[@hwillson](https://github.com/hwillson) in [#3711](https://github.com/apollographql/apollo-client/pull/3711)
### Apollo Utilities (1.0.17)
- No changes.
### Apollo GraphQL Anywhere (4.1.15)
- Add support for arrays to `graphql-anywhere`'s filter utility. <br/>
[@jsweet314](https://github.com/jsweet314) in [#3591](https://github.com/apollographql/apollo-client/pull/3591)
- Fix `Cannot convert object to primitive value` error that was showing up
when attempting to report a missing property on an object. <br/>
[@benjie](https://github.com/benjie) in [#3618](https://github.com/apollographql/apollo-client/pull/3618)
## 2.3.5 (June 19, 2018)
### Apollo Client (2.3.5)
- Internal code formatting updates.
- [@chentsulin](https://github.com/chentsulin) in [#3574](https://github.com/apollographql/apollo-client/pull/3574)
- Documentation updates.
- [@andtos90](https://github.com/andtos90) in [#3596](https://github.com/apollographql/apollo-client/pull/3596)
- [@serranoarevalo](https://github.com/serranoarevalo) in [#3554](https://github.com/apollographql/apollo-client/pull/3554)
- [@cooperka](https://github.com/cooperka) in [#3594](https://github.com/apollographql/apollo-client/pull/3594)
- [@pravdomil](https://github.com/pravdomil) in [#3587](https://github.com/apollographql/apollo-client/pull/3587)
- [@excitement-engineer](https://github.com/excitement-engineer) in [#3309](https://github.com/apollographql/apollo-client/pull/3309)
### Apollo Boost (0.1.10)
- No changes.
### Apollo Cache (1.1.12)
- No changes.
### Apollo Cache In-Memory (1.2.5)
- No changes.
### Apollo Utilities (1.0.16)
- Removed unnecessary whitespace from error message.
- [@mbaranovski](https://github.com/mbaranovski) in [#3593](https://github.com/apollographql/apollo-client/pull/3593)
### Apollo GraphQL Anywhere (4.1.14)
- No changes.
## 2.3.4 (June 13, 2018)
### Apollo Client (2.3.4)
- Export the `QueryOptions` interface, to make sure it can be used by other
projects (like `apollo-angular`).
- Fixed an issue caused by typescript changes to the constructor
`defaultOptions` param, that prevented `query` defaults from passing type
checks.
([@hwillson](https://github.com/hwillson) in [#3585](https://github.com/apollographql/apollo-client/pull/3585))
### Apollo Boost (0.1.9)
- No changes
### Apollo Cache (1.1.11)
- No changes
### Apollo Cache In-Memory (1.2.4)
- No changes
### Apollo Utilities (1.0.15)
- No changes
### Apollo GraphQL Anywhere (4.1.13)
- No changes
## 2.3.3 (June 13, 2018)
### Apollo Client (2.3.3)
- Typescript improvements. Made observable query parameterized on data and
variables: `ObservableQuery<TData, TVariables>`
([@excitement-engineer](https://github.com/excitement-engineer) in [#3140](https://github.com/apollographql/apollo-client/pull/3140))
- Added optional generics to cache manipulation methods (typescript).
([@mvestergaard](https://github.com/mvestergaard) in [#3541](https://github.com/apollographql/apollo-client/pull/3541))
- Typescript improvements. Created a new `QueryOptions` interface that
is now used by `ApolloClient.query` options, instead of the previous
`WatchQueryOptions` interface. This helps reduce confusion (especially
in the docs) that made it look like `ApolloClient.query` accepted
`ApolloClient.watchQuery` only options, like `pollingInterval`.
([@hwillson](https://github.com/hwillson) in [#3569](https://github.com/apollographql/apollo-client/pull/3569))
### Apollo Boost (0.1.8)
- Allow `cache` to be given as a configuration option to `ApolloBoost`.
([@dandean](https://github.com/dandean) in [#3561](https://github.com/apollographql/apollo-client/pull/3561))
- Allow `headers` and `credentials` to be passed in as configuration
parameters to the `apollo-boost` `ApolloClient` constructor.
([@rzane](https://github.com/rzane) in [#3098](https://github.com/apollographql/apollo-client/pull/3098))
### Apollo Cache (1.1.10)
- Added optional generics to cache manipulation methods (typescript).
([@mvestergaard](https://github.com/mvestergaard) in [#3541](https://github.com/apollographql/apollo-client/pull/3541))
### Apollo Cache In-Memory (1.2.3)
- Added optional generics to cache manipulation methods (typescript).
([@mvestergaard](https://github.com/mvestergaard) in [#3541](https://github.com/apollographql/apollo-client/pull/3541))
- Restore non-enumerability of `resultFields[ID_KEY]`.
([@benjamn](https://github.com/benjamn) in [#3544](https://github.com/apollographql/apollo-client/pull/3544))
- Cache query documents transformed by InMemoryCache.
([@benjamn](https://github.com/benjamn) in [#3553](https://github.com/apollographql/apollo-client/pull/3553))
### Apollo Utilities (1.0.14)
- Store key names generated by `getStoreKeyName` now leverage a more
deterministic approach to handling JSON based strings. This prevents store
key names from differing when using `args` like
`{ prop1: 'value1', prop2: 'value2' }` and
`{ prop2: 'value2', prop1: 'value1' }`.
([@gdi2290](https://github.com/gdi2290) in [#2869](https://github.com/apollographql/apollo-client/pull/2869))
- Avoid needless `hasOwnProperty` check in `deepFreeze`.
([@benjamn](https://github.com/benjamn) in [#3545](https://github.com/apollographql/apollo-client/pull/3545))
### Apollo GraphQL Anywhere (4.1.12)
- No new changes.
## 2.3.2 (May 29, 2018)
### Apollo Client (2.3.2)
- Fix SSR and `cache-and-network` fetch policy
([@dastoori](https://github.com/dastoori) in [#3372](https://github.com/apollographql/apollo-client/pull/3372))
- Fixed an issue where the `updateQuery` method passed to
`ObservableQuery.fetchMore` was receiving the original query variables,
instead of the new variables that it used to fetch more data.
([@abhiaiyer91](https://github.com/abhiaiyer91) in [#3500](https://github.com/apollographql/apollo-client/pull/3500))
- Fixed an issue involving `Object.setPrototypeOf()` not working on JSC
(Android), by instead setting the `prototype` of `this` manually.
([@seklyza](https://github.com/seklyza) in [#3306](https://github.com/apollographql/apollo-client/pull/3306))
- Added safeguards to make sure `QueryStore.initQuery` and
`QueryStore.markQueryResult` don't try to set the network status of a
`fetchMoreForQueryId` query, if it does not exist in the store. This was
happening when a query component was unmounted while a `fetchMore` was still
in flight.
([@conrad-vanl](https://github.com/conrad-vanl) in [#3367](https://github.com/apollographql/apollo-client/pull/3367), [@doomsower](https://github.com/doomsower) in [#3469](https://github.com/apollographql/apollo-client/pull/3469))
### Apollo Boost (0.1.7)
- Various internal code cleanup, tooling and dependency changes.
### Apollo Cache (1.1.9)
- Various internal code cleanup, tooling and dependency changes.
### Apollo Cache In-Memory (1.2.2)
- Fixed an issue that caused fragment only queries to sometimes fail.
([@abhiaiyer91](https://github.com/abhiaiyer91) in [#3507](https://github.com/apollographql/apollo-client/pull/3507))
- Fixed cache invalidation for inlined mixed types in union fields within
arrays.
([@dferber90](https://github.com/dferber90) in [#3422](https://github.com/apollographql/apollo-client/pull/3422))
### Apollo Utilities (1.0.13)
- Make `maybeDeepFreeze` a little more defensive, by always using
`Object.prototype.hasOwnProperty` (to avoid cases where the object being
frozen doesn't have its own `hasOwnProperty`).
([@jorisroling](https://github.com/jorisroling) in [#3418](https://github.com/apollographql/apollo-client/pull/3418))
- Remove certain small internal caches to prevent memory leaks when using SSR.
([@brunorzn](https://github.com/brunorzn) in [#3444](https://github.com/apollographql/apollo-client/pull/3444))
### Apollo GraphQL Anywhere (4.1.11)
- Source files are now excluded when publishing to npm.
([@hwillson](https://github.com/hwillson) in [#3454](https://github.com/apollographql/apollo-client/pull/3454))
|
apollographql/apollo-client
|
CHANGELOG.md
|
Markdown
|
mit
| 147,556
|
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("CalculatedSiteColumn")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Skanska ITN")]
[assembly: AssemblyProduct("CalculatedSiteColumn")]
[assembly: AssemblyCopyright("Copyright © Skanska ITN 2015")]
[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("d9f0177e-cf4a-4ec0-bc95-7224a40950f7")]
// 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")]
|
mirontoli/learn-spmeta2
|
001_calculated-sitecol/CalculatedSiteColumn/Properties/AssemblyInfo.cs
|
C#
|
mit
| 1,438
|
namespace Chloe.Server.Dtos
{
public class SocialComponentAddOrUpdateRequestDto: SocialComponentDto
{
}
}
|
QuinntyneBrown/azure-search-getting-started
|
src/Chloe/Server/Dtos/SocialComponentAddOrUpdateRequestDto.cs
|
C#
|
mit
| 118
|
/**
* @author mrdoob / http://mrdoob.com/
*/
export var Config = function ( name ) {
var storage = {
'autosave': true,
'theme': 'css/light.css',
'project/renderer': 'WebGLRenderer',
'project/renderer/antialias': true,
'project/renderer/gammaInput': false,
'project/renderer/gammaOutput': false,
'project/renderer/shadows': true,
'project/editable': false,
'project/vr': false,
'settings/history': false,
'ui/sidebar/animation/collapsed': true,
'ui/sidebar/script/collapsed': true
};
if ( window.localStorage[ name ] === undefined ) {
window.localStorage[ name ] = JSON.stringify( storage );
} else {
var data = JSON.parse( window.localStorage[ name ] );
for ( var key in data ) {
storage[ key ] = data[ key ];
}
}
return {
getKey: function ( key ) {
return storage[ key ];
},
setKey: function () { // key, value, key, value ...
for ( var i = 0, l = arguments.length; i < l; i += 2 ) {
storage[ arguments[ i ] ] = arguments[ i + 1 ];
}
window.localStorage[ name ] = JSON.stringify( storage );
console.log( '[' + /\d\d\:\d\d\:\d\d/.exec( new Date() )[ 0 ] + ']', 'Saved config to LocalStorage.' );
},
clear: function () {
delete window.localStorage[ name ];
}
};
};
|
tinnguyenhuuletrong/electron-threejs-editor
|
app/js/Config.js
|
JavaScript
|
mit
| 1,271
|
#include "Base.h"
#include <iostream>
using namespace std;
//start
int main (int argc, char** argv) {
Base b;
Derived d;
cout << "Objects Created" << endl;
b.b();
cout << "Calling derived methods" << endl;
d.a();
d.b();
d.c();
cout << ".. via base class pointers..." << endl;
Base* bp = &d;
bp->a();
bp->b();
bp->c();
//d.c(false);
}
//end
|
PatrickTrentin88/intro_cpp_qt
|
examples/derivation/exercise/main.cpp
|
C++
|
mit
| 398
|
let countdown;
const timerDisplay = document.querySelector('.display__time-left');
const endTime = document.querySelector('.display__end-time');
const buttons = document.querySelectorAll('[data-time]');
function timer(seconds) {
// clean any existing timers
clearInterval(countdown);
const now = Date.now();
const then = now + seconds * 1000;
displayTimeLeft(seconds);
displayEndTime(then);
countdown = setInterval(() => {
const secondsLeft = Math.round((then - Date.now()) / 1000);
// check if we should stop it
if(secondsLeft < 0) {
clearInterval(countdown);
return;
}
// display it
displayTimeLeft(secondsLeft);
}, 1000);
}
function displayTimeLeft(seconds) {
const minutes = Math.floor(seconds / 60);
const reminderSeconds = seconds % 60;
const display = `${minutes}:${reminderSeconds < 10 ? '0' : ''}${reminderSeconds}`;
timerDisplay.textContent = display;
document.title = display;
}
function displayEndTime(timestamp) {
const end = new Date(timestamp);
const hour = end.getHours();
// const adjustedHour = hour > 12 ? hour - 12 : hour;
const minutes = end.getMinutes();
endTime.textContent = `Be Back At ${hour}:${minutes < 10 ? '0' : ''}${minutes}`;
// endTime.textContent = `Be Back At ${adjustedHour}:${minutes < 10 ? '0' : ''}${minutes}`;
}
function startTimer() {
const seconds = parseInt(this.dataset.time);
timer(seconds);
}
buttons.forEach(button => button.addEventListener('click', startTimer));
document.customForm.addEventListener('submit', function(e) {
e.preventDefault();
const mins = this.minutes.value;
console.log(mins);
timer(mins * 60);
this.reset();
});
|
deaf-ayo/courses
|
wes-courses/javascript30/29 - Countdown Timer/scripts.js
|
JavaScript
|
mit
| 1,728
|
var path = require('path')
var configVars = require('./configVars.js')
var karmaConfig = {
basePath: './',
frameworks: ['jasmine-jquery', 'jasmine'],
port: 9876,
colors: true,
autoWatch: false,
browsers: ['PhantomJS'],
singleRun: true,
concurrency: 1,
files: [
'./' + configVars['unitTests']['entryFile']
],
reporters: [
'spec',
'coverage'
],
specReporter: {
maxLogLines: 2,
suppressErrorSummary: false,
suppressFailed: false,
suppressPassed: false,
suppressSkipped: false
},
coverageReporter: {
includeAllSources: true,
reporters: [
{
type: 'lcov',
subdir: '../' + configVars['unitTests']['coverageOutputPath']
},
{
type: 'text-summary'
}
]
},
preprocessors: {},
webpack: {
devtool: 'inline-source-map',
babel: {
presets: ['es2015'],
plugins: ['transform-object-assign'],
cacheDirectory: true
},
isparta: {
embedSource: true,
noAutoWrap: true,
babel: {
presets: ['es2015'],
plugins: [
'transform-object-assign',
'transform-es2015-modules-umd'
]
}
},
module: {
preLoaders: [
{
test: /\.js$/,
loader: 'babel'
},
{
test: /^(.(?!\.spec))*\.js$/,
include: path.resolve('./' + configVars['js']['srcPath']),
loader: 'isparta'
}
]
},
externals: [
{}
],
cache: true
}
}
karmaConfig.preprocessors['./' + configVars['unitTests']['entryFile']] = ['webpack', 'sourcemap']
module.exports = function (config) {
karmaConfig.logLevel = config.LOG_ERROR
config.set(karmaConfig)
}
|
MrSlide/Eve.js
|
karma.conf.js
|
JavaScript
|
mit
| 1,724
|
'use strict';
var should = require('should')
, request = require('supertest')
, helper = require('./helper');
describe('Routing > ', function() {
var url = 'http://localhost:3000';
before(function(done) {
helper.init(function(err) {
done();
});
});
describe('POST /users > ', function() {
before(function(done) {
helper.clearData(function(err) {
done();
});
});
it('유저 정보를 올바르게 입력하면 회원가입이 정상적으로 처리된다', function(done) {
var data = helper.getUserValueForTesting();
request(url)
.post('/users')
.send(data)
.end(function(err, res) {
if (err) {
throw err;
}
res.should.have.status(200);
res.body.should.have.property('user_id');
done();
});
});
it('해당 이메일 주소로 이미 가입되어 있다면 가입에 실패한다', function(done) {
var data = helper.getUserValueForTesting();
request(url)
.post('/users')
.send(data)
.end(function(err, res) {
if (err) {
throw err;
}
res.should.have.status(200);
res.body.should.have.property('msg');
done();
});
});
});
describe('GET /users/:user_id', function() {
var userId;
before(function(done) {
helper.clearData(function(err) {
helper.loadSeedData(function(err) {
helper.getUserValueInDatabase(function(err, userValue) {
userId = userValue.user_id;
done();
});
});
});
});
it('유저 정보를 얻는다', function(done) {
request(url)
.get('/users/' + userId)
.end(function(err, res) {
if (err) {
throw err;
}
res.should.have.status(200);
res.body.should.have.property('user');
done();
});
});
});
describe('POST /tokens > ', function() {
before(function(done) {
helper.clearData(function(err) {
helper.loadSeedData(function(err) {
done();
});
});
});
it('유저 정보를 올바르게 입력하면 로그인에 성공하고 user_id 와 token을 반환한다', function(done) {
var data = {
email: helper.getUserValueForTesting().email,
password: helper.getUserValueForTesting().password
};
request(url)
.post('/tokens')
.send(data)
.end(function(err, res) {
if (err) {
throw err;
}
res.should.have.status(200);
res.body.should.have.property('token');
res.body.should.have.property('user_id');
done();
});
});
});
describe('POST /users/:user_id/vobbles > ', function() {
var userId
, token;
before(function(done) {
helper.clearData(function(err) {
helper.loadSeedData(function(err) {
helper.getUserValueInDatabase(function(err, userValue) {
userId = userValue.user_id;
token = userValue.token;
done();
});
});
});
});
it('보블을 생성한다', function(done) {
var voiceFilePath = helper.getVoiceFilePathForTesting()
, imageFilePath = helper.getImageFilePathForTesting();
request(url)
.post('/users/' + userId + '/vobbles')
.field('token', token)
.field('latitude', '20.22')
.field('longitude', '50.5')
.attach('voice', voiceFilePath)
.attach('image', imageFilePath)
.end(function(err, res) {
if (err) {
throw err;
}
res.should.have.status(200);
res.body.should.have.property('vobble_id');
done();
});
});
});
describe('GET /vobbles > ', function() {
before(function(done) {
helper.clearData(function(err) {
helper.loadSeedData(function(err) {
done();
});
});
});
it('보블 정보를 반환한다', function(done) {
request(url)
.get('/vobbles?latitude=30&longitude=40')
.end(function(err, res) {
if (err) {
throw err;
}
res.should.have.status(200);
res.body.should.have.property('vobbles');
done();
});
});
});
describe('GET /vobbles/count > ', function() {
before(function(done) {
helper.clearData(function(err) {
helper.loadSeedData(function(err) {
done();
});
});
});
it('보블의 전체 갯수를 반환한다', function(done) {
request(url)
.get('/vobbles/count')
.end(function(err, res) {
if (err) {
throw err;
}
res.should.have.status(200);
res.body.should.have.property('count');
done();
});
});
});
describe('GET /users/:user_id/vobbles > ', function() {
var userId;
before(function(done) {
helper.clearData(function(err) {
helper.loadSeedData(function(err) {
helper.getUserValueInDatabase(function(err, userValue) {
userId = userValue.user_id;
done();
});
});
});
});
it('해당 유저의 보블 중 현재 위치에서 가장 가까운 n개의 보블 정보를 반환한다', function(done) {
request(url)
.get('/users/' + userId + '/vobbles?latitude=30&longitude=40')
.end(function(err, res) {
if (err) {
throw err;
}
res.should.have.status(200);
res.body.should.have.property('vobbles');
done();
});
});
});
describe('GET /users/:user_id/vobbles/count > ', function() {
var userId;
before(function(done) {
helper.clearData(function(err) {
helper.loadSeedData(function(err) {
helper.getUserValueInDatabase(function(err, userValue) {
userId = userValue.user_id;
done();
});
});
});
});
it('해당 유저가 올린 보블의 전체 갯수를 반환한다', function(done) {
request(url)
.get('/users/' + userId + '/vobbles/count')
.end(function(err, res) {
if (err) {
throw err;
}
res.should.have.status(200);
res.body.should.have.property('count');
done();
});
});
});
describe('POST /users/:user_id/vobbles/:vobble_id/delete > ', function() {
var userId
, token
, vobbleId;
before(function(done) {
helper.clearData(function(err) {
helper.loadSeedData(function(err) {
helper.getUserValueInDatabase(function(err, userValue) {
userId = userValue.user_id;
token = userValue.token;
helper.getVobbleValueInDatabase(userId, function(err, vobbleValue) {
vobbleId = vobbleValue.vobble_id;
done();
});
});
});
});
});
it('보블을 삭제한다.', function(done) {
var data = {
token: token
};
request(url)
.post('/users/' + userId + '/vobbles/' + vobbleId + '/delete')
.send(data)
.end(function(err, res) {
if (err) {
throw err;
}
res.should.have.status(200);
done();
});
});
});
});
|
Nexters/Vobble.API
|
tests/routes.test.js
|
JavaScript
|
mit
| 7,505
|
<?php if ( ! defined('BASEPATH')) exit('No se permite el acceso directo al script');
class Comprobaciones {
protected $CI;
public function __construct()
{
$this->CI =& get_instance();
}
//Saber si esta logueado el usurio y de que tipo es
private function logueado()
{
if(!$this->CI->session->userdata('logueado'))
{
echo "No logueado";exit();
}
if($this->CI->session->userdata('tipo') == 'Administrador')
{
$usuario = 'administrador';
}
else
{
$usuario = 'usuario';
}
return $usuario;
}
public function comprobar_admin($body = false, $datos = false)
{
$usuario = $this->logueado();
if($usuario == 'administrador')
{
if($body)
{
if(!$datos)
{
$plantilla['body'] = $this->CI->load->view($body, NULL, TRUE);
}
else
{
$plantilla['body'] = $this->CI->load->view($body, $datos, TRUE);
}
$this->CI->load->view('templates/admin', $plantilla);
}
else
{
return true;
}
}
else
{
redirect('admin');
}
}
}
|
JavierRodri89/comentariosPSL
|
application/libraries/Comprobaciones.php
|
PHP
|
mit
| 1,371
|
---
layout: page
title: Landing
header: Landing Page
tagline: "All the elemets to improve the sites with this theme"
group: navigation
img : 4.jpg
img-mobile : 4-mobile.jpg
---
{% include JB/setup %}
{% include themes/bootstrap/nav-bar.html %}
<div class="page-wrapper">
<!-- header-10 -->
<section class="header-10-sub v-center bg-midnight-blue">
<div class="background">
</div>
<div>
<div class="container">
<div class="hero-unit">
<h1>Startup Framework is a set of components</h1>
<p>
We’ve created the product that will help your
<br/>
startup to look even better.
</p>
</div>
</div>
</div>
<a class="control-btn fui-check" href="#"> </a>
</section>
<!-- content-7 -->
<section class="content-7 v-center">
<div>
<div class="container">
<h3>Take a look in our awesome product</h3>
<div class="row v-center">
<div class="col-sm-3">
<div>
Of course we haven’t forgotten about the responsive layout. Create a website with full mobile
support.
</div>
</div>
<div class="col-sm-4">
<div class="col-sm-offset-1">
<div class="screen-wrapper">
<div class="screen">
<img src="{{ BASE_PATH }}/assets/images/screen-popup.png" alt="">
<img src="{{ BASE_PATH }}/assets/images/screen.png" alt="">
</div>
</div>
</div>
</div>
<div class="col-sm-3">
<div class="col-sm-offset-2">
<h6>Responsive Layout</h6>
Of course we haven’t forgotten about the responsive layout. Full mobile support.
<h6>Retina Ready</h6>
Startup Framework works fine on devices supporting Retina Display. Feel the clarity!
</div>
</div>
</div>
</div>
</div>
</section>
<!-- content-23 -->
<section class="content-23 v-center bg-midnight-blue custom-bg">
<div>
<div class="container">
<div class="hero-unit hero-unit-bordered">
<h1>Scenic Nature</h1>
</div>
</div>
</div>
<a class="control-btn fui-check" href="#"> </a>
</section>
<!-- content-8 -->
<section class="content-8 v-center">
<div>
<div class="container">
<img src="{{ BASE_PATH }}/assets/images/img-1@2x.png" width="397" height="193" alt="">
<h3>Take a look to our amazing Kit</h3>
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<p>We have a great surprise for Designmodo fans – our first free HTML user interface kit.
Flat UI Free is made on the basis of Twitter Bootstrap in a stunning flat-style.
</p>
<a class="btn btn-large btn-clear" href="#">TRY IT NOW</a>
</div>
</div>
</div>
</div>
</section>
<!-- content-23 -->
<section class="content-23 v-center bg-midnight-blue">
<div id="bgVideo" class="background"></div>
<div>
<div class="container">
<div class="hero-unit">
<h1>Find a perfect suit for
<br class="hidden-phone">
your startup</h1>
</div>
</div>
</div>
<a class="control-btn fui-check" href="#sample"> </a>
</section>
<!-- content-8 -->
<section id="sample" class="content-8 v-center">
<div>
<div class="container">
<img width="380" height="187" alt="" src="{{ BASE_PATH }}/assets/images/ticket-red@2x.png"/>
<h3>Twenty Five Awesome Samples</h3>
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<p>
The most important part of the Startup Framework is the samples.
The samples form a set of 25 usable pages or you can add new blocks from UI Kit.
</p>
<a class="btn btn-large btn-clear" href="#">TRY IT NOW</a>
</div>
</div>
</div>
</div>
</section>
<!-- content-11 -->
<section class="content-11">
<div class="container">
<span>You have the design, you have the code</span>
<a class="btn btn-large btn-danger" href="#">TRY IT NOW</a>
</div>
</section>
<!-- footer-3 -->
<footer class="footer-3">
<div class="container">
<div class="row v-center">
<div class="col-sm-2">
<a class="brand" href="#">Startup</a>
</div>
<div class="col-sm-7">
<div class="additional-links">
Be sure to take a look to our <a href="#">Terms of Use</a> and <a href="#">Privacy Policy</a>
</div>
</div>
<div class="col-sm-3">
<h6>New York, NY</h6>
<div class="address">
62 West 55th Street, Suite 302<br>New York, NY, 10230
</div>
</div>
</div>
</div>
</footer>
</div>
|
startupui/startupui.github.io
|
landing.html
|
HTML
|
mit
| 6,085
|
# [qc.Math](README.md).snapToCeil
## Prototype
* number snapToCeil(input, gap, start)
## Paramters
| Paramter | Type | Description |
| ------------- | ------------- | -------------|
| input | number | The value to snap. |
| gap | number | The interval gap of the grid. |
| start | number | Optional starting offset for gap. |
| return | number | |
## Description
Snap a value to nearest grid slice, using ceil.
## Example
````
// return 15
var ret = game.math.snapToCeil(11, 5, 0);
// return 15
var ret = game.math.snapToCeil(14, 5, 0);
````
|
qiciengine/qiciengine-documentation
|
en/api/math/snapToCeil.md
|
Markdown
|
mit
| 583
|
<?php
//piesaistam šo modeli pie FuelPHP pakotnes Orm modeļa
use Orm\Model;
class Model_Employee extends Model
{
//glabā informāciju par to, kādi lauki ir šim modelim
protected static $_properties = array(
'id',
'name',
'surname',
'email',
'phonenumber',
'description',
'avatar',
'created_at',
'updated_at',
);
//nodefinē automātiskās aizpildes laukus
protected static $_observers = array(
'Orm\Observer_CreatedAt' => array(
'events' => array('before_insert'),
'mysql_timestamp' => false,
),
'Orm\Observer_UpdatedAt' => array(
'events' => array('before_save'),
'mysql_timestamp' => false,
),
);
//glabā validācijas prasības laukiem
public static function validate($factory)
{
//izsauc validācijas instanci, padodot iegūto masīvu.
$val = Validation::forge($factory);
$val->add_field('name', 'Name', 'required|max_length[70]');
$val->add_field('surname', 'Surname', 'required|max_length[70]');
$val->add_field('email', 'Email', 'required|valid_email|max_length[254]');
$val->add_field('phonenumber', 'Phonenumber', 'required|max_length[8]');
$val->add_field('description', 'Description', 'required');
$val->add_field('avatar', 'Avatar', 'max_length[136]');
return $val;
}
}
|
brunotreiguts/demo
|
fuel/app/classes/model/employee.php
|
PHP
|
mit
| 1,267
|
// Copyright (c) 2002-2003, Sony Computer Entertainment America
// Copyright (c) 2002-2003, Craig Reynolds <craig_reynolds@playstation.sony.com>
// Copyright (C) 2007 Bjoern Graf <bjoern.graf@gmx.net>
// Copyright (C) 2007 Michael Coles <michael@digini.com>
// All rights reserved.
//
// This software is licensed as described in the file license.txt, which
// you should have received as part of this distribution. The terms
// are also available at http://www.codeplex.com/SharpSteer/Project/License.aspx.
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using SharpSteer2;
using SharpSteer2.Helpers;
using Vector3 = System.Numerics.Vector3;
namespace Demo.PlugIns.Soccer
{
public class Player : SimpleVehicle
{
Trail _trail;
public override float MaxForce { get { return 3000.7f; } }
public override float MaxSpeed { get { return 10; } }
// constructor
public Player(List<Player> others, List<Player> allplayers, Ball ball, bool isTeamA, int id, IAnnotationService annotations = null)
:base(annotations)
{
_allPlayers = allplayers;
_ball = ball;
_imTeamA = isTeamA;
_myID = id;
Reset();
}
// reset state
public override void Reset()
{
base.Reset(); // reset the vehicle
Speed = 0.0f; // speed along Forward direction.
// Place me on my part of the field, looking at oponnents goal
Position = new Vector3(_imTeamA ? RandomHelpers.Random() * 20 : -RandomHelpers.Random() * 20, 0, (RandomHelpers.Random() - 0.5f) * 20);
if (_myID < 9)
{
Position = _imTeamA ? (Globals.PlayerPosition[_myID]) : (new Vector3(-Globals.PlayerPosition[_myID].X, Globals.PlayerPosition[_myID].Y, Globals.PlayerPosition[_myID].Z));
}
_home = Position;
if (_trail == null) _trail = new Trail(10, 60);
_trail.Clear(); // prevent long streaks due to teleportation
}
// per frame simulation update
public void Update(float elapsedTime)
{
// if I hit the ball, kick it.
float distToBall = Vector3.Distance(Position, _ball.Position);
float sumOfRadii = Radius + _ball.Radius;
if (distToBall < sumOfRadii)
_ball.Kick((_ball.Position - Position) * 50);
// otherwise consider avoiding collisions with others
Vector3 collisionAvoidance = SteerToAvoidNeighbors(1, _allPlayers);
if (collisionAvoidance != Vector3.Zero)
ApplySteeringForce(collisionAvoidance, elapsedTime);
else
{
float distHomeToBall = Vector3.Distance(_home, _ball.Position);
if (distHomeToBall < 12)
{
// go for ball if I'm on the 'right' side of the ball
if (_imTeamA ? Position.X > _ball.Position.X : Position.X < _ball.Position.X)
{
Vector3 seekTarget = SteerForSeek(_ball.Position);
ApplySteeringForce(seekTarget, elapsedTime);
}
else
{
if (distHomeToBall < 12)
{
float z = _ball.Position.Z - Position.Z > 0 ? -1.0f : 1.0f;
Vector3 behindBall = _ball.Position + (_imTeamA ? new Vector3(2, 0, z) : new Vector3(-2, 0, z));
Vector3 behindBallForce = SteerForSeek(behindBall);
annotation.Line(Position, behindBall, Color.Green.ToVector3().FromXna());
Vector3 evadeTarget = SteerForFlee(_ball.Position);
ApplySteeringForce(behindBallForce * 10 + evadeTarget, elapsedTime);
}
}
}
else // Go home
{
Vector3 seekTarget = SteerForSeek(_home);
Vector3 seekHome = SteerForSeek(_home);
ApplySteeringForce(seekTarget + seekHome, elapsedTime);
}
}
}
// draw this character/vehicle into the scene
public void Draw()
{
Drawing.DrawBasic2dCircularVehicle(this, _imTeamA ? Color.Red : Color.Blue);
_trail.Draw(annotation);
}
// per-instance reference to its group
readonly List<Player> _allPlayers;
readonly Ball _ball;
readonly bool _imTeamA;
readonly int _myID;
Vector3 _home;
}
}
|
martindevans/SharpSteer2
|
Demo/PlugIns/Soccer/Player.cs
|
C#
|
mit
| 3,920
|
from babymaker import BabyMaker, EnumType, IntType, StringType, UUIDType, FieldType, DatetimeType, FloatType, EmbedType
import unittest
import string
import sys
from datetime import datetime, timedelta
class TestMakeSomeBabies(unittest.TestCase):
def test_make_one(self):
fields = {
"id": UUIDType()
}
female_of_the_species = BabyMaker(fields)
one = female_of_the_species.make_one()
self.assertTrue("id" in one)
def test_make_some(self):
fields = {
"id": UUIDType()
}
female_of_the_species = BabyMaker(fields)
some = list(female_of_the_species.make_some(8))
self.assertEquals(len(some), 8)
for one in some:
self.assertTrue("id" in one)
def test_uuid_field_hex_format(self):
fields = {
"id": UUIDType(format="hex_str")
}
female_of_the_species = BabyMaker(fields)
one = female_of_the_species.make_one()
the_id = one.get("id")
self.assertEquals(len(the_id), 32)
for char in the_id:
self.assertTrue(char in string.hexdigits)
def test_uuid_field_default_format(self):
fields = {
"id": UUIDType()
}
female_of_the_species = BabyMaker(fields)
one = female_of_the_species.make_one()
the_id = one.get("id")
self.assertEquals(len(the_id), 36)
for char in the_id:
self.assertTrue(char in string.hexdigits + "-")
def test_uuid_field_int_format(self):
fields = {
"id": UUIDType("int")
}
female_of_the_species = BabyMaker(fields)
one = female_of_the_species.make_one()
the_id = one.get("id")
self.assertIsInstance(the_id, int)
def test_uuid_field_int_str_format(self):
fields = {
"id": UUIDType("int_str")
}
female_of_the_species = BabyMaker(fields)
one = female_of_the_species.make_one()
the_id = one.get("id")
for char in the_id:
self.assertTrue(char in string.digits)
will_it_blend = int(the_id)
def test_int_field(self):
fields = {
"id": IntType(min_value=10, max_value=11)
}
female_of_the_species = BabyMaker(fields)
one = female_of_the_species.make_one()
the_id = one.get("id")
self.assertIsInstance(the_id, int)
self.assertTrue(the_id >= 10)
self.assertTrue(the_id <= 11)
fields = {
"id": IntType()
}
female_of_the_species = BabyMaker(fields)
one = female_of_the_species.make_one()
the_id = one.get("id")
self.assertIsInstance(the_id, int)
self.assertTrue(the_id >= 0)
self.assertTrue(the_id <= sys.maxsize)
def test_float_field(self):
fields = {
"id": FloatType(min_value=2.0, max_value=10.0)
}
female_of_the_species = BabyMaker(fields)
one = female_of_the_species.make_one()
the_id = one.get("id")
self.assertIsInstance(the_id, float)
self.assertTrue(the_id >= 2.0)
self.assertTrue(the_id <= 10.0)
fields = {
"id": FloatType()
}
female_of_the_species = BabyMaker(fields)
one = female_of_the_species.make_one()
the_id = one.get("id")
self.assertIsInstance(the_id, float)
self.assertTrue(the_id >= 0.0)
self.assertTrue(the_id <= 1.0)
for baby in female_of_the_species.make_some(100):
the_id = baby.get("id")
self.assertIsInstance(the_id, float)
self.assertTrue(the_id >= 0.0)
self.assertTrue(the_id <= 1.0)
fields = {
"id": FloatType(min_value=1.0)
}
female_of_the_species = BabyMaker(fields)
one = female_of_the_species.make_one()
the_id = one.get("id")
self.assertIsInstance(the_id, float)
self.assertTrue(the_id >= 1.0)
self.assertTrue(the_id <= 2.0)
def test_string_field(self):
fields = {
"id": StringType(min_size=10, max_size=22)
}
female_of_the_species = BabyMaker(fields)
one = female_of_the_species.make_one()
the_id = one.get("id")
self.assertIsInstance(the_id, str)
for char in the_id:
self.assertTrue(char in string.printable)
self.assertTrue(len(the_id) >= 10)
self.assertTrue(len(the_id) <= 22)
fields = {
"id": StringType()
}
female_of_the_species = BabyMaker(fields)
one = female_of_the_species.make_one()
the_id = one.get("id")
self.assertIsInstance(the_id, str)
for char in the_id:
self.assertTrue(char in string.printable)
self.assertTrue(len(the_id) >= 0)
self.assertTrue(len(the_id) <= 64)
def test_string_field_with_limited_chars(self):
allowed_chars = "paul"
fields = {
"id": StringType(allowed_chars=allowed_chars, min_size=10, max_size=22)
}
female_of_the_species = BabyMaker(fields)
one = female_of_the_species.make_one()
the_id = one.get("id")
self.assertIsInstance(the_id, str)
for char in the_id:
self.assertTrue(char in allowed_chars)
self.assertTrue(len(the_id) >= 10)
self.assertTrue(len(the_id) <= 22)
def test_enum_type(self):
choices = [1, 8, "paul", 12, None]
fields = {
"id": EnumType(choices=choices)
}
female_of_the_species = BabyMaker(fields)
some = list(female_of_the_species.make_some(88))
self.assertEquals(len(some), 88)
for one in some:
the_id = one.get("id")
self.assertTrue(the_id in choices)
def test_base_field_type(self):
fields = {
"id": FieldType()
}
female_of_the_species = BabyMaker(fields)
some = list(female_of_the_species.make_some(88))
self.assertEquals(len(some), 88)
for one in some:
the_id = one.get("id")
self.assertIsNone(the_id)
def test_datetime_type(self):
start = datetime(1976, 7, 15)
end = datetime(1977, 7, 15)
fields = {
"created": DatetimeType(start, end)
}
female_of_the_species = BabyMaker(fields)
some = list(female_of_the_species.make_some(88))
self.assertEquals(len(some), 88)
for one in some:
created = one.get("created")
self.assertIsInstance(created, datetime)
self.assertTrue(created <= end)
self.assertTrue(created >= start)
def test_datetime_notime_type(self):
start = datetime(1976, 7, 15)
end = datetime(1977, 7, 15)
fields = {
"created": DatetimeType(start, end, include_time=False)
}
female_of_the_species = BabyMaker(fields)
some = list(female_of_the_species.make_some(88))
self.assertEquals(len(some), 88)
for one in some:
created = one.get("created")
self.assertIsInstance(created, datetime)
self.assertEquals(created.hour, 0)
self.assertEquals(created.minute, 0)
self.assertEquals(created.second, 0)
self.assertTrue(created <= end)
self.assertTrue(created >= start)
def test_datetime_incremental_type(self):
start = datetime(1976, 7, 15)
end = datetime(1977, 7, 15)
delta = timedelta(weeks=1)
fields = {
"created": DatetimeType(start, end, increment=delta)
}
female_of_the_species = BabyMaker(fields)
some = list(female_of_the_species.make_some(56))
self.assertEquals(len(some), 56)
test_value = start
for one in some:
created = one.get("created")
self.assertIsInstance(created, datetime)
self.assertTrue(created <= end)
self.assertTrue(created >= start)
self.assertEquals(created, test_value)
test_value += delta
if test_value >= end:
test_value = start
def test_datetime_decremental_type(self):
start = datetime(1976, 7, 15)
end = datetime(1977, 7, 15)
delta = timedelta(weeks=-1)
fields = {
"created": DatetimeType(start, end, increment=delta)
}
female_of_the_species = BabyMaker(fields)
some = list(female_of_the_species.make_some(56))
self.assertEquals(len(some), 56)
test_value = end
for one in some:
created = one.get("created")
self.assertIsInstance(created, datetime)
self.assertTrue(created <= end)
self.assertTrue(created >= start)
self.assertEquals(created, test_value)
test_value += delta
if test_value <= start:
test_value = end
def test_embedded_maker(self):
fields = {
"id": UUIDType()
}
female_of_the_species = BabyMaker(fields)
fields2 = {
"inbed": EmbedType(female_of_the_species),
"id": UUIDType()
}
grandma = BabyMaker(fields2)
one = grandma.make_one()
self.assertTrue("id" in one)
self.assertTrue("inbed" in one)
self.assertTrue("id" in one.inbed)
|
bvalerius/py-babymaker
|
tests/test_babymaker.py
|
Python
|
mit
| 9,457
|
DateInput = (function($) {
function DateInput(el, opts) {
if (typeof(opts) != "object") opts = {};
$.extend(this, DateInput.DEFAULT_OPTS, opts);
this.input = $(el);
this.bindMethodsToObj("show", "hide", "hideIfClickOutside", "keydownHandler", "selectDate");
this.build();
this.selectDate();
this.hide()
};
DateInput.DEFAULT_OPTS = {
month_names: ["一月份", "二月份", "三月份", "四月份", "五月份", "六月份", "七月份", "八月份", "九月份", "十月份", "十一月份", "十二月份"],
short_month_names: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
short_day_names: ["日", "一", "二", "三", "四", "五", "六"],
start_of_week: 1
};
DateInput.prototype = {
build: function() {
var monthNav = $('<p class="month_nav">' + '<span class="button prev" title="[Page-Up]">«</span>' + ' <span class="month_name"></span> ' + '<span class="button next" title="[Page-Down]">»</span>' + '</p>');
this.monthNameSpan = $(".month_name", monthNav);
$(".prev", monthNav).click(this.bindToObj(function() {
this.moveMonthBy( - 1)
}));
$(".next", monthNav).click(this.bindToObj(function() {
this.moveMonthBy(1)
}));
var yearNav = $('<p class="year_nav">' + '<span class="button prev" title="[Ctrl+Page-Up]">«</span>' + ' <span class="year_name"></span> ' + '<span class="button next" title="[Ctrl+Page-Down]">»</span>' + '</p>');
this.yearNameSpan = $(".year_name", yearNav);
$(".prev", yearNav).click(this.bindToObj(function() {
this.moveMonthBy( - 12)
}));
$(".next", yearNav).click(this.bindToObj(function() {
this.moveMonthBy(12)
}));
var nav = $('<div class="nav"></div>').append(monthNav, yearNav);
var tableShell = "<table><thead><tr>";
$(this.adjustDays(this.short_day_names)).each(function() {
tableShell += "<th>" + this + "</th>"
});
tableShell += "</tr></thead><tbody></tbody></table>";
this.dateSelector = this.rootLayers = $('<div class="date_selector"></div>').append(nav, tableShell).insertAfter(this.input);
if ($.browser.msie && $.browser.version < 7) {
this.ieframe = $('<iframe class="date_selector_ieframe" frameborder="0" src="#"></iframe>').insertBefore(this.dateSelector);
this.rootLayers = this.rootLayers.add(this.ieframe);
$(".button", nav).mouseover(function() {
$(this).addClass("hover")
});
$(".button", nav).mouseout(function() {
$(this).removeClass("hover")
})
};
this.tbody = $("tbody", this.dateSelector);
this.input.change(this.bindToObj(function() {
this.selectDate()
}));
this.selectDate()
},
selectMonth: function(date) {
var newMonth = new Date(date.getFullYear(), date.getMonth(), 1);
if (!this.currentMonth || !(this.currentMonth.getFullYear() == newMonth.getFullYear() && this.currentMonth.getMonth() == newMonth.getMonth())) {
this.currentMonth = newMonth;
var rangeStart = this.rangeStart(date),
rangeEnd = this.rangeEnd(date);
var numDays = this.daysBetween(rangeStart, rangeEnd);
var dayCells = "";
for (var i = 0; i <= numDays; i++) {
var currentDay = new Date(rangeStart.getFullYear(), rangeStart.getMonth(), rangeStart.getDate() + i, 12, 00);
if (this.isFirstDayOfWeek(currentDay)) dayCells += "<tr>";
if (currentDay.getMonth() == date.getMonth()) {
dayCells += '<td class="selectable_day" date="' + this.dateToString(currentDay) + '">' + currentDay.getDate() + '</td>'
} else {
dayCells += '<td class="unselected_month" date="' + this.dateToString(currentDay) + '">' + currentDay.getDate() + '</td>'
};
if (this.isLastDayOfWeek(currentDay)) dayCells += "</tr>"
};
this.tbody.empty().append(dayCells);
this.monthNameSpan.empty().append(this.monthName(date));
this.yearNameSpan.empty().append(this.currentMonth.getFullYear());
$(".selectable_day", this.tbody).click(this.bindToObj(function(event) {
this.changeInput($(event.target).attr("date"))
}));
$("td[date=" + this.dateToString(new Date()) + "]", this.tbody).addClass("today");
$("td.selectable_day", this.tbody).mouseover(function() {
$(this).addClass("hover")
});
$("td.selectable_day", this.tbody).mouseout(function() {
$(this).removeClass("hover")
})
};
$('.selected', this.tbody).removeClass("selected");
$('td[date=' + this.selectedDateString + ']', this.tbody).addClass("selected")
},
selectDate: function(date) {
if (typeof(date) == "undefined") {
date = this.stringToDate(this.input.val())
};
if (!date) date = new Date();
this.selectedDate = date;
this.selectedDateString = this.dateToString(this.selectedDate);
this.selectMonth(this.selectedDate)
},
changeInput: function(dateString) {
this.input.val(dateString).change();
this.hide()
},
show: function() {
this.rootLayers.css("display", "block");
$([window, document.body]).click(this.hideIfClickOutside);
this.input.unbind("focus", this.show);
$(document.body).keydown(this.keydownHandler);
this.setPosition()
},
hide: function() {
this.rootLayers.css("display", "none");
$([window, document.body]).unbind("click", this.hideIfClickOutside);
this.input.focus(this.show);
$(document.body).unbind("keydown", this.keydownHandler)
},
hideIfClickOutside: function(event) {
if (event.target != this.input[0] && !this.insideSelector(event)) {
this.hide()
}
},
insideSelector: function(event) {
var offset = this.dateSelector.position();
offset.right = offset.left + this.dateSelector.outerWidth();
offset.bottom = offset.top + this.dateSelector.outerHeight();
return event.pageY < offset.bottom && event.pageY > offset.top && event.pageX < offset.right && event.pageX > offset.left
},
keydownHandler: function(event) {
switch (event.keyCode) {
case 9:
case 27:
this.hide();
return;
break;
case 13:
this.changeInput(this.selectedDateString);
break;
case 33:
this.moveDateMonthBy(event.ctrlKey ? -12 : -1);
break;
case 34:
this.moveDateMonthBy(event.ctrlKey ? 12 : 1);
break;
case 38:
this.moveDateBy( - 7);
break;
case 40:
this.moveDateBy(7);
break;
case 37:
this.moveDateBy( - 1);
break;
case 39:
this.moveDateBy(1);
break;
default:
return
}
event.preventDefault()
},
stringToDate: function(string) {
var matches;
if (matches = string.match(/^(\d{1,2}) ([^\s]+) (\d{4,4})$/)) {
return new Date(matches[3], this.shortMonthNum(matches[2]), matches[1], 12, 00)
} else {
return null
}
},
dateToString: function(date) {
return date.getFullYear()+"-"+this.short_month_names[date.getMonth()]+"-" +date.getDate()
},
setPosition: function() {
var offset = this.input.offset();
this.rootLayers.css({
top: offset.top + this.input.outerHeight(),
left: offset.left
});
if (this.ieframe) {
this.ieframe.css({
width: this.dateSelector.outerWidth(),
height: this.dateSelector.outerHeight()
})
}
},
moveDateBy: function(amount) {
var newDate = new Date(this.selectedDate.getFullYear(), this.selectedDate.getMonth(), this.selectedDate.getDate() + amount);
this.selectDate(newDate)
},
moveDateMonthBy: function(amount) {
var newDate = new Date(this.selectedDate.getFullYear(), this.selectedDate.getMonth() + amount, this.selectedDate.getDate());
if (newDate.getMonth() == this.selectedDate.getMonth() + amount + 1) {
newDate.setDate(0)
};
this.selectDate(newDate)
},
moveMonthBy: function(amount) {
var newMonth = new Date(this.currentMonth.getFullYear(), this.currentMonth.getMonth() + amount, this.currentMonth.getDate());
this.selectMonth(newMonth)
},
monthName: function(date) {
return this.month_names[date.getMonth()]
},
bindToObj: function(fn) {
var self = this;
return function() {
return fn.apply(self, arguments)
}
},
bindMethodsToObj: function() {
for (var i = 0; i < arguments.length; i++) {
this[arguments[i]] = this.bindToObj(this[arguments[i]])
}
},
indexFor: function(array, value) {
for (var i = 0; i < array.length; i++) {
if (value == array[i]) return i
}
},
monthNum: function(month_name) {
return this.indexFor(this.month_names, month_name)
},
shortMonthNum: function(month_name) {
return this.indexFor(this.short_month_names, month_name)
},
shortDayNum: function(day_name) {
return this.indexFor(this.short_day_names, day_name)
},
daysBetween: function(start, end) {
start = Date.UTC(start.getFullYear(), start.getMonth(), start.getDate());
end = Date.UTC(end.getFullYear(), end.getMonth(), end.getDate());
return (end - start) / 86400000
},
changeDayTo: function(dayOfWeek, date, direction) {
var difference = direction * (Math.abs(date.getDay() - dayOfWeek - (direction * 7)) % 7);
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + difference)
},
rangeStart: function(date) {
return this.changeDayTo(this.start_of_week, new Date(date.getFullYear(), date.getMonth()), -1)
},
rangeEnd: function(date) {
return this.changeDayTo((this.start_of_week - 1) % 7, new Date(date.getFullYear(), date.getMonth() + 1, 0), 1)
},
isFirstDayOfWeek: function(date) {
return date.getDay() == this.start_of_week
},
isLastDayOfWeek: function(date) {
return date.getDay() == (this.start_of_week - 1) % 7
},
adjustDays: function(days) {
var newDays = [];
for (var i = 0; i < days.length; i++) {
newDays[i] = days[(i + this.start_of_week) % 7]
};
return newDays
}
};
$.fn.date_input = function(opts) {
return this.each(function() {
new DateInput(this, opts)
})
};
$.date_input = {
initialize: function(opts) {
$("input.date_input").date_input(opts)
}
};
return DateInput
})(jQuery);
//download by www.sucaijiayuan.com
|
xiaoyuexiao/best9homepage
|
js/jquery.date_input.pack.js
|
JavaScript
|
mit
| 9,928
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Webtrekk GmbH
*
* 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.
*
* Created by Thomas Dahlmann on 16.03.15.
*/
package com.webtrekk.SDKTest;
import com.webtrekk.webtrekksdk.WebtrekkApplication;
/**
* Created by user on 11/03/15.
*/
public class MyApplication extends WebtrekkApplication {
private static SDKInstanceManager mSDKManager = new SDKInstanceManager();
public SDKInstanceManager getSDKManager(){
return mSDKManager;
}
@Override
public void onCreate() {
super.onCreate();
mSDKManager.setup();
}
}
|
Webtrekk/webtrekk-android-sdk
|
sdk_test/src/main/java/com/webtrekk/SDKTest/MyApplication.java
|
Java
|
mit
| 1,622
|
## 如何使用外观模式
现在我们用 `PersistencyManager` 来管理专辑数据,用 `HTTPClient` 来处理网络请求,项目中的其他类不应该知道这个逻辑。他们只需要知道 `LibraryAPI` 这个“外观”就可以了。
为了实现外观模式,应该只让 `LibraryAPI` 持有 `PersistencyManager` 和 `HTTPClient` 的实例,然后 `LibraryAPI` 暴露一个简单的接口给其他类来访问,这样外部的访问类不需要知道内部的业务具体是怎样的,也不用知道你是通过 `PersistencyManager` 还是 `HTTPClient` 获取到数据的。
大致的设计是这样的:

`LibraryAPI` 会暴露给其他代码访问,但是 `PersistencyManager` 和 `HTTPClient` 则是不对外开放的。
打开 `LibraryAPI.swift` 然后添加如下代码:
```swift
private let persistencyManager: PersistencyManager
private let httpClient: HTTPClient
private let isOnline: Bool
```
除了两个实例变量之外,还有个 `Bool` 值: `isOnline` ,这个是用来标识当前是否为联网状态的,如果是联网状态就会去网络获取数据。
我们需要在 `init` 里面初始化这些变量:
```swift
override init() {
persistencyManager = PersistencyManager()
httpClient = HTTPClient()
isOnline = false
super.init()
}
```
`HTTPClient` 并不会直接和真实的服务器交互,只是用来演示外观模式的使用。所以 `inOnline` 这个值我们一直设置为 `false`。
接下来在 `LibraryAPI.swift` 里添加如下代码:
```swift
func getAlbums() -> [Album] {
return persistencyManager.getAlbums()
}
func addAlbum(album: Album, index: Int) {
persistencyManager.addAlbum(album, index: index)
if isOnline {
httpClient.postRequest("/api/addAlbum", body: album.description())
}
}
func deleteAlbum(index: Int) {
persistencyManager.deleteAlbumAtIndex(index)
if isOnline {
httpClient.postRequest("/api/deleteAlbum", body: "\(index)")
}
}
```
看一下 `addAlbum(_:index:)` 这个方法,先更新本地缓存,然后如果是联网状态还需要向服务器发送网络请求。这便是外观模式的强大之处:如果外部文件想要添加一个新的专辑,它不会也不用去了解内部的实现逻辑是怎么样的。
注意:当你设计外观的时候,请务必牢记:使用者随时可能直接访问你的隐藏类。永远不要假设使用者会遵循你当初的设计做事。
运行一下你的应用,你可以看到两个空的页面和一个工具栏:最上面的视图用来展示专辑封面,下面的视图展示数据列表。

你需要在屏幕上展示专辑数据,这是就该用下一种设计模式了:装饰者模式。
完成到这一步的Demo:
- [查看源码](https://github.com/yourtion/SwiftDesignPatterns-Demo1/tree/Use-Facade)
- [下载Zip](https://github.com/yourtion/SwiftDesignPatterns-Demo1/archive/Use-Facade.zip)
|
yourtion/SwiftDesignPatterns
|
Chapter05/Use-Facade.md
|
Markdown
|
mit
| 2,972
|
@extends('backend/layouts/admin')
{{-- Web site Title --}}
@section('title')
Group Management ::
@parent
@stop
{{-- Content --}}
@section('content')
{{Breadcrumbs::render('groups')}}
<div class="page-header">
<h3>
Group Management
<div class="pull-right">
<a href="{{ route('create/group') }}" class="btn btn-small btn-info"><i class="icon-plus-sign icon-white"></i> Create</a>
</div>
</h3>
</div>
{{ $groups->links() }}
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th class="span1">@lang('admin/groups/table.id')</th>
<th class="span6">@lang('admin/groups/table.name')</th>
<th class="span2">@lang('admin/groups/table.users')</th>
<th class="span2">@lang('admin/groups/table.created_at')</th>
<th class="span2">@lang('table.actions')</th>
</tr>
</thead>
<tbody>
@if ($groups->count() >= 1)
@foreach ($groups as $group)
<tr>
<td>{{ $group->id }}</td>
<td>{{ $group->name }}</td>
<td>{{ $group->users()->count() }}</td>
<td>{{ $group->created_at->diffForHumans() }}</td>
<td>
<a href="{{ route('update/group', $group->id) }}" class="btn btn-info">@lang('button.edit')</a>
<a href="{{ route('delete/group', $group->id) }}" class="btn btn-mini btn-danger">@lang('button.delete')</a>
</td>
</tr>
@endforeach
@else
<tr>
<td colspan="5">No results</td>
</tr>
@endif
</tbody>
</table>
{{ $groups->links() }}
@stop
|
atticus88/MediaCloud
|
app/views/backend/groups/index.blade.php
|
PHP
|
mit
| 1,427
|
var credentialUtil = require('../../lib/creds');
var fs = require('fs');
var path = require('path');
var test = require('tape');
var SSH_CONFIG_FILE = path.join(__dirname, '..', 'ssh_config.txt');
var GAURAV_SSH_CONFIG_FILE = path.join(__dirname, '..', 'gaurav_ssh_config.txt');
var REMTAIL_JSON_FILE = path.join(__dirname, '..', 'remtail.json');
var PRIVATE_KEY_FILE = path.join(__dirname, '..', 'privateKey.txt');
var SSH_CONFIG_CONTENTS = fs.readFileSync(SSH_CONFIG_FILE, 'UTF-8');
var GAURAV_SSH_CONFIG_CONTENTS = fs.readFileSync(GAURAV_SSH_CONFIG_FILE, 'UTF-8');
var REMTAIL_JSON_CONTENTS = fs.readFileSync(REMTAIL_JSON_FILE, 'UTF-8');
var PRIVATE_KEY_CONTENTS = fs.readFileSync(PRIVATE_KEY_FILE, 'UTF-8');
var SSH_CONFIG = credentialUtil.parseSshConfig(SSH_CONFIG_CONTENTS);
var REMTAIL_JSON = JSON.parse(REMTAIL_JSON_CONTENTS);
test('ssh config parsing', function(t) {
var expectedSshConfig = [
{
Host: 'trillworks',
HostName: 'trillworks.com',
User: 'nickc'
}, {
Host: 'globcong',
HostName: 'globcong.com',
User: 'maurice',
IdentityFile: 'test/privateKey.txt'
}
];
var sshConfig = credentialUtil.parseSshConfig(SSH_CONFIG_CONTENTS);
t.deepEquals(sshConfig, expectedSshConfig);
t.end();
});
test('basic ssh credentials map', function(t) {
var expectedCredentialsMap = {
'trillworks.com': {
user: 'nickc'
},
'globcong.com': {
user: 'maurice',
privateKey: PRIVATE_KEY_CONTENTS
}
};
var credentialsMap = credentialUtil.buildSshConfigCredentialsMap({}, SSH_CONFIG);
t.deepEquals(credentialsMap, expectedCredentialsMap);
t.end();
});
test('basic remtail credentials map', function (t) {
var expectedCredentialsMap = {
'trillworks.com': {
port: 22,
user: 'bigtex',
password: 'hunter2'
},
'globcong.com': {
user: 'peter',
password: 'blah'
},
"yahoo.com": {
user: 'ganley',
privateKey: PRIVATE_KEY_CONTENTS
}
};
var credentialsMap = credentialUtil.addFileCredentials({}, REMTAIL_JSON);
t.deepEquals(credentialsMap, expectedCredentialsMap);
t.end();
});
test('merging credentials maps', function(t) {
var expectedCredentialsMap = {
'trillworks.com': {
port: 22,
user: 'bigtex',
password: 'hunter2'
},
'globcong.com': {
user: 'peter',
password: 'blah',
privateKey: PRIVATE_KEY_CONTENTS
},
"yahoo.com": {
user: 'ganley',
privateKey: PRIVATE_KEY_CONTENTS
}
};
var credentialsMap = {};
credentialUtil.buildSshConfigCredentialsMap(credentialsMap, SSH_CONFIG);
credentialUtil.addFileCredentials(credentialsMap, REMTAIL_JSON);
t.deepEquals(credentialsMap, expectedCredentialsMap);
t.end();
});
test('gaurav ssh config with ForwardAgent entry', function(t) {
var expectedCredentialsMap = {
'ggmathur.ausoff.globcong.net': {
user: 'gaurav',
privateKey: PRIVATE_KEY_CONTENTS
},
'tst-user1.globcong.net': {
user: 'gaurav',
privateKey: PRIVATE_KEY_CONTENTS
},
'tst-user2.globcong.net': {
user: 'gaurav',
privateKey: PRIVATE_KEY_CONTENTS
},
'tst-svc1.globcong.net': {
user: 'gaurav',
privateKey: PRIVATE_KEY_CONTENTS
},
'tst-svc2.globcong.net': {
user: 'gaurav',
privateKey: PRIVATE_KEY_CONTENTS
}
};
var gauravSshConfig = credentialUtil.parseSshConfig(GAURAV_SSH_CONFIG_CONTENTS);
var credentialsMap = credentialUtil.buildSshConfigCredentialsMap({}, gauravSshConfig);
t.deepEquals(credentialsMap, expectedCredentialsMap);
t.end();
});
|
NickCarneiro/remtail
|
test/lib/test-creds.js
|
JavaScript
|
mit
| 4,007
|
using SimpleQA.Models;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace SimpleQA.WebApp.Controllers
{
public class UserController : Controller
{
readonly IModelBuilderMediator _mediator;
public UserController(IModelBuilderMediator mediator)
{
_mediator = mediator;
}
public async Task<ActionResult> Index(UserModelRequest request, CancellationToken cancel)
{
var model = await _mediator.BuildAsync<UserModelRequest, UserModel>(request, User.GetAppIdentity(), cancel);
return View(model);
}
public async Task<PartialViewResult> Inbox(CancellationToken cancel)
{
var model = await _mediator.BuildAsync<UserInboxRequest, UserInboxModel>(UserInboxRequest.Empty, User.GetAppIdentity(), cancel);
return PartialView(model);
}
}
}
|
vtortola/RedisClient
|
TestApplications/SimpleQA/SimpleQA.WebApp/Controllers/UserController.cs
|
C#
|
mit
| 915
|
/// <reference path="../../../../definitions/tsd.d.ts" />
import {AchievementProps} from "../Achievement/Achievement";
import LoginService from "../../service/LoginService";
export interface TeamProps {
_id: string;
name: string;
botId?: string;
image?: string;
unlockedAchievements?: AchievementProps[]
}
export class Team extends React.Component<TeamProps, any> {
constructor(props: TeamProps) {
super(props);
this.getEditButton = this.getEditButton.bind(this);
}
getEditButton() {
if (LoginService.getCurrentTeam() == this.props._id || LoginService.isAdmin()) {
return <a className="btn btn-primary" href={`teams/${this.props._id}/edit`}>
<i className="fa fa-pencil"></i>
</a>
}
}
render() {
return (
<div className="col-sm-6 col-md-4">
<div className="thumbnail">
<img height="20" src={this.props.image}/>
<div className="caption">
<h3>{this.props.name}</h3>
<p>
<a className="btn btn-primary" href={`teams/${this.props._id}`}>
<i className="fa fa-eye"></i>
</a>
{this.getEditButton()}
</p>
</div>
</div>
</div>
)
}
}
|
coveord/Blitz2016-Server
|
dashboard/src/client/components/Team/Team.tsx
|
TypeScript
|
mit
| 1,499
|
/*
* Certain versions of software and/or documents ("Material") accessible here may contain branding from
* Hewlett-Packard Company (now HP Inc.) and Hewlett Packard Enterprise Company. As of September 1, 2017,
* the Material is now offered by Micro Focus, a separately owned and operated company. Any reference to the HP
* and Hewlett Packard Enterprise/HPE marks is historical in nature, and the HP and Hewlett Packard Enterprise/HPE
* marks are the property of their respective owners.
* __________________________________________________________________
* MIT License
*
* (c) Copyright 2012-2019 Micro Focus or one of its affiliates.
*
* The only warranties for products and services of Micro Focus and its affiliates
* and licensors ("Micro Focus") are set forth in the express warranty statements
* accompanying such products and services. Nothing herein should be construed as
* constituting an additional warranty. Micro Focus shall not be liable for technical
* or editorial errors or omissions contained herein.
* The information contained herein is subject to change without notice.
* ___________________________________________________________________
*/
package com.microfocus.application.automation.tools.octane.executor;
import antlr.ANTLRException;
import com.hp.octane.integrations.dto.DTOFactory;
import com.hp.octane.integrations.dto.entities.EntityConstants;
import com.hp.octane.integrations.dto.executor.DiscoveryInfo;
import com.hp.octane.integrations.dto.executor.TestExecutionInfo;
import com.hp.octane.integrations.dto.executor.TestSuiteExecutionInfo;
import com.hp.octane.integrations.dto.executor.impl.TestingToolType;
import com.hp.octane.integrations.dto.scm.SCMRepository;
import com.hp.octane.integrations.executor.TestsToRunFramework;
import com.hp.octane.integrations.utils.SdkConstants;
import com.microfocus.application.automation.tools.model.ResultsPublisherModel;
import com.microfocus.application.automation.tools.octane.actions.UFTTestDetectionPublisher;
import com.microfocus.application.automation.tools.octane.configuration.SDKBasedLoggerProvider;
import com.microfocus.application.automation.tools.octane.executor.scmmanager.ScmPluginFactory;
import com.microfocus.application.automation.tools.octane.executor.scmmanager.ScmPluginHandler;
import com.microfocus.application.automation.tools.octane.testrunner.TestsToRunConverterBuilder;
import com.microfocus.application.automation.tools.results.RunResultRecorder;
import com.microfocus.application.automation.tools.run.RunFromFileBuilder;
import hudson.model.*;
import hudson.scm.SCM;
import hudson.tasks.BuildWrapper;
import hudson.tasks.Builder;
import hudson.tasks.LogRotator;
import hudson.triggers.SCMTrigger;
import jenkins.model.BuildDiscarder;
import jenkins.model.Jenkins;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This service is responsible to create jobs (discovery and execution) for execution process.
*/
public class TestExecutionJobCreatorService {
private static final Logger logger = SDKBasedLoggerProvider.getLogger(TestExecutionJobCreatorService.class);
/**
* Create (if needed) and run test execution
*
* @param suiteExecutionInfo
*/
public static void runTestSuiteExecution(TestSuiteExecutionInfo suiteExecutionInfo) {
/*
{
"tests": [{
"testName": "GUITest2",
"packageName": "GUITests"
}, {
"testName": "GUITest3",
"packageName": "GUITests"
}
],
"scmRepository": {
"type": "git",
"url": "git@github.com:radislavB/UftTests.git"
},
"executorId": "1",
"workspaceId": "1002",
"suiteId": "6",
"testingToolType": "uft"
}
*/
FreeStyleProject proj = getExecutionJob(suiteExecutionInfo);
//start job
if (proj != null) {
ParameterValue suiteRunIdParam = new StringParameterValue(UftConstants.SUITE_RUN_ID_PARAMETER_NAME, suiteExecutionInfo.getSuiteRunId());
ParameterValue suiteIdParam = new StringParameterValue(UftConstants.SUITE_ID_PARAMETER_NAME, suiteExecutionInfo.getSuiteId());
ParametersAction parameters = new ParametersAction(suiteRunIdParam, suiteIdParam);
Cause cause = StringUtils.isNotEmpty(suiteExecutionInfo.getSuiteRunId()) ? TriggeredBySuiteRunCause.create(suiteExecutionInfo.getSuiteRunId()) : new Cause.UserIdCause();
CauseAction causeAction = new CauseAction(cause);
proj.scheduleBuild2(0, parameters, causeAction);
}
}
private static FreeStyleProject getExecutionJob(TestSuiteExecutionInfo suiteExecutionInfo) {
try {
String projectName = String.format("%s %s",
UftConstants.EXECUTION_JOB_MIDDLE_NAME,
suiteExecutionInfo.getSuiteId());
//validate creation of job
FreeStyleProject proj = (FreeStyleProject) Jenkins.getInstanceOrNull().getItem(projectName);
if (proj == null) {
proj = Jenkins.getInstanceOrNull().createProject(FreeStyleProject.class, projectName);
proj.setDescription(String.format("This job was created by the Micro Focus Application Automation Tools plugin for running %s tests. It is associated with ALM Octane test suite #%s.",
suiteExecutionInfo.getTestingToolType().toString(), suiteExecutionInfo.getSuiteId()));
}
setScmRepository(suiteExecutionInfo.getScmRepository(), suiteExecutionInfo.getScmRepositoryCredentialsId(), proj, true);
setBuildDiscarder(proj, 40);
addConstantParameter(proj, UftConstants.SUITE_ID_PARAMETER_NAME, suiteExecutionInfo.getSuiteId(), "ALM Octane test suite ID");
addStringParameter(proj, UftConstants.SUITE_RUN_ID_PARAMETER_NAME, "", "The ID of the ALM Octane test suite run to associate with the test run results. Provided by ALM Octane when running a planned suite run.\nOtherwise, leave this parameter empty. ALM Octane creates a new test suite run for the new results.");
addExecutionAssignedNode(proj);
addTimestamper(proj);
//add build action
String fsTestsData = prepareMtbxData(suiteExecutionInfo.getTests());
List<RunFromFileBuilder> builders = proj.getBuildersList().getAll(RunFromFileBuilder.class);
if (builders != null && !builders.isEmpty()) {
builders.get(0).setFsTests(fsTestsData);
} else {
proj.getBuildersList().add(new RunFromFileBuilder(fsTestsData));
}
//add post-build action - publisher
RunResultRecorder runResultRecorder = null;
List publishers = proj.getPublishersList();//.add(new RunResultRecorder(ResultsPublisherModel.alwaysArchiveResults.getValue()));
for (Object publisher : publishers) {
if (publisher instanceof RunResultRecorder) {
runResultRecorder = (RunResultRecorder) publisher;
}
}
if (runResultRecorder == null) {
runResultRecorder = new RunResultRecorder(ResultsPublisherModel.alwaysArchiveResults.getValue());
publishers.add(runResultRecorder);
}
return proj;
} catch (IOException e) {
logger.error("Failed to create ExecutionJob : " + e.getMessage());
return null;
}
}
private static void setScmRepository(SCMRepository scmRepository, String scmRepositoryCredentialsId, FreeStyleProject proj, boolean executorJob) {
ScmPluginHandler scmPluginHandler = ScmPluginFactory.getScmHandler(scmRepository.getType());
try {
scmPluginHandler.setScmRepositoryInJob(scmRepository, scmRepositoryCredentialsId, proj, executorJob);
} catch (IOException e) {
throw new IllegalArgumentException("Failed to set SCM repository : " + e.getMessage());
}
}
private static String prepareMtbxData(List<TestExecutionInfo> tests) throws IOException {
/*<Mtbx>
<Test name="test1" path="${WORKSPACE}\${CHECKOUT_SUBDIR}\APITest1">
<Parameter name="A" value="abc" type="string"/>
<DataTable path="${WORKSPACE}\aa\bbb.xslx"/>
….
</Test>
<Test name="test2" path="${WORKSPACE}\${CHECKOUT_SUBDIR}\test2">
<Parameter name="p1" value="123" type="int"/>
<Parameter name="p4" value="123.4" type="float"/>
….
</Test>
</Mtbx>*/
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Mtbx");
doc.appendChild(rootElement);
for (TestExecutionInfo test : tests) {
Element testElement = doc.createElement("Test");
String packageAndTestName = (StringUtils.isNotEmpty(test.getPackageName()) ? test.getPackageName() + "\\" : "") + test.getTestName();
testElement.setAttribute("name", packageAndTestName);
String path = "${WORKSPACE}\\${CHECKOUT_SUBDIR}" + (StringUtils.isEmpty(test.getPackageName()) ? "" : SdkConstants.FileSystem.WINDOWS_PATH_SPLITTER + test.getPackageName()) +
SdkConstants.FileSystem.WINDOWS_PATH_SPLITTER + test.getTestName();
testElement.setAttribute("path", path);
if (StringUtils.isNotEmpty(test.getDataTable())) {
Element dataTableElement = doc.createElement("DataTable");
dataTableElement.setAttribute("path", "${WORKSPACE}\\${CHECKOUT_SUBDIR}" + SdkConstants.FileSystem.WINDOWS_PATH_SPLITTER + test.getDataTable());
testElement.appendChild(dataTableElement);
}
rootElement.appendChild(testElement);
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
return writer.toString();
} catch (Exception e) {
throw new IOException("Failed to build MTBX content : " + e.getMessage());
}
}
/**
* Create (if needed) and run test discovery
*
* @param discoveryInfo discovery info
*/
public static void runTestDiscovery(DiscoveryInfo discoveryInfo) {
/*
{
"scmRepository": {
"type": "git",
"url": "git@github.com:radislavB/UftTests.git"
},
"executorId": "1",
"executorLogicalName": "ABC",
"workspaceId": "1002",
"testingToolType": "uft",
"forceFullDiscovery": true
}
*/
FreeStyleProject proj = getDiscoveryJob(discoveryInfo);
//start job
if (proj != null) {
List<ParameterValue> paramList = new ArrayList<>();
ParameterValue fullScanParam = new BooleanParameterValue(UftConstants.FULL_SCAN_PARAMETER_NAME, discoveryInfo.isForceFullDiscovery());
paramList.add(fullScanParam);
ParametersDefinitionProperty parameters = proj.getProperty(ParametersDefinitionProperty.class);
if (parameters.getParameterDefinitionNames().contains(UftConstants.TEST_RUNNER_ID_PARAMETER_NAME)) {
ParameterValue testRunnerIdParam = new StringParameterValue(UftConstants.TEST_RUNNER_ID_PARAMETER_NAME, discoveryInfo.getExecutorId());
paramList.add(testRunnerIdParam);
}
ParametersAction paramAction = new ParametersAction(paramList);
Cause cause = new Cause.UserIdCause();
CauseAction causeAction = new CauseAction(cause);
proj.scheduleBuild2(0, paramAction, causeAction);
}
}
private static FreeStyleProject getDiscoveryJob(DiscoveryInfo discoveryInfo) {
if (EntityConstants.Executors.UFT_TEST_RUNNER_SUBTYPE_ENTITY_NAME.equals(discoveryInfo.getExecutorType())) {
return getDiscoveryJobForUftTestRunner(discoveryInfo);
} else {
return getDiscoveryJobForUftExecutor(discoveryInfo);
}
}
private static FreeStyleProject getDiscoveryJobForUftExecutor(DiscoveryInfo discoveryInfo) {
try {
String discoveryJobName = String.format("%s %s (%s)", UftConstants.DISCOVERY_JOB_MIDDLE_NAME, discoveryInfo.getExecutorId(), discoveryInfo.getExecutorLogicalName());
//validate creation of job
FreeStyleProject proj = (FreeStyleProject) Jenkins.getInstanceOrNull().getItem(discoveryJobName);
if (proj == null) {
proj = Jenkins.getInstanceOrNull().createProject(FreeStyleProject.class, discoveryJobName);
proj.setDescription(String.format("This job was created by the Micro Focus Application Automation Tools plugin for discovery of %s tests. It is associated with ALM Octane testing tool connection #%s.",
discoveryInfo.getTestingToolType().toString(), discoveryInfo.getExecutorId()));
}
setScmRepository(discoveryInfo.getScmRepository(), discoveryInfo.getScmRepositoryCredentialsId(), proj, false);
setBuildDiscarder(proj, 20);
addConstantParameter(proj, UftConstants.EXECUTOR_ID_PARAMETER_NAME, discoveryInfo.getExecutorId(), "ALM Octane test runner ID");
addConstantParameter(proj, UftConstants.EXECUTOR_LOGICAL_NAME_PARAMETER_NAME, discoveryInfo.getExecutorLogicalName(), "ALM Octane test runner logical name");
addBooleanParameter(proj, UftConstants.FULL_SCAN_PARAMETER_NAME, false, "Specify whether to synchronize the set of tests on ALM Octane with the whole SCM repository or to update the set of tests on ALM Octane based on the latest commits.");
//set polling once in two minutes
SCMTrigger scmTrigger = new SCMTrigger("H/2 * * * *");//H/2 * * * * : once in two minutes
proj.addTrigger(scmTrigger);
delayPollingStart(proj, scmTrigger);
addDiscoveryAssignedNode(proj);
addTimestamper(proj);
//add post-build action - publisher
UFTTestDetectionPublisher uftTestDetectionPublisher = null;
List publishers = proj.getPublishersList();
for (Object publisher : publishers) {
if (publisher instanceof UFTTestDetectionPublisher) {
uftTestDetectionPublisher = (UFTTestDetectionPublisher) publisher;
}
}
if (uftTestDetectionPublisher == null) {
uftTestDetectionPublisher = new UFTTestDetectionPublisher(discoveryInfo.getConfigurationId(), discoveryInfo.getWorkspaceId(), discoveryInfo.getScmRepositoryId());
publishers.add(uftTestDetectionPublisher);
}
return proj;
} catch (IOException | ANTLRException e) {
logger.error("Failed to create DiscoveryJob : " + e.getMessage());
return null;
}
}
private static FreeStyleProject getDiscoveryJobForUftTestRunner(DiscoveryInfo discoveryInfo) {
try {
String discoveryJobName = String.format("%s-%s-%s", UftConstants.DISCOVERY_JOB_MIDDLE_NAME_WITH_TEST_RUNNERS, discoveryInfo.getExecutorId(), discoveryInfo.getExecutorLogicalName());
//validate creation of job
FreeStyleProject proj = (FreeStyleProject) Jenkins.getInstanceOrNull().getItem(discoveryJobName);
if (proj == null) {
proj = Jenkins.getInstanceOrNull().createProject(FreeStyleProject.class, discoveryJobName);
proj.setDescription(String.format("This job was created by the Micro Focus Application Automation Tools plugin for discovery of %s tests. It is associated with ALM Octane test runner #%s.",
discoveryInfo.getTestingToolType().toString(), discoveryInfo.getExecutorId()));
}
setScmRepository(discoveryInfo.getScmRepository(), discoveryInfo.getScmRepositoryCredentialsId(), proj, false);
setBuildDiscarder(proj, 20);
addConstantParameter(proj, UftConstants.TEST_RUNNER_ID_PARAMETER_NAME, discoveryInfo.getExecutorId(), "ALM Octane test runner ID");
addConstantParameter(proj, UftConstants.TEST_RUNNER_LOGICAL_NAME_PARAMETER_NAME, discoveryInfo.getExecutorLogicalName(), "ALM Octane test runner logical name");
addBooleanParameter(proj, UftConstants.FULL_SCAN_PARAMETER_NAME, false, "Specify whether to synchronize the set of tests on ALM Octane with the whole SCM repository or to update the set of tests on ALM Octane based on the latest commits.");
//set polling once in two minutes
SCMTrigger scmTrigger = new SCMTrigger("H/2 * * * *");//H/2 * * * * : once in two minutes
proj.addTrigger(scmTrigger);
delayPollingStart(proj, scmTrigger);
addDiscoveryAssignedNode(proj);
addTimestamper(proj);
//add post-build action - publisher
UFTTestDetectionPublisher uftTestDetectionPublisher = null;
List publishers = proj.getPublishersList();
for (Object publisher : publishers) {
if (publisher instanceof UFTTestDetectionPublisher) {
uftTestDetectionPublisher = (UFTTestDetectionPublisher) publisher;
}
}
if (uftTestDetectionPublisher == null) {
uftTestDetectionPublisher = new UFTTestDetectionPublisher(discoveryInfo.getConfigurationId(), discoveryInfo.getWorkspaceId(), discoveryInfo.getScmRepositoryId());
publishers.add(uftTestDetectionPublisher);
}
return proj;
} catch (IOException | ANTLRException e) {
logger.error("Failed to create DiscoveryJob for test runner: " + e.getMessage());
return null;
}
}
private static void addTimestamper(FreeStyleProject proj) {
try {
Descriptor<BuildWrapper> wrapperDescriptor = Jenkins.getInstanceOrNull().getBuildWrapper("TimestamperBuildWrapper");
if (wrapperDescriptor != null) {
BuildWrapper wrapper = proj.getBuildWrappersList().get(wrapperDescriptor);
if (wrapper == null) {
wrapper = wrapperDescriptor.newInstance(null, null);
proj.getBuildWrappersList().add(wrapper);
}
}
} catch (Descriptor.FormException e) {
logger.error("Failed to addTimestamper : " + e.getMessage());
}
}
private static void setBuildDiscarder(FreeStyleProject proj, int numBuildsToKeep) throws IOException {
int irrelevant = -1;
BuildDiscarder bd = new LogRotator(irrelevant, numBuildsToKeep, irrelevant, irrelevant);
proj.setBuildDiscarder(bd);
}
/**
* Delay starting of polling by 5 minutes to allow original clone
*
* @param proj
* @param scmTrigger
*/
private static void delayPollingStart(final FreeStyleProject proj, final SCMTrigger scmTrigger) {
long delayStartPolling = 1000L * 60 * 5;//5 minute
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
scmTrigger.start(proj, false);
}
}, delayStartPolling);
}
private static ParametersDefinitionProperty getParametersDefinitions(FreeStyleProject proj) throws IOException {
ParametersDefinitionProperty parameters = proj.getProperty(ParametersDefinitionProperty.class);
if (parameters == null) {
parameters = new ParametersDefinitionProperty(new ArrayList<>());
proj.addProperty(parameters);
}
return parameters;
}
private static void addConstantParameter(FreeStyleProject proj, String parameterName, String parameterValue, String desc) throws IOException {
ParametersDefinitionProperty parameters = getParametersDefinitions(proj);
if (parameters.getParameterDefinition(parameterName) == null) {
ParameterDefinition param = new ChoiceParameterDefinition(parameterName, new String[]{parameterValue}, desc);
parameters.getParameterDefinitions().add(param);
}
}
private static void removeParameter(FreeStyleProject proj, String parameterName) throws IOException {
ParametersDefinitionProperty parameters = getParametersDefinitions(proj);
ParameterDefinition def = parameters.getParameterDefinition(parameterName);
if (def != null) {
parameters.getParameterDefinitions().remove(def);
}
}
private static void addStringParameter(FreeStyleProject proj, String parameterName, String defaultValue, String desc) throws IOException {
ParametersDefinitionProperty parameters = getParametersDefinitions(proj);
if (parameters.getParameterDefinition(parameterName) == null) {
ParameterDefinition param = new StringParameterDefinition(parameterName, defaultValue, desc);
parameters.getParameterDefinitions().add(param);
}
}
private static void addBooleanParameter(FreeStyleProject proj, String parameterName, Boolean defaultValue, String desc) throws IOException {
ParametersDefinitionProperty parameters = getParametersDefinitions(proj);
if (parameters.getParameterDefinition(parameterName) == null) {
ParameterDefinition param = new BooleanParameterDefinition(parameterName, defaultValue, desc);
parameters.getParameterDefinitions().add(param);
}
}
private static void addDiscoveryAssignedNode(FreeStyleProject proj) {
try {
Label joinedLabel = Label.parseExpression(Jenkins.getInstanceOrNull().getSelfLabel() + "||" + Jenkins.getInstanceOrNull().getSelfLabel());
//why twice Jenkins.getInstance().getSelfLabel()==master? because only one master is not saved in method proj.setAssignedLabel as it is label of Jenkins.getInstance().getSelfLabel()
proj.setAssignedLabel(joinedLabel);
} catch (ANTLRException | IOException e) {
logger.error("Failed to set add DiscoveryAssignedNode : " + e.getMessage());
}
}
private static void addExecutionAssignedNode(FreeStyleProject proj) {
Computer[] computers = Jenkins.getInstanceOrNull().getComputers();
Set<String> labels = new HashSet();
//add existing
String assigned = proj.getAssignedLabelString();
if (assigned != null) {
String[] assignedArr = StringUtils.split(assigned, "||");
for (String item : assignedArr) {
labels.add(item.trim());
}
}
//try to add new
try {
for (Computer computer : computers) {
if (computer instanceof Jenkins.MasterComputer) {
continue;
}
String label = "" + computer.getNode().getSelfLabel();
if (label.toLowerCase().contains("uft")) {
label = label.trim();
Pattern p = Pattern.compile("[^\\w]");
Matcher m = p.matcher(label);
if (m.find()){
//if contain non-letter/digit character, wrap with "
label = "\"" + label + "\"";
}
labels.add(label);
}
}
if (!labels.isEmpty()) {
String joined = StringUtils.join(labels, "||");
//if there are more than 1 wrapped label (for example : "label 1"), need to wrap it with parentheses
boolean parenthesesRequired = labels.stream().filter(l -> l.startsWith("\"")).count() > 1;
if (parenthesesRequired) {
joined = "(" + joined + ")";
}
proj.setAssignedLabel(Label.parseExpression(joined));
}
} catch (IOException | ANTLRException e) {
logger.error("Failed to set addExecutionAssignedNode : " + e.getMessage());
}
}
public static FreeStyleProject createExecutor(DiscoveryInfo discoveryInfo) {
try {
String projectName = String.format("%s-%s-%s", UftConstants.EXECUTION_JOB_MIDDLE_NAME_WITH_TEST_RUNNERS, discoveryInfo.getExecutorId(), discoveryInfo.getExecutorLogicalName());
//validate creation of job
FreeStyleProject proj = (FreeStyleProject) Jenkins.getInstanceOrNull().getItem(projectName);
if (proj == null) {
proj = Jenkins.getInstanceOrNull().createProject(FreeStyleProject.class, projectName);
proj.setDescription(String.format("This job was created by the Micro Focus Application Automation Tools plugin for running UFT tests. It is associated with ALM Octane test runner #%s.",
discoveryInfo.getExecutorId()));
}
setScmRepository(discoveryInfo.getScmRepository(), discoveryInfo.getScmRepositoryCredentialsId(), proj, true);
setBuildDiscarder(proj, 40);
addStringParameter(proj, UftConstants.TESTS_TO_RUN_PARAMETER_NAME, "", "Tests to run");
addStringParameter(proj, UftConstants.CHEKOUT_DIR_PARAMETER_NAME, "${WORKSPACE}\\${CHECKOUT_SUBDIR}", "Shared UFT directory");
addConstantParameter(proj, UftConstants.TEST_RUNNER_ID_PARAMETER_NAME, discoveryInfo.getExecutorId(), "ALM Octane test runner ID");
addConstantParameter(proj, UftConstants.TEST_RUNNER_LOGICAL_NAME_PARAMETER_NAME, discoveryInfo.getExecutorLogicalName(), "ALM Octane test runner logical name");
addStringParameter(proj, UftConstants.SUITE_ID_PARAMETER_NAME, "", "ALM Octane test suite ID");
addStringParameter(proj, UftConstants.SUITE_RUN_ID_PARAMETER_NAME, "", "The ID of the ALM Octane test suite run to associate with the test run results.");
addExecutionAssignedNode(proj);
addTimestamper(proj);
//add build action
Builder convertedBuilder = new TestsToRunConverterBuilder(TestsToRunFramework.MF_UFT.value());
Builder uftRunner = new RunFromFileBuilder("${testsToRunConverted}");
proj.getBuildersList().add(convertedBuilder);
proj.getBuildersList().add(uftRunner);
//add post-build action - publisher
RunResultRecorder runResultRecorder = null;
List publishers = proj.getPublishersList();
for (Object publisher : publishers) {
if (publisher instanceof RunResultRecorder) {
runResultRecorder = (RunResultRecorder) publisher;
}
}
if (runResultRecorder == null) {
runResultRecorder = new RunResultRecorder(ResultsPublisherModel.alwaysArchiveResults.getValue());
publishers.add(runResultRecorder);
}
return proj;
} catch (IOException e) {
logger.error("Failed to create executor job : " + e.getMessage());
return null;
}
}
/**
* This method is called after upgrade uftExecutor to testRunner in Octane. Upgrade contains reference to non-existing executor job.
* This method is intended to create missing executor job.
* Creation is triggered only if missing job name starts with UftConstants.EXECUTION_JOB_MIDDLE_NAME_WITH_TEST_RUNNERS.
* Scm details for new job is taken from matching discovery job. Matching is done by testRunner logical name
* @param uftExecutorJobNameWithTestRunner
* @return
*/
public static FreeStyleProject createExecutorByJobName(String uftExecutorJobNameWithTestRunner) throws IOException {
if (StringUtils.isNotEmpty(uftExecutorJobNameWithTestRunner) && uftExecutorJobNameWithTestRunner.startsWith(UftConstants.EXECUTION_JOB_MIDDLE_NAME_WITH_TEST_RUNNERS)) {
DTOFactory dtoFactory = DTOFactory.getInstance();
String[] parts = uftExecutorJobNameWithTestRunner.split("-");
String testRunnerId = parts[parts.length - 2];
String testRunnerLogicalName = parts[parts.length - 1];
//find matching discovery job
List<FreeStyleProject> jobs = Jenkins.getInstanceOrNull().getAllItems(FreeStyleProject.class);
FreeStyleProject foundDiscoveryJob = null;
for (FreeStyleProject job : jobs) {
if (UftJobRecognizer.isDiscoveryJob(job)) {
ParametersDefinitionProperty parameters = job.getProperty(ParametersDefinitionProperty.class);
ParameterDefinition parameterDefinition;
boolean replaceParams = false;
if (parameters.getParameterDefinitionNames().contains(UftConstants.TEST_RUNNER_LOGICAL_NAME_PARAMETER_NAME)) {
parameterDefinition = parameters.getParameterDefinition(UftConstants.TEST_RUNNER_LOGICAL_NAME_PARAMETER_NAME);
} else {
parameterDefinition = parameters.getParameterDefinition(UftConstants.EXECUTOR_LOGICAL_NAME_PARAMETER_NAME);
replaceParams = true;
}
if (parameterDefinition != null && testRunnerLogicalName.equals(parameterDefinition.getDefaultParameterValue().getValue().toString())) {
foundDiscoveryJob = job;
if(replaceParams){
addConstantParameter(job, UftConstants.TEST_RUNNER_ID_PARAMETER_NAME, testRunnerId, "ALM Octane test runner ID");
addConstantParameter(job, UftConstants.TEST_RUNNER_LOGICAL_NAME_PARAMETER_NAME, testRunnerLogicalName, "ALM Octane test runner logical name");
removeParameter(job,UftConstants.EXECUTOR_LOGICAL_NAME_PARAMETER_NAME);
removeParameter(job,UftConstants.EXECUTOR_ID_PARAMETER_NAME);
job.save();
}
break;
}
}
}
if (foundDiscoveryJob != null) {
//build DiscoveryInfo
DiscoveryInfo discoveryInfo = dtoFactory.newDTO(DiscoveryInfo.class);
discoveryInfo.setExecutorId(testRunnerId);
discoveryInfo.setExecutorLogicalName(testRunnerLogicalName);
discoveryInfo.setTestingToolType(TestingToolType.UFT);
SCM scm = foundDiscoveryJob.getScm();
ScmPluginHandler scmHandler = ScmPluginFactory.getScmHandlerByScmPluginName(scm.getClass().getName());
discoveryInfo.setScmRepositoryCredentialsId(scmHandler.getScmRepositoryCredentialsId(scm));
discoveryInfo.setScmRepository(dtoFactory.newDTO(SCMRepository.class)
.setType(scmHandler.getScmType())
.setUrl(scmHandler.getScmRepositoryUrl(scm)));
//createExecutor
return TestExecutionJobCreatorService.createExecutor(discoveryInfo);
} else {
logger.warn(uftExecutorJobNameWithTestRunner + " : job is no found. Trial to create it failed as no discovery job is found with test runner logical name " + testRunnerLogicalName);
}
}
return null;
}
}
|
HPSoftware/hpaa-octane-dev
|
src/main/java/com/microfocus/application/automation/tools/octane/executor/TestExecutionJobCreatorService.java
|
Java
|
mit
| 28,945
|
<table width="90%" border="0"><tr><td><script>function openfile(url) {fullwin = window.open(url, "fulltext", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes");}</script><div class="flayoutclass"><div class="flayoutclass_first"><table class="tableoutfmt2"><tr><th class="std1"><b>條目 </b></th><td class="std2">反掌折枝</td></tr>
<tr><th class="std1"><b>注音 </b></th><td class="std2">ㄈㄢ<sup class="subfont">ˇ</sup> ㄓㄤ<sup class="subfont">ˇ</sup> ㄓㄜ<sup class="subfont">ˊ</sup> ㄓ</td></tr>
<tr><th class="std1"><b>漢語拼音 </b></th><td class="std2"><font class="english_word">fǎn zhǎng zhé zhī</font></td></tr>
<tr><th class="std1"><b>釋義 </b></th><td class="std2">反轉手掌,折取樹枝。比喻至簡易之事。</td></tr>
<tr><th class="std1"><b><font class="fltypefont">附錄</font> </b></th><td class="std2">修訂本參考資料</td></tr>
</td></tr></table></div> <!-- flayoutclass_first --><div class="flayoutclass_second"></div> <!-- flayoutclass_second --></div> <!-- flayoutclass --></td></tr></table>
|
BuzzAcademy/idioms-moe-unformatted-data
|
all-data/9000-9999/9814-22.html
|
HTML
|
mit
| 1,125
|
<table width="90%" border="0"><tr><td><script>function openfile(url) {fullwin = window.open(url, "fulltext", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes");}</script><div class="flayoutclass"><div class="flayoutclass_first"><table class="tableoutfmt2"><tr><th class="std1"><b>條目 </b></th><td class="std2">歸真反璞</td></tr>
<tr><th class="std1"><b>注音 </b></th><td class="std2">ㄍㄨㄟ ㄓㄣ ㄈㄢ<sup class="subfont">ˇ</sup> ㄆㄨ<sup class="subfont">ˊ</sup></td></tr>
<tr><th class="std1"><b>漢語拼音 </b></th><td class="std2"><font class="english_word">guī zhēn fǎn pú</font></td></tr>
<tr><th class="std1"><b>釋義 </b></th><td class="std2"><img src=/cydic/dicword/fe59.jpg border=0 alt=* class=fontimg valign=center>除去外飾,回復淳樸的本性。戰國策˙齊策四:<img src=/cydic/dicword/fa40.gif border=0 alt=* class=fontimg valign=center>歸真反璞,則終身不辱。<img src=/cydic/dicword/fa41.gif border=0 alt=* class=fontimg valign=center><img src=/cydic/dicword/fe5a.jpg border=0 alt=* class=fontimg valign=center>死亡。常用於弔喪輓聯。或作<img src=/cydic/dicword/fa40.gif border=0 alt=* class=fontimg valign=center>歸真返璞<img src=/cydic/dicword/fa41.gif border=0 alt=* class=fontimg valign=center>。</td></tr>
<tr><th class="std1"><b><font class="fltypefont">附錄</font> </b></th><td class="std2">修訂本參考資料</td></tr>
</td></tr></table></div> <!-- flayoutclass_first --><div class="flayoutclass_second"></div> <!-- flayoutclass_second --></div> <!-- flayoutclass --></td></tr></table>
|
BuzzAcademy/idioms-moe-unformatted-data
|
all-data/10000-10999/10738-22.html
|
HTML
|
mit
| 1,651
|
<!DOCTYPE html>
<html prefix="og: http://ogp.me/ns# article: http://ogp.me/ns/article# " lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Posts about Support Worker | Minstry Of Education Jobs</title>
<link href="../assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="../assets/css/bootstrap-responsive.min.css" rel="stylesheet" type="text/css">
<link href="../assets/css/rst.css" rel="stylesheet" type="text/css">
<link href="../assets/css/code.css" rel="stylesheet" type="text/css">
<link href="../assets/css/colorbox.css" rel="stylesheet" type="text/css">
<link href="../assets/css/theme.css" rel="stylesheet" type="text/css">
<link rel="alternate" type="application/rss+xml" title="RSS" href="../rss.xml">
<link rel="canonical" href="http://wcmckee.com/minedujobs/categories/support-worker.html">
<!--[if lt IE 9]><script src="../assets/js/html5.js"></script><![endif]--><link rel="alternate" type="application/rss+xml" title="RSS for tag Support Worker" href="support-worker.xml">
</head>
<body class="home blog">
<div id="wrap" style="width:850px">
<div id="container" style="width:560px">
<article class="tagpage"><header><h1>Posts about Support Worker</h1>
<div class="metadata">
<p class="feedlink"><a href="support-worker.xml" type="application/rss+xml">RSS feed</a></p>
</div>
</header><ul class="postlist">
<li>
<time class="listdate" datetime="2015-10-01T09:00:00+13:00" title="2015-10-01 09:00">2015-10-01 09:00</time><a href="../posts/1184055.html" class="listtitle">1184055</a><a></a>
</li>
</ul></article>
</div>
<div id="sidebar">
<!--Sidebar content-->
<h1 id="blog-title">
<a href="http://wcmckee.com/minedujobs/" title="Minstry Of Education Jobs">Minstry Of Education Jobs</a>
</h1>
<ul class="unstyled">
<li>
<a rel="license" href="http://creativecommons.org/licenses/by/4.0/">
<img alt="Creative Commons Attribution 4.0 International License" style="border-width:0; margin-bottom:12px;" src="https://i.creativecommons.org/l/by/4.0/88x31.png"></a>
</li>
<li>
<a href="../archive.html">Archives</a>
</li>
<li>
<a href="index.html">Tags</a>
</li>
<li>
<a href="../rss.xml">RSS feed</a>
</li>
<li>
</ul>
</div>
<div id="footer">
Contents © 2015 <a href="mailto:joe@demo.site">Ministry Of Education</a> - Powered by <a href="https://getnikola.com" rel="nofollow">Nikola</a>
<a rel="license" href="http://creativecommons.org/licenses/by/4.0/">
<img alt="Creative Commons Attribution 4.0 International License" style="border-width:0; margin-bottom:12px;" src="https://i.creativecommons.org/l/by/4.0/88x31.png"></a>
</div>
</div>
<script src="../assets/js/jquery.min.js"></script><script src="../assets/js/bootstrap.min.js"></script><script src="../assets/js/moment-with-locales.min.js"></script><script src="../assets/js/fancydates.js"></script><script src="../assets/js/jquery.colorbox-min.js"></script><script type="text/javascript">jQuery("a.image-reference").colorbox({rel:"gal",maxWidth:"100%",maxHeight:"100%",scalePhotos:true});</script>
</body>
</html>
|
wcmckee/moejobs-site
|
output/categories/support-worker.html
|
HTML
|
mit
| 3,428
|
# frozen_string_literal: true
require 'test_helper'
describe "Main" do
def app
MainController
end
include Rack::Test::Methods
it "/" do
get "/"
last_response.content_type.must_include "text/html"
last_response.body.must_include "Podcast"
end
end
|
ninoseki/the_noises_podcast
|
test/main_test.rb
|
Ruby
|
mit
| 276
|
<?php
declare(strict_types=1);
/*
* This file is part of the MediaModule for Zikula.
*
* (c) Christian Flach <hi@christianflach.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Cmfcmf\Module\MediaModule\Security\CollectionPermission;
use Cmfcmf\Module\MediaModule\Entity\Collection\Permission\AbstractPermissionEntity;
use Doctrine\ORM\Query\Expr;
use Doctrine\ORM\QueryBuilder;
/**
* Represents a collection permission.
*/
interface CollectionPermissionInterface
{
/**
* Get the collection permission id.
*
* @return string
*/
public function getId();
/**
* Get the collection permission title.
*
* @return string
*/
public function getTitle();
/**
* Get a string representation of the targeted users of the given permission entity.
*
* @param AbstractPermissionEntity $permissionEntity
*
* @return string
*/
public function getTargets($permissionEntity);
/**
* Get the entity class related to this collection permission.
*
* @return string
*/
public function getEntityClass();
/**
* Get the form class related to this collection permission.
*
* @return string
*/
public function getFormClass();
/**
* Extends the given query builder to only return applicable permissions to the current user.
*
* @param QueryBuilder &$qb
* @param $permissionAlias
*
* @return Expr|null
*/
public function getApplicablePermissionsExpression(QueryBuilder &$qb, $permissionAlias);
}
|
cmfcmf/MediaModule
|
Security/CollectionPermission/CollectionPermissionInterface.php
|
PHP
|
mit
| 1,685
|
#############################################################################
# Makefile for building: tst_nodebeamtests
# Generated by qmake (3.0) (Qt 5.4.0)
# Project: ..\NodeBeamTests\NodeBeamTests.pro
# Template: app
# Command: C:\Qt\5.4\mingw491_32\bin\qmake.exe -spec win32-g++ CONFIG+=debug -o Makefile ..\NodeBeamTests\NodeBeamTests.pro
#############################################################################
MAKEFILE = Makefile
first: debug
install: debug-install
uninstall: debug-uninstall
QMAKE = C:\Qt\5.4\mingw491_32\bin\qmake.exe
DEL_FILE = del
CHK_DIR_EXISTS= if not exist
MKDIR = mkdir
COPY = copy /y
COPY_FILE = $(COPY)
COPY_DIR = xcopy /s /q /y /i
INSTALL_FILE = $(COPY_FILE)
INSTALL_PROGRAM = $(COPY_FILE)
INSTALL_DIR = $(COPY_DIR)
DEL_FILE = del
SYMLINK = copy /y
DEL_DIR = rmdir
MOVE = move
SUBTARGETS = \
debug \
release
debug: FORCE
$(MAKE) -f $(MAKEFILE).Debug
debug-make_first: FORCE
$(MAKE) -f $(MAKEFILE).Debug
debug-all: FORCE
$(MAKE) -f $(MAKEFILE).Debug all
debug-clean: FORCE
$(MAKE) -f $(MAKEFILE).Debug clean
debug-distclean: FORCE
$(MAKE) -f $(MAKEFILE).Debug distclean
debug-install: FORCE
$(MAKE) -f $(MAKEFILE).Debug install
debug-uninstall: FORCE
$(MAKE) -f $(MAKEFILE).Debug uninstall
release: FORCE
$(MAKE) -f $(MAKEFILE).Release
release-make_first: FORCE
$(MAKE) -f $(MAKEFILE).Release
release-all: FORCE
$(MAKE) -f $(MAKEFILE).Release all
release-clean: FORCE
$(MAKE) -f $(MAKEFILE).Release clean
release-distclean: FORCE
$(MAKE) -f $(MAKEFILE).Release distclean
release-install: FORCE
$(MAKE) -f $(MAKEFILE).Release install
release-uninstall: FORCE
$(MAKE) -f $(MAKEFILE).Release uninstall
Makefile: ../NodeBeamTests/NodeBeamTests.pro C:/Qt/5.4/mingw491_32/mkspecs/win32-g++/qmake.conf C:/Qt/5.4/mingw491_32/mkspecs/features/spec_pre.prf \
C:/Qt/5.4/mingw491_32/mkspecs/qdevice.pri \
C:/Qt/5.4/mingw491_32/mkspecs/features/device_config.prf \
C:/Qt/5.4/mingw491_32/mkspecs/common/shell-win32.conf \
C:/Qt/5.4/mingw491_32/mkspecs/qconfig.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_axbase.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_axbase_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_axcontainer.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_axcontainer_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_axserver.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_axserver_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_bluetooth.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_bluetooth_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_bootstrap_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_clucene_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_concurrent.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_concurrent_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_core.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_core_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_declarative.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_declarative_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_designer.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_designer_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_designercomponents_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_enginio.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_enginio_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_gui.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_gui_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_help.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_help_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_location.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_location_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_multimedia.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_multimedia_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_multimediawidgets.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_multimediawidgets_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_network.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_network_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_nfc.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_nfc_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_opengl.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_opengl_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_openglextensions.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_openglextensions_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_platformsupport_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_positioning.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_positioning_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_printsupport.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_printsupport_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_qml.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_qml_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_qmldevtools_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_qmltest.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_qmltest_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_qtmultimediaquicktools_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_quick.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_quick_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_quickparticles_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_quickwidgets.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_quickwidgets_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_script.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_script_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_scripttools.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_scripttools_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_sensors.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_sensors_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_serialport.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_serialport_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_sql.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_sql_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_svg.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_svg_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_testlib.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_testlib_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_uitools.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_uitools_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_webchannel.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_webchannel_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_webkit.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_webkit_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_webkitwidgets.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_webkitwidgets_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_websockets.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_websockets_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_webview.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_webview_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_widgets.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_widgets_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_winextras.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_winextras_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_xml.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_xml_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_xmlpatterns.pri \
C:/Qt/5.4/mingw491_32/mkspecs/modules/qt_lib_xmlpatterns_private.pri \
C:/Qt/5.4/mingw491_32/mkspecs/features/qt_functions.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/qt_config.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/win32/qt_config.prf \
C:/Qt/5.4/mingw491_32/mkspecs/win32-g++/qmake.conf \
C:/Qt/5.4/mingw491_32/mkspecs/features/spec_post.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/exclusive_builds.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/default_pre.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/win32/default_pre.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/resolve_config.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/exclusive_builds_post.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/default_post.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/win32/console.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/win32/rtti.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/precompile_header.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/warn_on.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/qt.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/resources.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/moc.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/testlib_defines.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/win32/opengl.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/uic.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/testcase_targets.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/exceptions.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/yacc.prf \
C:/Qt/5.4/mingw491_32/mkspecs/features/lex.prf \
../NodeBeamTests/NodeBeamTests.pro \
C:/Qt/5.4/mingw491_32/lib/Qt5OpenGL.prl \
C:/Qt/5.4/mingw491_32/lib/Qt5Widgets.prl \
C:/Qt/5.4/mingw491_32/lib/Qt5Gui.prl \
C:/Qt/5.4/mingw491_32/lib/Qt5Test.prl \
C:/Qt/5.4/mingw491_32/lib/Qt5Core.prl
$(QMAKE) -spec win32-g++ CONFIG+=debug -o Makefile ..\NodeBeamTests\NodeBeamTests.pro
C:\Qt\5.4\mingw491_32\mkspecs\features\spec_pre.prf:
C:\Qt\5.4\mingw491_32\mkspecs\qdevice.pri:
C:\Qt\5.4\mingw491_32\mkspecs\features\device_config.prf:
C:\Qt\5.4\mingw491_32\mkspecs\common\shell-win32.conf:
C:\Qt\5.4\mingw491_32\mkspecs\qconfig.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_axbase.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_axbase_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_axcontainer.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_axcontainer_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_axserver.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_axserver_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_bluetooth.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_bluetooth_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_bootstrap_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_clucene_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_concurrent.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_concurrent_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_core.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_core_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_declarative.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_declarative_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_designer.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_designer_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_designercomponents_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_enginio.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_enginio_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_gui.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_gui_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_help.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_help_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_location.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_location_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_multimedia.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_multimedia_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_multimediawidgets.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_multimediawidgets_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_network.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_network_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_nfc.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_nfc_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_opengl.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_opengl_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_openglextensions.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_openglextensions_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_platformsupport_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_positioning.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_positioning_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_printsupport.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_printsupport_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_qml.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_qml_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_qmldevtools_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_qmltest.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_qmltest_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_qtmultimediaquicktools_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_quick.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_quick_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_quickparticles_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_quickwidgets.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_quickwidgets_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_script.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_script_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_scripttools.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_scripttools_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_sensors.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_sensors_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_serialport.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_serialport_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_sql.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_sql_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_svg.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_svg_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_testlib.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_testlib_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_uitools.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_uitools_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_webchannel.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_webchannel_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_webkit.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_webkit_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_webkitwidgets.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_webkitwidgets_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_websockets.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_websockets_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_webview.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_webview_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_widgets.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_widgets_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_winextras.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_winextras_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_xml.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_xml_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_xmlpatterns.pri:
C:\Qt\5.4\mingw491_32\mkspecs\modules\qt_lib_xmlpatterns_private.pri:
C:\Qt\5.4\mingw491_32\mkspecs\features\qt_functions.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\qt_config.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\win32\qt_config.prf:
C:\Qt\5.4\mingw491_32\mkspecs\win32-g++\qmake.conf:
C:\Qt\5.4\mingw491_32\mkspecs\features\spec_post.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\exclusive_builds.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\default_pre.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\win32\default_pre.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\resolve_config.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\exclusive_builds_post.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\default_post.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\win32\console.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\win32\rtti.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\precompile_header.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\warn_on.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\qt.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\resources.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\moc.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\testlib_defines.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\win32\opengl.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\uic.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\testcase_targets.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\exceptions.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\yacc.prf:
C:\Qt\5.4\mingw491_32\mkspecs\features\lex.prf:
..\NodeBeamTests\NodeBeamTests.pro:
C:/Qt/5.4/mingw491_32/lib/Qt5OpenGL.prl:
C:/Qt/5.4/mingw491_32/lib/Qt5Widgets.prl:
C:/Qt/5.4/mingw491_32/lib/Qt5Gui.prl:
C:/Qt/5.4/mingw491_32/lib/Qt5Test.prl:
C:/Qt/5.4/mingw491_32/lib/Qt5Core.prl:
qmake: FORCE
@$(QMAKE) -spec win32-g++ CONFIG+=debug -o Makefile ..\NodeBeamTests\NodeBeamTests.pro
qmake_all: FORCE
make_first: debug-make_first release-make_first FORCE
all: debug-all release-all FORCE
clean: debug-clean release-clean FORCE
distclean: debug-distclean release-distclean FORCE
-$(DEL_FILE) Makefile
debug-mocclean:
$(MAKE) -f $(MAKEFILE).Debug mocclean
release-mocclean:
$(MAKE) -f $(MAKEFILE).Release mocclean
mocclean: debug-mocclean release-mocclean
debug-mocables:
$(MAKE) -f $(MAKEFILE).Debug mocables
release-mocables:
$(MAKE) -f $(MAKEFILE).Release mocables
mocables: debug-mocables release-mocables
check: first
FORCE:
$(MAKEFILE).Debug: Makefile
$(MAKEFILE).Release: Makefile
|
RORMasa/NodeBeamEditor
|
source/test/build-NodeBeamTests-Desktop_Qt_Qt_Version_MinGW_32bit-Debug/Makefile
|
Makefile
|
mit
| 18,118
|
# Variables
$projectDir = Get-Location
$outdir = "${env:ProgramFiles(x86)}\Microsoft SDKs\NuGetPackages\"
# Build azure-amqp
sl Dependencies\azure-amqp\Microsoft.Azure.Amqp\
dotnet restore
dotnet build
dotnet pack
sl $projectDir
# Install azure-amqp
cp Dependencies\azure-amqp\Microsoft.Azure.Amqp\bin\Debug\Microsoft.Azure.Amqp.2.0.0.nupkg $outdir
cp Dependencies\azure-amqp\Microsoft.Azure.Amqp\bin\Debug\Microsoft.Azure.Amqp.2.0.0.symbols.nupkg $outdir
# Build azure-event-hubs
## Build Microsoft.Azure.EventHubs
sl Dependencies\azure-event-hubs\csharp\src\Microsoft.Azure.EventHubs
dotnet restore
dotnet build
dotnet pack
## Install Microsoft.Azure.EventHubs
sl bin\Debug
cp Microsoft.Azure.EventHubs.1.0.0.nupkg $outdir
cp Microsoft.Azure.EventHubs.1.0.0.symbols.nupkg $outdir
sl ..\..
## Build Microsoft.Azure.EventHubs.Processor
sl ..\Microsoft.Azure.EventHubs.Processor
dotnet restore
dotnet build
dotnet pack
## Install Microsoft.Azure.EventHubs.Processor
sl bin\Debug
cp Microsoft.Azure.EventHubs.Processor.1.0.0.nupkg $outdir
cp Microsoft.Azure.EventHubs.Processor.1.0.0.symbols.nupkg $outdir
sl $projectDir
|
jonmseaman/WebSocketToEventHub
|
configure.ps1
|
PowerShell
|
mit
| 1,126
|
module Hancock::Pages::Decorators
module Pages
extend ActiveSupport::Concern
# included do
# def model
# Hancock::Pages::Page
# end
#
# def after_initialize
# end
# end
end
end
|
red-rocks/hancock_cms_pages
|
app/controllers/concerns/hancock/pages/decorators/pages.rb
|
Ruby
|
mit
| 231
|
module PmLibrary
extend ActiveSupport::Concern
included do
before_action :ensure_logged_in
end
private
def ensure_pm_topic_exists
redirect_to root_url if pm_topic.nil?
end
def ensure_valid_user
redirect_to root_url unless pm_topic.users.include?(current_user)
end
def user
current_user == pm_topic.sender ? 'sender' : 'recipient'
end
def correspondent
user == 'sender' ? 'recipient' : 'sender'
end
def user_handshake
"#{user}_handshake".to_sym
end
def user_unread
"#{user}_unread".to_sym
end
def correspondent_unread
"#{correspondent}_unread".to_sym
end
end
|
cribbles/tiktak
|
app/controllers/concerns/pm_library.rb
|
Ruby
|
mit
| 635
|
class PunchClockSetsController < ApplicationController
layout "payforms"
helper :punch_clocks
before_filter :require_department_admin
def index
@punch_clock_sets = PunchClockSet.all
end
def new
@punch_clock_set = PunchClockSet.new
@users_select = current_department.active_users.sort_by(&:name)
end
def create
@punch_clock_set = PunchClockSet.new(params[:punch_clock_set])
@punch_clock_set.department = current_department
if @punch_clock_set.save
flash[:notice] = "Mass punch clock was successfully created."
failed = []
params[:users].remove_blank.each do |uid|
clock = PunchClock.new({description: @punch_clock_set.description,
department: current_department,
user_id: uid,
runtime: 0,
last_touched: Time.now,
punch_clock_set_id: @punch_clock_set.id})
failed << User.find(uid).name unless clock.save
end
flash[:warning] = "Could not clock in the following users: #{failed.to_sentence}." unless failed.empty?
redirect_to action: :index
else
@users_select = current_department.active_users.sort_by(&:name)
render action: :new
end
end
def update
@punch_clock_set = PunchClockSet.find(params[:id])
messages = []
@punch_clock_set.punch_clocks.each do |pc|
if params[:pause]
error = pc.pause unless pc.paused?
messages << "Could not pause #{pc.user.name}'s clock." if error
elsif params[:unpause]
error = pc.unpause if pc.paused?
messages << "Could not unpause #{pc.user.name}'s clock." if error
elsif params[:submit] # Clocking out
messages << "Could not submit #{pc.user}'s clock: #{pc.submit}." if pc.submit
@punch_clock_set.reload
end
pc.last_touched = Time.now unless params[:submit]
pc.save if pc
end
flash[:error] = messages.join(" ") unless messages.empty?
flash[:notice] = "Submitted all clocks." if @punch_clock_set.punch_clocks.empty? && @punch_clock_set.destroy
redirect_to punch_clock_sets_path
end
# Should be refactored to use dependent: :destroy, but unsure if that works when
# the presence of the parent is optional. Must investigate. -ben
def destroy
@punch_clock_set = PunchClockSet.find(params[:id])
@punch_clock_set.punch_clocks.each {|clock| clock.destroy}
@punch_clock_set.destroy
redirect_to(punch_clock_sets_url)
end
end
|
YaleSTC/shifts
|
app/controllers/punch_clock_sets_controller.rb
|
Ruby
|
mit
| 2,588
|
#pragma once
#include <pga/compiler/Graph.h>
#include <algorithm>
#include <exception>
#include <iostream>
#include <map>
#include <set>
#include <vector>
namespace SearchHeuristics
{
struct OneToOneOperatorEdgesHeuristic : PGA::Compiler::GraphVisitor
{
std::set<size_t>& alwaysCutEdges;
std::set<size_t>& neverCutEdges;
OneToOneOperatorEdgesHeuristic(std::set<size_t>& alwaysCutEdges, std::set<size_t>& neverCutEdges) : alwaysCutEdges(alwaysCutEdges), neverCutEdges(neverCutEdges) {}
virtual bool visit(size_t i, const PGA::Compiler::Vertex_LW& vertex)
{
return true;
}
virtual bool visit(size_t i, const PGA::Compiler::Edge_LW& edge, const PGA::Compiler::Vertex_LW& src, const PGA::Compiler::Vertex_LW& dst)
{
#if defined(PGA_INVARIANT_CHECKING_LVL) && (PGA_INVARIANT_CHECKING_LVL >= 1)
if (isTerminal(src.operatorType()))
throw std::runtime_error("src can never be a terminal op.");
#endif
auto dstOpType = dst.operatorType();
if (is1To1(src.operatorType()) &&
dst.numIncomingEdges() == 1 &&
(is1To1(dstOpType) || dstOpType == PGA::Compiler::GENERATE))
{
if (alwaysCutEdges.find(i) != alwaysCutEdges.end())
{
#ifdef PGA_OPERATOR_GRAPH_ANALYZER_VERBOSE
std::cout << "partitioning has one or more conflicting heuristics for edge " << i << " (1to1)" << std::endl;
#endif
return true;
}
neverCutEdges.insert(i);
}
return true;
}
private:
#if defined(PGA_INVARIANT_CHECKING_LVL) && (PGA_INVARIANT_CHECKING_LVL >= 1)
inline bool isTerminal(PGA::Compiler::OperatorType opType) const
{
return opType == PGA::Compiler::GENERATE ||
opType == PGA::Compiler::DISCARD;
}
#endif
inline bool is1To1(PGA::Compiler::OperatorType opType) const
{
return opType == PGA::Compiler::ROTATE ||
opType == PGA::Compiler::TRANSLATE ||
opType == PGA::Compiler::SCALE ||
opType == PGA::Compiler::EXTRUDE ||
opType == PGA::Compiler::SET_AS_DYNAMIC_CONVEX_POLYGON ||
opType == PGA::Compiler::SET_AS_DYNAMIC_CONVEX_RIGHT_PRISM ||
opType == PGA::Compiler::SET_AS_DYNAMIC_CONCAVE_POLYGON ||
opType == PGA::Compiler::SET_AS_DYNAMIC_CONCAVE_POLYGON;
}
};
struct SubtreeOrderHeuristic : PGA::Compiler::GraphVisitor
{
struct Node
{
std::map<size_t, std::weak_ptr<Node>> parents;
size_t src;
std::map<size_t, std::weak_ptr<Node>> children;
Node(size_t src) : src(src) {}
~Node() {}
size_t order() const
{
return order_phase1();
}
void append(size_t edgeIdx, std::weak_ptr<Node> node)
{
children.emplace(std::make_pair(edgeIdx, node));
}
bool operator == (const Node& node) const
{
return src == node.src;
}
bool operator != (const Node& node) const
{
return !operator==(node);
}
void rollback(std::vector<std::shared_ptr<Node>>& nodes,
std::set<size_t>& neverCutEdges,
std::set<size_t>& newNeverCutEdges)
{
rollback_phase1(neverCutEdges, newNeverCutEdges);
rollback_phase2(nodes, neverCutEdges, newNeverCutEdges);
}
bool hasCommonAncestry(std::weak_ptr<Node> other) const
{
auto o = other.lock();
if (src == o->src)
return true;
if (parents.empty())
{
for (auto& otherParent : o->parents)
{
if (hasCommonAncestry(otherParent.second))
return true;
}
}
else
{
for (auto& parent : parents)
{
for (auto& otherParent : o->parents)
if (parent.second.lock()->hasCommonAncestry(otherParent.second))
return true;
}
}
return false;
}
bool addParent(size_t edgeIdx, std::weak_ptr<Node> newParent)
{
auto p0 = newParent.lock();
#if defined(PGA_INVARIANT_CHECKING_LVL) && (PGA_INVARIANT_CHECKING_LVL >= 1)
if (p0 == nullptr)
throw std::runtime_error("p0 == nullptr");
#endif
for (auto& parent : parents)
{
auto p1 = parent.second.lock();
#if defined(PGA_INVARIANT_CHECKING_LVL) && (PGA_INVARIANT_CHECKING_LVL >= 1)
if (p1 == nullptr)
throw std::runtime_error("p1 == nullptr");
#endif
if (p0 == p1)
return false;
}
parents.emplace(std::make_pair(edgeIdx, newParent));
return true;
}
private:
bool isParent(const Node* node) const
{
for (auto& parent : parents)
if (*parent.second.lock().get() == *node)
return true;
return false;
}
size_t order_phase1() const
{
if (parents.empty())
return order_phase2();
size_t acc = 0;
for (auto& parent : parents)
acc += parent.second.lock()->order_phase1();
return acc;
}
size_t order_phase2(std::set<size_t>& visited) const
{
if (visited.find(src) != visited.end())
return 0;
visited.insert(src);
size_t acc = 1;
for (auto& conn : children)
acc += conn.second.lock()->order_phase2(visited);
return acc;
}
size_t order_phase2() const
{
std::set<size_t> visited;
return order_phase2(visited);
}
void rollback_phase2(std::vector<std::shared_ptr<Node>>& nodes,
std::set<size_t>& neverCutEdges,
std::set<size_t>& newNeverCutEdges,
long connIdx,
std::set<size_t>& visited)
{
if (visited.find(src) != visited.end())
return;
visited.insert(src);
auto it1 = std::find_if(nodes.begin(), nodes.end(), NodeComparer(src));
#if defined(PGA_INVARIANT_CHECKING_LVL) && (PGA_INVARIANT_CHECKING_LVL >= 1)
if (it1 == nodes.end())
throw std::runtime_error("it1 == nodes.end()");
#endif
nodes.erase(it1);
if (connIdx != -1)
{
auto edgeIdx = static_cast<size_t>(connIdx);
auto it1 = newNeverCutEdges.find(edgeIdx);
if (it1 != newNeverCutEdges.end())
{
newNeverCutEdges.erase(it1);
auto it3 = neverCutEdges.find(edgeIdx);
#if defined(PGA_INVARIANT_CHECKING_LVL) && (PGA_INVARIANT_CHECKING_LVL >= 1)
if (it3 == neverCutEdges.end())
throw std::runtime_error("it3 == neverCutEdges.end()");
#endif
neverCutEdges.erase(it3);
}
}
for (auto& conn : children)
conn.second.lock()->rollback_phase2(nodes, neverCutEdges, newNeverCutEdges, static_cast<long>(conn.first), visited);
}
void rollback_phase2(std::vector<std::shared_ptr<Node>>& nodes,
std::set<size_t>& neverCutEdges,
std::set<size_t>& newNeverCutEdges,
long connIdx = -1)
{
std::set<size_t> visited;
rollback_phase2(nodes, neverCutEdges, newNeverCutEdges, connIdx, visited);
}
void rollback_phase1(std::set<size_t>& neverCutEdges, std::set<size_t>& newNeverCutEdges)
{
for (auto& parent : parents)
{
auto p0 = parent.second.lock();
#if defined(PGA_INVARIANT_CHECKING_LVL) && (PGA_INVARIANT_CHECKING_LVL >= 1)
if (p0 == nullptr)
throw std::runtime_error("p0 == nullptr");
#endif
auto edgeIdx = parent.first;
auto it1 = p0->children.find(edgeIdx);
p0->children.erase(it1);
auto it2 = newNeverCutEdges.find(edgeIdx);
if (it2 != newNeverCutEdges.end())
{
newNeverCutEdges.erase(it2);
auto it3 = neverCutEdges.find(edgeIdx);
#if defined(PGA_INVARIANT_CHECKING_LVL) && (PGA_INVARIANT_CHECKING_LVL >= 1)
if (it3 == neverCutEdges.end())
throw std::runtime_error("it3 == neverCutEdges.end()");
#endif
neverCutEdges.erase(it3);
}
}
}
};
struct NodeComparer
{
NodeComparer(size_t baseLine) : baseLine(baseLine) {}
bool operator()(const std::shared_ptr<Node>& a) const
{
return a->src == baseLine;
}
private:
size_t baseLine;
};
size_t maxSubtreeOrder;
std::set<size_t>& alwaysCutEdges;
std::set<size_t>& neverCutEdges;
std::set<size_t> newNeverCutEdges;
std::vector<std::shared_ptr<Node>> nodes;
SubtreeOrderHeuristic(size_t maxSubtreeOrder, std::set<size_t>& alwaysCutEdges, std::set<size_t>& neverCutEdges) : maxSubtreeOrder(maxSubtreeOrder), alwaysCutEdges(alwaysCutEdges), neverCutEdges(neverCutEdges) {}
virtual bool visit(size_t i, const PGA::Compiler::Vertex_LW& vertex)
{
return true;
}
virtual bool visit(size_t i, const PGA::Compiler::Edge_LW& edge, const PGA::Compiler::Vertex_LW& src, const PGA::Compiler::Vertex_LW& dst)
{
auto it1 = std::find_if(nodes.begin(), nodes.end(), NodeComparer(src));
if (it1 != nodes.end())
{
tryToAppendNode(*it1, src, dst, i);
return true;
}
if (src.operatorType() != PGA::Compiler::SUBDIV &&
src.operatorType() != PGA::Compiler::COMPSPLIT &&
src.operatorType() != PGA::Compiler::IFSIZELESS)
return true;
if (alwaysCutEdges.find(i) != alwaysCutEdges.end())
{
#ifdef PGA_OPERATOR_GRAPH_ANALYZER_VERBOSE
std::cout << "partitioning has one or more conflicting heuristics for edge " << i << " (sto)" << std::endl;
#endif
return true;
}
tryToAppendNode(createNode(src), src, dst, i);
return true;
}
void tryToAppendNode(std::shared_ptr<Node> srcSubtree, const PGA::Compiler::Vertex_LW& src, const PGA::Compiler::Vertex_LW& dst, size_t i)
{
std::shared_ptr<Node> dstSubtree;
bool hasOtherParent = dst.hasOtherParent(src);
auto it1 = std::find_if(nodes.begin(), nodes.end(), NodeComparer(dst));
if (it1 != nodes.end())
{
dstSubtree = *it1;
if (hasOtherParent)
{
if (srcSubtree->hasCommonAncestry(dstSubtree))
{
dstSubtree->addParent(i, static_cast<std::weak_ptr<Node>>(srcSubtree));
srcSubtree->append(i, static_cast<std::weak_ptr<Node>>(dstSubtree));
if (neverCutEdges.find(i) == neverCutEdges.end())
newNeverCutEdges.insert(i);
neverCutEdges.insert(i);
#if PGA_OPERATOR_GRAPH_ANALYZER_VERBOSE
std::cout << "added " << static_cast<size_t>(dst) << " to " << static_cast<size_t>(src) << " subtree again [edgeIdx=" << i << "] (sto)" << std::endl;
#endif
}
else
{
dstSubtree->rollback(nodes, neverCutEdges, newNeverCutEdges);
#if PGA_OPERATOR_GRAPH_ANALYZER_VERBOSE
std::cout << "rolled back " << static_cast<size_t>(dst) << " subtree! [edgeIdx=" << i << "] (sto)" << std::endl;
#endif
return;
}
}
}
if (srcSubtree->order() < maxSubtreeOrder)
{
if (hasOtherParent)
{
std::set<size_t> dstParents;
dst.getParents(dstParents);
for (auto& dstParent : dstParents)
{
if (dstParent == src) continue;
auto it2 = std::find_if(nodes.begin(), nodes.end(), NodeComparer(dstParent));
if (it2 == nodes.end())
return;
auto dstParentSubtree = *it2;
if (!srcSubtree->hasCommonAncestry(dstParentSubtree))
return;
}
}
if (dstSubtree == nullptr)
dstSubtree = createNode(dst);
dstSubtree->addParent(i, static_cast<std::weak_ptr<Node>>(srcSubtree));
srcSubtree->append(i, static_cast<std::weak_ptr<Node>>(dstSubtree));
if (neverCutEdges.find(i) == neverCutEdges.end())
newNeverCutEdges.insert(i);
neverCutEdges.insert(i);
#if PGA_OPERATOR_GRAPH_ANALYZER_VERBOSE
std::cout << "added " << static_cast<size_t>(dst) << " to " << static_cast<size_t>(src) << " subtree [edgeIdx=" << i << "] (sto)" << std::endl;
#endif
}
}
std::shared_ptr<Node> createNode(const PGA::Compiler::Vertex_LW& src)
{
#if defined(PGA_INVARIANT_CHECKING_LVL) && (PGA_INVARIANT_CHECKING_LVL >= 1)
auto it1 = std::find_if(nodes.begin(), nodes.end(), NodeComparer(src));
if (it1 != nodes.end())
throw std::runtime_error("it1 != nodes.end()");
#endif
auto nodeIdx = nodes.size();
nodes.emplace_back(new Node(src));
return nodes[nodeIdx];
}
};
struct RandomRuleHeuristic : PGA::Compiler::GraphVisitor
{
std::set<size_t>& alwaysCutEdges;
RandomRuleHeuristic(std::set<size_t>& alwaysCutEdges) : alwaysCutEdges(alwaysCutEdges) {}
virtual bool visit(size_t i, const PGA::Compiler::Vertex_LW& vertex)
{
return true;
}
virtual bool visit(size_t i, const PGA::Compiler::Edge_LW& edge, const PGA::Compiler::Vertex_LW& src, const PGA::Compiler::Vertex_LW& dst)
{
if (src.operatorType() != PGA::Compiler::STOCHASTIC)
return true;
alwaysCutEdges.insert(i);
return true;
}
};
}
|
pboechat/OperatorGraph
|
src/operator_graph_analyzer/SearchHeuristics.h
|
C
|
mit
| 12,034
|
var _ember = require('ember');
_ember['default'].debug('this will NOT be removed');
warn('this will NOT be removed');
info('this will NOT be removed');
console.log(message);
|
GavinJoyce/babel-plugin-remove-functions
|
test/fixtures/global-namespace/expected.js
|
JavaScript
|
mit
| 176
|
import numpy as np
class lemketableau:
def __init__(self,M,q,maxIter = 100):
n = len(q)
self.T = np.hstack((np.eye(n),-M,-np.ones((n,1)),q.reshape((n,1))))
self.n = n
self.wPos = np.arange(n)
self.zPos = np.arange(n,2*n)
self.W = 0
self.Z = 1
self.Y = 2
self.Q = 3
TbInd = np.vstack((self.W*np.ones(n,dtype=int),
np.arange(n,dtype=int)))
TnbInd = np.vstack((self.Z*np.ones(n,dtype=int),
np.arange(n,dtype=int)))
DriveInd = np.array([[self.Y],[0]])
QInd = np.array([[self.Q],[0]])
self.Tind = np.hstack((TbInd,TnbInd,DriveInd,QInd))
self.maxIter = maxIter
def lemkeAlgorithm(self):
initVal = self.initialize()
if not initVal:
return np.zeros(self.n),0,'Solution Found'
for k in range(self.maxIter):
stepVal = self.step()
if self.Tind[0,-2] == self.Y:
# Solution Found
z = self.extractSolution()
return z,0,'Solution Found'
elif not stepVal:
return None,1,'Secondary ray found'
return None,2,'Max Iterations Exceeded'
def initialize(self):
q = self.T[:,-1]
minQ = np.min(q)
if minQ < 0:
ind = np.argmin(q)
self.clearDriverColumn(ind)
self.pivot(ind)
return True
else:
return False
def step(self):
q = self.T[:,-1]
a = self.T[:,-2]
ind = np.nan
minRatio = np.inf
for i in range(self.n):
if a[i] > 0:
newRatio = q[i] / a[i]
if newRatio < minRatio:
ind = i
minRatio = newRatio
if minRatio < np.inf:
self.clearDriverColumn(ind)
self.pivot(ind)
return True
else:
return False
def extractSolution(self):
z = np.zeros(self.n)
q = self.T[:,-1]
for i in range(self.n):
if self.Tind[0,i] == self.Z:
z[self.Tind[1,i]] = q[i]
return z
def partnerPos(self,pos):
v,ind = self.Tind[:,pos]
if v == self.W:
ppos = self.zPos[ind]
elif v == self.Z:
ppos = self.wPos[ind]
else:
ppos = None
return ppos
def pivot(self,pos):
ppos = self.partnerPos(pos)
if ppos is not None:
self.swapColumns(pos,ppos)
self.swapColumns(pos,-2)
return True
else:
self.swapColumns(pos,-2)
return False
def swapMatColumns(self,M,i,j):
Mi = np.array(M[:,i],copy=True)
Mj = np.array(M[:,j],copy=True)
M[:,i] = Mj
M[:,j] = Mi
return M
def swapPos(self,v,ind,newPos):
if v == self.W:
self.wPos[ind] = newPos % (2*self.n+2)
elif v == self.Z:
self.zPos[ind] = newPos % (2*self.n+2)
def swapColumns(self,i,j):
iInd = self.Tind[:,i]
jInd = self.Tind[:,j]
v,ind = iInd
self.swapPos(v,ind,j)
v,ind = jInd
self.swapPos(v,ind,i)
self.Tind = self.swapMatColumns(self.Tind,i,j)
self.T = self.swapMatColumns(self.T,i,j)
def clearDriverColumn(self,ind):
a = self.T[ind,-2]
self.T[ind] /= a
for i in range(self.n):
if i != ind:
b = self.T[i,-2]
self.T[i] -= b * self.T[ind]
def ind2str(self,indvec):
v,pos = indvec
if v == self.W:
s = 'w%d' % pos
elif v == self.Z:
s = 'z%d' % pos
elif v == self.Y:
s = 'y'
else:
s = 'q'
return s
def indexStringArray(self):
indstr = np.array([self.ind2str(indvec) for indvec in self.Tind.T],dtype=object)
return indstr
def indexedTableau(self):
indstr = self.indexStringArray()
return np.vstack((indstr,self.T))
def __repr__(self):
IT = self.indexedTableau()
return IT.__repr__()
def __str__(self):
IT = self.indexedTableau()
return IT.__str__()
def lemkelcp(M,q,maxIter=100):
"""
sol = lemkelcp(M,q,maxIter)
Uses Lemke's algorithm to copute a solution to the
linear complementarity problem:
Mz + q >= 0
z >= 0
z'(Mz+q) = 0
The inputs are given by:
M - an nxn numpy array
q - a length n numpy array
maxIter - an optional number of pivot iterations. Set to 100 by default
The solution is a tuple of the form:
z,exit_code,exit_string = sol
The entries are summaries in the table below:
|z | exit_code | exit_string |
-----------------------------------------------------------
| solution to LCP | 0 | 'Solution Found' |
| None | 1 | 'Secondary ray found' |
| None | 2 | 'Max Iterations Exceeded' |
"""
tableau = lemketableau(M,q,maxIter)
return tableau.lemkeAlgorithm()
|
AndyLamperski/lemkelcp
|
lemkelcp/lemkelcp.py
|
Python
|
mit
| 5,431
|
////////////////////////////////////////////////////////////////////////////////
// The Loki Library
// Copyright (c) 2006 Rich Sposato
// Permission to use, copy, modify, distribute and sell this software for any
// purpose is hereby granted without fee, provided that the above copyright
// notice appear in all copies and that both that copyright notice and this
// permission notice appear in supporting documentation.
// The author makes no representations about the
// suitability of this software for any purpose. It is provided "as is"
// without express or implied warranty.
////////////////////////////////////////////////////////////////////////////////
// $Header: /cvsroot/loki-lib/loki/src/StrongPtr.cpp,v 1.3 2006/04/16 13:33:36 syntheticpp Exp $
// ----------------------------------------------------------------------------
#include <loki/StrongPtr.h>
#include <memory.h>
#include <cassert>
#include <loki/SmallObj.h>
//#define DO_EXTRA_LOKI_TESTS
#ifdef DO_EXTRA_LOKI_TESTS
#include <iostream>
#endif
// ----------------------------------------------------------------------------
namespace Loki
{
// ----------------------------------------------------------------------------
TwoRefCounts::TwoRefCounts( bool strong )
: m_counts( NULL )
{
void * temp = SmallObject<>::operator new(
sizeof(Loki::Private::TwoRefCountInfo) );
assert( temp != 0 );
m_counts = new ( temp ) Loki::Private::TwoRefCountInfo( strong );
}
// ----------------------------------------------------------------------------
TwoRefCounts::TwoRefCounts( const void * p, bool strong )
: m_counts( NULL )
{
void * temp = SmallObject<>::operator new(
sizeof(Loki::Private::TwoRefCountInfo) );
assert( temp != 0 );
void * p2 = const_cast< void * >( p );
m_counts = new ( temp ) Loki::Private::TwoRefCountInfo( p2, strong );
}
// ----------------------------------------------------------------------------
void TwoRefCounts::Increment( bool strong )
{
if ( strong )
{
m_counts->IncStrongCount();
}
else
{
m_counts->IncWeakCount();
}
}
// ----------------------------------------------------------------------------
bool TwoRefCounts::Decrement( bool strong )
{
if ( strong )
{
m_counts->DecStrongCount();
}
else
{
m_counts->DecWeakCount();
}
return !m_counts->HasStrongPointer();
}
// ----------------------------------------------------------------------------
void TwoRefCounts::Swap( TwoRefCounts & rhs )
{
std::swap( m_counts, rhs.m_counts );
}
// ----------------------------------------------------------------------------
void TwoRefCounts::ZapPointer( void )
{
assert( !m_counts->HasStrongPointer() );
if ( m_counts->HasWeakPointer() )
{
m_counts->ZapPointer();
}
else
{
SmallObject<>::operator delete ( m_counts,
sizeof(Loki::Private::TwoRefCountInfo) );
m_counts = NULL;
}
}
// ----------------------------------------------------------------------------
LockableTwoRefCounts::LockableTwoRefCounts( bool strong )
: m_counts( NULL )
{
void * temp = SmallObject<>::operator new(
sizeof(Loki::Private::LockableTwoRefCountInfo) );
assert( temp != 0 );
m_counts = new ( temp ) Loki::Private::LockableTwoRefCountInfo( strong );
}
// ----------------------------------------------------------------------------
LockableTwoRefCounts::LockableTwoRefCounts( const void * p, bool strong )
: m_counts( NULL )
{
void * temp = SmallObject<>::operator new(
sizeof(Loki::Private::LockableTwoRefCountInfo) );
assert( temp != 0 );
void * p2 = const_cast< void * >( p );
m_counts = new ( temp )
Loki::Private::LockableTwoRefCountInfo( p2, strong );
}
// ----------------------------------------------------------------------------
void LockableTwoRefCounts::Increment( bool strong )
{
if ( strong )
{
m_counts->IncStrongCount();
}
else
{
m_counts->IncWeakCount();
}
}
// ----------------------------------------------------------------------------
bool LockableTwoRefCounts::Decrement( bool strong )
{
if ( strong )
{
m_counts->DecStrongCount();
}
else
{
m_counts->DecWeakCount();
}
return !m_counts->HasStrongPointer();
}
// ----------------------------------------------------------------------------
void LockableTwoRefCounts::Swap( LockableTwoRefCounts & rhs )
{
std::swap( m_counts, rhs.m_counts );
}
// ----------------------------------------------------------------------------
void LockableTwoRefCounts::ZapPointer( void )
{
assert( !m_counts->HasStrongPointer() );
if ( m_counts->HasWeakPointer() )
{
m_counts->ZapPointer();
}
else
{
SmallObject<>::operator delete ( m_counts,
sizeof(Loki::Private::LockableTwoRefCountInfo) );
m_counts = NULL;
}
}
// ----------------------------------------------------------------------------
//
//namespace Private
//{
// ----------------------------------------------------------------------------
TwoRefLinks::TwoRefLinks( const void * p, bool strong )
: m_pointer( const_cast< void * >( p ) )
, m_strong( strong )
{
m_prev = m_next = this;
#ifdef DO_EXTRA_LOKI_TESTS
assert( CountPrevCycle( this ) == CountNextCycle( this ) );
#endif
}
// ----------------------------------------------------------------------------
TwoRefLinks::TwoRefLinks( const TwoRefLinks & rhs, bool strong )
: m_pointer( rhs.m_pointer )
, m_prev( const_cast< TwoRefLinks * >( &rhs ) )
, m_next( rhs.m_next )
, m_strong( strong )
{
m_prev->m_next = this;
m_next->m_prev = this;
#ifdef DO_EXTRA_LOKI_TESTS
assert( m_prev->HasPrevNode( this ) );
assert( m_next->HasNextNode( this ) );
assert( rhs.m_next->HasNextNode( this ) );
assert( rhs.m_prev->HasPrevNode( this ) );
assert( CountPrevCycle( this ) == CountNextCycle( this ) );
assert( CountPrevCycle( this ) == CountNextCycle( &rhs ) );
assert( AllNodesHaveSamePointer() );
#endif
}
// ----------------------------------------------------------------------------
void TwoRefLinks::SetPointer( void * p )
{
TwoRefLinks * node = m_prev;
if ( ( this == node ) || ( 0 == node ) )
return;
#ifdef DO_EXTRA_LOKI_TESTS
assert( m_prev->HasPrevNode( this ) );
assert( m_next->HasNextNode( this ) );
assert( CountPrevCycle( this ) == CountNextCycle( this ) );
assert( AllNodesHaveSamePointer() );
#endif
while ( node != this )
{
node->m_pointer = p;
node = node->m_next;
}
m_pointer = node;
#ifdef DO_EXTRA_LOKI_TESTS
assert( m_prev->HasPrevNode( this ) );
assert( m_next->HasNextNode( this ) );
assert( CountPrevCycle( this ) == CountNextCycle( this ) );
assert( AllNodesHaveSamePointer() );
#endif
}
// ----------------------------------------------------------------------------
bool TwoRefLinks::Release( bool strong )
{
assert( strong == m_strong );
(void)strong;
#ifdef DO_EXTRA_LOKI_TESTS
assert( m_prev->HasPrevNode( this ) );
assert( m_next->HasNextNode( this ) );
assert( CountPrevCycle( this ) == CountNextCycle( this ) );
assert( AllNodesHaveSamePointer() );
#endif
if ( NULL == m_next )
{
assert( NULL == m_prev );
// Return false so it does not try to destroy shared object
// more than once.
return false;
}
else if (m_next == this)
{
assert(m_prev == this);
// Set these to NULL to prevent re-entrancy.
m_prev = NULL;
m_next = NULL;
// Last one in the cycle has to release the pointer.
return true;
}
#ifdef DO_EXTRA_LOKI_TESTS
assert( this != m_prev );
assert( NULL != m_prev );
assert( m_prev->HasPrevNode( this ) );
assert( m_next->HasNextNode( this ) );
#endif
// If a single node is strong, then return false so it won't release.
if ( HasStrongPointer() )
{
// A cyclic chain of pointers is only as strong as the strongest link.
m_prev->m_next = m_next;
m_next->m_prev = m_prev;
return false;
}
return true;
}
// ----------------------------------------------------------------------------
void TwoRefLinks::ZapAllNodes( void )
{
TwoRefLinks * p = m_prev;
if ( ( this == p ) || ( 0 == p ) )
return;
#ifdef DO_EXTRA_LOKI_TESTS
assert( AllNodesHaveSamePointer() );
#endif
while ( p != this )
{
TwoRefLinks * p1 = p->m_prev;
p->m_pointer = 0;
p->m_next = p;
p->m_prev = p;
p = p1;
}
m_pointer = 0;
}
// ----------------------------------------------------------------------------
void TwoRefLinks::Swap( TwoRefLinks & rhs )
{
#ifdef DO_EXTRA_LOKI_TESTS
assert( m_prev->HasPrevNode( this ) );
assert( m_next->HasNextNode( this ) );
assert( CountPrevCycle( this ) == CountNextCycle( this ) );
assert( AllNodesHaveSamePointer() );
assert( rhs.AllNodesHaveSamePointer() );
#endif
std::swap( rhs.m_pointer, m_pointer );
if (m_next == this)
{
// This is in a cycle by itself.
assert(m_prev == this);
if (rhs.m_next == &rhs)
{
assert(rhs.m_prev == &rhs);
// both are in 1-node cycles - thus there is nothing to do.
return;
}
m_prev = rhs.m_prev;
m_next = rhs.m_next;
m_prev->m_next = m_next->m_prev = this;
rhs.m_next = rhs.m_prev = &rhs;
return;
}
if (rhs.m_next == &rhs)
{
// rhs is in a cycle by itself.
assert( rhs.m_prev == &rhs );
// rhs.Swap(*this);
rhs.m_prev = m_prev;
rhs.m_next = m_next;
m_prev->m_next = m_next->m_prev = &rhs;
m_next = m_prev = this;
return;
}
if (m_next == &rhs ) // rhs is next neighbour
{
if ( m_prev == &rhs )
return; // cycle of 2 pointers - no need to swap.
std::swap(m_prev, m_next);
std::swap(rhs.m_prev, rhs.m_next);
std::swap(rhs.m_prev, m_next);
std::swap(rhs.m_prev->m_next,m_next->m_prev);
}
else if ( m_prev == &rhs ) // rhs is prev neighbor
{
if ( m_next == &rhs )
return; // cycle of 2 pointers - no need to swap.
std::swap( m_prev, m_next );
std::swap( rhs.m_next, rhs.m_prev );
std::swap( rhs.m_next, m_prev );
std::swap( rhs.m_next->m_prev, m_prev->m_next );
}
else // not neighhbors
{
std::swap(m_prev, rhs.m_prev);
std::swap(m_next, rhs.m_next);
std::swap(m_prev->m_next, rhs.m_prev->m_next);
std::swap(m_next->m_prev, rhs.m_next->m_prev);
}
#ifdef DO_EXTRA_LOKI_TESTS
assert( m_next == this ? m_prev == this : m_prev != this);
assert( m_prev == this ? m_next == this : m_next != this);
assert( m_prev->HasPrevNode( this ) );
assert( m_next->HasNextNode( this ) );
assert( CountPrevCycle( this ) == CountNextCycle( this ) );
assert( rhs.m_prev->HasPrevNode( &rhs ) );
assert( rhs.m_next->HasNextNode( &rhs ) );
assert( CountPrevCycle( &rhs ) == CountNextCycle( &rhs ) );
assert( AllNodesHaveSamePointer() );
assert( rhs.AllNodesHaveSamePointer() );
#endif
}
// ----------------------------------------------------------------------------
bool TwoRefLinks::AllNodesHaveSamePointer( void ) const
{
const TwoRefLinks * next = m_next;
if ( NULL == next )
return true;
do
{
if ( next->m_pointer != m_pointer )
return false;
next = next->m_next;
} while ( next != this );
return true;
}
// ----------------------------------------------------------------------------
unsigned int TwoRefLinks::CountPrevCycle( const TwoRefLinks * pThis )
{
if ( NULL == pThis )
return 0;
const TwoRefLinks * p = pThis->m_prev;
if ( NULL == p )
return 0;
if ( pThis == p )
return 1;
unsigned int count = 1;
do
{
p = p->m_prev;
++count;
} while ( p != pThis );
return count;
}
// ----------------------------------------------------------------------------
unsigned int TwoRefLinks::CountNextCycle( const TwoRefLinks * pThis )
{
if ( NULL == pThis )
return 0;
const TwoRefLinks * p = pThis->m_next;
if ( NULL == p )
return 0;
if ( pThis == p )
return 1;
unsigned int count = 1;
while ( p != pThis )
{
p = p->m_next;
++count;
}
return count;
}
// ----------------------------------------------------------------------------
bool TwoRefLinks::HasPrevNode( const TwoRefLinks * p ) const
{
if ( this == p )
return true;
const TwoRefLinks * prev = m_prev;
if ( NULL == prev )
return false;
while ( prev != this )
{
if ( p == prev )
return true;
prev = prev->m_prev;
}
return false;
}
// ----------------------------------------------------------------------------
bool TwoRefLinks::HasNextNode( const TwoRefLinks * p ) const
{
if ( this == p )
return true;
const TwoRefLinks * next = m_next;
if ( NULL == next )
return false;
while ( next != this )
{
if ( p == next )
return true;
next = next->m_next;
}
return false;
}
// ----------------------------------------------------------------------------
bool TwoRefLinks::HasStrongPointer( void ) const
{
const TwoRefLinks * next = m_next;
if ( NULL == next )
return false;
while ( next != this )
{
if ( next->m_strong )
return true;
next = next->m_next;
}
return false;
}
// ----------------------------------------------------------------------------
bool TwoRefLinks::Merge( TwoRefLinks & rhs )
{
#ifdef DO_EXTRA_LOKI_TESTS
std::cout << std::endl << __FUNCTION__ << " " << __LINE__ << std::endl;
#endif
if ( NULL == m_next )
{
assert( NULL == m_prev );
return false;
}
TwoRefLinks * prhs = &rhs;
if ( prhs == this )
return true;
if ( NULL == prhs->m_next )
{
assert( NULL == prhs->m_prev );
return true;
}
#ifdef DO_EXTRA_LOKI_TESTS
std::cout << __FUNCTION__ << " " << __LINE__ << std::endl;
#endif
assert( CountPrevCycle( this ) == CountNextCycle( this ) );
assert( CountPrevCycle( prhs ) == CountNextCycle( prhs ) );
// If rhs node is already in this cycle, then no need to merge.
if ( HasPrevNode( &rhs ) )
{
assert( HasNextNode( &rhs ) );
return true;
}
#ifdef DO_EXTRA_LOKI_TESTS
std::cout << __FUNCTION__ << " " << __LINE__ << std::endl;
#endif
if ( prhs == prhs->m_next )
{
#ifdef DO_EXTRA_LOKI_TESTS
std::cout << __FUNCTION__ << " " << __LINE__ << std::endl;
#endif
/// rhs is in a cycle with 1 node.
assert( prhs->m_prev == prhs );
prhs->m_prev = m_prev;
prhs->m_next = this;
m_prev->m_next = prhs;
m_prev = prhs;
}
else if ( this == m_next )
{
#ifdef DO_EXTRA_LOKI_TESTS
std::cout << __FUNCTION__ << " " << __LINE__ << std::endl;
#endif
/// this is in a cycle with 1 node.
assert( m_prev == this );
m_prev = prhs->m_prev;
m_next = prhs;
prhs->m_prev->m_next = this;
prhs->m_prev = this;
}
else
{
#ifdef DO_EXTRA_LOKI_TESTS
std::cout << __FUNCTION__ << " " << __LINE__ << std::endl;
#endif
m_next->m_prev = prhs->m_prev;
prhs->m_prev->m_next = m_prev;
m_next = prhs;
prhs->m_prev = this;
}
#ifdef DO_EXTRA_LOKI_TESTS
std::cout << __FUNCTION__ << " " << __LINE__ << std::endl;
#endif
assert( CountPrevCycle( this ) == CountNextCycle( this ) );
#ifdef DO_EXTRA_LOKI_TESTS
std::cout << __FUNCTION__ << " " << __LINE__ << std::endl;
#endif
return true;
}
// ----------------------------------------------------------------------------
//
//} // end namespace Private
} // end namespace Loki
// ----------------------------------------------------------------------------
// $Log: StrongPtr.cpp,v $
// Revision 1.3 2006/04/16 13:33:36 syntheticpp
// change init order to declarartion order
//
// Revision 1.2 2006/04/15 00:46:46 rich_sposato
// Added line to remove compiler warning about unused parameter.
//
// Revision 1.1 2006/04/05 22:53:10 rich_sposato
// Added StrongPtr class to Loki along with tests for StrongPtr.
//
|
egorpushkin/neurolab
|
source/controls/Simple2dCharting/External/StrongPtr.cpp
|
C++
|
mit
| 17,326
|
module RubyArena
class Bullet
include Movable
DEFAULT_SPEED = 10
DEFAULT_ENERGY = 10
SIZE = 4
attr_reader :x, :y, :heading, :speed, :arena, :origin
def initialize(args)
@x = args.fetch(:x)
@y = args.fetch(:y)
@heading = args.fetch(:heading)
@speed = args.fetch(:speed, DEFAULT_SPEED)
@arena = args.fetch(:arena)
@origin = args.fetch(:origin)
@dead = false
end
def update
move
check_if_hit_some_robot
end
def intersect?(object)
Gosu.distance(x, y, object.x, object.y) < size/2 + object.size/2
end
def size
SIZE
end
def energy
DEFAULT_ENERGY
end
def dead?
@dead
end
private
def check_if_hit_some_robot
arena.robots.each do |robot|
if robot != origin && intersect?(robot)
robot.hit(self)
@dead = true
end
end
end
end
end
|
mrhead/ruby_arena
|
lib/ruby_arena/bullet.rb
|
Ruby
|
mit
| 938
|
package org.openprovenance.model;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.File;
import java.io.StringWriter;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import javax.xml.bind.JAXBException;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
/**
* Unit test for simple Provenance Challenge 1 like workflow.
*/
public class DL1Test
extends TestCase
{
public static String APP_NS="http://www.ipaw.info/dl1";
public static OPMFactory oFactory=new OPMFactory();
/**
* Create the test case
*
* @param testName name of the test case
*/
public DL1Test( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
static OPMGraph graph1;
public void testDL1() throws JAXBException
{
OPMGraph graph=makeDL1Graph(oFactory);
OPMSerialiser serial=OPMSerialiser.getThreadOPMSerialiser();
serial.serialiseOPMGraph(new File("target/dl1.xml"),graph,true);
//System.out.println(sw);
graph1=graph;
System.out.println("DL1 Test asserting True");
assertTrue( true );
}
public OPMGraph makeDL1Graph(OPMFactory oFactory)
{
Collection<Account> black=Collections.singleton(oFactory.newAccount("black"));
Collection<Account> summary=Collections.singleton(oFactory.newAccount("summary"));
Collection<Account> collection1=Collections.singleton(oFactory.newAccount("collection1"));
Collection<Account> collection2=Collections.singleton(oFactory.newAccount("collection2"));
List<Account> allAccounts=new LinkedList();
allAccounts.addAll(black);
allAccounts.addAll(summary);
allAccounts.addAll(collection1);
allAccounts.addAll(collection2);
Process p1=oFactory.newProcess("p1",
black,
"Query");
Process r1=oFactory.newProcess("r1",
black,
"Restore");
Process s1=oFactory.newProcess("s1",
black,
"Select");
Process ed1=oFactory.newProcess("ed1",
black,
"Edit");
Process g11=oFactory.newProcess("g11",
black,
"Generate");
Process g12=oFactory.newProcess("g12",
black,
"Generate");
Process rt1=oFactory.newProcess("rt1",
black,
"Retrieve");
Process sum1=oFactory.newProcess("sum1",
black,
"Summarize");
Agent hist1=oFactory.newAgent("hist1",
black,
"Historian1");
Artifact docdb=oFactory.newArtifact("docdb",
black,
"DocDB");
Artifact q=oFactory.newArtifact("q",
black,
"Query");
Artifact d1=oFactory.newArtifact("d1",
black,
"D1");
Artifact t1=oFactory.newArtifact("t1",
black,
"T1");
Artifact v1=oFactory.newArtifact("v1",
black,
"V1");
Artifact tds1=oFactory.newArtifact("tds1",
black,
"3Ds1");
Artifact td11=oFactory.newArtifact("td11",
black,
"3D1.1");
Artifact td12=oFactory.newArtifact("td12",
black,
"3D1.2");
Artifact m1=oFactory.newArtifact("m1",
black,
"Map1");
Artifact md1=oFactory.newArtifact("md1",
black,
"MD1");
Artifact ov1=oFactory.newArtifact("ov1",
black,
"OV1");
Artifact rv1=oFactory.newArtifact("rv1",
black,
"RV1");
Artifact sd1=oFactory.newArtifact("sd1",
summary,
"SD1");
Artifact st1=oFactory.newArtifact("st1",
black,
"ST1");
Artifact sv1=oFactory.newArtifact("sv1",
black,
"SV1");
Artifact stds1=oFactory.newArtifact("stds1",
black,
"S3Ds1");
Artifact std11=oFactory.newArtifact("std11",
black,
"S3D1.1");
Artifact std12=oFactory.newArtifact("std12",
black,
"S3D1.2");
Artifact sm1=oFactory.newArtifact("sm1",
black,
"SMap1");
Artifact smd1=oFactory.newArtifact("smd1",
black,
"SMD1");
Artifact ot1=oFactory.newArtifact("ot1",
black,
"OT1");
Artifact vp11=oFactory.newArtifact("vp11",
black,
"VP11");
Artifact vp12=oFactory.newArtifact("vp12",
black,
"VP12");
Artifact sd11=oFactory.newArtifact("sd11",
black,
"SD11");
Artifact sd12=oFactory.newArtifact("sd12",
black,
"SD12");
Artifact alg11=oFactory.newArtifact("alg11",
black,
"ALG11");
Artifact alg12=oFactory.newArtifact("alg12",
black,
"ALG12");
Artifact res1=oFactory.newArtifact("res1",
black,
"Res 1");
Used u1=oFactory.newUsed(p1,oFactory.newRole("query"),q,summary);
Used u2=oFactory.newUsed(p1,oFactory.newRole("db"),docdb,summary);
Used u3=oFactory.newUsed(r1,oFactory.newRole("in"),ov1,black);
Used u4=oFactory.newUsed(s1,oFactory.newRole("in"),rv1,black);
Used u5=oFactory.newUsed(ed1,oFactory.newRole("in"),ot1,black);
Used u6=oFactory.newUsed(g11,oFactory.newRole("vp"),vp11,black);
Used u7=oFactory.newUsed(g12,oFactory.newRole("vp"),vp12,black);
Used u8=oFactory.newUsed(g11,oFactory.newRole("vp"),sd11,black);
Used u9=oFactory.newUsed(g12,oFactory.newRole("vp"),sd12,black);
Used u10=oFactory.newUsed(g11,oFactory.newRole("vp"),alg11,black);
Used u11=oFactory.newUsed(g12,oFactory.newRole("vp"),alg12,black);
Used u12=oFactory.newUsed(rt1,oFactory.newRole("res"),res1,black);
Used u13=oFactory.newUsed(sum1,oFactory.newRole("in"),d1,summary);
WasGeneratedBy wg1=oFactory.newWasGeneratedBy(sd1,oFactory.newRole("out"),p1,summary);
WasGeneratedBy wg2=oFactory.newWasGeneratedBy(rv1,oFactory.newRole("out"),r1,black);
WasGeneratedBy wg3=oFactory.newWasGeneratedBy(v1,oFactory.newRole("out"),s1,black);
WasGeneratedBy wg4=oFactory.newWasGeneratedBy(t1,oFactory.newRole("out"),ed1,black);
WasGeneratedBy wg5=oFactory.newWasGeneratedBy(td11,oFactory.newRole("out"),g11,black);
WasGeneratedBy wg6=oFactory.newWasGeneratedBy(td12,oFactory.newRole("out"),g12,black);
WasGeneratedBy wg7=oFactory.newWasGeneratedBy(m1,oFactory.newRole("out"),rt1,black);
WasGeneratedBy wg8=oFactory.newWasGeneratedBy(sd1,oFactory.newRole("out"),sum1,summary);
// Document doc=oFactory.builder.newDocument();
// Element el=doc.createElementNS(APP_NS,"app:ignore");
// Element el2=doc.createElementNS(APP_NS,"app:image");
// el.appendChild(el2);
// el2.appendChild(doc.createTextNode("http://www.ipaw.info/challenge/anatomy1.img"));
// doc.appendChild(el);
// oFactory.addValue(a1,el,"http://www.ipaw.info/imagePointer");
// Document doc_=oFactory.builder.newDocument();
// Element el_=doc_.createElementNS(APP_NS,"app:ignore");
// el_.appendChild(doc_.createCDATASection(" {\"menu\": { \"id\": \"file\", \"value\": \"File\"}}"));
// doc_.appendChild(el_);
// oFactory.addValue(a1," {\"menu\": { \"id\": \"file\", \"value\": \"File\"}}","mime:application/json");
// oFactory.addValue(a1,10,"http://www.ipaw.info/imagePointer3");
// oFactory.addValue(a1,"foo","http://www.ipaw.info/imagePointer4");
// oFactory.addValue(a1,1.0,"http://www.ipaw.info/imagePointer5");
// Used u1=oFactory.newUsed(p1,oFactory.newRole("img1"),a1,black);
// Used u2=oFactory.newUsed(p1,oFactory.newRole("hdr1"),a2,black);
// Used u3=oFactory.newUsed(p1,oFactory.newRole("imgRef"),a3,black);
// Used u4=oFactory.newUsed(p1,oFactory.newRole("hdrRef"),a4,black);
// WasGeneratedBy wg1=oFactory.newWasGeneratedBy(a5,oFactory.newRole("x"),p1,black);
WasDerivedFrom cdt1=oFactory.newWasDerivedFrom(d1,t1,collection1);
WasDerivedFrom cdv1=oFactory.newWasDerivedFrom(d1,v1,collection1);
WasDerivedFrom cdtds1=oFactory.newWasDerivedFrom(d1,tds1,collection1);
WasDerivedFrom cdm1=oFactory.newWasDerivedFrom(d1,m1,collection1);
WasDerivedFrom cdmd1=oFactory.newWasDerivedFrom(d1,md1,collection1);
WasDerivedFrom ct3dst3d11=oFactory.newWasDerivedFrom(tds1,td11,collection1);
WasDerivedFrom ct3dst3d12=oFactory.newWasDerivedFrom(tds1,td12,collection1);
WasDerivedFrom csdst1=oFactory.newWasDerivedFrom(sd1,st1,collection2);
WasDerivedFrom csdsv1=oFactory.newWasDerivedFrom(sd1,sv1,collection2);
WasDerivedFrom csdstds1=oFactory.newWasDerivedFrom(sd1,stds1,collection2);
WasDerivedFrom csdsm1=oFactory.newWasDerivedFrom(sd1,sm1,collection2);
WasDerivedFrom csdsmd1=oFactory.newWasDerivedFrom(sd1,smd1,collection2);
WasDerivedFrom cst3dsst3d11=oFactory.newWasDerivedFrom(stds1,std11,collection2);
WasDerivedFrom cst3dsst3d12=oFactory.newWasDerivedFrom(stds1,std12,collection2);
// WasControlledBy wc1=oFactory.newWasControlledBy(p1,oFactory.newRole("user"),ag1,black);
WasControlledBy wc2=oFactory.newWasControlledBy(ed1,oFactory.newRole("user"),hist1,black);
WasDerivedFrom wd0=oFactory.newWasDerivedFrom(docdb,d1,black);
WasDerivedFrom wd1=oFactory.newWasDerivedFrom(sd1,d1,summary);
WasDerivedFrom wd2=oFactory.newWasDerivedFrom(st1,t1,summary);
WasDerivedFrom wd3=oFactory.newWasDerivedFrom(sv1,v1,summary);
WasDerivedFrom wd4=oFactory.newWasDerivedFrom(stds1,tds1,summary);
WasDerivedFrom wd5=oFactory.newWasDerivedFrom(sm1,m1,summary);
WasDerivedFrom wd6=oFactory.newWasDerivedFrom(std11,td11,summary);
WasDerivedFrom wd7=oFactory.newWasDerivedFrom(std12,td12,summary);
WasDerivedFrom wd8=oFactory.newWasDerivedFrom(smd1,md1,summary);
WasDerivedFrom wd9=oFactory.newWasDerivedFrom(rv1,ov1,black);
WasDerivedFrom wd10=oFactory.newWasDerivedFrom(v1,rv1,black);
WasDerivedFrom wd11=oFactory.newWasDerivedFrom(t1,ot1,black);
WasDerivedFrom wd12=oFactory.newWasDerivedFrom(m1,res1,black);
OPMGraph graph=oFactory.newOPMGraph(allAccounts,
new Overlaps[] { },
new Process[] { p1, r1, s1, ed1, g11, g12, rt1, sum1},
new Artifact[] {d1,t1,v1,tds1,td11,td12,m1, sd1,st1,sv1,stds1,std11,std12,sm1, docdb, rv1, ov1, ot1, vp11, vp12, sd11, sd12, alg11, alg12, res1, md1},
new Agent[] { hist1 },
new Object[] {cdt1, cdv1, cdtds1, cdm1, cdmd1, ct3dst3d11, ct3dst3d12,
csdst1, csdsv1, csdstds1, csdsm1, csdsmd1, cst3dsst3d11, cst3dsst3d12,
wd0, wd1, wd2, wd3, wd4, wd5, wd6, wd7, wd8, wd9, wd10, wd11,
u1, u2, u3, u4, u5, u6, u7, u8, u9, u10, u11, u12, u13,
wg1, wg2, wg3, wg4, wg5, wg6, wg7, wg8,
wc2 } );
return graph;
}
/** Produces a dot representation
* of created graph. */
public void testDL1Conversion() throws java.io.FileNotFoundException, java.io.IOException {
//OPMToDot toDot=new OPMToDot(true); // with roles
OPMToDot toDot=new OPMToDot("src/main/resources/dl1Config.xml"); // with multisteps
toDot.convert(graph1,"target/dl1.dot", "target/dl1.pdf");
}
/** Produces a dot representation
* of created graph. */
public void testDL1Conversion2() throws java.io.FileNotFoundException, java.io.IOException {
//OPMToDot toDot=new OPMToDot(true); // with roles
OPMToDot toDot=new OPMToDot("src/main/resources/dl1Config2.xml"); // with multisteps
toDot.convert(graph1,"target/dl12.dot", "target/dl12.pdf");
}
public void testDL1Copy() throws java.io.FileNotFoundException, java.io.IOException {
OPMFactory oFactory=new OPMFactory();
OPMGraph graph2=oFactory.newOPMGraph(graph1);
assertTrue( "self graph1 differ", graph1.equals(graph1) );
assertTrue( "self graph2 differ", graph2.equals(graph2) );
assertTrue( "graph1 graph2 differ", graph1.equals(graph2) );
}
}
|
lucmoreau/OpenProvenanceModel
|
opm/src/test/java/org/openprovenance/model/DL1Test.java
|
Java
|
mit
| 13,709
|
---
layout: post
title: Totem - Ruby Without Rails
comments: false
share: false
date: 2014-03-13
type: post
tags:
- jruby
- ruby
- ruby on rails
- totem
---
<p><a title="Totem" href="https://github.com/chadrem/totem">Totem</a> is my new Ruby gem for creating Ruby projects without having to depend on Rails. Some of the features it provides are:</p>
<ul>
<li>Interactive console</li>
<li>Logging</li>
<li>Standard folder structure (very Rails like)</li>
<li>Environments (development, production, etc)</li>
<li>Generators</li>
<li>Easy database access (via an add-on)</li>
</ul>
<p><a title="Totem" href="https://github.com/chadrem/totem">Totem</a> and <a title="Totem - Activerecord" href="https://github.com/chadrem/totem_activerecord">Totem - Activerecord</a> seek to bring these and many other features to your non-Rails application. Give it a try and feel free to contact me with your feedback.</p>
|
chadrem/chadrem.github.io
|
_posts/2014-03-13-totem-ruby-without-rails.html
|
HTML
|
mit
| 909
|
var test = require('tape')
var Rectangle = require('../src/Rectangle.js')
var Square = require('../src/Square.js')
test('Square constructor', function (t) {
t.plan(3)
t.equal(typeof Square, 'function', 'should be a function')
var squ = new Square(7)
t.equal(squ.width, 7, 'should set square width')
t.equal(squ.height, 7, 'should set square height')
})
test('Square::area', function (t) {
t.plan(2)
var squ = new Square(7)
t.equal(typeof squ.area, 'function', 'should be a function')
t.equal(squ.area, Rectangle.prototype.area, 'should be inherited from Rectangle')
})
test('Square::description', function (t) {
t.plan(2)
var squ = new Square(7)
t.equal(typeof squ.description, 'function', 'should be a function')
t.equal(squ.description(), 'Square of side 7 and area 49.', 'should return square\'s description')
})
|
dasilvacontin/js-practice
|
test/Square.spec.js
|
JavaScript
|
mit
| 849
|
%!TEX root = Gute-Frage-Umfragedesign.tex
\subsection{Forschungsfragen}
\begin{frame}{Forschungsfragen}
\begin{itemize}[<+->]
\item Kann die Eingabe mathematischer Formeln in den Computer aus Nutzersicht
verbessert werden?
\item Wer ist bereit neue Eingabemöglichkeiten für Formeln auszuprobieren?
\item Welche Eingabemöglichkeiten werden bisher genutzt?
\item Wie zufrieden sind die Benutzer mit der Eingabe?
\item Wo sind bisher Probleme bei der Eingabe?
\item Welche Strategien werden angewandt, wenn der Interviewte nicht weiß
wie eine Formel eingegeben werden kann?
\end{itemize}
\end{frame}
|
MartinThoma/LaTeX-examples
|
presentations/Gute-Frage-Schluesselqualifikation/LaTeX/Forschungsfragen.tex
|
TeX
|
mit
| 646
|
<link href="../../assets/css/bootstrap-responsive.min.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/css/style.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/css/lightbox.css" rel="stylesheet" type="text/css"/>
<script src="../../assets/js/lightbox.min.js" type="text/javascript"></script>
<script src="../../assets/js/bootstrap.min.js" type="text/javascript"></script>
<script src="../../assets/js/jquery-1.11.1.min.js" type="text/javascript"></script>
<h2> Admin - Edit program</h2>
<div id="background">
<!-- form to add a new attraction item -->
<div class="errors">{message}
</div>
<form action="/admin/confirm" method="post" enctype="multipart/form-data">
{fid}
{fname}
{fcaption}
{fdescription}
{flocation}
{fprice}
<div class="alert-info">At least 1 image required (better if all 4)</div>
{fimage1}
{fimage2}
{fimage3}
{fimage4}
{fsubmit}
</form>
<table>
<tr>
<td>
<a class="btn btn-danger" href="/admin">Cancel</a>
</td>
</tr>
</table>
</div>
|
AIMGym/CIAssignment
|
application/views/edit_program.php
|
PHP
|
mit
| 1,316
|
---
06/02/2017
<table>
<tr>
</tr>
</table>
<table>
<tr>
<td>Starting point:</td>
<td>Continuing with CLS </td>
</tr>
<tr>
<td>Target for this lesson?</td>
<td>To have a Github Pages Static Website</td>
</tr>
<tr>
<td>Did I reach my target?
(add details to "Lesson Review")</td>
<td> I think I successfully reached my target this lesson.</td>
</tr>
</table>
<table>
<tr>
<td>Lesson Review</td>
</tr>
<tr>
<td>How did I learn? What strategies were effective? </td>
</tr>
<tr>
<td>
My most effective learning strategies during today's lesson were: reading thoroughly the book before actually blindly copying random code so we could understand it fully, and also working with groups around us..</td>
</tr>
<tr>
<td>What limited my learning? Which habits do I need to work on? </td>
</tr>
<tr>
<td>
What limited my learning was the fact that I didn't focus and got distracted by other people and I need to work just focusing on my work, and not the people around me. </td>
</tr>
<tr>
<td>What will I change for next time? How will I improve my learning?</td>
</tr>
<tr>
<td>
Next lesson, to make our learning even easier, my partner and I will concentrate more on our work and less on the people around us so we can a lot of work done</td>
</tr>
</table>
|
marcuslos/marcuslos.github.io
|
_posts/2017-02-21-Week-3.md
|
Markdown
|
mit
| 1,363
|
# == Schema Information
#
# Table name: producers
#
# id :integer not null, primary key
# name :string(255)
# url :string(255)
# address :text
# country :string(255)
# description :text
# created_at :datetime
# updated_at :datetime
# logo_file_name :string(255)
# logo_content_type :string(255)
# logo_file_size :integer
# logo_updated_at :datetime
#
require 'test_helper'
class ProducerTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
|
evsandrey/d2d
|
test/models/producer_test.rb
|
Ruby
|
mit
| 585
|
import { moduleFor, test } from 'ember-qunit';
moduleFor('service:alert-box', 'Unit | Service | alert box', {
// Specify the other units that are required for this test.
// needs: ['service:foo']
});
// Replace this with your real tests.
test('it exists', function(assert) {
let service = this.subject();
assert.ok(service);
});
|
Josowsky/SiteScannerFrontEnd
|
tests/unit/services/alert-box-test.js
|
JavaScript
|
mit
| 339
|
using System;
using System.Reflection;
namespace _01.DefineAClassPerson
{
public class Startup
{
public static void Main()
{
Type personType = typeof(Person);
FieldInfo[] fields = personType.GetFields(BindingFlags.Public | BindingFlags.Instance);
Console.WriteLine(fields.Length);
}
}
}
|
ivanlutov/C-Fundamentals
|
C#OOPBasics/01.DefiningClassesExercises/01.DefineAClassPerson/Startup.cs
|
C#
|
mit
| 362
|
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) > [noicejs](./noicejs.md) > [Container](./noicejs.container.md) > [fail](./noicejs.container.fail.md)
## Container.fail() method
<b>Signature:</b>
```typescript
protected fail(msg: string): never;
```
## Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| msg | string | |
<b>Returns:</b>
never
|
ssube/noicejs
|
docs/api/noicejs.container.fail.md
|
Markdown
|
mit
| 455
|
<?php
require("../vendor/autoload.php");
use CrowdFlower\Account;
$apiKey = 'jLByZLxtuyWV9x6g-Msq';
/**
*
* Instatiate the container that fetches jobs.
*/
$crowd = new CrowdFlower\Account($apiKey);
/**
*
* Fetch units for a job.
*/
// Find all of the units
$units = $job->getUnits();
// Or find a single unit by Unit ID
$unitId = 456;
$unit = $job->getUnit($unitId);
/**
*
* Create units for a job.
*/
// First get the job we want to add units to.
$jobId = 123;
$job = $crowd->getJob($jobId);
// Units can be created one at a time..
$unit = Array ("data" => Array('column1' => 'name', 'column2' => 'url'));
$job->createUnit($unit);
// or in an array with multiple units.
$units = Array (
Array ("data" => Array('column1' => 'name', 'column2' => 'url')),
Array ("data" => Array('column1' => 'name2', 'column2' => 'url2'))
);
$job->createUnits($units);
/**
*
* Update units for a job.
*/
// First update an attribute.
$unit->setAttribute("data", Array('column1' => 'name updated', 'column2' => 'url updated'));
// Then update it on CrowdFlower's service.
$unit->update();
/**
*
* Get the status of all units in a job.
*/
$statuses = $job->UnitsStatus();
/**
*
* Cancel a unit.
*/
$unit->cancel();
/**
*
* Delete a unit.
*/
$unit->delete();
|
dadeg/php-crowdflower
|
examples/unit.php
|
PHP
|
mit
| 1,336
|
/**
* The MIT License
* Copyright (c) 2011 Kuali Mobility Team
*
* 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.
*/
package org.kuali.mobility.tags;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockJspWriter;
import org.springframework.mock.web.MockPageContext;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.ContextLoader;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.JspFragment;
import java.io.IOException;
import java.io.Writer;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
/**
* @author Kuali Mobility Team (mobility.collab@kuali.org)
*/
public class LabeledRowTagTest {
private static final Logger LOG = LoggerFactory.getLogger(LabeledRowTagTest.class);
private static final String NL = System.getProperty("line.separator").toString();
private static MockServletContext mockServletContext;
private PageContext mockPageContext;
private LabeledRowTag tag;
@BeforeClass
public static void init() {
mockServletContext = new MockServletContext();
String configLocations = "classpath:TagSpringBeans.xml";
mockServletContext.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, configLocations);
ContextLoader loader = new ContextLoader();
loader.initWebApplicationContext(mockServletContext);
}
@Before
public void setup() throws Exception {
mockPageContext = new MockPageContext(mockServletContext);
tag = new LabeledRowTag();
tag.setJspContext(mockPageContext);
JspFragment jspBodyFragment = mock(JspFragment.class);
doAnswer(new FakeJspBodyAnswerer()).when(jspBodyFragment)
.invoke((Writer) anyObject());
tag.setJspBody(jspBodyFragment);
}
@Test
public void testLabeledRowTagNoArgs() {
String expectedResult = "<div class=\"labeledRow labeledRowLabel\" style=\"width:30%; text-align:right; float:left; color:#900;\">TEST_LABEL</div> " + NL +
"<div class=\"labeledRow labeledRowData\" style=\"width:60%; padding-left:35%\"> " + NL +
"Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>" + NL;
try {
tag.setFieldLabel("TEST_LABEL");
tag.doTag();
String output = ((MockHttpServletResponse) mockPageContext.getResponse()).getContentAsString();
LOG.debug("Expected [" + expectedResult + "]");
LOG.debug("Output is [" + output + "]");
assertTrue("Tag failed to provide expected output.", output.equals(expectedResult));
} catch (JspException je) {
LOG.error(je.getLocalizedMessage(), je);
fail("JspException found testing tag.");
} catch (IOException ioe) {
LOG.error(ioe.getLocalizedMessage(), ioe);
fail("IOException found testing tag.");
} catch (NullPointerException npe) {
LOG.error(npe.getLocalizedMessage(), npe);
fail("NullPointerException found testing tag.");
}
}
@Test
public void testLabeledRowTagWithArgs() {
String expectedResult = "<div class=\"labeledRow labeledRowLabel\" style=\"width:30%; text-align:right; float:left; color:#900;\">TEST_LABEL</div> " + NL +
"<div class=\"labeledRow labeledRowData\" style=\"width:60%; padding-left:35%\">TEST_VALUE" + NL +
"Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>" + NL;
try {
tag.setFieldLabel("TEST_LABEL");
tag.setFieldValue("TEST_VALUE");
tag.doTag();
String output = ((MockHttpServletResponse) mockPageContext.getResponse()).getContentAsString();
LOG.debug("Expected [" + expectedResult + "]");
LOG.debug("Output is [" + output + "]");
assertTrue("Tag failed to provide expected output.", output.equals(expectedResult));
} catch (JspException je) {
LOG.error(je.getLocalizedMessage(), je);
fail("JspException found testing tag.");
} catch (IOException ioe) {
LOG.error(ioe.getLocalizedMessage(), ioe);
fail("IOException found testing tag.");
} catch (NullPointerException npe) {
LOG.error(npe.getLocalizedMessage(), npe);
fail("NullPointerException found testing tag.");
}
}
private static class FakeJspBodyAnswerer implements Answer {
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
MockJspWriter writer = (MockJspWriter) invocationOnMock.getArguments()[0];
writer.write("Lorem ipsum dolor sit amet, consectetur adipiscing elit.");
return null;
}
}
}
|
tamerman/mobile-starting-framework
|
shared/impl/src/test/java/org/kuali/mobility/tags/LabeledRowTagTest.java
|
Java
|
mit
| 5,746
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页内容</title>
<link href="<?php echo base_url() . 'style/' ?>css/style.css" rel="stylesheet" />
<script type="text/javascript" src="<?php echo base_url() ?>ueditor/ueditor.all.min.js"></script>
<script type="text/javascript">
window.UEDITOR_HOME_URL = "<?php echo base_url() ?>ueditor/";
window.onload = function(){
window.UEDITOR_CONFIG.initialFrameWidth = 800;
window.UEDITOR_CONFIG.initialFrameHeight = 200;
UE.getEditor('content');
}
</script>
<script type="text/javascript" src="<?php echo base_url() ?>ueditor/ueditor.config.js"></script>
<style type="text/css">
span{color: red}
</style>
</head>
<body>
<div class="formcontent">
<form action="<?php echo site_url() .'/project/BaiduEditer/saveInfo'?>" id="myform" method='post'>
<td>编辑器:</td>
<td>
<textarea name="content" id="content">
</textarea>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交">
</td>
</tr>
</form>
</div>
</body>
</html>
|
ZuoYouLai/studyCI
|
application/views/project/BaiduEditerView.php
|
PHP
|
mit
| 1,080
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class long_short_completo extends Model
{
public $fillable = ['id','tp_op','situacao','ativo','dt_entrada','vl_entrada','dt_saida','vl_saida','financeiro','percentual','tp_op_ls','financeiro_ls','percentual_ls'];
}
|
wcneto/laravel-stocks-robo-advisor
|
app/long_short_completo.php
|
PHP
|
mit
| 290
|
## parse-formats
Provides a list of various modules to parse data formats synchronously to JS objects.
Feel free to suggest more formats or more modules to parse them with via issue or pull request.
[](https://nodei.co/npm/parse-formats/)
#### Formats
| Ext | format | npm module |
| :---- |:------:| ----------:|
| .cson | [cson](https://github.com/bevry/cson) | [cson-parser](https://www.npmjs.com/package/cson-parser) |
| .csv | [csv](https://en.wikipedia.org/wiki/Comma-separated_values) | [parser-csv](https://www.npmjs.com/package/parser-csv) |
| .hjson | [hjson](https://hjson.org/) | [hjson](https://www.npmjs.com/package/hjson) |
| .ini | [ini](https://en.wikipedia.org/wiki/INI_file) | [ini](https://www.npmjs.com/package/ini) |
| .json | [json](http://www.json.org/) | [strip-json-comments](https://www.npmjs.com/package/strip-json-comments) or native |
| .json5 | [json5](http://json5.org/) | [json5](https://www.npmjs.com/package/json5) |
| .xml | [xml](https://en.wikipedia.org/wiki/XML) | [xml2json](https://www.npmjs.com/package/xml2json) |
| .yaml, .yml | [yaml](http://yaml.org/) | [js-yaml](https://www.npmjs.com/package/js-yaml) |
#### Source
````js
/* Common patterns */
function parse (parser, data, opts) {
return parser.parse(data, opts);
}
function self (parser, data, opts) {
return parser(data, opts);
}
/* { ext: { moduleName: function(module, data, opts) } } */
module.exports = {
'.cson': { 'cson-parser': parse },
'.csv': {
'parser-csv': function (parser, data, opts) {
return parser.parseSync(data, opts);
},
},
'.hjson': { 'hjson': parse },
'.ini': { 'ini': parse },
'.json': {
'strip-json-comments': function (stripComments, data) {
return JSON.parse(stripComments(data));
},
'path': function (_, data) {
return JSON.parse(data);
},
},
'.json5': { 'json5': parse },
'.xml': {
'xml2json': function (xml2json, data, opts) {
return JSON.parse(xml2json.toJson(data, opts));
},
},
'.yaml': { 'js-yaml': jsYaml },
'.yml': { 'js-yaml': jsYaml },
};
function jsYaml (jsYaml, data, opts) {
return jsYaml.load(data, opts);
}
````
|
dskrepps/parse-formats
|
readme.md
|
Markdown
|
mit
| 2,163
|
import xml.etree.ElementTree as ET
import datetime
import sys
import openpyxl
import re
import dateutil
def main():
print 'Number of arguments:', len(sys.argv), 'arguments.' #DEBUG
print 'Argument List:', str(sys.argv) #DEBUG
Payrate = raw_input("Enter your pay rate: ") #DEBUG
sNumber = raw_input("Enter 900#: ") #DEBUG
xml = ET.parse("xml.xml") #DEBUG
root = xml.getroot()
root = root[3][0] #Go directly to worksheet/table
sheet = openpyxl.load_workbook(sys.argv[1], data_only=True).active
writeName(root)
writeEmployeeNum(root)
writeStudentNum(sNumber)
writePayRate(payRate)
#At this point all that is left are the times
for x in root.findall(".//*"):
if x.text != None:
dates.append(x.text)
for x in char_range('G','Z'):
writeTimes(x + '17' , dates)
def writeTimes (position, dateList):
match = next(x[0] for x in enumerate(dateList) if x[1] == sheet[position].value)
jobCode = dateList[num+4]
if jobCode == 900:
raise error("Cannot start day with 900 break")
else:
sheet[date] = roundTime(
def roundTime(time):
date = dateutil.parser.parse(x)
if date.minute <= 7
return date.replace(minute=0)
else if date.minute >= 8 and date.minute <= 22:
return date.replace(minute=15)
else if date.minute >= 23 and date.minute <= 37:
return date.replace(minute=30)
else if date.minute >= 38 and date.minute <= 52:
return date.replace(minute=45)
else if date.minute >= 53:
if date.hour == 23:
raise error("Worked overnight or did not clock out")
else:
date += datetime.timedelta(minutes= (60-date.minute))
#Rounds time to next hour by adding minutes until 60
return date
else:
raise error("Something went wrong in roundTime")
def writeName(tree):
name = tree[-1][4][0].text
sheet['I8'] = name
def writeEmployeeNum(tree):
num = root[2][0][0].text
sheet['4D'] = re.match('.*?([0-9]+)$', num).group(1)
def writeStudentNum(num):
sheet['8S']=num
def writePayRate(num):
sheet['6k']=num
def char_range(c1, c2):
"""Generates the characters from `c1` to `c2`, inclusive."""
"""Courtesy http://stackoverflow.com/questions/7001144/range-over-character-in-python"""
for c in xrange(ord(c1), ord(c2)+1):
yield chr(c)
main()
|
JamesPavek/payroll
|
timesheet.py
|
Python
|
mit
| 2,615
|
#!/bin/bash
set -e
GITLAB_CI_HOST=${GITLAB_CI_HOST:-localhost}
GITLAB_CI_PORT=${GITLAB_CI_PORT:-}
GITLAB_CI_HTTPS=${GITLAB_CI_HTTPS:-false}
GITLAB_CI_EMAIL=${GITLAB_CI_EMAIL:-gitlab@localhost}
GITLAB_CI_SUPPORT=${GITLAB_CI_SUPPORT:-support@localhost}
GITLAB_CI_TIMEZONE=${GITLAB_CI_TIMEZONE:-UTC}
GITLAB_CI_NOTIFY_ON_BROKEN_BUILDS=${GITLAB_CI_NOTIFY_ON_BROKEN_BUILDS:-true}
GITLAB_CI_NOTIFY_PUSHER=${GITLAB_CI_NOTIFY_PUSHER:-$GITLAB_CI_NOTIFY_ADD_COMMITTER}
GITLAB_CI_NOTIFY_PUSHER=${GITLAB_CI_NOTIFY_PUSHER:-false}
GITLAB_CI_BACKUP_DIR="${GITLAB_CI_BACKUP_DIR:-$GITLAB_CI_DATA_DIR/backups}"
GITLAB_CI_BACKUPS=${GITLAB_CI_BACKUPS:-disable}
GITLAB_CI_BACKUP_TIME=${GITLAB_CI_BACKUP_TIME:-04:00}
GITLAB_CI_BACKUP_EXPIRY=${GITLAB_CI_BACKUP_EXPIRY:-}
AWS_BACKUPS=${AWS_BACKUPS:-false}
AWS_BACKUP_REGION=${AWS_BACKUP_REGION}
AWS_BACKUP_ACCESS_KEY_ID=${AWS_BACKUP_ACCESS_KEY_ID}
AWS_BACKUP_SECRET_ACCESS_KEY=${AWS_BACKUP_SECRET_ACCESS_KEY}
AWS_BACKUP_BUCKET=${AWS_BACKUP_BUCKET}
SSL_CERTIFICATE_PATH=${SSL_CERTIFICATE_PATH:-$GITLAB_CI_DATA_DIR/certs/gitlab_ci.crt}
SSL_KEY_PATH=${SSL_KEY_PATH:-$GITLAB_CI_DATA_DIR/certs/gitlab_ci.key}
SSL_DHPARAM_PATH=${SSL_DHPARAM_PATH:-$GITLAB_CI_DATA_DIR/certs/dhparam.pem}
SSL_VERIFY_CLIENT=${SSL_VERIFY_CLIENT:-off}
CA_CERTIFICATES_PATH=${CA_CERTIFICATES_PATH:-$GITLAB_CI_DATA_DIR/certs/ca.crt}
GITLAB_CI_HTTPS_HSTS_ENABLED=${GITLAB_CI_HTTPS_HSTS_ENABLED:-true}
GITLAB_CI_HTTPS_HSTS_MAX_AGE=${GITLAB_CI_HTTPS_HSTS_MAX_AGE:-31536000}
NGINX_WORKERS=${NGINX_WORKERS:-1}
NGINX_MAX_UPLOAD_SIZE=${NGINX_MAX_UPLOAD_SIZE:-20m}
REDIS_HOST=${REDIS_HOST:-}
REDIS_PORT=${REDIS_PORT:-}
UNICORN_WORKERS=${UNICORN_WORKERS:-2}
UNICORN_TIMEOUT=${UNICORN_TIMEOUT:-60}
SIDEKIQ_CONCURRENCY=${SIDEKIQ_CONCURRENCY:-25}
DB_TYPE=${DB_TYPE:-}
DB_HOST=${DB_HOST:-}
DB_PORT=${DB_PORT:-}
DB_NAME=${DB_NAME:-}
DB_USER=${DB_USER:-}
DB_PASS=${DB_PASS:-}
DB_POOL=${DB_POOL:-10}
SMTP_DOMAIN=${SMTP_DOMAIN:-www.gmail.com}
SMTP_HOST=${SMTP_HOST:-smtp.gmail.com}
SMTP_PORT=${SMTP_PORT:-587}
SMTP_USER=${SMTP_USER:-}
SMTP_PASS=${SMTP_PASS:-}
SMTP_OPENSSL_VERIFY_MODE=${SMTP_OPENSSL_VERIFY_MODE:-}
SMTP_STARTTLS=${SMTP_STARTTLS:-true}
SMTP_TLS=${SMTP_TLS:-false}
if [[ -n ${SMTP_USER} ]]; then
SMTP_ENABLED=${SMTP_ENABLED:-true}
SMTP_AUTHENTICATION=${SMTP_AUTHENTICATION:-login}
fi
SMTP_ENABLED=${SMTP_ENABLED:-false}
GITLAB_URL=${GITLAB_URL:-}
GITLAB_APP_ID=${GITLAB_APP_ID:-}
GITLAB_APP_SECRET=${GITLAB_APP_SECRET:-}
# use docker link feature to figure out gitlab url
[[ -z ${GITLAB_URL} && -n ${GITLAB_PORT_80_TCP_ADDR} ]] && \
GITLAB_URL="http://${GITLAB_PORT_80_TCP_ADDR}"
GITLAB_URL=$(sed 's/\//\\\//g' <<< $GITLAB_URL)
# is a mysql or postgresql database linked?
# requires that the mysql or postgresql containers have exposed
# port 3306 and 5432 respectively.
if [[ -n ${MYSQL_PORT_3306_TCP_ADDR} ]]; then
DB_TYPE=mysql
DB_HOST=${DB_HOST:-${MYSQL_PORT_3306_TCP_ADDR}}
DB_PORT=${DB_PORT:-${MYSQL_PORT_3306_TCP_PORT}}
# support for linked sameersbn/mysql image
DB_USER=${DB_USER:-${MYSQL_ENV_DB_USER}}
DB_PASS=${DB_PASS:-${MYSQL_ENV_DB_PASS}}
DB_NAME=${DB_NAME:-${MYSQL_ENV_DB_NAME}}
# support for linked orchardup/mysql and centurylink/mysql image
# also supports official mysql image
DB_USER=${DB_USER:-${MYSQL_ENV_MYSQL_USER}}
DB_PASS=${DB_PASS:-${MYSQL_ENV_MYSQL_PASSWORD}}
DB_NAME=${DB_NAME:-${MYSQL_ENV_MYSQL_DATABASE}}
elif [[ -n ${POSTGRESQL_PORT_5432_TCP_ADDR} ]]; then
DB_TYPE=postgres
DB_HOST=${DB_HOST:-${POSTGRESQL_PORT_5432_TCP_ADDR}}
DB_PORT=${DB_PORT:-${POSTGRESQL_PORT_5432_TCP_PORT}}
# support for linked official postgres image
DB_USER=${DB_USER:-${POSTGRESQL_ENV_POSTGRES_USER}}
DB_PASS=${DB_PASS:-${POSTGRESQL_ENV_POSTGRES_PASSWORD}}
DB_NAME=${DB_NAME:-${DB_USER}}
# support for linked sameersbn/postgresql image
DB_USER=${DB_USER:-${POSTGRESQL_ENV_DB_USER}}
DB_PASS=${DB_PASS:-${POSTGRESQL_ENV_DB_PASS}}
DB_NAME=${DB_NAME:-${POSTGRESQL_ENV_DB_NAME}}
# support for linked orchardup/postgresql image
DB_USER=${DB_USER:-${POSTGRESQL_ENV_POSTGRESQL_USER}}
DB_PASS=${DB_PASS:-${POSTGRESQL_ENV_POSTGRESQL_PASS}}
DB_NAME=${DB_NAME:-${POSTGRESQL_ENV_POSTGRESQL_DB}}
# support for linked paintedfox/postgresql image
DB_USER=${DB_USER:-${POSTGRESQL_ENV_USER}}
DB_PASS=${DB_PASS:-${POSTGRESQL_ENV_PASS}}
DB_NAME=${DB_NAME:-${POSTGRESQL_ENV_DB}}
fi
if [[ -z ${DB_HOST} ]]; then
echo "ERROR: "
echo " Please configure the database connection."
echo " Refer http://git.io/kD0ndg for more information."
echo " Cannot continue without a database. Aborting..."
exit 1
fi
# use default port number if it is still not set
case ${DB_TYPE} in
mysql) DB_PORT=${DB_PORT:-3306} ;;
postgres) DB_PORT=${DB_PORT:-5432} ;;
*)
echo "ERROR: "
echo " Please specify the database type in use via the DB_TYPE configuration option."
echo " Accepted values are \"postgres\" or \"mysql\". Aborting..."
exit 1
;;
esac
# set default user and database
DB_USER=${DB_USER:-root}
DB_NAME=${DB_NAME:-gitlab_ci_production}
# is a redis container linked?
if [[ -n ${REDISIO_PORT_6379_TCP_ADDR} ]]; then
REDIS_HOST=${REDIS_HOST:-${REDISIO_PORT_6379_TCP_ADDR}}
REDIS_PORT=${REDIS_PORT:-${REDISIO_PORT_6379_TCP_PORT}}
fi
# fallback to default redis port
REDIS_PORT=${REDIS_PORT:-6379}
if [[ -z ${REDIS_HOST} ]]; then
echo "ERROR: "
echo " Please configure the redis connection."
echo " Refer http://git.io/PMnRSw for more information."
echo " Cannot continue without a redis connection. Aborting..."
exit 1
fi
case ${GITLAB_CI_HTTPS} in
true)
GITLAB_CI_PORT=${GITLAB_CI_PORT:-443}
NGINX_X_FORWARDED_PROTO=${NGINX_X_FORWARDED_PROTO:-https}
;;
*)
GITLAB_CI_PORT=${GITLAB_CI_PORT:-80}
NGINX_X_FORWARDED_PROTO=${NGINX_X_FORWARDED_PROTO:-\$scheme}
;;
esac
case ${GITLAB_CI_BACKUPS} in
daily|weekly|monthly) GITLAB_CI_BACKUP_EXPIRY=${GITLAB_CI_BACKUP_EXPIRY:-604800} ;;
disable|*) GITLAB_CI_BACKUP_EXPIRY=${GITLAB_CI_BACKUP_EXPIRY:-0} ;;
esac
# populate ${GITLAB_CI_LOG_DIR}
mkdir -m 0755 -p ${GITLAB_CI_LOG_DIR}/supervisor && chown -R root:root ${GITLAB_CI_LOG_DIR}/supervisor
mkdir -m 0755 -p ${GITLAB_CI_LOG_DIR}/nginx && chown -R ${GITLAB_CI_USER}:${GITLAB_CI_USER} ${GITLAB_CI_LOG_DIR}/nginx
mkdir -m 0755 -p ${GITLAB_CI_LOG_DIR}/gitlab-ci && chown -R ${GITLAB_CI_USER}:${GITLAB_CI_USER} ${GITLAB_CI_LOG_DIR}/gitlab-ci
cd ${GITLAB_CI_INSTALL_DIR}
# copy configuration templates
case ${GITLAB_CI_HTTPS} in
true)
if [[ -f ${SSL_CERTIFICATE_PATH} && -f ${SSL_KEY_PATH} && -f ${SSL_DHPARAM_PATH} ]]; then
cp ${SETUP_DIR}/config/nginx/gitlab_ci-ssl /etc/nginx/sites-enabled/gitlab_ci
else
echo "SSL keys and certificates were not found."
echo "Assuming that the container is running behind a HTTPS enabled load balancer."
cp ${SETUP_DIR}/config/nginx/gitlab_ci /etc/nginx/sites-enabled/gitlab_ci
fi
;;
*) cp ${SETUP_DIR}/config/nginx/gitlab_ci /etc/nginx/sites-enabled/gitlab_ci ;;
esac
sudo -HEu ${GITLAB_CI_USER} cp ${SETUP_DIR}/config/gitlab-ci/application.yml config/application.yml
sudo -HEu ${GITLAB_CI_USER} cp ${SETUP_DIR}/config/gitlab-ci/resque.yml config/resque.yml
sudo -HEu ${GITLAB_CI_USER} cp ${SETUP_DIR}/config/gitlab-ci/database.yml config/database.yml
sudo -HEu ${GITLAB_CI_USER} cp ${SETUP_DIR}/config/gitlab-ci/unicorn.rb config/unicorn.rb
[[ ${SMTP_ENABLED} == true ]] && \
sudo -HEu ${GITLAB_CI_USER} cp ${SETUP_DIR}/config/gitlab-ci/smtp_settings.rb config/initializers/smtp_settings.rb
# override default configuration templates with user templates
case ${GITLAB_CI_HTTPS} in
true)
if [[ -f ${SSL_CERTIFICATE_PATH} && -f ${SSL_KEY_PATH} && -f ${SSL_DHPARAM_PATH} ]]; then
[[ -f ${GITLAB_CI_DATA_DIR}/config/nginx/gitlab_ci-ssl ]] && cp ${GITLAB_CI_DATA_DIR}/config/nginx/gitlab_ci-ssl /etc/nginx/sites-enabled/gitlab_ci
else
[[ -f ${GITLAB_CI_DATA_DIR}/nginx/gitlab_ci ]] && cp ${GITLAB_CI_DATA_DIR}/nginx/gitlab_ci /etc/nginx/sites-enabled/gitlab_ci
fi
;;
*) [[ -f ${GITLAB_CI_DATA_DIR}/nginx/gitlab_ci ]] && cp ${GITLAB_CI_DATA_DIR}/nginx/gitlab_ci /etc/nginx/sites-enabled/gitlab_ci ;;
esac
[[ -f ${GITLAB_CI_DATA_DIR}/config/gitlab-ci/application.yml ]] && sudo -HEu ${GITLAB_CI_USER} cp ${GITLAB_CI_DATA_DIR}/config/gitlab-ci/application.yml config/application.yml
[[ -f ${GITLAB_CI_DATA_DIR}/config/gitlab-ci/resque.yml ]] && sudo -HEu ${GITLAB_CI_USER} cp ${GITLAB_CI_DATA_DIR}/config/gitlab-ci/resque.yml config/resque.yml
[[ -f ${GITLAB_CI_DATA_DIR}/config/gitlab-ci/database.yml ]] && sudo -HEu ${GITLAB_CI_USER} cp ${GITLAB_CI_DATA_DIR}/config/gitlab-ci/database.yml config/database.yml
[[ -f ${GITLAB_CI_DATA_DIR}/config/gitlab-ci/unicorn.rb ]] && sudo -HEu ${GITLAB_CI_USER} cp ${GITLAB_CI_DATA_DIR}/config/gitlab-ci/unicorn.rb config/unicorn.rb
[[ ${SMTP_ENABLED} == true ]] && \
[[ -f ${GITLAB_CI_DATA_DIR}/config/gitlab-ci/smtp_settings.rb ]] && sudo -HEu ${GITLAB_CI_USER} cp ${GITLAB_CI_DATA_DIR}/config/gitlab-ci/smtp_settings.rb config/initializers/smtp_settings.rb
if [[ -f ${SSL_CERTIFICATE_PATH} || -f ${CA_CERTIFICATES_PATH} ]]; then
echo "Updating CA certificates..."
[[ -f ${SSL_CERTIFICATE_PATH} ]] && \
cp "${SSL_CERTIFICATE_PATH}" /usr/local/share/ca-certificates/gitlab_ci.crt
[[ -f ${CA_CERTIFICATES_PATH} ]] && \
cp "${CA_CERTIFICATES_PATH}" /usr/local/share/ca-certificates/ca.crt
update-ca-certificates --fresh >/dev/null
fi
# configure nginx
sed 's,{{GITLAB_CI_INSTALL_DIR}},'"${GITLAB_CI_INSTALL_DIR}"',g' -i /etc/nginx/sites-enabled/gitlab_ci
sed 's,{{GITLAB_CI_LOG_DIR}},'"${GITLAB_CI_LOG_DIR}"',g' -i /etc/nginx/sites-enabled/gitlab_ci
sed 's/{{YOUR_SERVER_FQDN}}/'"${GITLAB_CI_HOST}"'/g' -i /etc/nginx/sites-enabled/gitlab_ci
sed 's/{{GITLAB_CI_PORT}}/'"${GITLAB_CI_PORT}"'/' -i /etc/nginx/sites-enabled/gitlab_ci
sed 's,{{SSL_CERTIFICATE_PATH}},'"${SSL_CERTIFICATE_PATH}"',' -i /etc/nginx/sites-enabled/gitlab_ci
sed 's,{{SSL_KEY_PATH}},'"${SSL_KEY_PATH}"',' -i /etc/nginx/sites-enabled/gitlab_ci
sed 's,{{SSL_DHPARAM_PATH}},'"${SSL_DHPARAM_PATH}"',' -i /etc/nginx/sites-enabled/gitlab_ci
sed 's,{{SSL_VERIFY_CLIENT}},'"${SSL_VERIFY_CLIENT}"',' -i /etc/nginx/sites-enabled/gitlab_ci
if [[ -f ${CA_CERTIFICATES_PATH} ]]; then
sed 's,{{CA_CERTIFICATES_PATH}},'"${CA_CERTIFICATES_PATH}"',' -i /etc/nginx/sites-enabled/gitlab_ci
else
sed '/{{CA_CERTIFICATES_PATH}}/d' -i /etc/nginx/sites-enabled/gitlab_ci
fi
sed 's/worker_processes .*/worker_processes '"${NGINX_WORKERS}"';/' -i /etc/nginx/nginx.conf
sed 's/{{NGINX_MAX_UPLOAD_SIZE}}/'"${NGINX_MAX_UPLOAD_SIZE}"'/g' -i /etc/nginx/sites-enabled/gitlab_ci
sed 's,{{NGINX_X_FORWARDED_PROTO}},'"${NGINX_X_FORWARDED_PROTO}"',g' -i /etc/nginx/sites-enabled/gitlab_ci
if [[ ${GITLAB_CI_HTTPS_HSTS_ENABLED} == true ]]; then
sed 's/{{GITLAB_CI_HTTPS_HSTS_MAX_AGE}}/'"${GITLAB_CI_HTTPS_HSTS_MAX_AGE}"'/' -i /etc/nginx/sites-enabled/gitlab_ci
else
sed '/{{GITLAB_CI_HTTPS_HSTS_MAX_AGE}}/d' -i /etc/nginx/sites-enabled/gitlab_ci
fi
# configure relative_url_root
if [[ -n ${GITLAB_CI_RELATIVE_URL_ROOT} ]]; then
sed 's,{{GITLAB_CI_RELATIVE_URL_ROOT}},'"${GITLAB_CI_RELATIVE_URL_ROOT}"',' -i /etc/nginx/sites-enabled/gitlab_ci
sed 's,# alias '"${GITLAB_CI_INSTALL_DIR}"'/public,alias '"${GITLAB_CI_INSTALL_DIR}"'/public,' -i /etc/nginx/sites-enabled/gitlab_ci
sudo -HEu ${GITLAB_CI_USER} sed 's,{{GITLAB_CI_RELATIVE_URL_ROOT}},'"${GITLAB_CI_RELATIVE_URL_ROOT}"',' -i config/unicorn.rb
else
sed 's,{{GITLAB_CI_RELATIVE_URL_ROOT}},/,' -i /etc/nginx/sites-enabled/gitlab_ci
sudo -HEu ${GITLAB_CI_USER} sed '/{{GITLAB_CI_RELATIVE_URL_ROOT}}/d' -i config/unicorn.rb
fi
# disable ipv6 support
if [[ ! -f /proc/net/if_inet6 ]]; then
sed -e '/listen \[::\]:80/ s/^#*/#/' -i /etc/nginx/sites-enabled/gitlab_ci
sed -e '/listen \[::\]:443/ s/^#*/#/' -i /etc/nginx/sites-enabled/gitlab_ci
fi
# configure server url
sudo -HEu ${GITLAB_CI_USER} sed 's/{{GITLAB_URL}}/'"${GITLAB_URL}"'/' -i config/application.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/{{GITLAB_APP_ID}}/'"${GITLAB_APP_ID}"'/' -i config/application.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/{{GITLAB_APP_SECRET}}/'"${GITLAB_APP_SECRET}"'/' -i config/application.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/{{GITLAB_CI_HOST}}/'"${GITLAB_CI_HOST}"'/' -i config/application.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/{{GITLAB_CI_PORT}}/'"${GITLAB_CI_PORT}"'/' -i config/application.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/{{GITLAB_CI_HTTPS}}/'"${GITLAB_CI_HTTPS}"'/' -i config/application.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/{{GITLAB_CI_EMAIL}}/'"${GITLAB_CI_EMAIL}"'/' -i config/application.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/{{GITLAB_CI_SUPPORT}}/'"${GITLAB_CI_SUPPORT}"'/' -i config/application.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/{{GITLAB_CI_NOTIFY_ON_BROKEN_BUILDS}}/'"${GITLAB_CI_NOTIFY_ON_BROKEN_BUILDS}"'/' -i config/application.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/{{GITLAB_CI_NOTIFY_PUSHER}}/'"${GITLAB_CI_NOTIFY_PUSHER}"'/' -i config/application.yml
# configure backups
sudo -HEu ${GITLAB_CI_USER} sed 's,{{GITLAB_CI_BACKUP_DIR}},'"${GITLAB_CI_BACKUP_DIR}"',g' -i config/application.yml
sudo -HEu ${GITLAB_CI_USER} sed 's,{{GITLAB_CI_BACKUP_EXPIRY}},'"${GITLAB_CI_BACKUP_EXPIRY}"',g' -i config/application.yml
# apply aws s3 backup configuration
case ${AWS_BACKUPS} in
true)
if [[ -z ${AWS_BACKUP_REGION} || -z ${AWS_BACKUP_ACCESS_KEY_ID} || -z ${AWS_BACKUP_SECRET_ACCESS_KEY} || -z ${AWS_BACKUP_BUCKET} ]]; then
printf "\nMissing AWS options. Aborting...\n"
exit 1
fi
sudo -HEu ${GITLAB_CI_USER} sed 's/{{AWS_BACKUP_REGION}}/'"${AWS_BACKUP_REGION}"'/' -i config/application.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/{{AWS_BACKUP_ACCESS_KEY_ID}}/'"${AWS_BACKUP_ACCESS_KEY_ID}"'/' -i config/application.yml
sudo -HEu ${GITLAB_CI_USER} sed 's,{{AWS_BACKUP_SECRET_ACCESS_KEY}},'"${AWS_BACKUP_SECRET_ACCESS_KEY}"',' -i config/application.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/{{AWS_BACKUP_BUCKET}}/'"${AWS_BACKUP_BUCKET}"'/' -i config/application.yml
;;
*)
# remove backup configuration lines
sudo -HEu ${GITLAB_CI_USER} sed /upload:/,/remote_directory:/d -i config/application.yml
;;
esac
# configure timezone
sudo -HEu ${GITLAB_CI_USER} sed "s/# config.time_zone.*/config.time_zone = '${GITLAB_CI_TIMEZONE}'/" -i config/application.rb
# configure database
if [[ ${DB_TYPE} == postgres ]]; then
sudo -HEu ${GITLAB_CI_USER} sed 's/{{DB_ADAPTER}}/postgresql/' -i config/database.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/{{DB_ENCODING}}/unicode/' -i config/database.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/reconnect: false/#reconnect: false/' -i config/database.yml
elif [[ ${DB_TYPE} == mysql ]]; then
sudo -HEu ${GITLAB_CI_USER} sed 's/{{DB_ADAPTER}}/mysql2/' -i config/database.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/{{DB_ENCODING}}/utf8/' -i config/database.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/#reconnect: false/reconnect: false/' -i config/database.yml
else
echo "Invalid database type: '$DB_TYPE'. Supported choices: [mysql, postgres]."
fi
sudo -HEu ${GITLAB_CI_USER} sed 's/{{DB_HOST}}/'"${DB_HOST}"'/' -i config/database.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/{{DB_PORT}}/'"${DB_PORT}"'/' -i config/database.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/{{DB_NAME}}/'"${DB_NAME}"'/' -i config/database.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/{{DB_USER}}/'"${DB_USER}"'/' -i config/database.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/{{DB_PASS}}/'"${DB_PASS}"'/' -i config/database.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/{{DB_POOL}}/'"${DB_POOL}"'/' -i config/database.yml
# configure sidekiq concurrency
sed 's/{{SIDEKIQ_CONCURRENCY}}/'"${SIDEKIQ_CONCURRENCY}"'/' -i /etc/supervisor/conf.d/sidekiq.conf
# configure redis
sudo -HEu ${GITLAB_CI_USER} sed 's/{{REDIS_HOST}}/'"${REDIS_HOST}"'/g' -i config/resque.yml
sudo -HEu ${GITLAB_CI_USER} sed 's/{{REDIS_PORT}}/'"${REDIS_PORT}"'/g' -i config/resque.yml
# configure unicorn
sudo -HEu ${GITLAB_CI_USER} sed 's,{{GITLAB_CI_INSTALL_DIR}},'"${GITLAB_CI_INSTALL_DIR}"',g' -i config/unicorn.rb
sudo -HEu ${GITLAB_CI_USER} sed 's/{{UNICORN_WORKERS}}/'"${UNICORN_WORKERS}"'/' -i config/unicorn.rb
sudo -HEu ${GITLAB_CI_USER} sed 's/{{UNICORN_TIMEOUT}}/'"${UNICORN_TIMEOUT}"'/' -i config/unicorn.rb
# configure mail delivery
if [[ ${SMTP_ENABLED} == true ]]; then
sudo -HEu ${GITLAB_CI_USER} sed 's/{{SMTP_HOST}}/'"${SMTP_HOST}"'/' -i config/initializers/smtp_settings.rb
sudo -HEu ${GITLAB_CI_USER} sed 's/{{SMTP_PORT}}/'"${SMTP_PORT}"'/' -i config/initializers/smtp_settings.rb
case ${SMTP_USER} in
"") sudo -HEu ${GITLAB_CI_USER} sed '/{{SMTP_USER}}/d' -i config/initializers/smtp_settings.rb ;;
*) sudo -HEu ${GITLAB_CI_USER} sed 's/{{SMTP_USER}}/'"${SMTP_USER}"'/' -i config/initializers/smtp_settings.rb ;;
esac
case ${SMTP_PASS} in
"") sudo -HEu ${GITLAB_CI_USER} sed '/{{SMTP_PASS}}/d' -i config/initializers/smtp_settings.rb ;;
*) sudo -HEu ${GITLAB_CI_USER} sed 's/{{SMTP_PASS}}/'"${SMTP_PASS}"'/' -i config/initializers/smtp_settings.rb ;;
esac
sudo -HEu ${GITLAB_CI_USER} sed 's/{{SMTP_DOMAIN}}/'"${SMTP_DOMAIN}"'/' -i config/initializers/smtp_settings.rb
sudo -HEu ${GITLAB_CI_USER} sed 's/{{SMTP_STARTTLS}}/'"${SMTP_STARTTLS}"'/' -i config/initializers/smtp_settings.rb
sudo -HEu ${GITLAB_CI_USER} sed 's/{{SMTP_TLS}}/'"${SMTP_TLS}"'/' -i config/initializers/smtp_settings.rb
if [[ -n ${SMTP_OPENSSL_VERIFY_MODE} ]]; then
sudo -HEu ${GITLAB_CI_USER} sed 's/{{SMTP_OPENSSL_VERIFY_MODE}}/'"${SMTP_OPENSSL_VERIFY_MODE}"'/' -i config/initializers/smtp_settings.rb
else
sudo -HEu ${GITLAB_CI_USER} sed '/{{SMTP_OPENSSL_VERIFY_MODE}}/d' -i config/initializers/smtp_settings.rb
fi
case ${SMTP_AUTHENTICATION} in
"") sudo -HEu ${GITLAB_CI_USER} sed '/{{SMTP_AUTHENTICATION}}/d' -i config/initializers/smtp_settings.rb ;;
*) sudo -HEu ${GITLAB_CI_USER} sed 's/{{SMTP_AUTHENTICATION}}/'"${SMTP_AUTHENTICATION}"'/' -i config/initializers/smtp_settings.rb ;;
esac
fi
# take ownership of ${GITLAB_CI_DATA_DIR}
chown ${GITLAB_CI_USER}:${GITLAB_CI_USER} ${GITLAB_CI_DATA_DIR}
# create the backups directory
mkdir -p ${GITLAB_CI_BACKUP_DIR}
chown ${GITLAB_CI_USER}:${GITLAB_CI_USER} ${GITLAB_CI_BACKUP_DIR}
appInit () {
# due to the nature of docker and its use cases, we allow some time
# for the database server to come online.
case ${DB_TYPE} in
mysql)
prog="mysqladmin -h ${DB_HOST} -P ${DB_PORT} -u ${DB_USER} ${DB_PASS:+-p$DB_PASS} status"
;;
postgres)
prog=$(find /usr/lib/postgresql/ -name pg_isready)
prog="${prog} -h ${DB_HOST} -p ${DB_PORT} -U ${DB_USER} -d ${DB_NAME} -t 1"
;;
esac
timeout=60
echo -n "Waiting for database server to accept connections"
while ! ${prog} >/dev/null 2>&1
do
timeout=$(expr $timeout - 1)
if [[ $timeout -eq 0 ]]; then
echo -e "\nCould not connect to database server. Aborting..."
exit 1
fi
echo -n "."
sleep 1
done
echo
# run the `db:setup` rake task if required
case ${DB_TYPE} in
mysql)
QUERY="SELECT count(*) FROM information_schema.tables WHERE table_schema = '${DB_NAME}';"
COUNT=$(mysql -h ${DB_HOST} -P ${DB_PORT} -u ${DB_USER} ${DB_PASS:+-p$DB_PASS} -ss -e "${QUERY}")
;;
postgres)
QUERY="SELECT count(*) FROM information_schema.tables WHERE table_schema = 'public';"
COUNT=$(PGPASSWORD="${DB_PASS}" psql -h ${DB_HOST} -p ${DB_PORT} -U ${DB_USER} -d ${DB_NAME} -Atw -c "${QUERY}")
;;
esac
if [[ -z ${COUNT} || ${COUNT} -eq 0 ]]; then
echo "Setting up GitLab CI for firstrun. Please be patient, this could take a while..."
sudo -HEu ${GITLAB_CI_USER} bundle exec rake db:setup RAILS_ENV=production >/dev/null
fi
# migrate database if the gitlab-ci version has changed.
CURRENT_VERSION=
[[ -f ${GITLAB_CI_DATA_DIR}/VERSION ]] && CURRENT_VERSION=$(cat ${GITLAB_CI_DATA_DIR}/VERSION)
if [[ ${GITLAB_CI_VERSION} != ${CURRENT_VERSION} ]]; then
echo "Migrating database..."
sudo -HEu ${GITLAB_CI_USER} bundle exec rake db:migrate RAILS_ENV=production >/dev/null
sudo -HEu ${GITLAB_CI_USER} echo "${GITLAB_CI_VERSION}" > ${GITLAB_CI_DATA_DIR}/VERSION
fi
# setup cron job for automatic backups
case ${GITLAB_CI_BACKUPS} in
daily|weekly|monthly)
read hour min <<< ${GITLAB_CI_BACKUP_TIME//[:]/ }
crontab -u ${GITLAB_CI_USER} -l > /tmp/cron.${GITLAB_CI_USER}
case ${GITLAB_CI_BACKUPS} in
daily)
sudo -HEu ${GITLAB_CI_USER} cat >> /tmp/cron.${GITLAB_CI_USER} <<EOF
# Automatic Backups: daily
$min $hour * * * /bin/bash -l -c 'cd ${GITLAB_CI_INSTALL_DIR} && bundle exec rake backup:create RAILS_ENV=production'
EOF
;;
weekly)
sudo -HEu ${GITLAB_CI_USER} cat >> /tmp/cron.${GITLAB_CI_USER} <<EOF
# Automatic Backups: weekly
$min $hour * * 0 /bin/bash -l -c 'cd ${GITLAB_CI_INSTALL_DIR} && bundle exec rake backup:create RAILS_ENV=production'
EOF
;;
monthly)
sudo -HEu ${GITLAB_CI_USER} cat >> /tmp/cron.${GITLAB_CI_USER} <<EOF
# Automatic Backups: monthly
$min $hour 01 * * /bin/bash -l -c 'cd ${GITLAB_CI_INSTALL_DIR} && bundle exec rake backup:create RAILS_ENV=production'
EOF
;;
esac
crontab -u ${GITLAB_CI_USER} /tmp/cron.${GITLAB_CI_USER} && rm -rf /tmp/cron.${GITLAB_CI_USER}
;;
esac
# remove stale unicorn and sidekiq pid's if they exist.
rm -rf tmp/pids/unicorn.pid
rm -rf tmp/pids/sidekiq.pid
# remove state unicorn socket if it exists
rm -rf tmp/sockets/gitlab_ci.socket
}
appStart () {
appInit
# start supervisord
exec /usr/bin/supervisord -n -c /etc/supervisor/supervisord.conf
}
appRake () {
if [[ -z ${1} ]]; then
echo "Please specify the rake task to execute."
return 1
fi
echo "Running gitlab ci rake task..."
if [[ ${1} == backup:restore ]]; then
# check if the BACKUP argument is specified
for a in $@
do
if [[ $a == BACKUP=* ]]; then
timestamp=${a:7}
break
fi
done
if [[ -z ${timestamp} ]]; then
# user needs to select the backup to restore
nBackups=$(ls ${GITLAB_CI_BACKUP_DIR}/*_gitlab_ci_backup.tar.gz | wc -l)
if [[ $nBackups -eq 0 ]]; then
echo "No backup present. Cannot continue restore process.".
return 1
fi
for b in `ls ${GITLAB_CI_BACKUP_DIR} | sort -r`
do
echo " ├ $b"
done
read -p "Select a backup to restore: " file
if [[ ! -f ${GITLAB_CI_BACKUP_DIR}/${file} ]]; then
echo "Specified backup does not exist. Aborting..."
return 1
fi
timestamp=$(echo $file | cut -d'_' -f1)
fi
sudo -HEu ${GITLAB_CI_USER} bundle exec rake backup:restore BACKUP=$timestamp RAILS_ENV=production
else
sudo -HEu ${GITLAB_CI_USER} bundle exec rake $@ RAILS_ENV=production
fi
}
appHelp () {
echo "Available options:"
echo " app:start - Starts the gitlab-ci server (default)"
echo " app:init - Initialize the gitlab-ci server (e.g. create databases, compile assets), but don't start it."
echo " app:rake <task> - Execute a rake task."
echo " app:help - Displays the help"
echo " [command] - Execute the specified linux command eg. bash."
}
case ${1} in
app:start)
appStart
;;
app:init)
appInit
;;
app:rake)
shift 1
appRake $@
;;
app:help)
appHelp
;;
*)
if [[ -x ${1} ]]; then
${1}
else
prog=$(which ${1})
if [[ -n ${prog} ]] ; then
shift 1
$prog $@
else
appHelp
fi
fi
;;
esac
exit 0
|
outcoldman/docker-gitlab-ci
|
entrypoint.sh
|
Shell
|
mit
| 23,664
|
---
layout: post
date: '2016-06-17'
title: "Allure Couture C264 Beaded Tank Sheath Wedding Dress"
category: Allure Couture
tags: [Allure Couture]
---
### Allure Couture C264 Beaded Tank Sheath Wedding Dress
Just **$514.99**
###
One of our signature slip gowns. This sexy silhouette is created from two pieces - a top layer of English net embellished with beading and crystals and the bottom a soft satin ensuring a fabulous fit. Colors: White/Silver, Ivory/SilverFabric: English NetSizes: 2-32
<a href="https://www.eudances.com/en/allure-couture/2570-allure-couture-c264-beaded-tank-sheath-wedding-dress.html"><img src="//www.eudances.com/7069-thickbox_default/allure-couture-c264-beaded-tank-sheath-wedding-dress.jpg" alt="Allure Couture C264 Beaded Tank Sheath Wedding Dress" style="width:100%;" /></a>
<!-- break --><a href="https://www.eudances.com/en/allure-couture/2570-allure-couture-c264-beaded-tank-sheath-wedding-dress.html"><img src="//www.eudances.com/7070-thickbox_default/allure-couture-c264-beaded-tank-sheath-wedding-dress.jpg" alt="Allure Couture C264 Beaded Tank Sheath Wedding Dress" style="width:100%;" /></a>
<a href="https://www.eudances.com/en/allure-couture/2570-allure-couture-c264-beaded-tank-sheath-wedding-dress.html"><img src="//www.eudances.com/7071-thickbox_default/allure-couture-c264-beaded-tank-sheath-wedding-dress.jpg" alt="Allure Couture C264 Beaded Tank Sheath Wedding Dress" style="width:100%;" /></a>
<a href="https://www.eudances.com/en/allure-couture/2570-allure-couture-c264-beaded-tank-sheath-wedding-dress.html"><img src="//www.eudances.com/7072-thickbox_default/allure-couture-c264-beaded-tank-sheath-wedding-dress.jpg" alt="Allure Couture C264 Beaded Tank Sheath Wedding Dress" style="width:100%;" /></a>
<a href="https://www.eudances.com/en/allure-couture/2570-allure-couture-c264-beaded-tank-sheath-wedding-dress.html"><img src="//www.eudances.com/7068-thickbox_default/allure-couture-c264-beaded-tank-sheath-wedding-dress.jpg" alt="Allure Couture C264 Beaded Tank Sheath Wedding Dress" style="width:100%;" /></a>
Buy it: [https://www.eudances.com/en/allure-couture/2570-allure-couture-c264-beaded-tank-sheath-wedding-dress.html](https://www.eudances.com/en/allure-couture/2570-allure-couture-c264-beaded-tank-sheath-wedding-dress.html)
|
lastgown/lastgown.github.io
|
_posts/2016-06-17-Allure-Couture-C264-Beaded-Tank-Sheath-Wedding-Dress.md
|
Markdown
|
mit
| 2,289
|
#!/usr/bin/env bash
#Switch the base variables based on the platform
case "$(uname -s)" in
CYGWIN*) #On windows
#TODO: Standardize this path for windows
BASE_DIR=/cygdrive/c/EnglishCentral
printf "Environment set for Cygwin Windows platform.\n"
;;
Darwin) #On mac
BASE_DIR=/usr/local
printf "Environment set for Apple platform.\n"
;;
*)
printf "Error: Running on an unsupported environment."
exit 1
;;
esac
export FLASCC=$BASE_DIR/crossbridge/sdk
export FLEX=$BASE_DIR/air_sdk
export COMPC=$FLEX/bin/compc
export ASC2="java -jar $FLASCC/usr/lib/asc2.jar -merge -md -parallel"
export SWIG=$FLASCC/usr/bin/swig
#This is the path to the FLASCC crossbridge compiler tools. It is used to directly
# access those tools via absolute path rather than relying on the $PATH variable.
export FLASCC_BIN_PATH=$FLASCC/usr/bin
|
marstonstudio/crossUserMedia
|
encoder/as3/setenv.sh
|
Shell
|
mit
| 909
|
using System.Windows.Input;
using Cirrious.MvvmCross.ViewModels;
namespace RegionEx.Core.ViewModels
{
public class Main2ViewModel
: MvxViewModel
{
public ICommand FirstMain { get { return new MvxCommand(FirstMainCommand); } }
public ICommand FirstPopup { get { return new MvxCommand(FirstPopupCommand); } }
public ICommand SecondPopup { get { return new MvxCommand(SecondPopupCommand); } }
private void FirstMainCommand()
{
// Display the view model
ShowViewModel<Main1ViewModel>();
}
private void FirstPopupCommand()
{
// Display the view model
ShowViewModel<Popup1ViewModel>();
}
private void SecondPopupCommand()
{
// Display the view model
ShowViewModel<Popup2ViewModel>();
}
}
}
|
i486dx400/MultiRegionPresenter
|
RegionEx.Core/ViewModels/Main2ViewModel.cs
|
C#
|
mit
| 877
|
using VkNet.Enums;
using VkNet.Enums.Filters;
using VkNet.Enums.SafetyEnums;
using VkNet.Utils;
namespace VkNet.Model.RequestParams
{
/// <summary>
/// Параметры запроса для приложений
/// </summary>
public struct AppGetCatalogParams
{
/// <summary>
/// Параметры запроса для приложений.
/// </summary>
public AppGetCatalogParams(bool gog = true)
{
Sort = AppSort.PopularToday;
Offset = 0;
Count = 100;
Platform = AppPlatforms.Web;
Extended = false;
ReturnFriends = false;
Fields = null;
NameCase = null;
Query = null;
GenreId = null;
Filter = null;
}
/// <summary>
/// Способ сортировки приложений
/// </summary>
public AppSort Sort { get; set; }
/// <summary>
/// Смещение, необходимое для выборки определенного подмножества приложений.
/// </summary>
public uint Offset
{ get; set; }
/// <summary>
/// Количество приложений, информацию о которых необходимо вернуть.
/// </summary>
public uint Count { get; set; }
/// <summary>
/// Платформа для которой необходимо вернуть приложения, принимает значения: ios, android, winphone, web. По умолчанию используется web.
/// </summary>
public AppPlatforms Platform
{ get; set; }
/// <summary>
/// Позволяет получить дополнительные поля: screenshots, MAU (количество уникальных посетителей в месяц),
/// catalog_position, international (отображается ли приложение в каталоге у иностранных пользователей).
/// По умолчанию возвращает только основные поля приложений. Если указан extended – count не должен быть больше 100.
/// </summary>
public bool Extended
{ get; set; }
/// <summary>
/// <c>true</c> – возвращает список друзей, установивших это приложение.
/// (Данный параметр работает только, если пользователь передал валидный access_token)
/// <c>false</c> – не возвращать список друзей, по умолчанию.
/// </summary>
public bool ReturnFriends
{ get; set; }
/// <summary>
/// Список дополнительных полей, которые необходимо вернуть для профилей пользователей.
/// </summary>
public UsersFields Fields
{ get; set; }
/// <summary>
/// Падеж для склонения имени и фамилии пользователей.
/// </summary>
public NameCase NameCase
{ get; set; }
/// <summary>
/// Поисковая строка для поиска по каталогу приложений..
/// </summary>
public string Query
{ get; set; }
/// <summary>
/// Идентификатор жанра.
/// </summary>
public uint? GenreId
{ get; set; }
/// <summary>
/// Фильтр.
/// </summary>
public AppFilter Filter
{ get; set; }
/// <summary>
/// Привести к типу VkParameters.
/// </summary>
/// <param name="p">Параметры.</param>
/// <returns></returns>
internal static VkParameters ToVkParameters(AppGetCatalogParams p)
{
var parameters = new VkParameters
{
{ "sort", p.Sort },
{ "offset", p.Offset },
{ "count", p.Count },
{ "platform", p.Platform },
{ "extended", p.Extended },
{ "return_friends", p.ReturnFriends },
{ "fields", p.Fields },
{ "name_case", p.NameCase },
{ "q", p.Query },
{ "genre_id", p.GenreId },
{ "filter", p.Filter }
};
return parameters;
}
}
}
|
HarkBack/vk
|
VkNet/Model/RequestParams/App/AppGetCatalogParams.cs
|
C#
|
mit
| 4,016
|
import hoistNonReactStatics from 'hoist-non-react-statics';
import React, { Component } from 'react';
export default function fetchData(callback) {
return (WrappedComponent) => {
class FetchData extends Component {
render() {
return <WrappedComponent {...this.props} />;
}
}
FetchData.fetchData = callback;
return hoistNonReactStatics(FetchData, WrappedComponent);
};
}
export function fetchAllData(components, getState, dispatch) {
return Promise.all(
components.filter((component) => component && component.fetchData)
.map((component) => component.fetchData)
.map(fetchData => fetchData(getState, dispatch))
);
};
|
yuanqing/fetch-data
|
src/index.js
|
JavaScript
|
mit
| 678
|
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>gymsystems_client documentation</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="../images/favicon.ico">
<link rel="stylesheet" href="../styles/style.css">
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top visible-xs">
<a href="../" class="navbar-brand">gymsystems_client documentation</a>
<button type="button" class="btn btn-default btn-menu ion-ios-menu" id="btn-menu"></button>
</div>
<div class="xs-menu menu" id="mobile-menu">
<div id="book-search-input" role="search"><input type="text" placeholder="Type to search"></div> <compodoc-menu></compodoc-menu>
</div>
<div class="container-fluid main">
<div class="row main">
<div class="hidden-xs menu">
<compodoc-menu mode="normal"></compodoc-menu>
</div>
<!-- START CONTENT -->
<div class="content class">
<div class="content-data">
<ol class="breadcrumb">
<li>Classes</li>
<li>ExpansionSource</li>
</ol>
<ul class="nav nav-tabs" role="tablist">
<li class="active">
<a href="#info" role="tab" id="info-tab" data-toggle="tab" data-link="info">Info</a>
</li>
<li >
<a href="#source" role="tab" id="source-tab" data-toggle="tab" data-link="source">Source</a>
</li>
</ul>
<div class="tab-content">
<div class="tab-pane fade active in" id="c-info">
<p class="comment">
<h3>File</h3>
</p>
<p class="comment">
<code>src/app/shared/services/expansion-source.ts</code>
</p>
<p class="comment">
<h3>Extends</h3>
</p>
<p class="comment">
<code><a href="../classes/SubjectSource.html" target="_self" >SubjectSource</a></code>
</p>
<section>
<h3 id="index">Index</h3>
<table class="table table-sm table-bordered index-table">
<tbody>
<tr>
<td class="col-md-4">
<h6><b>Properties</b></h6>
</td>
</tr>
<tr>
<td class="col-md-4">
<ul class="index-list">
<li>
<span class="modifier">Private</span>
<a href="#alternateSubject">alternateSubject</a>
</li>
<li>
<a href="#currentSort">currentSort</a>
</li>
<li>
<a href="#isExpansionDetailRow">isExpansionDetailRow</a>
</li>
<li>
<span class="modifier">Public</span>
<a href="#subject">subject</a>
</li>
<li>
<a href="#sortChanged">sortChanged</a>
</li>
<li>
<span class="modifier">Public</span>
<a href="#subject">subject</a>
</li>
</ul>
</td>
</tr>
<tr>
<td class="col-md-4">
<h6><b>Methods</b></h6>
</td>
</tr>
<tr>
<td class="col-md-4">
<ul class="index-list">
<li>
<a href="#add">add</a>
</li>
<li>
<a href="#clearSelection">clearSelection</a>
</li>
<li>
<a href="#connect">connect</a>
</li>
<li>
<a href="#disconnect">disconnect</a>
</li>
<li>
<a href="#findIndexOf">findIndexOf</a>
</li>
<li>
<a href="#select">select</a>
</li>
<li>
<a href="#sortData">sortData</a>
</li>
<li>
<a href="#add">add</a>
</li>
<li>
<a href="#connect">connect</a>
</li>
<li>
<a href="#disconnect">disconnect</a>
</li>
<li>
<a href="#findIndexOf">findIndexOf</a>
</li>
<li>
<a href="#sortData">sortData</a>
</li>
</ul>
</td>
</tr>
<tr>
<td class="col-md-4">
<h6><b>Accessors</b></h6>
</td>
</tr>
<tr>
<td class="col-md-4">
<ul class="index-list">
<li>
<a href="#realRows">realRows</a>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
</section>
<section>
<h3 id="constructor">Constructor</h3>
<table class="table table-sm table-bordered">
<tbody>
<tr>
<td class="col-md-4">
<code>constructor(subject: BehaviorSubject<T[]>)</code>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Defined in <a href="" data-line="15" class="link-to-prism">src/app/shared/services/expansion-source.ts:15</a></div>
</td>
</tr>
<tr>
<td class="col-md-4">
<div>
<b>Parameters :</b>
<table class="params">
<thead>
<tr>
<td>Name</td>
<td>Type</td>
<td>Optional</td>
</tr>
</thead>
<tbody>
<tr>
<td>subject</td>
<td>
<code>BehaviorSubject<T[]></code>
</td>
<td>
No
</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>
</section>
<section>
<h3 id="inputs">
Properties
</h3>
<table class="table table-sm table-bordered">
<tbody>
<tr>
<td class="col-md-4">
<a name="alternateSubject"></a>
<span class="name">
<b>
<span class="modifier">Private</span>
alternateSubject</b>
<a href="#alternateSubject"><span class="icon ion-ios-link"></span></a>
</span>
</td>
</tr>
<tr>
<td class="col-md-4">
<i>Default value : </i><code>new BehaviorSubject<T[]>(null)</code>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Defined in <a href="" data-line="12" class="link-to-prism">src/app/shared/services/expansion-source.ts:12</a></div>
</td>
</tr>
</tbody>
</table>
<table class="table table-sm table-bordered">
<tbody>
<tr>
<td class="col-md-4">
<a name="currentSort"></a>
<span class="name">
<b>
currentSort</b>
<a href="#currentSort"><span class="icon ion-ios-link"></span></a>
</span>
</td>
</tr>
<tr>
<td class="col-md-4">
<i>Type : </i> <code>Sort</code>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Defined in <a href="" data-line="15" class="link-to-prism">src/app/shared/services/expansion-source.ts:15</a></div>
</td>
</tr>
</tbody>
</table>
<table class="table table-sm table-bordered">
<tbody>
<tr>
<td class="col-md-4">
<a name="isExpansionDetailRow"></a>
<span class="name">
<b>
isExpansionDetailRow</b>
<a href="#isExpansionDetailRow"><span class="icon ion-ios-link"></span></a>
</span>
</td>
</tr>
<tr>
<td class="col-md-4">
<i>Default value : </i><code>() => {...}</code>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Defined in <a href="" data-line="30" class="link-to-prism">src/app/shared/services/expansion-source.ts:30</a></div>
</td>
</tr>
</tbody>
</table>
<table class="table table-sm table-bordered">
<tbody>
<tr>
<td class="col-md-4">
<a name="subject"></a>
<span class="name">
<b>
<span class="modifier">Public</span>
subject</b>
<a href="#subject"><span class="icon ion-ios-link"></span></a>
</span>
</td>
</tr>
<tr>
<td class="col-md-4">
<i>Type : </i> <code>BehaviorSubject<T[]></code>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Defined in <a href="" data-line="17" class="link-to-prism">src/app/shared/services/expansion-source.ts:17</a></div>
</td>
</tr>
</tbody>
</table>
<table class="table table-sm table-bordered">
<tbody>
<tr>
<td class="col-md-4">
<a name="sortChanged"></a>
<span class="name">
<b>
sortChanged</b>
<a href="#sortChanged"><span class="icon ion-ios-link"></span></a>
</span>
</td>
</tr>
<tr>
<td class="col-md-4">
<i>Default value : </i><code>new BehaviorSubject(undefined)</code>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Inherited from <code><a href="../classes/SubjectSource.html" target="_self" >SubjectSource</a></code>
</div>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Defined in <code><a href="../classes/SubjectSource.html#source" target="_self" >SubjectSource:9</a></code>
</div>
</td>
</tr>
</tbody>
</table>
<table class="table table-sm table-bordered">
<tbody>
<tr>
<td class="col-md-4">
<a name="subject"></a>
<span class="name">
<b>
<span class="modifier">Public</span>
subject</b>
<a href="#subject"><span class="icon ion-ios-link"></span></a>
</span>
</td>
</tr>
<tr>
<td class="col-md-4">
<i>Type : </i> <code>BehaviorSubject<T[]></code>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Inherited from <code><a href="../classes/SubjectSource.html" target="_self" >SubjectSource</a></code>
</div>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Defined in <code><a href="../classes/SubjectSource.html#source" target="_self" >SubjectSource:13</a></code>
</div>
</td>
</tr>
</tbody>
</table>
</section>
<section>
<h3 id="methods">
Methods
</h3>
<table class="table table-sm table-bordered">
<tbody>
<tr>
<td class="col-md-4">
<a name="add"></a>
<span class="name">
<b>
add
</b>
<a href="#add"><span class="icon ion-ios-link"></span></a>
</span>
</td>
</tr>
<tr>
<td class="col-md-4">
<code>add(element: T)</code>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Defined in <a href="" data-line="37"
class="link-to-prism">src/app/shared/services/expansion-source.ts:37</a></div>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-description">
<b>Parameters :</b>
<table class="params">
<thead>
<tr>
<td>Name</td>
<td>Type</td>
<td>Optional</td>
</tr>
</thead>
<tbody>
<tr>
<td>element</td>
<td>
<code>T</code>
</td>
<td>
No
</td>
</tr>
</tbody>
</table>
</div>
<div>
</div>
<div class="io-description">
<b>Returns : </b> <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/number" target="_blank" >number</a></code>
</div>
<div class="io-description">
</div>
</td>
</tr>
</tbody>
</table>
<table class="table table-sm table-bordered">
<tbody>
<tr>
<td class="col-md-4">
<a name="clearSelection"></a>
<span class="name">
<b>
clearSelection
</b>
<a href="#clearSelection"><span class="icon ion-ios-link"></span></a>
</span>
</td>
</tr>
<tr>
<td class="col-md-4">
<code>clearSelection()</code>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Defined in <a href="" data-line="55"
class="link-to-prism">src/app/shared/services/expansion-source.ts:55</a></div>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-description">
<b>Returns : </b> <code><a href="https://www.typescriptlang.org/docs/handbook/basic-types.html" target="_blank" >void</a></code>
</div>
</td>
</tr>
</tbody>
</table>
<table class="table table-sm table-bordered">
<tbody>
<tr>
<td class="col-md-4">
<a name="connect"></a>
<span class="name">
<b>
connect
</b>
<a href="#connect"><span class="icon ion-ios-link"></span></a>
</span>
</td>
</tr>
<tr>
<td class="col-md-4">
<code>connect()</code>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Defined in <a href="" data-line="26"
class="link-to-prism">src/app/shared/services/expansion-source.ts:26</a></div>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-description">
<b>Returns : </b> <code>Observable<T[]></code>
</div>
</td>
</tr>
</tbody>
</table>
<table class="table table-sm table-bordered">
<tbody>
<tr>
<td class="col-md-4">
<a name="disconnect"></a>
<span class="name">
<b>
disconnect
</b>
<a href="#disconnect"><span class="icon ion-ios-link"></span></a>
</span>
</td>
</tr>
<tr>
<td class="col-md-4">
<code>disconnect()</code>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Defined in <a href="" data-line="59"
class="link-to-prism">src/app/shared/services/expansion-source.ts:59</a></div>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-description">
<b>Returns : </b> <code><a href="https://www.typescriptlang.org/docs/handbook/basic-types.html" target="_blank" >void</a></code>
</div>
</td>
</tr>
</tbody>
</table>
<table class="table table-sm table-bordered">
<tbody>
<tr>
<td class="col-md-4">
<a name="findIndexOf"></a>
<span class="name">
<b>
findIndexOf
</b>
<a href="#findIndexOf"><span class="icon ion-ios-link"></span></a>
</span>
</td>
</tr>
<tr>
<td class="col-md-4">
<code>findIndexOf(element: T)</code>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Defined in <a href="" data-line="51"
class="link-to-prism">src/app/shared/services/expansion-source.ts:51</a></div>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-description">
<b>Parameters :</b>
<table class="params">
<thead>
<tr>
<td>Name</td>
<td>Type</td>
<td>Optional</td>
</tr>
</thead>
<tbody>
<tr>
<td>element</td>
<td>
<code>T</code>
</td>
<td>
No
</td>
</tr>
</tbody>
</table>
</div>
<div>
</div>
<div class="io-description">
<b>Returns : </b> <code><a href="https://www.typescriptlang.org/docs/handbook/basic-types.html" target="_blank" >any</a></code>
</div>
<div class="io-description">
</div>
</td>
</tr>
</tbody>
</table>
<table class="table table-sm table-bordered">
<tbody>
<tr>
<td class="col-md-4">
<a name="select"></a>
<span class="name">
<b>
select
</b>
<a href="#select"><span class="icon ion-ios-link"></span></a>
</span>
</td>
</tr>
<tr>
<td class="col-md-4">
<code>select(element: T, row?: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/number" target="_blank">number</a>)</code>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Defined in <a href="" data-line="42"
class="link-to-prism">src/app/shared/services/expansion-source.ts:42</a></div>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-description">
<b>Parameters :</b>
<table class="params">
<thead>
<tr>
<td>Name</td>
<td>Type</td>
<td>Optional</td>
</tr>
</thead>
<tbody>
<tr>
<td>element</td>
<td>
<code>T</code>
</td>
<td>
No
</td>
</tr>
<tr>
<td>row</td>
<td>
<code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/number" target="_blank" >number</a></code>
</td>
<td>
Yes
</td>
</tr>
</tbody>
</table>
</div>
<div>
</div>
<div class="io-description">
<b>Returns : </b> <code><a href="https://www.typescriptlang.org/docs/handbook/basic-types.html" target="_blank" >void</a></code>
</div>
<div class="io-description">
</div>
</td>
</tr>
</tbody>
</table>
<table class="table table-sm table-bordered">
<tbody>
<tr>
<td class="col-md-4">
<a name="sortData"></a>
<span class="name">
<b>
sortData
</b>
<a href="#sortData"><span class="icon ion-ios-link"></span></a>
</span>
</td>
</tr>
<tr>
<td class="col-md-4">
<code>sortData($event: Sort, elements?: T[])</code>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Defined in <a href="" data-line="32"
class="link-to-prism">src/app/shared/services/expansion-source.ts:32</a></div>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-description">
<b>Parameters :</b>
<table class="params">
<thead>
<tr>
<td>Name</td>
<td>Type</td>
<td>Optional</td>
</tr>
</thead>
<tbody>
<tr>
<td>$event</td>
<td>
<code>Sort</code>
</td>
<td>
No
</td>
</tr>
<tr>
<td>elements</td>
<td>
<code>T[]</code>
</td>
<td>
Yes
</td>
</tr>
</tbody>
</table>
</div>
<div>
</div>
<div class="io-description">
<b>Returns : </b> <code><a href="https://www.typescriptlang.org/docs/handbook/basic-types.html" target="_blank" >void</a></code>
</div>
<div class="io-description">
</div>
</td>
</tr>
</tbody>
</table>
<table class="table table-sm table-bordered">
<tbody>
<tr>
<td class="col-md-4">
<a name="add"></a>
<span class="name">
<b>
add
</b>
<a href="#add"><span class="icon ion-ios-link"></span></a>
</span>
</td>
</tr>
<tr>
<td class="col-md-4">
<code>add(element: T)</code>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Inherited from <code><a href="../classes/SubjectSource.html" target="_self" >SubjectSource</a></code>
</div>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Defined in <code><a href="../classes/SubjectSource.html#source" target="_self" >SubjectSource:40</a></code>
</div>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-description">
<b>Parameters :</b>
<table class="params">
<thead>
<tr>
<td>Name</td>
<td>Type</td>
<td>Optional</td>
</tr>
</thead>
<tbody>
<tr>
<td>element</td>
<td>
<code>T</code>
</td>
<td>
No
</td>
</tr>
</tbody>
</table>
</div>
<div>
</div>
<div class="io-description">
<b>Returns : </b> <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/number" target="_blank" >number</a></code>
</div>
<div class="io-description">
</div>
</td>
</tr>
</tbody>
</table>
<table class="table table-sm table-bordered">
<tbody>
<tr>
<td class="col-md-4">
<a name="connect"></a>
<span class="name">
<b>
connect
</b>
<a href="#connect"><span class="icon ion-ios-link"></span></a>
</span>
</td>
</tr>
<tr>
<td class="col-md-4">
<code>connect()</code>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Inherited from <code><a href="../classes/SubjectSource.html" target="_self" >SubjectSource</a></code>
</div>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Defined in <code><a href="../classes/SubjectSource.html#source" target="_self" >SubjectSource:17</a></code>
</div>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-description">
<b>Returns : </b> <code>Observable<T[]></code>
</div>
</td>
</tr>
</tbody>
</table>
<table class="table table-sm table-bordered">
<tbody>
<tr>
<td class="col-md-4">
<a name="disconnect"></a>
<span class="name">
<b>
disconnect
</b>
<a href="#disconnect"><span class="icon ion-ios-link"></span></a>
</span>
</td>
</tr>
<tr>
<td class="col-md-4">
<code>disconnect()</code>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Inherited from <code><a href="../classes/SubjectSource.html" target="_self" >SubjectSource</a></code>
</div>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Defined in <code><a href="../classes/SubjectSource.html#source" target="_self" >SubjectSource:51</a></code>
</div>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-description">
<b>Returns : </b> <code><a href="https://www.typescriptlang.org/docs/handbook/basic-types.html" target="_blank" >void</a></code>
</div>
</td>
</tr>
</tbody>
</table>
<table class="table table-sm table-bordered">
<tbody>
<tr>
<td class="col-md-4">
<a name="findIndexOf"></a>
<span class="name">
<b>
findIndexOf
</b>
<a href="#findIndexOf"><span class="icon ion-ios-link"></span></a>
</span>
</td>
</tr>
<tr>
<td class="col-md-4">
<code>findIndexOf(element: T)</code>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Inherited from <code><a href="../classes/SubjectSource.html" target="_self" >SubjectSource</a></code>
</div>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Defined in <code><a href="../classes/SubjectSource.html#source" target="_self" >SubjectSource:47</a></code>
</div>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-description">
<b>Parameters :</b>
<table class="params">
<thead>
<tr>
<td>Name</td>
<td>Type</td>
<td>Optional</td>
</tr>
</thead>
<tbody>
<tr>
<td>element</td>
<td>
<code>T</code>
</td>
<td>
No
</td>
</tr>
</tbody>
</table>
</div>
<div>
</div>
<div class="io-description">
<b>Returns : </b> <code><a href="https://www.typescriptlang.org/docs/handbook/basic-types.html" target="_blank" >any</a></code>
</div>
<div class="io-description">
</div>
</td>
</tr>
</tbody>
</table>
<table class="table table-sm table-bordered">
<tbody>
<tr>
<td class="col-md-4">
<a name="sortData"></a>
<span class="name">
<b>
sortData
</b>
<a href="#sortData"><span class="icon ion-ios-link"></span></a>
</span>
</td>
</tr>
<tr>
<td class="col-md-4">
<code>sortData($event: Sort, elements?: T[])</code>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Inherited from <code><a href="../classes/SubjectSource.html" target="_self" >SubjectSource</a></code>
</div>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Defined in <code><a href="../classes/SubjectSource.html#source" target="_self" >SubjectSource:21</a></code>
</div>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-description">
<b>Parameters :</b>
<table class="params">
<thead>
<tr>
<td>Name</td>
<td>Type</td>
<td>Optional</td>
</tr>
</thead>
<tbody>
<tr>
<td>$event</td>
<td>
<code>Sort</code>
</td>
<td>
No
</td>
</tr>
<tr>
<td>elements</td>
<td>
<code>T[]</code>
</td>
<td>
Yes
</td>
</tr>
</tbody>
</table>
</div>
<div>
</div>
<div class="io-description">
<b>Returns : </b> <code><a href="https://www.typescriptlang.org/docs/handbook/basic-types.html" target="_blank" >void</a></code>
</div>
<div class="io-description">
</div>
</td>
</tr>
</tbody>
</table>
</section>
<section>
<h3 id="accessors">
Accessors
</h3>
<table class="table table-sm table-bordered">
<tbody>
<tr>
<td class="col-md-4">
<a name="realRows"></a>
<span class="name"><b>realRows</b><a href="#realRows"><span class="icon ion-ios-link"></span></a></span>
</td>
</tr>
<tr>
<td class="col-md-4">
<span class="accessor"><b>get</b><code>realRows()</code></span>
</td>
</tr>
<tr>
<td class="col-md-4">
<div class="io-line">Defined in <a href="" data-line="13" class="link-to-prism">src/app/shared/services/expansion-source.ts:13</a></div>
</td>
</tr>
</tbody>
</table>
</section>
</div>
<div class="tab-pane fade tab-source-code" id="c-source">
<pre class="line-numbers compodoc-sourcecode"><code class="language-typescript">import { DataSource } from '@angular/cdk/table';
import { Observable, BehaviorSubject } from 'rxjs';
import { Sort } from '@angular/material';
import { SubjectSource } from 'app/shared/services/subject-source';
export interface ExpansionRow<T> {
detailRow: boolean;
expanded: boolean;
T;
}
export class ExpansionSource<T> extends SubjectSource<T> {
private alternateSubject = new BehaviorSubject<T[]>(null);
private get realRows() { return <(T|ExpansionRow<T>)[]> this.alternateSubject.value; }
currentSort: Sort;
constructor(public subject: BehaviorSubject<T[]>) {
super(subject);
this.subject.subscribe(values => {
const rows = [];
values.forEach(element => rows.push(element, {detailRow: true, expanded: false, element}));
this.alternateSubject.next(rows);
});
}
connect(): Observable<T[]> {
return this.alternateSubject;
}
isExpansionDetailRow = (row: any) => row.hasOwnProperty('detailRow');
sortData($event: Sort, elements?: T[]) {
this.clearSelection();
super.sortData($event, elements);
}
add(element: T): number {
this.clearSelection();
return super.add(element);
}
select(element: T, row?: number) {
this.clearSelection();
if (element != null) {
row = row || this.alternateSubject.value.findIndex(m => m === element);
(<ExpansionRow<T>> this.realRows[row + 1]).expanded = true;
}
}
findIndexOf(element: T) {
return this.alternateSubject.value.findIndex(m => m === element);
}
clearSelection() {
this.realRows.filter(r => r.hasOwnProperty('detailRow')).forEach(r => (<ExpansionRow<T>> r).expanded = false );
}
disconnect() {}
}
</code></pre>
</div>
</div>
</div><div class="search-results">
<div class="has-results">
<h1 class="search-results-title"><span class='search-results-count'></span> result-matching "<span class='search-query'></span>"</h1>
<ul class="search-results-list"></ul>
</div>
<div class="no-results">
<h1 class="search-results-title">No results matching "<span class='search-query'></span>"</h1>
</div>
</div>
</div>
<!-- END CONTENT -->
</div>
</div>
<script>
var COMPODOC_CURRENT_PAGE_DEPTH = 1;
var COMPODOC_CURRENT_PAGE_CONTEXT = 'class';
var COMPODOC_CURRENT_PAGE_URL = 'ExpansionSource.html';
</script>
<script src="../js/libs/custom-elements.min.js"></script>
<script src="../js/libs/lit-html.js"></script>
<!-- Required to polyfill modern browsers as code is ES5 for IE... -->
<script src="../js/libs/custom-elements-es5-adapter.js" charset="utf-8" defer></script>
<script src="../js/menu-wc.js" defer></script>
<script src="../js/libs/bootstrap-native.js"></script>
<script src="../js/libs/es6-shim.min.js"></script>
<script src="../js/libs/EventDispatcher.js"></script>
<script src="../js/libs/promise.min.js"></script>
<script src="../js/libs/zepto.min.js"></script>
<script src="../js/compodoc.js"></script>
<script src="../js/tabs.js"></script>
<script src="../js/menu.js"></script>
<script src="../js/libs/clipboard.min.js"></script>
<script src="../js/libs/prism.js"></script>
<script src="../js/sourceCode.js"></script>
<script src="../js/search/search.js"></script>
<script src="../js/search/lunr.min.js"></script>
<script src="../js/search/search-lunr.js"></script>
<script src="../js/search/search_index.js"></script>
<script src="../js/lazy-load-graphs.js"></script>
</body>
</html>
|
OysteinAmundsen/gymsystems
|
client/documentation/classes/ExpansionSource.html
|
HTML
|
mit
| 46,275
|
---
layout: post.njk
title: "The Road Again"
date: 2021-11-12
summary: "I decide to take a break and go somewhere in my RV with the worst possible internet connection. Plus, how to be a tech teacher, YouTube makes moves, the gig economy and the end of coding as we know it."
hero: /images/newsletter/theroadagain.png
thumb: /images/newsletter/theroadagain_tn.jpg
category: newsletter
---
A few years ago I picked up a used RV in great condition. My wife loves hiking, and I love my wife, but I hate bugs…or being outside…or bad connections. We found a compromise…an RV lets you go glamping with AC/Heater a full kitchen. Now that's what I call 'roughing it'.
So far, the internet connection on these trips have gone from bad to worse at every campground we've been at. Last week, we went to Mistletoe State park. Let me tell you, the best connection was either standing next to the dumpster or by the public bathrooms. I thought about bringing a little table to either, but thankfully, better judgment prevailed.
<div class="article-side-image">

</div>
I abandoned all connected hope but had a great time with the family. In all honesty, it was so cold that I stayed mostly indoors, so me and Mojo, the coding dog, hung around in bed and I managed to get a couple of games of KOTOR (Knights of the Old Republic) going, so it wasn't so rough.
After the trip, I told my wife that my world did indeed not come to an end, plus I had a reasonable time, so that maybe we can try disconnecting once a quarter. I promised not to fuzz about the internet connection anymore. We'll see how that goes. I feel like it's a good idea to try to avoid burnout ([check out this post](https://www.linkedin.com/posts/planetoftheweb_technology-webdeveloper-webdesign-activity-6863556621222637568-aYqm))
## Looking for Tech Teachers
By the way, my ex-boss and friend asked me to tell you that we're always looking for great new technology teachers. If you want to make some extra cash and love programming/helping others. It's a fantastic gig.
<div class="article-side-image">

</div>
The team here is amazing and treat you like royalty (at least what I imagine royalty gets treated like). They assign you a producer, who helps you through the whole process with all the scary things and there's a whole amazing team of content managers, course testers, video and audio experts.
They help you focus on just the teaching part and I' always amazed at how much better I look and sound because of them. If you're good with the technology, they take care of the rest.
If you're interested in that type of thing, just [DM me on LinkedIn](https://www.linkedin.com/in/planetoftheweb/) and I'll point you to the right person.
## More Posts
Lately, I've been posting more about current events, and they're getting a lot of traction. I don't like controversial topics or hot takes. I'm the type of person that tries to consider all sides of an issue and like to hear what others (more opinionated than I) say. I think it's healthy to hear good arguments.
<iframe src="https://www.linkedin.com/embed/feed/update/urn:li:share:6864617430086361090" height="749" width="504" frameborder="0" allowfullscreen="" title="Embedded post"></iframe>
Case in point. Recently YouTube decided to remove their dislike button from public view. It's still there, but the results will be private. You can see the comments in the article. So far, I feel like we lose something when all we hear is the positive likes. It feels like giving my kids only candy to eat. At any rate, since the dislikes and nasty comments are still there, I don't think this helps anyone mental health.
It feels more like a move to placate corporate interests, who would suffer from the negative Public Relations and can possibly put pressure on YouTube/Google for this this type of change. I expect some sort of backlash but it won't matter YouTube can do what they want.
Honestly, it was probably a bad idea to put that there in the first place. Tell me what you think.
## YouTube as a Shopping Network
Another interesting bit of news from YouTube was the fact that they are planning on incorporating shopping more tighly into their platform.
<iframe src="https://www.linkedin.com/embed/feed/update/urn:li:share:6863945040201359361" height="552" width="504" frameborder="0" allowfullscreen="" title="Embedded post"></iframe>
They hope to have this ready for Christmas, but whatever the do, it better be quick with all the shipping and supply side problem we're having here on the US. That's going to be huge for creators. I already buy tons of stuff after watching YouTube videos, so if they figure out the right way to monetize this, they'll be rolling in cash.
## Meta's Virtual World

Of course you heard [Facebook's announcement on Meta](https://www.linkedin.com/posts/planetoftheweb_facialrecognition-metafacebook-facebook-activity-6861443774439055360-9jWZ). I'm wondering what you think. Me, I feel like this has been done before with Second Life, but the AR possibilities are interesting.
I think the real hook might be to create virtual work environments on the fly that allow you to attend meetings with others a-la-Jedi-Council, use an infinite amount of virtual monitors that take up no space (in my RV once the connection things are fixed). People might truly be able to work from anywhere.
## Other Posts
A couple of other things I posted about you might have missed. Microsoft announced an update to excel with [additional javscript API features](https://www.linkedin.com/posts/planetoftheweb_microsoft-brings-javascript-to-excel-activity-6863688367545102336-7iCT), Edge is now [available in Linux](https://www.linkedin.com/posts/planetoftheweb_microsofts-edge-browser-is-now-available-activity-6861740011126079489-rGL0)…I'm hoping it fits in a raspberry pi. That would be epic. Also, I did a post on whether developers would go back if their office was a [Trophy Office](https://www.linkedin.com/posts/planetoftheweb_webdeveloper-webdesigner-homeoffice-activity-6861731271077351424-BBqZ).
## The Gig Economy
Plugging along, my friend and fellow author Garrick Chow created a short video with his experience breaking into the Gig economy as a DoorDash/Uber Eats.
<iframe src="https://www.linkedin.com/embed/feed/update/urn:li:ugcPost:6864225477951942656" height="654" width="504" frameborder="0" allowfullscreen="" title="Embedded post"></iframe>
He's doing it as an experiment and documenting it online in a [new page](https://www.linkedin.com/company/staffinstructors/) that the creative team is putting together, so check it out and follow it. Who knows, I might do a cameo in there if the topic works for something I'm doing.
# The Toolbox
<iframe class="ratio ratio-16x9" src="https://www.linkedin.com/video/embed/live/urn:li:ugcPost:6863638563100123136" height="600" width="900" frameborder="0" allowfullscreen="" title="Embedded post"></iframe>
I'm back on my regular schedule with The Toolbox. This week, I talk about a new framework from the makers of Shopify called [Hydrogen](https://shopify.dev/custom-storefronts/hydrogen). If were to throw almost every library and framework I'm excited about using, that's what they've done with Hydrogen. Super exciting Stuff.
I also briefly talk about [Microsoft's Loop](https://www.microsoft.com/en-us/microsoft-loop), the upcoming App that's is very similar to [Notion](https://www.notion.so/). Notion is what I used to use before I made the switch to Obsidian. It's sort of like Teams, but instead of a having a communications focus, it's more about productivity and document sharing, which honestly is a bit weaker in Teams.
Finally, the most important thing I cover in this episode is what I'm calling "The End of Coding as we know it". I just finished doing a course on Publishing with Github and I realized that I didn't need to use my desktop version of VSCode at all. That was real surprising. I think this is going to be a paradigm shift in the industry. It removes so much friction for developers that in the future no one will want to code any other way.
I'm trying to get on a more regular schedule. You can [sign up for a reminder of Episode 12](https://www.linkedin.com/video/event/urn:li:ugcPost:6864473777623875584/). I've got lots of ideas of what to cover, but I want to keep the topics a bit under wraps for now. If you have any thoughts, let me know.
|
planetoftheweb/planetoftheweb.github.io
|
_site/newsletter/2021-11-12-the-road-again.md
|
Markdown
|
mit
| 8,550
|
from PySide import QtCore, QtGui
class MakinFrame(QtGui.QFrame):
mousegeser = QtCore.Signal(int,int)
def __init__(self,parent=None):
super(MakinFrame,self).__init__(parent)
self.setMouseTracking(True)
def setMouseTracking(self, flag):
def recursive_set(parent):
for child in parent.findChildren(QtCore.QObject):
try:
child.setMouseTracking(flag)
except:
pass
recursive_set(child)
QtGui.QWidget.setMouseTracking(self,flag)
recursive_set(self)
def mouseMoveEvent(self, me):
a = QtGui.QFrame.mouseMoveEvent(self,me)
self.mousegeser.emit(me.x(), me.y())
return a
|
imakin/PersonalAssistant
|
GameBot/src_py/makinreusable/makinframe.py
|
Python
|
mit
| 610
|
# frozen_string_literal: true
module ControllerMacros
def json
JSON.parse(response.body)
end
def sign(payload, key)
digest = OpenSSL::Digest.new('sha256')
OpenSSL::HMAC.hexdigest(digest, key, payload)
end
end
|
rainforestapp/rainforest-integrations
|
spec/support/controller_macros.rb
|
Ruby
|
mit
| 230
|
{% extends "backoffice/base.html" %}
{% block active_bdata3 %}active{% endblock %}
{% block title %}Bdata Mode 3{% endblock %}
{% block title_mini %}{{city.name}}{% endblock %}
{% block content %}
<div class="space-6"></div>
<div class="row-fluid">
<div class="span6">
<div class="widget-box transparent">
<div class="widget-body">
<div class="widget-main no-padding">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>
<i class="icon-caret-right blue"></i>
NBusstop
</th>
<th class="hidden-phone">
<i class="icon-caret-right blue"></i>
Названия маршрутов
</th>
</tr>
</thead>
<tbody>
{%for k,v in bdata3.items%}
<tr>
<td>{{k}}</td>
<td>{{v}}</td>
</tr>
{%endfor%}
</tbody>
</table>
</div><!-- /widget-main -->
</div><!-- /widget-body -->
</div><!-- /widget-box -->
</div>
</div>
<div class="hr hr32 hr-dotted"></div>
{% endblock %}
|
norn/bustime
|
backoffice/templates/backoffice/bdata3.html
|
HTML
|
mit
| 1,060
|
from graphics_module.objects import *
import numpy as np
def make_pixels_array_basic(amount):
return np.full(10,Pixel(), dtype=np.object)
def make_pixels_array_config_based(config):
if config.colorscheme == "b&w":
c = Color()
elif config.colorscheme == "light":
c = Color(r=245,g=235,b=234,a=0.85) #"light" or whatever to be slightly colorized dots
if config.aplha == True:
lol = 4 #random influenced aplha
#and so on
def get_color(config):
if not config:#has attribute "lower_limit": I don't know
lower_limit = 230
|
sindresf/The-Playground
|
Python/Machine Learning/LSTM Music Visualizer/LSTM Music Visualizer/graphics_module/initialization.py
|
Python
|
mit
| 576
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Coq bench</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.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">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<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="../../..">Unstable</a></li>
<li><a href=".">8.4.dev / contrib:color dev</a></li>
<li class="active"><a href="">2015-01-07 03:53:32</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="../../../../../about.html">About</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href=".">« Up</a>
<h1>
contrib:color
<small>
dev
<span class="label label-info">Not compatible with this Coq</span>
</small>
</h1>
<p><em><script>document.write(moment("2015-01-07 03:53:32 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2015-01-07 03:53:32 UTC)</em><p>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>ruby lint.rb unstable ../unstable/packages/coq:contrib:color/coq:contrib:color.dev</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
<dt>Output</dt>
<dd><pre>The package is valid.
</pre></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 --dry-run coq:contrib:color.dev coq.8.4.dev</code></dd>
<dt>Return code</dt>
<dd>768</dd>
<dt>Duration</dt>
<dd>0 s</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.4.dev).
The following dependencies couldn't be met:
- coq:contrib:color -> coq >= dev
Your request can't be satisfied:
- Conflicting version constraints for coq
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq, to test if the problem was incompatibility with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --dry-run coq:contrib:color.dev</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>3 s</dd>
<dt>Output</dt>
<dd><pre>The following actions will be performed:
- remove coq.8.4.dev
=== 1 to remove ===
=-=- Removing Packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Removing coq.8.4.dev.
[WARNING] Directory /home/bench/.opam/system/lib/coq is not empty, not removing
[WARNING] Directory /home/bench/.opam/system/share/coq is not empty, not removing
The following actions will be performed:
- install coq.hott [required by coq:contrib:color]
- install coq:contrib:color.dev
=== 2 to install ===
=-=- Synchronizing package archives -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
=-=- Installing packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Building coq.hott:
./configure -configdir /home/bench/.opam/system/lib/coq/config -mandir /home/bench/.opam/system/man -docdir /home/bench/.opam/system/doc -prefix /home/bench/.opam/system -usecamlp5 -camlp5dir /home/bench/.opam/system/lib/camlp5 -coqide no
make -j4
make install
Installing coq.hott.
Building coq:contrib:color.dev:
coq_makefile -f Make -o Makefile
make -j4
make install
Installing coq:contrib:color.dev.
</pre></dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</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">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</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-old
|
clean/Linux-x86_64-4.01.0-1.2.0/unstable/8.4.dev/contrib:color/dev/2015-01-07_03-53-32.html
|
HTML
|
mit
| 6,890
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Nate Coraor <nate@coraor.org>
#
# This file is part of Ansible
#
# Ansible 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 3 of the License, or
# (at your option) any later version.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
#
DOCUMENTATION = '''
---
module: zfs_permissions
short_description: Manage zfs administrative permissions
description:
- Manages ZFS file system administrative permissions on Solaris and FreeBSD. See zfs(1M) for more information about the properties.
version_added: "1.10"
options:
name:
description:
- File system or volume name e.g. C(rpool/myfs)
required: true
state:
description:
- Whether to allow (C(present)), or unallow (C(absent)) a permission.
required: true
choices: [present, absent]
users:
description:
- Users to whom permission(s) should be granted, separated by commas.
required: false
groups:
description:
- Groups to whom permission(s) should be granted, separated by commas.
required: false
everyone:
description:
- Apply permissions to everyone.
required: false
default: false
choices: ['on','off']
permissions:
description:
- The permission(s) to delegate, separated by commas (required if C(state) is C(present))
required: false
choices: ['allow','clone','create','destroy',...]
local:
description:
- Apply permissions to C(name) "locally" (C(zfs allow -l))
required: false
default: null
choices: ['on','off']
descendents:
description:
- Apply permissions to C(name)'s descendents (C(zfs allow -d))
required: false
default: null
choices: ['on','off']
recursive:
description:
- Unallow permissions recursively (ignored when C(state) is C(present))
required: false
default: false
choices: ['on','off']
author: "Nate Coraor (@natefoo)"
'''
EXAMPLES = '''
# Grant `zfs allow` and `unallow` permission to the `adm` user with local+descendents scope
- zfs_permissions: name=rpool/myfs users=adm permissions=allow,unallow
# Grant `zfs send` to everyone, plus the group `backup`
- zfs_permissions: name=rpool/myvol groups=backup everyone=yes permissions=send
# Grant `zfs send,receive` to users `foo` and `bar` with local scope only
- zfs_permissions: name=rpool/myfs users=foo,bar permissions=send,receive local=yes
# Revoke all permissions from everyone (permissions specifically assigned to users and groups remain)
- zfs_permissions: name=rpool/myfs state=absent everyone=yes
'''
import sys
class ZfsPermissions(object):
def __init__(self, module):
self.module = module
self.name = module.params.get('name')
self.state = module.params.get('state')
self.users = module.params.get('users') or []
self.groups = module.params.get('groups') or []
self.everyone = module.boolean(module.params.get('everyone'))
self.perms = module.params.get('permissions') or []
self.recursive = module.boolean(module.params.get('recursive'))
self.scope = None
self.changed = False
self.__current_perms = None
if self.state == 'present' and not self.perms:
self.module.fail_json(msg='The `permissions` option is required for state=present')
if self.state == 'present' and not (self.users or self.groups or self.everyone):
self.module.fail_json(msg='One of `users`, `groups`, or `everyone` must be set')
for splittable in ('users', 'groups', 'perms'):
if getattr(self, splittable):
setattr(self, splittable, getattr(self, splittable).split(','))
local = module.boolean(module.params.get('local'))
descendents = module.boolean(module.params.get('descendents'))
if (local and descendents) or (not local and not descendents):
self.scope = 'ld'
elif local:
self.scope = 'l'
elif descendents:
self.scope = 'd'
else:
self.module.fail_json(msg='Impossible value for local and descendents')
self.subcommand = 'allow'
self.recursive_opt = []
if self.state == 'absent':
self.subcommand = 'unallow'
if self.recursive:
self.recursive_opt = ['-r']
else:
self.recursive_opt = []
self.run()
@property
def current_perms(self):
if self.__current_perms is None:
rc, out, err = self.run_command(['zfs', 'allow', self.name])
if rc:
self.module.fail_json(msg='Getting permissions for %s failed: %s' % (self.name, err))
perms = dict(l = dict(u=dict(), g=dict(), e=[]),
d = dict(u=dict(), g=dict(), e=[]),
ld = dict(u=dict(), g=dict(), e=[]))
reading = None
for line in out.splitlines():
if line == 'Local permissions:':
reading = 'l'
elif line == 'Descendent permissions:':
reading = 'd'
elif line == 'Local+Descendent permissions:':
reading = 'ld'
elif line.startswith('\tuser '):
user, cur_perms = line.split()[1:3]
perms[reading]['u'][user] = cur_perms.split(',')
elif line.startswith('\tgroup '):
group, cur_perms = line.split()[1:3]
perms[reading]['g'][group] = cur_perms.split(',')
elif line.startswith('\teveryone '):
perms[reading]['e'] = line.split()[1].split(',')
self.__current_perms = perms
return self.__current_perms
def run_command(self, cmd):
progname = cmd[0]
cmd[0] = self.module.get_bin_path(progname, True)
return self.module.run_command(cmd)
def change_required(self, ent_type):
# zfs allow/unallow are idempotent, so we only need to do this for Ansible's changed flag
rval = []
if ent_type == 'u':
entities = self.users
elif ent_type == 'g':
entities = self.groups
for ent in entities:
ent_perms = self.current_perms[self.scope][ent_type].get(ent, None)
if self.state == 'present' and ent_perms is None:
rval.append(ent)
elif self.state == 'absent' and ent_perms is not None:
rval.append(ent)
elif ent_perms is not None:
for perm in self.perms:
if ((self.state == 'present' and perm not in ent_perms) or
(self.state == 'absent' and perm in ent_perms)):
# at least one desired permission is absent, or
# at least one undesired permission is present
rval.append(ent)
break
return rval
def run(self):
def run_cmd(args):
cmd = ['zfs', self.subcommand] + self.recursive_opt + ['-%s' % self.scope] + args
if self.perms:
cmd = cmd + [','.join(self.perms)]
cmd = cmd + [self.name]
if self.module.check_mode:
return 'Check mode skipped execution of: %s' % ' '.join(cmd)
rc, out, err = self.run_command(cmd)
if rc:
msg = 'Changing permissions with `%s` failed: %s' % (' '.join(cmd), err)
self.module.fail_json(msg=msg)
return out
stdout = ''
for ent_type in ('u', 'g'):
change = self.change_required(ent_type)
if change:
args = ['-%s' % ent_type, ','.join(change)]
stdout += run_cmd(args)
self.changed = True
if self.everyone:
everyone_perms = self.current_perms[self.scope]['e']
if self.state == 'absent' and not self.perms and everyone_perms:
args = ['-e']
stdout += run_cmd(args)
self.changed = True
for perm in self.perms:
if ((self.state == 'present' and perm not in everyone_perms) or
(self.state == 'absent' and perm in everyone_perms)):
#
args = ['-e']
stdout += run_cmd(args)
self.changed = True
break
exit_args = dict(changed=self.changed, state=self.state)
if self.changed:
exit_args.update(msg='ZFS permissions updated', stdout=stdout)
self.module.exit_json(**exit_args)
def main():
module = AnsibleModule(
argument_spec = dict(
name = dict(required=True),
state = dict(default="present", choices=["absent", "present"]),
users = dict(default=None),
groups = dict(default=None),
everyone = dict(default=False, choices=BOOLEANS),
permissions = dict(default=None),
local = dict(default=None, choices=BOOLEANS),
descendents = dict(default=None, choices=BOOLEANS),
recursive = dict(default=False, choices=BOOLEANS)
),
supports_check_mode = True
)
zfs_permissions = ZfsPermissions(module)
sys.exit(0)
# import module snippets
from ansible.module_utils.basic import *
if __name__ == '__main__':
main()
|
martenson/ansible-common-roles
|
paths/library/zfs_permissions.py
|
Python
|
mit
| 9,934
|
/**
* Title: Art
* Author: Victor Cueva Llanos
* Email: Ingvcueva@gmail.com
**/
#include <bits/stdc++.h>
#define MOD 1000000007
#define MAXN 100005
using namespace std;
int N[MAXN];
int main(int nargs, char **args) {
// clock_t _inicio = clock();
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> N[i];
}
bool ok = false;
for (int i = 2; i < n && !ok; i++) {
ok = (N[i] == N[i-1] && N[i-1] == N[i-2]);
}
puts(ok?"Yes":"No");
}
// printf("Time elapsed: %ld ms\n", (clock() - _inicio)/1000);
return 0;
}
|
Victoralin10/ACMSolutions
|
codechef/SNCKPA16/MAKEART.cpp
|
C++
|
mit
| 693
|
//
// Copyright (c) 2009 Ivan Zlatev <ivan@ivanz.com>
//
// Authors:
// Ivan Zlatev <ivan@ivanz.com>
//
// License: MIT/X11 - See LICENSE.txt
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace PicasaUploader
{
public partial class DuplicateActionDialog : Form
{
public DuplicateActionDialog ()
{
InitializeComponent ();
_formatString = textLabel.Text;
_action = DuplicateAction.Cancel;
}
private DuplicateAction _action;
private readonly string _formatString;
public void ShowDialog (string photoTitle, string albumTitle)
{
textLabel.Text = String.Format (_formatString, photoTitle, albumTitle);
_action = DuplicateAction.Cancel;
base.ShowDialog();
}
public DuplicateAction DuplicateAction
{
get { return _action; }
}
private void uploadAllButton_Click (object sender, EventArgs e)
{
_action = DuplicateAction.UploadAll;
this.Close ();
}
private void uploadButton_Click (object sender, EventArgs e)
{
_action = DuplicateAction.Upload;
this.Close ();
}
private void skipAllButton_Click (object sender, EventArgs e)
{
_action = DuplicateAction.SkipAll;
this.Close ();
}
private void skipButton_Click (object sender, EventArgs e)
{
_action = DuplicateAction.Skip;
this.Close ();
}
private void replaceAllButton_Click (object sender, EventArgs e)
{
_action = DuplicateAction.ReplaceAll;
this.Close ();
}
private void replaceButton_Click (object sender, EventArgs e)
{
_action = DuplicateAction.Replace;
this.Close ();
}
}
}
|
ivanz/PicasaUploader
|
PicasaUploader/UI/Dialogs/DuplicateActionDialog.cs
|
C#
|
mit
| 2,133
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\Templating\Helper\Fixtures;
use Symfony\Component\Templating\TemplateNameParserInterface;
use Symfony\Component\Templating\TemplateReference;
class StubTemplateNameParser implements TemplateNameParserInterface {
private $root;
private $rootTheme;
public function __construct($root, $rootTheme) {
$this->root = $root;
$this->rootTheme = $rootTheme;
}
public function parse($name) {
list($bundle, $controller, $template) = explode(':', $name);
if ($template[0] == '_') {
$path = $this->rootTheme . '/Custom/' . $template;
} elseif ($bundle === 'TestBundle') {
$path = $this->rootTheme . '/' . $controller . '/' . $template;
} else {
$path = $this->root . '/' . $controller . '/' . $template;
}
return new TemplateReference($path, 'php');
}
}
|
flyingfeet/FlyingFeet
|
vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Fixtures/StubTemplateNameParser.php
|
PHP
|
mit
| 1,063
|
'use strict';
/* jshint ignore:start */
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
/* jshint ignore:end */
var _ = require('lodash'); /* jshint ignore:line */
var Holodeck = require('../../../../../holodeck'); /* jshint ignore:line */
var Request = require(
'../../../../../../../lib/http/request'); /* jshint ignore:line */
var Response = require(
'../../../../../../../lib/http/response'); /* jshint ignore:line */
var RestException = require(
'../../../../../../../lib/base/RestException'); /* jshint ignore:line */
var Twilio = require('../../../../../../../lib'); /* jshint ignore:line */
var serialize = require(
'../../../../../../../lib/base/serialize'); /* jshint ignore:line */
var client;
var holodeck;
describe('SyncMapItem', function() {
beforeEach(function() {
holodeck = new Holodeck();
client = new Twilio('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'AUTHTOKEN', {
httpClient: holodeck
});
});
it('should generate valid fetch request',
function() {
holodeck.mock(new Response(500, '{}'));
var promise = client.preview.sync.services('ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMaps('MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMapItems('key').fetch();
promise = promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
});
promise.done();
var solution = {
serviceSid: 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
mapSid: 'MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
key: 'key'
};
var url = _.template('https://preview.twilio.com/Sync/Services/<%= serviceSid %>/Maps/<%= mapSid %>/Items/<%= key %>')(solution);
holodeck.assertHasRequest(new Request({
method: 'GET',
url: url
}));
}
);
it('should generate valid fetch response',
function() {
var body = JSON.stringify({
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'created_by': 'created_by',
'data': {},
'date_created': '2015-07-30T20:00:00Z',
'date_updated': '2015-07-30T20:00:00Z',
'key': 'key',
'map_sid': 'MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'revision': 'revision',
'service_sid': 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'url': 'https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items/key'
});
holodeck.mock(new Response(200, body));
var promise = client.preview.sync.services('ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMaps('MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMapItems('key').fetch();
promise = promise.then(function(response) {
expect(response).toBeDefined();
}, function() {
throw new Error('failed');
});
promise.done();
}
);
it('should generate valid remove request',
function() {
holodeck.mock(new Response(500, '{}'));
var promise = client.preview.sync.services('ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMaps('MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMapItems('key').remove();
promise = promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
});
promise.done();
var solution = {
serviceSid: 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
mapSid: 'MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
key: 'key'
};
var url = _.template('https://preview.twilio.com/Sync/Services/<%= serviceSid %>/Maps/<%= mapSid %>/Items/<%= key %>')(solution);
holodeck.assertHasRequest(new Request({
method: 'DELETE',
url: url
}));
}
);
it('should generate valid delete response',
function() {
var body = JSON.stringify(null);
holodeck.mock(new Response(204, body));
var promise = client.preview.sync.services('ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMaps('MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMapItems('key').remove();
promise = promise.then(function(response) {
expect(response).toBe(true);
}, function() {
throw new Error('failed');
});
promise.done();
}
);
it('should generate valid create request',
function() {
holodeck.mock(new Response(500, '{}'));
var opts = {
key: 'key',
data: '{}'
};
var promise = client.preview.sync.services('ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMaps('MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMapItems.create(opts);
promise = promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
});
promise.done();
var solution = {
serviceSid: 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
mapSid: 'MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
};
var url = _.template('https://preview.twilio.com/Sync/Services/<%= serviceSid %>/Maps/<%= mapSid %>/Items')(solution);
var values = {
Key: 'key',
Data: serialize.object('{}'),
};
holodeck.assertHasRequest(new Request({
method: 'POST',
url: url,
data: values
}));
}
);
it('should generate valid create response',
function() {
var body = JSON.stringify({
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'created_by': 'created_by',
'data': {},
'date_created': '2015-07-30T20:00:00Z',
'date_updated': '2015-07-30T20:00:00Z',
'key': 'key',
'map_sid': 'MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'revision': 'revision',
'service_sid': 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'url': 'https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items/key'
});
holodeck.mock(new Response(201, body));
var opts = {
key: 'key',
data: '{}'
};
var promise = client.preview.sync.services('ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMaps('MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMapItems.create(opts);
promise = promise.then(function(response) {
expect(response).toBeDefined();
}, function() {
throw new Error('failed');
});
promise.done();
}
);
it('should generate valid list request',
function() {
holodeck.mock(new Response(500, '{}'));
var promise = client.preview.sync.services('ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMaps('MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMapItems.list();
promise = promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
});
promise.done();
var solution = {
serviceSid: 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
mapSid: 'MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
};
var url = _.template('https://preview.twilio.com/Sync/Services/<%= serviceSid %>/Maps/<%= mapSid %>/Items')(solution);
holodeck.assertHasRequest(new Request({
method: 'GET',
url: url
}));
}
);
it('should generate valid read_empty response',
function() {
var body = JSON.stringify({
'items': [],
'meta': {
'first_page_url': 'https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items?PageSize=50&Page=0',
'key': 'items',
'next_page_url': null,
'page': 0,
'page_size': 50,
'previous_page_url': null,
'url': 'https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items?PageSize=50&Page=0'
}
});
holodeck.mock(new Response(200, body));
var promise = client.preview.sync.services('ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMaps('MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMapItems.list();
promise = promise.then(function(response) {
expect(response).toBeDefined();
}, function() {
throw new Error('failed');
});
promise.done();
}
);
it('should generate valid read_full response',
function() {
var body = JSON.stringify({
'items': [
{
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'created_by': 'created_by',
'data': {},
'date_created': '2015-07-30T20:00:00Z',
'date_updated': '2015-07-30T20:00:00Z',
'key': 'key',
'map_sid': 'MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'revision': 'revision',
'service_sid': 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'url': 'https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items/key'
}
],
'meta': {
'first_page_url': 'https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items?PageSize=50&Page=0',
'key': 'items',
'next_page_url': null,
'page': 0,
'page_size': 50,
'previous_page_url': null,
'url': 'https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items?PageSize=50&Page=0'
}
});
holodeck.mock(new Response(200, body));
var promise = client.preview.sync.services('ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMaps('MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMapItems.list();
promise = promise.then(function(response) {
expect(response).toBeDefined();
}, function() {
throw new Error('failed');
});
promise.done();
}
);
it('should generate valid update request',
function() {
holodeck.mock(new Response(500, '{}'));
var opts = {
data: '{}'
};
var promise = client.preview.sync.services('ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMaps('MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMapItems('key').update(opts);
promise = promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
});
promise.done();
var solution = {
serviceSid: 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
mapSid: 'MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
key: 'key'
};
var url = _.template('https://preview.twilio.com/Sync/Services/<%= serviceSid %>/Maps/<%= mapSid %>/Items/<%= key %>')(solution);
var values = {
Data: serialize.object('{}'),
};
holodeck.assertHasRequest(new Request({
method: 'POST',
url: url,
data: values
}));
}
);
it('should generate valid update response',
function() {
var body = JSON.stringify({
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'created_by': 'created_by',
'data': {},
'date_created': '2015-07-30T20:00:00Z',
'date_updated': '2015-07-30T20:00:00Z',
'key': 'key',
'map_sid': 'MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'revision': 'revision',
'service_sid': 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'url': 'https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items/key'
});
holodeck.mock(new Response(200, body));
var opts = {
data: '{}'
};
var promise = client.preview.sync.services('ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMaps('MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
.syncMapItems('key').update(opts);
promise = promise.then(function(response) {
expect(response).toBeDefined();
}, function() {
throw new Error('failed');
});
promise.done();
}
);
});
|
wanjunsli/twilio-node
|
spec/integration/rest/preview/sync/service/syncMap/syncMapItem.spec.js
|
JavaScript
|
mit
| 13,231
|
Imports System
Imports System.Reflection
Imports 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.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("Triple A Number")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("University of Hartford")>
<Assembly: AssemblyProduct("Triple A Number")>
<Assembly: AssemblyCopyright("Copyright © University of Hartford 2013")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("602e2fbf-9bea-4e66-9459-7f08f512a310")>
' 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")>
|
patkub/visual-basic-intro
|
Triple A Number/Triple A Number/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,192
|
/*!
@file
@brief Header file
@author Philip Pavo
Contains classes for working with VK API
*/
#include <string>
#include <map>
#include <vector>
#include "jsoncpp/json/json.h"
#ifndef VKLIB_H
#define VKLIB_H
using namespace std;
/**
@brief Main namespace
@author Philip Pavo
*/
namespace VK{
/**
@brief Root class for all VK models
*/
class Model{
public:
Model parse();
};
/**
A City class describes a city.
*/
class City: public Model{
public:
int id;
string title;
int getId();
static City parse(Json::Value);
};
/**
A Country class describes a country.
*/
class Country: public Model{
public:
int id;
string title;
int getId();
static Country parse(Json::Value);
};
/**
A Education class describes a education of user
*/
class Education: public Model{
public:
int university;
string university_name;
int faculty;
string faculty_name;
int graduation;
/**
Parse Education object from Json Value object
@param json Json Value Object
@return Education object
*/
static Education parse(Json::Value json);
};
/**
A University class describes a university
*/
class University: public Model{
public:
int id;
int country;
int city;
string name;
int faculty;
string faculty_name;
int chair;
string chair_name;
int graduation;
/**
Parse University object from Json Value object
@param json Json Value Object
@return University object
*/
static University parse(Json::Value json);
};
/**
A School class describes a school
*/
class School: public Model{
public:
int id;
int country;
int city;
string name;
int year_from;
int year_to;
int year_graduated;
string class_l;
string speciality;
int type;
string type_str;
/**
Parse School object from Json Value object
@param json Json Value Object
@return School object
*/
static School parse(Json::Value json);
};
/**
A User class describes a user.
*/
class User: public Model{
public:
string first_name;
string last_name;
bool online;
bool online_mobile;
string photo_50;
string photo_100;
string photo_200;
/**
Parse user from Json Value Object
@param json Json Value Object
@return User object
*/
static User parse(Json::Value json);
private:
};
class UserFull: public User{
private:
/**
A Sex class describes a sex field
*/
class Sex{
public:
const int MALE = 2;
const int FEMALE = 1;
};
/**
A Contacts class describes a contacts field
*/
class Contacts: public Model{
public:
string mobile_phone;
string home_phone;
static UserFull::Contacts parse(Json::Value);
};
/**
A Occupation class describes a information about the current occupation user
*/
class Occupation: public Model{
public:
const string TYPE_WORK = "work";
const string TYPE_SCHOOL = "school";
const string TYPE_UNIVERSITY = "university";
string type;
int id;
string name;
};
class Relation{
public:
const int SINGLE = 1;
const int RELATIONSHIP = 2;
const int ENGAGED = 3;
const int MARRIED = 4;
const int COMPLICATED = 5;
const int SEARCHING = 6;
const int IN_LOVE = 7;
};
class Attitude{
public:
const int VERY_NEGATIVE = 1;
const int NEGATIVE = 2;
const int COMPROMISABLE = 3;
const int NEUTRAL = 4;
const int POSITIVE = 5;
};
class Political{
public:
const int COMMUNNIST = 1;
const int SOCIALIST = 2;
const int CENTRIST = 3;
const int LIBERAL = 4;
const int CONSERVATIVE = 5;
const int MONARCHIST = 6;
const int ULTRACONSERVATIVE = 7;
const int LIBERTARIAN = 8;
const int APATHETIC = 9;
};
class LifeMain{
const int FAMILY_AND_CHILDREN = 1;
const int CAREER_AND_MONEY = 2;
const int ENTERTAINMENT_AND_LEISURE = 3;
const int SCIENCE_AND_RESEARCH = 4;
const int IMPROOVING_THE_WORLD = 5;
const int PERSONAL_DEVELOPMENT = 6;
const int BEAUTY_AND_ART = 7;
const int FAME_AND_INFLUENCE = 8;
};
class PeopleMain{
const int INTELLECT_AND_CREATIVITY = 1;
const int KINDNESS_AND_HONESTLY = 2;
const int HEALTH_AND_BEAUTY = 3;
const int WEALTH_AND_POWER = 4;
const int COURAGE_AND_PERSISTENCE = 5;
const int HUMOR_AND_LOVE_FOR_LIFE = 6;
};
class RelativeType{
const string PARTNER = "partner";
const string GRANDCHILD = "grandchild";
const string GRANDPARENT = "grandparent";
const string CHILD = "child";
const string SUBLING = "sibling";
const string PARENT = "parent";
};
public:
/**
A Seen class describes a user seen (Time & Platform)
*/
class Seen: public Model{
public:
static const int PLATFORM_MOBILE = 1;
static const int PLATFORM_IPHONE = 2;
static const int PLATFORM_IPAD = 3;
static const int PLATFORM_ANDROID = 4;
static const int PLATFORM_WPHONE = 5;
static const int PLATFORM_WINDOWS = 6;
static const int PLATFORM_WEB = 7;
long long int time;
int platform;
static string getPlatformName(int platform);
static UserFull::Seen parse(Json::Value);
};
string photo_id;
bool verified;
bool blacklisted;
int sex;
string bdate;
City city;
Country country;
string home_town;
string list;
string domain;
bool has_mobile;
UserFull::Contacts contacts;
string site;
Education education;
vector<University> universities;
vector<School> schools;
string status;
UserFull::Seen last_seen;
int followers_count;
int common_count;
map<string, int> counters;
UserFull::Occupation occupation;
string nickname;
//relaives
int relation;
//personal
//connections
//exports
bool wall_comments;
string activities;
string interests;
string music;
string movies;
string tv;
string books;
string games;
string about;
string quotes;
bool can_post;
bool can_see_all_posts;
bool can_see_audio;
bool can_write_private_message;
bool can_send_friend_request;
bool is_favorite;
int timezone;
string screen_name;
string maiden_name;
//crop_photo
bool is_friend;
int friend_status;
/**
Parse user from Json Value Object
@param json Json Value Object
@return UserFull object
*/
static UserFull parse(Json::Value);
};
class Utils{
public:
static string data2str(map<string, string>);
static string urlencode(const string &c);
static string char2hex(char);
static int CURL_WRITER(char *data, size_t size, size_t nmemb, string *buffer);
};
class Parameters: public map<string, string>{
public:
//Commons
static const string USER_ID;
static const string USER_IDS;
static const string FIELDS;
static const string SORT;
static const string OFFSET;
static const string COUNT;
static const string OWNER_ID;
//auth
static const string VERSION;
static const string HTTPS;
static const string LANG;
static const string ACCESS_TOKEN;
static const string SIG;
//get users
static const string NAME_CASE;
//Get subscriptions
static const string EXTENDED;
//Search
static const string Q;
static const string CITY;
static const string COUNTRY;
static const string HOMETOWN;
static const string UNIVERSITY_COUNTRY;
static const string UNIVERSITY;
static const string UNIVERSITY_YEAR;
static const string SEX;
static const string STATUS;
static const string AGE_FROM;
static const string AGE_TO;
static const string BIRTH_DAY;
static const string BIRTH_MONTH;
static const string BIRTH_YEAR;
static const string ONLINE;
static const string HAS_PHOTO;
static const string SCHOOL_COUNTRY;
static const string SCHOOL_CITY;
static const string SCHOOL;
static const string SCHOOL_YEAR;
static const string RELIGION;
static const string INTERESTS;
static const string COMPANY;
static const string POSITION;
static const string GROUP_ID;
static const string FRIENDS_ONLY;
static const string FROM_GROUP;
static const string MESSAGE;
static const string ATTACHMENTS;
static const string SERVICES;
static const string SIGNED;
static const string PUBLISH_DATE;
static const string LAT;
static const string LONG;
static const string PLACE_ID;
static const string POST_ID;
//Errors
static const string ERROR_CODE;
static const string ERROR_MSG;
static const string REQUEST_PARAMS;
//Captcha
static const string CAPTCHA_IMG;
static const string CAPTCHA_SID;
static const string CAPTCHA_KEY;
static const string REDIRECT_URI;
//Photos
static const string PHOTO;
static const string PHOTOS;
static const string ALBUM_ID;
static const string PHOTO_IDS;
static const string PHOTO_SIZES;
static const string REV;
static const string FEED_TYPE;
static const string FEED;
Parameters();
//Parameters(map<string, string> data);
string join(string...);
};
class UsersList: public Model{
public:
vector<UserFull> list;
UsersList(vector<VK::UserFull> users);
UsersList(Json::Value json);
vector<UserFull> toVector();
static vector<UserFull> parse(Json::Value json);
};
class Response{
public:
};
/**
@brief API class
*/
class API{
public:
static string api_url;
string access_token;
int user_id;
string version;
string lang;
string https;
/**
API constructor
@param version Api version
@param lang Api language
@param https Api requests via https
@param access_token Access token for requests
*/
API(string version, string lang, bool https, string access_token);
/**
HTTP Post request
@param url request url
@param data data string
@return json string
*/
static string post(string url, string data);
/**
HTTP Post request
@param url method name
@param data map of data
@return json Json Value Object
*/
Json::Value call(string method, map<string, string> params);
UsersList usersGet(map<string, string> params);
vector<UserFull> usersSearch(map<string, string> params);
bool usersIsAppUser(map<string, string> params);
vector<UserFull> usersGetSubscriptions(map<string, string> params);
vector<UserFull> usersGetFollowers(map<string, string> params);
vector<UserFull> usersReport(int user_id, string type, map<string, string> params);
vector<UserFull> usersGetNearby(double latitude, double longitude, map<string, string> params);
private:
};
}
#endif
|
PhilipPavo/CPP-VK-lib
|
src/vklib.h
|
C
|
mit
| 11,312
|
<!-- 来必力City版安装代码 -->
<div id="lv-container" data-id="city" data-uid="MTAyMC80MDcxOC8xNzI0NA==">
<script type="text/javascript">
(function(d, s) {
var j, e = d.getElementsByTagName(s)[0];
if (typeof LivereTower === 'function') { return; }
j = d.createElement(s);
j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
j.async = true;
e.parentNode.insertBefore(j, e);
})(document, 'script');
</script>
<noscript> 为正常使用来必力评论功能请激活JavaScript</noscript>
</div>
<!-- City版安装代码已完成 -->
|
linexjlin/linexjlin.github.io
|
_includes/livere.html
|
HTML
|
mit
| 594
|
import java.io.File;
import java.nio.file.Files;
import java.util.*;
public class P08NestedFolders {
public static void main(String[] args) {
String path = "C:\\Exercises\\JavaAdvanced\\08.Resources\\Files-and-Streams";
File root = new File(path);
Deque<File> directories = new ArrayDeque<>();
List<String> allDirNames = new LinkedList<>();
if (root.exists()) {
directories.addLast(root);
} else {
System.out.println(path + " directory does not exist.");
return;
}
int dirCounter = 0;
while (!directories.isEmpty()) {
File currentDir = directories.pollFirst();
if (currentDir.isDirectory()) {
allDirNames.add(currentDir.getName());
dirCounter++;
for (File dir : currentDir.listFiles()) {
if (dir.isDirectory()) {
directories.addLast(dir);
}
}
}
}
allDirNames.stream().forEach(d -> System.out.println(d));
System.out.println(dirCounter + " folders");
}
}
|
Jovtcho/JavaFundamentals
|
Java Advanced/08.Fiels-and-Streams-Lab/P08NestedFolders.java
|
Java
|
mit
| 1,165
|
package br.edu.utfpr.recipes.dao;
import br.edu.utfpr.recipes.entidade.Usuario;
import org.hibernate.Query;
public class DaoUsuario extends DaoGenerics<Usuario> {
public DaoUsuario() {
super.clazz = Usuario.class;
}
public Usuario buscaUsuarioPorEmail(String email) {
session = HibernateConfiguration.getSessionFactory().openSession();
Query query = session.createQuery(
"From " + clazz.getSimpleName() + " where email =:email ");
Usuario usuario = (Usuario) query.setParameter("email", email).uniqueResult();
return usuario;
}
}
|
mairieli/recipes-pi
|
src/main/java/br/edu/utfpr/recipes/dao/DaoUsuario.java
|
Java
|
mit
| 614
|
package com.miraclewong.systemwidget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class TopBar extends RelativeLayout {
// 包含topbar上的元素:左按钮、右按钮、标题
private Button mLeftButton, mRightButton;
private TextView mTitleView;
// 布局属性,用来控制组件元素在ViewGroup中的位置
private LayoutParams mLeftParams, mTitlepParams, mRightParams;
// 左按钮的属性值,即我们在atts.xml文件中定义的属性
private int mLeftTextColor;
private Drawable mLeftBackground;
private String mLeftText;
// 右按钮的属性值,即我们在atts.xml文件中定义的属性
private int mRightTextColor;
private Drawable mRightBackground;
private String mRightText;
// 标题的属性值,即我们在atts.xml文件中定义的属性
private float mTitleTextSize;
private int mTitleTextColor;
private String mTitle;
// 映射传入的接口对象
private topbarClickListener mListener;
public TopBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public TopBar(Context context) {
super(context);
}
public TopBar(Context context, AttributeSet attrs) {
super(context, attrs);
// 设置topbar的背景
setBackgroundColor(0xFFF59563);
// 通过这个方法,将你在atts.xml中定义的declare-styleable
// 的所有属性的值存储到TypedArray中
TypedArray ta = context.obtainStyledAttributes(attrs,
R.styleable.TopBar);
// 从TypedArray中取出对应的值来为要设置的属性赋值
mLeftTextColor = ta.getColor(
R.styleable.TopBar_leftTextColor, 0);
mLeftBackground = ta.getDrawable(
R.styleable.TopBar_leftBackground);
mLeftText = ta.getString(R.styleable.TopBar_leftText);
mRightTextColor = ta.getColor(
R.styleable.TopBar_rightTextColor, 0);
mRightBackground = ta.getDrawable(
R.styleable.TopBar_rightBackground);
mRightText = ta.getString(R.styleable.TopBar_rightText);
mTitleTextSize = ta.getDimension(
R.styleable.TopBar_titleTextSize, 10);
mTitleTextColor = ta.getColor(
R.styleable.TopBar_titleTextColor, 0);
mTitle = ta.getString(R.styleable.TopBar_title);
// 获取完TypedArray的值后,一般要调用
// recyle方法来避免重新创建的时候的错误
ta.recycle();
mLeftButton = new Button(context);
mRightButton = new Button(context);
mTitleView = new TextView(context);
// 为创建的组件元素赋值
// 值就来源于我们在引用的xml文件中给对应属性的赋值
mLeftButton.setTextColor(mLeftTextColor);
mLeftButton.setBackground(mLeftBackground);
mLeftButton.setText(mLeftText);
mRightButton.setTextColor(mRightTextColor);
mRightButton.setBackground(mRightBackground);
mRightButton.setText(mRightText);
mTitleView.setText(mTitle);
mTitleView.setTextColor(mTitleTextColor);
mTitleView.setTextSize(mTitleTextSize);
mTitleView.setGravity(Gravity.CENTER);
// 为组件元素设置相应的布局元素
mLeftParams = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.MATCH_PARENT);
mLeftParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, TRUE);
// 添加到ViewGroup
addView(mLeftButton, mLeftParams);
mRightParams = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.MATCH_PARENT);
mRightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE);
addView(mRightButton, mRightParams);
mTitlepParams = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.MATCH_PARENT);
mTitlepParams.addRule(RelativeLayout.CENTER_IN_PARENT, TRUE);
addView(mTitleView, mTitlepParams);
// 按钮的点击事件,不需要具体的实现,
// 只需调用接口的方法,回调的时候,会有具体的实现
mRightButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mListener.rightClick();
}
});
mLeftButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mListener.leftClick();
}
});
}
// 暴露一个方法给调用者来注册接口回调
// 通过接口来获得回调者对接口方法的实现
public void setOnTopbarClickListener(topbarClickListener mListener) {
this.mListener = mListener;
}
/**
* 设置按钮的显示与否 通过id区分按钮,flag区分是否显示
*
* @param id id
* @param flag 是否显示
*/
public void setButtonVisable(int id, boolean flag) {
if (flag) {
if (id == 0) {
mLeftButton.setVisibility(View.VISIBLE);
} else {
mRightButton.setVisibility(View.VISIBLE);
}
} else {
if (id == 0) {
mLeftButton.setVisibility(View.GONE);
} else {
mRightButton.setVisibility(View.GONE);
}
}
}
// 接口对象,实现回调机制,在回调方法中
// 通过映射的接口对象调用接口中的方法
// 而不用去考虑如何实现,具体的实现由调用者去创建
public interface topbarClickListener {
// 左按钮点击事件
void leftClick();
// 右按钮点击事件
void rightClick();
}
}
|
MiracleWong/AndroidHeros
|
systemwidget/src/main/java/com/miraclewong/systemwidget/TopBar.java
|
Java
|
mit
| 6,137
|
<!--body content start-->
<!--about audrey -->
<section id= "about-audrey"class="body-content gray-bg" >
<div class="container">
<div class="row page-content">
<div class="post-list-aside">
<div class="post-single">
<div class="col-md-6">
<div class="post-slider post-img text-center">
<ul class="slides">
<li data-thumb="/static/img/post/post-pic1.jpg">
<a href="javascript:;" title="Freshness Photo">
<img src="/static/img/post/post-pic1.jpg" alt="">
</a>
</li>
<li data-thumb="/static/img/post/post-pic2.jpg">
<a href="javascript:;" title="Awesome Lightbox">
<img src="/static/img/post/post-pic2.jpg" alt="">
</a>
</li>
<li data-thumb="/static/img/post/post-pic3.png">
<a href="javascript:;" title="Massive UI Components">
<img src="/static/img/post/post-pic3.png" alt="">
</a>
</li>
<li data-thumb="/static/img/post/post-pic4.jpg">
<a href="javascript:;" title="Massive UI Components">
<img src="/static/img/post/post-pic4.jpg" alt="">
</a>
</li>
</ul>
</div>
</div>
<div class="col-md-6">
<div class="">
<h4 class="text-uppercase">
G'DAY YOGIS
</h4>
<p>
Lid est laborum dolo rumes fugats untras. Etharums ser quidem rerum facilis dolores nemis omnis fugats vitaes nemo minima rerums unsers sadips amets.. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam
rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni
dolores. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt
explicabo.
</p>
<p>
Lid est laborum dolo rumes fugats untras. Etharums ser quidem rerum facilis dolores nemis omnis fugats vitaes nemo minima rerums unsers sadips amets..
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!--who i am -->
<section class="body-content">
<!--post-->
<div class="page-content ">
<div class="container">
<div class="row">
<!--post style 4 start-->
<div class="post-list-aside">
<div class="post-single">
<div class="col-md-6">
<div class="post-img m-top-50">
<img src="{{ site.static-image-url }}/audreyprofile.png" alt="" style="border-radius:15px; width:300px; height:250px;">
</div>
</div>
<div class="col-md-6">
<div class="post-desk">
<div class="m-bot-30">
<span class="post-sub-title text-uppercase">who i am </span>
<h4 class="text-uppercase">
I am a traveler yogi
</h4>
</div>
<p>
Phasellus fringilla suscipit risus nec eleifend. Pellentesque eu quam sem, ac malesuada leo sem quam pellente. Awesome sliders give you the opportunity to showcase your content.
</p>
<ul class="m-bot-30 circle-list inline-block">
<li>
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
</li>
<li>
Adipisci blanditiis delectus deserunt dolorem
</li>
<li>
Impedit inventore itaque iure libero maiores simso.
</li>
</ul>
<div>
<a href="/yoga/#about-audrey" class="btn btn-small btn-dark-solid "> Read More </a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- timeline-->
<section class="body-content ">
<div class="page-content timeline-parallax-1">
<div class="container">
<div class="row">
<div class="heading-title text-center">
<h3 class="text-uppercase">Timeline </h3>
<span class="text-uppercase">Happy life </span>
</div>
<div class="col-md-12">
<!--time line dark -->
<div class="timeline dark-1">
<article class="timeline-item alt">
<div class="timeline-desk">
<div class="panel">
<div class="panel-body">
<span class="timeline-icon">
<i class="icon-mobile"></i>
</span>
<span class="timeline-date">08:25 am</span>
<h1 class="text-uppercase">1 hour ago</h1>
<p><a href='http://www.freepik.com/free-vector/world-map-blue-template_718596.htm'>Designed by Freepik</a></p>
</div>
</div>
</div>
</article>
<article class="timeline-item ">
<div class="timeline-desk">
<div class="panel">
<div class="panel-body">
<span class="timeline-icon">
<i class="icon-lightbulb"></i>
</span>
<span class="timeline-date">10:00 am</span>
<h1 class="text-uppercase">2 hours ago</h1>
<p>Completed Coffee meeting with <a href="#">Stive Martin</a> regarding the Product Promotion</p>
</div>
</div>
</div>
</article>
<article class="timeline-item alt">
<div class="timeline-desk">
<div class="panel">
<div class="panel-body">
<span class="timeline-icon">
<i class="icon-strategy"></i>
</span>
<span class="timeline-date">11:35 am</span>
<h1 class="text-uppercase">10 hours ago</h1>
<p>3 new photo Uploaded on facebook fan page</p>
</div>
</div>
</div>
</article>
<article class="timeline-item">
<div class="timeline-desk">
<div class="panel">
<div class="panel-body">
<span class="timeline-icon">
<i class="icon-telescope"></i>
</span>
<span class="timeline-date">3:20 pm</span>
<h1 class="text-uppercase">4:30</h1>
<p>Outdoor visit at California State Route 85 with John Boltana & Harry Piterson regarding to setup a new show room.</p>
<p>
<i class=" fa fa-exclamation-sign"></i> New task added for <span><a href="#" >Denial Collins</a></span>
</p>
</div>
</div>
</div>
</article>
</div>
<!--time line dark -->
</div>
</div>
</div>
</section>
<!--skills-->
<section class="body-content"
<div class="row m-bot-80">
<div class="col-md-6">
<div class="">
<p></p>
<p></p>
<p></p>
<h4 class="text-uppercase">
who we are
</h4>
<p>
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas
sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore
veritatis et quasi architecto beatae vitae dicta sunt explicabo.
</p>
</div>
</div>
<div class="col-md-6">
<p></p>
<p></p>
<p></p>
<h4 class="text-uppercase">
Massive Skills
</h4>
<!-- progress bar start -->
<div class="progress massive-progress">
<div class="progress-bar" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100">
HTML / CSS / JQUERY <span>80%</span>
</div>
</div>
<!-- progress bar end -->
<!-- progress bar start -->
<div class="progress massive-progress">
<div class="progress-bar" role="progressbar" aria-valuenow="90" aria-valuemin="0" aria-valuemax="100">
PHOTOSHOP <span>90%</span>
</div>
</div>
<!-- progress bar end -->
<!-- progress bar start -->
<div class="progress massive-progress">
<div class="progress-bar" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100">
GRAPHIC DESIGN <span>75% </span>
</div>
</div>
<!-- progress bar end -->
<!-- progress bar start -->
<div class="progress massive-progress">
<div class="progress-bar" role="progressbar" aria-valuenow="82" aria-valuemin="0" aria-valuemax="100">
PHP / WORDPRESS <span>82%</span>
</div>
</div>
<!-- progress bar end -->
</div>
</div>
</section>
<section class="body-content">
<img src="/static/img/worldtravel-audrey.png" style=" display: block; width:auto; height: 700px;">
<a href='http://www.freepik.com/free-vector/world-map-blue-template_718596.htm'>Designed by Freepik</a>
</section>
<section class="body-content gray-bg">
<!-- testimonial -->
<div class="page-content">
<div class="container">
<div class="row">
<div class="heading-title text-center">
<h3 class="text-uppercase">Testimonial </h3>
<span class="text-uppercase">Some testimonials examples</span>
</div>
<div id="testimonial-centered"class="col-md-6">
<!--testimonial start -->
<div id="testimonial-4" class="testimonial-alt">
<div class="item">
<div class="content">
<p>
Nam nec dui dolor. Curabitur in laoreet erat. Nam nec dui dolor. Aliquam varius dolor nunc, interdum commodo justoporttitor vitae. Quisque fermentum purus.
</p>
</div>
<div class="testi-auth">
<div class="avatar">
<a href="#">
<img src="/static/img/testimonial/1.jpg" alt="Customer Testimonails">
</a>
</div>
<div class="testimonial-meta">
Kevin Paige
<span>ABC</span>
</div>
</div>
</div>
<div class="item">
<div class="content">
<p>
Nam nec dui dolor. Curabitur in laoreet erat. Nam nec dui dolor. Aliquam varius dolor nunc, interdum commodo justoporttitor vitae. Quisque fermentum purus.
</p>
</div>
<div class="testi-auth">
<div class="avatar">
<a href="#">
<img src="/static/img/testimonial/2.jpg" alt="Customer Testimonails">
</a>
</div>
<div class="testimonial-meta">
John Doe
<span>DEF</span>
</div>
</div>
</div>
<div class="item">
<div class="content">
<p>
Nam nec dui dolor. Curabitur in laoreet erat. Nam nec dui dolor. Aliquam varius dolor nunc, interdum commodo justoporttitor vitae. Quisque fermentum purus.
</p>
</div>
<div class="testi-auth">
<div class="avatar">
<a href="#">
<img src="/static/img/testimonial/3.jpg" alt="Customer Testimonails">
</a>
</div>
<div class="testimonial-meta">
Martin Smith
<span>GEF</span>
</div>
</div>
</div>
</div>
<!--testimonial end-->
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!--body content end-->
|
jordanrancie/jordanrancie.github.io
|
_includes/yoga/about-audrey.html
|
HTML
|
mit
| 19,523
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.