code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
export * from './login.component';
export * from './login-vm.model';
| wickdninja/Angular2AspNetCoreStarter | src/app/login/index.ts | TypeScript | mit | 69 |
# coding: utf-8
"""
ORCID Member
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: Latest
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from orcid_api_v3.models.created_date_v30 import CreatedDateV30 # noqa: F401,E501
from orcid_api_v3.models.external_i_ds_v30 import ExternalIDsV30 # noqa: F401,E501
from orcid_api_v3.models.fuzzy_date_v30 import FuzzyDateV30 # noqa: F401,E501
from orcid_api_v3.models.last_modified_date_v30 import LastModifiedDateV30 # noqa: F401,E501
from orcid_api_v3.models.organization_v30 import OrganizationV30 # noqa: F401,E501
from orcid_api_v3.models.source_v30 import SourceV30 # noqa: F401,E501
from orcid_api_v3.models.url_v30 import UrlV30 # noqa: F401,E501
class EducationSummaryV30(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'created_date': 'CreatedDateV30',
'last_modified_date': 'LastModifiedDateV30',
'source': 'SourceV30',
'put_code': 'int',
'department_name': 'str',
'role_title': 'str',
'start_date': 'FuzzyDateV30',
'end_date': 'FuzzyDateV30',
'organization': 'OrganizationV30',
'url': 'UrlV30',
'external_ids': 'ExternalIDsV30',
'display_index': 'str',
'visibility': 'str',
'path': 'str'
}
attribute_map = {
'created_date': 'created-date',
'last_modified_date': 'last-modified-date',
'source': 'source',
'put_code': 'put-code',
'department_name': 'department-name',
'role_title': 'role-title',
'start_date': 'start-date',
'end_date': 'end-date',
'organization': 'organization',
'url': 'url',
'external_ids': 'external-ids',
'display_index': 'display-index',
'visibility': 'visibility',
'path': 'path'
}
def __init__(self, created_date=None, last_modified_date=None, source=None, put_code=None, department_name=None, role_title=None, start_date=None, end_date=None, organization=None, url=None, external_ids=None, display_index=None, visibility=None, path=None): # noqa: E501
"""EducationSummaryV30 - a model defined in Swagger""" # noqa: E501
self._created_date = None
self._last_modified_date = None
self._source = None
self._put_code = None
self._department_name = None
self._role_title = None
self._start_date = None
self._end_date = None
self._organization = None
self._url = None
self._external_ids = None
self._display_index = None
self._visibility = None
self._path = None
self.discriminator = None
if created_date is not None:
self.created_date = created_date
if last_modified_date is not None:
self.last_modified_date = last_modified_date
if source is not None:
self.source = source
if put_code is not None:
self.put_code = put_code
if department_name is not None:
self.department_name = department_name
if role_title is not None:
self.role_title = role_title
if start_date is not None:
self.start_date = start_date
if end_date is not None:
self.end_date = end_date
if organization is not None:
self.organization = organization
if url is not None:
self.url = url
if external_ids is not None:
self.external_ids = external_ids
if display_index is not None:
self.display_index = display_index
if visibility is not None:
self.visibility = visibility
if path is not None:
self.path = path
@property
def created_date(self):
"""Gets the created_date of this EducationSummaryV30. # noqa: E501
:return: The created_date of this EducationSummaryV30. # noqa: E501
:rtype: CreatedDateV30
"""
return self._created_date
@created_date.setter
def created_date(self, created_date):
"""Sets the created_date of this EducationSummaryV30.
:param created_date: The created_date of this EducationSummaryV30. # noqa: E501
:type: CreatedDateV30
"""
self._created_date = created_date
@property
def last_modified_date(self):
"""Gets the last_modified_date of this EducationSummaryV30. # noqa: E501
:return: The last_modified_date of this EducationSummaryV30. # noqa: E501
:rtype: LastModifiedDateV30
"""
return self._last_modified_date
@last_modified_date.setter
def last_modified_date(self, last_modified_date):
"""Sets the last_modified_date of this EducationSummaryV30.
:param last_modified_date: The last_modified_date of this EducationSummaryV30. # noqa: E501
:type: LastModifiedDateV30
"""
self._last_modified_date = last_modified_date
@property
def source(self):
"""Gets the source of this EducationSummaryV30. # noqa: E501
:return: The source of this EducationSummaryV30. # noqa: E501
:rtype: SourceV30
"""
return self._source
@source.setter
def source(self, source):
"""Sets the source of this EducationSummaryV30.
:param source: The source of this EducationSummaryV30. # noqa: E501
:type: SourceV30
"""
self._source = source
@property
def put_code(self):
"""Gets the put_code of this EducationSummaryV30. # noqa: E501
:return: The put_code of this EducationSummaryV30. # noqa: E501
:rtype: int
"""
return self._put_code
@put_code.setter
def put_code(self, put_code):
"""Sets the put_code of this EducationSummaryV30.
:param put_code: The put_code of this EducationSummaryV30. # noqa: E501
:type: int
"""
self._put_code = put_code
@property
def department_name(self):
"""Gets the department_name of this EducationSummaryV30. # noqa: E501
:return: The department_name of this EducationSummaryV30. # noqa: E501
:rtype: str
"""
return self._department_name
@department_name.setter
def department_name(self, department_name):
"""Sets the department_name of this EducationSummaryV30.
:param department_name: The department_name of this EducationSummaryV30. # noqa: E501
:type: str
"""
self._department_name = department_name
@property
def role_title(self):
"""Gets the role_title of this EducationSummaryV30. # noqa: E501
:return: The role_title of this EducationSummaryV30. # noqa: E501
:rtype: str
"""
return self._role_title
@role_title.setter
def role_title(self, role_title):
"""Sets the role_title of this EducationSummaryV30.
:param role_title: The role_title of this EducationSummaryV30. # noqa: E501
:type: str
"""
self._role_title = role_title
@property
def start_date(self):
"""Gets the start_date of this EducationSummaryV30. # noqa: E501
:return: The start_date of this EducationSummaryV30. # noqa: E501
:rtype: FuzzyDateV30
"""
return self._start_date
@start_date.setter
def start_date(self, start_date):
"""Sets the start_date of this EducationSummaryV30.
:param start_date: The start_date of this EducationSummaryV30. # noqa: E501
:type: FuzzyDateV30
"""
self._start_date = start_date
@property
def end_date(self):
"""Gets the end_date of this EducationSummaryV30. # noqa: E501
:return: The end_date of this EducationSummaryV30. # noqa: E501
:rtype: FuzzyDateV30
"""
return self._end_date
@end_date.setter
def end_date(self, end_date):
"""Sets the end_date of this EducationSummaryV30.
:param end_date: The end_date of this EducationSummaryV30. # noqa: E501
:type: FuzzyDateV30
"""
self._end_date = end_date
@property
def organization(self):
"""Gets the organization of this EducationSummaryV30. # noqa: E501
:return: The organization of this EducationSummaryV30. # noqa: E501
:rtype: OrganizationV30
"""
return self._organization
@organization.setter
def organization(self, organization):
"""Sets the organization of this EducationSummaryV30.
:param organization: The organization of this EducationSummaryV30. # noqa: E501
:type: OrganizationV30
"""
self._organization = organization
@property
def url(self):
"""Gets the url of this EducationSummaryV30. # noqa: E501
:return: The url of this EducationSummaryV30. # noqa: E501
:rtype: UrlV30
"""
return self._url
@url.setter
def url(self, url):
"""Sets the url of this EducationSummaryV30.
:param url: The url of this EducationSummaryV30. # noqa: E501
:type: UrlV30
"""
self._url = url
@property
def external_ids(self):
"""Gets the external_ids of this EducationSummaryV30. # noqa: E501
:return: The external_ids of this EducationSummaryV30. # noqa: E501
:rtype: ExternalIDsV30
"""
return self._external_ids
@external_ids.setter
def external_ids(self, external_ids):
"""Sets the external_ids of this EducationSummaryV30.
:param external_ids: The external_ids of this EducationSummaryV30. # noqa: E501
:type: ExternalIDsV30
"""
self._external_ids = external_ids
@property
def display_index(self):
"""Gets the display_index of this EducationSummaryV30. # noqa: E501
:return: The display_index of this EducationSummaryV30. # noqa: E501
:rtype: str
"""
return self._display_index
@display_index.setter
def display_index(self, display_index):
"""Sets the display_index of this EducationSummaryV30.
:param display_index: The display_index of this EducationSummaryV30. # noqa: E501
:type: str
"""
self._display_index = display_index
@property
def visibility(self):
"""Gets the visibility of this EducationSummaryV30. # noqa: E501
:return: The visibility of this EducationSummaryV30. # noqa: E501
:rtype: str
"""
return self._visibility
@visibility.setter
def visibility(self, visibility):
"""Sets the visibility of this EducationSummaryV30.
:param visibility: The visibility of this EducationSummaryV30. # noqa: E501
:type: str
"""
allowed_values = ["LIMITED", "REGISTERED_ONLY", "PUBLIC", "PRIVATE"] # noqa: E501
if visibility not in allowed_values:
raise ValueError(
"Invalid value for `visibility` ({0}), must be one of {1}" # noqa: E501
.format(visibility, allowed_values)
)
self._visibility = visibility
@property
def path(self):
"""Gets the path of this EducationSummaryV30. # noqa: E501
:return: The path of this EducationSummaryV30. # noqa: E501
:rtype: str
"""
return self._path
@path.setter
def path(self, path):
"""Sets the path of this EducationSummaryV30.
:param path: The path of this EducationSummaryV30. # noqa: E501
:type: str
"""
self._path = path
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(EducationSummaryV30, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, EducationSummaryV30):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| Royal-Society-of-New-Zealand/NZ-ORCID-Hub | orcid_api_v3/models/education_summary_v30.py | Python | mit | 13,754 |
# Script Name : sqlite_check.py
# Author : Craig Richards
# Created : 20 May 2013
# Last Modified :
# Version : 1.0
# Modifications :
# Description : Runs checks to check my SQLITE database
import sqlite3 as lite
import sys
import os
dropbox = os.getenv("dropbox")
dbfile = ("Databases\jarvis.db")
master_db = os.path.join(dropbox, dbfile)
con = None
try:
con = lite.connect(master_db)
cur = con.cursor()
cur.execute('SELECT SQLITE_VERSION()')
data = cur.fetchone()
print
"SQLite version: %s" % data
except lite.Error, e:
print
"Error %s:" % e.args[0]
sys.exit(1)
finally:
if con:
con.close()
con = lite.connect(master_db)
cur = con.cursor()
cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
rows = cur.fetchall()
for row in rows:
print
row
con = lite.connect(master_db)
cur = con.cursor()
cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
while True:
row = cur.fetchone()
if row == None:
break
print
row[0]
| areriff/pythonlearncanvas | Python Script Sample/sqlite_check.py | Python | mit | 1,034 |
package br.com.caelum.tubaina.parser.html.desktop;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import br.com.caelum.tubaina.Book;
import br.com.caelum.tubaina.Chapter;
import br.com.caelum.tubaina.TubainaBuilderData;
import br.com.caelum.tubaina.TubainaException;
import br.com.caelum.tubaina.io.HtmlResourceManipulatorFactory;
import br.com.caelum.tubaina.io.ResourceManipulatorFactory;
import br.com.caelum.tubaina.io.TubainaHtmlDir;
import br.com.caelum.tubaina.io.TubainaHtmlIO;
import br.com.caelum.tubaina.parser.Parser;
import br.com.caelum.tubaina.parser.html.referencereplacer.ReferenceParser;
import br.com.caelum.tubaina.parser.html.referencereplacer.ReferenceReplacer;
import br.com.caelum.tubaina.parser.html.referencereplacer.SingleHtmlChapterReferenceReplacer;
import br.com.caelum.tubaina.parser.html.referencereplacer.SingleHtmlSectionReferenceReplacer;
import br.com.caelum.tubaina.template.FreemarkerProcessor;
import br.com.caelum.tubaina.util.Utilities;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.Configuration;
public class SingleHtmlGenerator implements Generator {
private final Parser parser;
private final File templateDir;
private Configuration cfg;
private List<String> ifdefs;
public SingleHtmlGenerator(Parser parser, TubainaBuilderData data) {
this.parser = parser;
this.templateDir = new File(data.getTemplateDir(), "singlehtml/");
this.ifdefs = data.getIfdefs();
configureFreemarker();
}
public void generate(Book book, File outputDir) throws IOException {
StringBuffer bookContent = generateHeader(book);
bookContent.append(new SingleHtmlTOCGenerator(book, cfg).generateTOC());
ResourceManipulatorFactory htmlResourceManipulatorFactory = new HtmlResourceManipulatorFactory();
TubainaHtmlDir bookRoot = new TubainaHtmlIO(templateDir, htmlResourceManipulatorFactory).createTubainaDir(outputDir, book);
for (Chapter c : book.getChapters()) {
StringBuffer chapterContent = generateChapter(book, c);
bookContent.append(chapterContent);
if (!c.getResources().isEmpty()) {
bookRoot.cd(Utilities.toDirectoryName(null, c.getTitle()))
.writeResources(c.getResources());
}
}
bookContent = resolveReferencesOf(bookContent);
bookContent.append(generateFooter());
bookRoot.writeIndex(bookContent);
}
private StringBuffer resolveReferencesOf(StringBuffer bookContent) {
List<ReferenceReplacer> replacers = new ArrayList<ReferenceReplacer>();
replacers.add(new SingleHtmlSectionReferenceReplacer());
replacers.add(new SingleHtmlChapterReferenceReplacer());
ReferenceParser referenceParser = new ReferenceParser(replacers);
bookContent = new StringBuffer(referenceParser.replaceReferences(bookContent.toString()));
return bookContent;
}
private StringBuffer generateHeader(Book book) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("booktitle", book.getName());
return new FreemarkerProcessor(cfg).process(map, "book-header.ftl");
}
private StringBuffer generateChapter(Book book, Chapter chapter) {
StringBuffer chapterContent = new SingleHtmlChapterGenerator(parser, cfg, ifdefs).generateSingleHtmlChapter(book, chapter);
return fixPaths(chapter, chapterContent);
}
private StringBuffer fixPaths(Chapter chapter, StringBuffer chapterContent) {
String chapterName = Utilities.toDirectoryName(null, chapter.getTitle());
return new StringBuffer(chapterContent.toString().replace("$$RELATIVE$$", chapterName));
}
private StringBuffer generateFooter() {
return new FreemarkerProcessor(cfg).process(new HashMap<String, Object>(), "book-footer.ftl");
}
private void configureFreemarker() {
cfg = new Configuration();
try {
cfg.setDefaultEncoding("UTF-8");
cfg.setDirectoryForTemplateLoading(templateDir);
} catch (IOException e) {
throw new TubainaException("Couldn't load freemarker template for Single HTML mode", e);
}
cfg.setObjectWrapper(new BeansWrapper());
}
}
| caelum/tubaina | src/main/java/br/com/caelum/tubaina/parser/html/desktop/SingleHtmlGenerator.java | Java | mit | 4,139 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="hi_IN" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Wankcoin</source>
<translation>बिटकोइन के संबंध में</translation>
</message>
<message>
<location line="+39"/>
<source><b>Wankcoin</b> version</source>
<translation>बिटकोइन वर्सन</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING 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 type="unfinished"/>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>कापीराइट</translation>
</message>
<message>
<location line="+0"/>
<source>The Wankcoin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>पता पुस्तक</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>दो बार क्लिक करे पता या लेबल संपादन करने के लिए !</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>नया पता लिखिए !</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>चुनिन्दा पते को सिस्टम क्लिपबोर्ड पर कापी करे !</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&नया पता</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Wankcoin 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 type="unfinished"/>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&पता कॉपी करे</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Wankcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Wankcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&मिटाए !!</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Wankcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>&लेबल कॉपी करे </translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&एडिट</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>पता पुस्तक का डेटा एक्सपोर्ट (निर्यात) करे !</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>ग़लतियाँ एक्सपोर्ट (निर्यात) करे!</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>फाइल में लिख नही सके %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>लेबल</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>पता</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(कोई लेबल नही !)</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 line="+21"/>
<source>Enter passphrase</source>
<translation>पहचान शब्द/अक्षर डालिए !</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>नया पहचान शब्द/अक्षर डालिए !</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>दोबारा नया पहचान शब्द/अक्षर डालिए !</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>नया पहचान शब्द/अक्षर वॉलेट मे डालिए ! <br/> कृपा करके पहचान शब्द में <br> 10 से ज़्यादा अक्षॉरों का इस्तेमाल करे </b>,या <b>आठ या उससे से ज़्यादा शब्दो का इस्तेमाल करे</b> !</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>एनक्रिप्ट वॉलेट !</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>वॉलेट खोलने के आपका वॉलेट पहचान शब्द्/अक्षर चाईए !</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>वॉलेट खोलिए</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>वॉलेट डीक्रिप्ट( विकोड) करने के लिए आपका वॉलेट पहचान शब्द्/अक्षर चाईए !</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation> डीक्रिप्ट वॉलेट</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>पहचान शब्द/अक्षर बदलिये !</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>कृपा करके पुराना एवं नया पहचान शब्द/अक्षर वॉलेट में डालिए !</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>वॉलेट एनक्रिपशन को प्रमाणित कीजिए !</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR WANKCOINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>वॉलेट एनक्रिप्ट हो गया !</translation>
</message>
<message>
<location line="-56"/>
<source>Wankcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your wankcoins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>वॉलेट एनक्रिप्ट नही हुआ!</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>वॉलेट एनक्रिपशन नाकाम हो गया इंटर्नल एरर की वजह से! आपका वॉलेट एनक्रीपत नही हुआ है!</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>आपके द्वारा डाले गये पहचान शब्द/अक्षर मिलते नही है !</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>वॉलेट का लॉक नही खुला !</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>वॉलेट डीक्रिप्ट करने के लिए जो पहचान शब्द/अक्षर डाले गये है वो सही नही है!</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>वॉलेट का डीक्रिप्ट-ष्ण असफल !</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>नेटवर्क से समकालिक (मिल) रहा है ...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&विवरण</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>वॉलेट का सामानया विवरण दिखाए !</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>& लेन-देन
</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>देखिए पुराने लेन-देन के विवरण !</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>स्टोर किए हुए पते और लेबलओ को बदलिए !</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>पते की सूची दिखाए जिन्हे भुगतान करना है !</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>बाहर जायें</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>अप्लिकेशन से बाहर निकलना !</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Wankcoin</source>
<translation>बीटकोइन के बारे में जानकारी !</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&विकल्प</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&बैकप वॉलेट</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Wankcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Wankcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>पहचान शब्द/अक्षर जो वॉलेट एनक्रिपशन के लिए इस्तेमाल किया है उसे बदलिए!</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Wankcoin</source>
<translation>बीटकोइन</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>वॉलेट</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About Wankcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Wankcoin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Wankcoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&फाइल</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&सेट्टिंग्स</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&मदद</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>टैबस टूलबार</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[टेस्टनेट]</translation>
</message>
<message>
<location line="+47"/>
<source>Wankcoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Wankcoin network</source>
<translation><numerusform>%n सक्रिया संपर्क बीटकोइन नेटवर्क से</numerusform><numerusform>%n सक्रिया संपर्क बीटकोइन नेटवर्क से</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n घंटा</numerusform><numerusform>%n घंटे</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n दिन</numerusform><numerusform>%n दिनो</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n हफ़्ता</numerusform><numerusform>%n हफ्ते</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>%1 पीछे</translation>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>भूल</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>चेतावनी</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>जानकारी</translation>
</message>
<message>
<location line="+70"/>
<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 type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>नवीनतम</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>भेजी ट्रांजक्शन</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>प्राप्त हुई ट्रांजक्शन</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>तारीख: %1\n
राशि: %2\n
टाइप: %3\n
पता:%4\n</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Wankcoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड नहीं है</translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड है</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Wankcoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>पता एडिट करना</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&लेबल</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>इस एड्रेस बुक से जुड़ा एड्रेस</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&पता</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>इस एड्रेस बुक से जुड़ी प्रविष्टि केवल भेजने वाले addresses के लिए बदली जा सकती है|</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>नया स्वीकार्य पता</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>नया भेजने वाला पता</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>एडिट स्वीकार्य पता </translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>एडिट भेजने वाला पता</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>डाला गया पता "%1" एड्रेस बुक में पहले से ही मोजूद है|</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Wankcoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>वॉलेट को unlock नहीं किया जा सकता|</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>नयी कुंजी का निर्माण असफल रहा|</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Wankcoin-Qt</source>
<translation>बीटकोइन-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>संस्करण</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>खपत :</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>विकल्प</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start Wankcoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start Wankcoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Wankcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the Wankcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Wankcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show Wankcoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&ओके</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&कैन्सल</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>चेतावनी</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Wankcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>फार्म</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Wankcoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>बाकी रकम :</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>अपुष्ट :</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>वॉलेट</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>हाल का लेन-देन</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>आपका चालू बॅलेन्स</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>लेन देन की पुष्टि अभी नहीं हुई है, इसलिए इन्हें अभी मोजुदा बैलेंस में गिना नहीं गया है|</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start wankcoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>भुगतान का अनुरोध</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>राशि :</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>लेबल :</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>लागू नही
</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the Wankcoin-Qt help message to get a list with possible Wankcoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>Wankcoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Wankcoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the Wankcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Wankcoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<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="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>सिक्के भेजें|</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>एक साथ कई प्राप्तकर्ताओं को भेजें</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>बाकी रकम :</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 WKC</source>
<translation>123.456 WKC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>भेजने की पुष्टि करें</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> से %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>सिक्के भेजने की पुष्टि करें</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>क्या आप %1 भेजना चाहते हैं?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>और</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>भेजा गया अमाउंट शुन्य से अधिक होना चाहिए|</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<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>फार्म</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>अमाउंट:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>प्राप्तकर्ता:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>आपकी एड्रेस बुक में इस एड्रेस के लिए एक लेबल लिखें</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>लेबल:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt-A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Clipboard से एड्रेस paste करें</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt-P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>प्राप्तकर्ता हटायें</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Wankcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Wankcoin एड्रेस लिखें (उदाहरण: 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<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 type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt-A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Clipboard से एड्रेस paste करें</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt-P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>हस्ताक्षर</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Wankcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Wankcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Wankcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Wankcoin एड्रेस लिखें (उदाहरण: 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter Wankcoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Wankcoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>खुला है जबतक %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/अपुष्ट</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 पुष्टियाँ</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>taareek</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 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, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>राशि</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>सही</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>ग़लत</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, अभी तक सफलतापूर्वक प्रसारित नहीं किया गया है</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>अज्ञात</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>लेन-देन का विवरण</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation> ये खिड़की आपको लेन-देन का विस्तृत विवरण देगी !</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>taareek</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>टाइप</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>पता</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>राशि</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>खुला है जबतक %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>ऑफलाइन ( %1 पक्का करना)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>अपुष्ट ( %1 मे %2 पक्के )</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>पक्के ( %1 पक्का करना)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>यह ब्लॉक किसी भी और नोड को मिला नही है ! शायद यह ब्लॉक कोई भी नोड स्वीकारे गा नही !</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>जेनरेट किया गया किंतु स्वीकारा नही गया !</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>स्वीकारा गया</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>स्वीकार्य ओर से</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>भेजा गया</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>भेजा खुद को भुगतान</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>माइंड</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(लागू नहीं)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>ट्रांसेक्शन स्तिथि| पुष्टियों की संख्या जानने के लिए इस जगह पर माउस लायें|</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>तारीख तथा समय जब ये ट्रांसेक्शन प्राप्त हुई थी|</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>ट्रांसेक्शन का प्रकार|</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>ट्रांसेक्शन की मंजिल का पता|</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>अमाउंट बैलेंस से निकला या जमा किया गया |</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>सभी</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>आज</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>इस हफ्ते</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>इस महीने</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>पिछले महीने</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>इस साल</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>विस्तार...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>स्वीकार करना</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>भेजा गया</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>अपनेआप को</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>माइंड</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>अन्य</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>ढूँदने के लिए कृपा करके पता या लेबल टाइप करे !</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>लघुत्तम राशि</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>पता कॉपी करे</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>लेबल कॉपी करे </translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>कॉपी राशि</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>एडिट लेबल</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>लेन-देन का डेटा निर्यात करे !</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>पक्का</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>taareek</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>टाइप</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>लेबल</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>पता</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>राशि</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>ग़लतियाँ एक्सपोर्ट (निर्यात) करे!</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>फाइल में लिख नही सके %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>विस्तार:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>तक</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>बैकप वॉलेट</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>वॉलेट डेटा (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>बैकप असफल</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>बैकप सफल</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>wankcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Wankcoin version</source>
<translation>बीटकोइन संस्करण</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>खपत :</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or wankcoind</source>
<translation>-server या wankcoind को कमांड भेजें</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>commands की लिस्ट बनाएं</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>किसी command के लिए मदद लें</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>विकल्प:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: wankcoin.conf)</source>
<translation>configuraion की फाइल का विवरण दें (default: wankcoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: wankcoind.pid)</source>
<translation>pid फाइल का विवरण दें (default: wankcoin.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9336 or testnet: 19336)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9335 or testnet: 19335)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=wankcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Wankcoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Wankcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<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>
<message>
<location line="+4"/>
<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 line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<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 line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Wankcoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>ब्लॉक्स जाँचे जा रहा है...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>वॉलेट जाँचा जा रहा है...</translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>जानकारी</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Wankcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>चेतावनी</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>पता पुस्तक आ रही है...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Wankcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Wankcoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>राशि ग़लत है</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>ब्लॉक इंडेक्स आ रहा है...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Wankcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>वॉलेट आ रहा है...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>रि-स्केनी-इंग...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>लोड हो गया|</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>भूल</translation>
</message>
<message>
<location line="-31"/>
<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>
</context>
</TS> | wcoin/wankcoin0 | src/qt/locale/bitcoin_hi_IN.ts | TypeScript | mit | 106,338 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Platibus.Diagnostics;
using Xunit;
namespace Platibus.UnitTests.Diagnostics
{
[Trait("Category", "UnitTests")]
[Trait("Dependency", "InfluxDB")]
public class InfluxDBSinkTests
{
protected TimeSpan SampleRate = TimeSpan.FromSeconds(5);
// docker run -it --rm --name influxdb -e INFLUXDB_ADMIN_ENABLED=true -p 8096:8086 -p 8093:8083 influxdb
protected InfluxDBOptions Options = new InfluxDBOptions(new Uri("http://localhost:8096"), "platibus");
protected List<DiagnosticEvent> DiagnosticEvents = new List<DiagnosticEvent>();
public InfluxDBSinkTests()
{
CreateDatabase();
WaitForInfluxDB(Options.Uri);
}
private static void WaitForInfluxDB(Uri uri)
{
var pingUri = new UriBuilder(uri)
{
Path = "ping"
}.Uri;
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)))
using (var client = new HttpClient())
{
while (!cts.IsCancellationRequested)
{
try
{
var response = client.GetAsync(pingUri).Result;
if (response.IsSuccessStatusCode) return;
Task.Delay(TimeSpan.FromSeconds(1)).Wait(cts.Token);
}
catch (Exception)
{
}
}
}
throw new TimeoutException("InfluxDB not available");
}
private void CreateDatabase()
{
var uri = new UriBuilder(Options.Uri)
{
Path = "query",
Query = "q=CREATE DATABASE " + Options.Database
}.Uri;
using (var client = new HttpClient())
{
var response = client.PostAsync(uri, new StringContent("")).Result;
Assert.True(response.IsSuccessStatusCode, $"Error creating InfluxDB database '{Options.Database}': {response}");
}
}
[Fact]
public async Task AcknowledgementFailuresAreRecorded()
{
GivenQueuedMessageFlowWithAcknowledgementFailure();
await WhenConsumingEvents();
}
protected void GivenQueuedMessageFlowWithAcknowledgementFailure()
{
var fakes = new DiagnosticFakes(this);
DiagnosticEvents.AddRange(fakes.QueuedMessageFlowWithAcknowledgementFailure());
}
protected async Task WhenConsumingEvents()
{
var sink = new InfluxDBSink(Options, SampleRate);
var consumeTasks = DiagnosticEvents.Select(async e => await sink.ConsumeAsync(e)).ToList();
await Task.WhenAll(consumeTasks);
sink.RecordMeasurements();
}
}
}
| sweetlandj/Platibus | Source/Platibus.UnitTests/Diagnostics/InfluxDBSinkTests.cs | C# | mit | 3,062 |
// Lab14avst.java
// Lab14a
// Student starting version
import java.awt.*;
import java.applet.*;
import java.util.ArrayList;
public class Lab14avst extends Applet {
public void paint(Graphics g) {
drawGrid(g);
Shape square = new Shape1Square();
Shape triangle = new Shape2Triangle();
Shape octagon = new Shape3Octagon();
Shape circle = new Shape4Circle();
ArrayList<Shape> shapes = new ArrayList<Shape>();
shapes.add(square);
shapes.add(triangle);
shapes.add(octagon);
shapes.add(circle);
for (Shape shape : shapes) {
shape.drawShape(g);
shape.displayName(g);
shape.displayNumSides(g);
}
}
public void drawGrid(Graphics g) {
g.drawRect(10, 10, 800, 600);
g.drawLine(10, 300, 810, 300);
g.drawLine(410, 10, 410, 610);
}
}
| andrewwiik/Lab14avst | Lab14avst.java | Java | mit | 771 |
/**
* Created by wQ on 2017/3/28.
*/
export * from './navbar/index';
export * from './footer/index';
export * from './sidenav/index';
| CuteCodevx/skinhearing | src/client/app/core/index.ts | TypeScript | mit | 136 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
// load header
$this->load->view('layouts/header');
// currency
$this->load->helper('currency_helper');
$attr_form = array(
'name' => 'work_order'
);
$date = date('Y-m-d');
?>
<!-- content -->
<div class="container-fluid font_mini">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<h3>Entry Trucking Container Data <a href="<?php echo site_url('Order/view_trucking'); ?>" class="btn btn-default"><span class="glyphicon glyphicon-chevron-left"></span> Back</a></h3>
<hr>
</div>
</div>
<div class="row">
<div class="col-md-12>
<div class="panel panel-default">
<div class="panel-body">
<?php echo form_open(); ?>
<?php if(validation_errors()) { ?>
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<?php echo validation_errors(); ?>
</div>
<?php } ?>
<?php if(isset($sppb_error) && $sppb_error == "error") { ?>
<div class="alert alert-warning">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<?php echo "Failed entry trucking data. Please entry SPPB!"; ?>
</div>
<?php } ?>
<?php if($this->session->flashdata('failed')) { ?>
<div class="alert alert-warning">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<?php echo $this->session->flashdata('failed'); ?>
</div>
<?php } ?>
<?php if(isset($trucking_error) && $trucking_error == "error") { ?>
<div class="alert alert-warning">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<?php echo "Failed entry trucking data. Please don't inserted empty or more than one container!"; ?>
</div>
<?php } ?>
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">Header Trucking</div>
<div class="panel-body">
<div class="row">
<div class="col-md-5 col-md-offset-1">
<table>
<tr>
<td><strong>Work Order Number</strong></td>
<td style="padding: 0px 10px">:</td>
<td><?php echo $work_order_number; ?></td>
</tr>
<tr>
<td><strong>Customer</strong></td>
<td style="padding: 20px 10px">:</td>
<td><?php echo $customer_name; ?></td>
</tr>
</table>
<button type="submit" class="btn btn-success">Save</button>
</div>
<div class="col-md-5 col-md-offset-1">
<table>
<tr>
<td><strong>Delivery Number</strong></td>
<td style="padding: 0px 10px">:</td>
<td>
<input type="text" name="do_number" class="form-control" readonly="true" value="<?php echo set_value('do_number', $do_number) ?>">
</td>
</tr>
<tr>
<td><strong>Date</strong></td>
<td style="padding: 13px 10px">:</td>
<td>
<input type="text" name="document_date" id="document_date" class="form-control" value="<?php echo set_value('document_date', $do_date); ?>">
</td>
</tr>
</table>
<?php
if ($check_container > 0) {
echo anchor('Order/print_do/'.$work_order_number.'/'.$this->uri->segment(4), '<span class="glyphicon glyphicon-print"></span> Print', array('class' => 'btn btn-primary'));
} else {
echo '<button type="button" class="btn btn-primary" disabled><span class="glyphicon glyphicon-print"></span> Print</button>';
}
?>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Trucking Data</div>
<div class="panel-body">
<div class="table-responsive">
<div class="table-responsive">
<table class="table table-striped table-bordered" id="tableTrucking">
<thead>
<tr>
<th class="text-center">Container Number</th>
<th class="text-center">Container Detail</th>
<th class="text-center">Commodity</th>
<th class="text-center">From / To</th>
<th class="text-center">Trucking by</th>
<th class="text-center">Truck Number</th>
<th class="text-center">Chassis Number</th>
<th class="text-center">Driver</th>
<th class="text-center">Est. Location Date</th>
<th class="text-center">Detail To</th>
<th class="text-center">Remarks</th>
</tr>
</thead>
<tbody>
<?php
$loop_code = 0;
foreach ($data_container as $key => $value) {
$tampung = $value->COMMODITY_DESCRIPTION;
$string = strip_tags($tampung);
$hasil = substr($string, 0, 7)."...";
?>
<tr id="<?php echo $loop_code; ?>">
<?php /* <td>
<button type="button" class="btn btn-danger btn_remove" id="<?php echo $loop_code; ?>" ><span class="glyphicon glyphicon-remove"></span></button>
</td> */ ?>
<td><?php echo $value->CONTAINER_NUMBER; ?></td>
<td><?php echo $value->CONTAINER_SIZE_ID . " - " . $value->CONTAINER_TYPE_ID . " - " . $value->CONTAINER_CATEGORY_ID; ?></td>
<td><?php echo $hasil; ?></td>
<td><?php echo $value->FROM_NAME . " - " . $value->TO_NAME; ?></td>
<td>
<select class="form-control coba" data-id="<?php echo $loop_code; ?>" id="#select<?php echo $loop_code; ?>" name="container[<?php echo $loop_code; ?>][own_truck]">
<option></option>
<?php
foreach ($data_own as $key1 => $value1) {
?>
<option <?php if ($value->TRUCK_OWNER_ID == $value1->TRUCK_OWNER_ID ) echo 'selected' ; ?> value="<?php echo $value1->TRUCK_OWNER_ID ?>"><?php echo $value1->TRUCK_OWNER_NAME ?></option>
<?php
}
?>
</select>
</td>
<td>
<input type="text" name="container[<?php echo $loop_code; ?>][truck_number]" class="form-control" onClick="search_truck(<?php echo $loop_code; ?>)" id="truck<?php echo $loop_code; ?>" value="<?php echo $value->TRUCK_ID_NUMBER; ?>">
<input type="hidden" name="container[<?php echo $loop_code; ?>][container_number]" class="form-control" value="<?php echo $value->CONTAINER_NUMBER; ?>" value="<?php echo $value->CONTAINER_NUMBER ?>">
<input type="hidden" name="container[<?php echo $loop_code; ?>][do_number]" class="form-control" value="<?php echo $do_number; ?>">
</td>
<td>
<input type="text" name="container[<?php echo $loop_code; ?>][chasis_number]" class="form-control" onClick="search_chasis(<?php echo $loop_code; ?>)" id="chasis<?php echo $loop_code; ?>" value="<?php echo $value->CHASIS_ID_NUMBER; ?>" >
</td>
<td>
<?php
/*
<input type="text" id="#driver<?php echo $loop_code; ?>" name="container[<?php echo $loop_code; ?>][driver_name]" id="driver<?php echo $loop_code; ?>" class="form-control" onClick="search_driver(<?php echo $loop_code; ?>)" value="<?php echo $value->DRIVER_NAME; ?>">
<input type="hidden" name="container[<?php echo $loop_code; ?>][driver_id]" id="driver_id<?php echo $loop_code; ?>" class="form-control" value="<?php echo $value->DRIVER_ID ?>">
*/
?>
<select class="form-control js-example-basic-single js-states" name="container[<?php echo $loop_code; ?>][driver_id]">
<option value=""></option>
<?php
foreach ($data_driver as $key1 => $value1) {
?>
<option <?php if ($value->DRIVER_ID == $value1->DRIVER_ID ) echo 'selected' ; ?> value="<?php echo $value1->DRIVER_ID; ?>" ><?php echo $value1->DRIVER_NAME; ?></option>
<?php
}
?>
</select>
</td>
<td>
<input type="text" name="container[<?php echo $loop_code; ?>][est_date]" id="est_date" class="form-control est_date" value="<?php echo $value->EST_DATE; ?>">
</td>
<td>
<select class="form-control js-example-basic-single js-states" name="container[<?php echo $loop_code; ?>][detail_to]">
<option value=""></option>
<?php
foreach ($data_address as $value1) {
?>
<option <?php if ($value->FINAL_LOCATION_DETAIL == $value1 ) echo 'selected' ; ?> value="<?php echo $value1; ?>" ><?php echo $value1; ?></option>
<?php
}
?>
</select>
</td>
<td>
<textarea class="form-control" name="container[<?php echo $loop_code; ?>][remarks]"><?php echo $value->REMARKS; ?></textarea>
</td>
</tr>
<?php
$loop_code++;
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- end of content -->
<!-- js -->
<?php
$this->load->view('layouts/js.php');
?>
<!-- script datatables -->
<script type="text/javascript">
function search_commodity(id)
{
// autocomplete hoarding
$('#commo'+id+'').autocomplete({
source: "<?php echo site_url('Order/search_commodity'); ?>",
minLength:1,
select:function(event, data){
$('#commo_id'+id+'').val(data.item.commodity_id);
}
});
}
function search_truck(id)
{
// autocomplete hoarding
$('#truck'+id+'').autocomplete({
source: "<?php echo site_url('Order/search_truck'); ?>",
minLength:1
});
}
function search_chasis(id)
{
// autocomplete hoarding
$('#chasis'+id+'').autocomplete({
source: "<?php echo site_url('Order/search_chasis'); ?>",
minLength:1
});
}
function search_driver(id)
{
// autocomplete hoarding
$('#driver'+id+'').autocomplete({
source: "<?php echo site_url('Order/search_driver'); ?>",
minLength:1,
select:function(event, data){
$('#driver_id'+id+'').val(data.item.driver_id);
}
});
}
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#'+button_id+'').remove();
});
$(document).ready(function() {
$(".js-example-basic-single").select2();
var d = new Date();
var a = d.setDate(d.getDate() - 5);
$('#date').datetimepicker({
timepicker:false,
format: "Y-m-d",
minDate: a
});
$('#document_date').datetimepicker({
timepicker:false,
format: "Y-m-d"
});
$('.est_date').datetimepicker({
timepicker:false,
format: "Y-m-d"
});
$('#table-trucking').DataTable({
responsive: true
});
// autocomplete hoarding
$("#hoarding_name").autocomplete({
source: "<?php echo site_url('Order/search_hoarding'); ?>",
minLength:1,
select:function(event, data){
$('input[name=hoarding_id]').val(data.item.hoarding_id);
}
});
// // autocomplete hoarding
// $('#').autocomplete({
// source: "<?php echo site_url('Order/search_nik'); ?>",
// minLength:1,
// select:function(event, data){
// $('#nik_isi'+id+'').val(data.item.pic_id);
// }
// });
// autocomplete importir
$("#importir_name").autocomplete({
source: "<?php echo site_url('Order/search_company'); ?>",
minLength:1,
select:function(event, data){
$('input[name=importir_id]').val(data.item.company_id);
}
});
if($(".coba").attr("selectedIndex") != "TR001") {
var but_id = $(this).attr("data-id");
$('#driver'+but_id+'').prop('disabled', true);
}
});
</script>
<?php
$this->load->view('layouts/footer.php');
?>
| adrianvaldii/hsp | application/views/orders/v_entrytrucking.php | PHP | mit | 19,797 |
<?php include_once('../app/view/include/header.inc.php'); ?>
<!-- Affichage et selection de l'adresse -->
<script>
$(function() {
var addresspickerMap = $( "#addresspicker" ).addresspicker({
regionBias: "fr",
elements: {
lat: "#lat",
lng: "#lng",
country: '#country',
postal_code: '#postal_code',
locality: '#locality'
}
});
});
</script>
<div class="col-lg-12">
<h1> Administration des restaurants </h1>
<?php include_once('../app/view/include/header.restaurant.inc.php'); ?>
<form class="form-horizontal" name="formu_resto" action="" method="POST" enctype="multipart/form-data">
<fieldset>
<!-- Form Name -->
<legend>Modifier restaurant</legend>
<!-- Nom -->
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Nom</label>
<div class="col-md-4">
<input required id="nom_resto" name="nom_resto" class="form-control input-md" value='<?php echo $verif_details[0]['lr_nom'];?>'>
</div>
</div>
<!-- Adresse -->
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Adresse</label>
<div class="col-md-4">
<input id="addresspicker" name="adresse_resto" type="text" class="form-control input-md" required value='<?php echo $verif_details[0]['lr_adresse'];?>'>
<input id="lat" name="latitude" value='<?php echo $verif_details[0]['lr_latitude'];?>' />
<input id="lng" name="longitude" value='<?php echo $verif_details[0]['lr_longitude'];?>' />
<input id="country" name="pays" value='<?php echo $verif_details[0]['lr_pays'];?>' />
<input id="postal_code" name="code_postal" value='<?php echo $verif_details[0]['lr_code_postal'];?>' />
<input id="locality" name="ville" value='<?php echo $verif_details[0]['lr_ville'];?>' />
</div>
</div>
<!-- Description -->
<div class="form-group">
<label class="col-md-4 control-label" for="textarea">Description</label>
<div class="col-md-4">
<textarea required class="form-control" id="desc_resto" name="desc_resto"> <?php echo $verif_details[0]['lr_description'];?></textarea>
</div>
</div>
<!-- Horraire -->
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Horraire</label>
<br/>
<div class="col-md-8">
<!--<input required id="horraire_resto" name="horraire_resto" type="text" placeholder="Horraire" class="form-control input-md"> -->
<select name="jour1">
<option>Lundi</option>
</select>
<br/>
MIDI
<select name="horraire_midi_ouverture1">
<option>09:00</option>
<option>10:00</option>
<option>11:00</option>
<option selected><?php echo $verif_details[0]['lh_open_day'];?></option>
</select>
à
<select name="horraire_midi_fermeture1">
<option>13:00</option>
<option selected><?php echo $verif_details[0]['lh_close_day'];?></option>
<option>15:00</option>
</select>
<br/>
SOIR
<select name="horraire_soir_ouverture1">
<option selected><?php echo $verif_details[0]['lh_open_night'];?></option>
<option>20:00</option>
<option>21:00</option>
</select>
à
<select name="horraire_soir_fermeture1">
<option>22:00</option>
<option selected><?php echo $verif_details[0]['lh_close_night'];?></option>
<option>00:00</option>
</select>
<br/>
<br/>
<select name="jour2">
<option>Mardi</option>
</select>
<br/>
MIDI
<select name="horraire_midi_ouverture2">
<option>09:00</option>
<option>10:00</option>
<option>11:00</option>
<option selected><?php echo $verif_details[0]['lh_open_day'];?></option>
</select>
à
<select name="horraire_midi_fermeture2">
<option>13:00</option>
<option selected><?php echo $verif_details[0]['lh_close_day'];?></option>
<option>15:00</option>
</select>
<br/>
SOIR
<select name="horraire_soir_ouverture2">
<option selected><?php echo $verif_details[0]['lh_open_night'];?></option>
<option>20:00</option>
<option>21:00</option>
</select>
à
<select name="horraire_soir_fermeture2">
<option>22:00</option>
<option selected><?php echo $verif_details[0]['lh_close_night'];?></option>
<option>00:00</option>
</select>
<br/>
<br/>
<select name="jour3">
<option>Mercredi</option>
</select>
<br/>
MIDI
<select name="horraire_midi_ouverture3">
<option>09:00</option>
<option>10:00</option>
<option>11:00</option>
<option selected><?php echo $verif_details[0]['lh_open_day'];?></option>
</select>
à
<select name="horraire_midi_fermeture3">
<option>13:00</option>
<option selected><?php echo $verif_details[0]['lh_close_day'];?></option>
<option>15:00</option>
</select>
<br/>
SOIR
<select name="horraire_soir_ouverture3">
<option selected><?php echo $verif_details[0]['lh_open_night'];?></option>
<option>20:00</option>
<option>21:00</option>
</select>
à
<select name="horraire_soir_fermeture3">
<option>22:00</option>
<option selected><?php echo $verif_details[0]['lh_close_night'];?></option>
<option>00:00</option>
</select>
<br/>
<br/>
<select name="jour4">
<option>Jeudi</option>
</select>
<br/>
MIDI
<select name="horraire_midi_ouverture4">
<option>09:00</option>
<option>10:00</option>
<option>11:00</option>
<option selected><?php echo $verif_details[0]['lh_open_day'];?></option>
</select>
à
<select name="horraire_midi_fermeture4">
<option>13:00</option>
<option selected><?php echo $verif_details[0]['lh_close_day'];?></option>
<option>15:00</option>
</select>
<br/>
SOIR
<select name="horraire_soir_ouverture4">
<option selected><?php echo $verif_details[0]['lh_open_night'];?></option>
<option>20:00</option>
<option>21:00</option>
</select>
à
<select name="horraire_soir_fermeture4">
<option>22:00</option>
<option selected><?php echo $verif_details[0]['lh_close_night'];?></option>
<option>00:00</option>
</select>
<br/>
<br/>
<select name="jour5">
<option>Vendredi</option>
</select>
<br/>
MIDI
<select name="horraire_midi_ouverture5">
<option>09:00</option>
<option>10:00</option>
<option>11:00</option>
<option selected><?php echo $verif_details[0]['lh_open_day'];?></option>
</select>
à
<select name="horraire_midi_fermeture5">
<option>13:00</option>
<option selected><?php echo $verif_details[0]['lh_close_day'];?></option>
<option>15:00</option>
</select>
<br/>
SOIR
<select name="horraire_soir_ouverture5">
<option selected><?php echo $verif_details[0]['lh_open_night'];?></option>
<option>20:00</option>
<option>21:00</option>
</select>
à
<select name="horraire_soir_fermeture5">
<option>22:00</option>
<option selected><?php echo $verif_details[0]['lh_close_night'];?></option>
<option>00:00</option>
</select>
<br/>
<br/>
<select name="jour6">
<option>Samedi</option>
</select>
<br/>
MIDI
<select name="horraire_midi_ouverture6">
<option>09:00</option>
<option>10:00</option>
<option>11:00</option>
<option selected><?php echo $verif_details[0]['lh_open_day'];?></option>
</select>
à
<select name="horraire_midi_fermeture6">
<option>13:00</option>
<option selected><?php echo $verif_details[0]['lh_close_day'];?></option>
<option>15:00</option>
</select>
<br/>
SOIR
<select name="horraire_soir_ouverture6">
<option selected><?php echo $verif_details[0]['lh_open_night'];?></option>
<option>20:00</option>
<option>21:00</option>
</select>
à
<select name="horraire_soir_fermeture6">
<option>22:00</option>
<option selected><?php echo $verif_details[0]['lh_close_night'];?></option>
<option>00:00</option>
</select>
<br/>
<br/>
<select name="jour7">
<option>Dimanche</option>
</select>
<br/>
MIDI
<select name="horraire_midi_ouverture7">
<option>09:00</option>
<option>10:00</option>
<option>11:00</option>
<option selected><?php echo $verif_details[0]['lh_open_day'];?></option>
</select>
à
<select name="horraire_midi_fermeture7">
<option>13:00</option>
<option selected><?php echo $verif_details[0]['lh_close_day'];?></option>
<option>15:00</option>
</select>
<br/>
SOIR
<select name="horraire_soir_ouverture7">
<option selected><?php echo $verif_details[0]['lh_open_night'];?></option>
<option>20:00</option>
<option>21:00</option>
</select>
à
<select name="horraire_soir_fermeture7">
<option>22:00</option>
<option selected><?php echo $verif_details[0]['lh_close_night'];?></option>
<option>00:00</option>
</select>
</div>
</div>
<!-- Photo -->
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Photo</label>
</div>
<div class="row">
<div class="row">
<?php echo "<div class='col-lg-3 col-md-4 col-xs-6'><img width='300' class='img-responsive thumbnail' "; if($verif_details[0]['lr_image_1'] == ""){echo " src='images/no-picture.jpg' alt='Pas d image 1 !'"; } else {echo " src='".$verif_details[0]['lr_image_1']."' alt='".$verif_details[0]['lr_nom']."'";} echo"/></div>" ;?>
<?php echo "<div class='col-lg-3 col-md-4 col-xs-6'><img width='300' class='img-responsive thumbnail' "; if($verif_details[0]['lr_image_2'] == ""){echo " src='images/no-picture.jpg' alt='Pas d image 2 !'"; } else {echo " src='".$verif_details[0]['lr_image_2']."' alt='".$verif_details[0]['lr_nom']."'";} echo"/></div>" ;?>
<?php echo "<div class='col-lg-3 col-md-4 col-xs-6'><img width='300' class='img-responsive thumbnail' "; if($verif_details[0]['lr_image_3'] == ""){echo " src='images/no-picture.jpg' alt='Pas d image 3 !'"; } else {echo " src='".$verif_details[0]['lr_image_3']."' alt='".$verif_details[0]['lr_nom']."'";} echo"/></div>" ;?>
<?php echo "<div class='col-lg-3 col-md-4 col-xs-6'><img width='300' class='img-responsive thumbnail' "; if($verif_details[0]['lr_image_4'] == ""){echo " src='images/no-picture.jpg' alt='Pas d image 4 !'"; } else {echo " src='".$verif_details[0]['lr_image_4']."' alt='".$verif_details[0]['lr_nom']."'";} echo"/></div>" ;?>
</div>
</div>
<!-- Ajouter image n°1 -->
<div class="form-group">
<label class="col-md-4 control-label" for="filebutton">Ajouter une image</label>
<div class="col-md-4">
<input id="img1_resto" name="ch_file1" class="input-file" type="file">
</div>
</div>
<!-- Ajouter image n°2 -->
<div class="form-group">
<label class="col-md-4 control-label" for="filebutton">Ajouter une image</label>
<div class="col-md-4">
<input id="img1_resto" name="ch_file2" class="input-file" type="file">
</div>
</div>
<!-- Ajouter image n°3 -->
<div class="form-group">
<label class="col-md-4 control-label" for="filebutton">Ajouter une image</label>
<div class="col-md-4">
<input id="img1_resto" name="ch_file3" class="input-file" type="file">
</div>
</div>
<!-- Ajouter image n°4 -->
<div class="form-group">
<label class="col-md-4 control-label" for="filebutton">Ajouter une image</label>
<div class="col-md-4">
<input id="img1_resto" name="ch_file4" class="input-file" type="file">
</div>
</div>
<!-- Button Valider -->
<div class="form-group">
<label class="col-md-4 control-label" for="singlebutton"></label>
<div class="col-md-4">
<button id="singlebutton" name="singlebutton" class="btn btn-primary" type="submit">Valider</button>
</div>
</div>
</fieldset>
</form>
</div>
<?php include_once('../app/view/include/footer.inc.php'); ?> | jordanams/lunchr | lunchr_back-office/app/view/restaurants/update_resto.php | PHP | mit | 13,225 |
namespace SimShift.Entities
{
public enum ShifterTableConfigurationDefault
{
Economy,
Efficiency,
Performance,
PeakRpm,
AlsEenOpa,
Henk,
PowerEfficiency
}
} | zappybiby/SimShift | SimShift/SimShift/Entities/ShifterTableConfigurationDefault.cs | C# | mit | 230 |
package com.convenient.plan.service;
import net.sf.json.JSONArray;
public interface PlanIndexService {
/**
* 获取所有项目的计划,并以JSONArray的格式返回
* @return
* @throws RuntimeException
* @throws Exception
*/
public JSONArray getAllProjectPlan() throws RuntimeException, Exception;
}
| zhaiwh8312/plan | java/plan/src/com/convenient/plan/service/PlanIndexService.java | Java | mit | 320 |
class GamesController < ApplicationController
def show
@game = Game.find_by(id: params[:id])
end
def create
if @user = User.find_by(id: params[:user_id])
@game = Game.new(user: @user)
@game.save
redirect_to user_game_path(@user.id, @game.id)
else
@errors = ['You must be logged in']
redirect_to welcome_index_path
end
end
def five
if @user = User.find_by(id: params[:id])
@game = Game.new(user: @user)
@game.save
@five = true
render :'/games/show'
else
@errors = ['You must be logged in']
redirect_to welcome_index_path
end
end
def get_computer_move
@game = Game.find_by(id: params[:id])
board = params[:squares]
render json: @game.computer_move(board)
end
def get_computer_move_five
@game = Game.find_by(id: params[:id])
board = params[:squares]
render json: @game.computer_move_five(board)
end
def save
@game = Game.find_by(id: params[:id])
winner = (params[:winner] == 'X')
@game.update(end_time: Time.now, won: winner)
render json: @game
end
end
| jesusmarlima/tic_tac_toe | tic-tac-toe/app/controllers/games_controller.rb | Ruby | mit | 1,117 |
#ifndef RT_Rectangle_HH
#define RT_Rectangle_HH
#include "SceneObj.hh"
class Rectangle : public SceneObj {
public:
Rectangle();
~Rectangle() = default;
Rectangle(const Rectangle &other) = default;
Rectangle(Rectangle &&other) = default;
Rectangle &operator=(const Rectangle &other) = default;
Rectangle &operator=(Rectangle &&other) = default;
double intersect(Vector rayVec, Camera camera) const;
void calcNormal(Vector &normVec, const Position &impact) const;
private:
double height;
double width;
};
#endif /* end of include guard: RT_Rectangle_HH */
| Tastyep/cpp-rt | inc/Rectangle.hh | C++ | mit | 580 |
angular.module('messages')
.controller('messageCtrl',['$scope','messages','socket','$stateParams',MessageController])
function MessageController($scope,messages,socket,$stateParams) {
$scope.messages = messages;
$scope.msg = '';
$scope.sendMsg = function() {
socket.sendMsg({content : $scope.msg, to : $stateParams.id});
};
}; | Pranay92/collaborate-client | app/modules/messages/messages.controller.js | JavaScript | mit | 351 |
package me.ivanyu.simplekv.types;
import java.util.Comparator;
public class KeyComparator implements Comparator<Key> {
public static final KeyComparator INSTANCE = new KeyComparator();
@Override
public int compare(Key k1, Key k2) {
if (k1 == null)
throw new NullPointerException("k1 can't be null");
if (k2 == null)
throw new NullPointerException("k2 can't be null");
return k1.keyValue.compareTo(k2.keyValue);
}
}
| ivanyu/btree | src/main/java/me/ivanyu/simplekv/types/KeyComparator.java | Java | mit | 483 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
try:
from ._models_py3 import DetectedLanguage
from ._models_py3 import DocumentEntities
from ._models_py3 import DocumentError
from ._models_py3 import DocumentKeyPhrases
from ._models_py3 import DocumentLanguage
from ._models_py3 import DocumentLinkedEntities
from ._models_py3 import DocumentSentiment
from ._models_py3 import DocumentStatistics
from ._models_py3 import EntitiesResult
from ._models_py3 import Entity
from ._models_py3 import EntityLinkingResult
from ._models_py3 import ErrorResponse
from ._models_py3 import InnerError
from ._models_py3 import KeyPhraseResult
from ._models_py3 import LanguageBatchInput
from ._models_py3 import LanguageInput
from ._models_py3 import LanguageResult
from ._models_py3 import LinkedEntity
from ._models_py3 import Match
from ._models_py3 import MultiLanguageBatchInput
from ._models_py3 import MultiLanguageInput
from ._models_py3 import RequestStatistics
from ._models_py3 import SentenceSentiment
from ._models_py3 import SentimentConfidenceScorePerLabel
from ._models_py3 import SentimentResponse
from ._models_py3 import TextAnalyticsError
from ._models_py3 import TextAnalyticsWarning
except (SyntaxError, ImportError):
from ._models import DetectedLanguage # type: ignore
from ._models import DocumentEntities # type: ignore
from ._models import DocumentError # type: ignore
from ._models import DocumentKeyPhrases # type: ignore
from ._models import DocumentLanguage # type: ignore
from ._models import DocumentLinkedEntities # type: ignore
from ._models import DocumentSentiment # type: ignore
from ._models import DocumentStatistics # type: ignore
from ._models import EntitiesResult # type: ignore
from ._models import Entity # type: ignore
from ._models import EntityLinkingResult # type: ignore
from ._models import ErrorResponse # type: ignore
from ._models import InnerError # type: ignore
from ._models import KeyPhraseResult # type: ignore
from ._models import LanguageBatchInput # type: ignore
from ._models import LanguageInput # type: ignore
from ._models import LanguageResult # type: ignore
from ._models import LinkedEntity # type: ignore
from ._models import Match # type: ignore
from ._models import MultiLanguageBatchInput # type: ignore
from ._models import MultiLanguageInput # type: ignore
from ._models import RequestStatistics # type: ignore
from ._models import SentenceSentiment # type: ignore
from ._models import SentimentConfidenceScorePerLabel # type: ignore
from ._models import SentimentResponse # type: ignore
from ._models import TextAnalyticsError # type: ignore
from ._models import TextAnalyticsWarning # type: ignore
from ._text_analytics_client_enums import (
DocumentSentimentValue,
ErrorCodeValue,
InnerErrorCodeValue,
SentenceSentimentValue,
WarningCodeValue,
)
__all__ = [
'DetectedLanguage',
'DocumentEntities',
'DocumentError',
'DocumentKeyPhrases',
'DocumentLanguage',
'DocumentLinkedEntities',
'DocumentSentiment',
'DocumentStatistics',
'EntitiesResult',
'Entity',
'EntityLinkingResult',
'ErrorResponse',
'InnerError',
'KeyPhraseResult',
'LanguageBatchInput',
'LanguageInput',
'LanguageResult',
'LinkedEntity',
'Match',
'MultiLanguageBatchInput',
'MultiLanguageInput',
'RequestStatistics',
'SentenceSentiment',
'SentimentConfidenceScorePerLabel',
'SentimentResponse',
'TextAnalyticsError',
'TextAnalyticsWarning',
'DocumentSentimentValue',
'ErrorCodeValue',
'InnerErrorCodeValue',
'SentenceSentimentValue',
'WarningCodeValue',
]
| Azure/azure-sdk-for-python | sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/v3_0/models/__init__.py | Python | mit | 4,297 |
@extends('layouts.master')
@section('content')
<section class="jumbotron text-center">
<div class="container">
<a href="https://twitter.com/TeamHarekaze"><img src="{{ asset('img/favicon.png') }}"></a>
<h1 class="jumbotron-heading">Team:Harekaze</h1>
<p class="lead text-muted">"In a crisis on CTF!"</p>
</div>
</section>
<section>
<header class="section-header">
<h2 id="rule"><a href="#Rule">Rule</a></h2>
</header>
<div class="container">
<p>ぼくたちのCTFに参加する場合は次のルールを守ってね。</p>
<p>守らないと、おちんちん引っこ抜くぞ <i class="fa fa-heart" aria-hidden="true" style="color:#EF75BC"></i></p>
<ul type="disc">
<li>他のプレイヤーへの妨害行為</li>
<li>他のプレイヤーの回答などをのぞき見する行為</li>
<li>他のプレイヤーに問題・ヒント・解答を教えること</li>
<li>他のプレイヤーからヒント・解答を得ること</li>
<li>設問によって攻撃が許可されているサーバ、ネットワーク以外への攻撃</li>
<li>その他、運営を阻害する行為</li>
</ul>
</div>
</section>
@stop
| HayatoDoi/HarekazeCTF | src/resources/views/home/top.blade.php | PHP | mit | 1,208 |
<?php namespace Fisharebest\Localization\Locale;
use Fisharebest\Localization\Territory\TerritorySo;
/**
* Class LocaleArSo
*
* @author Greg Roach <fisharebest@gmail.com>
* @copyright (c) 2015 Greg Roach
* @license GPLv3+
*/
class LocaleArSo extends LocaleAr {
public function territory() {
return new TerritorySo;
}
}
| fweber1/Annies-Ancestors | webtrees/vendor/fisharebest/localization/src/Locale/LocaleArSo.php | PHP | mit | 344 |
/**
* Created by uzysjung on 2016. 10. 21..
*/
import React, { PropTypes,Component } from 'react';
import Box from '../../components/widget/Box'
import { Link, browserHistory } from 'react-router'
import superagent from 'superagent';
import { Form , FormGroup, Col, Button, FormControl, Checkbox, ControlLabel , PageHeader, Alert } from 'react-bootstrap'
const styleLogin = {
panel : {
maxWidth : 600,
position : 'absolute',
top : '50%',
left : '50%',
transform : 'translate(-50%,-50%)'
},
header : {
maxHeight : 40,
bottomMargin : 100,
borderBottom : '1px solid #bababa'
}
};
class LoginPage extends React.Component {
constructor(props) {
super(props);
this.state = {
email : '',
password : ''
}
}
componentWillMount() {
const { authenticated, replace, redirect } = this.props;
if (authenticated) {
replace(redirect)
}
}
componentDidMount() {
}
handleFormSubmit = (e) => {
e.preventDefault();
const { email, password } = this.state;
setTimeout(() => this.setState({error: false}), 3000);
if ( !email || email.length < 1) {
this.setState({error: 'Insert Email address'});
return;
}
if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(email)) {
this.setState({error: 'Please check whether this email is valid'});
return;
}
if (!password) {
this.setState({error: 'Insert Password'});
return;
}
if ( password && password.length < 5 ) {
this.setState({error: 'Password must be longer than 5 characters'});
return;
}
superagent.post('/api/login').send({login_email: email, login_pw: password}).end((err, result) => {
if (!err) {
localStorage.setItem('jwt', result.body.token);
browserHistory.push('/');
} else {
this.setState({error: 'Login email/password incorrect :('});
}
});
};
handleForChange = (e) => {
console.log('e.target.id',e.target.id);
switch(e.target.id) {
case 'formHorizontalEmail' :
this.setState( { email : e.target.value } );
break;
case 'formHorizontalPassword' :
this.setState( { password : e.target.value } );
break;
}
};
renderAlert() {
if (this.state.error) {
return (
<Alert bsStyle="danger">
{this.state.error}
</Alert>
)
}
return null;
}
render() {
return (
<div style={styleLogin.panel}>
<PageHeader style={styleLogin.header}>Weapon Management System</PageHeader>
<Box
title="Login"
status="info"
solid
>
<Form onSubmit={this.handleFormSubmit} horizontal>
<FormGroup controlId="formHorizontalEmail">
<Col componentClass={ControlLabel} sm={2}>
Email
</Col>
<Col sm={10}>
<FormControl type="email" placeholder="Email" value={this.state.email} onChange={this.handleForChange} />
</Col>
</FormGroup>
<FormGroup controlId="formHorizontalPassword">
<Col componentClass={ControlLabel} sm={2}>
Password
</Col>
<Col sm={10}>
<FormControl type="password" placeholder="Password" value={this.state.password} onChange={this.handleForChange} />
</Col>
</FormGroup>
<FormGroup>
<Col smOffset={2} sm={10}>
<Checkbox>Remember me</Checkbox>
</Col>
</FormGroup>
{this.renderAlert()}
<FormGroup>
<Col smOffset={2} sm={10}>
<Button className="btn btn-success" type="submit">
Sign in
</Button>
</Col>
</FormGroup>
</Form>
</Box>
</div>
);
}
}
export default LoginPage;
| hamxabaig/rfid-tags | client/src/containers/pages/LoginPage.js | JavaScript | mit | 4,990 |
package com.velocity.model.transactions.query.response;
import com.velocity.gson.annotations.SerializedName;
/**
* This class holds the data for ScoreThreshold
*
* @author ranjitk
*
*/
public class ScoreThreshold {
/* Attribute for ScoreThreshold value exists or not. */
@SerializedName("Nillable")
private boolean nillable;
@SerializedName("Value")
private String value;
public boolean isNillable() {
return nillable;
}
public void setNillable(boolean nillable) {
this.nillable = nillable;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
| nab-velocity/android-sdk | VelocityLibrary/src/com/velocity/model/transactions/query/response/ScoreThreshold.java | Java | mit | 666 |
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Mexican Wave
#Problem level: 6 kyu
def wave(str):
li=[]
for i in range(len(str)):
x=list(str)
x[i]=x[i].upper()
li.append(''.join(x))
return [x for x in li if x!=str]
| Kunalpod/codewars | mexican_wave.py | Python | mit | 255 |
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
$(function () {
$('[data-toggle="popover"]').popover()
}) | tochiton/NetBrigde | public/assets/js/script.js | JavaScript | mit | 120 |
<?php
namespace coopers98\GenericCRUD;
use DB;
use Illuminate\Http\Request;
use View;
trait GenericCRUD {
protected $dbConnection = 'mysql';
protected $table_name = 'generic';
protected $columns = [ ];
protected $ignored_columns = [ 'created_at', 'updated_at', 'deleted_at' ];
protected $readonly_columns = [ 'id', '_id' ]; // default to id being readonly
protected $date_columns = [ ];
protected $resourceLink = 'generic';
protected $masterTemplate = 'genericcrud::master';
protected $showView = 'genericcrud::show';
protected $indexView = 'genericcrud::index';
protected $confirmDeleteView = 'genericcrud::confirm_delete';
protected $editView = 'genericcrud::edit';
protected $createView = 'genericcrud::create';
protected $extraViewValues = [ ];
protected $toolEntries = [ ];
//
// Gives a 1 step easy way to do admin checks
//
protected $is_admin = false;
/**
* Will translate MySQL types to internally known types
*
* @param $fullType
*
* @return string
*/
protected function translateType( $fullType ) {
if ( stripos( $fullType, 'int' ) !== false ) {
return 'int';
}
if ( stripos( $fullType, 'double' ) !== false ) {
return 'double';
}
if ( stripos( $fullType, 'decimal' ) !== false ) {
return 'decimal';
}
if ( stripos( $fullType, 'varchar' ) === 0 ) {
return 'string';
}
if ( stripos( $fullType, 'enum' ) === 0 ) {
return 'enum';
}
if ( stripos( $fullType, 'datetime' ) === 0 ) {
return 'datetime';
}
return $fullType;
}
/**
* Populate our column data
*/
protected function populateColumns() {
$columns = DB::connection( $this->dbConnection )->select( DB::raw( 'SHOW FIELDS FROM ' . $this->table_name ) );
foreach ( $columns as $column ) {
$this->columns[ $column->Field ] = [
'Type' => $column->Type,
'Null' => $column->Null,
'Key' => $column->Key,
'Default' => $column->Default,
'Extra' => $column->Extra,
'ShortType' => $this->translateType( $column->Type )
];
if ( $this->columns[ $column->Field ]['ShortType'] == 'enum' ) {
$vals = explode( ',', substr( $column->Type, 5, - 1 ) );
foreach ( $vals as $val ) {
$val = trim( $val, "'" );
$this->columns[ $column->Field ]['enumVals'][ $val ] = $val;
}
}
}
}
/**
* Display a listing of the resource.
* GET /genericupdate
*
* @return Response
*/
public function index( Request $request ) {
$this->authorizeList();
$limit = $request->input( 'limit', 25 );
$limit = $limit > 1000 ? 1000 : $limit;
$items = DB::connection( $this->dbConnection )->table( $this->table_name )->paginate( $limit );
return View::make( $this->indexView )
->with( 'masterTemplate', $this->masterTemplate )
->with( 'items', $items )
->with( 'columns', $this->columns )
->with( 'ignored_columns', $this->ignored_columns )
->with( 'table_name', $this->table_name )
->with( 'resource_link', $this->resourceLink )
->with( 'tool_entries', $this->toolEntries );
}
/**
* Show the form for creating a new resource.
* GET /genericupdate/create
*
* @return Response
*/
public function create() {
$this->authorizeCreate();
return View::make( $this->createView )
->with( 'masterTemplate', $this->masterTemplate )
->with( 'columns', $this->columns )
->with( 'ignored_columns', $this->ignored_columns )
->with( 'table_name', $this->table_name )
->with( 'readonly_columns', $this->readonly_columns )
->with( 'date_columns', $this->date_columns )
->with( 'is_admin', $this->is_admin )
->with( 'resource_link', $this->resourceLink );
}
/**
* Store a newly created resource in storage.
* POST /genericupdate
*
* @return Response
*/
public function store( Request $request ) {
$this->authorizeStore();
$updates = array();
foreach ( $this->columns as $column_name => $column_attributes ) {
if ( ! in_array( $column_name, $this->ignored_columns ) && strlen( $request->{$column_name} ) > 0 ) {
switch ( $column_attributes['ShortType'] ) {
case 'date':
$updates[ $column_name ] = date( 'Y-m-d', strtotime( $request->{$column_name} ) );
break;
default:
$updates[ $column_name ] = $request->{$column_name};
}
}
}
DB::connection( $this->dbConnection )->table( $this->table_name )->insert( $updates );
return redirect()->route( $this->resourceLink . '.index' )
->with( 'message', 'Entry Created' );
}
/**
* Display the specified resource.
* GET /genericupdate/{id}
*
* @param int $id
*
* @return Response
*/
public function show( $id ) {
$this->authorizeShow();
$entry = DB::connection( $this->dbConnection )->table( $this->table_name )->find( $id );
if ( is_array( $entry ) ) {
$entry = json_decode( json_encode( $entry ), false );
}
return View::make( $this->showView )
->with( 'id', $id )
->with( 'masterTemplate', $this->masterTemplate )
->with( 'data', $entry )
->with( 'columns', $this->columns )
->with( 'ignored_columns', $this->ignored_columns )
->with( 'table_name', $this->table_name )
->with( 'is_admin', $this->is_admin )
->with( 'resource_link', $this->resourceLink );
}
/**
* Show the form for editing the specified resource.
* GET /genericupdate/{id}/edit
*
* @param int $id
*
* @return Response
*/
public function edit( $id ) {
$this->authorizeEdit();
$entry = DB::connection( $this->dbConnection )->table( $this->table_name )->find( $id );
if ( is_array( $entry ) ) {
$entry = json_decode( json_encode( $entry ), false );
}
return View::make( $this->editView )
->with( 'id', $id )
->with( 'masterTemplate', $this->masterTemplate )
->with( 'data', $entry )
->with( 'columns', $this->columns )
->with( 'ignored_columns', $this->ignored_columns )
->with( 'table_name', $this->table_name )
->with( 'readonly_columns', $this->readonly_columns )
->with( 'date_columns', $this->date_columns )
->with( 'is_admin', $this->is_admin )
->with( 'resource_link', $this->resourceLink );
}
/**
* Update the specified resource in storage.
* PUT /genericupdate/{id}
*
* @param int $id
*
* @return Response
*/
public function update( $id, Request $request ) {
$this->authorizeUpdate();
$updates = array();
foreach ( $this->columns as $column_name => $column_attributes ) {
if ( ! in_array( $column_name, $this->ignored_columns ) && strlen( $request->{$column_name} ) > 0 ) {
$updates[ $column_name ] = $request->{$column_name};
}
}
DB::connection( $this->dbConnection )->table( $this->table_name )
->where( 'id', $id )
->update( $updates );
return redirect()->route( $this->resourceLink . '.show', [ $id ] )
->with( 'message', 'Entry Updated' );
}
/**
* Remove the specified resource from storage.
* DELETE /genericupdate/{id}
*
* @param int $id
*
* @return Response
*/
public function destroy( Request $request, $id ) {
$this->authorizeDelete();
$confirmed = $request->input( 'confirmed', false );
if ( ! $confirmed ) {
$entry = DB::connection( $this->dbConnection )->table( $this->table_name )->find( $id );
if ( is_array( $entry ) ) {
$entry = json_decode( json_encode( $entry ), false );
}
return View::make( $this->confirmDeleteView )
->with( 'masterTemplate', $this->masterTemplate )
->with( 'data', $entry )
->with( 'columns', $this->columns )
->with( 'ignored_columns', $this->ignored_columns )
->with( 'table_name', $this->table_name )
->with( 'resource_link', $this->resourceLink );
}
if ( array_key_exists( 'deleted_at', $this->columns ) ) {
// Soft delete
DB::connection( $this->dbConnection )
->table( $this->table_name )
->where( 'id', '=', $id )
->update( 'deleted_at', time() );
} else {
DB::connection( $this->dbConnection )->table( $this->table_name )->where( 'id', '=', $id )->delete();
}
return redirect()->route( $this->resourceLink . '.index' )
->with( 'message', 'Entry deleted' );
}
public function authorizeList() {
}
public function authorizeShow() {
}
public function authorizeEdit() {
}
public function authorizeUpdate() {
}
public function authorizeCreate() {
}
public function authorizeStore() {
}
public function authorizeDelete() {
}
public function checkAdmin() {
if ( ! $this->is_admin ) {
return redirect()->route( $this->resourceLink . '.index' )
->with( 'error', 'Unauthorized to do that' );
}
}
} | coopers98/genericcrud | src/GenericCRUD.php | PHP | mit | 9,026 |
'use strict';
//var async = require('async'),
// nconf = require('nconf'),
// user = require('../user'),
// groups = require('../groups'),
// topics = require('../topics'),
// posts = require('../posts'),
// notifications = require('../notifications'),
// messaging = require('../messaging'),
// plugins = require('../plugins'),
// utils = require('../../public/src/utils'),
// websockets = require('./index'),
// meta = require('../meta'),
var linkParser = require('../controllers/mind-map/linkParser_new-format'),
swaggerBuilder = require('../modeling/swaggerBuilder'),
swaggerBuildertr069 = require('../modeling/swaggerBuilder-Scope');
var SocketCustom = {};
SocketCustom.refreshLinkParser = function(socket, sets, callback) {
if (!socket.uid) {
return callback(new Error('[[invalid-uid]]'));
}
linkParser.init(function(err) {
callback(null, '{"message": "Refreshed Link Parser"}');
});
};
SocketCustom.refreshSwagger = function(socket, data, callback) {
if (!socket.uid) {
return callback(new Error('[[invalid-uid]]'));
}
swaggerBuilder.init(function(err) {
callback(null, '{"message": "Refreshed Swagger File"}');
});
};
SocketCustom.refreshZoneSwagger = function(socket, data, callback) {
if (!socket.uid) {
return callback(new Error('[[invalid-uid]]'));
}
swaggerBuildertr069.init(function(err) {
callback(null, '{"message": "Refreshed Zone Swagger File"}');
});
};
/* Exports */
module.exports = SocketCustom;
| cablelabs/dev-portal | src/socket.io/custom.js | JavaScript | mit | 1,565 |
//---------------------------------------------------------------------------
//
// <copyright file="RBTree.cs" company="Microsoft">
// Copyright (C) by Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: Root of a red-black tree.
//
//---------------------------------------------------------------------------
/*
The Red-black tree is a popular balanced binary tree data structure for
ordered lists, yielding O(log n) worst-case performance for standard operations
like search, insert, and delete. This implementation is based on Bob Sedgewick's
Left-Leaning Red-Black Trees idea.
formal paper: http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf
slides: http://www.cs.princeton.edu/~rs/talks/LLRB/RedBlack.pdf
RB-trees are binary trees satisfying some additional constraints:
1. Every node is colored either red or black. (Equivalently, the edge
from the node to its parent is colored red or black.)
2. Leaf nodes (null pointers) are black.
3. No consecutive reds - if a node is red, its parent is black.
4. Every leaf (null) has the same "black depth" - the number of black
nodes on the path from the leaf to the root.
A left-leaning tree has one additional constraint:
5. A mixed-color family leans left. If a node has one red child and one
black child, the red child is the left child.
This constraint makes the rebalancing algorithms simpler, as there are fewer
cases to worry about.
This implementation augments a simple textbook RB-tree in several ways.
1. Bulk data. Every node holds an array of data items, up to MaxSize.
This gets the speed of array operations (indexing, bulk moves by
memcopy, etc.) for much of the work.
2. Order statistics. Every node knows the number of items in its left
subtree. This permits O(log n) implementations of search-by-index,
IndexOf(x), and other index-based operations.
3. Fingers. Short-lived pointers to a position within the data structure.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows; // SR, SRID
using TypeConverterHelper = System.Windows.Markup.TypeConverterHelper;
namespace MS.Internal.Data
{
internal class RBTree<T> : RBNode<T>, IList<T>
{
#if LiveShapingInstrumentation
protected static int QuickSortThreshold = 15;
#else
const int QuickSortThreshold = 15;
#endif
public RBTree() : base(false)
{
Size = MaxSize;
}
public override bool HasData { get { return false; } }
public Comparison<T> Comparison
{
get { return _comparison; }
set { _comparison = value; }
}
public RBFinger<T> BoundedSearch(T x, int low, int high)
{
return BoundedSearch(x, low, high, Comparison);
}
public void Insert(T x)
{
RBFinger<T> finger = Find(x, Comparison);
Insert(finger, x, true);
}
void Insert(RBFinger<T> finger, T x, bool checkSort=false)
{
#if RBTreeFlightRecorder
SaveTree();
int size = LeftSize;
#endif
RBNode<T> node = finger.Node;
if (node == this)
{
node = InsertNode(0);
node.InsertAt(0, x);
}
else if (node.Size < MaxSize)
{
node.InsertAt(finger.Offset, x);
}
else
{
RBNode<T> successor = node.GetSuccessor();
RBNode<T> succsucc = null;
if (successor.Size >= MaxSize)
{
if (successor != this)
succsucc = successor;
successor = InsertNode(finger.Index + node.Size - finger.Offset);
}
node.InsertAt(finger.Offset, x, successor, succsucc);
}
LeftChild.IsRed = false;
#if RBTreeFlightRecorder
Verify(size + 1, checkSort);
#endif
}
public void Sort()
{
try
{
QuickSort();
}
catch (Exception e)
{
throw new InvalidOperationException(SR.Get(SRID.InvalidOperation_IComparerFailed), e);
}
}
public void QuickSort()
{
#if RBTreeFlightRecorder
SaveTree();
int size = Count;
#endif
if (Count > 1)
{
RBFinger<T> low = FindIndex(0, false);
RBFinger<T> high = FindIndex(Count, false);
QuickSort3(low, high);
InsertionSortImpl();
}
#if RBTreeFlightRecorder
Verify(size);
#endif
}
public void InsertionSort()
{
#if RBTreeFlightRecorder
SaveTree();
int size = Count;
#endif
if (Count > 1)
{
InsertionSortImpl();
}
#if RBTreeFlightRecorder
Verify(size);
#endif
}
// QuickSort, with the following techniques:
// 1. choose pivot by median-of-3
// 2. detect items equal to the pivot (3-way pivoting)
// 3. recurse on smaller subfile first (limits stack depth)
// 4. insertion-sort small subfiles, in one pass at the end
// 5. eliminate tail recursion
void QuickSort3(RBFinger<T> low, RBFinger<T> high)
{
while (high - low > QuickSortThreshold)
{
// the goal of 3-way pivoting is to swap items so as to divide the list
// into three pieces:
// "red" (item < pivot), "green" (item == pivot), "blue" (item > pivot)
// This is the famous "Dutch National Flag" problem, named by Dijkstra
// in honor of his ----'s flag, which has three vertical stripes
// of different colors (I don't remember the Dutch colors, so I'm using
// red, greeen, and blue, like the bits in a pixel color.)
//
// The following algorithm seems to be the best in practice. It's not
// widely known - I reinvented it based on memories of a conversation
// I had with someone (Tarjan, Cole, Bentley, McIlroy, Sedgewick?) long
// ago. I think Doug McIlroy had the idea.
//
// We maintain an invariant: the region to the left of "left"
// has three subregions containing green, red, and green items, respectively.
// The fingers greenL, red, and left give the right-boundaries of these
// regions, so the picture is
//
// |--low |--greenL |--red |--left
// v v v v
// .------------------------------------------
// | green | red | green | unknown
// .------------------------------------------
//
// Similarly, the region to the right of "right" looks like
//
// |--right |--blue |--greenR |--high
// v v v v
// -----------------------------------------.
// unknown | green | blue | green |
// -----------------------------------------.
//
// We advance left and right toward each other, swapping items as needed
// to preserve the invariant (the details are best expressed in the the
// code itself). When left and right reach each other, we swap the red
// region with the green region to its left, and swap blue with the
// green to its right, and we're done.
RBFinger<T> greenL=low, red=low+1, blue=high-1, greenR=high;
T x;
// select pivot - median of 3
RBFinger<T> mid = FindIndex((low.Index + high.Index)/2);
int c = Comparison(low.Item, mid.Item);
if (c < 0)
{
c = Comparison(mid.Item, blue.Item);
if (c < 0)
{ // r, g, b
}
else if (c == 0)
{ // r, g, g
greenR =blue;
}
else
{
c = Comparison(low.Item, blue.Item);
if (c < 0)
{ // r, b, g
Exchange(mid, blue);
}
else if (c == 0)
{ // g, b, g
Exchange(mid, blue);
greenL = red;
}
else
{ // g, b, r
Exchange(low, mid);
Exchange(low, blue);
}
}
}
else if (c == 0)
{
c = Comparison(low.Item, blue.Item);
if (c < 0)
{ // g, g, b
greenL = red;
}
else if (c == 0)
{ // g, g, g
greenL = red;
greenR = blue;
}
else
{ // g, g, r
Exchange(low, blue);
greenR = blue;
}
}
else
{
c = Comparison(low.Item, blue.Item);
if (c < 0)
{ // g, r, b
Exchange(low, mid);
}
else if (c == 0)
{ // g, r, g
Exchange(low, mid);
greenR = blue;
}
else
{
c = Comparison(mid.Item, blue.Item);
if (c < 0)
{ // b, r, g
Exchange(low, mid);
Exchange(mid, blue);
}
else if (c == 0)
{ // b, g, g
Exchange(low, blue);
greenL = red;
}
else
{ // b, g, r
Exchange(low, blue);
}
}
}
// Now partition the list into three pieces, using the pivot item
x = mid.Item;
RBFinger<T> left = red, right = blue;
for (;;)
{
// advance 'left'
while (left < right)
{
c = Comparison(left.Item, x);
if (c < 0)
{ // red
Trade(greenL, red, left);
greenL += left - red;
red = ++left;
}
else if (c == 0)
{ // green
++left;
}
else
{ // blue
break;
}
}
// advance 'right'
while (left < right)
{
RBFinger<T> f = right - 1;
c = Comparison(f.Item, x);
if (c < 0)
{ // red
break;
}
else if (c == 0)
{ // green
--right;
}
else
{ // blue
Trade(right, blue, greenR);
greenR -= blue - right;
blue = --right;
}
}
// check for termination
c = right - left;
if (c == 0)
{ // one or both of the loops terminated due to pointer collision.
// swap the outer green regions into the middle, and terminate
Trade(low, greenL, red); red += low-greenL;
Trade(blue, greenR, high); blue += high-greenR;
break;
}
else if (c == 1)
{ // this should never happen
}
else if (c == 2)
{ // special case - this[left] is blue, this[left+1] is red
// swap the outer green regions into the middle, and terminate
Trade(low, greenL, red); red += low-greenL+1; Exchange(red-1, left+1);
if (red > left) ++left;
Trade(blue, greenR, high); blue += high-greenR-1; Exchange(left, blue);
break;
}
else
{ // swap this[left] (blue) with this[right-1] (red) and continue
Exchange(left, right-1);
Trade(greenL, red, left); greenL += left-red; red = ++left;
Trade(right, blue, greenR); greenR -= blue-right; blue = --right;
}
}
// Now sort the red and blue regions. Sort the smaller one first by
// recursion, then the larger one by tail-recursion.
if (red - low < high - blue)
{
QuickSort3(low, red);
low = blue;
}
else
{
QuickSort3(blue, high);
high = red;
}
}
}
// Input: two regions [left, mid) and [mid, right), each of a single color
// Output: swap so that the color on the left is now on the right, and vice-versa
void Trade(RBFinger<T> left, RBFinger<T> mid, RBFinger<T> right)
{
int n = Math.Min(mid-left, right-mid);
for (int k = 0; k < n; ++k)
{
--right;
Exchange(left, right);
++left;
}
}
void Exchange(RBFinger<T> f1, RBFinger<T> f2)
{
T x = f1.Item;
f1.SetItem(f2.Item);
f2.SetItem(x);
}
void InsertionSortImpl()
{
RBFinger<T> finger = FindIndex(1);
while (finger.Node != this)
{
RBFinger<T> fingerL = LocateItem(finger, Comparison);
ReInsert(ref finger, fingerL);
++finger;
}
}
internal RBNode<T> InsertNode(int index)
{
RBNode<T> node;
LeftChild = InsertNode(this, this, LeftChild, index, out node);
return node;
}
internal void RemoveNode(int index)
{
LeftChild = DeleteNode(this, LeftChild, index);
if (LeftChild != null)
LeftChild.IsRed = false;
}
internal virtual RBNode<T> NewNode()
{
return new RBNode<T>();
}
internal void ForEach(Action<T> action)
{
foreach (T x in this)
{
action(x);
}
}
internal void ForEachUntil(Func<T, bool> action)
{
foreach (T x in this)
{
if (action(x))
break;
}
}
internal int IndexOf(T item, Func<T,T,bool>AreEqual)
{
if (Comparison != null)
{
RBFinger<T> finger = Find(item, Comparison);
while (finger.Found && !AreEqual(finger.Item, item))
{
++finger;
finger.Found = (finger.IsValid && Comparison(finger.Item, item) == 0);
}
return finger.Found ? finger.Index : -1;
}
else
{
int result = 0;
ForEachUntil( (x) =>
{
if (AreEqual(x, item))
return true;
++ result;
return false;
});
return (result < Count) ? result : -1;
}
}
#region IList<T>
public virtual int IndexOf(T item)
{
return IndexOf(item, (x,y)=>{ return Object.Equals(x,y); });
}
public void Insert(int index, T item)
{
VerifyIndex(index, 1);
RBFinger<T> finger = FindIndex(index, false);
Insert(finger, item);
}
public void RemoveAt(int index)
{
VerifyIndex(index);
SaveTree();
int size = LeftSize;
RBFinger<T> finger = FindIndex(index, true);
RemoveAt(ref finger);
if (LeftChild != null)
LeftChild.IsRed = false;
Verify(size - 1);
}
public T this[int index]
{
get
{
VerifyIndex(index);
RBFinger<T> finger = FindIndex(index);
return finger.Node.GetItemAt(finger.Offset);
}
set
{
VerifyIndex(index);
RBFinger<T> finger = FindIndex(index);
finger.Node.SetItemAt(finger.Offset, value);
}
}
public void Add(T item)
{
SaveTree();
int size = LeftSize;
RBNode<T> node = LeftChild;
if (node == null)
{
node = InsertNode(0);
node.InsertAt(0, item);
}
else
{
while (node.RightChild != null)
node = node.RightChild;
if (node.Size < MaxSize)
{
node.InsertAt(node.Size, item);
}
else
{
node = InsertNode(this.LeftSize);
node.InsertAt(0, item);
}
}
LeftChild.IsRed = false;
Verify(size + 1, false);
}
public void Clear()
{
LeftChild = null;
LeftSize = 0;
}
public bool Contains(T item)
{
RBFinger<T> finger = Find(item, Comparison);
return finger.Found;
}
public void CopyTo(T[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex");
if (arrayIndex + Count > array.Length)
throw new ArgumentException(SR.Get(SRID.Argument_InvalidOffLen));
foreach (T item in this)
{
array[arrayIndex] = item;
++arrayIndex;
}
}
public int Count
{
get { return LeftSize; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(T item)
{
RBFinger<T> finger = Find(item, Comparison);
if (finger.Found)
RemoveAt(ref finger);
if (LeftChild != null)
LeftChild.IsRed = false;
return finger.Found;
}
public IEnumerator<T> GetEnumerator()
{
RBFinger<T> finger = FindIndex(0);
while (finger.Node != this)
{
yield return finger.Node.GetItemAt(finger.Offset);
++finger;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
RBFinger<T> finger = FindIndex(0);
while (finger.Node != this)
{
yield return finger.Node.GetItemAt(finger.Offset);
++finger;
}
}
void VerifyIndex(int index, int delta=0)
{
if (index < 0 || index >= Count+delta)
throw new ArgumentOutOfRangeException("index");
}
#endregion IList<T>
#region Debugging
#if DEBUG
public bool CheckSort { get; set; }
public bool Verify(int expectedSize, bool checkSort = true)
{
if (!CheckSort || Comparison == null)
checkSort = false;
int index = 0, size = 0;
T maxItem = default(T);
BlackHeight = -1;
bool b = Verify(LeftChild, checkSort ? Comparison : null, 0, ref index, ref maxItem, out size) && size == LeftSize && size == expectedSize;
return b;
}
void SaveTree()
{
StringBuilder sb = new StringBuilder();
sb.Append(LeftSize);
SaveTree(LeftChild, sb);
_savedTree = sb.ToString();
}
public void LoadTree(string s)
{
if (s.StartsWith("\"", StringComparison.Ordinal)) s = s.Substring(1);
int index = s.IndexOf('(');
LeftSize = Int32.Parse(s.Substring(0, index), TypeConverterHelper.InvariantEnglishUS);
s = s.Substring(index);
this.LeftChild = LoadTree(ref s);
this.LeftChild.Parent = this;
}
string _savedTree;
#else
void Verify(int expectedSize, bool checkSort = true) {}
void SaveTree() {}
public void LoadTree(string s) {}
#endif // DEBUG
#endregion Debugging
Comparison<T> _comparison;
}
}
| mind0n/hive | Cache/Libs/net46/wpf/src/Framework/MS/Internal/Data/RBTree.cs | C# | mit | 22,932 |
<?php
namespace LinkORB\Framework\Controller;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class AuthenticationController
{
public function loginAction(Application $app, Request $request)
{
return $app['twig']->render('@BaseTemplates/login.html.twig', array(
'error' => $app['security.last_error']($request)
));
}
}
| linkorb/framework | src/Controller/AuthenticationController.php | PHP | mit | 430 |
<?php
namespace Victoire\Widget\CalculatorBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Trigger.
*
* @ORM\Table("vic_widget_calculator_trigger")
* @ORM\Entity
*/
class Trigger
{
const COMPARISON_EQUAL_TO = '==';
const COMPARISON_GREATER_THAN = '>';
const COMPARISON_LESS_THAN = '<';
const COMPARISON_DIFFERENT_TO = '!=';
const COMPARISON_GREATER_OR_EQUAL_TO = '>=';
const COMPARISON_LESS_OR_EQUAL_TO = '<=';
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="target", type="string", length=255)
*/
private $target;
/**
* @var string
*
* @ORM\Column(name="value", type="string", length=255)
*/
private $value;
/**
* @var string
*
* @ORM\Column(name="comparisonSymbol", type="string", length=255)
*/
private $comparisonSymbol;
/**
* @var string
*
* @ORM\ManyToOne(targetEntity="Variable", inversedBy="triggers")
*/
private $variable;
public function __construct()
{
$this->comparisonSymbol = $this::COMPARISON_EQUAL_TO;
}
/**
* Get id.
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set target.
*
* @param string $target
*
* @return Trigger
*/
public function setTarget($target)
{
$this->target = $target;
return $this;
}
/**
* Get target.
*
* @return string
*/
public function getTarget()
{
return $this->target;
}
/**
* Set value.
*
* @param string $value
*
* @return Trigger
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
/**
* Get value.
*
* @return string
*/
public function getValue()
{
return $this->value;
}
/**
* Set variable.
*
* @param \Victoire\Widget\CalculatorBundle\Entity\Variable $variable
*
* @return Trigger
*/
public function setVariable(\Victoire\Widget\CalculatorBundle\Entity\Variable $variable = null)
{
$this->variable = $variable;
return $this;
}
/**
* Get variable.
*
* @return \Victoire\Widget\CalculatorBundle\Entity\Variable
*/
public function getVariable()
{
return $this->variable;
}
/**
* Set comparisonSymbol.
*
* @param string $comparisonSymbol
*
* @return Trigger
*/
public function setComparisonSymbol($comparisonSymbol)
{
$this->comparisonSymbol = $comparisonSymbol;
return $this;
}
/**
* Get comparisonSymbol.
*
* @return string
*/
public function getComparisonSymbol()
{
return $this->comparisonSymbol;
}
}
| FriendsOfVictoire/WidgetCalculatorBundle | Entity/Trigger.php | PHP | mit | 3,007 |
# This is modified from a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
import array
import struct
import zlib
from enum import Enum
from pkg_resources import parse_version
from kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO
if parse_version(ks_version) < parse_version('0.7'):
raise Exception(
"Incompatible Kaitai Struct Python API: 0.7 or later is required, but you have %s" % (ks_version))
from .cfg_2 import Cfg2
from .header import Header
from .data import Data
from .cfg_3 import Cfg3
from .command import Command
def _kaitai_repr(self):
_repr_list = []
for item in vars(self):
if not item.startswith('_'):
_r = getattr(self, item)
if type(_r) in (int, float, str, bytes, bool):
_repr_list.append("=".join((item, _r.__repr__())))
else:
_repr_list.append(item)
return "<" + self.__class__.__name__ + " |" + ", ".join(_repr_list) + ">"
def _enum_repr(self):
_repr_list = []
for item in ("name", "value"):
_r = getattr(self, item)
_repr_list.append("=".join((item, _r.__repr__())))
return "<" + self.__class__.__name__[:-4] + " |" + ", ".join(_repr_list) + ">"
def _kaitai_show(self, parent_path=' '):
if type(self) in (int, float, str, bytes, bool):
print(" == ".join((parent_path, self.__repr__())))
elif type(self) == list:
for i, item in enumerate(self):
try:
item.show('{}[{}]'.format(parent_path,i))
except:
_kaitai_show(item,'{}[{}]'.format(parent_path,i))
else:
for item in sorted(vars(self)):
if not item.startswith('_'):
_r = getattr(self, item)
try:
_r.show(parent_path+'.'+item)
except:
_kaitai_show(_r,parent_path+'.'+item)
def _enum_show(self, parent_path=' '):
for item in ("name", "value"):
_r = getattr(self, item)
print(parent_path+'.'+item+' == '+_r.__repr__())
KaitaiStruct.__repr__ = _kaitai_repr
Enum.__repr__ = _enum_repr
KaitaiStruct.show = _kaitai_show
Enum.show = _enum_show
#msg.show()
class PhasorMessage(KaitaiStruct):
def __repr__(self):
_repr_list = [
"time=" + str(self.time)] if self.fracsec.fraction_of_second else []
for item in vars(self):
if not item.startswith('_'):
_r = getattr(self, item)
if type(_r) in (int, float, str, bytes):
_repr_list.append("=".join((item, _r.__repr__())))
else:
_repr_list.append(item)
return "<" + self.__class__.__name__ + " |" + ", ".join(_repr_list) + ">"
def show(self, parent_path=' '):
if self.fracsec.fraction_of_second:
print(parent_path+'.time == '+str(self.time))
_kaitai_show(self, parent_path)
def __init__(self, _io, _parent=None, _root=None, _mini_cfgs=None):
self._io = _io
self._parent = _parent
self._root = _root if _root else self
self._pkt_pos = self._io.pos()
self.sync = self._root.SyncWord(self._io, self, self._root)
self.framesize = self._io.read_u2be()
self.idcode = self._io.read_u2be()
self._mini_cfg = _mini_cfgs.mini_cfg[self.idcode]
self.soc = self._io.read_u4be()
self.fracsec = self._root.Fracsec(self._io, self, self._root,
self._mini_cfg.time_base.time_base if self._mini_cfg else None)
_on = self.sync.frame_type.value
if _on == 0:
if self._mini_cfg:
self.data = Data(self._io, _mini_cfg=self._mini_cfg)
else:
self.data = self._io.read_bytes((self.framesize - 16))
elif _on == 3:
self._raw_data = self._io.read_bytes((self.framesize - 16))
io = KaitaiStream(BytesIO(self._raw_data))
self.data = Cfg2(io)
_mini_cfgs.add_cfg(self.idcode, self.data)
elif _on == 4:
self._raw_data = self._io.read_bytes((self.framesize - 16))
io = KaitaiStream(BytesIO(self._raw_data))
self.data = Command(io)
elif _on == 5:
_mini_cfgs.add_cfg(self.raw_pkt)
self._raw_data = self._io.read_bytes((self.framesize - 16))
io = KaitaiStream(BytesIO(self._raw_data))
self.data = Cfg3(io)
elif _on == 2:
self._raw_data = self._io.read_bytes((self.framesize - 16))
io = KaitaiStream(BytesIO(self._raw_data))
self.data = Cfg2(io)
elif _on == 1:
self._raw_data = self._io.read_bytes((self.framesize - 16))
io = KaitaiStream(BytesIO(self._raw_data))
self.data = Header(io)
self.chk = self._io.read_u2be()
class SyncWord(KaitaiStruct):
class FrameTypeEnum(Enum):
data = 0
header = 1
cfg1 = 2
cfg2 = 3
cmd = 4
cfg3 = 5
class VersionNumberEnum(Enum):
c_37_118_2005 = 1
c_37_118_2_2011 = 2
def __init__(self, _io, _parent=None, _root=None):
self._io = _io
self._parent = _parent
self._root = _root if _root else self
self.magic = self._io.ensure_fixed_contents(struct.pack('1b', -86))
self.reserved = self._io.read_bits_int(1) != 0
self.frame_type = self._root.SyncWord.FrameTypeEnum(
self._io.read_bits_int(3))
self.version_number = self._root.SyncWord.VersionNumberEnum(
self._io.read_bits_int(4))
class Fracsec(KaitaiStruct):
def __repr__(self):
_repr_list = ["fraction_of_second=" +
str(self.fraction_of_second)] if self.fraction_of_second else []
for item in vars(self):
if not item.startswith('_'):
_r = getattr(self, item)
if type(_r) in (int, float, str):
_repr_list.append("=".join((item, _r.__repr__())))
else:
_repr_list.append(item)
return "<" + self.__class__.__name__ + " |" + ", ".join(_repr_list) + ">"
def show(self, parent_path):
if self.fraction_of_second:
print(parent_path+'.fraction_of_second == ' + str(self.fraction_of_second))
_kaitai_show(self, parent_path)
class LeapSecondDirectionEnum(Enum):
add = 0
delete = 1
class MsgTqEnum(Enum):
normal_operation_clock_locked_to_utc_traceable_source = 0
time_within_10_to_9_s_of_utc = 1
time_within_10_to_8_s_of_utc = 2
time_within_10_to_7_s_of_utc = 3
time_within_10_to_6_s_of_utc = 4
time_within_10_to_5_s_of_utc = 5
time_within_10_to_4_s_of_utc = 6
time_within_10_to_3_s_of_utc = 7
time_within_10_to_2_s_of_utc = 8
time_within_10_to_1_s_of_utc = 9
time_within_1_s_of_utc = 10
time_within_10_s_of_utc = 11
fault_clock_failure_time_not_reliable = 15
def __init__(self, _io, _parent=None, _root=None, _time_base=None):
self._io = _io
self._parent = _parent
self._root = _root if _root else self
self._time_base = _time_base
self.reserved = self._io.read_bits_int(1) != 0
self.leap_second_direction = self._root.Fracsec.LeapSecondDirectionEnum(
self._io.read_bits_int(1))
self.leap_second_occurred = self._io.read_bits_int(1) != 0
self.leap_second_pending = self._io.read_bits_int(1) != 0
self.time_quality = self._root.Fracsec.MsgTqEnum(
self._io.read_bits_int(4))
self.raw_fraction_of_second = self._io.read_bits_int(24)
@property
def fraction_of_second(self):
if hasattr(self, '_m_fraction_of_second'):
return self._m_fraction_of_second if hasattr(self, '_m_fraction_of_second') else None
if self._time_base:
self._m_fraction_of_second = self.raw_fraction_of_second / self._time_base
return self._m_fraction_of_second if hasattr(self, '_m_fraction_of_second') else None
@property
def time(self):
if hasattr(self, '_m_time'):
return self._m_time if hasattr(self, '_m_time') else None
self._m_time = self.soc + self.fracsec.fraction_of_second
return self._m_time if hasattr(self, '_m_time') else None
@property
def chk_body(self):
if hasattr(self, '_m_chk_body'):
return self._m_chk_body if hasattr(self, '_m_chk_body') else None
_pos = self._io.pos()
self._io.seek(0)
self._m_chk_body = self._io.read_bytes((self.framesize - 2))
self._io.seek(_pos)
return self._m_chk_body if hasattr(self, '_m_chk_body') else None
@property
def raw_pkt(self):
if hasattr(self, '_m_pkt'):
return self._m_pkt if hasattr(self, '_m_pkt') else None
_pos = self._io.pos()
self._io.seek(self._pkt_pos)
self._m_pkt = self._io.read_bytes(self.framesize)
self._io.seek(_pos)
return self._m_pkt if hasattr(self, '_m_pkt') else None
| sonusz/PhasorToolBox | phasortoolbox/parser/common.py | Python | mit | 9,531 |
require "cm-writeonce/version"
module CmWriteonce
require 'createsend'
def self.initialize(cm_key, cm_list, filename)
@cm_key = cm_key
@cm_list = cm_list
@now = DateTime.now.to_time.to_i
@auth = {:api_key => @cm_key}
cs = CreateSend::CreateSend.new @auth
i = 0
File.open(filename).read.split("\n").each do |line|
begin
name, email_address, street_address, city, province, country, postal_code, telephone, initial_source, campaign, gender, language_preference = line.split(",")
if i == 0
raise "Could not find correct headers in CSV file!" unless name == "Name" &&
email_address == "Email Address" &&
street_address == "Street Address" &&
city == "City" &&
province == "Province" &&
country == "Country" &&
postal_code == "Postal Code" &&
telephone == "Telephone" &&
initial_source == "Initial Source" &&
campaign == "Campaign" &&
gender == "Gender" &&
language_preference == "Language Preference"
else
email_address.downcase!
postal_code.upcase!
postal_code = postal_code.gsub(/\s+/, "")
province = province.upcase!
country = country.split(' ').map(&:capitalize).join(' ')
telephone = telephone.gsub(/([-() ])/, '')
gender.capitalize!
language_preference.upcase!
custom_fields = [ { :Key => 'Street Address', :Value => street_address, :Clear => false },
{ :Key => 'City', :Value => city, :Clear => false },
{ :Key => 'Province', :Value => province, :Clear => false },
{ :Key => 'Country', :Value => country, :Clear => false },
{ :Key => 'Postal Code', :Value => postal_code, :Clear => false },
{ :Key => 'Telephone', :Value => telephone, :Clear => false },
{ :Key => 'Campaign', :Value => campaign, :Clear => false },
{ :Key => 'Gender', :Value => gender, :Clear => false },
{ :Key => 'Language Preference', :Value => language_preference, :Clear => false } ]
begin
details = CreateSend::Subscriber.new @auth, @cm_list, email_address
details.update email_address, name, custom_fields, true
puts "Updated " << name << " <" << email_address << ">"
rescue Exception => e
if e.message == 'The CreateSend API responded with the following error - 203: Subscriber not in list or has already been removed.'
custom_fields << { :Key => 'Initial Source', :Value => initial_source }
email_address = CreateSend::Subscriber.add @auth, @cm_list, email_address, name, custom_fields, true
puts "Added " << name << " <" << email_address << ">"
end
end
end
i = i + 1
rescue Exception => e
puts e.message
puts "Expecting: Name,Email Address,Address,City,Province,Country,Postal Code,Telephone,Initial Source,Campaign,Gender,Language Preference"
abort
end
end
end
end
| drewgillson/cm-writeonce | lib/cm-writeonce.rb | Ruby | mit | 4,212 |
import {getTims} from '../api/api';
export function loadData() {
return getTims().then(data => {
const parser = new DOMParser();
const doc = parser.parseFromString(data, 'text/xml');
if (doc.documentElement.nodeName === 'parseerror') {
throw new Error(doc);
}
return toJSON(doc);
}).catch(e => {
console.error(e);
});
}
function toJSON(doc) {
const json = {
published: null,
disruptions: []
};
const { header, disruptions } = getChildren(doc.documentElement, 'header', 'disruptions');
if (header) {
const publishedElement = getChild(header, 'publishdatetime');
if (publishedElement) {
const pubDateAttr = getAttr(publishedElement, 'canonical');
if (pubDateAttr) {
json.published = pubDateAttr.value;
}
}
const refreshRateElement = getChild(header, 'refreshrate');
if (refreshRateElement) {
const refreshRate = Number(refreshRateElement.textContent);
if (!isNaN(refreshRate) && refreshRate > 0) {
json.refreshRate = refreshRate;
}
}
}
if (disruptions) {
json.disruptions = mapDisruptions(disruptions);
}
return json;
}
function mapDisruptions(disruptions) {
const res = {};
for (let i = 0; i < disruptions.children.length; ++i) {
const disr = disruptions.children[i];
const idAttr = getAttr(disr, 'id');
if (!idAttr || !idAttr.value) {
continue;
}
const props = {};
for (let j = 0; j < disr.children.length; ++j) {
const propElem = disr.children[j];
if (propElem.children.length === 0) {
props[propElem.nodeName] = propElem.textContent;
} else if (propElem.nodeName.toLowerCase() === 'causearea') {
const displayPoint = getChild(propElem, 'displaypoint');
if (displayPoint) {
const point = getChild(displayPoint, 'point');
if (point) {
const coords = getChild(point, 'coordinatesll');
if (coords) {
const split = coords.textContent.split(',');
if (split.length === 2) {
props.coords = {
lat: parseFloat(split[1]),
lng: parseFloat(split[0])
};
}
}
}
}
}
}
res[idAttr.value] = props;
}
return res;
}
function getChildren(element, ...names) {
const res = {};
for (let i = 0; i < element.children.length; ++i) {
const name = element.children[i].nodeName.toLowerCase();
if (names.find(n => n === name)) {
res[name] = element.children[i];
}
}
return res;
}
function getChild(element, name) {
const res = getChildren(element, name);
return res[name] || null;
}
function getAttr(element, name) {
for (let i = 0; i < element.attributes.length; ++i) {
if (element.attributes[i].name === name) {
return element.attributes[i];
}
}
return null;
} | kirill-kruchkov/tfl | src/app/tims.js | JavaScript | mit | 2,910 |
describe :next do
it "runs the given lambda if called from the :run block" do
m = Moron_Text.new(<<-EOF)
COMM 1 /* 1
COMM 2 /* 1
EOF
stack = []
l = lambda { |name, line, moron| stack << :lambda }
m.run(l) { |name, line, moron| stack << :block; moron.next }
stack.should == [:block, :lambda, :block, :lambda]
end
it "runs the given Class :run block if called from the instance :run lambda" do
stack = []
c = Class.new(Moron_Text)
c.run { |name, line, moron| stack << :class }
o = c.new(<<-EOF)
COMM 3 /* 2
COMM 4 /* 2
EOF
l = lambda { |name, line, moron| stack << :lambda; moron.next }
o.run(l)
stack.should == [:lambda, :class, :lambda, :class]
end
it "runs the given Class :run block if called from: instance :run lambda and block" do
stack = []
c = Class.new(Moron_Text)
c.run { |name, line, moron| stack << :class }
o = c.new(<<-EOF)
COMM 5 /* 3
COMM 6 /* 3
EOF
l = lambda { |name, line, moron| stack << :lambda; moron.next }
o.run(l) { |name, line, moron| stack << :block; moron.next }
stack.should == [:block, :lambda, :class, :block, :lambda, :class]
end
it "fails w/ Typo if :next is called in Class :run" do
stack = []
c = Class.new(Moron_Text)
c.run { |name, line, moron| moron.next if name == 'COMM 8' }
o = c.new(<<-EOF)
COMM 7 /* 4
COMM 8 /* 4
COMM 9 /* 4
EOF
lambda {
o.run { |name, line, moron| stack << :block; moron.next }
}.should.raise(Moron_Text::TYPO).
message.should =~ /Typo. COMM 8/
end
end # === describe :next
| da99/moron_text | specs/0031-next.rb | Ruby | mit | 1,638 |
if not String.method_defined? :to_underscore
class String
# ruby mutation methods have the expectation to return self if a mutation
# occurred, nil otherwise.
# (see http://www.ruby-doc.org/core-1.9.3/String.html#method-i-gsub-21)
def to_underscore!
gsub!(/(.)([A-Z])/,'\1_\2') && downcase!
end
def to_underscore
dup.tap { |s| s.to_underscore! }
end
end
end
| binford2k/arnold | gem/lib/arnold/monkeypatch.rb | Ruby | mit | 412 |
'use strict';
angular.module('cocoApp')
.directive('loginform', [function () {
return {
restrict: 'E',
controller: 'LoginInterceptCtrl',
scope: {
eventid: '='
},
templateUrl: 'partials/login.html'
};
}]);
| blang/coco | app/scripts/directives/loginform.js | JavaScript | mit | 256 |
/*
Copyright (c) 2012 Greg Reimer ( http://obadger.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.
*/
(function(w, d, $){
// defaults
var defaultArgs = {
rays: 16,
originX: '50%',
originY: '50%',
bgColorStart: 'rgba(0,0,0,0.1)',
bgColorEnd: 'rgba(0,0,0,0.2)',
rayColorStart: 'hsla(0,0%,100%,0.2)',
rayColorEnd: 'hsla(0,0%,100%,0.3)',
sizingRatio: 1
};
$.fn.pow = (function(){
return function(args){
// bail if none
if (this.length === 0) { return; }
// set defaults
args = $.extend({}, defaultArgs, args);
// set vars and grab a few values to use later
var $el = this.eq(0);
var width = $el.outerWidth();
var height = $el.outerHeight();
var offset = $el.offset();
var originX = (parseFloat(args.originX) || 0) / 100;
var originY = (parseFloat(args.originY) || 0) / 100;
// center rays on a given element
if (args.originEl) {
var $oel = $(args.originEl);
if ($oel.length) {
var oOffset = $oel.offset();
var oWidth = $oel.outerWidth();
var oHeight = $oel.outerHeight();
originX = (((oOffset.left - offset.left) + (oWidth / 2)) / width);
originY = (((oOffset.top - offset.top) + (oHeight / 2)) / height);
}
}
// convert to absolute lengths
originX = width * originX;
originY = height * originY;
// find maximum distance to a corner
var radius = Math.max.apply(Math, [
{x:0,y:0},
{x:width,y:0},
{x:0,y:height},
{x:width,y:height}
].map(function(c){
// use the pythagorean theorem, luke
return Math.sqrt(Math.pow(c.x - originX, 2) + Math.pow(c.y - originY, 2));
}));
try{
var canvas = $('<canvas width="'+width+'" height="'+height+'" style="position:fixed;top:-999999px"></canvas>').appendTo(d.body).get(0);
var ctx = canvas.getContext('2d');
} catch(err) {
return;
}
// build the background gradient
var bgGrad = ctx.createRadialGradient(
originX, originY, 0, // inner circle, infinitely small
originX, originY, radius // outer circle, will just cover canvas area
);
bgGrad.addColorStop(0, args.bgColorStart);
bgGrad.addColorStop(1, args.bgColorEnd);
// build the foreground gradient
var rayGrad = ctx.createRadialGradient(
originX, originY, 0, // inner circle, infinitely small
originX, originY, radius // outer circle, will just cover canvas area
);
rayGrad.addColorStop(0, args.rayColorStart);
rayGrad.addColorStop(1, args.rayColorEnd);
// fill in bg
ctx.fillStyle = bgGrad;
ctx.fillRect(0,0,width,height);
// draw rays
ctx.fillStyle = rayGrad;
ctx.beginPath();
var spokeCount = args.rays * 2;
ctx.moveTo(originX, originY);
for (var i=0; i<args.rays; i++){
for (var j=0; j<2; j++) {
var thisSpoke = i * 2 + j;
var traversal = thisSpoke / spokeCount;
var ax = originX + radius * 1.5 * Math.cos(traversal * 2 * Math.PI);
var ay = originY + radius * 1.5 * Math.sin(traversal * 2 * Math.PI);
ctx.lineTo(ax,ay);
}
ctx.lineTo(originX, originY);
}
ctx.fill();
// set the data as css to the element
var data = canvas.toDataURL("image/png");
$(canvas).remove();
$el.css({
'background-image':'url("'+data+'")',
'background-repeat':'no-repeat',
'background-position':'50% 50%',
'background-size':'cover'
});
};
})();
})(window, document, jQuery);
| chatgris/sucreries | lib/vendor/assets/javascripts/sucreries/pow/pow.js | JavaScript | mit | 4,672 |
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
protected $redirectTo = '/';
use AuthenticatesUsers;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
public function username() {
return 'kasutajanimi';
}
public function logout(Request $request)
{
Auth::logout();
Session::flush();
return redirect()->back();
}
} | Volcania/LAFF | app/Http/Controllers/Auth/LoginController.php | PHP | mit | 1,178 |
# encoding: utf-8
# (c) 2011 Martin Kozák (martinkozak@martinkozak.net)
require "abstract"
##
# Base +Unified Queues+ module.
#
module UnifiedQueues
##
# Universal single queue interface.
#
class Single
##
# Abstract single driver class.
# @abstract
#
class Driver
##
# Holds native object.
# @return [Object]
#
attr_accessor :native
@native
##
# Constructor.
#
def initialize(cls, *args, &block)
if self.instance_of? UnifiedQueues::Single::Driver
not_implemented
end
if cls.kind_of? Class
@native = cls::new(*args, &block)
else
@native = cls
end
end
##
# Pushes the value into the queue.
#
# @param [Object] value value for push
# @param [Object] key key for priority queues
# @abstract
#
def push(value, key = value, &block)
not_implemented
end
alias :<< :push
##
# Pops value out of the queue.
#
# @param [Boolean|Integer] blocking +true+ or timeout if it should block, +false+ otherwise
# @param [Object] queue value
# @abstract
#
def pop(blocking = false, &block)
not_implemented
end
##
# Indicates queue is empty.
#
# @param [Boolean] +true+ if it's, +false+ otherwise
# @abstract
#
def empty?(&block)
not_implemented
end
##
# Clears the queue.
# @abstract
#
def clear!(&block)
while not self.pop.nil?
end
end
alias :clear :clear!
##
# Returns length of the queue.
#
# @return [Integer]
# @abstract
#
def length(&block)
not_implemented
end
alias :size :length
##
# Returs type of the queue. Queue can be +:linear+ which means,
# calls values are returned using +return+ or +:evented+
# which indicates necessity of callbacks.
#
# @return [:linear, :evented]
# @abstract
#
def type
not_implemented
end
##
# Indicates, driver is evented so expexts callbacks.
# @return [Boolean] +true+ if it is, +false+ otherwise
#
def evented?
self.type == :evented
end
##
# Indicates, driver is evented so expexts callbacks.
# @return [Boolean] +true+ if it is, +false+ otherwise
#
def linear?
self.type == :linear
end
end
end
end | martinkozak/unified-queues | lib/unified-queues/single/driver.rb | Ruby | mit | 3,560 |
package view;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.UUID;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import controller.EnterKeyListenerForButtons;
import controller.MandatoryStringCellEditor;
import controller.TableValidator;
import controller.UsernameCellEditor;
import main.CourierSystem;
import model.Employee;
import model.EmployeeRole;
import net.miginfocom.swing.MigLayout;
public class EmployeeManagement extends Container {
private static final long serialVersionUID = 1L;
private JTable table;
private EmployeeTableModel employeeTable;
public EmployeeManagement() {
employeeTable = new EmployeeTableModel();
setLayout(new MigLayout("", "[grow][50%][grow][10]", "[25][40][5][grow][][20]"));
JLabel lblEmployeeManagement = new JLabel("Employee Management");
lblEmployeeManagement.setFont(new Font("Tahoma", Font.BOLD, 16));
add(lblEmployeeManagement, "cell 0 0 3 1,alignx center,aligny center");
JButton btnAddEmployee = new JButton("Add Employee");
add(btnAddEmployee, "cell 0 1,alignx center");
btnAddEmployee.addKeyListener(new EnterKeyListenerForButtons(btnAddEmployee));
JButton btnRemoveEmployee = new JButton("Remove Employee");
add(btnRemoveEmployee, "cell 1 1,alignx center");
btnRemoveEmployee.addKeyListener(new EnterKeyListenerForButtons(btnRemoveEmployee));
JButton btnSaveChanges = new JButton("Save Changes");
add(btnSaveChanges, "cell 2 1");
btnSaveChanges.addKeyListener(new EnterKeyListenerForButtons(btnSaveChanges));
JScrollPane scrollPane = new JScrollPane();
add(scrollPane, "cell 0 3 3 1,grow");
table = new JTable(employeeTable);
table.setCellSelectionEnabled(true);
scrollPane.setViewportView(table);
table.setColumnSelectionAllowed(true);
table.getColumnModel().getColumn(1).setCellEditor(new MandatoryStringCellEditor(new JTextField()));
table.getColumnModel().getColumn(3).setCellEditor(new UsernameCellEditor(new JTextField()));
JComboBox<EmployeeRole> roleComboBox = new JComboBox<EmployeeRole>();
roleComboBox.addItem(EmployeeRole.Administrator);
roleComboBox.addItem(EmployeeRole.Courier);
roleComboBox.addItem(EmployeeRole.OrderTaker);
table.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(roleComboBox));
JLabel lblNewLabel = new JLabel(" ");
add(lblNewLabel, "cell 0 4");
btnAddEmployee.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
employeeTable.addRow(new Employee());
btnAddEmployee.setEnabled(false);
}
});
btnRemoveEmployee.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (table.getCellEditor() != null)
table.getCellEditor().cancelCellEditing();
int selectedRow = table.getSelectedRow();
System.out.println("Selected Row: " + selectedRow);
Employee employee = employeeTable.employees.get(selectedRow);
if (employee.id != 0) {
if (!CourierSystem.currentUser.equals(employee)) {
employee.ArchiveEmployee();
saveAction();
}
else {
JOptionPane.showMessageDialog(btnRemoveEmployee, "You cannot delete yourself.");
}
}
employeeTable.removeRow(selectedRow);
btnAddEmployee.setEnabled(true);
}
});
btnSaveChanges.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveAction();
btnAddEmployee.setEnabled(true);
}
});
}
private void saveAction() {
if (!TableValidator.isValid(table))
return;
try {
UUID uuid = UUID.randomUUID();
CourierSystem.Employees = new HashMap<String, Employee>();
for (Employee emp : employeeTable.employees) {
if (emp.userName == "" && emp.role == EmployeeRole.Courier) {
emp.userName = "courier" + uuid.toString();
}
CourierSystem.Employees.put(emp.name, emp);
}
CourierSystem.UpdateEmployees();
} catch (Exception e1) {
e1.printStackTrace();
} finally {
employeeTable.refresh();
}
}
}
| zkastl/AcmeCourierService | AcmeCourierSystem/src/view/EmployeeManagement.java | Java | mit | 4,397 |
module Holistics
class SubcommandBase < Thor
def self.banner(command, namespace = nil, subcommand = false)
"#{basename} #{subcommand_prefix} #{command.usage}"
end
def self.subcommand_prefix
self.name.gsub(%r{.*::}, '').gsub(%r{^[A-Z]}) { |match| match[0].downcase }.gsub(%r{[A-Z]}) { |match| "_#{match[0].downcase}" }
end
end
end | pmint93/holistics-cli | lib/holistics/subcommand_base.rb | Ruby | mit | 362 |
<?php
namespace DeviceBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class DeviceBundle extends Bundle
{
}
| sstie/app2_repo | src/DeviceBundle/DeviceBundle.php | PHP | mit | 119 |
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("Aliencube.GitHub.Markdown.ViewModels")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7465ee4c-138b-4d14-a809-fad81d0b3f16")]
| aliencube/GitHub-Flavoured-Markdown-Converter | SourceCodes/04_ViewModels/GitHub.Markdown.ViewModels/Properties/AssemblyInfo.cs | C# | mit | 577 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This bot regenerates the page VEIDs
The following parameters are supported:
-debug If given, doesn't do any real changes, but only shows
what would have been changed.
"""
__version__ = '$Id: basic.py 4946 2008-01-29 14:58:25Z wikipedian $'
import wikipedia
import pagegenerators, catlib, re, socket, sys
from iplib import CIDR, IPv4Address
class IpNetworkBot:
def __init__(self, nets_generator, debug):
"""
Constructor. Parameters:
* generator - The page generator that determines on which pages
to work on.
* debug - If True, doesn't do any real changes, but only shows
what would have been changed.
"""
self.nets_generator = nets_generator
self.nets = dict()
self.debug = debug
def registerIpNet(self, page):
if ":" in page.title(): return
text = page.get()
in_ipnettpl = False
private = False
for line in text.split("\n"):
if line.startswith("{{IPNetwork"):
in_ipnettpl = True
continue
if line.startswith("}}"):
in_ipnettpl = False
continue
if in_ipnettpl:
if line.startswith("|PRIVATE=1"):
private = True
if not private:
print page.title()
def run(self):
print "# generated by netlist.py"
for page in self.nets_generator:
self.registerIpNet(page)
def main():
# The generator gives the pages that should be worked upon.
gen = None
# If debug is True, doesn't do any real changes, but only show
# what would have been changed.
debug = False
wantHelp = False
# Parse command line arguments
for arg in wikipedia.handleArgs():
if arg.startswith("-debug"):
debug = True
else:
wantHelp = True
if not wantHelp:
# The preloading generator is responsible for downloading multiple
# pages from the wiki simultaneously.
cat = catlib.Category(wikipedia.getSite(), 'Category:%s' % 'IP-Network')
nets_gen = pagegenerators.CategorizedPageGenerator(cat, start = None, recurse = False)
nets_gen = pagegenerators.PreloadingGenerator(nets_gen)
bot = IpNetworkBot(nets_gen, debug)
bot.run()
else:
wikipedia.showHelp()
if __name__ == "__main__":
try:
main()
finally:
wikipedia.stopme()
| sicekit/sicekit | robots/tool-list_networks.py | Python | mit | 2,437 |
using System;
using NetOffice;
using NetOffice.Attributes;
namespace NetOffice.WordApi.Enums
{
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// </summary>
///<remarks> MSDN Online Documentation: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.WdExportItem"/> </remarks>
[SupportByVersion("Word", 12,14,15,16)]
[EntityType(EntityType.IsEnum)]
public enum WdExportItem
{
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// </summary>
/// <remarks>0</remarks>
[SupportByVersion("Word", 12,14,15,16)]
wdExportDocumentContent = 0,
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// </summary>
/// <remarks>7</remarks>
[SupportByVersion("Word", 12,14,15,16)]
wdExportDocumentWithMarkup = 7
}
} | NetOfficeFw/NetOffice | Source/Word/Enums/WdExportItem.cs | C# | mit | 781 |
module UserAnnouncementsHelper
include UserAnnouncements::AdminHelper
include UserAnnouncements::RolesHelper
include UserAnnouncements::MiscHelper
include UserAnnouncements::StyleHelper
include UserAnnouncements::ShowAnnouncements
end | stevedowney/user_announcements | app/helpers/user_announcements_helper.rb | Ruby | mit | 244 |
class Sites::Settings::CategoriesController < Sites::Settings::ApplicationController
private
# Never trust parameters from the scary internet, only allow the white list through.
def category_params
params.require(:category).permit(:name)
end
def collection_url
site_settings_categories_url
end
end
| wuwx/MultiTenantCMS | app/controllers/sites/settings/categories_controller.rb | Ruby | mit | 338 |
<?php
namespace League\Flysystem\EventableFilesystem\Event;
use League\Event\AbstractEvent;
use League\Flysystem\FilesystemInterface;
class Before extends AbstractEvent
{
/**
* @var FilesystemInterface
*/
protected $filesystem;
/**
* @var string
*/
protected $method;
/**
* @var array
*/
protected $arguments;
/**
* @var mixed
*/
protected $result = false;
/**
* @param FilesystemInterface $filesystem
* @param string $method
* @param array $arguments
*/
public function __construct(FilesystemInterface $filesystem, $method, array $arguments)
{
$this->filesystem = $filesystem;
$this->method = $method;
$this->arguments = $arguments;
}
/**
* @return FilesystemInterface
*/
public function getFilesystem()
{
return $this->filesystem;
}
/**
* Get the event name.
*
* @return string event name
*/
public function getName()
{
$method = $this->getMethod();
return 'before.'.strtolower($method);
}
/**
* Get the called method name.
*
* @return string method
*/
public function getMethod()
{
return $this->method;
}
/**
* Get the passed arguments.
*
* @return array method arguments
*/
public function getArguments()
{
return $this->arguments;
}
/**
* Get an argument by key.
*
* @param string $key argument key
* @param mixed $default default return value
*
* @return mixed
*/
public function getArgument($key, $default = null)
{
if (! array_key_exists($key, $this->arguments)) {
return $default;
}
return $this->arguments[$key];
}
/**
* Set an argument value.
*
* @param string $key
* @param mixed $value
*
* @return $this
*/
public function setArgument($key, $value)
{
$this->arguments[$key] = $value;
return $this;
}
/**
* Set the arguments.
*
* @param array $arguments
*
* @return self
*/
public function setArguments(array $arguments)
{
$this->arguments = array_merge($this->arguments, $arguments);
return $this;
}
/**
* Set the result, used when the operation is canceled.
*
* @param mixed $result
*
* @return self
*/
public function setResult($result)
{
$this->result = $result;
return $this;
}
/**
* Get the result, used when the operation is canceled.
*
* @return mixed
*/
public function getResult()
{
return $this->result;
}
/**
* Cancel the operation.
*
* @param mixed $result
*/
public function cancelOperation($result = false)
{
$this->setResult($result);
$this->stopPropagation();
}
}
| thephpleague/flysystem-eventable-filesystem | src/Event/Before.php | PHP | mit | 3,029 |
'use strict'
import Macro from './macro.js'
/**
* マクロスタック
*/
export default class MacroStack {
/**
* コンストラクタ
*/
constructor () {
/**
* [*store manual] スタックの中身
* @private
* @type {Array}
*/
this.stack = []
}
/**
* スタックへ積む
* @param {Macro} macro マクロ
*/
push (macro) {
this.stack.push(macro)
}
/**
* スタックから降ろす
* @return {Macro} マクロ
*/
pop () {
return this.stack.pop()
}
/**
* スタックが空かどうか
* @return {boolean} 空ならtrue
*/
isEmpty () {
return this.stack.length <= 0
}
/**
* スタックの一番上のマクロを返す
* @return {Macro} マクロ
*/
getTop () {
if (this.isEmpty()) {
return null
} else {
return this.stack[this.stack.length - 1]
}
}
/**
* 状態を保存
* @param {number} tick 時刻
* @return {object} 保存データ
*/
store (tick) {
// Generated by genStoreMethod.js
let data = {}
// 保存
// 以下、手動で復元する
// store this.stack
data.stack = []
this.stack.forEach((macro) => {
data.stack.push(macro.store(tick))
})
return data
}
/**
* 状態を復元
* @param {object} data 復元データ
* @param {number} tick 時刻
* @param {AsyncTask} task 非同期処理管理
*/
restore (data, tick, task) {
// Generated by genRestoreMethod.js
// 復元
// 以下、手動で復元する
// restore this.stack
this.stack = []
// console.log(data)
data.stack.forEach((macroData) => {
let macro = new Macro('')
macro.restore(macroData, tick, task)
this.stock.push(macro)
})
}
}
| okayumoka/Ponkan2 | src/macro/macro-stack.js | JavaScript | mit | 1,794 |
<?php
/*
Safe sample
input : use fopen to read /tmp/tainted.txt and put the first line in $tainted
sanitize : use mysql_real_escape_string via an object
construction : interpretation with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$handle = @fopen("/tmp/tainted.txt", "r");
if ($handle) {
if(($tainted = fgets($handle, 4096)) == false) {
$tainted = "";
}
fclose($handle);
} else {
$tainted = "";
}
class Sanitize{
public function sanitize($input){
return mysql_real_escape_string($input);
}
}
$temp = new Sanitize();
$tainted = $temp->sanitize($tainted);
$query = "user[username=' $tainted ']";
$xml = simplexml_load_file("users.xml");//file load
echo "query : ". $query ."<br /><br />" ;
$res=$xml->xpath($query);//execution
print_r($res);
echo "<br />" ;
?> | stivalet/PHP-Vulnerability-test-suite | Injection/CWE_91/safe/CWE_91__fopen__object-func_mysql_real_escape_string__username-interpretation_simple_quote.php | PHP | mit | 1,670 |
<?php
/*
Safe sample
input : use fopen to read /tmp/tainted.txt and put the first line in $tainted
sanitize : use of the function addslashes
construction : use of sprintf via a %s with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$handle = @fopen("/tmp/tainted.txt", "r");
if ($handle) {
if(($tainted = fgets($handle, 4096)) == false) {
$tainted = "";
}
fclose($handle);
} else {
$tainted = "";
}
$tainted = addslashes($tainted);
$query = sprintf("cat '%s'", $tainted);
$ret = system($query);
?> | stivalet/PHP-Vulnerability-test-suite | Injection/CWE_78/safe/CWE_78__fopen__func_addslashes__cat-sprintf_%s_simple_quote.php | PHP | mit | 1,396 |
<?php
class DepartmentObj extends FactoryObj
{
public function __construct($deptid=null)
{
parent::__construct("deptid", "departments", $deptid);
}
public function pre_save()
{
if(!$this->is_valid_id()) {
if(!isset($this->appkey) or empty($this->appkey)) {
do {
$this->appkey = $this->generate_appkey();
} while($this->appkey_exists($this->appkey));
}
$parse = @parse_url($this->apphost);
$this->apphost = (isset($parse['host'])) ? $parse['host'] : $this->apphost;
$this->regdate = date("Y-m-d H:i:s");
}
}
public function pre_load()
{
if(!$this->is_valid_id() and isset($this->appkey)) {
$this->deptid = $this->load_deptid_from_appkey($this->appkey);
}
}
private function load_deptid_from_appkey($appkey)
{
$conn = Yii::app()->db;
$query = "
SELECT deptid
FROM {{departments}}
WHERE appkey = :appkey;
";
$command = $conn->createCommand($query);
$command->bindParam(":appkey",$appkey);
return $command->queryScalar();
}
public function user_has_access($username)
{
$conn = Yii::app()->db;
$query = "
SELECT COUNT(*)
FROM {{dept_access}}
WHERE deptid = :deptid
AND username = :username;
";
$command = $conn->createCommand($query);
$command->bindParam(":deptid",$this->deptid);
$command->bindParam(":username",$username);
return ($command->queryScalar() != 0);
}
private function appkey_exists($appkey)
{
$conn = Yii::app()->db;
$query = "
SELECT COUNT(*)
FROM {{departments}}
WHERE appkey = :appkey
";
$command = $conn->createCommand($query);
$command->bindParam(":appkey",$appkey);
return ($command->queryScalar()!=0);
}
private function generate_appkey($length=12)
{
$pool = "ABCDEF1234567890";
$key = "";
for($a=0;$a<$length;$a++) {
if($a%4==0 and $a!=0 and $a!=$length) {
$key .= "-";
}
$key .= substr($pool,rand(0,strlen($pool)-1),1);
}
return $key;
}
public function load_broadcasts()
{
$conn = Yii::app()->db;
$query = "
SELECT broadcastid
FROM {{broadcasts}}
WHERE deptid = :deptid
ORDER BY date_created DESC;
";
$command = $conn->createCommand($query);
$command->bindParam(":deptid",$this->deptid);
$result = $command->queryAll();
if(!$result or empty($result)) {
return array();
}
$return = array();
foreach($result as $row) {
$return[] = new BroadcastObj($row["broadcastid"]);
}
return $return;
}
public function load_pending_broadcasts()
{
$conn = Yii::app()->db;
$query = "
SELECT broadcastid
FROM {{broadcasts}}
WHERE deptid = :deptid
AND status = 0
ORDER BY date_created DESC;
";
$command = $conn->createCommand($query);
$command->bindParam(":deptid",$this->deptid);
return $command->queryAll();
}
}
| assettcu/broadcast | protected/models/DepartmentObj.php | PHP | mit | 3,650 |
<?php
namespace Ballet\WaytocBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class FrontController extends Controller
{
public function indexAction()
{
return $this->render('BalletWaytocBundle:Default:index.html.twig');
}
public function aboutAction(){
return $this->render('BalletWaytocBundle:Default:about.html.twig');
}
}
| kaffau/Ballet | src/Ballet/WaytocBundle/Controller/FrontController.php | PHP | mit | 394 |
const interviewSchema = require('./interview.schema');
const InterviewModel = require('mongoose').model('Interview', interviewSchema);
module.exports = InterviewModel;
| JasonRammoray/interview-assistant | app/server/models/interview/interview.model.js | JavaScript | mit | 169 |
"use strict";
/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var non_max_suppression_impl_1 = require("../backends/non_max_suppression_impl");
var engine_1 = require("../engine");
var tensor_util_env_1 = require("../tensor_util_env");
var util = require("../util");
var operation_1 = require("./operation");
/**
* Bilinear resize a batch of 3D images to a new shape.
*
* @param images The images, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param size The new shape `[newHeight, newWidth]` to resize the
* images to. Each channel is resized individually.
* @param alignCorners Defaults to False. If true, rescale
* input by `(new_height - 1) / (height - 1)`, which exactly aligns the 4
* corners of images and resized images. If false, rescale by
* `new_height / height`. Treat similarly the width dimension.
*/
/** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */
function resizeBilinear_(images, size, alignCorners) {
if (alignCorners === void 0) { alignCorners = false; }
var $images = tensor_util_env_1.convertToTensor(images, 'images', 'resizeBilinear');
util.assert($images.rank === 3 || $images.rank === 4, function () { return "Error in resizeBilinear: x must be rank 3 or 4, but got " +
("rank " + $images.rank + "."); });
util.assert(size.length === 2, function () { return "Error in resizeBilinear: new shape must 2D, but got shape " +
(size + "."); });
var batchImages = $images;
var reshapedTo4D = false;
if ($images.rank === 3) {
reshapedTo4D = true;
batchImages =
$images.as4D(1, $images.shape[0], $images.shape[1], $images.shape[2]);
}
var newHeight = size[0], newWidth = size[1];
var forward = function (backend, save) {
save([batchImages]);
return backend.resizeBilinear(batchImages, newHeight, newWidth, alignCorners);
};
var backward = function (dy, saved) {
return {
x: function () { return engine_1.ENGINE.runKernelFunc(function (backend) { return backend.resizeBilinearBackprop(dy, saved[0], alignCorners); }, {}); }
};
};
var res = engine_1.ENGINE.runKernelFunc(forward, { x: batchImages }, backward, 'ResizeBilinear', { alignCorners: alignCorners, newHeight: newHeight, newWidth: newWidth });
if (reshapedTo4D) {
return res.as3D(res.shape[1], res.shape[2], res.shape[3]);
}
return res;
}
/**
* NearestNeighbor resize a batch of 3D images to a new shape.
*
* @param images The images, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param size The new shape `[newHeight, newWidth]` to resize the
* images to. Each channel is resized individually.
* @param alignCorners Defaults to False. If true, rescale
* input by `(new_height - 1) / (height - 1)`, which exactly aligns the 4
* corners of images and resized images. If false, rescale by
* `new_height / height`. Treat similarly the width dimension.
*/
/** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */
function resizeNearestNeighbor_(images, size, alignCorners) {
if (alignCorners === void 0) { alignCorners = false; }
var $images = tensor_util_env_1.convertToTensor(images, 'images', 'resizeNearestNeighbor');
util.assert($images.rank === 3 || $images.rank === 4, function () { return "Error in resizeNearestNeighbor: x must be rank 3 or 4, but got " +
("rank " + $images.rank + "."); });
util.assert(size.length === 2, function () {
return "Error in resizeNearestNeighbor: new shape must 2D, but got shape " +
(size + ".");
});
util.assert($images.dtype === 'float32' || $images.dtype === 'int32', function () { return '`images` must have `int32` or `float32` as dtype'; });
var batchImages = $images;
var reshapedTo4D = false;
if ($images.rank === 3) {
reshapedTo4D = true;
batchImages =
$images.as4D(1, $images.shape[0], $images.shape[1], $images.shape[2]);
}
var newHeight = size[0], newWidth = size[1];
var forward = function (backend, save) {
save([batchImages]);
return backend.resizeNearestNeighbor(batchImages, newHeight, newWidth, alignCorners);
};
var backward = function (dy, saved) {
return {
batchImages: function () { return engine_1.ENGINE.runKernelFunc(function (backend) { return backend.resizeNearestNeighborBackprop(dy, saved[0], alignCorners); }, {}); }
};
};
var res = engine_1.ENGINE.runKernelFunc(forward, { batchImages: batchImages }, backward);
if (reshapedTo4D) {
return res.as3D(res.shape[1], res.shape[2], res.shape[3]);
}
return res;
}
/**
* Performs non maximum suppression of bounding boxes based on
* iou (intersection over union).
*
* @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is
* `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of
* the bounding box.
* @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.
* @param maxOutputSize The maximum number of boxes to be selected.
* @param iouThreshold A float representing the threshold for deciding whether
* boxes overlap too much with respect to IOU. Must be between [0, 1].
* Defaults to 0.5 (50% box overlap).
* @param scoreThreshold A threshold for deciding when to remove boxes based
* on score. Defaults to -inf, which means any score is accepted.
* @return A 1D tensor with the selected box indices.
*/
/** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */
function nonMaxSuppression_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold) {
if (iouThreshold === void 0) { iouThreshold = 0.5; }
if (scoreThreshold === void 0) { scoreThreshold = Number.NEGATIVE_INFINITY; }
var $boxes = tensor_util_env_1.convertToTensor(boxes, 'boxes', 'nonMaxSuppression');
var $scores = tensor_util_env_1.convertToTensor(scores, 'scores', 'nonMaxSuppression');
var inputs = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold);
maxOutputSize = inputs.maxOutputSize;
iouThreshold = inputs.iouThreshold;
scoreThreshold = inputs.scoreThreshold;
var attrs = { maxOutputSize: maxOutputSize, iouThreshold: iouThreshold, scoreThreshold: scoreThreshold };
return engine_1.ENGINE.runKernelFunc(function (b) { return b.nonMaxSuppression($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold); }, { boxes: $boxes, scores: $scores }, null /* grad */, 'NonMaxSuppressionV3', attrs);
}
/** This is the async version of `nonMaxSuppression` */
function nonMaxSuppressionAsync_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold) {
if (iouThreshold === void 0) { iouThreshold = 0.5; }
if (scoreThreshold === void 0) { scoreThreshold = Number.NEGATIVE_INFINITY; }
return __awaiter(this, void 0, void 0, function () {
var $boxes, $scores, inputs, boxesAndScores, boxesVals, scoresVals, res;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
$boxes = tensor_util_env_1.convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');
$scores = tensor_util_env_1.convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');
inputs = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold);
maxOutputSize = inputs.maxOutputSize;
iouThreshold = inputs.iouThreshold;
scoreThreshold = inputs.scoreThreshold;
return [4 /*yield*/, Promise.all([$boxes.data(), $scores.data()])];
case 1:
boxesAndScores = _a.sent();
boxesVals = boxesAndScores[0];
scoresVals = boxesAndScores[1];
res = non_max_suppression_impl_1.nonMaxSuppressionV3(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold);
if ($boxes !== boxes) {
$boxes.dispose();
}
if ($scores !== scores) {
$scores.dispose();
}
return [2 /*return*/, res];
}
});
});
}
/**
* Performs non maximum suppression of bounding boxes based on
* iou (intersection over union).
*
* This op also supports a Soft-NMS mode (c.f.
* Bodla et al, https://arxiv.org/abs/1704.04503) where boxes reduce the score
* of other overlapping boxes, therefore favoring different regions of the image
* with high scores. To enable this Soft-NMS mode, set the `softNmsSigma`
* parameter to be larger than 0.
*
* @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is
* `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of
* the bounding box.
* @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.
* @param maxOutputSize The maximum number of boxes to be selected.
* @param iouThreshold A float representing the threshold for deciding whether
* boxes overlap too much with respect to IOU. Must be between [0, 1].
* Defaults to 0.5 (50% box overlap).
* @param scoreThreshold A threshold for deciding when to remove boxes based
* on score. Defaults to -inf, which means any score is accepted.
* @param softNmsSigma A float representing the sigma parameter for Soft NMS.
* When sigma is 0, it falls back to nonMaxSuppression.
* @return A map with the following properties:
* - selectedIndices: A 1D tensor with the selected box indices.
* - selectedScores: A 1D tensor with the corresponding scores for each
* selected box.
*/
/** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */
function nonMaxSuppressionWithScore_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma) {
if (iouThreshold === void 0) { iouThreshold = 0.5; }
if (scoreThreshold === void 0) { scoreThreshold = Number.NEGATIVE_INFINITY; }
if (softNmsSigma === void 0) { softNmsSigma = 0.0; }
var $boxes = tensor_util_env_1.convertToTensor(boxes, 'boxes', 'nonMaxSuppression');
var $scores = tensor_util_env_1.convertToTensor(scores, 'scores', 'nonMaxSuppression');
var inputs = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma);
maxOutputSize = inputs.maxOutputSize;
iouThreshold = inputs.iouThreshold;
scoreThreshold = inputs.scoreThreshold;
softNmsSigma = inputs.softNmsSigma;
var attrs = { maxOutputSize: maxOutputSize, iouThreshold: iouThreshold, scoreThreshold: scoreThreshold, softNmsSigma: softNmsSigma };
var result = engine_1.ENGINE.runKernel('NonMaxSuppressionV5', { boxes: $boxes, scores: $scores }, attrs);
return { selectedIndices: result[0], selectedScores: result[1] };
}
/** This is the async version of `nonMaxSuppressionWithScore` */
function nonMaxSuppressionWithScoreAsync_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma) {
if (iouThreshold === void 0) { iouThreshold = 0.5; }
if (scoreThreshold === void 0) { scoreThreshold = Number.NEGATIVE_INFINITY; }
if (softNmsSigma === void 0) { softNmsSigma = 0.0; }
return __awaiter(this, void 0, void 0, function () {
var $boxes, $scores, inputs, boxesAndScores, boxesVals, scoresVals, res;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
$boxes = tensor_util_env_1.convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');
$scores = tensor_util_env_1.convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');
inputs = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma);
maxOutputSize = inputs.maxOutputSize;
iouThreshold = inputs.iouThreshold;
scoreThreshold = inputs.scoreThreshold;
softNmsSigma = inputs.softNmsSigma;
return [4 /*yield*/, Promise.all([$boxes.data(), $scores.data()])];
case 1:
boxesAndScores = _a.sent();
boxesVals = boxesAndScores[0];
scoresVals = boxesAndScores[1];
res = non_max_suppression_impl_1.nonMaxSuppressionV5(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma);
if ($boxes !== boxes) {
$boxes.dispose();
}
if ($scores !== scores) {
$scores.dispose();
}
return [2 /*return*/, res];
}
});
});
}
function nonMaxSuppSanityCheck(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma) {
if (iouThreshold == null) {
iouThreshold = 0.5;
}
if (scoreThreshold == null) {
scoreThreshold = Number.NEGATIVE_INFINITY;
}
if (softNmsSigma == null) {
softNmsSigma = 0.0;
}
var numBoxes = boxes.shape[0];
maxOutputSize = Math.min(maxOutputSize, numBoxes);
util.assert(0 <= iouThreshold && iouThreshold <= 1, function () { return "iouThreshold must be in [0, 1], but was '" + iouThreshold + "'"; });
util.assert(boxes.rank === 2, function () { return "boxes must be a 2D tensor, but was of rank '" + boxes.rank + "'"; });
util.assert(boxes.shape[1] === 4, function () {
return "boxes must have 4 columns, but 2nd dimension was " + boxes.shape[1];
});
util.assert(scores.rank === 1, function () { return 'scores must be a 1D tensor'; });
util.assert(scores.shape[0] === numBoxes, function () { return "scores has incompatible shape with boxes. Expected " + numBoxes + ", " +
("but was " + scores.shape[0]); });
util.assert(0 <= softNmsSigma && softNmsSigma <= 1, function () { return "softNmsSigma must be in [0, 1], but was '" + softNmsSigma + "'"; });
return { maxOutputSize: maxOutputSize, iouThreshold: iouThreshold, scoreThreshold: scoreThreshold, softNmsSigma: softNmsSigma };
}
/**
* Extracts crops from the input image tensor and resizes them using bilinear
* sampling or nearest neighbor sampling (possibly with aspect ratio change)
* to a common output size specified by crop_size.
*
* @param image 4d tensor of shape `[batch,imageHeight,imageWidth, depth]`,
* where imageHeight and imageWidth must be positive, specifying the
* batch of images from which to take crops
* @param boxes 2d float32 tensor of shape `[numBoxes, 4]`. Each entry is
* `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the normalized
* coordinates of the box in the boxInd[i]'th image in the batch
* @param boxInd 1d int32 tensor of shape `[numBoxes]` with values in range
* `[0, batch)` that specifies the image that the `i`-th box refers to.
* @param cropSize 1d int32 tensor of 2 elements `[cropHeigh, cropWidth]`
* specifying the size to which all crops are resized to.
* @param method Optional string from `'bilinear' | 'nearest'`,
* defaults to bilinear, which specifies the sampling method for resizing
* @param extrapolationValue A threshold for deciding when to remove boxes based
* on score. Defaults to 0.
* @return A 4D tensor of the shape `[numBoxes,cropHeight,cropWidth,depth]`
*/
/** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */
function cropAndResize_(image, boxes, boxInd, cropSize, method, extrapolationValue) {
var $image = tensor_util_env_1.convertToTensor(image, 'image', 'cropAndResize');
var $boxes = tensor_util_env_1.convertToTensor(boxes, 'boxes', 'cropAndResize', 'float32');
var $boxInd = tensor_util_env_1.convertToTensor(boxInd, 'boxInd', 'cropAndResize', 'int32');
method = method || 'bilinear';
extrapolationValue = extrapolationValue || 0;
var numBoxes = $boxes.shape[0];
util.assert($image.rank === 4, function () { return 'Error in cropAndResize: image must be rank 4,' +
("but got rank " + $image.rank + "."); });
util.assert($boxes.rank === 2 && $boxes.shape[1] === 4, function () { return "Error in cropAndResize: boxes must be have size [" + numBoxes + ",4] " +
("but had shape " + $boxes.shape + "."); });
util.assert($boxInd.rank === 1 && $boxInd.shape[0] === numBoxes, function () { return "Error in cropAndResize: boxInd must be have size [" + numBoxes + "] " +
("but had shape " + $boxes.shape + "."); });
util.assert(cropSize.length === 2, function () { return "Error in cropAndResize: cropSize must be of length 2, but got " +
("length " + cropSize.length + "."); });
util.assert(cropSize[0] >= 1 && cropSize[1] >= 1, function () { return "cropSize must be atleast [1,1], but was " + cropSize; });
util.assert(method === 'bilinear' || method === 'nearest', function () { return "method must be bilinear or nearest, but was " + method; });
var forward = function (backend, save) {
return backend.cropAndResize($image, $boxes, $boxInd, cropSize, method, extrapolationValue);
};
var res = engine_1.ENGINE.runKernelFunc(forward, { images: $image, boxes: $boxes, boxInd: $boxInd }, null /* der */, 'CropAndResize', { method: method, extrapolationValue: extrapolationValue, cropSize: cropSize });
return res;
}
exports.resizeBilinear = operation_1.op({ resizeBilinear_: resizeBilinear_ });
exports.resizeNearestNeighbor = operation_1.op({ resizeNearestNeighbor_: resizeNearestNeighbor_ });
exports.nonMaxSuppression = operation_1.op({ nonMaxSuppression_: nonMaxSuppression_ });
exports.nonMaxSuppressionAsync = nonMaxSuppressionAsync_;
exports.nonMaxSuppressionWithScore = operation_1.op({ nonMaxSuppressionWithScore_: nonMaxSuppressionWithScore_ });
exports.nonMaxSuppressionWithScoreAsync = nonMaxSuppressionWithScoreAsync_;
exports.cropAndResize = operation_1.op({ cropAndResize_: cropAndResize_ });
//# sourceMappingURL=image_ops.js.map | ManakCP/NestJs | node_modules/@tensorflow/tfjs-core/dist/ops/image_ops.js | JavaScript | mit | 21,358 |
//------------------------------------------------------------------------------
// <copyright file="DirectoryListingScheduler.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.Azure.Storage.DataMovement
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class DirectoryListingScheduler : IDisposable
{
SemaphoreSlim semaphore = null;
public DirectoryListingScheduler(int maxParallelListingThreads)
{
semaphore = new SemaphoreSlim(maxParallelListingThreads, maxParallelListingThreads);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public Task Schedule(
SubDirectoryTransfer subDirectoryTransfer,
CancellationToken cancellationToken,
Action persistDirTransfer,
int timeOut)
{
if (this.semaphore.Wait(timeOut, cancellationToken))
{
try
{
if (null != persistDirTransfer)
{
persistDirTransfer();
}
}
catch
{
this.semaphore.Release();
throw;
}
Task task = subDirectoryTransfer.ExecuteAsync(cancellationToken);
task.ContinueWith((sourceTask) =>
{
this.semaphore.Release();
return sourceTask;
});
return task;
}
else
{
return null;
}
}
/// <summary>
/// Public dispose method to release all resources owned.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (null != this.semaphore)
{
this.semaphore.Dispose();
this.semaphore = null;
}
}
}
}
}
| Azure/azure-storage-net-data-movement | lib/DirectoryListingScheduler.cs | C# | mit | 2,466 |
/*
* Copyright (c) 2014 Microsoft Mobile
*
* 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.
*/
#include "pch.h"
| Microsoft/Lumia-Imaging-SDK-Extras | Native/Samples/CustomWRL/CustomWRL.WindowsPhone/pch.cpp | C++ | mit | 1,120 |
(function(){
angular
.module("InteractionDesign")
.controller("ResultsChartController", ResultsChartController);
function ResultsChartController($scope, $location) {
$scope.$location = $location;
var data1 = [
{ x: new Date(2012, 00, 1), y: 12 },
{ x: new Date(2012, 00, 2), y: 13 },
{ x: new Date(2012, 00, 3), y: 16 },
{ x: new Date(2012, 00, 4), y: 37 },
{ x: new Date(2012, 00, 5), y: 39 },
{ x: new Date(2012, 00, 6), y: 42 },
{ x: new Date(2012, 00, 7), y: 25 },
{ x: new Date(2012, 00, 8), y: 18 },
{ x: new Date(2012, 00, 9), y: 22 },
{ x: new Date(2012, 00, 10), y: 25 },
{ x: new Date(2012, 00, 11), y: 25 },
{ x: new Date(2012, 00, 12), y: 28 }
];
var data2 = [
{ x: new Date(2012, 00, 1), y: 50 },
{ x: new Date(2012, 00, 2), y: 45 },
{ x: new Date(2012, 00, 3), y: 40 },
{ x: new Date(2012, 00, 4), y: 25 },
{ x: new Date(2012, 00, 5), y: 24 },
{ x: new Date(2012, 00, 6), y: 29 },
{ x: new Date(2012, 00, 7), y: 43 },
{ x: new Date(2012, 00, 8), y: 35 },
{ x: new Date(2012, 00, 9), y: 34 },
{ x: new Date(2012, 00, 10), y: 39 },
{ x: new Date(2012, 00, 11), y: 43 },
{ x: new Date(2012, 00, 12), y: 48 }
];
var data3 = [
{ x: new Date(2012, 00, 1), y: 26 },
{ x: new Date(2012, 00, 2), y: 25 },
{ x: new Date(2012, 00, 3), y: 23 },
{ x: new Date(2012, 00, 4), y: 20 },
{ x: new Date(2012, 00, 5), y: 17 },
{ x: new Date(2012, 00, 6), y: 17 },
{ x: new Date(2012, 00, 7), y: 17 },
{ x: new Date(2012, 00, 8), y: 18 },
{ x: new Date(2012, 00, 9), y: 12 },
{ x: new Date(2012, 00, 10), y: 8 },
{ x: new Date(2012, 00, 11), y: 8 },
{ x: new Date(2012, 00, 12), y: 12 }
];
var data4 = [
{ x: new Date(2012, 00, 1), y: 25 },
{ x: new Date(2012, 00, 2), y: 26 },
{ x: new Date(2012, 00, 3), y: 28 },
{ x: new Date(2012, 00, 4), y: 28 },
{ x: new Date(2012, 00, 5), y: 30 },
{ x: new Date(2012, 00, 6), y: 35 },
{ x: new Date(2012, 00, 7), y: 25 },
{ x: new Date(2012, 00, 8), y: 18 },
{ x: new Date(2012, 00, 9), y: 22 },
{ x: new Date(2012, 00, 10), y: 25 },
{ x: new Date(2012, 00, 11), y: 25 },
{ x: new Date(2012, 00, 12), y: 28 }
];
var data5 = [
{ x: new Date(2012, 00, 1), y: 25 },
{ x: new Date(2012, 00, 2), y: 24 },
{ x: new Date(2012, 00, 3), y: 45 },
{ x: new Date(2012, 00, 4), y: 29 },
{ x: new Date(2012, 00, 5), y: 24 },
{ x: new Date(2012, 00, 6), y: 29 },
{ x: new Date(2012, 00, 7), y: 18 },
{ x: new Date(2012, 00, 8), y: 22 },
{ x: new Date(2012, 00, 9), y: 25 },
{ x: new Date(2012, 00, 10), y: 25 },
{ x: new Date(2012, 00, 11), y: 28 },
{ x: new Date(2012, 00, 12), y: 28 }
];
var data6 = [
{ x: new Date(2012, 00, 1), y: 26 },
{ x: new Date(2012, 00, 2), y: 25 },
{ x: new Date(2012, 00, 3), y: 23 },
{ x: new Date(2012, 00, 4), y: 50 },
{ x: new Date(2012, 00, 5), y: 25 },
{ x: new Date(2012, 00, 6), y: 29 },
{ x: new Date(2012, 00, 7), y: 25 },
{ x: new Date(2012, 00, 8), y: 28 },
{ x: new Date(2012, 00, 9), y: 12 },
{ x: new Date(2012, 00, 10), y: 8 },
{ x: new Date(2012, 00, 11), y: 8 },
{ x: new Date(2012, 00, 12), y: 12 }
];
$scope.filters = [
{name: "Age", selected: false, options: [
{name: "18-24", selected: false},
{name: "25-34", selected: false},
{name: "35-49", selected: false},
{name: "50-65", selected: false},
{name: "65+", selected: false}
]},
{name: "Occupation", selected: false, options: [
{name: "Students", selected: false},
{name: "Blue-Collar", selected: false},
{name: "White-Collar", selected: false}
]},
{name: "Gender", selected: false, options: [
{name: "Male", selected: false},
{name: "Female", selected: false}
]},
{name: "State", selected: false, options: [
{name: "Alabama", selected: false},
{name: "Arkansas", selected: false},
{name: "New York", selected: false},
{name: "California", selected: false},
{name: "Massachusetts", selected: false}
]},
{name: "Political Party", selected: false, options: [
{name: "Democrat", selected: false},
{name: "Republican", selected: false}
]},
];
$scope.clickFilter = function(filter) {
for (filterIdx in $scope.filters) {
var theFilter = $scope.filters[filterIdx];
if (theFilter.name == filter.name && theFilter.selected == false) {
theFilter.selected = true;
}
else {
theFilter.selected = false;
for (optionIdx in theFilter.options) {
theFilter.options[optionIdx].selected = false;
}
}
}
}
$scope.clickSubOption = function(filter, subOption) {
for (filterIdx in $scope.filters) {
var theFilter = $scope.filters[filterIdx];
if (theFilter.name == filter.name && theFilter.selected == true) {
for (optionIdx in theFilter.options) {
var option = theFilter.options[optionIdx];
if (option.name == subOption.name && option.selected == false) {
option.selected = true;
}
else {
option.selected = false;
}
}
}
}
if (subOption.name == "18-24" && subOption.selected == true) {
reloadChart(data4, data5, data6, false, "Results 18-24");
}
else {
reloadChart(data1, data2, data3, false, "Results");
}
}
function reloadChart(data_1, data_2, data_3, animated, title) {
var chart = new CanvasJS.Chart("chartContainer",
{
theme: "theme2",
title:{
text: title
},
animationEnabled: animated,
axisX: {
valueFormatString: "MMM",
interval:1,
intervalType: "month"
},
axisY:{
includeZero: false
},
data: [
{
type: "line",
showInLegend: true,
lineThickness: 2,
name: "Hillary Clinton",
dataPoints: data_1
},
{
type: "line",
showInLegend: true,
lineThickness: 2,
name: "Bernie Sanders",
dataPoints: data_2
},
{
type: "line",
showInLegend: true,
lineThickness: 2,
name: "Donald Trump",
dataPoints: data_3
}
]
});
chart.render();
}
reloadChart(data1, data2, data3, true, "Results");
}
})(); | lhaber9/RiskLegacyHCI | public/experiments/js/resultsChartController.js | JavaScript | mit | 7,139 |
// ch08-arrays--splice.js
'use strict';
// ADDING OR REMOVING ELEMENTS AT ANY POSITION
// SPLICE
// The first argument is the index you want to start modifying
// The second argument is the number of elements to remove (use 0 if you don’t want to remove any elements)
// The remaining arguments are the elements to be added
const arr = [1, 5, 7];
console.log(`arr: \t${arr}\tlength: \t${arr.length}`);
// arr: 1,5,7 length: 3
const arr1 = arr.splice(1, 0, 2, 3, 4);
console.log(`arr: \t${arr}\tlength: ${arr.length}\tarr1: \t${arr1}\tlength: ${arr1.length}`);
// arr: 1,2,3,4,5,7 length: 6 arr1: [] length: 0
const arr2 = arr.splice(5, 0, 6);
console.log(`arr: \t${arr}\tlength: ${arr.length}\tarr2: \t${arr2}\tlength: ${arr2.length}`);
// arr: 1,2,3,4,5,6,7 length: 7 arr2: [] length: 0
const arr3 = arr.splice(1, 2);
console.log(`arr: \t${arr}\tlength: ${arr.length}\tarr3: \t${arr3}\tlength: ${arr3.length}`);
// arr: 1,4,5,6,7 length: 5 arr3: 2,3 length: 2
const arr4 = arr.splice(2, 1, 'a', 'b');
console.log(`arr: \t${arr}\tlength: ${arr.length}\tarr4: \t${arr4}\tlength: ${arr4.length}`);
// arr: 1,4,a,b,6,7 length: 6 arr4: 5 length: 1
| Juantxo/learningJS | es6/ch08-arrays--splice.js | JavaScript | mit | 1,175 |
import { bind, unbind } from '@segmentstream/utils/eventListener'
import listenEvents from './listenEvents'
import Storage from '../Storage'
const timeout = 10 // 10 seconds
let interval = null
let hasActive = false
let events = []
const storagePrefix = 'timeOnSite:'
const storage = new Storage({ prefix: storagePrefix })
// Load from storage
let activeTime = storage.get('activeTime') || 0
let time = storage.get('time') || 0
const firedEventsJSON = storage.get('firedEvents')
let firedEvents = firedEventsJSON ? JSON.parse(firedEventsJSON) : []
const addEventsListener = () => {
listenEvents.forEach((eventName) => {
bind(window.document, eventName, setActive, false)
})
}
const removeEventsListener = () => {
listenEvents.forEach((eventName) => {
unbind(window.document, eventName, setActive, false)
})
}
const incActiveTime = () => {
activeTime += timeout
storage.set('activeTime', activeTime)
}
const incTime = () => {
time += timeout
storage.set('time', time)
}
const fireEvent = (eventName) => {
firedEvents.push(eventName)
storage.set('firedEvents', JSON.stringify(firedEvents))
}
const processEvents = () => {
if (hasActive) {
incActiveTime()
hasActive = false
}
incTime()
events.forEach((event) => {
const timeForEvent = event.isActiveTime ? activeTime : time
if (!firedEvents.includes(`${event.name}:${event.seconds}`) && event.seconds <= timeForEvent) {
event.handler(timeForEvent)
fireEvent(`${event.name}:${event.seconds}`)
}
})
}
const setActive = () => { hasActive = true }
const addEvent = (seconds, handler, eventName, isActiveTime) => {
events.push({ seconds, handler, isActiveTime, name: eventName })
}
const startTracking = () => {
interval = setInterval(processEvents, timeout * 1000)
addEventsListener()
}
const stopTracking = () => {
clearInterval(interval)
removeEventsListener()
}
startTracking()
export const reset = () => {
if (interval) {
stopTracking()
}
activeTime = 0
time = 0
hasActive = false
firedEvents = []
storage.remove('activeTime')
storage.remove('time')
storage.remove('firedEvents')
startTracking()
}
export default (seconds, handler, eventName, isActiveTime = false) => {
if (!seconds) return
if (typeof handler !== 'function') {
throw new TypeError('Must pass function handler to `ddManager.trackTimeOnSite`.')
}
String(seconds)
.replace(/\s+/mg, '')
.split(',')
.forEach((secondsStr) => {
const second = parseInt(secondsStr)
if (second > 0) {
addEvent(second, handler, eventName, isActiveTime)
}
})
}
| driveback/digital-data-manager | src/trackers/trackTimeOnSite.js | JavaScript | mit | 2,627 |
package city.test1;
/**
* @author chris Class representing one of the many possible stations found in
* an intersection.
*/
public class Station {
private String name;
public Station(String name) {
this.name = name;
}
/**
*
* @return Returns the station name.
*/
public String getName() {
return this.name;
}
@Override
public String toString() {
return this.name;
}
}
| saibot94/city-graph-pIII | src/city/test1/Station.java | Java | mit | 433 |
<?php
session_start();
if(!$_SESSION["surveyvaliduser"])
header("location:userlogin.php");
/*make this your index page for users. And use <?php require_once("showquestion.php") ?> at the position you need to dispaly the question*/
require_once("showquestion.php");
?>
| quizzr-cms/quizzr | survey/index.php | PHP | mit | 280 |
RSpec::Matchers.define :generate do |html|
match do |helper, options = nil|
if helper.is_a?(Hash)
helper, options = helper.keys.first, helper.values.first
end
if helper == :link_to && options == :nil_name
@inline = bh.send helper, nil, '/'
@block = @inline
elsif helper == :link_to || helper == :button_to
@inline = bh.send helper, *['content', '/', options].compact
if bh.test_button_to_with_block
@block = bh.send(helper, *['/', options].compact) { 'content' }
else
@block = @inline
end
elsif helper == :dropdown
@block = bh.send(helper, *['caption', options].compact) { 'content' }
@inline = @block
elsif helper == :glyphicon || helper == :icon
@inline = bh.send helper, *['zoom-in', options].compact
@block = bh.send helper, *[:zoom_in, options].compact
elsif helper == :progress_bar
@inline = bh.send helper, *Array.wrap(options)
@block = @inline
elsif helper == :navbar || helper == :nav || helper == :panel_row
@block = bh.send(helper, *[options].compact) { 'content' }
@inline = @block
else
@inline = bh.send helper, *['content', options].compact
@block = bh.send(helper, *[options].compact) { 'content' }
end
case html
when Regexp then @inline.match(html) && @block.match(html)
else @inline.eql?(html) && @block.eql?(html)
end
end
failure_message{|actual| "expected #{html}, got #{@inline} and #{@block}"}
end | juliobetta/bh | spec/support/matchers.rb | Ruby | mit | 1,505 |
version https://git-lfs.github.com/spec/v1
oid sha256:81e9c9e173a9043e925313a488beecd37914141528b2ccf21df1fc5620343cb8
size 2512
| yogeshsaroya/new-cdnjs | ajax/libs/tinymce/3.5.8/plugins/advlink/langs/zh-tw_dlg.js | JavaScript | mit | 129 |
/* global bowlineApp */
function releaseModule($rootScope,$http,$timeout,login,ENV) {
console.log("!trace releaseModule instantiated, login status: ",login.status);
this.validator = {};
// This just gets all releases.
this.getReleases = function(mine,username,search,callback) {
var loginpack = {};
if (login.status) {
loginpack = login.sessionpack;
}
$http.post(ENV.api_url + '/api/getReleases', { session: loginpack, username: username, mineonly: mine, search: search })
.success(function(data){
// console.log("!trace getReleases data",data);
callback(null,data);
}.bind(this)).error(function(data){
callback("Had trouble with getReleases from API");
}.bind(this));
};
this.editRelease = function(release,add_release,callback) {
if (add_release) {
$http.post(ENV.api_url + '/api/addRelease', { release: release, session: login.sessionpack })
.success(function(addresult){
// console.log("!trace addRelease data",release);
callback(addresult.error,addresult.releaseid);
}.bind(this)).error(function(data){
callback("Had trouble with addRelease from API");
}.bind(this));
} else {
$http.post(ENV.api_url + '/api/editRelease', { release: release, session: login.sessionpack })
.success(function(release){
// console.log("!trace editRelease data",release);
callback(release.error,release.releaseid);
}.bind(this)).error(function(data){
callback("Had trouble with editRelease from API");
}.bind(this));
}
};
this.searchCollaborators = function(searchstring,callback) {
$http.post(ENV.api_url + '/api/searchCollaborators', { session: login.sessionpack, search: searchstring })
.success(function(users){
// console.log("!trace searchCollaborators release",release);
callback(null,users);
}.bind(this)).error(function(data){
callback("Had trouble with searchCollaborators from API");
}.bind(this));
};
// This just gets all releases.
this.getSingleRelease = function(id,callback) {
$http.post(ENV.api_url + '/api/getSingleRelease', { id: id, session: login.sessionpack })
.success(function(release){
// console.log("!trace getReleases release",release);
callback(null,release);
}.bind(this)).error(function(data){
callback("Had trouble with getSingleRelease from API");
}.bind(this));
};
// Get the tags for a release.
this.getTags = function(id,callback) {
$http.post(ENV.api_url + '/api/getTags', { releaseid: id, session: login.sessionpack })
.success(function(tags){
console.log("!trace getTags tags",tags);
callback(null,tags);
}.bind(this)).error(function(data){
callback("Had trouble with getTags from API");
}.bind(this));
};
// Get the validator for releases.
this.getReleaseValidator = function(callback) {
$http.post(ENV.api_url + '/api/getReleaseValidator', { session: login.sessionpack })
.success(function(data){
// console.log("!trace getReleaseValidator data",data);
callback(null,data);
this.validator = data;
}.bind(this)).error(function(data){
callback("Had trouble with getReleaseValidator from API");
}.bind(this));
};
this.forceUpdate = function(id,callback) {
$http.post(ENV.api_url + '/api/forceUpdate', { id: id, session: login.sessionpack })
.success(function(data){
var err = null;
if (data.error) {
err = data.error;
}
// console.log("!trace forceUpdate data",data);
callback(err,data);
}.bind(this)).error(function(data){
callback("Had trouble with forceUpdate from API");
}.bind(this));
};
this.getLogText = function(releaseid,logid,callback) {
$http.post(ENV.api_url + '/api/getLogText', { releaseid: releaseid, logid: logid, session: login.sessionpack })
.success(function(data){
var err = null;
if (data.error) {
err = data.error;
}
// console.log("!trace getLogText data",data);
callback(err,data.log);
}.bind(this)).error(function(data){
callback("Had trouble with getLogText from API");
}.bind(this));
};
this.getLogs = function(id,startpos,endpos,callback){
$http.post(ENV.api_url + '/api/getLogs', { id: id, session: login.sessionpack, startpos: startpos, endpos: endpos })
.success(function(data){
var err = null;
if (data.error) {
err = data.error;
}
// console.log("!trace getLogs data",data);
callback(err,data);
}.bind(this)).error(function(data){
callback("Had trouble with getLogs from API");
}.bind(this));
};
this.getFamily = function(id,callback){
$http.post(ENV.api_url + '/api/getFamily', { id: id, session: login.sessionpack })
.success(function(data){
var err = null;
if (data.error) {
err = data.error;
}
// console.log("!trace getFamily data",data);
callback(err,data);
}.bind(this)).error(function(data){
callback("Had trouble with getFamily from API");
}.bind(this));
};
this.validateJob = function(id,callback){
$http.post(ENV.api_url + '/api/validateJob', { id: id, session: login.sessionpack })
.success(function(data){
var err = null;
if (data.error) {
err = data.error;
}
// console.log("!trace validateJob data",data);
callback(err,data);
}.bind(this)).error(function(data){
callback("Had trouble with validateJob from API");
}.bind(this));
};
this.startJob = function(id,callback){
$http.post(ENV.api_url + '/api/startJob', { id: id, session: login.sessionpack })
.success(function(data){
var err = null;
if (data.error) {
err = data.error;
}
// console.log("!trace startJob data",data);
callback(err,data);
}.bind(this)).error(function(data){
callback("Had trouble with startJob from API");
}.bind(this));
};
this.stopJob = function(id,callback){
$http.post(ENV.api_url + '/api/stopJob', { id: id, session: login.sessionpack })
.success(function(data){
var err = null;
if (data.error) {
err = data.error;
}
// console.log("!trace stopJob data",data);
callback(err,data);
}.bind(this)).error(function(data){
callback("Had trouble with stopJob from API");
}.bind(this));
};
}
bowlineApp.factory('releaseModule', ["$rootScope", "$http", "$timeout", 'loginModule', 'ENV', function($rootScope,$http,$timeout,login,ENV) {
return new releaseModule($rootScope,$http,$timeout,login,ENV);
}]); | dougbtv/bowline | www/app/scripts/controllers/releaseModule.js | JavaScript | mit | 6,461 |
public class Eagle implements Animal {
/**
* Constructor with package access only
* Only classes in the same package can instantiate it, like the AnimalFactory
*/
Eagle(){}
@Override
public void move() {
System.out.println("Eagle flying...");
}
}
| wwesantos/Java-Design-Patterns | FACTORY/Eagle.java | Java | mit | 263 |
using System;
using Xamarin.Forms;
using System.Collections.Generic;
namespace MenuTeste
{
public class MenuPage : ContentPage
{
public MenuListView Menu {
get;
set;
}
public MenuPage ()
{
Menu = new MenuListView ();
Title = "itm";
Content = new StackLayout () {
Children = {
Menu
}
};
//this.Menu.ItemSelected += Menu_ItemSelected;
}
}
/// <summary>
/// Classe responsável por criar os itens do menu da master detail page
/// </summary>
public class MenuListView : ListView
{
public MenuListView ()
{
List<ItemMenu> items = this.CreateMenuItems ();
//this.SeparatorColor = Color.Transparent;
//this.SeparatorVisibility = SeparatorVisibility.None;
ItemsSource = items;
VerticalOptions = LayoutOptions.FillAndExpand;
HorizontalOptions = LayoutOptions.CenterAndExpand;
BackgroundColor = Color.Transparent;
var cell = new DataTemplate (typeof(ImageCell));
cell.SetBinding (TextCell.TextColorProperty, "TextColor");
cell.SetBinding (TextCell.TextProperty, "DisplayText");
cell.SetBinding (ImageCell.ImageSourceProperty, "DisplayImage");
ItemTemplate = cell;
}
private List<ItemMenu> CreateMenuItems ()
{
List<ItemMenu> items = new List<ItemMenu> ();
items.Add (new ItemMenu () {
DisplayText = "Início",
DisplayImage = "Icon-60.png",
TextColor = Color.Black,
Target = typeof(Content1)
});
return items;
}
}
public class ListMenuItem
{
public List<ItemMenu> Itens{ get; set; }
public string DisplayText {
get;
set;
}
}
/// <summary>
/// Classe responsável por armazenar o título, imagem e a página de detail do menu
/// </summary>
public class ItemMenu
{
public string DisplayText { get; set; }
public string DisplayImage { get; set; }
public Type Target { get; set; }
public Color TextColor { get; set; }
}
}
| rafaelrmou/AppCursoZ | MenuTeste/MenuTeste/MenuPage.cs | C# | mit | 1,897 |
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using DancingGoat.Models.Coffees;
using DancingGoat.Models.Products;
using DancingGoat.Repositories;
using DancingGoat.Repositories.Filters;
using DancingGoat.Services;
namespace DancingGoat.Controllers
{
public class CoffeesController : Controller
{
private readonly ICoffeeRepository mCoffeeRepository;
private readonly ICalculationService mCalculationService;
public CoffeesController(ICoffeeRepository coffeeRepository, ICalculationService calculationService)
{
mCoffeeRepository = coffeeRepository;
mCalculationService = calculationService;
}
// GET: Coffees
public ActionResult Index()
{
var items = GetFilteredCoffees(null);
var filter = new CoffeeFilterViewModel();
filter.Load();
return View(new ProductListViewModel
{
Filter = filter,
Items = items
});
}
// POST: Filter
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Filter(CoffeeFilterViewModel filter)
{
if (!Request.IsAjaxRequest())
{
return HttpNotFound();
}
var items = GetFilteredCoffees(filter);
return PartialView("CoffeeList", items);
}
private IEnumerable<ProductListItemViewModel> GetFilteredCoffees(IRepositoryFilter filter)
{
var coffees = mCoffeeRepository.GetCoffees(filter);
var items = coffees.Select(
coffee => new ProductListItemViewModel(
coffee,
mCalculationService.CalculateListingPrice(coffee.SKU),
coffee.Product.PublicStatus?.PublicStatusDisplayName));
return items;
}
}
} | Kentico/Mvc | src/DancingGoat/Controllers/CoffeesController.cs | C# | mit | 1,959 |
/*
* 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.
*/
//var winMae;
var wins;
//function mae2(idLink, maeNombre, winParent) {
// //alert(idLink.text());
//
// //alert($(idLink).text());
//
// var wins = new dhtmlXWindows();
// skin="dhx_terrace";
// wins.setSkin(skin);
// winId="win"+maeNombre;
// wins.createWindow(winId, 1, 1, 900, 530);
// wins.window(winId).setText("<h4>" + $(idLink).text() + "</h4>");
// wins.window(winId).setModal(true);
// wins.window(winId).button("minmax").disable();
// wins.window(winId).centerOnScreen();
// wins.window(winId).progressOn();
// wins.window(winId).setIconCss("without_icon");
// var urlParametros={'maeTipoId':maeTipoId, 'winParent': winParent, 'maeParametros': maeParametros};
// var url = Routing.generate('maestro', urlParametros);
// wins.window(winId).attachURL(url);
//
// wins.window(winId).attachEvent("onContentLoaded", function(id){
// //alert(id.id);
// id.progressOff();
// var ifr = id.getFrame();
// ifr.contentWindow.wins=wins;
// //ifr.contentWindow.winParent=winParent;
// //alert(ifr.contentWindow.winParent);
// });
//
//
//// alert(maeParametros);
//// var parametros = JSON.parse(maeParametros);
//// alert(parametros);
//////
//// for(x=0; x<parametros.length; x++) {
//// alert(parametros[x].maeNombre);
//// //console.log(parametros[x].description);
//// }
//}
function mae(maeTipoId, winParent, maeParametros) {
var wins = new dhtmlXWindows();
skin="dhx_terrace";
wins.setSkin(skin);
var url="";
switch (maeTipoId) {
case "1": //perfiles
winId="winPerfil";
//wins.createWindow(winId, 1, 1, 90, 60);
wins.createWindow(winId, 1, 1, 900, 630);
//wins.window(winId).setText("<h5>Perfil de cargo</h5>");
wins.window(winId).setText("Perfil de cargo");
var url = Routing.generate('perfil');
break;
case "2": //personas
winId="winPersona";
wins.createWindow(winId, 1, 1, 900, 530);
wins.window(winId).setText("Personas");
var url = Routing.generate('persona');
break;
case "3": //competencias
winId="winCompetencia";
wins.createWindow(winId, 1, 1, 900, 600);
wins.window(winId).setText("<h5>UCL's</h5>");
var url = Routing.generate('competencia');
break;
case "4": //actividadClave
winId="winActvidadClave";
wins.createWindow(winId, 1, 1, 700, 450);
wins.window(winId).setText("<h5>Competencia - Actividades Claves</h5>");
break;
case "5": //aprendizajes
winId="winAprendizaje";
wins.createWindow(winId, 1, 1, 900, 530);
wins.window(winId).setText("<h5>Conocimiento - Aprendizajes</h5>");
break;
case "6": //conocimientos
winId="winConocimiento";
wins.createWindow(winId, 1, 1, 900, 630);
wins.window(winId).setText("<h5>Competencias Conductuales</h5>");
var url = Routing.generate('conocimiento');
break;
case "7": //pregunta
winId="winPregunta";
wins.createWindow(winId, 1, 1, 900, 630);
wins.window(winId).setText("Cuestionario Evaluacion");
parametros=[{'preguntaTipoId': maeParametros}];
var maeParametros = JSON.stringify(parametros);
break;
case "8": //clientes
winId="winCliente";
wins.createWindow(winId, 1, 1, 900, 630);
wins.window(winId).setText("Clientes");
var url = Routing.generate('empresa');
break;
case "9": //cursos
winId="winCurso";
wins.createWindow(winId, 1, 1, 900, 630);
wins.window(winId).setText("Cursos");
break;
case "11": //evaluaciones
winId="winEvaluacion";
wins.createWindow(winId, 1, 1, 900, 630);
wins.window(winId).setText("Evaluaciones");
var url = Routing.generate('evaluacion');
break;
}
// switch (maeTipoId) {
// case 1:
// case 2:
// case 3:
// case 4:
// winId="winEntidad";
// wins.createWindow(winId, 1, 1, 900, 530);
// switch (maeTipoId) {
// case 1:
// wins.window(winId).setText("<h4>Clientes</h4>");
// break;
// case 2:
// wins.window(winId).setText("<h4>Proveedores</h4>");
// break;
// case 3:
// wins.window(winId).setText("<h4>Empresas de Factoring</h4>");
// break;
// case 4:
// wins.window(winId).setText("<h4>Empresas Mandantes</h4>");
// break;
// }
//
// break;
// case 5:
// winId="winEntidadDireccion";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Clientes - Direcciones</h4>");
// break;
// case 6:
// winId="winGlosaPago";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Glosas de Pago</h4>");
// break;
// case 7:
// winId="winVendedor";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Vendedores</h4>");
// break;
// case 8:
// winId="winComprador";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Compradores</h4>");
// break;
// case 9:
// winId="winObservacion";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Observaciones</h4>");
// break;
// case 10:
// winId="winSucursal";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Sucursales</h4>");
// break;
// case 11:
// winId="winBodega";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Bodegas</h4>");
// break;
// case 12:
// winId="winObra";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Obras</h4>");
// break;
// case 13:
// winId="winCuentaBanco";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Cuentas Bancos</h4>");
// break;
// case 14:
// winId="winProducto";
// wins.createWindow(winId, 1, 1, 900, 530);
// wins.window(winId).setText("<h4>Servicios o Productos</h4>");
// break;
// case 15:
// winId="winProductoFamilia";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Productos o Servicios - Familias</h4>");
// break;
// case 16:
// winId="winListaPrecio";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Lista de Precios</h4>");
// break;
// case 17:
// winId="winCentroCosto";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Centros de Costo</h4>");
// break;
// case 18:
// winId="winCurso";
// wins.createWindow(winId, 1, 1, 900, 530);
// wins.window(winId).setText("<h4>Cursos</h4>");
// break;
// case 19:
// winId="winRelator";
// wins.createWindow(winId, 1, 1, 900, 530);
// wins.window(winId).setText("<h4>Relatores</h4>");
// break;
// }
//win.window("VtnResumenLibro").
wins.window(winId).setModal(true);
//winReferenciaForm.setText("<span class='text_title_header'>Header Text</span>");
//winReferenciaForm.button("close").disable();
wins.window(winId).button("minmax").disable();
//winFac.attachObject("dvReferencias", false);
wins.window(winId).centerOnScreen();
//winReferenciaForm.attachHTMLString("hola!");
//dhxWins.window(id).progressOn();
wins.window(winId).progressOn();
//dhxWins.window(id).setIconCss(css);
//wins.window(winId).setIconCss("without_icon");
//var urlParametros={'maeTipoId':maeTipoId, 'winParent': winParent, 'maeParametros': maeParametros};
//var url = Routing.generate('maestro', urlParametros);
//alert(url);
wins.window(winId).attachURL(url);
wins.window(winId).attachEvent("onContentLoaded", function(id){
//alert(id.id);
id.progressOff();
var ifr = id.getFrame();
ifr.contentWindow.wins=wins;
//ifr.contentWindow.winParent=winParent;
//alert(ifr.contentWindow.winParent);
});
}
function maeVolver(maeTipoId, winParent, winName, maeParametros) {
winId=winName;
wins.window(winId).progressOn();
var jsnParametros = JSON.stringify(maeParametros);
var urlParametros = {'maeTipoId': maeTipoId, 'winParent':winParent, 'maeParametros': jsnParametros};
var url=Routing.generate('maestro', urlParametros);
document.location.href=url;
}
| mujd/Tarea6 | web/public/js/mae/maeFunciones.js | JavaScript | mit | 10,330 |
namespace Turbo.Plugins.Jack.Alerts
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Turbo.Plugins.Default;
using Turbo.Plugins.Jack.Models;
using Turbo.Plugins.Jack.Extensions;
/// <summary>
/// Helper class to display visual alerts
/// </summary>
public class Alert
{
public IController Hud { get; private set; }
public IPlayer Player { get { return Hud.Game.Me; } }
// state
public bool Enabled { get; set; }
public bool MultiLine { get; set; }
public bool Visible
{
get
{
return Rule != null && Rule.VisibleCondition != null && Rule.VisibleCondition.Invoke(Player);
}
}
// conditions
public AlertRule Rule { get; set; }
// decorators
public TopLabelDecorator Label { get; set; }
public WorldDecoratorCollection PlayerDecorators { get; set; }
public WorldDecoratorCollection ActorDecorators { get; set; }
// text
public string MessageFormat { get; set; }
public uint TextSnoId { get; set; }
public string AlertText { get; set; }
public Func<uint, string> AlertTextFunc { get; set; }
public Func<IEnumerable<string>> LinesFunc { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Alert" /> class.
/// </summary>
/// <param name="hud">The hud.</param>
/// <param name="heroClass">The hero class.</param>
/// <param name="text">The text.</param>
public Alert(IController hud, HeroClass heroClass = HeroClass.None, string text = null)
{
Hud = hud;
Enabled = true;
MessageFormat = "{0}";
AlertText = text;
if (text == null)
AlertTextFunc = (id) => Hud.GuessLocalizedName(id);
else
AlertTextFunc = (id) => text;
Rule = new AlertRule(hud, heroClass);
Label = new TopLabelDecorator(Hud)
{
TextFont = Hud.Render.CreateFont("tahoma", 11, 255, 244, 30, 30, false, false, 242, 0, 0, 0, true),
TextFunc = () => string.Format(CultureInfo.InvariantCulture, MessageFormat, AlertText ?? AlertTextFunc.Invoke(TextSnoId)),
};
}
}
} | JackCeparou/JackCeparouCompass | Alerts/Alert.cs | C# | mit | 2,405 |
// Generated by CoffeeScript 1.7.1
(function() {
var M, TRM, TYPES, alert, badge, debug, echo, help, info, log, njs_fs, options, rainbow, rpr, urge, warn, whisper,
__slice = [].slice;
njs_fs = require('fs');
TYPES = require('coffeenode-types');
TRM = require('coffeenode-trm');
rpr = TRM.rpr.bind(TRM);
badge = 'HOLLERITH/KEY';
log = TRM.get_logger('plain', badge);
info = TRM.get_logger('info', badge);
whisper = TRM.get_logger('whisper', badge);
alert = TRM.get_logger('alert', badge);
debug = TRM.get_logger('debug', badge);
warn = TRM.get_logger('warn', badge);
help = TRM.get_logger('help', badge);
urge = TRM.get_logger('urge', badge);
echo = TRM.echo.bind(TRM);
rainbow = TRM.rainbow.bind(TRM);
options = require('../../options');
M = options['marks'];
/*
*===========================================================================================================
888b 888 8888888888 888 888
8888b 888 888 888 o 888
88888b 888 888 888 d8b 888
888Y88b 888 8888888 888 d888b 888
888 Y88b888 888 888d88888b888
888 Y88888 888 88888P Y88888
888 Y8888 888 8888P Y8888
888 Y888 8888888888 888P Y888
*===========================================================================================================
*/
this.new_key = function() {
var complement, complement_esc, datatype, idx, idxs, index_count, pad, predicate, predicate_esc, schema, theme, theme_esc, topic, topic_esc, type;
schema = arguments[0], theme = arguments[1], topic = arguments[2], predicate = arguments[3], complement = arguments[4], idx = 6 <= arguments.length ? __slice.call(arguments, 5) : [];
/* TAINT should go to `hollerith/KEY` */
if ((datatype = schema[predicate]) == null) {
throw new Error("unknown datatype " + (rpr(predicate)));
}
index_count = datatype['index-count'], type = datatype.type, pad = datatype.pad;
if (index_count !== idx.length) {
throw new Error("need " + index_count + " indices for predicate " + (rpr(predicate)) + ", got " + idx.length);
}
theme_esc = KEY.esc(theme);
topic_esc = KEY.esc(topic);
predicate_esc = KEY.esc(predicate);
complement_esc = KEY.esc(complement);
/* TAINT parametrize */
idxs = index_count === 0 ? '' : idxs.join(',');
return 's' + '|' + theme_esc + '|' + topic_esc + '|' + predicate_esc + '|' + complement_esc + '|' + idxs;
};
/*
*===========================================================================================================
.d88888b. 888 8888888b.
d88P" "Y88b 888 888 "Y88b
888 888 888 888 888
888 888 888 888 888
888 888 888 888 888
888 888 888 888 888
Y88b. .d88P 888 888 .d88P
"Y88888P" 88888888 8888888P"
*===========================================================================================================
*/
this.new_route = function(realm, type, name) {
var R, part;
R = [realm, type];
if (name != null) {
R.push(name);
}
return ((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = R.length; _i < _len; _i++) {
part = R[_i];
_results.push(this.esc(part));
}
return _results;
}).call(this)).join(M['slash']);
};
this.new_id = function(realm, type, idn) {
var slash;
slash = M['slash'];
return (this.new_route(realm, type)) + slash + (this.esc(idn));
};
this.new_node = function() {
var R, crumb, idn, joiner, realm, tail, type;
realm = arguments[0], type = arguments[1], idn = arguments[2], tail = 4 <= arguments.length ? __slice.call(arguments, 3) : [];
joiner = M['joiner'];
R = M['primary'] + M['node'] + joiner + (this.new_id(realm, type, idn));
if (tail.length > 0) {
R += M['slash'] + (((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = tail.length; _i < _len; _i++) {
crumb = tail[_i];
_results.push(this.esc(crumb));
}
return _results;
}).call(this)).join(M['slash']));
}
R += joiner;
return R;
};
this.new_secondary_node = function() {
var R, crumb, idn, joiner, realm, slash, tail, type;
realm = arguments[0], type = arguments[1], idn = arguments[2], tail = 4 <= arguments.length ? __slice.call(arguments, 3) : [];
joiner = M['joiner'];
slash = M['slash'];
R = M['secondary'] + M['node'] + slash + (this.esc(realm)) + (this.esc(type));
if (tail.length > 0) {
R += joiner + (((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = tail.length; _i < _len; _i++) {
crumb = tail[_i];
_results.push(this.esc(crumb));
}
return _results;
}).call(this)).join(slash));
}
R += joiner + (this.esc(idn)) + joiner;
return R;
};
this.new_facet_pair = function(realm, type, idn, name, value, distance) {
if (distance == null) {
distance = 0;
}
return [this.new_facet(realm, type, idn, name, value, distance), this.new_secondary_facet(realm, type, idn, name, value, distance)];
};
this.new_facet = function(realm, type, idn, name, value, distance) {
var joiner;
if (distance == null) {
distance = 0;
}
joiner = M['joiner'];
return M['primary'] + M['facet'] + joiner + (this.new_id(realm, type, idn)) + joiner + (this.esc(name)) + joiner + (this.esc(value)) + joiner + distance + joiner;
};
this.new_secondary_facet = function(realm, type, idn, name, value, distance) {
var joiner;
if (distance == null) {
distance = 0;
}
joiner = M['joiner'];
return M['secondary'] + M['facet'] + joiner + (this.new_route(realm, type)) + joiner + (this.esc(name)) + joiner + (this.esc(value)) + joiner + (this.esc(idn)) + joiner + distance + joiner;
};
this.new_link_pair = function(realm_0, type_0, idn_0, realm_1, type_1, idn_1, distance) {
if (distance == null) {
distance = 0;
}
return [this.new_link(realm_0, type_0, idn_0, realm_1, type_1, idn_1, distance), this.new_secondary_link(realm_0, type_0, idn_0, realm_1, type_1, idn_1, distance)];
};
this.new_link = function(realm_0, type_0, idn_0, realm_1, type_1, idn_1, distance) {
var joiner;
if (distance == null) {
distance = 0;
}
joiner = M['joiner'];
return M['primary'] + M['link'] + joiner + (this.new_id(realm_0, type_0, idn_0)) + joiner + (this.new_id(realm_1, type_1, idn_1)) + joiner + distance + joiner;
};
this.new_secondary_link = function(realm_0, type_0, idn_0, realm_1, type_1, idn_1, distance) {
var joiner;
if (distance == null) {
distance = 0;
}
joiner = M['joiner'];
return M['secondary'] + M['link'] + joiner + (this.new_route(realm_0, type_0)) + joiner + (this.new_id(realm_1, type_1, idn_1)) + joiner + (this.esc(idn_0)) + joiner + distance + joiner;
};
this.read = function(key) {
var R, fields, layer, type, _ref, _ref1;
_ref = key.split(M['joiner']), (_ref1 = _ref[0], layer = _ref1[0], type = _ref1[1]), fields = 2 <= _ref.length ? __slice.call(_ref, 1) : [];
switch (layer) {
case M['primary']:
switch (type) {
case M['node']:
R = this._read_primary_node.apply(this, fields);
break;
case M['facet']:
R = this._read_primary_facet.apply(this, fields);
break;
case M['link']:
R = this._read_primary_link.apply(this, fields);
break;
default:
throw new Error("unknown type mark " + (rpr(type)));
}
break;
case M['secondary']:
switch (type) {
case M['facet']:
R = this._read_secondary_facet.apply(this, fields);
break;
case M['link']:
R = this._read_secondary_link.apply(this, fields);
break;
default:
throw new Error("unknown type mark " + (rpr(type)));
}
break;
default:
throw new Error("unknown layer mark " + (rpr(layer)));
}
R['key'] = key;
return R;
};
this._read_primary_node = function(id) {
var R;
R = {
level: 'primary',
type: 'node',
id: id
};
return R;
};
this._read_primary_facet = function(id, name, value, distance) {
var R;
R = {
level: 'primary',
type: 'facet',
id: id,
name: name,
value: value,
distance: parseInt(distance, 10)
};
return R;
};
this._read_primary_link = function(id_0, id_1, distance) {
var R;
R = {
level: 'primary',
type: 'link',
id: id_0,
target: id_1,
distance: parseInt(distance, 10)
};
return R;
};
this._read_secondary_facet = function(route, name, value, idn, distance) {
var R;
R = {
level: 'secondary',
type: 'facet',
id: route + M['slash'] + idn,
name: name,
value: value,
distance: parseInt(distance, 10)
};
return R;
};
this._read_secondary_link = function(route_0, id_1, idn_0, distance) {
var R, id_0;
id_0 = route_0 + M['slash'] + idn_0;
R = {
level: 'secondary',
type: 'link',
id: id_0,
target: id_1,
distance: parseInt(distance, 10)
};
return R;
};
this.infer = function(key_0, key_1) {
return this._infer(key_0, key_1, 'primary');
};
this.infer_secondary = function(key_0, key_1) {
return this._infer(key_0, key_1, 'secondary');
};
this.infer_pair = function(key_0, key_1) {
return this._infer(key_0, key_1, 'pair');
};
this._infer = function(key_0, key_1, mode) {
var id_1, id_2, info_0, info_1, type_0, type_1;
info_0 = TYPES.isa_text(key_0) ? this.read(key_0) : key_0;
info_1 = TYPES.isa_text(key_1) ? this.read(key_1) : key_1;
if ((type_0 = info_0['type']) === 'link') {
if ((id_1 = info_0['target']) !== (id_2 = info_1['id'])) {
throw new Error("unable to infer link from " + (rpr(info_0['key'])) + " and " + (rpr(info_1['key'])));
}
switch (type_1 = info_1['type']) {
case 'link':
return this._infer_link(info_0, info_1, mode);
case 'facet':
return this._infer_facet(info_0, info_1, mode);
}
}
throw new Error("expected a link plus a link or a facet, got a " + type_0 + " and a " + type_1);
};
this._infer_facet = function(link, facet, mode) {
var distance, facet_idn, facet_realm, facet_type, link_idn, link_realm, link_type, name, slash, value, _ref, _ref1;
_ref = this.split_id(link['id']), link_realm = _ref[0], link_type = _ref[1], link_idn = _ref[2];
_ref1 = this.split_id(link['id']), facet_realm = _ref1[0], facet_type = _ref1[1], facet_idn = _ref1[2];
/* TAINT route not distinct from ID? */
/* TAINT should slashes in name be escaped? */
/* TAINT what happens when we infer from an inferred facet? do all the escapes get re-escaped? */
/* TAINT use module method */
slash = M['slash'];
/* TAINT make use of dash configurable */
name = (this.esc(facet_realm)) + '-' + (this.esc(facet_type)) + '-' + (this.esc(facet['name']));
value = facet['value'];
distance = link['distance'] + facet['distance'] + 1;
switch (mode) {
case 'primary':
return this.new_facet(link_realm, link_type, link_idn, name, value, distance);
case 'secondary':
return this.new_secondary_facet(link_realm, link_type, link_idn, name, value, distance);
case 'pair':
return this.new_facet_pair(link_realm, link_type, link_idn, name, value, distance);
default:
throw new Error("unknown mode " + (rpr(mode)));
}
};
this._infer_link = function(link_0, link_1, mode) {
/*
$^|gtfs/stoptime/876|0|gtfs/trip/456
+ $^|gtfs/trip/456|0|gtfs/route/777
----------------------------------------------------------------
= $^|gtfs/stoptime/876|1|gtfs/route/777
= %^|gtfs/stoptime|1|gtfs/route/777|876
*/
var distance, idn_0, idn_2, realm_0, realm_2, type_0, type_2, _ref, _ref1;
_ref = this.split_id(link_0['id']), realm_0 = _ref[0], type_0 = _ref[1], idn_0 = _ref[2];
_ref1 = this.split_id(link_1['target']), realm_2 = _ref1[0], type_2 = _ref1[1], idn_2 = _ref1[2];
distance = link_0['distance'] + link_1['distance'] + 1;
switch (mode) {
case 'primary':
return this.new_link(realm_0, type_0, idn_0, realm_2, type_2, idn_2, distance);
case 'secondary':
return this.new_secondary_link(realm_0, type_0, idn_0, realm_2, type_2, idn_2, distance);
case 'pair':
return this.new_link_pair(realm_0, type_0, idn_0, realm_2, type_2, idn_2, distance);
default:
throw new Error("unknown mode " + (rpr(mode)));
}
};
this.esc = (function() {
/* TAINT too complected */
var d, escape, joiner_matcher, joiner_replacer;
escape = function(text) {
var R;
R = text;
R = R.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1');
R = R.replace(/\x08/g, '\\x08');
return R;
};
joiner_matcher = new RegExp(escape(M['joiner']), 'g');
/* TAINT not correct, could be single digit if byte value < 0x10 */
joiner_replacer = ((function() {
var _i, _len, _ref, _results;
_ref = new Buffer(M['joiner']);
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
d = _ref[_i];
_results.push('µ' + d.toString(16));
}
return _results;
})()).join('');
return function(x) {
var R;
if (x === void 0) {
throw new Error("value cannot be undefined");
}
R = TYPES.isa_text(x) ? x : rpr(x);
R = R.replace(/µ/g, 'µb5');
R = R.replace(joiner_matcher, joiner_replacer);
return R;
};
})();
this.unescape = function(text_esc) {
var matcher;
matcher = /µ([0-9a-f]{2})/g;
return text_esc.replace(matcher, function(_, cid_hex) {
return String.fromCharCode(parseInt(cid_hex, 16));
});
};
this.split_id = function(id) {
/* TAINT must unescape */
var R, slash;
R = id.split(slash = M['slash']);
if (R.length !== 3) {
throw new Error("expected three parts separated by " + (rpr(slash)) + ", got " + (rpr(id)));
}
if (!(R[0].length > 0)) {
throw new Error("realm cannot be empty in " + (rpr(id)));
}
if (!(R[1].length > 0)) {
throw new Error("type cannot be empty in " + (rpr(id)));
}
if (!(R[2].length > 0)) {
throw new Error("IDN cannot be empty in " + (rpr(id)));
}
return R;
};
this.split = function(x) {
return x.split(M['joiner']);
};
this.split_compound_selector = function(compound_selector) {
/* TAINT must unescape */
return compound_selector.split(M['loop']);
};
this._idn_from_id = function(id) {
var match;
match = id.replace(/^.+?([^\/]+)$/);
if (match == null) {
throw new Error("not a valid ID: " + (rpr(id)));
}
return match[1];
};
this.lte_from_gte = function(gte) {
var R, length;
length = Buffer.byteLength(gte);
R = new Buffer(1 + length);
R.write(gte);
R[length] = 0xff;
return R;
};
if (module.parent == null) {
help(this.new_id('gtfs', 'stop', '123'));
help(this.new_facet('gtfs', 'stop', '123', 'name', 1234));
help(this.new_facet('gtfs', 'stop', '123', 'name', 'foo/bar|baz'));
help(this.new_facet('gtfs', 'stop', '123', 'name', 'Bayerischer Platz'));
help(this.new_secondary_facet('gtfs', 'stop', '123', 'name', 'Bayerischer Platz'));
help(this.new_facet_pair('gtfs', 'stop', '123', 'name', 'Bayerischer Platz'));
help(this.new_link('gtfs', 'stoptime', '456', 'gtfs', 'stop', '123'));
help(this.new_secondary_link('gtfs', 'stoptime', '456', 'gtfs', 'stop', '123'));
help(this.new_link_pair('gtfs', 'stoptime', '456', 'gtfs', 'stop', '123'));
help(this.read(this.new_facet('gtfs', 'stop', '123', 'name', 'Bayerischer Platz')));
help(this.read(this.new_secondary_facet('gtfs', 'stop', '123', 'name', 'Bayerischer Platz')));
help(this.read(this.new_link('gtfs', 'stoptime', '456', 'gtfs', 'stop', '123')));
help(this.read(this.new_secondary_link('gtfs', 'stoptime', '456', 'gtfs', 'stop', '123')));
help(this.infer('$^|gtfs/stoptime/876|0|gtfs/trip/456', '$^|gtfs/trip/456|0|gtfs/route/777'));
help(this.infer('$^|gtfs/stoptime/876|0|gtfs/trip/456', '%^|gtfs/trip|0|gtfs/route/777|456'));
help(this.infer('$^|gtfs/trip/456|0|gtfs/stop/123', '$:|gtfs/stop/123|0|name|Bayerischer Platz'));
help(this.infer('$^|gtfs/stoptime/876|1|gtfs/stop/123', '$:|gtfs/stop/123|0|name|Bayerischer Platz'));
}
}).call(this);
| loveencounterflow/hollerith1 | lib/scratch/KEY.js | JavaScript | mit | 16,912 |
def goodSegement1(badList,l,r):
sortedBadList = sorted(badList)
current =sortedBadList[0]
maxVal = 0
for i in range(len(sortedBadList)):
current = sortedBadList[i]
maxIndex = i+1
# first value
if i == 0 and l<=current<=r:
val = current - l
prev = l
print("first index value")
print("prev, current : ",prev,current)
if(val>maxVal):
maxVal = val
print("1. (s,e)",l,current)
# other middle values
elif l<=current<=r:
prev = sortedBadList[i-1]
val = current - prev
print("prev, current : ",prev,current)
if(val>maxVal):
maxVal = val
print("2. (s,e)",prev,current)
# last value
if maxIndex == len(sortedBadList) and l<=current<=r:
print("last index value")
next = r
val = next - current
if(val>maxVal):
maxVal = val
print("3. (s,e)",current,next)
print("maxVal:",maxVal-1)
pass
goodSegement1([2,5,8,10,3],1,12)
goodSegement1([37,7,22,15,49,60],3,48)
| nithincvpoyyil/nithincvpoyyil.github.io | test.py | Python | mit | 1,191 |
module Licode
# Defines errors raised by methods of the Licode Ruby SDK.
class LicodeError < StandardError; end
# Defines errors raised when authentication fails
class LicodeAuthenticationError < LicodeError; end
end
| joshuairl/licode-ruby-sdk | lib/licode/exceptions.rb | Ruby | mit | 227 |
/*
* Copyright 2002-2011 Drew Noakes
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* More information about this project is available at:
*
* http://drewnoakes.com/code/exif/
* http://code.google.com/p/metadata-extractor/
*/
package com.drew.metadata.exif;
import com.drew.lang.annotations.NotNull;
import com.drew.lang.annotations.Nullable;
import com.drew.metadata.TagDescriptor;
/**
* Provides human-readable string representations of tag values stored in a <code>KyoceraMakernoteDirectory</code>.
* <p/>
* Some information about this makernote taken from here:
* http://www.ozhiker.com/electronics/pjmt/jpeg_info/kyocera_mn.html
* <p/>
* Most manufacturer's MakerNote counts the "offset to data" from the first byte
* of TIFF header (same as the other IFD), but Kyocera (along with Fujifilm) counts
* it from the first byte of MakerNote itself.
*
* @author Drew Noakes http://drewnoakes.com
*/
public class KyoceraMakernoteDescriptor extends TagDescriptor<KyoceraMakernoteDirectory>
{
public KyoceraMakernoteDescriptor(@NotNull KyoceraMakernoteDirectory directory)
{
super(directory);
}
@Nullable
public String getDescription(int tagType)
{
switch (tagType) {
case KyoceraMakernoteDirectory.TAG_KYOCERA_PRINT_IMAGE_MATCHING_INFO:
return getPrintImageMatchingInfoDescription();
case KyoceraMakernoteDirectory.TAG_KYOCERA_PROPRIETARY_THUMBNAIL:
return getProprietaryThumbnailDataDescription();
default:
return super.getDescription(tagType);
}
}
@Nullable
public String getPrintImageMatchingInfoDescription()
{
byte[] bytes = _directory.getByteArray(KyoceraMakernoteDirectory.TAG_KYOCERA_PRINT_IMAGE_MATCHING_INFO);
if (bytes==null)
return null;
return "(" + bytes.length + " bytes)";
}
@Nullable
public String getProprietaryThumbnailDataDescription()
{
byte[] bytes = _directory.getByteArray(KyoceraMakernoteDirectory.TAG_KYOCERA_PROPRIETARY_THUMBNAIL);
if (bytes==null)
return null;
return "(" + bytes.length + " bytes)";
}
}
| lany/phototagger | src/com/drew/metadata/exif/KyoceraMakernoteDescriptor.java | Java | mit | 2,815 |
package xdg_test
import (
"os"
"path/filepath"
"testing"
"github.com/adrg/xdg"
"github.com/stretchr/testify/require"
)
type envSample struct {
name string
value string
expected interface{}
actual interface{}
}
func testDirs(t *testing.T, samples ...*envSample) {
// Test home directory.
require.NotEmpty(t, xdg.Home)
t.Logf("Home: %s", xdg.Home)
// Set environment variables.
for _, sample := range samples {
require.NoError(t, os.Setenv(sample.name, sample.value))
}
xdg.Reload()
// Test results.
for _, sample := range samples {
var actual interface{}
switch v := sample.actual.(type) {
case *string:
actual = *v
case *[]string:
actual = *v
}
require.Equal(t, sample.expected, actual)
t.Logf("%s: %v", sample.name, actual)
}
}
type testInputData struct {
relPaths []string
pathFunc func(string) (string, error)
searchFunc func(string) (string, error)
}
func TestBaseDirFuncs(t *testing.T) {
inputs := []*testInputData{
{
relPaths: []string{"app.data", "appname/app.data"},
pathFunc: xdg.DataFile,
searchFunc: xdg.SearchDataFile,
},
{
relPaths: []string{"app.yaml", "appname/app.yaml"},
pathFunc: xdg.ConfigFile,
searchFunc: xdg.SearchConfigFile,
},
{
relPaths: []string{"app.state", "appname/app.state"},
pathFunc: xdg.StateFile,
searchFunc: xdg.SearchStateFile,
},
{
relPaths: []string{"app.cache", "appname/app.cache"},
pathFunc: xdg.CacheFile,
searchFunc: xdg.SearchCacheFile,
},
{
relPaths: []string{"app.pid", "appname/app.pid"},
pathFunc: xdg.RuntimeFile,
searchFunc: xdg.SearchRuntimeFile,
},
}
// Test base directories for regular files.
testBaseDirsRegular(t, inputs)
// Test base directories for symbolic links.
for _, input := range inputs {
input.relPaths = []string{input.relPaths[1]}
}
testBaseDirsSymlinks(t, inputs)
}
func testBaseDirsRegular(t *testing.T, inputs []*testInputData) {
for _, input := range inputs {
for _, relPath := range input.relPaths {
// Get suitable path for input file.
expFullPath, err := input.pathFunc(relPath)
require.NoError(t, err)
// Create input file.
f, err := os.Create(expFullPath)
require.NoError(t, err)
require.NoError(t, f.Close())
// Search input file after creation.
actFullPath, err := input.searchFunc(relPath)
require.NoError(t, err)
require.Equal(t, expFullPath, actFullPath)
// Remove created file.
require.NoError(t, os.Remove(expFullPath))
// Search input file after removal.
_, err = input.searchFunc(relPath)
require.Error(t, err)
// Check that the same path is returned.
actFullPath, err = input.pathFunc(relPath)
require.NoError(t, err)
require.Equal(t, expFullPath, actFullPath)
}
}
}
func testBaseDirsSymlinks(t *testing.T, inputs []*testInputData) {
for _, input := range inputs {
for _, relPath := range input.relPaths {
// Get suitable path for input file.
expFullPath, err := input.pathFunc(relPath)
require.NoError(t, err)
// Replace input directory with symlink.
symlinkDir := filepath.Dir(expFullPath)
inputDir := filepath.Join(filepath.Dir(symlinkDir), "inputdir")
require.NoError(t, os.Remove(symlinkDir))
require.NoError(t, os.Mkdir(inputDir, os.ModeDir|0700))
require.NoError(t, os.Symlink(inputDir, symlinkDir))
// Create input file.
inputPath := filepath.Join(symlinkDir, "input.file")
f, err := os.Create(inputPath)
require.NoError(t, err)
require.NoError(t, f.Close())
// Create symbolic link.
require.NoError(t, os.Symlink(inputPath, expFullPath))
// Search input file after creation.
actFullPath, err := input.searchFunc(relPath)
require.NoError(t, err)
require.Equal(t, expFullPath, actFullPath)
// Remove created symbolic links, files and directories.
require.NoError(t, os.Remove(expFullPath))
require.NoError(t, os.Remove(inputPath))
require.NoError(t, os.Remove(symlinkDir))
require.NoError(t, os.Remove(inputDir))
// Search input file after removal.
_, err = input.searchFunc(relPath)
require.Error(t, err)
// Check that the same path is returned.
actFullPath, err = input.pathFunc(relPath)
require.NoError(t, err)
require.Equal(t, expFullPath, actFullPath)
}
}
}
func TestInvalidPaths(t *testing.T) {
inputs := map[string]func(string) (string, error){
"\000/app.data": xdg.DataFile,
"appname\000/app.yaml": xdg.ConfigFile,
"appname/\000/app.state": xdg.StateFile,
"\000appname/app.cache": xdg.CacheFile,
"\000/appname/app.pid": xdg.RuntimeFile,
}
for inputPath, xdgFunc := range inputs {
_, err := xdgFunc(inputPath)
require.Error(t, err)
}
}
| adrg/xdg | xdg_test.go | GO | mit | 4,720 |
import sublime, sublime_plugin
from indenttxt import indentparser
class IndentToList(sublime_plugin.TextCommand):
def run(self, edit):
parser = indentparser.IndentTxtParser()
#Get current selection
sels = self.view.sel()
selsParsed = 0
if(len(sels) > 0):
for sel in sels:
#Make sure selection isn't just a cursor
if(abs(sel.b - sel.a) > 0):
self.parseRegion(parser, sel, edit)
selsParsed += 1
#All selections just cursor marks?
if(selsParsed == 0):
region = sublime.Region(0, self.view.size() - 1)
self.parseRegion(parser, region, edit)
def parseRegion(self, parser, region, edit):
lines = self.view.line(region)
text = self.view.substr(lines)
indented = parser.parseText(text)
newview = self.view.window().new_file()
newview.insert(edit, 0, indented)
| Harrison-M/indent.txt-sublime | indentsublime.py | Python | mit | 967 |
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :email
t.string :salt
t.string :crypted_password
t.boolean :admin
t.string :name
t.timestamps null: false
end
end
end
| luketlancaster/where-coffee | db/migrate/20150615180544_create_users.rb | Ruby | mit | 258 |
def Setup(Settings,DefaultModel):
# set1-test_of_models_against_datasets/osm299.py
Settings["experiment_name"] = "set1_Mix_model_versus_datasets_299px"
Settings["graph_histories"] = ['together'] #['all','together',[],[1,0],[0,0,0],[]]
# 5556x_minlen30_640px 5556x_minlen20_640px 5556x_reslen20_299px 5556x_reslen30_299px
n=0
Settings["models"][n]["dataset_name"] = "5556x_reslen30_299px"
Settings["models"][n]["dump_file_override"] = 'SegmentsData_marked_R100_4Tables.dump'
Settings["models"][n]["pixels"] = 299
Settings["models"][n]["model_type"] = 'img_osm_mix'
Settings["models"][n]["unique_id"] = 'mix_minlen30_299px'
Settings["models"][n]["top_repeat_FC_block"] = 2
Settings["models"][n]["epochs"] = 800
Settings["models"].append(DefaultModel.copy())
n+=1
Settings["models"][n]["dataset_pointer"] = -1
Settings["models"][n]["dataset_name"] = "5556x_reslen20_299px"
Settings["models"][n]["dump_file_override"] = 'SegmentsData_marked_R100_4Tables.dump'
Settings["models"][n]["pixels"] = 299
Settings["models"][n]["model_type"] = 'img_osm_mix'
Settings["models"][n]["unique_id"] = 'mix_minlen20_299px'
Settings["models"][n]["top_repeat_FC_block"] = 2
Settings["models"][n]["epochs"] = 800
Settings["models"].append(DefaultModel.copy())
n+=1
Settings["models"][n]["dataset_pointer"] = -1
Settings["models"][n]["dataset_name"] = "5556x_mark_res_299x299"
Settings["models"][n]["dump_file_override"] = 'SegmentsData_marked_R100_4Tables.dump'
Settings["models"][n]["pixels"] = 299
Settings["models"][n]["model_type"] = 'img_osm_mix'
Settings["models"][n]["unique_id"] = 'mix_nosplit_299px'
Settings["models"][n]["top_repeat_FC_block"] = 2
Settings["models"][n]["epochs"] = 800
return Settings
| previtus/MGR-Project-Code | Settings/set1-test_of_models_against_datasets/mix299.py | Python | mit | 1,829 |
# A Nested Array to Model a Bingo Board SOLO CHALLENGE
# I spent [#] hours on this challenge.
#The first number in the sub-arrays correspond to the letter "B", the second "I", the third "N", the fourth "G", and the fifth "O". So if the call was N34, you would look in the third column for the number 34. If the number is on your board, you'll replace it with an "X."
# Release 0: Pseudocode
# Outline:
# Create a method to generate a letter ( b, i, n, g, o) and a number (1-100) done
#bingo should correspond to the index of the number within the array... probably going to have to try an if loop here. if number @ index is called, return the letter that corresponds to that index. done
# Check the called column for the number called. done
#identify the index of the number called, index == column
# If the number is in the column, replace with an 'x' done
#if element is identified in that particular array, replace with x; else nothing. done
# Display a column to the console done
#column should display at the end of each number done
# Display the board to the console (prettily)
#this will be a pain. it's done. It's not awesome, but I'm ok with that.
# Initial Solution
=begin
class BingoBoard
attr_accessor :bingo_board
attr_reader :letters
attr_accessor :call_out
def initialize(board)
@bingo_board = board
@letters = ["B", "I", "N", "G", "O"]
@call_out = []
end
#Create a method to call letters and numbers (like B43). It will need to generate a letter ( "B", "I", "N", "G", "O") and a number from 1 to 100.
def call_out_update
@call_out[0] = letters.sample
@call_out[1] = rand 1..100
p @call_out
end
def check_board(call_out)
called_letter = call_out[0]
called_num = call_out[1]
check_letters = []
check_letters << @bingo_board
#need to find the number in the array. if the number is in index 0, return B, if it's in index 1, return I, if it's in index 2 return N, else G, else 0
#index is an array method, so you can't call index on the element itself. this is also an enumerator.
if called_letter == 'B'
i = 0
check_letters.map! { |array|
if array.is_a? Array
array.each { |array_num|
if called_num == array_num[0]
array[i].shift
array[i].insert(0, 'x')
else
i += 1
end
}
end
}
elsif called_letter == 'I'
i = 0
check_letters.map! { |array|
if array.is_a? Array
array.each { |array_num|
if called_num == array_num[1]
array[i].shift
array[i].insert(1, 'x')
else
i += 1
end
}
end
}
elsif called_letter == 'N'
i = 0
check_letters.map! { |array|
if array.is_a? Array
array.each { |array_num|
if called_num == array_num[2]
array[i].shift
array[i].insert(2, 'x')
else
i += 1
end
}
end
}
elsif called_letter == 'G'
i = 0
check_letters.map! { |array|
if array.is_a? Array
array.each { |array_num|
if called_num == array_num[3]
array[i].shift
array[i].insert(3, 'x')
else
i += 1
end
}
end
}
elsif called_letter == 'O'
i = 0
check_letters.map! { |array|
if array.is_a? Array
array.each { |array_num|
if called_num == array_num[4]
array[i].shift
array[i].insert(4, 'x')
else
i += 1
end
}
end
}
else
puts "what?"
end
check_letters.flatten!(1)
@bingo_board == check_letters
puts @bingo_board[0].to_s
puts @bingo_board[1].to_s
puts @bingo_board[2].to_s
puts @bingo_board[3].to_s
puts @bingo_board[4].to_s
end
end
=end
# Refactored Solution
# I spent over 3 hours on this. It needs to be refactored. I'm tomboxing myself, if there is time at the end of the week I will refactor. This is some seriously awful code work though, super repetetive. I will try to refactor it by the end of the week.
class BingoBoard
attr_accessor :bingo_board
attr_reader :letters
attr_accessor :call_out
def initialize(board)
@bingo_board = board
@letters = ["B", "I", "N", "G", "O"]
@call_out = []
end
#Create a method to call letters and numbers (like B43). It will need to generate a letter ( "B", "I", "N", "G", "O") and a number from 1 to 100.
def call_out_update
@call_out[0] = letters.sample
@call_out[1] = rand 1..100
p @call_out
end
def check_board(call_out)
called_letter = call_out[0]
called_num = call_out[1]
check_letters = []
check_letters << @bingo_board
bingo_hash = {
"B" => 0,
"I" => 1,
"N" => 2,
"G" => 3,
"O" => 4
}
if bingo_hash.has_key?(called_letter)
check_letters.map! { |element|
if element.is_a? Array
element.each { |array_num|
if called_num == array_num[bingo_hash[called_letter]]
element[bingo_hash[called_letter]].shift
element[bingo_hash[called_letter]].insert(bingo_hash[called_letter], 'x')
end
}
end
}
else
puts "what?"
end
check_letters.flatten!(1)
@bingo_board == check_letters
puts @bingo_board[0].to_s
puts @bingo_board[1].to_s
puts @bingo_board[2].to_s
puts @bingo_board[3].to_s
puts @bingo_board[4].to_s
end
end
#DRIVER CODE (I.E. METHOD CALLS) GO BELOW THIS LINE
board = [[47, 44, 71, 8, 88],
[22, 69, 75, 65, 73],
[84, 85, 97, 89, 57],
[25, 31, 96, 68, 51],
[75, 70, 54, 80, 83]]
new_game = BingoBoard.new(board)
new_game.check_board(new_game.call_out_update)
#Reflection
=begin
How difficult was pseudocoding this challenge? What do you think of your pseudocoding style?
I thought the pseudo coding was ok when I did it. When I went to code I realized I was focusing on the wrong thing and copied in the actual items to focus on. My pseudocoding style needs work as a whole.
What are the benefits of using a class for this challenge?
a class can pass information between it's methods easier than methods not contained by a class can.
How can you access coordinates in a nested array?
array[0][0] is an example. It pulls the first item from the first array within the array. you can stack as needed.
What methods did you use to access and modify the array?
map * a lot. there are totally better ways to do this. I couldn't find them on my initial solution.
Give an example of a new method you learned while reviewing the Ruby docs. Based on what you see in the docs, what purpose does it serve, and how is it called?
haven't reviewed any for this. I did use each_with_index on the 6.7 challenge. I may try to incorporate that here. it seems like it would cut down the mountains / valleys I created here.
How did you determine what should be an instance variable versus a local variable?
By not planning ahead. I ended up trying to use as many instance variables as possible in the end so that way the information could be used in the entire class.
What do you feel is most improved in your refactored solution?
results pending on that one.
=end
| cguard90/phase-0 | week-6/bingo_solution.rb | Ruby | mit | 7,469 |
/* The MIT License (MIT)
Copyright (c) 2014 Thomas James Barry, Zachary Y. Gateley, Kenneth Drew Gonzales
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 tzk.image.tool;
import java.awt.event.MouseEvent;
import tzk.image.ui.*;
import java.util.ArrayList;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.SwingUtilities;
/**
* Fill allows users to paint a whole area of the same color, with a
* single color.
*
* Contributers: Thomas James Barry/ thomasbarry92@gmail.com /5076942
* Zachary Gateley/ zach.cykic@gmail.com /5415772
* K Drew Gonzales/ drewgonzales360@gmail.com /5470602
*/
public class Fill extends SimpleTool {
public Fill(ImageCraft iC) {
super(iC);
imageCraft = iC;
super.setButton(imageCraft.jFill);
}
/**
* Bucket fill.
* If the pixel clicked on is a different color than the current color
* from ImageCraft (primaryColor for left mouse button, secondaryColor
* for right mouse button), change color of this pixel and all adjacent
* pixels of the same color to the current color.
* @param evt
*/
@Override
public void mousePressed(MouseEvent evt) {
// Get the color that we're working with
// Left button clicked: use primary color
// Right button clicked: use secondary color
Color toColor = imageCraft.getPaintColor(!SwingUtilities.isRightMouseButton(evt));
// The point clicked on
// These integers variables will be reused in our loop
int x = evt.getX();
int y = evt.getY();
// The current, visible BufferedImage canvas area
BufferedImage image = imageCraft.drawingArea.getCurrentDrawing();
// This is the color that we will paint over.
// Second parameter of Color constructor keeps alpha channel
Color fromColor = new Color(image.getRGB(x, y), true);
// Make sure that we clicked on a color that is not the color to paint with
if (toColor.equals(fromColor)) {
// If it is the same color, do nothing.
System.out.println("Cannot fill. Clicked same color.");
System.out.println("toColor: "+toColor);
System.out.println("fromColor: "+fromColor);
return;
}
// FILL
// Create stack of coordinate points to fill
// Each coordinate takes up two elements, x on even number, y on odd number
// For each coordinate in the stack, pull the pen up. Go upwards until
// the color is no longer threshold distance from fromColor.
// Then put the pen down and start drawing downwards until the color
// is no longer threshold distance from fromColor.
// On the way down, check left and right. If the side color is
// threshold distance from fromColor, add that point to the stack,
// if a point on that unbroken line segment has not already been
// added to the stack.
ArrayList<Integer> stack = new ArrayList<>();
stack.add(x);
stack.add(y);
// Create a new BufferedImage object
// This will be sent to SimpleHistory constructor
BufferedImage fillImage = imageCraft.newBlankImage();
Graphics fillGraphics = fillImage.getGraphics();
// The graphics object of the BufferedImage itself
Graphics imageGraphics = image.getGraphics();
// Set the color of the graphics object to our paint color
fillGraphics.setColor(toColor);
imageGraphics.setColor(toColor);
// This will represent the pixel being checked
Color color;
// colorDistance from fromColor that passes as a pixel to be painted
// Maybe we can let the user select this?
int threshold = 50;
// Whether we need to check the left side or the right side
boolean checkLeft, checkRight;
// Draw the line segment once, not once per pixel
// This remembers where to start drawing the line
int yTop;
// Remember image width and height since they are used within the loop
int width = image.getWidth();
int height = image.getHeight();
// Loop through each coordinate in the stack
while (stack.size() > 0) {
// Get x, y coordinates, the first two elements in the stack
x = stack.remove(0);
y = stack.remove(0);
yTop = y;
// Go to top of line, pen up (not painting)
while (y > 0) {
color = new Color(image.getRGB(x, y - 1), true);
if (colorDistance(color, fromColor) > threshold) {
break;
}
y--;
}
// Reset booleans to true. We want to start checking the sides
// of our line immediately
checkLeft = true;
checkRight = true;
// Start painting downwards, checking left and right as we go
while (y < height) {
color = new Color(image.getRGB(x, y), true);
// Hit a barrier. Stop.
if (colorDistance(color, fromColor) > threshold) {
break;
}
// Check left
// Only check up until the left side of the image
if (x > 0) {
color = new Color(image.getRGB(x - 1, y), true);
// If color.equals(toColor), then we have already painted
// this pixel
if (!color.equals(toColor) &&
colorDistance(color, fromColor) <= threshold) {
// If we haven't seen a pixel on the left side that we
// want to fill yet, be vigilant
if (checkLeft) {
// We have a match!
// Add coordinates to stack
stack.add(x - 1);
stack.add(y);
// Stop looking on the left side
checkLeft = false;
}
}
// Otherwise, when we see something that we do *not* want
// to fill, start being vigilant again for a pixel to fill
else {
checkLeft = true;
}
}
// Check right
// Only check up to the right side of the image
if (x < width - 1) {
color = new Color(image.getRGB(x + 1, y), true);
// If color.equals(toColor), then we have already painted
// this pixel
if (!color.equals(toColor) &&
colorDistance(color, fromColor) <= threshold) {
// If we haven't seen a pixel on the right side that we
// want to fill yet, be vigilant
if (checkRight) {
// We have a match!
// Add coordinates to stack
stack.add(x + 1);
stack.add(y);
// Stop looking on the right side
checkRight = false;
}
}
// Otherwise, when we see something that we do *not* want
// to fill, start being vigilant again for a pixel to fill
else {
checkRight = true;
}
}
// Increment row, get new color for condition and loop
y++;
}
// Draw the column's line in both the action image
// and the currentImage. We need it
fillGraphics.drawLine(x, yTop, x, y - 1);
imageGraphics.drawLine(x, yTop, x, y - 1);
}
// Draw our final image
imageCraft.drawingArea.getGraphics().drawImage(image, 0, 0, null);
imageCraft.drawingArea.getGraphics().drawImage(fillImage, 0, 0, null);
// Create new history object in layer
imageCraft.currentLayer.addHistory(fillImage, "Fill");
}
/**
* Do nothing. Fill only works on mousePressed.
* @param evt
*/
@Override
public void mouseDragged(MouseEvent evt) {
}
/**
* Do nothing. Fill only works on mousePressed.
*
* @param evt
*/
@Override
public void mouseReleased(MouseEvent evt) {
}
/**
* Checks the length of the distance between two colors in RGBA four space.
* This method plots out the coordinates of the channels of two colors
* passed as parameters into four space and calculates the length
* of the line segment connecting the two points.
*
* @param color1
* @param color2
* @return
*/
private int colorDistance(Color color1, Color color2) {
int r1 = color1.getRed();
int g1 = color1.getGreen();
int b1 = color1.getBlue();
int a1 = color1.getAlpha();
int r2 = color2.getRed();
int g2 = color2.getGreen();
int b2 = color2.getBlue();
int a2 = color2.getAlpha();
return (int) Math.sqrt(Math.pow(r2 - r1, 2) + Math.pow(g2 - g1, 2) + Math.pow(b2 - b1, 2) + Math.pow(a2 - a1, 2));
}
// Variables declaration
private final ImageCraft imageCraft;
// End of variables declaration
}
| thomasjbarry/Image-Craft | tzk.imagecraft/src/tzk/image/tool/Fill.java | Java | mit | 11,078 |
"use strict";
var Construct = require("can-construct");
var define = require("can-define");
var make = define.make;
var queues = require("can-queues");
var addTypeEvents = require("can-event-queue/type/type");
var ObservationRecorder = require("can-observation-recorder");
var canLog = require("can-log");
var canLogDev = require("can-log/dev/dev");
var defineHelpers = require("../define-helpers/define-helpers");
var assign = require("can-assign");
var diff = require("can-diff/list/list");
var ns = require("can-namespace");
var canReflect = require("can-reflect");
var canSymbol = require("can-symbol");
var singleReference = require("can-single-reference");
var splice = [].splice;
var runningNative = false;
var identity = function(x) {
return x;
};
// symbols aren't enumerable ... we'd need a version of Object that treats them that way
var localOnPatchesSymbol = "can.patches";
var makeFilterCallback = function(props) {
return function(item) {
for (var prop in props) {
if (item[prop] !== props[prop]) {
return false;
}
}
return true;
};
};
var onKeyValue = define.eventsProto[canSymbol.for("can.onKeyValue")];
var offKeyValue = define.eventsProto[canSymbol.for("can.offKeyValue")];
var getSchemaSymbol = canSymbol.for("can.getSchema");
var inSetupSymbol = canSymbol.for("can.initializing");
function getSchema() {
var definitions = this.prototype._define.definitions;
var schema = {
type: "list",
keys: {}
};
schema = define.updateSchemaKeys(schema, definitions);
if(schema.keys["#"]) {
schema.values = definitions["#"].Type;
delete schema.keys["#"];
}
return schema;
}
/** @add can-define/list/list */
var DefineList = Construct.extend("DefineList",
/** @static */
{
setup: function(base) {
if (DefineList) {
addTypeEvents(this);
var prototype = this.prototype;
var result = define(prototype, prototype, base.prototype._define);
define.makeDefineInstanceKey(this, result);
var itemsDefinition = result.definitions["#"] || result.defaultDefinition;
if (itemsDefinition) {
if (itemsDefinition.Type) {
this.prototype.__type = make.set.Type("*", itemsDefinition.Type, identity);
} else if (itemsDefinition.type) {
this.prototype.__type = make.set.type("*", itemsDefinition.type, identity);
}
}
this[getSchemaSymbol] = getSchema;
}
}
},
/** @prototype */
{
// setup for only dynamic DefineMap instances
setup: function(items) {
if (!this._define) {
Object.defineProperty(this, "_define", {
enumerable: false,
value: {
definitions: {
length: { type: "number" },
_length: { type: "number" }
}
}
});
Object.defineProperty(this, "_data", {
enumerable: false,
value: {}
});
}
define.setup.call(this, {}, false);
Object.defineProperty(this, "_length", {
enumerable: false,
configurable: true,
writable: true,
value: 0
});
if (items) {
this.splice.apply(this, [ 0, 0 ].concat(canReflect.toArray(items)));
}
},
__type: define.types.observable,
_triggerChange: function(attr, how, newVal, oldVal) {
var index = +attr;
// `batchTrigger` direct add and remove events...
// Make sure this is not nested and not an expando
if ( !isNaN(index)) {
var itemsDefinition = this._define.definitions["#"];
var patches, dispatched;
if (how === 'add') {
if (itemsDefinition && typeof itemsDefinition.added === 'function') {
ObservationRecorder.ignore(itemsDefinition.added).call(this, newVal, index);
}
patches = [{type: "splice", insert: newVal, index: index, deleteCount: 0}];
dispatched = {
type: how,
action: "splice",
insert: newVal,
index: index,
deleteCount: 0,
patches: patches
};
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
dispatched.reasonLog = [ canReflect.getName(this), "added", newVal, "at", index ];
}
//!steal-remove-end
this.dispatch(dispatched, [ newVal, index ]);
} else if (how === 'remove') {
if (itemsDefinition && typeof itemsDefinition.removed === 'function') {
ObservationRecorder.ignore(itemsDefinition.removed).call(this, oldVal, index);
}
patches = [{type: "splice", index: index, deleteCount: oldVal.length}];
dispatched = {
type: how,
patches: patches,
action: "splice",
index: index, deleteCount: oldVal.length,
target: this
};
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
dispatched.reasonLog = [ canReflect.getName(this), "remove", oldVal, "at", index ];
}
//!steal-remove-end
this.dispatch(dispatched, [ oldVal, index ]);
} else {
this.dispatch(how, [ newVal, index ]);
}
} else {
this.dispatch({
type: "" + attr,
target: this
}, [ newVal, oldVal ]);
}
},
get: function(index) {
if (arguments.length) {
if(isNaN(index)) {
ObservationRecorder.add(this, index);
} else {
ObservationRecorder.add(this, "length");
}
return this[index];
} else {
return canReflect.unwrap(this, Map);
}
},
set: function(prop, value) {
// if we are setting a single value
if (typeof prop !== "object") {
// We want change events to notify using integers if we're
// setting an integer index. Note that <float> % 1 !== 0;
prop = isNaN(+prop) || (prop % 1) ? prop : +prop;
if (typeof prop === "number") {
// Check to see if we're doing a .attr() on an out of
// bounds index property.
if (typeof prop === "number" &&
prop > this._length - 1) {
var newArr = new Array((prop + 1) - this._length);
newArr[newArr.length - 1] = value;
this.push.apply(this, newArr);
return newArr;
}
this.splice(prop, 1, value);
} else {
var defined = defineHelpers.defineExpando(this, prop, value);
if (!defined) {
this[prop] = value;
}
}
}
// otherwise we are setting multiple
else {
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
canLogDev.warn('can-define/list/list.prototype.set is deprecated; please use can-define/list/list.prototype.assign or can-define/list/list.prototype.update instead');
}
//!steal-remove-end
//we are deprecating this in #245
if (canReflect.isListLike(prop)) {
if (value) {
this.replace(prop);
} else {
canReflect.assignList(this, prop);
}
} else {
canReflect.assignMap(this, prop);
}
}
return this;
},
assign: function(prop) {
if (canReflect.isListLike(prop)) {
canReflect.assignList(this, prop);
} else {
canReflect.assignMap(this, prop);
}
return this;
},
update: function(prop) {
if (canReflect.isListLike(prop)) {
canReflect.updateList(this, prop);
} else {
canReflect.updateMap(this, prop);
}
return this;
},
assignDeep: function(prop) {
if (canReflect.isListLike(prop)) {
canReflect.assignDeepList(this, prop);
} else {
canReflect.assignDeepMap(this, prop);
}
return this;
},
updateDeep: function(prop) {
if (canReflect.isListLike(prop)) {
canReflect.updateDeepList(this, prop);
} else {
canReflect.updateDeepMap(this, prop);
}
return this;
},
_items: function() {
var arr = [];
this._each(function(item) {
arr.push(item);
});
return arr;
},
_each: function(callback) {
for (var i = 0, len = this._length; i < len; i++) {
callback(this[i], i);
}
},
splice: function(index, howMany) {
var args = canReflect.toArray(arguments),
added = [],
i, len, listIndex,
allSame = args.length > 2,
oldLength = this._length;
index = index || 0;
// converting the arguments to the right type
for (i = 0, len = args.length - 2; i < len; i++) {
listIndex = i + 2;
args[listIndex] = this.__type(args[listIndex], listIndex);
added.push(args[listIndex]);
// Now lets check if anything will change
if (this[i + index] !== args[listIndex]) {
allSame = false;
}
}
// if nothing has changed, then return
if (allSame && this._length <= added.length) {
return added;
}
// default howMany if not provided
if (howMany === undefined) {
howMany = args[1] = this._length - index;
}
runningNative = true;
var removed = splice.apply(this, args);
runningNative = false;
queues.batch.start();
if (howMany > 0) {
// tears down bubbling
this._triggerChange("" + index, "remove", undefined, removed);
}
if (args.length > 2) {
this._triggerChange("" + index, "add", added, removed);
}
this.dispatch('length', [ this._length, oldLength ]);
queues.batch.stop();
return removed;
},
/**
*/
serialize: function() {
return canReflect.serialize(this, Map);
}
}
);
for(var prop in define.eventsProto) {
Object.defineProperty(DefineList.prototype, prop, {
enumerable:false,
value: define.eventsProto[prop],
writable: true
});
}
var eventsProtoSymbols = ("getOwnPropertySymbols" in Object) ?
Object.getOwnPropertySymbols(define.eventsProto) :
[canSymbol.for("can.onKeyValue"), canSymbol.for("can.offKeyValue")];
eventsProtoSymbols.forEach(function(sym) {
Object.defineProperty(DefineList.prototype, sym, {
configurable: true,
enumerable:false,
value: define.eventsProto[sym],
writable: true
});
});
// Converts to an `array` of arguments.
var getArgs = function(args) {
return args[0] && Array.isArray(args[0]) ?
args[0] :
canReflect.toArray(args);
};
// Create `push`, `pop`, `shift`, and `unshift`
canReflect.eachKey({
push: "length",
unshift: 0
},
// Adds a method
// `name` - The method name.
// `where` - Where items in the `array` should be added.
function(where, name) {
var orig = [][name];
DefineList.prototype[name] = function() {
// Get the items being added.
var args = [],
// Where we are going to add items.
len = where ? this._length : 0,
i = arguments.length,
res, val;
// Go through and convert anything to a `map` that needs to be converted.
while (i--) {
val = arguments[i];
args[i] = this.__type(val, i);
}
// Call the original method.
runningNative = true;
res = orig.apply(this, args);
runningNative = false;
if (!this.comparator || args.length) {
queues.batch.start();
this._triggerChange("" + len, "add", args, undefined);
this.dispatch('length', [ this._length, len ]);
queues.batch.stop();
}
return res;
};
});
canReflect.eachKey({
pop: "length",
shift: 0
},
// Creates a `remove` type method
function(where, name) {
var orig = [][name];
DefineList.prototype[name] = function() {
if (!this._length) {
// For shift and pop, we just return undefined without
// triggering events.
return undefined;
}
var args = getArgs(arguments),
len = where && this._length ? this._length - 1 : 0,
oldLength = this._length ? this._length : 0,
res;
// Call the original method.
runningNative = true;
res = orig.apply(this, args);
runningNative = false;
// Create a change where the args are
// `len` - Where these items were removed.
// `remove` - Items removed.
// `undefined` - The new values (there are none).
// `res` - The old, removed values (should these be unbound).
queues.batch.start();
this._triggerChange("" + len, "remove", undefined, [ res ]);
this.dispatch('length', [ this._length, oldLength ]);
queues.batch.stop();
return res;
};
});
canReflect.eachKey({
"map": 3,
"filter": 3,
"reduce": 4,
"reduceRight": 4,
"every": 3,
"some": 3
},
function a(fnLength, fnName) {
DefineList.prototype[fnName] = function() {
var self = this;
var args = [].slice.call(arguments, 0);
var callback = args[0];
var thisArg = args[fnLength - 1] || self;
if (typeof callback === "object") {
callback = makeFilterCallback(callback);
}
args[0] = function() {
var cbArgs = [].slice.call(arguments, 0);
// use .get(index) to ensure observation added.
// the arguments are (item, index) or (result, item, index)
cbArgs[fnLength - 3] = self.get(cbArgs[fnLength - 2]);
return callback.apply(thisArg, cbArgs);
};
var ret = Array.prototype[fnName].apply(this, args);
if(fnName === "map") {
return new DefineList(ret);
}
else if(fnName === "filter") {
return new self.constructor(ret);
} else {
return ret;
}
};
});
assign(DefineList.prototype, {
includes: (function(){
var arrayIncludes = Array.prototype.includes;
if(arrayIncludes){
return function includes() {
return arrayIncludes.apply(this, arguments);
};
} else {
return function includes() {
throw new Error("DefineList.prototype.includes must have Array.prototype.includes available. Please add a polyfill to this environment.");
};
}
})(),
indexOf: function(item, fromIndex) {
for (var i = fromIndex || 0, len = this.length; i < len; i++) {
if (this.get(i) === item) {
return i;
}
}
return -1;
},
lastIndexOf: function(item, fromIndex) {
fromIndex = typeof fromIndex === "undefined" ? this.length - 1: fromIndex;
for (var i = fromIndex; i >= 0; i--) {
if (this.get(i) === item) {
return i;
}
}
return -1;
},
join: function() {
ObservationRecorder.add(this, "length");
return [].join.apply(this, arguments);
},
reverse: function() {
// this shouldn't be observable
var list = [].reverse.call(this._items());
return this.replace(list);
},
slice: function() {
// tells computes to listen on length for changes.
ObservationRecorder.add(this, "length");
var temp = Array.prototype.slice.apply(this, arguments);
return new this.constructor(temp);
},
concat: function() {
var args = [];
// Go through each of the passed `arguments` and
// see if it is list-like, an array, or something else
canReflect.eachIndex(arguments, function(arg) {
if (canReflect.isListLike(arg)) {
// If it is list-like we want convert to a JS array then
// pass each item of the array to this.__type
var arr = Array.isArray(arg) ? arg : canReflect.toArray(arg);
arr.forEach(function(innerArg) {
args.push(this.__type(innerArg));
}, this);
} else {
// If it is a Map, Object, or some primitive
// just pass arg to this.__type
args.push(this.__type(arg));
}
}, this);
// We will want to make `this` list into a JS array
// as well (We know it should be list-like), then
// concat with our passed in args, then pass it to
// list constructor to make it back into a list
return new this.constructor(Array.prototype.concat.apply(canReflect.toArray(this), args));
},
forEach: function(cb, thisarg) {
var item;
for (var i = 0, len = this.length; i < len; i++) {
item = this.get(i);
if (cb.call(thisarg || item, item, i, this) === false) {
break;
}
}
return this;
},
replace: function(newList) {
var patches = diff(this, newList);
queues.batch.start();
for (var i = 0, len = patches.length; i < len; i++) {
this.splice.apply(this, [
patches[i].index,
patches[i].deleteCount
].concat(patches[i].insert));
}
queues.batch.stop();
return this;
},
sort: function(compareFunction) {
var sorting = Array.prototype.slice.call(this);
Array.prototype.sort.call(sorting, compareFunction);
this.splice.apply(this, [0,sorting.length].concat(sorting) );
return this;
}
});
// Add necessary event methods to this object.
for (var prop in define.eventsProto) {
DefineList[prop] = define.eventsProto[prop];
Object.defineProperty(DefineList.prototype, prop, {
enumerable: false,
value: define.eventsProto[prop],
writable: true
});
}
Object.defineProperty(DefineList.prototype, "length", {
get: function() {
if (!this[inSetupSymbol]) {
ObservationRecorder.add(this, "length");
}
return this._length;
},
set: function(newVal) {
if (runningNative) {
this._length = newVal;
return;
}
// Don't set _length if:
// - null or undefined
// - a string that doesn't convert to number
// - already the length being set
if (newVal == null || isNaN(+newVal) || newVal === this._length) {
return;
}
if (newVal > this._length - 1) {
var newArr = new Array(newVal - this._length);
this.push.apply(this, newArr);
}
else {
this.splice(newVal);
}
},
enumerable: true
});
DefineList.prototype.attr = function(prop, value) {
canLog.warn("DefineMap::attr shouldn't be called");
if (arguments.length === 0) {
return this.get();
} else if (prop && typeof prop === "object") {
return this.set.apply(this, arguments);
} else if (arguments.length === 1) {
return this.get(prop);
} else {
return this.set(prop, value);
}
};
DefineList.prototype.item = function(index, value) {
if (arguments.length === 1) {
return this.get(index);
} else {
return this.set(index, value);
}
};
DefineList.prototype.items = function() {
canLog.warn("DefineList::get should should be used instead of DefineList::items");
return this.get();
};
var defineListProto = {
// type
"can.isMoreListLikeThanMapLike": true,
"can.isMapLike": true,
"can.isListLike": true,
"can.isValueLike": false,
// get/set
"can.getKeyValue": DefineList.prototype.get,
"can.setKeyValue": DefineList.prototype.set,
// Called for every reference to a property in a template
// if a key is a numerical index then translate to length event
"can.onKeyValue": function(key, handler, queue) {
var translationHandler;
if (isNaN(key)) {
return onKeyValue.apply(this, arguments);
}
else {
translationHandler = function() {
handler(this[key]);
};
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
Object.defineProperty(translationHandler, "name", {
value: "translationHandler(" + key + ")::" + canReflect.getName(this) + ".onKeyValue('length'," + canReflect.getName(handler) + ")",
});
}
//!steal-remove-end
singleReference.set(handler, this, translationHandler, key);
return onKeyValue.call(this, 'length', translationHandler, queue);
}
},
// Called when a property reference is removed
"can.offKeyValue": function(key, handler, queue) {
var translationHandler;
if ( isNaN(key)) {
return offKeyValue.apply(this, arguments);
}
else {
translationHandler = singleReference.getAndDelete(handler, this, key);
return offKeyValue.call(this, 'length', translationHandler, queue);
}
},
"can.deleteKeyValue": function(prop) {
// convert string key to number index if key can be an integer:
// isNaN if prop isn't a numeric representation
// (prop % 1) if numeric representation is a float
// In both of the above cases, leave as string.
prop = isNaN(+prop) || (prop % 1) ? prop : +prop;
if(typeof prop === "number") {
this.splice(prop, 1);
} else if(prop === "length" || prop === "_length") {
return; // length must not be deleted
} else {
this.set(prop, undefined);
}
return this;
},
// shape get/set
"can.assignDeep": function(source){
queues.batch.start();
canReflect.assignList(this, source);
queues.batch.stop();
},
"can.updateDeep": function(source){
queues.batch.start();
this.replace(source);
queues.batch.stop();
},
// observability
"can.keyHasDependencies": function(key) {
return !!(this._computed && this._computed[key] && this._computed[key].compute);
},
"can.getKeyDependencies": function(key) {
var ret;
if(this._computed && this._computed[key] && this._computed[key].compute) {
ret = {};
ret.valueDependencies = new Set();
ret.valueDependencies.add(this._computed[key].compute);
}
return ret;
},
/*"can.onKeysAdded": function(handler,queue) {
this[canSymbol.for("can.onKeyValue")]("add", handler,queue);
},
"can.onKeysRemoved": function(handler,queue) {
this[canSymbol.for("can.onKeyValue")]("remove", handler,queue);
},*/
"can.splice": function(index, deleteCount, insert){
this.splice.apply(this, [index, deleteCount].concat(insert));
},
"can.onPatches": function(handler,queue){
this[canSymbol.for("can.onKeyValue")](localOnPatchesSymbol, handler,queue);
},
"can.offPatches": function(handler,queue) {
this[canSymbol.for("can.offKeyValue")](localOnPatchesSymbol, handler,queue);
}
};
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
defineListProto["can.getName"] = function() {
return canReflect.getName(this.constructor) + "[]";
};
}
//!steal-remove-end
canReflect.assignSymbols(DefineList.prototype, defineListProto);
canReflect.setKeyValue(DefineList.prototype, canSymbol.iterator, function() {
var index = -1;
if(typeof this.length !== "number") {
this.length = 0;
}
return {
next: function() {
index++;
return {
value: this[index],
done: index >= this.length
};
}.bind(this)
};
});
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
// call `list.log()` to log all event changes
// pass `key` to only log the matching event, e.g: `list.log("add")`
DefineList.prototype.log = defineHelpers.log;
}
//!steal-remove-end
define.DefineList = DefineList;
module.exports = ns.DefineList = DefineList;
| canjs/can-define | list/list.js | JavaScript | mit | 21,262 |
package com.clusterpoint.api.request;
import java.util.HashMap;
import java.util.Map;
import org.w3c.dom.Node;
/**
* The CPSPartialReplaceRequest class is a wrapper for the CPSModifyRequest class for the partial-replace command
* @see com.clusterpoint.api.response.CPSModifyResponse
*/
public class CPSPartialReplaceRequest extends CPSModifyRequest {
/**
* Constructs an instance of the CPSPartialReplaceRequest class.
*/
public CPSPartialReplaceRequest() {
super("partial-replace");
}
/**
* Constructs an instance of the CPSPartialReplaceRequest class.
* @param id document id
* @param document replaceable document contents
*/
public CPSPartialReplaceRequest(String id, String document) {
super("partial-replace");
Map<String, String> map = new HashMap<String, String>();
map.put(id, document);
this.setDocuments(map);
}
/**
* Constructs an instance of the CPSPartialReplaceRequest class.
* @param document replaceable document content with document id in it
*/
public CPSPartialReplaceRequest(String document) {
super("partial-replace", document);
}
/**
* Constructs an instance of the CPSPartialReplaceRequest class.
* @param document Document as DOM Node
*/
public CPSPartialReplaceRequest(Node document) {
super("partial-replace", document);
}
}
| clusterpoint/java-client-api | src/com/clusterpoint/api/request/CPSPartialReplaceRequest.java | Java | mit | 1,298 |
using Abp.Domain.Services;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Nankingcigar.Demo.Core.DomainService.Route
{
public interface IRouteManager : IDomainService
{
Task<IEnumerable<Entity.View.Route.Route>> GetRoutesByModuleAndUser(string moduleName);
}
} | CigarYang/Demo | Nankingcigar.Demo.Core/DomainService/Route/IRouteManager.cs | C# | mit | 311 |
version https://git-lfs.github.com/spec/v1
oid sha256:691b4033e555f469bcdba73a60c0e6a24b38ebffbbf94ebe7ba61e3edbf61601
size 6745
| yogeshsaroya/new-cdnjs | ajax/libs/blueimp-file-upload/9.5.2/jquery.fileupload-angular.min.js | JavaScript | mit | 129 |
<?php
namespace Gedmo\Tree;
use Doctrine\Common\EventManager;
use Tool\BaseTestCaseORM;
use Doctrine\Common\Util\Debug;
use Tree\Fixture\Transport\Car;
use Tree\Fixture\Transport\Bus;
use Tree\Fixture\Transport\Vehicle;
use Tree\Fixture\Transport\Engine;
/**
* These are tests for Tree behavior
*
* @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
* @package Gedmo.Tree
* @link http://www.gediminasm.org
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
class MultiInheritanceTest3 extends BaseTestCaseORM
{
const CAR = "Tree\Fixture\Transport\Car";
const BUS = "Tree\Fixture\Transport\Bus";
const VEHICLE = "Tree\Fixture\Transport\Vehicle";
const ENGINE = "Tree\Fixture\Transport\Engine";
protected function setUp()
{
parent::setUp();
$evm = new EventManager;
$evm->addEventSubscriber(new TreeListener);
$this->getMockSqliteEntityManager($evm);
}
public function testConsistence()
{
$this->populate();
$carRepo = $this->em->getRepository(self::CAR);
$audi = $carRepo->findOneByTitle('Audi-80');
$this->assertEquals(2, $carRepo->childCount($audi));
$this->assertEquals(1, $audi->getLeft());
$this->assertEquals(6, $audi->getRight());
$children = $carRepo->children($audi);
$this->assertCount(2, $children);
$path = $carRepo->getPath($children[0]);
$this->assertCount(2, $path);
$carRepo->moveDown($children[0]);
$this->assertEquals(4, $children[0]->getLeft());
$this->assertEquals(5, $children[0]->getRight());
$this->assertTrue($carRepo->verify());
}
/*public function testHeavyLoad()
{
$carRepo = $this->em->getRepository(self::CAR);
$parent = null;
$num = 100;
for($i = 0; $i < 100; $i++) {
$engine = new Engine;
$engine->setType('e'.$i);
$engine->setValves(8);
$this->em->persist($engine);
$car = new Car;
$car->setParent($parent);
$car->setTitle('car'.$i);
$car->setEngine($engine);
$this->em->persist($car);
// siblings
$rnd = rand(0, 3);
for ($j = 0; $j < $rnd; $j++) {
$siblingEngine = new Engine;
$siblingEngine->setType('e'.$i.$j);
$siblingEngine->setValves(8);
$this->em->persist($siblingEngine);
$siblingCar = new Car;
$siblingCar->setTitle('car'.$i.$j);
$siblingCar->setEngine($siblingEngine);
$siblingCar->setParent($car);
$this->em->persist($siblingCar);
}
$num += $rnd;
$parent = $car;
}
$this->em->flush();
$this->assertTrue($carRepo->verify());
var_dump('processed: '.$num);
}*/
protected function getUsedEntityFixtures()
{
return array(
self::VEHICLE,
self::CAR,
self::ENGINE,
self::BUS
);
}
private function populate()
{
// engines
$v8 = new Engine;
$v8->setType('V8');
$v8->setValves(8);
$this->em->persist($v8);
$v6 = new Engine;
$v6->setType('V6');
$v6->setValves(8);
$this->em->persist($v6);
$vb8 = new Engine;
$vb8->setType('VB8');
$vb8->setValves(8);
$this->em->persist($vb8);
$jet = new Engine;
$jet->setType('Jet');
$jet->setValves(16);
$this->em->persist($jet);
// cars
$audi80 = new Car;
$audi80->setEngine($v6);
$audi80->setTitle('Audi-80');
$this->em->persist($audi80);
$audi80s = new Car;
$audi80s->setParent($audi80);
$audi80s->setTitle('Audi-80s');
$audi80s->setEngine($v8);
$this->em->persist($audi80s);
$icarus = new Bus;
$icarus->setEngine($vb8);
$icarus->setTitle('Icarus');
$this->em->persist($icarus);
$audiJet = new Car;
$audiJet->setParent($audi80);
$audiJet->setTitle('Audi-jet');
$audiJet->setEngine($jet);
$this->em->persist($audiJet);
$this->em->flush();
$this->em->flush();
}
} | torstenzander/myinvoiz | vendor/gedmo-doctrine-extensions/tests/Gedmo/Tree/MultiInheritanceTest3.php | PHP | mit | 4,377 |
<?php
/**
* @brief Application Class
* @author <a href='http://www.invisionpower.com'>Invision Power Services, Inc.</a>
* @copyright (c) 2001 - 2016 Invision Power Services, Inc.
* @license http://www.invisionpower.com/legal/standards/
* @package IPS Community Suite
* @since 18 Feb 2013
* @version SVN_VERSION_NUMBER
*/
namespace IPS;
/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
exit;
}
/**
* @brief Abstract class that applications extend and use to handle application data
*/
class _Application extends \IPS\Node\Model
{
/**
* @brief IPS Applications
*/
public static $ipsApps = array(
'blog',
'calendar',
'chat',
'cms',
'core',
'downloads',
'forums',
'gallery',
'nexus'
);
/**
* @brief [ActiveRecord] Multiton Store
*/
protected static $multitons;
/**
* @brief Have fetched all?
*/
protected static $gotAll = FALSE;
/**
* @brief Defined versions
*/
protected $definedVersions = NULL;
/**
* @brief [Node] Title prefix. If specified, will look for a language key with "{$key}_title" as the key
*/
public static $titleLangPrefix = '__app_';
/**
* @brief Defined theme locations for the theme system
*/
public $themeLocations = array('admin', 'front', 'global');
/**
* Set default
*
* @return void
*/
public function setAsDefault()
{
/* Update any FURL customizations */
if ( \IPS\Settings::i()->furl_configuration )
{
$furlCustomizations = json_decode( \IPS\Settings::i()->furl_configuration, TRUE );
try
{
/* Add the top-level directory to all the FURLs for the old default app */
$previousDefaultApp = \IPS\Db::i()->select( 'app_directory', 'core_applications', 'app_default=1' )->first();
if( file_exists( \IPS\ROOT_PATH . "/applications/{$previousDefaultApp}/data/furl.json" ) )
{
$oldDefaultAppDefinition = json_decode( preg_replace( '/\/\*.+?\*\//s', '', \file_get_contents( \IPS\ROOT_PATH . "/applications/{$previousDefaultApp}/data/furl.json" ) ), TRUE );
if ( $oldDefaultAppDefinition['topLevel'] )
{
foreach ( $oldDefaultAppDefinition['pages'] as $k => $data )
{
if ( isset( $furlCustomizations[ $k ] ) )
{
$furlCustomizations[ $k ] = \IPS\Http\Url\Friendly::buildFurlDefinition( $furlCustomizations[ $k ]['friendly'], $furlCustomizations[ $k ]['real'], $newDefaultAppDefinition['topLevel'], FALSE, $furlCustomizations[ $k ]['alias'], $furlCustomizations[ $k ]['custom'], $furlCustomizations[ $k ]['verify'] );
}
}
}
}
}
catch ( \UnderflowException $e ){}
/* And remove it from the new */
if( file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/furl.json" ) )
{
$newDefaultAppDefinition = json_decode( preg_replace( '/\/\*.+?\*\//s', '', \file_get_contents( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/furl.json" ) ), TRUE );
if ( $newDefaultAppDefinition['topLevel'] )
{
foreach ( $newDefaultAppDefinition['pages'] as $k => $data )
{
if ( isset( $furlCustomizations[ $k ] ) )
{
$furlCustomizations[ $k ] = \IPS\Http\Url\Friendly::buildFurlDefinition( rtrim( preg_replace( '/^' . preg_quote( $newDefaultAppDefinition['topLevel'], '/' ) . '\/?/', '', $furlCustomizations[ $k ]['friendly'] ), '/' ), $furlCustomizations[ $k ]['real'], $newDefaultAppDefinition['topLevel'], TRUE, $furlCustomizations[ $k ]['alias'], $furlCustomizations[ $k ]['custom'], $furlCustomizations[ $k ]['verify'] );
}
}
}
}
/* Save the new FURL customisation */
\IPS\Db::i()->update( 'core_sys_conf_settings', array( 'conf_value' => json_encode( $furlCustomizations ) ), array( 'conf_key=?', 'furl_configuration' ) );
}
/* Actually update the database */
\IPS\Db::i()->update( 'core_applications', array( 'app_default' => 0 ) );
\IPS\Db::i()->update( 'core_applications', array( 'app_default' => 1 ), array( 'app_id=?', $this->id ) );
/* Clear cached data */
unset( \IPS\Data\Store::i()->applications );
unset( \IPS\Data\Store::i()->settings );
unset( \IPS\Data\Store::i()->furl_configuration );
\IPS\Member::clearCreateMenu();
/* Clear guest page caches */
\IPS\Data\Cache::i()->clearAll();
}
/**
* Get Applications
*
* @return array
*/
public static function applications()
{
if( static::$gotAll === FALSE )
{
if ( isset( \IPS\Data\Store::i()->applications ) )
{
$rows = \IPS\Data\Store::i()->applications;
}
else
{
$rows = iterator_to_array( \IPS\Db::i()->select( '*', 'core_applications', NULL, 'app_position' ) );
\IPS\Data\Store::i()->applications = $rows;
}
static::$multitons = array();
foreach ( $rows as $row )
{
try
{
static::$multitons[ $row['app_directory'] ] = static::constructFromData( $row );
}
catch( \UnexpectedValueException $e )
{
if ( mb_stristr( $e->getMessage(), 'Missing:' ) )
{
/* Ignore this, the app is in the table, but not 4.0 compatible */
continue;
}
}
}
static::$gotAll = TRUE;
}
return static::$multitons;
}
/**
* Get enabled applications
*
* @return array
*/
public static function enabledApplications()
{
$applications = static::applications();
$enabled = array();
foreach( $applications as $key => $application )
{
if( $application->enabled )
{
$enabled[ $key ] = $application;
}
}
return $enabled;
}
/**
* Does an application exist and is it enabled? Note: does not check if offline for a particular member
*
* @see \IPS\Application::canAccess()
* @param string $key Application key
* @return bool
*/
public static function appIsEnabled( $key )
{
$applications = static::applications();
if ( !array_key_exists( $key, $applications ) )
{
return FALSE;
}
if ( ! file_exists( \IPS\ROOT_PATH . '/applications/' . $key . '/Application.php' ) )
{
return FALSE;
}
return $applications[ $key ]->enabled;
}
/**
* Load Record
*
* @see \IPS\Db::build
* @param int|string $id ID
* @param string $idField The database column that the $id parameter pertains to (NULL will use static::$databaseColumnId)
* @param mixed $extraWhereClause Additional where clause(s) (see \IPS\Db::build for details)
* @return static
* @throws \InvalidArgumentException
* @throws \OutOfRangeException
*/
public static function load( $id, $idField=NULL, $extraWhereClause=NULL )
{
static::applications(); // Load all applications so we can grab the data from the cache
return parent::load( $id, $idField, $extraWhereClause );
}
/**
* Fetch All Root Nodes
*
* @param string|NULL $permissionCheck The permission key to check for or NULl to not check permissions
* @param \IPS\Member|NULL $member The member to check permissions for or NULL for the currently logged in member
* @param mixed $where Additional WHERE clause
* @note This is overridden to prevent UnexpectedValue exceptions when there is an old application record in core_applications without an Application.php file
* @return array
*/
public static function roots( $permissionCheck='view', $member=NULL, $where=array() )
{
return static::applications();
}
/**
* Get all extensions
*
* @param \IPS\Application|string $app The app key of the application which owns the extension
* @param string $extension Extension Type
* @param \IPS\Member|bool $checkAccess Check access permission for application against supplied member (or logged in member, if TRUE) before including extension
* @param string|NULL $firstApp If specified, the application with this key will be returned first
* @param string|NULL $firstExtensionKey If specified, the extension with this key will be returned first
* @param bool $construct Should an object be returned? (If false, just the classname will be returned)
* @return array
*/
public static function allExtensions( $app, $extension, $checkAccess=TRUE, $firstApp=NULL, $firstExtensionKey=NULL, $construct=TRUE )
{
$extensions = array();
/* Get applications */
$apps = static::applications();
if ( $firstApp !== NULL )
{
$apps = static::$multitons;
usort( $apps, function( $a, $b ) use ( $firstApp )
{
if ( $a->directory === $firstApp )
{
return -1;
}
if ( $b->directory === $firstApp )
{
return 1;
}
return 0;
} );
}
/* Get extensions */
foreach ( $apps as $application )
{
if ( !static::appIsEnabled( $application->directory ) )
{
continue;
}
if( $checkAccess !== FALSE )
{
if( !$application->canAccess( $checkAccess === TRUE ? NULL : $checkAccess ) )
{
continue;
}
}
$_extensions = array();
foreach ( $application->extensions( $app, $extension, $construct, $checkAccess ) as $key => $class )
{
$_extensions[ $application->directory . '_' . $key ] = $class;
}
if ( $firstExtensionKey !== NULL AND array_key_exists( $application->directory . '_' . $firstExtensionKey, $_extensions ) )
{
uksort( $_extensions, function( $a, $b ) use ( $application, $firstExtensionKey )
{
if ( $a === $application->directory . '_' . $firstExtensionKey )
{
return -1;
}
if ( $b === $application->directory . '_' . $firstExtensionKey )
{
return 1;
}
return 0;
} );
}
$extensions = array_merge( $extensions, $_extensions );
}
/* Return */
return $extensions;
}
/**
* Retrieve a list of applications that contain a specific type of extension
*
* @param \IPS\Application|string $app The app key of the application which owns the extension
* @param string $extension Extension Type
* @param \IPS\Member|bool $checkAccess Check access permission for application against supplied member (or logged in member, if TRUE) before including extension
* @return array
*/
public static function appsWithExtension( $app, $extension, $checkAccess=TRUE )
{
$_apps = array();
foreach( static::applications() as $application )
{
if ( static::appIsEnabled( $application->directory ) )
{
/* If $checkAccess is false we don't verify access to the app */
if( $checkAccess !== FALSE )
{
/* If we passed true, we want to check current member, otherwise pass the member in directly */
if( $application->canAccess( ( $checkAccess === TRUE ) ? NULL : $checkAccess ) !== TRUE )
{
continue;
}
}
if( count( $application->extensions( $app, $extension ) ) )
{
$_apps[ $application->directory ] = $application;
}
}
}
return $_apps;
}
/**
* Get available version for an application
* Used by the installer/upgrader
*
* @param string $appKey The application key
* @param bool $human Return the human-readable version instead
* @return int|null
*/
public static function getAvailableVersion( $appKey, $human=FALSE )
{
$versionsJson = \IPS\ROOT_PATH . "/applications/{$appKey}/data/versions.json";
$_versions = $human ? array_values( json_decode( file_get_contents( $versionsJson ), TRUE ) ) : array_keys( json_decode( file_get_contents( $versionsJson ), TRUE ) );
if ( file_exists( $versionsJson ) and $versionsJson = $_versions )
{
return array_pop( $versionsJson );
}
return NULL;
}
/**
* Get all defined versions for an application
*
* @return array
*/
public function getAllVersions()
{
if( $this->definedVersions !== NULL )
{
return $this->definedVersions;
}
$this->definedVersions = array();
$versionsJson = \IPS\ROOT_PATH . "/applications/{$this->directory}/data/versions.json";
if ( file_exists( $versionsJson ) )
{
$this->definedVersions = json_decode( file_get_contents( $versionsJson ), TRUE );
}
return $this->definedVersions;
}
/**
* Return the human version of an INT long version
*
* @param int $longVersion Long version (10001)
* @return string|false Long Version (1.1.1 Beta 1)
*/
public function getHumanVersion( $longVersion )
{
$this->getAllVersions();
if ( isset( $this->definedVersions[ $longVersion ] ) )
{
return $this->definedVersions[ (int) $longVersion ];
}
return false;
}
/**
* The available version we can upgrade to
*
* @param bool $latestOnly If TRUE, will return the latest version only
* @param bool $skipSameHumanVersion If TRUE, will not include any versions with the same "human" version number as the current version
* @return array
*/
public function availableUpgrade( $latestOnly=FALSE, $skipSameHumanVersion=TRUE )
{
$update = array();
if( $this->update_version )
{
$versions = json_decode( $this->update_version, TRUE );
if ( is_array( $versions ) and !isset( $versions[0] ) and isset( $versions['longversion'] ) )
{
$versions = array( $versions );
}
$update = array();
foreach ( $versions as $data )
{
if( !empty( $data['longversion'] ) and $data['longversion'] > $this->long_version and ( !$skipSameHumanVersion or $data['version'] != $this->version ) )
{
if( $data['released'] AND intval($data['released']) == $data['released'] AND \strlen($data['released']) == 10 )
{
$data['released'] = (string) \IPS\DateTime::ts( $data['released'] )->localeDate();
}
$update[] = $data;
}
}
}
if ( !empty( $update ) and $latestOnly )
{
$update = array_pop( $update );
}
return $update;
}
/**
* Is the application up to date with security patches?
*
* @return bool
*/
public function missingSecurityPatches()
{
$updates = $this->availableUpgrade();
if( !empty( $updates ) )
{
foreach( $updates as $update )
{
if( $update['security'] )
{
return TRUE;
}
}
}
return FALSE;
}
/**
* MD5 check (returns path to files which do not match)
*
* @retrun array
* @throws \IPS\Http\Request\Exception
*/
public static function md5Check()
{
/* For Community in the Cloud customers we cannot do this because they have encoded files
and the encoder produces different output each time it runs, so every Cloud customer
has different files, even for the same version */
$key = \IPS\IPS::licenseKey();
if ( $key['cloud'] )
{
return array();
}
/* For everyone else, get the correct md5 sums for each file... */
$correctMd5s = \IPS\Http\Url::ips( 'md5' )->request()->get()->decodeJson();
/* And return whichever ones don't match */
return static::_md5sumCheckerIterator( \IPS\ROOT_PATH, $correctMd5s, 1 );
}
/**
* MD5 check directory
*
* @param string $directory Directory to look through
* @param array $correctMd5s The correct md5 hashes
* @param int $depth How deep into the folder structure we are
* @return array
*/
public static function _md5sumCheckerIterator( $directory, $correctMd5s, $depth = 1 )
{
$return = array();
foreach( new \DirectoryIterator( $directory ) as $file )
{
if ( mb_substr( $file, 0, 1 ) === '.' or mb_substr( $file, 0, 1 ) === '_' or $file == 'index.html' )
{
continue;
}
if ( $file->isDir() )
{
/* We only want to check directories which are ours (not other random directories they have on the server) and we can ignore datastore, plugins and uploads */
if ( $depth === 1 and !in_array( $file->getFilename(), array( \IPS\CP_DIRECTORY, 'api', 'applications', 'system' ) ) )
{
continue;
}
/* If this is an application directory but the application has been disabled then we shouldn't check it */
if( mb_strpos( $file->getPathname(), \IPS\ROOT_PATH . DIRECTORY_SEPARATOR . 'applications' ) !== FALSE AND $file->getFilename() != 'applications' )
{
$applications = static::applications();
/* If the directory name is a valid application key and the application is not enabled, don't check it */
if( isset( $applications[ $file->getFilename() ] ) AND !static::appIsEnabled( $file->getFilename() ) )
{
continue;
}
}
$return = array_merge( $return, static::_md5sumCheckerIterator( $file->getPathname(), $correctMd5s, $depth + 1 ) );
}
elseif ( mb_substr( $file, -4 ) === '.php' )
{
$fullPath = $file->getPathname();
$shortPath = str_replace( '\\', '/', mb_substr( $fullPath, mb_strlen( \IPS\ROOT_PATH ) ) );
if ( $shortPath != '/init.php' and isset( $correctMd5s[ $shortPath ] ) and !\IPS\Login::compareHashes( md5( preg_replace( '#\s#', '', utf8_decode( file_get_contents( $fullPath ) ) ) ), $correctMd5s[ $shortPath ] ) ) // We strip whitespace since FTP in ASCII mode will change the whitespace characters
{
$return[] = $fullPath;
}
}
}
return $return;
}
/**
* @brief [ActiveRecord] Database Table
*/
public static $databaseTable = 'core_applications';
/**
* @brief [ActiveRecord] Database Prefix
*/
public static $databasePrefix = 'app_';
/**
* @brief [ActiveRecord] ID Database Column
*/
public static $databaseColumnId = 'directory';
/**
* @brief [ActiveRecord] Database ID Fields
*/
protected static $databaseIdFields = array( 'app_id' );
/**
* @brief [ActiveRecord] Multiton Map
*/
protected static $multitonMap = array();
/**
* @brief [Node] Subnode class
*/
public static $subnodeClass = 'IPS\Application\Module';
/**
* @brief [Node] Node Title
*/
public static $nodeTitle = 'applications_and_modules';
/**
* @brief [Node] Order Database Column
*/
public static $databaseColumnOrder = 'position';
/**
* @brief [Node] ACP Restrictions
*/
protected static $restrictions = array( 'app' => 'core', 'module' => 'applications', 'prefix' => 'app_' );
/**
* Construct ActiveRecord from database row
*
* @param array $data Row from database table
* @param bool $updateMultitonStoreIfExists Replace current object in multiton store if it already exists there?
* @return static
*/
public static function constructFromData( $data, $updateMultitonStoreIfExists = TRUE )
{
/* Load class */
if( !file_exists( \IPS\ROOT_PATH . '/applications/' . $data['app_directory'] . '/Application.php' ) )
{
if( !\IPS\Dispatcher::hasInstance() OR \IPS\Dispatcher::i()->controllerLocation !== 'setup' )
{
throw new \UnexpectedValueException( "Missing: " . '/applications/' . $data['app_directory'] . '/Application.php' );
}
else
{
$className = "\\IPS\\{$data['app_directory']}\\Application";
if( !class_exists( $className ) )
{
$code = <<<EOF
namespace IPS\\{$data['app_directory']};
class Application extends \\IPS\\Application{}
EOF;
eval( $code );
}
}
}
else
{
require_once \IPS\ROOT_PATH . '/applications/' . $data['app_directory'] . '/Application.php';
}
/* Initiate an object */
$classname = 'IPS\\' . $data['app_directory'] . '\\Application';
$obj = new $classname;
$obj->_new = FALSE;
/* Import data */
foreach ( $data as $k => $v )
{
if( static::$databasePrefix )
{
$k = \substr( $k, \strlen( static::$databasePrefix ) );
}
$obj->_data[ $k ] = $v;
}
$obj->changed = array();
/* Return */
return $obj;
}
/**
* @brief Modules Store
*/
protected $modules = NULL;
/**
* Get Modules
*
* @see static::$modules
* @param string $location Location (e.g. "admin" or "front")
* @return array
*/
public function modules( $location=NULL )
{
/* Don't have an instance? */
if( $this->modules === NULL )
{
$modules = \IPS\Application\Module::modules();
$this->modules = array_key_exists( $this->directory, $modules ) ? $modules[ $this->directory ] : array();
}
/* Return */
return isset( $this->modules[ $location ] ) ? $this->modules[ $location ] : array();
}
/**
* Returns the ACP Menu JSON for this application.
*
* @return array
*/
public function acpMenu()
{
return json_decode( file_get_contents( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/acpmenu.json" ), TRUE );
}
/**
* ACP Menu Numbers
*
* @param array $queryString Query String
* @return int
*/
public function acpMenuNumber( $queryString )
{
return 0;
}
/**
* Get Extensions
*
* @param \IPS\Application|string $app The app key of the application which owns the extension
* @param string $extension Extension Type
* @param bool $construct Should an object be returned? (If false, just the classname will be returned)
* @param \IPS\Member|bool $checkAccess Check access permission for extension against supplied member (or logged in member, if TRUE)
* @return array
*/
public function extensions( $app, $extension, $construct=TRUE, $checkAccess=FALSE )
{
$app = ( is_string( $app ) ? $app : $app->directory );
$classes = array();
$directory = \IPS\ROOT_PATH . "/applications/{$this->directory}/extensions/{$app}/{$extension}";
if ( is_dir( $directory ) )
{
$dir = new \DirectoryIterator( $directory );
foreach ( $dir as $file )
{
/* Macs create copies of files with "._" prefix which breaks when we just load up all files in a dir, ignore those */
if ( !$file->isDir() and !$file->isDot() and mb_substr( $file, -4 ) === '.php' AND mb_substr( $file, 0, 2 ) != '._' )
{
$classname = 'IPS\\' . $this->directory . '\extensions\\' . $app . '\\' . $extension . '\\' . mb_substr( $file, 0, -4 );
if ( method_exists( $classname, 'generate' ) )
{
$classes = array_merge( $classes, $classname::generate() );
}
elseif ( !$construct )
{
$classes[ mb_substr( $file, 0, -4 ) ] = $classname;
}
else
{
try
{
$classes[ mb_substr( $file, 0, -4 ) ] = new $classname( $checkAccess === TRUE ? \IPS\Member::loggedIn() : ( $checkAccess === FALSE ? NULL : $checkAccess ) );
}
catch( \RuntimeException $e ){}
}
}
}
}
return $classes;
}
/**
* [Node] Get Node Title
*
* @return string
*/
protected function get__title()
{
$key = "__app_{$this->directory}";
return \IPS\Member::loggedIn()->language()->addToStack( $key );
}
/**
* [Node] Get Node Icon
*
* @return string
*/
protected function get__icon()
{
return 'cubes';
}
/**
* [Node] Does this node have children?
*
* @param string|NULL $permissionCheck The permission key to check for or NULl to not check permissions
* @param \IPS\Member|NULL $member The member to check permissions for or NULL for the currently logged in member
* @param bool $subnodes Include subnodes?
* @param array $_where Additional WHERE clause
* @return bool
*/
public function hasChildren( $permissionCheck='view', $member=NULL, $subnodes=TRUE, $_where=array() )
{
return $subnodes;
}
/**
* [Node] Does the currently logged in user have permission to delete this node?
*
* @return bool
*/
public function canDelete()
{
if( \IPS\NO_WRITES or !static::restrictionCheck( 'delete' ) )
{
return FALSE;
}
if( $this->_data['protected'] )
{
return FALSE;
}
else
{
return TRUE;
}
}
/**
* @brief Cached URL
*/
protected $_url = NULL;
/**
* Get URL
*
* @return \IPS\Http\Url
*/
public function url()
{
if( $this->_url === NULL )
{
$this->_url = \IPS\Http\Url::internal( "app={$this->directory}" );
}
return $this->_url;
}
/**
* [Node] Get buttons to display in tree
* Example code explains return value
*
* @code
array(
array(
'icon' => array(
'icon.png' // Path to icon
'core' // Application icon belongs to
),
'title' => 'foo', // Language key to use for button's title parameter
'link' => \IPS\Http\Url::internal( 'app=foo...' ) // URI to link to
'class' => 'modalLink' // CSS Class to use on link (Optional)
),
... // Additional buttons
);
* @endcode
* @param string $url Base URL
* @param bool $subnode Is this a subnode?
* @return array
*/
public function getButtons( $url, $subnode=FALSE )
{
/* Get normal buttons */
$buttons = parent::getButtons( $url );
$edit = NULL;
$uninstall = NULL;
if( \IPS\IN_DEV and isset( $buttons['edit'] ) )
{
$edit = $buttons['edit'];
}
unset( $buttons['edit'] );
unset( $buttons['copy'] );
if( isset( $buttons['delete'] ) )
{
$buttons['delete']['title'] = 'uninstall';
$buttons['delete']['data'] = array( 'delete' => '' );
$uninstall = $buttons['delete'];
unset( $buttons['delete'] );
}
/* Default */
if( $this->enabled )
{
$buttons['default'] = array(
'icon' => $this->default ? 'star' : 'star-o',
'title' => 'make_default_app',
'link' => \IPS\Http\Url::internal( "app=core&module=applications&controller=applications&appKey={$this->_id}&do=setAsDefault" ),
);
}
/* Online/offline */
if( !$this->protected )
{
$buttons['offline'] = array(
'icon' => 'lock',
'title' => 'permissions',
'link' => \IPS\Http\Url::internal( "app=core&module=applications&controller=applications&id={$this->_id}&do=permissions" ),
'data' => array( 'ipsDialog' => '', 'ipsDialog-forceReload' => 'true', 'ipsDialog-title' => \IPS\Member::loggedIn()->language()->addToStack('permissions') )
);
}
/* View Details */
$buttons['details'] = array(
'icon' => 'search',
'title' => 'app_view_details',
'link' => \IPS\Http\Url::internal( "app=core&module=applications&controller=applications&do=details&id={$this->_id}" ),
'data' => array( 'ipsDialog' => '', 'ipsDialog-title' => \IPS\Member::loggedIn()->language()->addToStack('app_view_details') )
);
/* Upgrade */
if( !$this->protected )
{
$buttons['upgrade'] = array(
'icon' => 'upload',
'title' => 'upload_new_version',
'link' => \IPS\Http\Url::internal( "app=core&module=applications&controller=applications&appKey={$this->_id}&do=upload" ),
'data' => array( 'ipsDialog' => '', 'ipsDialog-title' => \IPS\Member::loggedIn()->language()->addToStack('upload_new_version') )
);
}
/* Uninstall */
if ( $uninstall )
{
$buttons['delete'] = $uninstall;
if ( $this->default )
{
$buttons['delete']['data'] = array( 'ipsDialog' => '', 'ipsDialog-title' => \IPS\Member::loggedIn()->language()->addToStack('uninstall') );
}
}
/* Developer */
if( \IPS\IN_DEV )
{
if ( $edit )
{
$buttons['edit'] = $edit;
}
$buttons['compilejs'] = array(
'icon' => 'cog',
'title' => 'app_compile_js',
'link' => \IPS\Http\Url::internal( "app=core&module=applications&controller=applications&appKey={$this->_id}&do=compilejs" )
);
$buttons['build'] = array(
'icon' => 'cog',
'title' => 'app_build',
'link' => \IPS\Http\Url::internal( "app=core&module=applications&controller=applications&appKey={$this->_id}&do=build" ),
'data' => array( 'ipsDialog' => '', 'ipsDialog-title' => \IPS\Member::loggedIn()->language()->addToStack('app_build') )
);
$buttons['export'] = array(
'icon' => 'download',
'title' => 'download',
'link' => \IPS\Http\Url::internal( "app=core&module=applications&controller=applications&appKey={$this->_id}&do=download" ),
'data' => array( 'ipsDialog' => '', 'ipsDialog-title' => \IPS\Member::loggedIn()->language()->addToStack('download'), 'ipsDialog-remoteVerify' => 'false' )
);
$buttons['developer'] = array(
'icon' => 'cogs',
'title' => 'developer_mode',
'link' => \IPS\Http\Url::internal( "app=core&module=applications&controller=developer&appKey={$this->_id}" ),
);
}
return $buttons;
}
/**
* [Node] Get whether or not this node is enabled
*
* @note Return value NULL indicates the node cannot be enabled/disabled
* @return bool|null
*/
protected function get__enabled()
{
if ( $this->directory == 'core' )
{
return TRUE;
}
return $this->enabled and ( !in_array( $this->directory, static::$ipsApps ) or $this->long_version == \IPS\Application::load('core')->long_version );
}
/**
* [Node] Set whether or not this node is enabled
*
* @param bool|int $enabled Whether to set it enabled or disabled
* @return void
*/
protected function set__enabled( $enabled )
{
if ( \IPS\NO_WRITES )
{
throw new \RuntimeException;
}
$this->enabled = $enabled;
$this->save();
\IPS\Plugin\Hook::writeDataFile();
}
/**
* [Node] Get whether or not this node is locked to current enabled/disabled status
*
* @note Return value NULL indicates the node cannot be enabled/disabled
* @return bool|null
*/
protected function get__locked()
{
if ( $this->directory == 'core' )
{
return TRUE;
}
if ( !$this->_enabled and in_array( $this->directory, static::$ipsApps ) and $this->long_version != \IPS\Application::load('core')->long_version )
{
return TRUE;
}
return FALSE;
}
/**
* [Node] Get Node Description
*
* @return string|null
*/
protected function get__description()
{
if ( $this->_locked and $this->directory != 'core' )
{
return \IPS\Member::loggedIn()->language()->addToStack('app_force_disabled');
}
elseif ( $this->disabled_groups )
{
$groups = array();
if ( $this->disabled_groups != '*' )
{
foreach ( explode( ',', $this->disabled_groups ) as $groupId )
{
try
{
$groups[] = \IPS\Member\Group::load( $groupId )->name;
}
catch ( \OutOfRangeException $e ) { }
}
}
if ( empty( $groups ) )
{
return \IPS\Member::loggedIn()->language()->addToStack('app_offline_to_all');
}
else
{
return \IPS\Member::loggedIn()->language()->addToStack( 'app_offline_to_groups', FALSE, array( 'sprintf' => array( \IPS\Member::loggedIn()->language()->formatList( $groups ) ) ) );
}
}
return NULL;
}
/**
* Return the custom badge for each row
*
* @return NULL|array Null for no badge, or an array of badge data (0 => CSS class type, 1 => language string, 2 => optional raw HTML to show instead of language string)
*/
public function get__badge()
{
if ( $availableUpgrade = $this->availableUpgrade( TRUE ) )
{
return array(
0 => 'new',
1 => '',
2 => \IPS\Theme::i()->getTemplate( 'global', 'core' )->updatebadge( $availableUpgrade['version'], $availableUpgrade['updateurl'], $availableUpgrade['released'] )
);
}
return NULL;
}
/**
* [Node] Does the currently logged in user have permission to add a child node?
*
* @return bool
* @note Modules are added via the developer center and should not be added by a regular admin via the standard node controller
*/
public function canAdd()
{
return false;
}
/**
* [Node] Does the currently logged in user have permission to add aa root node?
*
* @return bool
* @note If IN_DEV is on, the admin can create a new application
*/
public static function canAddRoot()
{
return ( \IPS\IN_DEV ) ? true : false;
}
/**
* [Node] Does the currently logged in user have permission to edit permissions for this node?
*
* @return bool
* @note We don't allow permissions to be set for applications - they are handled by modules and by the enabled/disabled mode
*/
public function canManagePermissions()
{
return false;
}
/**
* Add or edit an application
*
* @param \IPS\Helpers\Form $form Form object we can add our fields to
* @return void
*/
public function form( &$form )
{
if ( !$this->directory )
{
$form->add( new \IPS\Helpers\Form\Text( 'app_title', NULL, FALSE, array( 'app' => 'core', 'key' => ( !$this->directory ) ? NULL : "__app_{$this->directory}" ) ) );
}
$form->add( new \IPS\Helpers\Form\Text( 'app_directory', $this->directory, TRUE, array( 'disabled' => $this->id ? TRUE : FALSE, 'regex' => '/^[a-zA-Z][a-zA-Z0-9]+$/' ) ) );
$form->add( new \IPS\Helpers\Form\Text( 'app_author', $this->author ) );
$form->add( new \IPS\Helpers\Form\Url( 'app_website', $this->website ) );
$form->add( new \IPS\Helpers\Form\Url( 'app_update_check', $this->update_check ) );
$form->add( new \IPS\Helpers\Form\YesNo( 'app_protected', $this->protected, FALSE ) );
}
/**
* [Node] Format form values from add/edit form for save
*
* @param array $values Values from the form
* @return array
*/
public function formatFormValues( $values )
{
/* New application stuff */
if ( !$this->id )
{
/* Check dir is writable */
if( !is_writable( \IPS\ROOT_PATH . '/applications/' ) )
{
\IPS\Output::i()->error( 'app_dir_not_write', '4S134/2', 403, '' );
}
/* Check key isn't in use */
$values['app_directory'] = mb_strtolower( $values['app_directory'] );
try
{
$test = \IPS\Application::load( $values['app_directory'] );
\IPS\Output::i()->error( 'app_error_key_used', '1S134/1', 403, '' );
}
catch ( \OutOfRangeException $e ) { }
/* Attempt to create the basic directory structure for the developer */
if( is_writable( \IPS\ROOT_PATH . '/applications/' ) )
{
/* If we can make the root dir, we can create the subfolders */
if( @mkdir( \IPS\ROOT_PATH . '/applications/' . $values['app_directory'] ) )
{
@chmod( \IPS\ROOT_PATH . '/applications/' . $values['app_directory'], \IPS\FOLDER_PERMISSION_NO_WRITE );
/* Create directories */
foreach ( array( 'data', 'dev', 'dev/css', 'dev/email', 'dev/html', 'dev/resources', 'dev/js', 'extensions', 'extensions/core', 'hooks', 'interface', 'modules', 'modules/admin', 'modules/front', 'setup', '/setup/upg_working', 'sources', 'tasks' ) as $f )
{
@mkdir( \IPS\ROOT_PATH . '/applications/' . $values['app_directory'] . '/' . $f );
@chmod( \IPS\ROOT_PATH . '/applications/' . $values['app_directory'] . '/' . $f, \IPS\FOLDER_PERMISSION_NO_WRITE );
\file_put_contents( \IPS\ROOT_PATH . '/applications/' . $values['app_directory'] . '/' . $f . '/index.html', '' );
}
/* Create files */
@\file_put_contents( \IPS\ROOT_PATH . '/applications/' . $values['app_directory'] . '/data/schema.json', '[]' );
@\file_put_contents( \IPS\ROOT_PATH . '/applications/' . $values['app_directory'] . '/data/settings.json', '[]' );
@\file_put_contents( \IPS\ROOT_PATH . '/applications/' . $values['app_directory'] . '/data/tasks.json', '[]' );
@\file_put_contents( \IPS\ROOT_PATH . '/applications/' . $values['app_directory'] . '/data/themesettings.json', '[]' );
@\file_put_contents( \IPS\ROOT_PATH . '/applications/' . $values['app_directory'] . '/data/acpmenu.json', '[]' );
@\file_put_contents( \IPS\ROOT_PATH . '/applications/' . $values['app_directory'] . '/data/modules.json', '[]' );
@\file_put_contents( \IPS\ROOT_PATH . '/applications/' . $values['app_directory'] . '/data/widgets.json', '[]' );
@\file_put_contents( \IPS\ROOT_PATH . '/applications/' . $values['app_directory'] . '/data/acpsearch.json', '{}' );
@\file_put_contents( \IPS\ROOT_PATH . '/applications/' . $values['app_directory'] . '/data/hooks.json', '[]' );
@\file_put_contents( \IPS\ROOT_PATH . '/applications/' . $values['app_directory'] . '/data/versions.json', json_encode( array() ) );
@\file_put_contents( \IPS\ROOT_PATH . '/applications/' . $values['app_directory'] . '/dev/lang.php', '<?' . "php\n\n\$lang = array(\n\t'__app_{$values['app_directory']}'\t=> \"{$values['app_title']}\"\n);\n" );
@\file_put_contents( \IPS\ROOT_PATH . '/applications/' . $values['app_directory'] . '/dev/jslang.php', '<?' . "php\n\n\$lang = array(\n\n);\n" );
@\file_put_contents( \IPS\ROOT_PATH . '/applications/' . $values['app_directory'] . '/Application.php', str_replace(
array(
'{app}',
'{website}',
'{author}',
'{year}',
'{subpackage}',
'{date}'
),
array(
$values['app_directory'],
$values['app_website'],
$values['app_author'],
date('Y'),
$values['app_title'],
date( 'd M Y' ),
),
file_get_contents( \IPS\ROOT_PATH . "/applications/core/data/defaults/Application.txt" )
) );
@\file_put_contents( \IPS\ROOT_PATH . '/applications/' . $values['app_directory'] . '/data/application.json', json_encode( array(
'application_title' => $values['app_title'],
'app_author' => $values['app_author'],
'app_directory' => $values['app_directory'],
'app_protected' => $values['app_protected'],
'app_website' => $values['app_website'],
'app_update_check' => $values['app_update_check'],
) ) );
}
}
/* Enable it */
$values['enabled'] = TRUE;
$values['app_added'] = time();
}
if( isset( $values['app_title'] ) )
{
unset( $values['app_title'] );
}
return $values;
}
/**
* [Node] Perform actions after saving the form
*
* @param array $values Values from the form
* @return void
*/
public function postSaveForm( $values )
{
/* Clear out member's cached "Create Menu" contents */
\IPS\Member::clearCreateMenu();
unset( \IPS\Data\Store::i()->applications );
unset( \IPS\Data\Store::i()->settings );
}
/**
* Install database changes from the schema.json file
*
* @param bool $skipInserts Skip inserts
* @throws \Exception
*/
public function installDatabaseSchema( $skipInserts=FALSE )
{
if( file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/schema.json" ) )
{
$schema = json_decode( file_get_contents( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/schema.json" ), TRUE );
foreach( $schema as $table => $definition )
{
/* Look for missing tables first */
if( !\IPS\Db::i()->checkForTable( $table ) )
{
\IPS\Db::i()->createTable( $definition );
}
else
{
/* If the table exists, look for missing columns */
if( is_array( $definition['columns'] ) AND count( $definition['columns'] ) )
{
/* Get the table definition first */
$tableDefinition = \IPS\Db::i()->getTableDefinition( $table );
foreach( $definition['columns'] as $column )
{
/* Column does not exist in the table definition? Add it then. */
if( empty($tableDefinition['columns'][ $column['name'] ]) )
{
\IPS\Db::i()->addColumn( $table, $column );
}
}
}
}
if ( isset( $definition['inserts'] ) AND !$skipInserts )
{
foreach ( $definition['inserts'] as $insertData )
{
$adminName = \IPS\Member::loggedIn()->name;
try
{
\IPS\Db::i()->insert( $definition['name'], array_map( function( $column ) use( $adminName ) {
if( !is_string( $column ) )
{
return $column;
}
$column = str_replace( '<%TIME%>', time(), $column );
$column = str_replace( '<%ADMIN_NAME%>', $adminName, $column );
$column = str_replace( '<%IP_ADDRESS%>', $_SERVER['REMOTE_ADDR'], $column );
return $column;
}, $insertData ) );
}
catch( \IPS\Db\Exception $e )
{}
}
}
}
}
if( file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/setup/install/queries.json" ) )
{
$schema = json_decode( file_get_contents( \IPS\ROOT_PATH . "/applications/{$this->directory}/setup/install/queries.json" ), TRUE );
ksort($schema);
foreach( $schema as $instruction )
{
if ( $instruction['method'] === 'addColumn' )
{
/* Check to see if it exists first */
$tableDefinition = \IPS\Db::i()->getTableDefinition( $instruction['params'][0] );
if ( ! empty( $tableDefinition['columns'][ $instruction['params'][1]['name'] ] ) )
{
/* Run an alter instead */
\IPS\Db::i()->changeColumn( $instruction['params'][0], $instruction['params'][1]['name'], $instruction['params'][1] );
continue;
}
}
try
{
if( isset( $instruction['params'][1] ) and is_array( $instruction['params'][1] ) )
{
$groups = array_filter( iterator_to_array( \IPS\Db::i()->select( 'g_id', 'core_groups' ) ), function( $groupId ) {
if( $groupId == 2 )
{
return FALSE;
}
return TRUE;
});
foreach( $instruction['params'][1] as $column => $value )
{
if( $value === "<%NO_GUESTS%>" )
{
$instruction['params'][1][ $column ] = implode( ",", $groups );
}
}
}
call_user_func_array( array( \IPS\Db::i(), $instruction['method'] ), $instruction['params'] );
}
catch( \Exception $e )
{
if( $instruction['method'] == 'insert' )
{
return;
}
throw $e;
}
}
}
}
/**
* Install database changes from an upgrade schema file
*
* @param int $version Version to execute database updates from
* @param int $lastJsonIndex JSON index to begin from
* @param int $limit Limit updates
* @param bool $return Check table size first and return queries for larger tables instead of running automatically
* @return array Returns an array: ( count: count of queries run, queriesToRun: array of queries to run)
* @note We ignore some database errors that shouldn't prevent us from continuing.
* @li 1007: Can't create database because it already exists
* @li 1008: Can't drop database because it does not exist
* @li 1050: Can't rename a table as it already exists
* @li 1051: Can't drop a table because it doesn't exist
* @li 1060: Can't add a column as it already exists
* @li 1062: Can't add an index as index already exists
* @li 1062: Can't add a row as PKEY already exists
* @li 1091: Can't drop key or column because it does not exist
*/
public function installDatabaseUpdates( $version=0, $lastJsonIndex=0, $limit=50, $return=FALSE )
{
$toReturn = array();
$tableCounts = array();
$count = 0;
/* Try to prevent timeouts to the extent possible */
$cutOff = null;
if( $maxExecution = @ini_get( 'max_execution_time' ) )
{
/* If max_execution_time is set to "no limit" we should add a hard limit to prevent browser timeouts */
if ( $maxExecution == -1 )
{
$maxExecution = 30;
}
$cutOff = time() + ( $maxExecution * .5 );
}
if( file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/setup/upg_{$version}/queries.json" ) )
{
$schema = json_decode( file_get_contents( \IPS\ROOT_PATH . "/applications/{$this->directory}/setup/upg_{$version}/queries.json" ), TRUE );
ksort($schema, SORT_NUMERIC);
foreach( $schema as $jsonIndex => $instruction['params'] )
{
if ( $lastJsonIndex AND ( $jsonIndex <= $lastJsonIndex ) )
{
continue;
}
if ( $count >= $limit )
{
return array( 'count' => $count, 'queriesToRun' => $toReturn );
}
else if( $cutOff !== null AND time() >= $cutOff )
{
return array( 'count' => $count, 'queriesToRun' => $toReturn );
}
$_SESSION['lastJsonIndex'] = $jsonIndex;
$count++;
$_table = $instruction['params']['params'][0];
if ( ! is_string( $_table ) )
{
$_table = $instruction['params']['params'][0]['name'];
}
if ( ! isset( $tableCounts[ $_table ] ) and \IPS\Db::i()->checkForTable( $_table ) )
{
$tableCounts[ $_table ] = \IPS\Db::i()->select( 'count(*)', $_table )->first();
}
/* If we are deleting stuff, then make sure the counts are recounted after */
if ( $instruction['params']['method'] == 'delete' and isset( $tableCounts[ $_table ] ) )
{
unset( $tableCounts[ $_table ] );
}
/* Check table size first and store query if requested */
if( $return === TRUE )
{
if(
/* Only run manually if we have a table row count */
isset( $tableCounts[ $_table ] ) AND
/* And only if the row count is greater than the manual threshold */
$tableCounts[ $_table ] > \IPS\UPGRADE_MANUAL_THRESHOLD AND
/* And if it's not a drop table, insert or rename table query */
!in_array( $instruction['params']['method'], array( 'dropTable', 'insert', 'renameTable' ) ) AND
/* ANNNNNDDD only if the method is not delete or there's a where clause, i.e. a truncate table statement does not run manually */
( $instruction['params']['method'] != 'delete' OR isset( $instructions['params']['params'][1] ) )
)
{
\IPS\Log::debug( "Big table " . $_table . ", storing query to run manually", 'upgrade' );
\IPS\Db::i()->returnQuery = TRUE;
$query = call_user_func_array( array( \IPS\Db::i(), $instruction['params']['method'] ), $instruction['params']['params'] );
if( $query )
{
$toReturn[] = $query;
if ( $instruction['params']['method'] == 'renameTable' )
{
$tableCounts[ $instruction['params']['params'][1] ] = $tableCounts[ $_table ];
foreach( $toReturn as $k => $v )
{
$toReturn[ $k ] = preg_replace( "/\`" . \IPS\Db::i()->prefix . $_table . "\`/", "`" . \IPS\Db::i()->prefix . $instruction['params']['params'][1] . "`", $v );
}
}
return array( 'count' => $count, 'queriesToRun' => $toReturn );
}
}
}
try
{
call_user_func_array( array( \IPS\Db::i(), $instruction['params']['method'] ), $instruction['params']['params'] );
}
catch( \IPS\Db\Exception $e )
{
/* If the issue is with a create table other than exists, we should just throw it */
if ( $instruction['params']['method'] == 'createTable' and ! in_array( $e->getCode(), array( 1007, 1050 ) ) )
{
throw $e;
}
/* Can't change a column as it doesn't exist */
if ( $e->getCode() == 1054 )
{
if ( $instruction['params']['method'] == 'changeColumn' )
{
if ( \IPS\Db::i()->checkForTable( $instruction['params']['params'][0] ) )
{
/* Does the column exist already? */
if ( \IPS\Db::i()->checkForColumn( $instruction['params']['params'][0], $instruction['params']['params'][2]['name'] ) )
{
/* Just make sure it's up to date */
\IPS\Db::i()->changeColumn( $instruction['params']['params'][0], $instruction['params']['params'][2]['name'], $instruction['params']['params'][2] );
continue;
}
else
{
/* The table exists, so lets just add the column */
\IPS\Db::i()->addColumn( $instruction['params']['params'][0], $instruction['params']['params'][2] );
continue;
}
}
}
throw $e;
}
/* Can't rename a table as it doesn't exist */
else if ( $e->getCode() == 1017 )
{
if ( $instruction['params']['method'] == 'renameTable' )
{
if ( \IPS\Db::i()->checkForTable( $instruction['params']['params'][1] ) )
{
/* The table we are renaming to *does* exist */
continue;
}
}
throw $e;
}
/* Possibly trying to change a column to not null that has NULL values */
else if ( $e->getCode() == 1138 )
{
if ( $instruction['params']['method'] == 'changeColumn' and ! $instruction['params']['params'][2]['allow_null'] )
{
$currentDefintion = \IPS\Db::i()->getTableDefinition( $instruction['params']['params'][1] );
$column = $currentDefintion[ $instruction['params']['params'][2]['name'] ];
if ( isset( $currentDefintion['columns'][ $column ] ) AND $currentDefintion['columns'][ $column ]['allow_null'] )
{
\IPS\Db::i()->update( $instruction['params']['params'][1], array( $column => '' ), array( $column . ' IS NULL' ) );
/* Just make sure it's up to date */
\IPS\Db::i()->changeColumn( $instruction['params']['params'][0], $instruction['params']['params'][2]['name'], $instruction['params']['params'][2] );
continue;
}
}
throw $e;
}
/* If the error isn't important we should ignore it */
else if( !in_array( $e->getCode(), array( 1007, 1008, 1050, 1060, 1061, 1062, 1091, 1051 ) ) )
{
throw $e;
}
}
}
}
return array( 'count' => $count, 'queriesToRun' => $toReturn );
}
/**
* Rebuild common data during an install or upgrade. This is a shortcut method which
* * Installs module data from JSON file
* * Installs task data from JSON file
* * Installs setting data from JSON file
* * Installs ACP live search keywords from JSON file
* * Installs hooks from JSON file
* * Updates latest version in the database
*
* @param bool $skipMember Skip clearing member cache clearing
* @return void
*/
public function installJsonData( $skipMember=FALSE )
{
/* Rebuild modules */
$this->installModules();
/* Rebuild tasks */
$this->installTasks();
/* Rebuild settings */
$this->installSettings();
/* Rebuild sidebar widgets */
$this->installWidgets();
/* Rebuild search keywords */
$this->installSearchKeywords();
/* Rebuild hooks */
$this->installHooks();
/* Update app version data */
$versions = $this->getAllVersions();
$longVersions = array_keys( $versions );
$humanVersions = array_values( $versions );
if( count($versions) )
{
$latestLVersion = array_pop( $longVersions );
$latestHVersion = array_pop( $humanVersions );
\IPS\Db::i()->update( 'core_applications', array( 'app_version' => $latestHVersion, 'app_long_version' => $latestLVersion ), array( 'app_directory=?', $this->directory ) );
}
unset( \IPS\Data\Store::i()->applications );
if( !$skipMember )
{
\IPS\Member::clearCreateMenu();
}
}
/**
* Install the application's modules
*
* @return void
*/
public function installModules()
{
if( file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/modules.json" ) )
{
$currentModules = array();
$moduleStore = array();
foreach ( \IPS\Db::i()->select( '*', 'core_modules', array( 'sys_module_application=?', $this->directory ) ) as $row )
{
$currentModules[ $row['sys_module_area'] ][ $row['sys_module_key'] ] = array(
'default_controller' => $row['sys_module_default_controller'],
'protected' => $row['sys_module_protected']
);
$moduleStore[ $row['sys_module_area'] ][ $row['sys_module_key'] ] = $row;
}
$insert = array();
$update = array();
$position = 0;
foreach( json_decode( file_get_contents( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/modules.json" ), TRUE ) as $area => $modules )
{
foreach ( $modules as $key => $data )
{
if ( !isset( $currentModules[ $area ][ $key ] ) )
{
$module = new \IPS\Application\Module;
}
elseif ( $currentModules[ $area ][ $key ] != $data )
{
$module = \IPS\Application\Module::constructFromData( $moduleStore[ $area ][ $key ] );
}
else
{
continue;
}
$module->application = $this->directory;
$module->key = $key;
$module->protected = intval( $data['protected'] );
$module->visible = TRUE;
$module->position = ++$position;
$module->area = $area;
$module->default_controller = $data['default_controller'];
$module->default = isset( $data['default'] ) and $data['default'];
$module->save( TRUE );
}
}
}
}
/**
* Install the application's tasks
*
* @return void
*/
public function installTasks()
{
if( file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/tasks.json" ) )
{
foreach ( json_decode( file_get_contents( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/tasks.json" ), TRUE ) as $key => $frequency )
{
\IPS\Db::i()->replace( 'core_tasks', array(
'app' => $this->directory,
'key' => $key,
'frequency' => $frequency,
'next_run' => \IPS\DateTime::create()->add( new \DateInterval( $frequency ) )->getTimestamp()
) );
}
}
}
/**
* Install the application's extension data where required
*
* @param bool $newInstall TRUE if the community is being installed for the first time (opposed to an app being added)
* @return void
*/
public function installExtensions( $newInstall=FALSE )
{
/* File storage */
$settings = json_decode( \IPS\Settings::i()->upload_settings, TRUE );
try
{
$fileSystem = \IPS\Db::i()->select( '*', 'core_file_storage', array( 'method=?', 'FileSystem' ), 'id ASC' )->first();
}
catch( \UnderflowException $ex )
{
$fileSystem = \IPS\Db::i()->select( '*', 'core_file_storage', NULL, 'id ASC' )->first();
}
foreach( $this->extensions( 'core', 'FileStorage' ) as $key => $path )
{
$settings[ 'filestorage__' . $this->directory . '_' . $key ] = $fileSystem['id'];
}
\IPS\Db::i()->update( 'core_sys_conf_settings', array( 'conf_value' => json_encode( $settings ) ), array( 'conf_key=?', 'upload_settings' ) );
\IPS\Settings::i()->upload_settings = json_encode( $settings );
unset( \IPS\Data\Store::i()->settings );
$inserts = array();
foreach( $this->extensions( 'core', 'Notifications' ) as $key => $class )
{
if ( method_exists( $class, 'getConfiguration' ) )
{
$defaults = $class->getConfiguration( NULL );
foreach( $defaults AS $k => $config )
{
$inserts[] = array(
'notification_key' => $k,
'default' => implode( ',', $config['default'] ),
'disabled' => implode( ',', $config['disabled'] ),
);
}
}
}
if( count( $inserts ) )
{
\IPS\Db::i()->insert( 'core_notification_defaults', $inserts );
}
/* Install Menu items */
if ( !$newInstall )
{
$defaultNavigation = $this->defaultFrontNavigation();
foreach ( $defaultNavigation as $type => $tabs )
{
foreach ( $tabs as $config )
{
$config['real_app'] = $this->directory;
if ( !isset( $config['app'] ) )
{
$config['app'] = $this->directory;
}
\IPS\core\FrontNavigation::insertMenuItem( NULL, $config, \IPS\Db::i()->select( 'MAX(position)', 'core_menu' )->first() );
}
}
unset( \IPS\Data\Store::i()->frontNavigation );
}
}
/**
* Install the application's settings
*
* @return void
*/
public function installSettings()
{
if( file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/settings.json" ) )
{
$currentDefaults = iterator_to_array( \IPS\Db::i()->select( '*', 'core_sys_conf_settings' )->setKeyField('conf_key')->setValueField('conf_default') );
$insert = array();
$update = array();
foreach ( json_decode( file_get_contents( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/settings.json" ), TRUE ) as $setting )
{
if ( ! array_key_exists( $setting['key'], $currentDefaults ) )
{
$insert[] = array( 'conf_key' => $setting['key'], 'conf_value' => $setting['default'], 'conf_default' => $setting['default'], 'conf_app' => $this->directory );
}
elseif ( $currentDefaults[ $setting['key'] ] != $setting['default'] )
{
$update[] = array( array( 'conf_default' => $setting['default'] ), array( 'conf_key=?', $setting['key'] ) );
}
}
if ( !empty( $insert ) )
{
\IPS\Db::i()->insert( 'core_sys_conf_settings', $insert, TRUE );
}
foreach ( $update as $data )
{
\IPS\Db::i()->update( 'core_sys_conf_settings', $data[0], $data[1] );
}
unset( \IPS\Data\Store::i()->settings );
}
}
/**
* Install the application's language strings
*
* @param int|null $offset Offset to begin import from
* @param int|null $limit Number of rows to import
* @return int Rows inserted
*/
public function installLanguages( $offset=null, $limit=null )
{
$languages = array_keys( \IPS\Lang::languages() );
$inserted = 0;
$current = array();
foreach( $languages as $languageId )
{
foreach( iterator_to_array( \IPS\Db::i()->select( 'word_key, word_default, word_js', 'core_sys_lang_words', array( 'word_app=? AND lang_id=?', $this->directory, $languageId ) ) ) as $word )
{
$current[ $languageId ][ $word['word_key'] . '-.-' . $word['word_js'] ] = $word['word_default'];
}
}
if ( !$offset and file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/installLang.json" ) )
{
$inserts = array();
foreach ( json_decode( file_get_contents( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/installLang.json" ), TRUE ) as $key => $default )
{
foreach( $languages as $languageId )
{
if ( !isset( $current[ $languageId ][ $key . '-.-0' ] ) )
{
$inserts[] = array(
'word_app' => $this->directory,
'word_key' => $key,
'lang_id' => $languageId,
'word_default' => $default,
'word_custom' => $default,
'word_default_version' => $this->long_version,
'word_custom_version' => $this->long_version,
'word_js' => 0,
'word_export' => 0,
);
}
}
}
if ( count( $inserts ) )
{
\IPS\Db::i()->insert( 'core_sys_lang_words', $inserts, TRUE );
}
}
if( file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/lang.xml" ) )
{
/* Open XML file */
$xml = new \IPS\Xml\XMLReader;
$xml->open( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/lang.xml" );
$xml->read();
/* Get the version */
$xml->read();
$xml->read();
$version = $xml->getAttribute('version');
/* Get all installed languages */
$inserts = array();
$batchSize = 25;
$batchesDone = 0;
$i = 0;
/* Try to prevent timeouts to the extent possible */
$cutOff = null;
if( $maxExecution = @ini_get( 'max_execution_time' ) )
{
/* If max_execution_time is set to "no limit" we should add a hard limit to prevent browser timeouts */
if ( $maxExecution == -1 )
{
$maxExecution = 30;
}
$cutOff = time() + ( $maxExecution * .5 );
}
/* Start looping through each word */
while ( $xml->read() )
{
if( $xml->name != 'word' OR $xml->nodeType != \XMLReader::ELEMENT )
{
continue;
}
if( $cutOff !== null AND time() >= $cutOff )
{
return $inserted;
}
$i++;
if ( $offset !== null )
{
if ( $i - 1 < $offset )
{
$xml->next();
continue;
}
}
$inserted++;
$key = $xml->getAttribute('key');
$value = $xml->readString();
foreach( $languages as $languageId )
{
if ( !isset( $current[ $languageId ][ $key . '-.-' . (int) $xml->getAttribute('js') ] ) or $current[ $languageId ][ $key . '-.-' . (int) $xml->getAttribute('js') ] != $value )
{
$inserts[] = array(
'word_app' => $this->directory,
'word_key' => $key,
'lang_id' => $languageId,
'word_default' => $value,
'word_default_version' => $version,
'word_js' => (int) $xml->getAttribute('js'),
'word_export' => 1,
);
}
}
$done = ( $limit !== null AND $i === ( $limit + $offset ) );
if ( $done OR $i % $batchSize === 0 )
{
if ( count( $inserts ) )
{
\IPS\Db::i()->insert( 'core_sys_lang_words', $inserts, TRUE );
$inserts = array();
}
$batchesDone++;
}
if ( $done )
{
break;
}
$xml->next();
}
if ( count( $inserts ) )
{
\IPS\Db::i()->insert( 'core_sys_lang_words', $inserts, TRUE );
}
}
return $inserted;
}
/**
* Install the application's email templates
*
* @return void
*/
public function installEmailTemplates()
{
if( file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/emails.xml" ) )
{
/* First, delete any existing non-customized email templates for this app */
\IPS\Db::i()->delete( 'core_email_templates', array( 'template_app=? AND template_parent=0', $this->directory ) );
/* Open XML file */
$xml = new \IPS\Xml\XMLReader;
$xml->open( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/emails.xml" );
$xml->read();
/* Start looping through each word */
while ( $xml->read() and $xml->name == 'template' )
{
if( $xml->nodeType != \XMLReader::ELEMENT )
{
continue;
}
$insert = array(
'template_parent' => 0,
'template_app' => $this->directory,
'template_edited' => 0,
);
while ( $xml->read() and $xml->name != 'template' )
{
if( $xml->nodeType != \XMLReader::ELEMENT )
{
continue;
}
switch( $xml->name )
{
case 'template_name':
$insert['template_name'] = $xml->readString();
$insert['template_key'] = md5( $this->directory . ';' . $insert['template_name'] );
break;
case 'template_data':
$insert['template_data'] = $xml->readString();
break;
case 'template_content_html':
$insert['template_content_html'] = $xml->readString();
break;
case 'template_content_plaintext':
$insert['template_content_plaintext'] = $xml->readString();
break;
}
}
\IPS\Db::i()->replace( 'core_email_templates', $insert );
}
/* Now re-associate customized email templates */
foreach( \IPS\Db::i()->select( '*', 'core_email_templates', array( 'template_app=? AND template_parent>0', $this->directory ) ) as $template )
{
/* Find the real parent now */
try
{
$parent = \IPS\Db::i()->select( '*', 'core_email_templates', array( 'template_app=? and template_name=? and template_parent=0', $template['template_app'], $template['template_name'] ) )->first();
/* And now update this template */
\IPS\Db::i()->update( 'core_email_templates', array( 'template_parent' => $parent['template_id'] ), array( 'template_id=?', $template['template_id'] ) );
\IPS\Db::i()->update( 'core_email_templates', array( 'template_edited' => 1 ), array( 'template_id=?', $parent['template_id'] ) );
}
catch( \UnderflowException $ex ) { }
}
\IPS\Data\Cache::i()->clearAll();
\IPS\Data\Store::i()->clearAll();
}
}
/**
* Install the application's skin templates, CSS files and resources
*
* @param bool $update If set to true, do not overwrite current theme setting values
* @return void
*/
public function installSkins( $update=FALSE )
{
/* Clear old caches */
\IPS\Data\Cache::i()->clearAll();
\IPS\Data\Store::i()->clearAll();
/* Install the stuff */
$this->installThemeSettings( $update );
$this->clearTemplates();
$this->installTemplates( $update );
}
/**
* Install the application's theme settings
*
* @param bool $update If set to true, do not overwrite current theme setting values
* @return void
*/
public function installThemeSettings( $update=FALSE )
{
if ( file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/themesettings.json" ) )
{
unset( \IPS\Data\Store::i()->themes );
$currentSettings = iterator_to_array( \IPS\Db::i()->select( '*', 'core_theme_settings_fields', array( 'sc_set_id=? AND sc_app=?', \IPS\Theme::defaultTheme(), $this->directory ) )->setKeyField('sc_key') );
$json = json_decode( file_get_contents( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/themesettings.json" ), TRUE );
/* Add */
foreach( $json as $key => $data)
{
$insertedSetting = FALSE;
if ( ! isset( $currentSettings[ $data['sc_key'] ] ) )
{
$insertedSetting = TRUE;
$currentId = \IPS\Db::i()->insert( 'core_theme_settings_fields', array(
'sc_set_id' => \IPS\Theme::defaultTheme(),
'sc_key' => $data['sc_key'],
'sc_tab_key' => $data['sc_tab_key'],
'sc_type' => $data['sc_type'],
'sc_multiple' => $data['sc_multiple'],
'sc_default' => $data['sc_default'],
'sc_content' => $data['sc_content'],
'sc_show_in_vse' => ( isset( $data['sc_show_in_vse'] ) ) ? $data['sc_show_in_vse'] : 0,
'sc_updated' => time(),
'sc_app' => $this->directory,
'sc_title' => $data['sc_title'],
'sc_order' => $data['sc_order'],
'sc_condition' => $data['sc_condition'],
) );
$currentSettings[ $data['sc_key'] ] = $data;
}
else
{
/* Update */
\IPS\Db::i()->update( 'core_theme_settings_fields', array(
'sc_tab_key' => $data['sc_tab_key'],
'sc_type' => $data['sc_type'],
'sc_multiple' => $data['sc_multiple'],
'sc_default' => $data['sc_default'],
'sc_show_in_vse' => ( isset( $data['sc_show_in_vse'] ) ) ? $data['sc_show_in_vse'] : 0,
'sc_content' => $data['sc_content'],
'sc_title' => $data['sc_title'],
'sc_order' => $data['sc_order'],
'sc_condition' => $data['sc_condition'],
), array( 'sc_set_id=? AND sc_key=? AND sc_app=?', \IPS\Theme::defaultTheme(), $data['sc_key'], $this->directory ) );
$currentId = $currentSettings[ $data['sc_key'] ]['sc_id'];
}
/* Are we updating the value? */
if( $update === FALSE OR $insertedSetting === TRUE )
{
\IPS\Db::i()->delete('core_theme_settings_values', array('sv_id=?', $currentId ) );
\IPS\Db::i()->insert('core_theme_settings_values', array( 'sv_id' => $currentId, 'sv_value' => (string)$data['sc_default'] ) );
}
}
if ( $update )
{
$defaultCurrentSettings = $currentSettings;
foreach( \IPS\Theme::themes() as $theme )
{
/* If we are using the stock default theme, then use the setting values from the JSON as the base */
if ( $theme->id == \IPS\Theme::defaultTheme() and $theme->key === 'default' )
{
$currentSettings = $defaultCurrentSettings;
}
else
{
$currentSettings = iterator_to_array( \IPS\Db::i()->select( '*', 'core_theme_settings_fields', array( 'sc_set_id=?', $theme->id ) )->setKeyField('sc_key') );
}
$added = FALSE;
$save = json_decode( $theme->template_settings, TRUE );
/* Add */
foreach( $json as $key => $data )
{
if ( ! isset( $currentSettings[ $data['sc_key'] ] ) )
{
$added = TRUE;
$save[ $data['sc_key'] ] = $data['sc_default'];
\IPS\Db::i()->insert( 'core_theme_settings_fields', array(
'sc_set_id' => $theme->id,
'sc_key' => $data['sc_key'],
'sc_tab_key' => $data['sc_tab_key'],
'sc_type' => $data['sc_type'],
'sc_multiple' => $data['sc_multiple'],
'sc_default' => $data['sc_default'],
'sc_content' => $data['sc_content'],
'sc_show_in_vse' => ( isset( $data['sc_show_in_vse'] ) ) ? $data['sc_show_in_vse'] : 0,
'sc_updated' => time(),
'sc_app' => $this->directory,
'sc_title' => $data['sc_title'],
'sc_order' => $data['sc_order'],
'sc_condition' => $data['sc_condition'],
) );
}
else
{
/* Update */
\IPS\Db::i()->update( 'core_theme_settings_fields', array(
'sc_type' => $data['sc_type'],
'sc_multiple' => $data['sc_multiple'],
'sc_default' => $data['sc_default'],
'sc_show_in_vse' => ( isset( $data['sc_show_in_vse'] ) ) ? $data['sc_show_in_vse'] : 0,
'sc_content' => $data['sc_content'],
'sc_title' => $data['sc_title'],
'sc_condition' => $data['sc_condition'],
), array( 'sc_set_id=? AND sc_key=?', $theme->id, $data['sc_key'] ) );
$currentId = $currentSettings[ $data['sc_key'] ]['sc_id'];
try
{
$currentValue = \IPS\Db::i()->select( 'sv_value', 'core_theme_settings_values', array( array( 'sv_id=?', $currentId ) ) )->first();
}
catch( \UnderFlowException $ex )
{
$currentValue = $currentSettings[ $data['sc_key'] ]['sc_default'];
}
/* Are we using the existing default? If so, update it */
if ( ( $data['sc_default'] != $currentSettings[ $data['sc_key'] ]['sc_default'] ) and ( $currentValue == $currentSettings[ $data['sc_key'] ]['sc_default'] ) )
{
$added = TRUE;
$save[ $data['sc_key'] ] = $data['sc_default'];
\IPS\Db::i()->delete('core_theme_settings_values', array('sv_id=?', $currentId ) );
\IPS\Db::i()->insert('core_theme_settings_values', array( 'sv_id' => $currentId, 'sv_value' => (string)$data['sc_default'] ) );
}
}
}
if ( $added )
{
$theme->template_settings = json_encode( $save );
$theme->save();
}
}
}
}
}
/**
* Clear out existing templates before installing new ones
*
* @return void
*/
public function clearTemplates()
{
if( file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/theme.xml" ) )
{
unset( \IPS\Data\Store::i()->themes );
\IPS\Theme::removeTemplates( $this->directory );
\IPS\Theme::removeCss( $this->directory );
\IPS\Theme::removeResources( $this->directory );
}
}
/**
* Install the application's templates
* Theme resources should be raw binary data everywhere (filesystem and DB) except in the theme XML download where they are base64 encoded.
*
* @param bool $update If set to true, do not overwrite current theme setting values
* @param int|null $offset Offset to begin import from
* @param int|null $limit Number of rows to import
* @return int Rows inserted
*/
public function installTemplates( $update=FALSE, $offset=null, $limit=null )
{
$i = 0;
$inserted = 0;
if ( \IPS\Dispatcher::hasInstance() AND class_exists( '\IPS\Dispatcher', FALSE ) and \IPS\Dispatcher::i()->controllerLocation === 'setup' )
{
$class = '\IPS\Theme';
}
else
{
$class = ( \IPS\Theme::designersModeEnabled() ) ? '\IPS\Theme\Advanced\Theme' : '\IPS\Theme';
}
if( file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/theme.xml" ) )
{
unset( \IPS\Data\Store::i()->themes );
/* Try to prevent timeouts to the extent possible */
$cutOff = null;
if( $maxExecution = @ini_get( 'max_execution_time' ) )
{
/* If max_execution_time is set to "no limit" we should add a hard limit to prevent browser timeouts */
if ( $maxExecution == -1 )
{
$maxExecution = 30;
}
$cutOff = time() + ( $maxExecution * .5 );
}
/* Open XML file */
$xml = new \IPS\Xml\XMLReader;
$xml->open( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/theme.xml" );
$xml->read();
while( $xml->read() )
{
if( $xml->nodeType != \XMLReader::ELEMENT )
{
continue;
}
if( $cutOff !== null AND time() >= $cutOff )
{
break;
}
$i++;
if ( $offset !== null )
{
if ( $i - 1 < $offset )
{
$xml->next();
continue;
}
}
$inserted++;
if( $xml->name == 'template' )
{
$template = array(
'app' => $this->directory,
'group' => $xml->getAttribute('template_group'),
'name' => $xml->getAttribute('template_name'),
'variables' => $xml->getAttribute('template_data'),
'content' => $xml->readString(),
'location' => $xml->getAttribute('template_location'),
'_default_template' => true
);
try
{
$class::addTemplate( $template );
}
catch( \OverflowException $e )
{
if ( ! $update )
{
throw $e;
}
}
}
else if( $xml->name == 'css' )
{
$css = array(
'app' => $this->directory,
'location' => $xml->getAttribute('css_location'),
'path' => $xml->getAttribute('css_path'),
'name' => $xml->getAttribute('css_name'),
'content' => $xml->readString(),
'_default_template' => true
);
try
{
$class::addCss( $css );
}
catch( \OverflowException $e )
{
if( ! $update )
{
throw $e;
}
}
}
else if( $xml->name == 'resource' )
{
$resource = array(
'app' => $this->directory,
'location' => $xml->getAttribute('location'),
'path' => $xml->getAttribute('path'),
'name' => $xml->getAttribute('name'),
'content' => base64_decode( $xml->readString() ),
);
$class::addResource( $resource, TRUE );
}
if( $limit !== null AND $i === ( $limit + $offset ) )
{
break;
}
}
}
return $inserted;
}
/**
* Install the application's javascript
*
* @param int|null $offset Offset to begin import from
* @param int|null $limit Number of rows to import
* @return int Rows inserted
*/
public function installJavascript( $offset=null, $limit=null )
{
if( file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/javascript.xml" ) )
{
return \IPS\Output\Javascript::importXml( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/javascript.xml", $offset, $limit );
}
}
/**
* Install the application's ACP search keywords
*
* @return void
*/
public function installSearchKeywords()
{
if( file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/acpsearch.json" ) )
{
\IPS\Db::i()->delete( 'core_acp_search_index', array( 'app=?', $this->directory ) );
$inserts = array();
$maxInserts = 50;
foreach( json_decode( file_get_contents( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/acpsearch.json" ), TRUE ) as $url => $data )
{
foreach ( $data['keywords'] as $word )
{
$inserts[] = array(
'url' => $url,
'keyword' => $word,
'app' => $this->directory,
'lang_key' => $data['lang_key'],
'restriction' => $data['restriction'] ?: NULL
);
if( count( $inserts ) >= $maxInserts )
{
\IPS\Db::i()->insert( 'core_acp_search_index', $inserts );
$inserts = array();
}
}
}
if( count( $inserts ) )
{
\IPS\Db::i()->insert( 'core_acp_search_index', $inserts );
}
}
}
/**
* Install hooks
*
* @return void
*/
public function installHooks()
{
if( file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/hooks.json" ) )
{
\IPS\Db::i()->delete( 'core_hooks', array( 'app=?', $this->directory ) );
$inserts = array();
$templatesToRecompile = array();
foreach( json_decode( file_get_contents( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/hooks.json" ), TRUE ) as $filename => $data )
{
$inserts[] = array(
'app' => $this->directory,
'type' => $data['type'],
'class' => $data['class'],
'filename' => $filename
);
if ( $data['type'] === 'S' )
{
$templatesToRecompile[ $data['class'] ] = $data['class'];
}
}
if( count( $inserts ) )
{
\IPS\Db::i()->insert( 'core_hooks', $inserts );
}
\IPS\Plugin\Hook::writeDataFile();
foreach ( $templatesToRecompile as $k )
{
$exploded = explode( '_', $k );
\IPS\Theme::deleteCompiledTemplate( $exploded[1], $exploded[2], $exploded[3] );
}
}
}
/**
* Install the application's widgets
*
* @return void
*/
public function installWidgets()
{
if( file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/widgets.json" ) )
{
$currentWidgets = iterator_to_array( \IPS\Db::i()->select( '`key`', 'core_widgets', array( 'app=?', $this->directory ) ) );
$inserts = array();
foreach ( json_decode( file_get_contents( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/widgets.json" ), TRUE ) as $key => $json )
{
if ( ! in_array( $key, $currentWidgets ) )
{
$inserts[] = array(
'app' => $this->directory,
'key' => $key,
'class' => $json['class'],
'restrict' => json_encode( $json['restrict'] ),
'default_area' => ( isset( $json['default_area'] ) ? $json['default_area'] : NULL ),
'allow_reuse' => ( isset( $json['allow_reuse'] ) ? $json['allow_reuse'] : 0 ),
'menu_style' => ( isset( $json['menu_style'] ) ? $json['menu_style'] : 'menu' ),
'embeddable' => ( isset( $json['embeddable'] ) ? $json['embeddable'] : 0 ),
);
}
}
if( count( $inserts ) )
{
\IPS\Db::i()->insert( 'core_widgets', $inserts, TRUE );
unset( \IPS\Data\Store::i()->widgets );
}
}
}
/**
* Install 'other' items. Left blank here so that application classes can override for app
* specific installation needs. Always run as the last step.
*
* @return void
*/
public function installOther()
{
}
/**
* Default front navigation
*
* @code
// Each item...
array(
'key' => 'Example', // The extension key
'app' => 'core', // [Optional] The extension application. If ommitted, uses this application
'config' => array(...), // [Optional] The configuration for the menu item
'title' => 'SomeLangKey', // [Optional] If provided, the value of this language key will be copied to menu_item_X
'children' => array(...), // [Optional] Array of child menu items for this item. Each has the same format.
)
return array(
'rootTabs' => array(), // These go in the top row
'browseTabs' => array(), // These go under the Browse tab on a new install or when restoring the default configuraiton; or in the top row if installing the app later (when the Browse tab may not exist)
'browseTabsEnd' => array(), // These go under the Browse tab after all other items on a new install or when restoring the default configuraiton; or in the top row if installing the app later (when the Browse tab may not exist)
'activityTabs' => array(), // These go under the Activity tab on a new install or when restoring the default configuraiton; or in the top row if installing the app later (when the Activity tab may not exist)
)
* @endcode
* @return array
*/
public function defaultFrontNavigation()
{
return array(
'rootTabs' => array(),
'browseTabs' => array(),
'browseTabsEnd' => array(),
'activityTabs' => array()
);
}
/**
* Database check
*
* @return array Queries needed to correct database in the following format ( table => x, query = x );
*/
public function databaseCheck()
{
$db = \IPS\Db::i();
$changesToMake = array();
/* Loop the tables in the schema */
foreach( json_decode( file_get_contents( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/schema.json" ), TRUE ) as $tableName => $tableDefinition )
{
$tableChanges = array();
$needIgnore = false;
$innoDbFullTextIndexes = array();
/* Get our local definition of this table */
try
{
$localDefinition = \IPS\Db::i()->getTableDefinition( $tableName );
$localDefinition = \IPS\Db::i()->normalizeDefinition( $localDefinition );
$compareDefinition = \IPS\Db::i()->normalizeDefinition( $tableDefinition );
$tableDefinition = \IPS\Db::i()->updateDefinitionIndexLengths( $tableDefinition );
if ( $compareDefinition != $localDefinition )
{
/* Normalise it a little to prevent unnecessary conflicts */
foreach ( $tableDefinition['columns'] as $k => $c )
{
foreach ( array( 'length', 'decimals' ) as $i )
{
if ( isset( $c[ $i ] ) )
{
$tableDefinition['columns'][ $k ][ $i ] = intval( $c[ $i ] );
}
else
{
$tableDefinition['columns'][ $k ][ $i ] = NULL;
}
}
if ( !isset( $c['values'] ) )
{
$tableDefinition['columns'][ $k ]['values'] = array();
}
if ( $c['type'] === 'BIT' )
{
$tableDefinition['columns'][ $k ]['default'] = ( is_null($c['default']) ) ? NULL : "b'{$c['default']}'";
}
ksort( $tableDefinition['columns'][ $k ] );
}
$dropped = array();
/* Loop the columns */
foreach ( $tableDefinition['columns'] as $columnName => $columnData )
{
/* If it doesn't exist in the local database, create it */
if ( !isset( $localDefinition['columns'][ $columnName ] ) )
{
$tableChanges[] = "ADD COLUMN {$db->compileColumnDefinition( $columnData )}";
}
/* Or if it's wrong, change it */
elseif ( $columnData != $localDefinition['columns'][ $columnName ] )
{
/* First check indexes to see if any need to be adjusted */
foreach( $localDefinition['indexes'] as $indexName => $indexData )
{
/* We skip the primary key as it can cause errors related to auto-increment */
if( $indexName == 'PRIMARY' )
{
if ( isset( $tableDefinition['columns'][ $indexData['columns'][0] ] ) and isset( $tableDefinition['columns'][ $indexData['columns'][0] ]['auto_increment'] ) and $tableDefinition['columns'][ $indexData['columns'][0] ]['auto_increment'] === TRUE )
{
continue;
}
}
foreach( $indexData['columns'] as $indexColumn )
{
/* If the column we are about to adjust is included in this index, see if it needs adjusting */
if( $indexColumn == $columnName AND !in_array( $indexName, $dropped ) )
{
$thisIndex = $db->updateDefinitionIndexLengths( $compareDefinition );
if( !isset( $thisIndex['indexes'][ $indexName ] ) )
{
$tableChanges[] = "DROP INDEX `{$db->escape_string( $indexName )}`";
$dropped[] = $indexName;
}
elseif( $thisIndex['indexes'][ $indexName ] !== $localDefinition['indexes'][ $indexName ] )
{
$tableChanges[] = "DROP INDEX `{$db->escape_string( $indexName )}`";
$tableChanges[] = $db->buildIndex( $tableName, $thisIndex['indexes'][ $indexName ] );
$dropped[] = $indexName;
if( $tableDefinition['indexes'][ $indexName ]['type'] == 'unique' OR $tableDefinition['indexes'][ $indexName ]['type'] == 'primary' )
{
$needIgnore = TRUE;
}
}
}
}
}
/* If we are about to adjust the column to not allow NULL values then adjust those values first... */
if( isset( $columnData['allow_null'] ) and $columnData['allow_null'] === FALSE )
{
$defaultValue = "''";
/* Default value */
if( isset( $columnData['default'] ) and !in_array( \strtoupper( $columnData['type'] ), array( 'TINYTEXT', 'TEXT', 'MEDIUMTEXT', 'LONGTEXT', 'BLOB', 'MEDIUMBLOB', 'BIGBLOB', 'LONGBLOB' ) ) )
{
if( $columnData['type'] == 'BIT' )
{
$defaultValue = "{$columnData['default']}";
}
else
{
$defaultValue = in_array( $columnData['type'], array( 'TINYINT', 'SMALLINT', 'MEDIUMINT', 'INT', 'INTEGER', 'BIGINT', 'REAL', 'DOUBLE', 'FLOAT', 'DECIMAL', 'NUMERIC' ) ) ? floatval( $columnData['default'] ) : ( ! in_array( $columnData['default'], array( 'CURRENT_TIMESTAMP', 'BIT' ) ) ? '\'' . $db->escape_string( $columnData['default'] ) . '\'' : $columnData['default'] );
}
}
$changesToMake[] = array( 'table' => $tableName, 'query' => "UPDATE `{$db->prefix}{$db->escape_string( $tableName )}` SET `{$db->escape_string( $columnName )}`={$defaultValue} WHERE `{$db->escape_string( $columnName )}` IS NULL;" );
}
$tableChanges[] = "CHANGE COLUMN `{$db->escape_string( $columnName )}` {$db->compileColumnDefinition( $columnData )}";
}
}
/* Loop the index */
foreach ( $compareDefinition['indexes'] as $indexName => $indexData )
{
if( in_array( $indexName, $dropped ) )
{
continue;
}
if ( !isset( $localDefinition['indexes'][ $indexName ] ) )
{
/* InnoDB FullText indexes must be added one at a time */
if( $tableDefinition['engine'] === 'InnoDB' AND $tableDefinition['indexes'][ $indexName ]['type'] === 'fulltext' )
{
$innoDbFullTextIndexes[] = $db->buildIndex( $tableName, $tableDefinition['indexes'][ $indexName ] );
}
else
{
$tableChanges[] = $db->buildIndex( $tableName, $tableDefinition['indexes'][ $indexName ] );
}
if( $tableDefinition['indexes'][ $indexName ]['type'] == 'unique' OR $tableDefinition['indexes'][ $indexName ]['type'] == 'primary' )
{
$needIgnore = TRUE;
}
}
elseif ( $indexData != $localDefinition['indexes'][ $indexName ] )
{
$tableChanges[] = ( ( $indexName == 'PRIMARY KEY' ) ? "DROP " . $indexName . ", " : "DROP INDEX `" . $db->escape_string( $indexName ) . "`, " ) . $db->buildIndex( $tableName, $tableDefinition['indexes'][ $indexName ] );
if( $tableDefinition['indexes'][ $indexName ]['type'] == 'unique' OR $tableDefinition['indexes'][ $indexName ]['type'] == 'primary' )
{
$needIgnore = TRUE;
}
}
}
}
if( count( $tableChanges ) )
{
if( $needIgnore )
{
$changesToMake[] = array( 'table' => $tableName, 'query' => "CREATE TABLE `{$db->prefix}{$db->escape_string( $tableName )}_new` LIKE `{$db->prefix}{$db->escape_string( $tableName )}`;" );
$changesToMake[] = array( 'table' => $tableName, 'query' => "ALTER TABLE `{$db->prefix}{$db->escape_string( $tableName )}_new` " . implode( ", ", $tableChanges ) . ";" );
$changesToMake[] = array( 'table' => $tableName, 'query' => "INSERT IGNORE INTO `{$db->prefix}{$db->escape_string( $tableName )}_new` SELECT * FROM `{$db->prefix}{$db->escape_string( $tableName )}`;" );
$changesToMake[] = array( 'table' => $tableName, 'query' => "DROP TABLE `{$db->prefix}{$db->escape_string( $tableName )}`;" );
$changesToMake[] = array( 'table' => $tableName, 'query' => "RENAME TABLE `{$db->prefix}{$db->escape_string( $tableName )}_new` TO `{$db->prefix}{$db->escape_string( $tableName )}`;" );
}
else
{
$changesToMake[] = array( 'table' => $tableName, 'query' => "ALTER TABLE `{$db->prefix}{$db->escape_string( $tableName )}` " . implode( ", ", $tableChanges ) . ";" );
}
}
/* InnoDB FullText indexes must be added one at a time */
if( count( $innoDbFullTextIndexes ) )
{
foreach( $innoDbFullTextIndexes as $newIndex )
{
$changesToMake[] = array( 'table' => $tableName, 'query' => "ALTER TABLE `{$db->prefix}{$db->escape_string( $tableName )}` " . $newIndex . ";" );
}
}
}
/* If the table doesn't exist, create it */
catch ( \OutOfRangeException $e )
{
$changesToMake[] = array( 'table' => $tableName, 'query' => $db->_createTableQuery( $tableDefinition ) );
}
}
/* And loop any install routine for columns added to other tables */
if ( file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/setup/install/queries.json" ) )
{
foreach( json_decode( file_get_contents( \IPS\ROOT_PATH . "/applications/{$this->directory}/setup/install/queries.json" ), TRUE ) as $query )
{
switch ( $query['method'] )
{
/* Add column */
case 'addColumn':
$localDefinition = \IPS\Db::i()->getTableDefinition( $query['params'][0] );
if ( !isset( $localDefinition['columns'][ $query['params'][1]['name'] ] ) )
{
$changesToMake[] = array( 'table' => $query['params'][0], 'query' => "ALTER TABLE `{$db->prefix}{$query['params'][0]}` ADD COLUMN {$db->compileColumnDefinition( $query['params'][1] )}" );
}
else
{
$correctDefinition = $db->compileColumnDefinition( $query['params'][1] );
if ( $correctDefinition != $db->compileColumnDefinition( $localDefinition['columns'][ $query['params'][1]['name'] ] ) )
{
$changesToMake[] = array( 'table' => $query['params'][0], 'query' => "ALTER TABLE `{$db->prefix}{$query['params'][0]}` CHANGE COLUMN `{$query['params'][1]['name']}` {$correctDefinition}" );
}
}
break;
}
}
}
/* Return */
return $changesToMake;
}
/**
* Create a new version number and move current working version
* code into it
*
* @param int $long The "long" version number (e.g. 100000)
* @param string $human The "human" version number (e.g. "1.0.0")
* @return void
*/
public function assignNewVersion( $long, $human )
{
/* Add to versions.json */
$json = json_decode( \file_get_contents( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/versions.json" ), TRUE );
$json[ $long ] = $human;
static::writeJson( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/versions.json", $json );
/* Do stuff */
$setupDir = \IPS\ROOT_PATH . "/applications/{$this->directory}/setup";
$workingDir = $setupDir . "/upg_working";
if ( file_exists( $workingDir ) )
{
/* We need to make sure the array is 1-indexed otherwise the upgrader gets confused */
$queriesJsonFile = $workingDir . "/queries.json";
if ( file_exists( $queriesJsonFile ) )
{
$write = array();
$i = 0;
foreach ( json_decode( \file_get_contents( $queriesJsonFile ), TRUE ) as $query )
{
$write[ ++$i ] = $query;
}
static::writeJson( $queriesJsonFile, $write );
}
/* Add the actual version number in upgrade.php */
$upgradeFile = $workingDir . "/upgrade.php";
if ( file_exists( $upgradeFile ) )
{
$contents = file_get_contents( $upgradeFile );
$contents = str_replace(
array(
'{version_human}',
'upg_working'
),
array(
$human,
"upg_{$long}"
),
$contents
);
\file_put_contents( $upgradeFile, $contents );
}
/* Rename the directory */
rename( $workingDir, $setupDir . "/upg_{$long}" );
}
/* Update core_dev */
\IPS\Db::i()->update( 'core_dev', array(
'working_version' => $long,
), array( 'app_key=? AND working_version=?', $this->directory, 'working' ) );
}
/**
* Build application for release
*
* @return void
* @throws \RuntimeException
*/
public function build()
{
/* Write the application data to the application.json file */
$applicationData = array(
'application_title' => \IPS\Member::loggedIn()->language()->get('__app_' . $this->directory ),
'app_author' => $this->author,
'app_directory' => $this->directory,
'app_protected' => $this->protected,
'app_website' => $this->website,
'app_update_check' => $this->update_check,
);
\IPS\Application::writeJson( \IPS\ROOT_PATH . '/applications/' . $this->directory . '/data/application.json', $applicationData );
/* Update app version data */
$versions = $this->getAllVersions();
$longVersions = array_keys( $versions );
$humanVersions = array_values( $versions );
if( count($versions) )
{
$latestLVersion = array_pop( $longVersions );
$latestHVersion = array_pop( $humanVersions );
\IPS\Db::i()->update( 'core_applications', array( 'app_version' => $latestHVersion, 'app_long_version' => $latestLVersion ), array( 'app_directory=?', $this->directory ) );
$this->long_version = $latestLVersion;
$this->version = $latestHVersion;
}
/* Take care of languages for this app */
$this->buildLanguages();
$this->installLanguages();
/* Take care of skins for this app */
$this->buildThemeTemplates();
$this->installSkins( TRUE );
/* Take care of emails for this app */
$this->buildEmailTemplates();
$this->installEmailTemplates();
/* Take care of javascript for this app */
$this->buildJavascript();
$this->installJavascript();
/* Take care of hooks for this app */
$this->buildHooks();
foreach( $this->extensions( 'core', 'Build' ) as $builder )
{
$builder->build();
}
}
/**
* Build skin templates for an app
*
* @return void
* @throws \RuntimeException
*/
public function buildThemeTemplates()
{
/* Delete compiled items */
\IPS\Theme::deleteCompiledTemplate( $this->directory );
\IPS\Theme::deleteCompiledCss( $this->directory );
\IPS\Theme::deleteCompiledResources( $this->directory );
\IPS\Theme::i()->importDevHtml( $this->directory, 0 );
\IPS\Theme::i()->importDevCss( $this->directory, 0 );
/* Build XML and write to app directory */
$xml = new \XMLWriter;
$xml->openMemory();
$xml->setIndent( TRUE );
$xml->startDocument( '1.0', 'UTF-8' );
/* Root tag */
$xml->startElement('theme');
$xml->startAttribute('name');
$xml->text( "Default" );
$xml->endAttribute();
$xml->startAttribute('author_name');
$xml->text( "Invision Power Services, Inc" );
$xml->endAttribute();
$xml->startAttribute('author_url');
$xml->text( "http://www.invisionpower.com" );
$xml->endAttribute();
/* Skin settings */
foreach (
\IPS\Db::i()->select(
'core_theme_settings_fields.*',
'core_theme_settings_fields',
array( 'sc_set_id=? AND sc_app=?', 1, $this->directory ),
'sc_key ASC'
)
as $row
)
{
/* Initiate the <fields> tag */
$xml->startElement('field');
unset( $row['sc_id'], $row['sc_set_id'] );
foreach( $row as $k => $v )
{
if ( $k != 'sc_content' )
{
$xml->startAttribute( $k );
$xml->text( $v );
$xml->endAttribute();
}
}
/* Write value */
if ( preg_match( '/<|>|&/', $row['sc_content'] ) )
{
$xml->writeCData( str_replace( ']]>', ']]]]><![CDATA[>', $row['sc_content'] ) );
}
else
{
$xml->text( $row['sc_content'] );
}
/* Close the <fields> tag */
$xml->endElement();
}
/* Templates */
foreach ( \IPS\Db::i()->select( '*', 'core_theme_templates', array( 'template_set_id=? AND template_user_added=? AND template_app=?', 0, 0 , $this->directory ), 'template_group, template_name, template_location' ) as $template )
{
/* Initiate the <template> tag */
$xml->startElement('template');
foreach( $template as $k => $v )
{
if ( in_array( \substr( $k, 9 ), array('app', 'location', 'group', 'name', 'data' ) ) )
{
$xml->startAttribute( $k );
$xml->text( $v );
$xml->endAttribute();
}
}
/* Write value */
if ( preg_match( '/<|>|&/', $template['template_content'] ) )
{
$xml->writeCData( str_replace( ']]>', ']]]]><![CDATA[>', $template['template_content'] ) );
}
else
{
$xml->text( $template['template_content'] );
}
/* Close the <template> tag */
$xml->endElement();
}
/* Css */
foreach ( \IPS\Db::i()->select( '*', 'core_theme_css', array( 'css_set_id=? AND css_added_to=? AND css_app=?', 0, 0 , $this->directory ), 'css_path, css_name, css_location' ) as $css )
{
$xml->startElement('css');
foreach( $css as $k => $v )
{
if ( in_array( \substr( $k, 4 ), array('app', 'location', 'path', 'name', 'attributes' ) ) )
{
$xml->startAttribute( $k );
$xml->text( $v );
$xml->endAttribute();
}
}
/* Write value */
if ( preg_match( '/<|>|&/', $css['css_content'] ) )
{
$xml->writeCData( str_replace( ']]>', ']]]]><![CDATA[>', $css['css_content'] ) );
}
else
{
$xml->text( $css['css_content'] );
}
$xml->endElement();
}
/* Resources */
$_resources = $this->_buildThemeResources();
foreach ( $_resources as $data )
{
$xml->startElement('resource');
$xml->startAttribute('name');
$xml->text( $data['resource_name'] );
$xml->endAttribute();
$xml->startAttribute('app');
$xml->text( $data['resource_app'] );
$xml->endAttribute();
$xml->startAttribute('location');
$xml->text( $data['resource_location'] );
$xml->endAttribute();
$xml->startAttribute('path');
$xml->text( $data['resource_path'] );
$xml->endAttribute();
/* Write value */
$xml->text( base64_encode( $data['resource_data'] ) );
$xml->endElement();
}
/* Finish */
$xml->endDocument();
/* Write it */
if ( is_writable( \IPS\ROOT_PATH . '/applications/' . $this->directory . '/data' ) )
{
\file_put_contents( \IPS\ROOT_PATH . '/applications/' . $this->directory . '/data/theme.xml', $xml->outputMemory() );
}
else
{
throw new \RuntimeException( \IPS\Member::loggedIn()->language()->addToStack('dev_could_not_write_data') );
}
}
/**
* Build Resources ready for non IN_DEV use
*
* @return array
*/
protected function _buildThemeResources()
{
$resources = array();
$path = \IPS\ROOT_PATH . "/applications/" . $this->directory . "/dev/resources/";
\IPS\Theme::i()->importDevResources( $this->directory, 0 );
if ( is_dir( $path ) )
{
foreach( new \DirectoryIterator( $path ) as $location )
{
if ( $location->isDot() || \substr( $location->getFilename(), 0, 1 ) === '.' )
{
continue;
}
if ( $location->isDir() )
{
$resources = $this->_buildResourcesRecursive( $location->getFilename(), '/', $resources );
}
}
}
return $resources;
}
/**
* Build Resources ready for non IN_DEV use (Iterable)
* Theme resources should be raw binary data everywhere (filesystem and DB) except in the theme XML download where they are base64 encoded.
*
* @param string $location Location Folder Name
* @param string $path Path
* @param array $resources Array of resources to append to
* @return array
*/
protected function _buildResourcesRecursive( $location, $path='/', $resources=array() )
{
$root = \IPS\ROOT_PATH . "/applications/{$this->directory}/dev/resources/{$location}";
foreach( new \DirectoryIterator( $root . $path ) as $file )
{
if ( $file->isDot() || \substr( $file->getFilename(), 0, 1 ) === '.' || $file == 'index.html' )
{
continue;
}
if ( $file->isDir() )
{
$resources = $this->_buildResourcesRecursive( $location, $path . $file->getFilename() . '/', $resources );
}
else
{
$resources[] = array(
'resource_app' => $this->directory,
'resource_location' => $location,
'resource_path' => $path,
'resource_name' => $file->getFilename(),
'resource_data' => \file_get_contents( $root . $path . $file->getFilename() ),
'resource_added' => time()
);
}
}
return $resources;
}
/**
* Build languages for an app
*
* @return void
* @throws \RuntimeException
*/
public function buildLanguages()
{
/* Create the lang.xml file */
$xml = new \XMLWriter;
$xml->openMemory();
$xml->setIndent( TRUE );
$xml->startDocument( '1.0', 'UTF-8' );
/* Root tag */
$xml->startElement('language');
/* Initiate the <app> tag */
$xml->startElement('app');
/* Set key */
$xml->startAttribute('key');
$xml->text( $this->directory );
$xml->endAttribute();
/* Set version */
$xml->startAttribute('version');
$xml->text( $this->long_version );
$xml->endAttribute();
/* Import the language files */
$lang = array();
require \IPS\ROOT_PATH . "/applications/{$this->directory}/dev/lang.php";
foreach ( $lang as $k => $v )
{
/* Start */
$xml->startElement( 'word' );
/* Add key */
$xml->startAttribute('key');
$xml->text( $k );
$xml->endAttribute();
/* Add javascript flag */
$xml->startAttribute('js');
$xml->text( 0 );
$xml->endAttribute();
/* Write value */
if ( preg_match( '/<|>|&/', $v ) )
{
$xml->writeCData( str_replace( ']]>', ']]]]><![CDATA[>', $v ) );
}
else
{
$xml->text( $v );
}
/* End */
$xml->endElement();
}
$lang = array();
require \IPS\ROOT_PATH . "/applications/{$this->directory}/dev/jslang.php";
foreach ( $lang as $k => $v )
{
/* Start */
$xml->startElement( 'word' );
/* Add key */
$xml->startAttribute('key');
$xml->text( $k );
$xml->endAttribute();
/* Add javascript flag */
$xml->startAttribute('js');
$xml->text( 1 );
$xml->endAttribute();
/* Write value */
if ( preg_match( '/<|>|&/', $v ) )
{
$xml->writeCData( str_replace( ']]>', ']]]]><![CDATA[>', $v ) );
}
else
{
$xml->text( $v );
}
/* End */
$xml->endElement();
}
/* Finish */
$xml->endDocument();
/* Write it */
if ( is_writable( \IPS\ROOT_PATH . '/applications/' . $this->directory . '/data' ) )
{
\file_put_contents( \IPS\ROOT_PATH . '/applications/' . $this->directory . '/data/lang.xml', $xml->outputMemory() );
}
else
{
throw new \RuntimeException( \IPS\Member::loggedIn()->language()->addToStack('dev_could_not_write_data') );
}
}
/**
* Build email templates for an app
*
* @return void
* @throws \RuntimeException
*/
public function buildEmailTemplates()
{
/* Where are we looking? */
$path = \IPS\ROOT_PATH . "/applications/{$this->directory}/dev/email";
/* We create an array and store the templates temporarily so we can merge plaintext and HTML together */
$templates = array();
$templateKeys = array();
/* Loop over files in the directory */
if ( is_dir( $path ) )
{
foreach( new \DirectoryIterator( $path ) as $location )
{
if ( $location->isDir() and mb_substr( $location, 0, 1 ) !== '.' and ( $location->getFilename() === 'plain' or $location->getFilename() === 'html' ) )
{
foreach( new \DirectoryIterator( $path . '/' . $location->getFilename() ) as $sublocation )
{
if ( $sublocation->isDir() and mb_substr( $sublocation, 0, 1 ) !== '.' )
{
foreach( new \DirectoryIterator( $path . '/' . $location->getFilename() . '/' . $sublocation->getFilename() ) as $file )
{
if ( $file->isDot() or !$file->isFile() or mb_substr( $file, 0, 1 ) === '.' or $file->getFilename() === 'index.html' )
{
continue;
}
$data = $this->_buildEmailTemplateFromInDev( $path . '/' . $location->getFilename() . '/' . $sublocation->getFilename(), $file, $sublocation->getFilename() . '__' );
$extension = mb_substr( $file->getFilename(), mb_strrpos( $file->getFilename(), '.' ) + 1 );
$type = ( $extension === 'txt' ) ? "plaintext" : "html";
if ( ! isset( $templates[ $data['template_name'] ] ) )
{
$templates[ $data['template_name'] ] = array();
}
$templates[ $data['template_name'] ] = array_merge( $templates[ $data['template_name'] ], $data );
/* Delete the template in the store */
$key = $templates[ $data['template_name'] ]['template_key'] . '_email_' . $type;
unset( \IPS\Data\Store::i()->$key );
/* Remember our templates */
$templateKeys[] = $data['template_key'];
}
}
}
}
else
{
if ( $location->isDot() or !$location->isFile() or mb_substr( $location, 0, 1 ) === '.' or $location->getFilename() === 'index.html' )
{
continue;
}
$data = $this->_buildEmailTemplateFromInDev( $path, $location );
$extension = mb_substr( $location->getFilename(), mb_strrpos( $location->getFilename(), '.' ) + 1 );
$type = ( $extension === 'txt' ) ? "plaintext" : "html";
if ( ! isset( $templates[ $data['template_name'] ] ) )
{
$templates[ $data['template_name'] ] = array();
}
$templates[ $data['template_name'] ] = array_merge( $templates[ $data['template_name'] ], $data );
/* Delete the template in the store */
$key = $templates[ $data['template_name'] ]['template_key'] . '_email_' . $type;
unset( \IPS\Data\Store::i()->$key );
/* Remember our templates */
$templateKeys[] = $data['template_key'];
}
}
}
/* Clear out invalid templates */
\IPS\Db::i()->delete( 'core_email_templates', array( "template_app=? AND template_key NOT IN('" . implode( "','", $templateKeys ) . "')", $this->directory ) );
/* If we have any templates, put them in the database */
if( count($templates) )
{
foreach( $templates as $template )
{
\IPS\Db::i()->insert( 'core_email_templates', $template, TRUE );
}
/* Build the executable copies */
$this->parseEmailTemplates();
}
$xml = \IPS\Xml\SimpleXML::create('emails');
/* Templates */
foreach ( \IPS\Db::i()->select( '*', 'core_email_templates', array( 'template_parent=? AND template_app=?', 0, $this->directory ), 'template_key ASC' ) as $template )
{
$forXml = array();
foreach( $template as $k => $v )
{
if ( in_array( \substr( $k, 9 ), array('app', 'name', 'content_html', 'data', 'content_plaintext' ) ) )
{
$forXml[ $k ] = $v;
}
}
$xml->addChild( 'template', $forXml );
}
/* Write it */
if ( is_writable( \IPS\ROOT_PATH . '/applications/' . $this->directory . '/data' ) )
{
\file_put_contents( \IPS\ROOT_PATH . '/applications/' . $this->directory . '/data/emails.xml', $xml->asXML() );
}
else
{
throw new \RuntimeException( \IPS\Member::loggedIn()->language()->addToStack('dev_could_not_write_data') );
}
}
/**
* Imports an IN_DEV email template into the database
*
* @param string $path Path to file
* @param object $file DirectoryIterator File Object
* @param string|null $namePrefix Name prefix
* @return array
*/
protected function _buildEmailTemplateFromInDev( $path, $file, $namePrefix='' )
{
/* Get the content */
$html = file_get_contents( $path . '/' . $file->getFilename() );
$params = array();
/* Parse the header tag */
preg_match( '/^<ips:template parameters="(.+?)?" \/>(\r\n?|\n)/', $html, $params );
/* Strip the params tag */
$html = str_replace( $params[0], '', $html );
/* Figure out some details */
$extension = mb_substr( $file->getFilename(), mb_strrpos( $file->getFilename(), '.' ) + 1 );
$name = $namePrefix . str_replace( '.' . $extension, '', $file->getFilename() );
$type = ( $extension === 'txt' ) ? "plaintext" : "html";
$return = array(
'template_app' => $this->directory,
'template_name' => $name,
'template_data' => ( isset( $params[1] ) ) ? $params[1] : '',
'template_content_' . $type => $html,
'template_key' => md5( $this->directory . ';' . $name ),
);
return $return;
}
/**
* Build javascript for this app
*
* @return void
* @throws \RuntimeException
*/
public function buildJavascript()
{
/* Remove existing file object maps */
$map = isset( \IPS\Data\Store::i()->javascript_map ) ? \IPS\Data\Store::i()->javascript_map : array();
$map[ $this->directory ] = array();
\IPS\Data\Store::i()->javascript_map = $map;
$xml = \IPS\Output\Javascript::createXml( $this->directory );
/* Write it */
if ( is_writable( \IPS\ROOT_PATH . '/applications/' . $this->directory . '/data' ) )
{
\file_put_contents( \IPS\ROOT_PATH . '/applications/' . $this->directory . '/data/javascript.xml', $xml->outputMemory() );
}
else
{
throw new \RuntimeException( \IPS\Member::loggedIn()->language()->addToStack('dev_could_not_write_data') );
}
}
/**
* Build hooks for an app
*
* @return void
* @throws \RuntimeException
*/
public function buildHooks()
{
/* Build data */
$data = array();
foreach ( \IPS\Db::i()->select( '*', 'core_hooks', array( 'app=?', $this->directory ) ) as $hook )
{
$data[ $hook['filename'] ] = array(
'type' => $hook['type'],
'class' => $hook['class'],
);
}
/* Write it */
try
{
\IPS\Application::writeJson( \IPS\ROOT_PATH . '/applications/' . $this->directory . '/data/hooks.json', $data );
}
catch ( \RuntimeException $e )
{
throw new \RuntimeException( \IPS\Member::loggedIn()->language()->addToStack('dev_could_not_write_data') );
}
}
/**
* Compile email template into executable template
*
* @return void
*/
public function parseEmailTemplates()
{
foreach( \IPS\Db::i()->select( '*','core_email_templates', NULL, 'template_parent DESC' ) as $template )
{
/* Rebuild built copies */
$htmlFunction = 'namespace IPS\Theme;' . "\n" . \IPS\Theme::compileTemplate( $template['template_content_html'], "email_html_{$template['template_app']}_{$template['template_name']}", $template['template_data'] );
$ptFunction = 'namespace IPS\Theme;' . "\n" . \IPS\Theme::compileTemplate( $template['template_content_plaintext'], "email_plaintext_{$template['template_app']}_{$template['template_name']}", $template['template_data'] );
$key = $template['template_key'] . '_email_html';
\IPS\Data\Store::i()->$key = $htmlFunction;
$key = $template['template_key'] . '_email_plaintext';
\IPS\Data\Store::i()->$key = $ptFunction;
}
}
/**
* Write JSON file
*
* @param string $file Filepath
* @param array $data Data to write
* @return void
* @throws \RuntimeException Could not write
*/
public static function writeJson( $file, $data )
{
/* Format the JSON if we can (JSON_PRETTY_PRINT) is only available on PHP 5.4+ */
if ( version_compare( PHP_VERSION, '5.4.0' ) >= 0 )
{
$json = json_encode( $data, JSON_PRETTY_PRINT );
/* No idea why, but for some people blank structures have line breaks in them and for some people they don't
which unecessarily makes version control think things have changed - so let's make it the same for everyone */
$json = preg_replace( '/\[\s*\]/', '[]', $json );
$json = preg_replace( '/\{\s*\}/', '{}', $json );
}
else
{
$json = json_encode( $data );
}
/* Write it */
if( \file_put_contents( $file, $json ) === FALSE )
{
throw new \RuntimeException;
}
@chmod( $file, 0777 );
}
/**
* Can the user access this application?
*
* @param \IPS\Member|NULL $member Member we are checking against or NULL for currently logged on user
* @return bool
*/
public function canAccess( $member=NULL )
{
/* If it's not enabled, we can't */
if( !$this->enabled )
{
return FALSE;
}
/* If all groups have access, we can */
if( $this->disabled_groups === NULL )
{
return TRUE;
}
/* If all groups have access, we can */
if( $this->disabled_groups == '*' )
{
return FALSE;
}
/* Check member */
$member = ( $member === NULL ) ? \IPS\Member::loggedIn() : $member;
$memberGroups = array_merge( array( $member->member_group_id ), array_filter( explode( ',', $member->mgroup_others ) ) );
$accessGroups = explode( ',', $this->disabled_groups );
/* Are we in an allowed group? */
if( count( array_intersect( $accessGroups, $memberGroups ) ) )
{
return TRUE;
}
return FALSE;
}
/**
* Can manage the widgets
*
* @param \IPS\Member|NULL $member Member we are checking against or NULL for currently logged on user
* @return boolean
*/
public function canManageWidgets( $member=NULL )
{
/* Check member */
$member = ( $member === NULL ) ? \IPS\Member::loggedIn() : $member;
return $member->modPermission('can_manage_sidebar');
}
/**
* Save Changes
*
* @param bool $skipMember Skip clearing member cache clearing
* @return void
*/
public function save( $skipMember=FALSE )
{
parent::save();
unset( \IPS\Data\Store::i()->applications );
unset( \IPS\Data\Store::i()->frontNavigation );
/* Clear out member's cached "Create Menu" contents */
if( !$skipMember )
{
\IPS\Member::clearCreateMenu();
}
}
/**
* Delete Record
*
* @return void
*/
public function delete()
{
/* Get our uninstall callback script(s) if present. They are stored in an array so that we only create one object per extension, instead of one each time we loop. */
$uninstallExtensions = array();
foreach( $this->extensions( 'core', 'Uninstall', TRUE ) as $extension )
{
$uninstallExtensions[] = $extension;
}
/* Call preUninstall() so that application may perform any necessary cleanup before other data is removed (i.e. database tables) */
foreach( $uninstallExtensions as $extension )
{
if( method_exists( $extension, 'preUninstall' ) )
{
$extension->preUninstall( $this->directory );
}
}
/* Call onOtherAppUninstall so that other applications may perform any necessary cleanup */
/* @todo This is deprecated - we need to migrate to onOtherUninstall() but I'm leaving this call as-is to prevent breaking
backwards-compatibility until a major release */
foreach( static::allExtensions( 'core', 'Uninstall', FALSE ) as $extension )
{
if( method_exists( $extension, 'onOtherAppUninstall' ) )
{
$extension->onOtherAppUninstall( $this->directory );
}
}
$templatesToRecompile = array();
/* Note any templates that will need recompiling */
foreach ( \IPS\Db::i()->select( 'class', 'core_hooks', array( 'app=? AND type=?', $this->directory, 'S' ) ) as $class )
{
$templatesToRecompile[ $class ] = $class;
}
/* Delete menu items */
\IPS\core\FrontNavigation::deleteByApplication( $this );
/* Delete data from shared tables */
\IPS\Content\Search\Index::i()->removeApplicationContent( $this );
\IPS\Db::i()->delete( 'core_permission_index', array( 'app=? AND perm_type=? AND perm_type_id IN(?)', 'core', 'module', \IPS\Db::i()->select( 'sys_module_id', 'core_modules', array( 'sys_module_application=?', $this->directory ) ) ) );
\IPS\Db::i()->delete( 'core_modules', array( 'sys_module_application=?', $this->directory ) );
\IPS\Db::i()->delete( 'core_dev', array( 'app_key=?', $this->directory ) );
\IPS\Db::i()->delete( 'core_hooks', array( 'app=?', $this->directory ) );
\IPS\Db::i()->delete( 'core_item_markers', array( 'item_app=?', $this->directory ) );
\IPS\Db::i()->delete( 'core_permission_index', array( 'app=?', $this->directory ) );
\IPS\Db::i()->delete( 'core_upgrade_history', array( 'upgrade_app=?', $this->directory ) );
\IPS\Db::i()->delete( 'core_admin_logs', array( 'appcomponent=?', $this->directory ) );
\IPS\Db::i()->delete( 'core_sys_conf_settings', array( 'conf_app=?', $this->directory ) );
\IPS\Db::i()->delete( 'core_queue', array( 'app=?', $this->directory ) );
\IPS\Db::i()->delete( 'core_follow', array( 'follow_app=?', $this->directory ) );
\IPS\Db::i()->delete( 'core_view_updates', array( "classname LIKE CONCAT( ?, '%' )", "IPS\\\\{$this->directory}" ) );
$classes = array();
foreach( $this->extensions( 'core', 'ContentRouter' ) AS $contentRouter )
{
foreach ( $contentRouter->classes as $class )
{
$classes[] = $class;
if ( isset( $class::$commentClass ) )
{
$classes[] = $class::$commentClass;
}
if ( isset( $class::$reviewClass ) )
{
$classes[] = $class::$reviewClass;
}
}
}
if( count( $classes ) )
{
$queueWhere = array();
$queueWhere[] = array( 'app=?', 'core' );
$queueWhere[] = array( \IPS\Db::i()->in( '`key`', array( 'rebuildPosts', 'RebuildReputationIndex' ) ) );
foreach ( \IPS\Db::i()->select( '*', 'core_queue', $queueWhere ) as $queue )
{
$queue['data'] = json_decode( $queue['data'], TRUE );
if( in_array( $queue['data']['class'], $classes ) )
{
\IPS\Db::i()->delete( 'core_queue', array( 'id=?', $queue['id'] ) );
}
}
\IPS\Db::i()->delete( 'core_notifications', \IPS\Db::i()->in( 'item_class', $classes ) );
}
unset( \IPS\Data\Store::i()->settings );
/* Delete tasks and task logs */
\IPS\Db::i()->delete( 'core_tasks_log', array( 'task IN(?)', \IPS\Db::i()->select( 'id', 'core_tasks', array( 'app=?', $this->directory ) ) ) );
\IPS\Db::i()->delete( 'core_tasks', array( 'app=?', $this->directory ) );
/* Delete reports */
\IPS\Db::i()->delete( 'core_rc_reports', array( 'rid IN(?)', \IPS\Db::i()->select('id', 'core_rc_index', \IPS\Db::i()->in( 'class', $classes ) ) ) );
\IPS\Db::i()->delete( 'core_rc_comments', array( 'rid IN(?)', \IPS\Db::i()->select('id', 'core_rc_index', \IPS\Db::i()->in( 'class', $classes ) ) ) );
\IPS\Db::i()->delete( 'core_rc_index', \IPS\Db::i()->in('class', $classes) );
/* Delete language strings */
\IPS\Db::i()->delete( 'core_sys_lang_words', array( 'word_app=?', $this->directory ) );
/* Delete email templates */
$emailTemplates = \IPS\Db::i()->select( '*', 'core_email_templates', array( 'template_app=?', $this->directory ) );
if( $emailTemplates->count() )
{
foreach( $emailTemplates as $template )
{
if( $template['template_content_html'] )
{
$k = $template['template_key'] . '_email_html';
unset( \IPS\Data\Store::i()->$k );
}
if( $template['template_content_plaintext'] )
{
$k = $template['template_key'] . '_email_plaintext';
unset( \IPS\Data\Store::i()->$k );
}
}
\IPS\Db::i()->delete( 'core_email_templates', array( 'template_app=?', $this->directory ) );
}
/* Delete skin template/CSS/etc. */
\IPS\Theme::removeTemplates( $this->directory, NULL, NULL, NULL, TRUE );
\IPS\Theme::removeCss( $this->directory, NULL, NULL, NULL, TRUE );
\IPS\Theme::removeResources( $this->directory, NULL, NULL, NULL, TRUE );
/* Delete theme settings */
$valueIds = iterator_to_array( \IPS\Db::i()->select( 'sc_id', 'core_theme_settings_fields', array( array( 'sc_app=?', $this->directory ) ) ) );
\IPS\Db::i()->delete( 'core_theme_settings_fields', array( 'sc_app=?', $this->directory ) );
if ( count( $valueIds ) )
{
\IPS\Db::i()->delete( 'core_theme_settings_values', array( 'sv_id IN(?)', implode( ',', $valueIds ) ) );
}
unset( \IPS\Data\Store::i()->themes );
/* Delete any stored files */
foreach( $this->extensions( 'core', 'FileStorage', TRUE ) as $extension )
{
$extension->delete();
}
$notificationTypes = array();
foreach( $this->extensions( 'core', 'Notifications' ) as $key => $class )
{
if ( method_exists( $class, 'getConfiguration' ) )
{
$defaults = $class->getConfiguration( NULL );
foreach( $defaults AS $k => $config )
{
$notificationTypes[] = $k;
}
}
}
if( count( $notificationTypes ) )
{
\IPS\Db::i()->delete( 'core_notification_defaults', "notification_key IN('" . implode( "','", $notificationTypes ) . "')");
\IPS\Db::i()->delete( 'core_notification_preferences', "notification_key IN('" . implode( "','", $notificationTypes ) . "')");
}
/* Delete database tables */
if( file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/schema.json" ) )
{
$schema = @json_decode( file_get_contents( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/schema.json" ), TRUE );
if( is_array( $schema ) AND count( $schema ) )
{
foreach( $schema as $tableName => $definition )
{
try
{
\IPS\Db::i()->dropTable( $tableName, TRUE );
}
catch( \IPS\Db\Exception $e )
{
/* Ignore "Cannot drop table because it does not exist" */
if( $e->getCode() <> 1051 )
{
throw $e;
}
}
}
}
}
/* Revert other database changes performed by installation */
if( file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/setup/install/queries.json" ) )
{
$schema = json_decode( file_get_contents( \IPS\ROOT_PATH . "/applications/{$this->directory}/setup/install/queries.json" ), TRUE );
ksort($schema);
foreach( $schema as $instruction )
{
switch ( $instruction['method'] )
{
case 'addColumn':
try
{
\IPS\Db::i()->dropColumn( $instruction['params'][0], $instruction['params'][1]['name'] );
}
catch( \IPS\Db\Exception $e )
{
/* Ignore "Cannot drop key because it does not exist" */
if( $e->getCode() <> 1091 )
{
throw $e;
}
}
break;
case 'addIndex':
try
{
\IPS\Db::i()->dropIndex( $instruction['params'][0], $instruction['params'][1]['name'] );
}
catch( \IPS\Db\Exception $e )
{
/* Ignore "Cannot drop key because it does not exist" */
if( $e->getCode() <> 1091 )
{
throw $e;
}
}
break;
}
}
}
/* delete widgets */
\IPS\Db::i()->delete( 'core_widgets', array( 'app = ?', $this->directory ) );
\IPS\Db::i()->delete( 'core_widget_areas', array( 'app = ?', $this->directory ) );
/* clean up widget areas table */
foreach ( \IPS\Db::i()->select( '*', 'core_widget_areas' ) as $row )
{
$data = json_decode( $row['widgets'], true );
foreach ( $data as $key => $widget)
{
if ( isset( $widget['app'] ) and $widget['app'] == $this->directory )
{
unset( $data[$key]) ;
}
}
\IPS\Db::i()->update( 'core_widget_areas', array( 'widgets' => json_encode( $data ) ), array( 'id=?', $row['id'] ) );
}
/* Clean up widget trash table */
$trash = array();
foreach( \IPS\Db::i()->select( '*', 'core_widget_trash' ) AS $garbage )
{
$data = json_decode( $garbage['data'], TRUE );
if ( isset( $data['app'] ) AND $data['app'] == $this->directory )
{
$trash[] = $garbage['id'];
}
}
\IPS\Db::i()->delete( 'core_widget_trash', \IPS\Db::i()->in( 'id', $trash ) );
/* Call postUninstall() so that application may perform any necessary cleanup after other data is removed */
foreach( $uninstallExtensions as $extension )
{
if( method_exists( $extension, 'postUninstall' ) )
{
$extension->postUninstall( $this->directory );
}
}
/* Clean up FURL Definitions */
if ( file_exists( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/furl.json" ) )
{
$current = json_decode( \IPS\Db::i()->select( 'conf_value', 'core_sys_conf_settings', array( "conf_key=?", 'furl_configuration' ) )->first(), true );
$default = json_decode( preg_replace( '/\/\*.+?\*\//s', '', @file_get_contents( \IPS\ROOT_PATH . "/applications/{$this->directory}/data/furl.json" ) ), true );
if ( isset( $default['pages'] ) and $current !== NULL )
{
foreach( $default['pages'] AS $key => $def )
{
if ( isset( $current[$key] ) )
{
unset( $current[$key] );
}
}
\IPS\Db::i()->update( 'core_sys_conf_settings', array( 'conf_value' => json_encode( $current ) ), array( "conf_key=?", 'furl_configuration' ) );
}
}
/* Delete from DB */
\IPS\File::unclaimAttachments( 'core_Admin', $this->id, NULL, 'appdisabled' );
parent::delete();
/* Rebuild hooks file */
\IPS\Plugin\Hook::writeDataFile();
foreach ( $templatesToRecompile as $k )
{
$exploded = explode( '_', $k );
\IPS\Theme::deleteCompiledTemplate( $exploded[1], $exploded[2], $exploded[3] );
}
/* Clear out member's cached "Create Menu" contents */
\IPS\Member::clearCreateMenu();
/* Clear out data store for updated values */
unset( \IPS\Data\Store::i()->modules );
unset( \IPS\Data\Store::i()->applications );
unset( \IPS\Data\Store::i()->settings );
unset( \IPS\Data\Store::i()->widgets );
unset( \IPS\Data\Store::i()->furl_configuration );
}
/**
* Return an array of version upgrade folders this application contains
*
* @param int $start If provided, only upgrade steps above this version will be returned
* @return array
*/
public function getUpgradeSteps( $start=0 )
{
$path = \IPS\ROOT_PATH . "/applications/{$this->directory}/setup";
if( !is_dir( $path ) )
{
return array();
}
$versions = array();
foreach( new \DirectoryIterator( $path ) as $file )
{
if( $file->isDir() AND !$file->isDot() )
{
if( mb_substr( $file->getFilename(), 0, 4 ) == 'upg_' )
{
$_version = intval( mb_substr( $file->getFilename(), 4 ) );
if( $_version > $start )
{
$versions[] = $_version;
}
}
}
}
/* Sort the versions lowest to highest */
sort( $versions, SORT_NUMERIC );
return $versions;
}
/**
* Can view page even when user is a guest when guests cannot access the site
*
* @param \IPS\Application\Module $module The module
* @param string $controller The controller
* @param string|NULL $do To "do" parameter
* @return bool
*/
public function allowGuestAccess( \IPS\Application\Module $module, $controller, $do )
{
return FALSE;
}
/**
* Can view page even when site is offline
*
* @param \IPS\Application\Module $module The module
* @param string $controller The controller
* @param string|NULL $do To "do" parameter
* @return bool
*/
public function allowOfflineAccess( \IPS\Application\Module $module, $controller, $do )
{
return FALSE;
}
/**
* [Node] Does the currently logged in user have permission to edit this node?
*
* @return bool
*/
public function canEdit()
{
return ( \IPS\Member::loggedIn()->hasAcpRestriction( 'core', 'applications', 'app_manage' ) );
}
} | Tresint/worldherb | forum/system/Application/Application.php | PHP | mit | 124,243 |
'use strict';
const _ = require('lodash');
const Promise = require('bluebird');
const fs = require('fs-extra');
const wd = require('wd');
const StateError = require('../errors/state-error');
const find = require('./find-func').find;
module.exports = class ActionsBuilder {
static create(actions) {
return new ActionsBuilder(actions);
}
constructor(actions) {
this._actions = actions;
}
wait(milliseconds) {
this._pushAction(this.wait, (browser) => {
return browser.sleep(milliseconds);
});
return this;
}
waitForElementToShow(selector, timeout) {
this._waitElementAction(this.waitForElementToShow, selector, {
timeout: timeout,
asserter: wd.asserters.isDisplayed,
error: 'was not shown'
});
return this;
}
waitForElementToHide(selector, timeout) {
this._waitElementAction(this.waitForElementToHide, selector, {
timeout: timeout,
asserter: wd.asserters.isNotDisplayed,
error: 'was not hidden'
});
return this;
}
_waitElementAction(method, selector, options) {
options = _.defaults(options, {timeout: 1000});
if (typeof selector !== 'string') {
throw new TypeError(method.name + ' accepts only CSS selectors');
}
if (typeof options.timeout !== 'number') {
throw new TypeError(method.name + ' accepts only numeric timeout');
}
this._pushAction(method, (browser) => {
return browser.waitForElementByCssSelector(selector, options.asserter, options.timeout)
.catch(() => {
//assuming its timeout error, no way to distinguish
return Promise.reject(new StateError(
'Element ' + selector + ' ' + options.error + ' in ' + options.timeout + 'ms'));
});
});
return this;
}
waitForJSCondition(jsFunc, timeout) {
if (typeof jsFunc !== 'function') {
throw new TypeError('waitForCondition should accept function');
}
timeout = (typeof timeout === 'undefined' ? 1000 : timeout);
this._pushAction(this.waitForJSCondition, (browser) => {
return browser.waitFor(wd.asserters.jsCondition(serializeFunc(jsFunc)), timeout)
.catch(() => Promise.reject(new StateError('Condition was not met in ' + timeout + 'ms')));
});
return this;
}
_pushAction(method, action) {
let stackHolder = {};
// capture stack trace to use it later in case
// of an error.
Error.captureStackTrace(stackHolder, method);
this._actions.push(function() {
return action.apply(null, arguments)
.catch((e) => {
if (e instanceof StateError) {
// replace stack of the error, so that
// stacktrace will now link to user's
// test code wil call to the action instead
// of gemini's internals.
replaceStack(e, stackHolder.stack);
}
return Promise.reject(e);
});
});
}
click(element, button) {
button = acceptMouseButton(button);
if (isInvalidElement(element)) {
throw new TypeError('.click() must receive valid element or CSS selector');
}
this._pushAction(this.click, (browser) => {
return findElement(element, browser)
.then((element) => browser.moveTo(element))
.then(() => browser.click(button));
});
return this;
}
doubleClick(element) {
if (isInvalidElement(element)) {
throw new TypeError('.doubleClick() must receive valid element or CSS selector');
}
this._pushAction(this.doubleClick, (browser) => {
return findElement(element, browser)
.then((element) => {
return browser.moveTo(element)
.then(() => browser.doubleclick());
});
});
return this;
}
dragAndDrop(element, dragTo) {
if (isInvalidElement(element)) {
throw new TypeError('.dragAndDrop() "element" argument should be valid element or CSS selector');
}
if (isInvalidElement(dragTo)) {
throw new TypeError('.dragAndDrop() "dragTo" argument should be valid element or CSS selector');
}
return this.mouseDown(element)
.mouseMove(dragTo)
.mouseUp();
}
mouseDown(element, button) {
button = acceptMouseButton(button);
if (isInvalidElement(element)) {
throw new TypeError('.mouseDown() must receive valid element or CSS selector');
}
this._pushAction(this.mouseDown, (browser) => {
return findElement(element, browser)
.then((element) => browser.moveTo(element))
.then(() => browser.buttonDown(button));
});
return this;
}
mouseUp(element, button) {
button = acceptMouseButton(button);
this._pushAction(this.mouseUp, (browser) => {
let action;
if (element) {
action = findElement(element, browser)
.then((element) => browser.moveTo(element));
} else {
action = Promise.resolve();
}
return action.then(() => browser.buttonUp(button));
});
return this;
}
mouseMove(element, offset) {
if (isInvalidElement(element)) {
throw new TypeError('.mouseMove() must receive valid element or CSS selector');
}
if (offset) {
if ('x' in offset && typeof offset.x !== 'number') {
throw new TypeError('offset.x should be a number');
}
if ('y' in offset && typeof offset.y !== 'number') {
throw new TypeError('offset.y should be a number');
}
}
this._pushAction(this.mouseMove, (browser) => {
return findElement(element, browser)
.then((element) => {
if (offset) {
return browser.moveTo(element, offset.x, offset.y);
}
return browser.moveTo(element);
});
});
return this;
}
sendKeys(element, keys) {
let action;
if (typeof keys === 'undefined' || keys === null) {
keys = element;
action = (browser) => browser.keys(keys);
} else {
if (isInvalidElement(element)) {
throw new TypeError('.sendKeys() must receive valid element or CSS selector');
}
action = (browser) => {
return findElement(element, browser)
.then((element) => browser.type(element, keys));
};
}
if (isInvalidKeys(keys)) {
throw new TypeError('keys should be string or array of strings');
}
this._pushAction(this.sendKeys, action);
return this;
}
sendFile(element, path) {
if (typeof path !== 'string') {
throw new TypeError('path must be string');
}
if (isInvalidElement(element)) {
throw new TypeError('.sendFile() must receive valid element or CSS selector');
}
this._pushAction(this.sendFile, (browser) => {
return fs.statAsync(path)
.then((stat) => {
if (!stat.isFile()) {
return Promise.reject(new StateError(path + ' should be existing file'));
}
return findElement(element, browser);
})
.then((element) => element.sendKeys(path));
});
return this;
}
focus(element) {
if (isInvalidElement(element)) {
throw new TypeError('.focus() must receive valid element or CSS selector');
}
return this.sendKeys(element, '');
}
tap(element) {
if (isInvalidElement(element)) {
throw new TypeError('.tap() must receive valid element or CSS selector');
}
this._pushAction(this.tap, (browser) => {
return findElement(element, browser)
.then((elem) => browser.tapElement(elem));
});
return this;
}
flick(offsets, speed, element) {
if (element && isInvalidElement(element)) {
throw new TypeError('.flick() must receive valid element or CSS selector');
}
this._pushAction(this.flick, (browser) => {
if (element) {
return findElement(element, browser)
.then((elem) => browser.flick(elem, offsets.x, offsets.y, speed));
}
return browser.flick(offsets.x, offsets.y, speed);
});
return this;
}
executeJS(callback) {
if (typeof callback !== 'function') {
throw new TypeError('executeJS argument should be function');
}
this._pushAction(this.executeJS, (browser) => browser.execute(serializeFunc(callback)));
return this;
}
setWindowSize(width, height) {
this._pushAction(this.setWindowSize, (browser, postActions) => {
return (postActions ? mkRestoreAction_() : Promise.resolve())
.then(() => browser.setWindowSize(width, height));
function mkRestoreAction_() {
return browser.getWindowSize()
.then((size) => {
if (size.width !== width || size.height !== height) {
postActions.setWindowSize(size.width, size.height);
}
});
}
});
return this;
}
changeOrientation(options = {}) {
options = _.defaults(options, {timeout: 2500});
this._pushAction(this.changeOrientation, (browser, postActions) => {
if (postActions) {
postActions.changeOrientation(options);
}
return getBodyWidth()
.then((initialBodyWidth) => {
return rotate()
.then((result) => waitForOrientationChange(initialBodyWidth).then(() => result));
});
function getBodyWidth() {
return browser.evalScript(serializeFunc(function(window) {
return window.document.body.clientWidth;
}));
}
function rotate() {
const orientations = ['PORTRAIT', 'LANDSCAPE'];
const getAnotherOrientation = (orientation) => _(orientations).without(orientation).first();
return browser.getOrientation()
.then((initialOrientation) => browser.setOrientation(getAnotherOrientation(initialOrientation)));
}
function waitForOrientationChange(initialBodyWidth) {
return browser
.waitFor(wd.asserters.jsCondition(serializeFunc(function(window, initialBodyWidth) {
return window.document.body.clientWidth !== Number(initialBodyWidth);
}, [initialBodyWidth])), options.timeout)
.catch(() => Promise.reject(new StateError(`Orientation did not changed in ${options.timeout} ms`)));
}
});
return this;
}
};
function acceptMouseButton(button) {
if (typeof button === 'undefined') {
return 0;
}
if ([0, 1, 2].indexOf(button) === -1) {
throw new TypeError('Mouse button should be 0 (left), 1 (middle) or 2 (right)');
}
return button;
}
function isInvalidKeys(keys) {
if (typeof keys !== 'string') {
if (!Array.isArray(keys)) {
return true;
}
return keys.some((chunk) => typeof chunk !== 'string');
}
return false;
}
function isInvalidElement(element) {
return (!element || !element._selector) && typeof element !== 'string';
}
function replaceStack(error, stack) {
let message = error.stack.split('\n')[0];
error.stack = [message].concat(stack.split('\n').slice(1)).join('\n');
}
function serializeFunc(func, args) {
return '(' + func.toString() + (_.isEmpty(args) ? ')(window);' : `)(window, '${args.join('\', \'')}');`);
}
function findElement(element, browser) {
if (element.cache && element.cache[browser.sessionId]) {
return Promise.resolve(element.cache[browser.sessionId]);
}
if (typeof element === 'string') {
element = find(element);
}
return browser.findElement(element._selector)
.then((foundElement) => {
element.cache = element.cache || {};
element.cache[browser.sessionId] = foundElement;
return foundElement;
})
.catch((error) => {
if (error.status === 7) {
error = new StateError('Could not find element with css selector in actions chain: '
+ error.selector);
}
return Promise.reject(error);
});
}
| gemini-testing/gemini | lib/tests-api/actions-builder.js | JavaScript | mit | 13,442 |
// require(d) gulp for compatibility with sublime-gulp.
var gulp = require('gulp');
const { src, dest, series, parallel } = require('gulp');
const clean = require('gulp-clean');
const eslint = require('gulp-eslint');
const csso = require('gulp-csso');
const rename = require('gulp-rename');
const babel = require("gulp-babel");
const minify_babel = require("gulp-babel-minify");
const minify = require('gulp-minify');
const rollup = require('rollup');
// Erase build directory
function cleandist() {
return gulp.src(['build/*'], {read: false, allowEmpty: true})
.pipe(clean())
}
// Lint Task
function lint() {
return gulp.src('./src/*.js')
.pipe(eslint())
.pipe(eslint.format())
}
// Build ES6 module
function build_es6() {
return gulp.src('./src/*.js')
.pipe(minify({
ext: {
src:'.js',
min:'.min.js'
},
preserveComments: 'some',
noSource: true
}))
.pipe(gulp.dest('./build/es6/chordictionary'))
}
// Build CommonJS module
async function build_commonjs() {
const bundle = await rollup.rollup({
input: './src/main.js'
});
await bundle.write({
file: './tmp/chordictionary_cjs.js',
format: 'cjs',
name: 'chordictionary'
});
await gulp.src('./tmp/chordictionary_cjs.js', { allowEmpty: true })
.pipe(clean())
.pipe(babel())
.pipe(rename('chordictionary.min.js'))
.pipe(minify_babel())
.pipe(gulp.dest('./build/commonjs'))
}
// Build IIFE script
async function build_iife() {
const bundle = await rollup.rollup({
input: './src/main.js'
});
await bundle.write({
file: './tmp/chordictionary_iife.js',
format: 'iife',
name: 'chordictionary'
});
await gulp.src('./tmp/chordictionary_iife.js', { allowEmpty: true })
.pipe(clean())
.pipe(babel())
.pipe(rename('chordictionary.min.js'))
.pipe(minify_babel())
.pipe(gulp.dest('./build/iife'));
}
// CSS task
function css() {
return gulp.src('./src/chordictionary.css')
.pipe(csso())
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest('./build'));
}
const build = gulp.series(cleandist, gulp.parallel(css, lint), gulp.parallel(build_es6, build_commonjs, build_iife));
exports.lint = lint;
exports.css = css;
exports.clean = cleandist;
exports.build = build;
exports.default = build;
| greird/chordictionaryjs | gulpfile.js | JavaScript | mit | 2,191 |
# -*- coding: utf-8 -*-
import threading
import logging
import unittest
import gc
from stockviderApp.utils import retryLogger
from stockviderApp.sourceDA.symbols.referenceSymbolsDA import ReferenceSymbolsDA
from stockviderApp.localDA.symbols.dbReferenceSymbolsDA import DbReferenceSymbolsDA
from stockviderApp.sourceDA.symbols.googleSymbolsDA import GoogleSymbolsDA
from stockviderApp.sourceDA.symbols.yahooSymbolsDA import YahooSymbolsDA
from stockviderApp.sourceDA.symbols.wikiSymbolsDA import WikiSymbolsDA
from stockviderApp.localDA.symbols.dbGoogleSymbolsDA import DbGoogleSymbolsDA
from stockviderApp.localDA.symbols.dbYahooSymbolsDA import DbYahooSymbolsDA
from stockviderApp.localDA.symbols.dbWikiSymbolsDA import DbWikiSymbolsDA
from stockviderApp.localDA.rawData.dbGoogleRawDataDA import DbGoogleRawDataDA
from stockviderApp.localDA.rawData.dbYahooRawDataDA import DbYahooRawDataDA
from stockviderApp.localDA.rawData.dbWikiRawDataDA import DbWikiRawDataDA
from stockviderApp.sourceDA.rawData.googleRawDataDA import GoogleRawDataDA
from stockviderApp.sourceDA.rawData.yahooRawDataDA import YahooRawDataDA
from stockviderApp.sourceDA.rawData.wikiRawDataDA import WikiRawDataDA
from stockviderApp.sourceDA.rawData.referenceRawDataDA import ReferenceRawDataDA
from stockviderApp.localDA.rawData.dbReferenceRawDataDA import DbReferenceRawDataDA
class ThreadUpdateRawData(threading.Thread):
'''
Threading class handling data retrieval from Quand sources.
'''
threadLimiter = threading.BoundedSemaphore(3)
# De toute façon il y en a que 3 max
def __init__(self, _updateFunc, _symbolList, _exchange):
threading.Thread.__init__(self)
self.updateFunc = _updateFunc
self.symbolList = _symbolList
self.exchange = _exchange
# Récupère le logger
self.logger = logging.getLogger(__name__)
return
def run(self):
# Demande l'acquisition d'un thread
ThreadUpdateRawData.threadLimiter.acquire()
# Découpe la liste de symbols en plusieurs listes (pb de mémoire)
listOfSymbsList = ThreadUpdateRawData._chunks(self.symbolList, 100)
for (curIndex, currentSymbolsList) in enumerate(listOfSymbsList):
self.logger.info("Traitement de la liste " + str(curIndex + 1) +
"/" + str(len(listOfSymbsList)))
# Execute la fonction d'update
self.updateFunc(currentSymbolsList, self.exchange)
# Relache proprement la mémoire
gc.collect()
# Release le thread
ThreadUpdateRawData.threadLimiter.release()
return
@classmethod
def _chunks(cls, l, n):
'''
Chuncks and returns the list in multiple list of size n.
:param l: list to chunck
:type l: list
:param n: chunck size
:type n: int
:returns: list of chunked lists
:rtype: list
'''
listOfLists = []
for i in range(0, len(l), n):
listOfLists.append(l[i:i+n])
return listOfLists
class DbManager(object):
'''
Class wrapping all procedures to update the local database from
outside sources.
'''
# A virer en prod - utile en debug pour limiter la récupération de données
limitNbr = None # A none il n'est pas pris en compte
exchangeTuple = ('NYSE', 'NASDAQ')
instrumentType = 'EQUITIES'
def __init__(self):
# Récupère le logger
self.logger = logging.getLogger(__name__)
return
def runTest(self):
'''
Runs tests.
'''
self.logger.info("Début des tests unitaires")
self._runUnitTest()
self.logger.info("Fin des tests unitaires")
return
def runSymbols(self):
'''
Handles the symbol tables update in the database.
'''
self.logger.info("Début de l'update des symbols Quandl")
# Update les symbols des tables Quandl
self._updateQuandlSymbols(self.exchangeTuple)
self.logger.info("Fin de l'update des symbols Quandl")
self.logger.info("Début de l'update des symbols de référence")
# Upate les symbols de référence
for exchange in self.exchangeTuple:
self.logger.info("Référence - ajout des symbols de " + str(exchange))
self._updateReferenceSymbols(exchange, self.instrumentType)
self.logger.info("Fin de l'update des symbols de référence")
self.logger.info("Début du nettoyage des symbols de référence")
# Nettoie les doublons dans les symbols de ref entre Nyse et Nasdaq
self._cleanDuplicatedReferenceSymbols()
self.logger.info("Fin du nettoyage des symbols de référence")
self.logger.info("Début du mapping des symbols de référence")
# Mappe les symbols de référence
for exchange in self.exchangeTuple:
self.logger.info("Référence - mapping des symbols de " + str(exchange))
self._mapReferenceSymbols(exchange)
self.logger.info("Fin du mapping des symbols de référence")
return
def runQuandlRawData(self, exchange):
'''
Handle the Quandl data update in the database.
'''
self.logger.info("Début de traitement des raw data Quandl de " + str(exchange))
self._updateQuandlRawData(exchange)
return
def runReferenceRawData(self, exchange):
'''
Handle the aggregated data update in the database.
'''
self.logger.info("Début de traitement des raw data Reference de " + str(exchange))
self._updateReferenceRawData(exchange)
return
# -------------------------------------------------------------
def _runUnitTest(self):
'''
Runs unit tests.
'''
# Lance les tests
testsuite = unittest.TestLoader().discover('./test/')
testResults = unittest.TextTestRunner(verbosity=1).run(testsuite)
# Log les erreurs et les echec
self.logger.warning("Erreur de test : ")
for errorString in testResults.errors:
self.logger.error(errorString)
for failureString in testResults.failures:
self.logger.error(failureString)
return
# ------------------ Méthodes d'update des symbols -------------------
@retryLogger(maxRetryNbr=3, sleepTimeIncr=30)
def _updateReferenceSymbols(self, exchange, instrumentType):
'''
Updates the reference symbol table in the database.
:param exchange: name of the exchange
:type exchange: str
:param instrumentType: type of instrument (EQUITIES, BOND, ...)
:type instrumentType: str
.. warning::
This procedure must be called after the local update of the Quandl
symbols.
'''
# Met en place le DAO des symbols de référence
referenceSymbolsDAO = ReferenceSymbolsDA(exchange)
dbReferenceSymbolDAO = DbReferenceSymbolsDA()
# Récupère les symbols de référence
referenceSymbolsList = referenceSymbolsDAO.returnSymbolsList(instrumentType)[0:DbManager.limitNbr]
# Les ajoute en DB
dbReferenceSymbolDAO.updateOrAddSymbolsList(referenceSymbolsList, exchange)
self.logger.info("Référence - symbols ajoutés dans la table")
return
def _cleanDuplicatedReferenceSymbols(self):
'''
Cleans the reference symbol table from duplicated entries.
.. note::
It may happen that the same symbol is listed on both NYSE and
NASDAQ. This procedure ensures that these symbols are only recorded
once in the database.
'''
# Met en place le DAO local des symbols de référence
dbReferenceSymbolDAO = DbReferenceSymbolsDA()
dbReferenceSymbolDAO.cleanDuplicatedSymbols('NYSE', 'NASDAQ')
self.logger.info("Référence - NYSE/NASDAQ nettoyés")
return
def _mapReferenceSymbols(self, exchange):
'''
Maps the 1-1 relation of reference symbols object with each Quandl
symbols.
:param exchange: name of the exchange
:type exchange: str
'''
# Met en place le DAO des symbols de référence
dbReferenceSymbolDAO = DbReferenceSymbolsDA()
# Récupère tous les symbols de l'exchange
referenceSymbolsList = dbReferenceSymbolDAO.getAllSymbolsList(exchange)
refSymbolNamesList = [refSymbol.symbol for refSymbol in referenceSymbolsList]
# Mappe les symbols de référence avec les symbols de chaque source
dbReferenceSymbolDAO.mapOneToOneRelationsSymbols(refSymbolNamesList, exchange)
self.logger.info("Référence - symbols mappés")
return
def _updateQuandlSymbols(self, exchangeNamesTuple):
'''
Updates the Quandl symbol tables in the database.
:param exchangeNamesTuple: tuple of exchange names
:type exchangeNamesTuple: tuple
'''
self.logger.info("Début de l'update des symbols Google")
self._updateGoogleSymbols(exchangeNamesTuple)
self.logger.info("Fin de l'update des symbols Google")
self.logger.info("Début de l'update des symbols Yahoo")
self._updateYahooSymbols(exchangeNamesTuple)
self.logger.info("Fin de l'update des symbols Yahoo")
self.logger.info("Début de l'update des symbols Wiki")
self._updateWikiSymbols(exchangeNamesTuple)
self.logger.info("Fin de l'update des symbols Wiki")
return
@retryLogger(maxRetryNbr=3, sleepTimeIncr=30)
def _updateGoogleSymbols(self, exchangeNamesTuple):
'''
Updates the Google symbol table in the database.
:param exchangeNamesTuple: tuple of exchange names
:type exchangeNamesTuple: tuple
'''
# Met en place les DAO des symbols
googleSymbolsDAO = GoogleSymbolsDA()
dbGoogleSymbolsDAO = DbGoogleSymbolsDA()
# Récupère tous les symbols de la source
symbolsListGoogle = googleSymbolsDAO.returnSymbolsDict()
# Crée la liste d'exchange effectifs de cette source
googleExchangeNamesList = []
for exchange in exchangeNamesTuple:
googleExchangeNamesList.append(self._returnEffectiveExchange(exchange)['Google'])
googleExchangeNamesList = list(set(googleExchangeNamesList))
# Ajoute les symbols à la DB pour chaque exchange du tuple
for exchange in googleExchangeNamesList:
self.logger.info("Google - traitement des symbols de " + str(exchange))
# Récupère la liste de symbols de cet exchange
currentSymbolsList = symbolsListGoogle[exchange][0:DbManager.limitNbr]
# Les ajoute en DB
dbGoogleSymbolsDAO.updateOrAddSymbolsList(currentSymbolsList, exchange)
return
@retryLogger(maxRetryNbr=3, sleepTimeIncr=30)
def _updateYahooSymbols(self, exchangeNamesTuple):
'''
Updates the Yahoo symbol table in the database.
:param exchangeNamesTuple: tuple of exchange names
:type exchangeNamesTuple: tuple
'''
# Met en place les DAO des symbols
yahooSymbolsDAO = YahooSymbolsDA()
dbYahooSymbolsDAO = DbYahooSymbolsDA()
# Récupère tous les symbols de la source
symbolsListYahoo = yahooSymbolsDAO.returnSymbolsDict()
# Crée la liste d'exchange effectifs de cette source
yahooExchangeNamesList = []
for exchange in exchangeNamesTuple:
yahooExchangeNamesList.append(self._returnEffectiveExchange(exchange)['Yahoo'])
yahooExchangeNamesList = list(set(yahooExchangeNamesList))
# Ajoute les symbols à la DB pour chaque exchange du tuple
for exchange in yahooExchangeNamesList:
self.logger.info("Yahoo - traitement des symbols de " + str(exchange))
# Récupère la liste de symbols de cet exchange
currentSymbolsList = symbolsListYahoo[exchange][0:DbManager.limitNbr]
# Les ajoute en DB
dbYahooSymbolsDAO.updateOrAddSymbolsList(currentSymbolsList, exchange)
return
@retryLogger(maxRetryNbr=3, sleepTimeIncr=30)
def _updateWikiSymbols(self, exchangeNamesTuple):
'''
Updates the Wiki symbol table in the database.
:param exchangeNamesTuple: tuple of exchange names
:type exchangeNamesTuple: tuple
'''
# Met en place les DAO des symbols
wikiSymbolsDAO = WikiSymbolsDA()
dbWikiSymbolsDAO = DbWikiSymbolsDA()
# Récupère tous les symbols de la source
symbolsListWiki = wikiSymbolsDAO.returnSymbolsDict()
# Crée la liste d'exchange effectifs de cette source
wikiExchangeNamesList = []
for exchange in exchangeNamesTuple:
wikiExchangeNamesList.append(self._returnEffectiveExchange(exchange)['Wiki'])
wikiExchangeNamesList = list(set(wikiExchangeNamesList))
# Ajoute les symbols à la DB pour chaque exchange du tuple
for exchange in wikiExchangeNamesList:
self.logger.info("Wiki - traitement des symbols de " + str(exchange))
# Récupère la liste de symbols de cet exchange
currentSymbolsList = symbolsListWiki[exchange][0:DbManager.limitNbr]
# Les ajoute en DB
dbWikiSymbolsDAO.updateOrAddSymbolsList(currentSymbolsList, exchange)
return
# -------------- Méthodes d'update des raw data ---------------------
def _updateQuandlRawData(self, exchange):
'''
Updates the Quandl data tables in the database.
:param exchange: name of the exchange
:type exchange: str
'''
# Ces liste stockent les objets Db des symbols
googleSymbolsList = []
yahooSymbolsList = []
wikiSymbolsList = []
# Récupère les DAO
dbReferenceSymbolDAO = DbReferenceSymbolsDA()
# Parcourt la liste des symbols de référence
for refSymbol in dbReferenceSymbolDAO.getAllSymbolsList(exchange):
# Récupère pour chaque symbol de référence le symbol de chaque source
# et l'append à sa liste s'il existe
if refSymbol.googleSymbol is not None:
googleSymbolsList.append(refSymbol.googleSymbol)
if refSymbol.yahooSymbol is not None:
yahooSymbolsList.append(refSymbol.yahooSymbol)
if refSymbol.wikiSymbol is not None:
wikiSymbolsList.append(refSymbol.wikiSymbol)
self.logger.info("Liste de symbols (Google, Yahoo, Wiki) assemblées")
self.logger.info("Début de la maj des raw data (Google, Yahoo Wiki) (threading)")
# Crée un thread par source et execute la fonction de maj
googleThread = ThreadUpdateRawData(self._updateGoogleRawData, googleSymbolsList, exchange)
yahooThread = ThreadUpdateRawData(self._updateYahooRawData, yahooSymbolsList, exchange)
wikiThread = ThreadUpdateRawData(self._updateWikiRawData, wikiSymbolsList, exchange)
googleThread.start()
yahooThread.start()
wikiThread.start()
# Il faut les join avant de quitter cette fonction pour s'assurer que tout le monde est là
googleThread.join()
yahooThread.join()
wikiThread.join()
self.logger.info("Google - fin de la maj des raw data")
self.logger.info("Yahoo - fin de la maj des raw data")
self.logger.info("Wiki - fin de la maj des raw data")
self.logger.info("Fin de la maj des raw data (Google, Yahoo Wiki) (threading)")
return
def _updateReferenceRawData(self, exchange):
'''
Updates the reference (aggregated) data table in the database.
:param exchange: name of the exchange
:type exchange: str
'''
# Récupère les DAO
dbReferenceSymbolDAO = DbReferenceSymbolsDA()
# Cette liste stocke les objets Db des symbols
refSymbolsList = []
self.logger.info("Début de la maj des raw data de reference (threading)")
# Construit la liste des symbols de référence à traiter
# Elle est construite après la maj des autres symbols car sinon
# les symbols de référence récupérés ne seront pas à jour.
for refSymbol in dbReferenceSymbolDAO.getAllSymbolsList(exchange):
if refSymbol.googleSymbol is not None or refSymbol.yahooSymbol is not None \
or refSymbol.wikiSymbol is not None :
refSymbolsList.append(refSymbol)
# Traite les reference raw data en les mettant dans un thread
# Ici le thread ne sert à rien sauf pour profiter de sa fonction de chunk
referenceThread = ThreadUpdateRawData(self._updateReferenceRawDataLists, refSymbolsList, exchange)
referenceThread.start()
referenceThread.join()
self.logger.info("Référence - fin de la maj des raw data")
return
def _updateGoogleRawData(self, dbSymbolsList, exchange):
'''
Updates the Google data table in the database.
:param dbSymbolsList: list of Google symbol objects
:param dbSymbolsList: list
:param exchange: name of the exchange
:type exchange: str
'''
self.logger.info("Google - début de la maj des raw data")
# Liste des objets raw data à update
toUpdateRawDataList = []
toMapSymbolNamesList = []
# Liste de symbols à problème
issuesSymbolsList = []
# Récupère les DAO
googleRawDataDAO = GoogleRawDataDA()
dbGoogleRawDataDAO = DbGoogleRawDataDA()
dbGoogleSymbolsDAO = DbGoogleSymbolsDA()
# Pour chaque symbol
for dbSymbol in dbSymbolsList:
self.logger.debug("GOOGLE : " + str(exchange) + "-" + dbSymbol.symbol.upper())
# Nom du symbol à demander chez Quandl
googleSymbolName = "_".join([dbSymbol.exchange.upper(), dbSymbol.symbol.upper()])
# Appelle la fonction de récupération des data
returnValue = self._returnQuandlRawDataDictAndNew(dbSymbol,
googleSymbolName,
googleRawDataDAO)
# Dans ce cas la data n'a pas été récupérée correctement.
# Tout a été loggé on peut passer au symbol d'après.
if returnValue is None:
issuesSymbolsList.append({'Symbol' : dbSymbol.symbol.upper(),
'Exchange' : dbSymbol.exchange.upper()})
continue
(isNew, rawDataDict) = returnValue
# Met ces données dans la liste de données à maj
toUpdateRawDataList.append(rawDataDict)
if isNew:
# Met le symbol dans la liste des symbols à mapper
toMapSymbolNamesList.append(dbSymbol.symbol.upper())
# Effectue toutes les maj en DB
dbGoogleRawDataDAO.updateOrAddRawDataList(toUpdateRawDataList, exchange)
# Effectue le mapping
dbGoogleSymbolsDAO.mapOneToOneRelations(toMapSymbolNamesList, exchange)
self.logger.warning("Google - symbols à problèmes : " + str(issuesSymbolsList))
return
def _updateYahooRawData(self, dbSymbolsList, exchange):
'''
Updates the Yahoo data table in the database.
:param dbSymbolsList: list of Yahoo symbol objects
:param dbSymbolsList: list
:param exchange: name of the exchange
:type exchange: str
'''
self.logger.info("Yahoo - début de la maj des raw data")
# Liste des objets raw data à update
toUpdateRawDataList = []
toMapSymbolNamesList = []
# Liste de symbols à problème
issuesSymbolsList = []
# Récupère les DAO
yahooRawDataDAO = YahooRawDataDA()
dbYahooRawDataDAO = DbYahooRawDataDA()
dbYahooSymbolsDAO = DbYahooSymbolsDA()
exchange = self._returnEffectiveExchange(exchange)['Yahoo']
# Pour chaque symbol
for dbSymbol in dbSymbolsList:
self.logger.debug("YAHOO : " + str(exchange) + "-" + dbSymbol.symbol.upper())
# Nom du symbol à demander chez Quandl
yahooSymbolName = dbSymbol.symbol.upper()
# Appelle la fonction de récupération des data
returnValue = self._returnQuandlRawDataDictAndNew(dbSymbol,
yahooSymbolName,
yahooRawDataDAO)
# Dans ce cas la data n'a pas été récupérée correctement.
# Tout a été loggé on peut passer au symbol d'après.
if returnValue is None:
issuesSymbolsList.append({'Symbol' : dbSymbol.symbol.upper(),
'Exchange' : dbSymbol.exchange.upper()})
continue
(isNew, rawDataDict) = returnValue
# Met ces données dans la liste de données à maj
toUpdateRawDataList.append(rawDataDict)
if isNew:
# Met le symbol dans la liste des symbols à mapper
toMapSymbolNamesList.append(dbSymbol.symbol.upper())
# Effectue toutes les maj en DB
dbYahooRawDataDAO.updateOrAddRawDataList(toUpdateRawDataList, exchange)
# Effectue le mapping
dbYahooSymbolsDAO.mapOneToOneRelations(toMapSymbolNamesList, exchange)
self.logger.warning("Yahoo - symbols à problèmes : " + str(issuesSymbolsList))
return
def _updateWikiRawData(self, dbSymbolsList, exchange):
'''
Updates the Wiki data table in the database.
:param dbSymbolsList: list of Wiki symbol objects
:param dbSymbolsList: list
:param exchange: name of the exchange
:type exchange: str
'''
self.logger.info("Wiki - début de la maj des raw data")
# Liste des objets raw data à update
toUpdateRawDataList = []
toMapSymbolNamesList = []
# Liste de symbols à problème
issuesSymbolsList = []
# Récupère les DAO
wikiRawDataDAO = WikiRawDataDA()
dbWikiRawDataDAO = DbWikiRawDataDA()
dbWikiSymbolsDAO = DbWikiSymbolsDA()
exchange = self._returnEffectiveExchange(exchange)['Wiki']
# Pour chaque symbol
for dbSymbol in dbSymbolsList:
self.logger.debug("WIKI : " + str(exchange) + "-" + dbSymbol.symbol.upper())
# Nom du symbol à demander chez Quandl
wikiSymbolName = dbSymbol.symbol.upper()
# Appelle la fonction de récupération des data
returnValue = self._returnQuandlRawDataDictAndNew(dbSymbol,
wikiSymbolName,
wikiRawDataDAO)
# Dans ce cas la data n'a pas été récupérée correctement.
# Tout a été loggé on peut passer au symbol d'après.
if returnValue is None:
issuesSymbolsList.append({'Symbol' : dbSymbol.symbol.upper(),
'Exchange' : dbSymbol.exchange.upper()})
continue
(isNew, rawDataDict) = returnValue
# Met ces données dans la liste de données à maj
toUpdateRawDataList.append(rawDataDict)
if isNew:
# Met le symbol dans la liste des symbols à mapper
toMapSymbolNamesList.append(dbSymbol.symbol.upper())
# Effectue toutes les maj en DB
dbWikiRawDataDAO.updateOrAddRawDataList(toUpdateRawDataList, exchange)
# Effectue le mapping
dbWikiSymbolsDAO.mapOneToOneRelations(toMapSymbolNamesList, exchange)
self.logger.warning("Wiki - symbols à problèmes : " + str(issuesSymbolsList))
return
@retryLogger(maxRetryNbr=3, sleepTimeIncr=10)
def _returnQuandlRawDataDictAndNew(self, dbSymbol, quandlSymbolName, rawDataDAO):
'''
Returns the rawData dict of the symbol fetched from Quandl. Indicates
also if the rawData is new to the database (1st time fetched).
:param dbSymbol: symbol object
:type dbSymbol: BaseSymbol
:param quandlSymbolName: name of the symbol to fetch from Quandl
:type quandlSymbolName: str
:param rawDataDAO: data access object to the Quandl database
:type rawDataDAO: QuandlRawDataDA
:returns: tuple with the raw data dict and a boolean indicating if the
data is new to the local database.
:rtype: tuple
'''
# Booléen pour savoir la data est nouvelle ou non
isNew = False
# Récupère les meta data
metaData = rawDataDAO.returnMetaData(quandlSymbolName)
# Initialisation du data frame (si on fait 2 updates sans update du côté
# de quandl il sera à None car aucune nouvelle date ne sera récupérée).
dataFrame = None
# Si le raw data du symbol n'existe pas
if dbSymbol.rawData is None:
# Récupère l'ensemble des données
dataFrame = rawDataDAO.returnDataFrame(quandlSymbolName,
metaData['oldest_available_date'],
metaData['newest_available_date'])
# Il s'agit d'une nouvelle data
isNew = True
else:
# Récupère les données
if metaData['oldest_available_date'] < dbSymbol.rawData.oldestDateAvailable:
# Effectue un maj complète
dataFrame = rawDataDAO.returnDataFrame(quandlSymbolName,
metaData['oldest_available_date'],
metaData['newest_available_date'])
elif dbSymbol.rawData.newestDateAvailable < metaData['newest_available_date']:
# Ne récupère que le bout qui manque
dataFrame = rawDataDAO.returnDataFrame(quandlSymbolName,
dbSymbol.rawData.newestDateAvailable ,
metaData['newest_available_date'])
# Forme le dict du symbol et des raw data
rawDataDict = {'symbol' : dbSymbol.symbol.upper(),
'metaData': metaData,
'dataFrame' : dataFrame}
return (isNew, rawDataDict)
def _updateReferenceRawDataLists(self, dbSymbolsList, exchange):
'''
Updates the reference (aggregated) data table in the database.
:param dbSymbolsList: list of reference symbol objects
:param dbSymbolsList: list
:param exchange: name of the exchange
:type exchange: str
'''
self.logger.info("Référence - début de la maj des raw data")
# Liste des objets raw data à update
toUpdateRawDataList = []
toMapSymbolNamesList = []
# Liste de symbols à problème
issuesSymbolsList = []
# Récupère les DAO des symbols de référence
dbReferenceSymbolDAO = DbReferenceSymbolsDA()
referenceRawDataDAO = ReferenceRawDataDA()
dbReferenceRawDataDAO = DbReferenceRawDataDA()
# Parcourt la liste des symbols de référence
for refSymbol in dbSymbolsList:
self.logger.debug("REFERENCE : " + str(exchange) + "-" + refSymbol.symbol.upper())
try:
# Récupère les meta data
metaData = referenceRawDataDAO.returnMetaData(refSymbol)
# Initilise le dataFrame
dataFrame = None
# Initialise le raw data du symbol s'il n'existe pas
if refSymbol.rawData is None:
# Récupère l'ensemble des données
dataFrame = referenceRawDataDAO.returnDataFrame(refSymbol,
metaData['oldest_available_date'],
metaData['newest_available_date'])
# Met le symbol dans la liste des symbols à mapper
toMapSymbolNamesList.append(refSymbol.symbol.upper())
else:
# Récupère les données
if metaData['oldest_available_date'] < refSymbol.rawData.oldestDateAvailable:
# Effectue un maj complète
dataFrame = referenceRawDataDAO.returnDataFrame(refSymbol,
metaData['oldest_available_date'],
metaData['newest_available_date'])
elif refSymbol.rawData.sourceNewestConsolidatedDate < metaData['newest_available_date']:
# Ne récupère que le bout qui manque
dataFrame = referenceRawDataDAO.returnDataFrame(refSymbol,
refSymbol.rawData.sourceNewestConsolidatedDate ,
metaData['newest_available_date'])
# Met ces données dans la liste de données à maj
rawDataDict = {'symbol' : refSymbol.symbol.upper(),
'metaData': metaData,
'dataFrame' : dataFrame}
toUpdateRawDataList.append(rawDataDict)
except Exception as e:
# Dans ce cas il y a eu un problème avec ce symbol,
# on l'ajoute à la liste des symbols à problème
self.logger.error('Erreur', exc_info=True)
issuesSymbolsList.append({'Symbol' : refSymbol.symbol.upper(),
'Exchange' : refSymbol.exchange.upper()})
# Effectue la maj de la db
dbReferenceRawDataDAO.updateOrAddRawDataList(toUpdateRawDataList, exchange)
# Effectuer le mapping
dbReferenceSymbolDAO.mapOneToOneRelationsRawData(toMapSymbolNamesList, exchange)
self.logger.warning("Référence - symbols à problèmes : " + str(issuesSymbolsList))
return
# ---------------- Méthodes utilitaires -----------------------
def _returnEffectiveExchange(self, exchange):
'''
Returns a dcit with the effective exchange name for each source.
:param exchange: name of the exchange
:type exchange: str
:returns: dict of effective name ordered by source
:rtype: dict
.. note::
Dict attribute access:
>>> exchangeDict['Google']
>>> exchangeDict['Yahoo']
>>> exchangeDict['Wiki']
'''
exchangeDict = {}
exchangeDict['Google'] = exchange.upper()
if exchange.upper() in ('NYSE', 'NASDAQ'):
exchangeDict['Yahoo'] = 'OTHER'
exchangeDict['Wiki'] = 'OTHER'
return exchangeDict
| aberdah/Stockvider | stockvider/stockviderApp/dbManager.py | Python | mit | 33,602 |
var AIO = require('../../index');
// create an instance
aio = AIO(process.env.AIO_KEY || 'xxxxxxxxxxxx');
// get a list of all groups
aio.groups(function(err, data) {
if(err) {
return console.error(err);
}
// log data array
console.log(data);
});
// get a specific group by name
aio.groups('Test', function(err, data) {
if(err) {
return console.error(err);
}
// log data object
console.log(data);
});
| bbx10/io-client-node | examples/groups/read.js | JavaScript | mit | 435 |
'use strict';
// Configuring the Workouts module
angular.module('workouts').run(['Menus',
function(Menus) {
// Add the workouts dropdown item
Menus.addMenuItem('topbar', {
title: 'Workouts',
state: 'workouts',
type: 'dropdown',
position: 0
});
// Add the dropdown list item
Menus.addSubMenuItem('topbar', 'workouts', {
title: 'List Workouts',
state: 'workouts.list'
});
// Add the dropdown create item
Menus.addSubMenuItem('topbar', 'workouts', {
title: 'Create Workouts',
state: 'workouts.create'
});
}
]);
| grantgeorge/mean | modules/workouts/client/config/workouts.client.config.js | JavaScript | mit | 599 |
package net.jackw.authenticator;
public class Totp extends HotpGenerator {
private int interval = 30;
private String cachedCode;
private long cachedSeed = 0;
private static final int DEFAULT_INTERVAL = 30;
public Totp (byte[] secret) {
super(secret);
this.interval = DEFAULT_INTERVAL;
}
public Totp (byte[] secret, HashAlgorithm hashAlgorithm, int length, int interval) {
super(secret, hashAlgorithm, length);
if (interval < 10 || interval > 180) {
throw new IllegalArgumentException("Interval must be between 10 and 180 seconds");
}
this.interval = interval;
}
public Totp (String extra) throws CodeGeneratorConstructionException {
super(extra);
try {
this.interval = Integer.parseInt(extra.split(",")[3]);
} catch (ArrayIndexOutOfBoundsException | NumberFormatException e) {
throw new CodeGeneratorConstructionException("Extra string was invalid", e);
}
}
@Override
public String generateCode() {
// Convert the time in milliseconds to the number of 30s intervals since the epoch
long seed = TimeProvider.getInstance().now() / (interval * 1000);
return generateHotp(seed);
}
@Override
public String getExtra () {
String result = super.getExtra();
result += "," + Long.toString(interval);
return result;
}
@Override
public Type getType () {
return Type.TOTP;
}
@Override
public String getCodeForDisplay () {
// Check if the code needs regenerating
if (cachedSeed != TimeProvider.getInstance().now() / (interval * 1000)) {
cachedCode = generateCode();
cachedSeed = TimeProvider.getInstance().now() / (interval * 1000);
}
return cachedCode;
}
public float getTimeRemainingFraction () {
return (TimeProvider.getInstance().now() % (interval * 1000)) / (interval * 1000.0f);
}
public void setInterval (int interval) {
this.interval = interval;
}
}
| jackwickham/authenticator | app/src/main/java/net/jackw/authenticator/Totp.java | Java | mit | 1,847 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="lv_LV" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Faucetcoin</source>
<translation>Par Faucetcoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>Faucetcoin</b> version</source>
<translation><b>Faucetcoin</b> versija</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING 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 type="unfinished"/>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The Faucetcoin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adrešu grāmata</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Adresi vai nosaukumu rediģē ar dubultklikšķi</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Izveidot jaunu adresi</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopēt iezīmēto adresi uz starpliktuvi</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Jauna adrese</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Faucetcoin 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 type="unfinished"/>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Kopēt adresi</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Parādīt &QR kodu</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Faucetcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Faucetcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Dzēst</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Faucetcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Kopēt &Nosaukumu</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Rediģēt</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Eksportēt adreses</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Fails ar komatu kā atdalītāju (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Kļūda eksportējot</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Nevar ierakstīt failā %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Nosaukums</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adrese</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(bez nosaukuma)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Paroles dialogs</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Ierakstiet paroli</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Jauna parole</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Jaunā parole vēlreiz</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>Ierakstiet maciņa jauno paroli.<br/>Lūdzu izmantojiet <b>10 vai vairāk nejauši izvēlētas zīmes</b>, vai <b>astoņus un vairāk vārdus</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Šifrēt maciņu</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Lai veikto šo darbību, maciņš jāatslēdz ar paroli.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Atslēgt maciņu</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Šai darbībai maciņš jāatšifrē ar maciņa paroli.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Atšifrēt maciņu</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Mainīt paroli</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Ierakstiet maciņa veco un jauno paroli.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Apstiprināt maciņa šifrēšanu</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR LITECOINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Maciņš nošifrēts</translation>
</message>
<message>
<location line="-56"/>
<source>Faucetcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your faucetcoins from being stolen by malware infecting your computer.</source>
<translation>Faucetcoin aizvērsies, lai pabeigtu šifrēšanu. Atcerieties, ka maciņa šifrēšana nevar pilnībā novērst bitkoinu zādzību, ko veic datorā ieviesušās kaitīgas programmas.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Maciņa šifrēšana neizdevās</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Maciņa šifrēšana neizdevās programmas kļūdas dēļ. Jūsu maciņš netika šifrēts.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Ievadītās paroles nav vienādas.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Maciņu atšifrēt neizdevās</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Maciņa atšifrēšanai ievadītā parole nav pareiza.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Maciņu neizdevās atšifrēt</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Parakstīt &ziņojumu...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Sinhronizācija ar tīklu...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Pārskats</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Rādīt vispārēju maciņa pārskatu</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transakcijas</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Skatīt transakciju vēsturi</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Rediģēt saglabātās adreses un nosaukumus</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Rādīt maksājumu saņemšanas adreses</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Iziet</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Aizvērt programmu</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Faucetcoin</source>
<translation>Parādīt informāciju par Faucetcoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Par &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Parādīt informāciju par Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Iespējas</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>Š&ifrēt maciņu...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Izveidot maciņa rezerves kopiju</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Mainīt paroli</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Faucetcoin address</source>
<translation>Nosūtīt bitkoinus uz Faucetcoin adresi</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Faucetcoin</source>
<translation>Mainīt Faucetcoin konfigurācijas uzstādījumus</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Izveidot maciņa rezerves kopiju citur</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Mainīt maciņa šifrēšanas paroli</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Debug logs</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Atvērt atkļūdošanas un diagnostikas konsoli</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Pārbaudīt ziņojumu...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Faucetcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Maciņš</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About Faucetcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Faucetcoin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Faucetcoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Fails</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Uzstādījumi</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Palīdzība</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Ciļņu rīkjosla</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>Faucetcoin client</source>
<translation>Faucetcoin klients</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Faucetcoin network</source>
<translation><numerusform>%n aktīvu savienojumu ar Faucetcoin tīklu</numerusform><numerusform>%n aktīvs savienojums ar Faucetcoin tīklu</numerusform><numerusform>%n aktīvu savienojumu as Faucetcoin tīklu</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Kļūda</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Brīdinājums</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<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 type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Sinhronizēts</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Sinhronizējos...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Apstiprināt transakcijas maksu</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Transakcija nosūtīta</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Ienākoša transakcija</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Datums: %1
Daudzums: %2
Tips: %3
Adrese: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Faucetcoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Maciņš ir <b>šifrēts</b> un pašlaik <b>atslēgts</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Maciņš ir <b>šifrēts</b> un pašlaik <b>slēgts</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Faucetcoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Tīkla brīdinājums</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Mainīt adrese</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Nosaukums</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Adrešu grāmatas ieraksta nosaukums</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adrese</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Adrese adrešu grāmatas ierakstā. To var mainīt tikai nosūtīšanas adresēm.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Jauna saņemšanas adrese</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Jauna nosūtīšanas adrese</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Mainīt saņemšanas adresi</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Mainīt nosūtīšanas adresi</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Nupat ierakstītā adrese "%1" jau atrodas adrešu grāmatā.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Faucetcoin address.</source>
<translation>Ierakstītā adrese "%1" nav derīga Faucetcoin adrese.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Nav iespējams atslēgt maciņu.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Neizdevās ģenerēt jaunu atslēgu.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Faucetcoin-Qt</source>
<translation>Faucetcoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versija</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Lietojums:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>komandrindas izvēles</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Lietotāja interfeisa izvēlnes</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Uzstādiet valodu, piemēram "de_DE" (pēc noklusēšanas: sistēmas lokāle)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Sākt minimizētu</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Uzsākot, parādīt programmas informācijas logu (pēc noklusēšanas: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Iespējas</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Galvenais</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>&Maksāt par transakciju</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Faucetcoin after logging in to the system.</source>
<translation>Automātiski sākt Faucetcoin pēc pieteikšanās sistēmā.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Faucetcoin on system login</source>
<translation>&Sākt Faucetcoin reizē ar sistēmu</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Tīkls</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Faucetcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Uz rūtera automātiski atvērt Faucetcoin klienta portu. Tas strādā tikai tad, ja rūteris atbalsta UPnP un tas ir ieslēgts.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Kartēt portu, izmantojot &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Faucetcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Savienoties caur SOCKS proxy:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Proxy &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>proxy IP adrese (piem. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Ports:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Proxy ports (piem. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &Versija:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>proxy SOCKS versija (piem. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Logs</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Pēc loga minimizācijas rādīt tikai ikonu sistēmas teknē.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimizēt uz sistēmas tekni, nevis rīkjoslu</translation>
</message>
<message>
<location line="+7"/>
<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>Logu aizverot, minimizēt, nevis beigt darbu. Kad šī izvēlne iespējota, programma aizvērsies tikai pēc Beigt komandas izvēlnē.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimizēt aizverot</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Izskats</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Lietotāja interfeiss un &valoda:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Faucetcoin.</source>
<translation>Šeit var iestatīt lietotāja valodu. Iestatījums aktivizēsies pēc Faucetcoin pārstartēšanas.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Vienības, kurās attēlot daudzumus:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Izvēlēties dalījuma vienību pēc noklusēšanas, ko izmantot interfeisā un nosūtot bitkoinus.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Faucetcoin addresses in the transaction list or not.</source>
<translation>Rādīt vai nē Faucetcoin adreses transakciju sarakstā.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Attēlot adreses transakciju sarakstā</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Atcelt</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Pielietot</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>pēc noklusēšanas</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Brīdinājums</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Faucetcoin.</source>
<translation>Iestatījums aktivizēsies pēc Bitkoin pārstartēšanas.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Norādītā proxy adrese nav derīga.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Forma</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Faucetcoin network after a connection is established, but this process has not completed yet.</source>
<translation>Attēlotā informācija var būt novecojusi. Jūsu maciņš pēc savienojuma izveides automātiski sinhronizējas ar Faucetcoin tīklu, taču šis process vēl nav beidzies.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Bilance:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Neapstiprinātas:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Maciņš</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Pēdējās transakcijas</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Jūsu tekošā bilance</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Kopējā apstiprināmo transakciju vērtība, vēl nav ieskaitīta kopējā bilancē</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>nav sinhronizēts</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start faucetcoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR koda dialogs</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Pieprasīt maksājumu</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Daudzums:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Nosaukums:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Ziņojums:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Saglabāt kā...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Kļūda kodējot URI QR kodā.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Rezultāta URI pārāk garš, mēģiniet saīsināt nosaukumu vai ziņojumu. </translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Saglabāt QR kodu</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG attēli (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Klienta vārds</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>N/A</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Klienta versija</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informācija</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Sākuma laiks</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Tīkls</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Savienojumu skaits</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Testa tīklā</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Bloku virkne</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Pašreizējais bloku skaits</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Bloku skaita novērtējums</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Pēdējā bloka laiks</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Atvērt</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the Faucetcoin-Qt help message to get a list with possible Faucetcoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsole</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Kompilācijas datums</translation>
</message>
<message>
<location line="-104"/>
<source>Faucetcoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Faucetcoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the Faucetcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Notīrīt konsoli</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Faucetcoin RPC console.</source>
<translation>Laipni lūgti Faucetcoin RPC konsolē.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Izmantojiet bultiņas uz augšu un leju, lai pārvietotos pa vēsturi, un <b>Ctrl-L</b> ekrāna notīrīšanai.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Ierakstiet <b>help</b> lai iegūtu pieejamo komandu sarakstu.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Sūtīt bitkoinus</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Sūtīt vairākiem saņēmējiem uzreiz</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Dzēst visus transakcijas laukus</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>&Notīrīt visu</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Bilance:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123,456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Apstiprināt nosūtīšanu</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> līdz %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Apstiprināt bitkoinu sūtīšanu</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Vai tiešām vēlaties nosūtīt %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>un</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Nosūtāmajai summai jābūt lielākai par 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Daudzums pārsniedz pieejamo.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Kopsumma pārsniedz pieejamo, ja pieskaitīta %1 transakcijas maksa.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Atrastas divas vienādas adreses, vienā nosūtīšanas reizē uz katru adresi var sūtīt tikai vienreiz.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<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>Kļūda: transakcija tika atteikta. Tā var gadīties, ja kāds no maciņā esošiem bitkoiniem jau iztērēts, piemēram, izmantojot wallet.dat kopiju, kurā nav atzīmēti iztērētie bitkoini.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Forma</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Apjo&ms</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>&Saņēmējs:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Lai pievienotu adresi adrešu grāmatai, tai jādod nosaukums</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Nosaukums:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Izvēlēties adresi no adrešu grāmatas</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>ielīmēt adresi no starpliktuves</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Dzēst šo saņēmēju</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Faucetcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Ierakstiet Faucetcoin adresi (piem. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<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 type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>ielīmēt adresi no starpliktuves</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Faucetcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>&Notīrīt visu</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Faucetcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Faucetcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Ierakstiet Faucetcoin adresi (piem. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter Faucetcoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Faucetcoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Atvērts līdz %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/neapstiprinātas</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 apstiprinājumu</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Datums</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 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, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Daudzums</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, vēl nav veiksmīgi izziņots</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>nav zināms</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Transakcijas detaļas</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Šis panelis parāda transakcijas detaļas</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Datums</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tips</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adrese</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Daudzums</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Atvērts līdz %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Nav pieslēgts (%1 apstiprinājumu)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Nav apstiprināts (%1 no %2 apstiprinājumu)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Apstiprināts (%1 apstiprinājumu)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Neviens cits mezgls šo bloku nav saņēmis un droši vien netiks akceptēts!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Ģenerēts, taču nav akceptēts</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Saņemts ar</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Saņemts no</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Nosūtīts</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Maksājums sev</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Atrasts</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(nav pieejams)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transakcijas statuss. Turiet peli virs šī lauka, lai redzētu apstiprinājumu skaitu.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Transakcijas saņemšanas datums un laiks.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Transakcijas tips.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Transakcijas mērķa adrese.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Bilancei pievienotais vai atņemtais daudzums.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Visi</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Šodien</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Šonedēļ</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Šomēnes</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Pēdējais mēnesis</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Šogad</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Diapazons...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Saņemts ar</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Nosūtīts</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Sev</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Atrasts</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Cits</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Ierakstiet meklējamo nosaukumu vai adresi</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Minimālais daudzums</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopēt adresi</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopēt nosaukumu</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopēt daudzumu</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Mainīt nosaukumu</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Rādīt transakcijas detaļas</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Eksportēt transakcijas datus</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Fails ar komatu kā atdalītāju (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Apstiprināts</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Datums</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tips</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Nosaukums</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adrese</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Daudzums</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Eksportēšanas kļūda</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Nevar ierakstīt failā %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Diapazons:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Izveidot maciņa rezerves kopiju</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Maciņa dati (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Rezerves kopēšana neizdevās</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Kļūda, saglabājot maciņu jaunajā vietā.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Faucetcoin version</source>
<translation>Faucetcoin versija</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Lietojums:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or faucetcoind</source>
<translation>Nosūtīt komantu uz -server vai faucetcoind</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Komandu saraksts</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Palīdzība par komandu</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Iespējas:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: faucetcoin.conf)</source>
<translation>Norādiet konfigurācijas failu (pēc noklusēšanas: faucetcoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: faucetcoind.pid)</source>
<translation>Norādiet pid failu (pēc noklusēšanas: faucetcoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Norādiet datu direktoriju</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Uzstādiet datu bāzes bufera izmēru megabaitos (pēc noklusēšanas: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9949 or testnet: 39938)</source>
<translation>Gaidīt savienojumus portā <port> (pēc noklusēšanas: 9949 vai testnet: 39938)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Uzturēt līdz <n> savienojumiem ar citiem mezgliem(pēc noklusēšanas: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Pievienoties mezglam, lai iegūtu citu mezglu adreses, un atvienoties</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Norādiet savu publisko adresi</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Slieksnis pārkāpējmezglu atvienošanai (pēc noklusēšanas: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Sekundes, cik ilgi atturēt pārkāpējmezglus no atkārtotas pievienošanās (pēc noklusēšanas: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9939 or testnet: 39939)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Pieņemt komandrindas un JSON-RPC komandas</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Darbināt fonā kā servisu un pieņemt komandas</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Izmantot testa tīklu</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=faucetcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Faucetcoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Faucetcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<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>
<message>
<location line="+4"/>
<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 line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<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 line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Faucetcoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Debug izvadei sākumā pievienot laika zīmogu</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Faucetcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Debug/trace informāciju izvadīt konsolē, nevis debug.log failā</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Debug/trace informāciju izvadīt debug programmai</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>JSON-RPC savienojumu lietotājvārds</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Brīdinājums</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>JSON-RPC savienojumu parole</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Atļaut JSON-RPC savienojumus no norādītās IP adreses</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Nosūtīt komandas mezglam, kas darbojas adresē <ip> (pēc noklusēšanas: 127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Izpildīt komandu, kad labāk atbilstošais bloks izmainās (%s cmd aizvieto ar bloka hešu)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Atjaunot maciņa formātu uz jaunāko</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Uzstādīt atslēgu bufera izmēru uz <n> (pēc noklusēšanas: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Atkārtoti skanēt bloku virkni, meklējot trūkstošās maciņa transakcijas</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>JSON-RPC savienojumiem izmantot OpenSSL (https)</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Servera sertifikāta fails (pēc noklusēšanas: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Servera privātā atslēga (pēc noklusēšanas: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Pieņemamie šifri (pēc noklusēšanas: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Šis palīdzības paziņojums</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Nevar pievienoties pie %s šajā datorā (pievienošanās atgrieza kļūdu %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Savienoties caurs socks proxy</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Atļaut DNS uzmeklēšanu priekš -addnode, -seednode un -connect</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Ielādē adreses...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Nevar ielādēt wallet.dat: maciņš bojāts</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Faucetcoin</source>
<translation>Nevar ielādēt wallet.dat: maciņa atvēršanai nepieciešama jaunāka Faucetcoin versija</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Faucetcoin to complete</source>
<translation>Bija nepieciešams pārstartēt maciņu: pabeigšanai pārstartējiet Faucetcoin</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Kļūda ielādējot wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Nederīga -proxy adrese: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>-onlynet komandā norādīts nepazīstams tīkls: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Pieprasīta nezināma -socks proxy versija: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Nevar uzmeklēt -bind adresi: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Nevar atrisināt -externalip adresi: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Nederīgs daudzums priekš -paytxfree=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Nederīgs daudzums</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Nepietiek bitkoinu</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Ielādē bloku indeksu...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Pievienot mezglu, kam pievienoties un turēt savienojumu atvērtu</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Faucetcoin is probably already running.</source>
<translation>Nevar pievienoties %s uz šī datora. Faucetcoin droši vien jau darbojas.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Maksa par KB, ko pievienot nosūtāmajām transakcijām</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Ielādē maciņu...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Nevar maciņa formātu padarīt vecāku</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Nevar ierakstīt adresi pēc noklusēšanas</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Skanēju no jauna...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Ielāde pabeigta</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Izmantot opciju %s</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Kļūda</translation>
</message>
<message>
<location line="-31"/>
<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>Konfigurācijas failā jāuzstāda rpcpassword=<password>:
%s
Ja fails neeksistē, izveidojiet to ar atļauju lasīšanai tikai īpašniekam.</translation>
</message>
</context>
</TS> | Faucetcoin/faucetcoin | src/qt/locale/bitcoin_lv_LV.ts | TypeScript | mit | 106,457 |
package main
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
oauth "github.com/akrennmair/goauth"
goconf "github.com/akrennmair/goconf"
"io/ioutil"
"log"
"net/http"
"strconv"
"strings"
"time"
)
type Timeline struct {
Tweets []*Tweet
}
type UserList struct {
Users []TwitterUser
}
type UserIdList struct {
Ids []int64
}
type Tweet struct {
Favorited *bool
In_reply_to_status_id *int64
Retweet_count interface{}
In_reply_to_screen_name *string
Place *PlaceDesc
Truncated *bool
User *TwitterUser
Retweeted *bool
In_reply_to_status_id_str *string
In_reply_to_user_id_str *string
In_reply_to_user_id *int64
Source *string
Id *int64
Id_str *string
//Coordinates *TODO
Text *string
Created_at *string
}
type TwitterUser struct {
Protected *bool
Listed_count int
Name *string
Verified *bool
Lang *string
Time_zone *string
Description *string
Location *string
Statuses_count int
Url *string
Screen_name *string
Follow_request_sent *bool
Following *bool
Friends_count *int64
Favourites_count *int64
Followers_count *int64
Id *int64
Id_str *string
}
type PlaceDesc struct {
Name *string
Full_name *string
Url *string
Country_code *string
}
type TwitterEvent struct {
Delete *WhatEvent
}
type WhatEvent struct {
Status *EventDetail
}
type EventDetail struct {
Id *int64
Id_str *string
User_id *int64
User_id_str *string
}
type Configuration struct {
Characters_reserved_per_media *int64
Max_media_per_upload *int64
Short_url_length_https *int64
Short_url_length *int64
}
const (
request_token_url = "https://api.twitter.com/oauth/request_token"
access_token_url = "https://api.twitter.com/oauth/access_token"
authorization_url = "https://api.twitter.com/oauth/authorize"
INITIAL_NETWORK_WAIT time.Duration = 250e6 // 250 milliseconds
INITIAL_HTTP_WAIT time.Duration = 10e9 // 10 seconds
MAX_NETWORK_WAIT time.Duration = 16e9 // 16 seconds
MAX_HTTP_WAIT time.Duration = 240e9 // 240 seconds
)
type TwitterAPI struct {
authcon *oauth.OAuthConsumer
config *goconf.ConfigFile
access_token *oauth.AccessToken
request_token *oauth.RequestToken
ratelimit_rem uint
ratelimit_limit uint
ratelimit_reset int64
}
func NewTwitterAPI(consumer_key, consumer_secret string, cfg *goconf.ConfigFile) *TwitterAPI {
tapi := &TwitterAPI{
authcon: &oauth.OAuthConsumer{
Service: "twitter",
RequestTokenURL: request_token_url,
AccessTokenURL: access_token_url,
AuthorizationURL: authorization_url,
ConsumerKey: consumer_key,
ConsumerSecret: consumer_secret,
UserAgent: PROGRAM_NAME + "/" + PROGRAM_VERSION + " (" + PROGRAM_URL + ")",
Timeout: 60e9, // 60 second default timeout
CallBackURL: "oob",
},
config: cfg,
}
if tapi.config != nil {
if timeout, err := tapi.config.GetInt("default", "http_timeout"); err == nil && timeout > 0 {
tapi.authcon.Timeout = int64(timeout) * 1e9
}
}
return tapi
}
func (tapi *TwitterAPI) GetRequestAuthorizationURL() (string, error) {
s, rt, err := tapi.authcon.GetRequestAuthorizationURL()
tapi.request_token = rt
return s, err
}
func (tapi *TwitterAPI) GetRateLimit() (remaining uint, limit uint, reset int64) {
curtime := time.Now().Unix()
return tapi.ratelimit_rem, tapi.ratelimit_limit, tapi.ratelimit_reset - curtime
}
func (tapi *TwitterAPI) SetPIN(pin string) {
tapi.access_token = tapi.authcon.GetAccessToken(tapi.request_token.Token, pin)
}
func (tapi *TwitterAPI) SetAccessToken(at *oauth.AccessToken) {
tapi.access_token = at
}
func (tapi *TwitterAPI) GetAccessToken() *oauth.AccessToken {
return tapi.access_token
}
func (tapi *TwitterAPI) HomeTimeline(count uint, since_id int64) (*Timeline, error) {
return tapi.get_timeline("home_timeline",
func() *oauth.Pair {
if count != 0 {
return &oauth.Pair{"count", strconv.FormatUint(uint64(count), 10)}
}
return nil
}(),
func() *oauth.Pair {
if since_id != 0 {
return &oauth.Pair{"since_id", strconv.FormatInt(since_id, 10)}
}
return nil
}())
}
func (tapi *TwitterAPI) Mentions(count uint, since_id int64) (*Timeline, error) {
return tapi.get_timeline("mentions",
func() *oauth.Pair {
if count != 0 {
return &oauth.Pair{"count", strconv.FormatUint(uint64(count), 10)}
}
return nil
}(),
func() *oauth.Pair {
if since_id != 0 {
return &oauth.Pair{"since_id", strconv.FormatInt(since_id, 10)}
}
return nil
}())
}
func (tapi *TwitterAPI) PublicTimeline(count uint, since_id int64) (*Timeline, error) {
return tapi.get_timeline("public_timeline",
func() *oauth.Pair {
if count != 0 {
return &oauth.Pair{"count", strconv.FormatUint(uint64(count), 10)}
}
return nil
}(),
func() *oauth.Pair {
if since_id != 0 {
return &oauth.Pair{"since_id", strconv.FormatInt(since_id, 10)}
}
return nil
}())
}
func (tapi *TwitterAPI) RetweetedByMe(count uint, since_id int64) (*Timeline, error) {
return tapi.get_timeline("retweeted_by_me",
func() *oauth.Pair {
if count != 0 {
return &oauth.Pair{"count", strconv.FormatUint(uint64(count), 10)}
}
return nil
}(),
func() *oauth.Pair {
if since_id != 0 {
return &oauth.Pair{"since_id", strconv.FormatInt(since_id, 10)}
}
return nil
}())
}
func (tapi *TwitterAPI) RetweetedToMe(count uint, since_id int64) (*Timeline, error) {
return tapi.get_timeline("retweeted_to_me",
func() *oauth.Pair {
if count != 0 {
return &oauth.Pair{"count", strconv.FormatUint(uint64(count), 10)}
}
return nil
}(),
func() *oauth.Pair {
if since_id != 0 {
return &oauth.Pair{"since_id", strconv.FormatInt(since_id, 10)}
}
return nil
}())
}
func (tapi *TwitterAPI) RetweetsOfMe(count uint, since_id int64) (*Timeline, error) {
return tapi.get_timeline("retweets_of_me",
func() *oauth.Pair {
if count != 0 {
return &oauth.Pair{"count", strconv.FormatUint(uint64(count), 10)}
}
return nil
}(),
func() *oauth.Pair {
if since_id != 0 {
return &oauth.Pair{"since_id", strconv.FormatInt(since_id, 10)}
}
return nil
}())
}
func (tapi *TwitterAPI) UserTimeline(screen_name string, count uint, since_id int64) (*Timeline, error) {
return tapi.get_timeline("user_timeline",
func() *oauth.Pair {
if count != 0 {
return &oauth.Pair{"count", strconv.FormatUint(uint64(count), 10)}
}
return nil
}(),
func() *oauth.Pair {
if since_id != 0 {
return &oauth.Pair{"since_id", strconv.FormatInt(since_id, 10)}
}
return nil
}(),
func() *oauth.Pair {
if screen_name != "" {
return &oauth.Pair{"screen_name", screen_name}
}
return nil
}())
}
func (tapi *TwitterAPI) RetweetedToUser(screen_name string, count uint, since_id int64) (*Timeline, error) {
return tapi.get_timeline("retweeted_to_user",
func() *oauth.Pair {
if count != 0 {
return &oauth.Pair{"count", strconv.FormatUint(uint64(count), 10)}
}
return nil
}(),
func() *oauth.Pair {
if since_id != 0 {
return &oauth.Pair{"since_id", strconv.FormatInt(since_id, 10)}
}
return nil
}(),
func() *oauth.Pair {
if screen_name != "" {
return &oauth.Pair{"screen_name", screen_name}
}
return nil
}())
}
func (tapi *TwitterAPI) RetweetedByUser(screen_name string, count uint, since_id int64) (*Timeline, error) {
return tapi.get_timeline("retweeted_by_user",
func() *oauth.Pair {
if count != 0 {
return &oauth.Pair{"count", strconv.FormatUint(uint64(count), 10)}
}
return nil
}(),
func() *oauth.Pair {
if since_id != 0 {
return &oauth.Pair{"since_id", strconv.FormatInt(since_id, 10)}
}
return nil
}(),
func() *oauth.Pair {
if screen_name != "" {
return &oauth.Pair{"screen_name", screen_name}
}
return nil
}())
}
func (tapi *TwitterAPI) RetweetedBy(tweet_id int64, count uint) (*UserList, error) {
jsondata, err := tapi.get_statuses(strconv.FormatInt(tweet_id, 10)+"/retweeted_by",
func() *oauth.Pair {
if count != 0 {
return &oauth.Pair{"count", strconv.FormatUint(uint64(count), 10)}
}
return nil
}())
if err != nil {
return nil, err
}
ul := &UserList{}
if jsonerr := json.Unmarshal(jsondata, &ul.Users); jsonerr != nil {
return nil, jsonerr
}
return ul, nil
}
func (tapi *TwitterAPI) RetweetedByIds(tweet_id int64, count uint) (*UserIdList, error) {
jsondata, err := tapi.get_statuses(strconv.FormatInt(tweet_id, 10)+"/retweeted_by/ids",
func() *oauth.Pair {
if count != 0 {
return &oauth.Pair{"count", strconv.FormatUint(uint64(count), 10)}
}
return nil
}())
if err != nil {
return nil, err
}
uidl := &UserIdList{}
if jsonerr := json.Unmarshal(jsondata, &uidl.Ids); jsonerr != nil {
return nil, jsonerr
}
return uidl, nil
}
func (tapi *TwitterAPI) Update(tweet Tweet) (*Tweet, error) {
params := oauth.Params{
&oauth.Pair{
Key: "status",
Value: *tweet.Text,
},
}
if tweet.In_reply_to_status_id != nil && *tweet.In_reply_to_status_id != int64(0) {
params = append(params, &oauth.Pair{"in_reply_to_status_id", strconv.FormatInt(*tweet.In_reply_to_status_id, 10)})
}
resp, err := tapi.authcon.Post("https://api.twitter.com/1.1/statuses/update.json", params, tapi.access_token)
if err != nil {
return nil, err
}
tapi.UpdateRatelimit(resp.Header)
if resp.StatusCode == 403 {
return nil, errors.New(resp.Status)
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
newtweet := &Tweet{}
if jsonerr := json.Unmarshal(data, newtweet); jsonerr != nil {
return nil, jsonerr
}
return newtweet, nil
}
func (tapi *TwitterAPI) Retweet(tweet Tweet) (*Tweet, error) {
resp, err := tapi.authcon.Post(fmt.Sprintf("https://api.twitter.com/1.1/statuses/retweet/%d.json", *tweet.Id), oauth.Params{}, tapi.access_token)
if err != nil {
return nil, err
}
tapi.UpdateRatelimit(resp.Header)
if resp.StatusCode == 403 {
return nil, errors.New(resp.Status)
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
newtweet := &Tweet{}
if jsonerr := json.Unmarshal(data, newtweet); jsonerr != nil {
return nil, jsonerr
}
return newtweet, nil
}
func (tapi *TwitterAPI) Favorite(tweet Tweet) error {
resp, err := tapi.authcon.Post(fmt.Sprintf("https://api.twitter.com/1.1/favorites/create/%d.json", *tweet.Id), oauth.Params{}, tapi.access_token)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return errors.New(resp.Status)
}
return nil
}
func (tapi *TwitterAPI) Follow(screen_name string) error {
params := oauth.Params{
&oauth.Pair{
Key: "screen_name",
Value: screen_name,
},
}
resp, err := tapi.authcon.Post("https://api.twitter.com/1.1/friendships/create.json", params, tapi.access_token)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return errors.New(resp.Status)
}
return nil
}
func (tapi *TwitterAPI) Unfollow(user TwitterUser) error {
params := oauth.Params{
&oauth.Pair{
Key: "user_id",
Value: *user.Id_str,
},
&oauth.Pair{
Key: "screen_name",
Value: *user.Screen_name,
},
}
resp, err := tapi.authcon.Post("https://api.twitter.com/1.1/friendships/destroy.json", params, tapi.access_token)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return errors.New(resp.Status)
}
return nil
}
func (tapi *TwitterAPI) DestroyTweet(tweet Tweet) error {
resp, err := tapi.authcon.Post(fmt.Sprintf("https://api.twitter.com/1.1/statuses/destroy/%d.json", *tweet.Id), oauth.Params{}, tapi.access_token)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return errors.New(resp.Status)
}
return nil
}
func (tapi *TwitterAPI) Configuration() (*Configuration, error) {
params := oauth.Params{}
resp, err := tapi.authcon.Get("https://api.twitter.com/1.1/help/configuration.json", params, tapi.access_token)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, errors.New(resp.Status)
}
jsondata, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
config := &Configuration{}
if err := json.Unmarshal(jsondata, config); err != nil {
return nil, err
}
return config, nil
}
func (tapi *TwitterAPI) VerifyCredentials() (*TwitterUser, error) {
params := oauth.Params{
&oauth.Pair{
Key: "skip_status",
Value: "true",
},
}
resp, err := tapi.authcon.Get("https://api.twitter.com/1.1/account/verify_credentials.json", params, tapi.access_token)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, errors.New(resp.Status)
}
jsondata, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
user := &TwitterUser{}
if err := json.Unmarshal(jsondata, user); err != nil {
return nil, err
}
return user, nil
}
func (tapi *TwitterAPI) get_timeline(tl_name string, p ...*oauth.Pair) (*Timeline, error) {
jsondata, err := tapi.get_statuses(tl_name, p...)
if err != nil {
return nil, err
}
tl := &Timeline{}
if jsonerr := json.Unmarshal(jsondata, &tl.Tweets); jsonerr != nil {
return nil, jsonerr
}
return tl, nil
}
func (tapi *TwitterAPI) get_statuses(id string, p ...*oauth.Pair) ([]byte, error) {
var params oauth.Params
for _, x := range p {
if x != nil {
params.Add(x)
}
}
resp, geterr := tapi.authcon.Get("https://api.twitter.com/1.1/statuses/"+id+".json", params, tapi.access_token)
if geterr != nil {
return nil, geterr
}
tapi.UpdateRatelimit(resp.Header)
return ioutil.ReadAll(resp.Body)
}
type HTTPError int
func (e HTTPError) Error() string {
return "HTTP code " + strconv.Itoa(int(e))
}
func (tapi *TwitterAPI) UserStream(tweetchan chan<- []*Tweet, actions chan<- interface{}) {
network_wait := INITIAL_NETWORK_WAIT
http_wait := INITIAL_HTTP_WAIT
last_network_backoff := time.Now()
last_http_backoff := time.Now()
for {
if err := tapi.doUserStream(tweetchan, actions); err != nil {
log.Printf("user stream returned error: %v", err)
if _, ok := err.(HTTPError); ok {
if (time.Now().Sub(last_http_backoff)) > 1800 {
http_wait = INITIAL_HTTP_WAIT
}
log.Printf("HTTP wait: backing off %d seconds", http_wait/1e9)
time.Sleep(http_wait)
if http_wait < MAX_HTTP_WAIT {
http_wait *= 2
}
last_http_backoff = time.Now()
} else {
if (time.Now().Sub(last_network_backoff)) > 1800 {
network_wait = INITIAL_NETWORK_WAIT
}
log.Printf("Network wait: backing off %d milliseconds", network_wait/1e6)
time.Sleep(network_wait)
if network_wait < MAX_NETWORK_WAIT {
network_wait += INITIAL_NETWORK_WAIT
}
last_network_backoff = time.Now()
}
}
}
}
func (tapi *TwitterAPI) doUserStream(tweetchan chan<- []*Tweet, actions chan<- interface{}) error {
resolve_urls := false
if tapi.config != nil {
if resolve, err := tapi.config.GetBool("default", "resolve_urls"); err == nil {
resolve_urls = resolve
}
}
resp, err := tapi.authcon.Get("https://userstream.twitter.com/2/user.json", oauth.Params{}, tapi.access_token)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode > 200 {
bodydata, _ := ioutil.ReadAll(resp.Body)
log.Printf("HTTP error: %s", string(bodydata))
return HTTPError(resp.StatusCode)
}
buf := bufio.NewReader(resp.Body)
for {
line, err := getLine(buf)
if err != nil {
log.Printf("getLine error: %v", err)
return err
}
if len(line) == 0 {
continue
}
if bytes.HasPrefix(line, []byte("{\"delete\":")) {
action := &TwitterEvent{}
if err := json.Unmarshal(line, action); err != nil {
continue
}
if action.Delete != nil && action.Delete.Status != nil && action.Delete.Status.Id != nil {
actions <- ActionDeleteTweet(*action.Delete.Status.Id)
}
} else {
newtweet := &Tweet{}
if err := json.Unmarshal(line, newtweet); err != nil {
log.Printf("couldn't unmarshal tweet: %v\n", err)
continue
}
// TODO: move this to goroutine if resolving turns out to block everything.
if resolve_urls {
newtweet.ResolveURLs()
}
if newtweet.Id != nil && newtweet.Text != nil {
tweetchan <- []*Tweet{newtweet}
}
}
}
// not reached
return nil
}
func getLine(buf *bufio.Reader) ([]byte, error) {
line := []byte{}
for {
data, isprefix, err := buf.ReadLine()
if err != nil {
return line, err
}
line = append(line, data...)
if !isprefix {
break
}
}
return line, nil
}
func (tapi *TwitterAPI) UpdateRatelimit(hdrs http.Header) {
for k, v := range hdrs {
switch strings.ToLower(k) {
case "x-ratelimit-limit":
if limit, err := strconv.ParseUint(v[0], 10, 0); err == nil {
tapi.ratelimit_limit = uint(limit)
}
case "x-ratelimit-remaining":
if rem, err := strconv.ParseUint(v[0], 10, 0); err == nil {
tapi.ratelimit_rem = uint(rem)
}
case "x-ratelimit-reset":
if reset, err := strconv.ParseInt(v[0], 10, 64); err == nil {
tapi.ratelimit_reset = reset
}
}
}
}
func (t *Tweet) RelativeCreatedAt() string {
if t.Created_at == nil {
return ""
}
tt, err := time.Parse(time.RubyDate, *t.Created_at)
if err != nil {
return *t.Created_at
}
delta := time.Now().Unix() - tt.Unix()
switch {
case delta < 60:
return "less than a minute ago"
case delta < 120:
return "about a minute ago"
case delta < 45*60:
return fmt.Sprintf("about %d minutes ago", delta/60)
case delta < 120*60:
return "about an hour ago"
case delta < 24*60*60:
return fmt.Sprintf("about %d hours ago", delta/3600)
case delta < 48*60*60:
return "1 day ago"
}
return fmt.Sprintf("%d days ago", delta/(3600*24))
}
func longify_url(url string) (longurl string) {
defer func() {
if r := recover(); r != nil {
log.Printf("longify_url: %v", r)
longurl = url
}
}()
if resp, err := http.Head(url); err == nil && resp.Request != nil && resp.Request.URL != nil {
longurl = strings.Replace(resp.Request.URL.String(), "%23", "#", -1) // HACK, breaks real %23
} else {
longurl = url
}
return
}
func (t *Tweet) ResolveURLs() {
if t.Text != nil {
*t.Text = FindURLs(*t.Text, longify_url)
}
}
| akrennmair/gockel | twitterapi.go | GO | mit | 18,513 |
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace ProjectMarkdown.Converters
{
[ValueConversion(typeof(bool), typeof(Visibility))]
public class VisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var visibilityValue = Visibility.Visible;
if (value != null)
{
var isSavedValue = (bool)value;
if (isSavedValue)
{
visibilityValue = Visibility.Hidden;
}
}
return visibilityValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| aykanatm/ProjectMarkdown | ProjectMarkdown/Converters/VisibilityConverter.cs | C# | mit | 879 |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Ilaro.Admin.Core;
using Ilaro.Admin.DataAnnotations;
namespace Ilaro.Admin.Sample.Models.Northwind
{
public class Category
{
public int CategoryID { get; set; }
[StringLength(15)]
public string CategoryName { get; set; }
public string Description { get; set; }
//public byte[] Picture { get; set; }
[Cascade(CascadeOption.AskUser)]
public ICollection<Product> Products { get; set; }
}
} | tassyo1/Ilaro.Admin | src/Ilaro.Admin/Ilaro.Admin.Sample/Models/Northwind/Category.cs | C# | mit | 547 |
using System;
using System.Collections.Generic;
namespace Graphql.Api.Core.Models
{
public class TrainingWeek
{
public Guid Id { get; set; }
public int Number { get; set; }
public IList<TrainingDay> Days { get; set; }
}
} | spetz/graphql-sample | Core/Models/TrainingWeek.cs | C# | mit | 258 |
/**
* World interface that represents the entire play area.
*/
public interface World {
public boolean contains(Bot bot);
public int getHeight();
public int getWidth();
}
| jemmele06/BattleBots | src/World.java | Java | mit | 187 |
'use strict';
angular.module('angular-tabs', ['angular-tabs-utils'])
.provider('$uiTabs', function () {
/**
*
*/
var TabDefinition = function () {
this.$dirty = false;
this.$selected = false;
this.$volatile = true;
this.$data = {};
};
TabDefinition.prototype.onClose = ['$q', function ($q) {
return function () {
var deferred = $q.defer();
deferred.resolve();
return deferred.promise;
};
}];
/**
* Map of tab definitions
*/
var tabDefinitions = {
null: {template: ''}
};
/**
*
* @param type {string}
* @param definition {Object}
* @returns {Object} self
*/
this.tab = function (type, definition) {
var tabDefinition = angular.extend(
{}, definition
);
if (tabDefinition.volatile !== undefined) {
tabDefinition.$volatile = !!tabDefinition.volatile;
delete tabDefinition.volatile;
}
tabDefinitions[type] = tabDefinition;
return this;
};
/**
*
* @param definition {Object}
* @returns {Object} self
*/
this.welcome = function (definition) {
return this.tab(null, definition);
};
this.config = function(options) {
TabDefinition.prototype.tabHeaderItemTemplate = options.tabHeaderItemTemplate;
TabDefinition.prototype.tabHeaderMenuItemTemplate = options.tabHeaderMenuItemTemplate;
TabDefinition.prototype.tabHeaderItemTemplateUrl = options.tabHeaderItemTemplateUrl || 'src/templates/templateItemUrl.html';
TabDefinition.prototype.tabHeaderMenuItemTemplateUrl = options.tabHeaderMenuItemTemplateUrl || 'src/templates/templateMenuItemUrl.html';
};
/**
*
* @param handler {function}
*/
this.onClose = function (handler) {
TabDefinition.prototype.onClose = handler;
};
/*
*
*/
function initTab(type, options) {
var tabDefinition = tabDefinitions[type];
if (!tabDefinition) {
return undefined;
}
var tabDefInstance = angular.extend(new TabDefinition(), tabDefinition, options || {});
if (!!tabDefInstance.template && !!options && !!options.templateUrl) {
delete tabDefInstance.template;
}
return tabDefInstance;
}
this.$get = ["$rootScope", "$injector", "$sce", "$http", "$q", "$templateCache", "utils", function ($rootScope, $injector, $sce, $http, $q, $templateCache, utils) {
/**
* Basically TABS.arr & TABS.map contain the same tabs objects
*/
var TABS = {
arr : [],
map : {},
history : [],
activeTab: undefined
};
/**
* Return a tab object
* @param id tab id
* @returns {tab}
*/
var getTab = function (id) {
return TABS.map[id];
};
var removeTab = function (id) {
var tab = getTab(id);
$q.when(tab).
then(function () {
if (tab.onClose) {
var fn = angular.isString(tab.onClose) ? $injector.get(tab.onClose) : $injector.invoke(tab.onClose);
return fn(tab);
}
}).
// after tab close resolved
then(function () {
removeTabIntern(tab);
});
};
var removeTabIntern = function (tab) {
utils.remove(TABS.history, function (tabId) {
return tabId === tab.$$tabId;
});
if (tab.$selected && TABS.history.length > 0) {
selectTab(TABS.history[TABS.history.length - 1]);
}
cleanTabScope(tab);
TABS.arr.splice(TABS.arr.indexOf(tab), 1);
delete TABS.map[tab.$$tabId];
$rootScope.$broadcast('$tabRemoveSuccess', tab);
};
var getActiveTab = function () {
return TABS.activeTab;
};
/**
* Return all tabs
* @returns {*}
*/
var getTabs = function () {
return TABS.arr; // clone ?
};
/*
Private
*/
var cleanTabScope = function (tab) {
if (tab.scope) {
tab.scope.$destroy();
tab.scope = null;
}
};
/**
* Add a new tab
* @param type type of a tab described with $uiTabsProvider
* @param options init tab options (title, disabled)
* @param id (optional) tab's unique id. If 'id' exists, tab content of this tab will be replaced
* @returns {Promise(tab)}
*/
var addTab = function (type, options, id) {
var newTab = initTab(type, options);
if (!newTab) {
throw new Error('Unknown tab type: ' + type);
}
newTab.$$tabId = id || Math.random().toString(16).substr(2);
newTab.close = function () {
removeTab(this.$$tabId);
};
return loadTabIntern(newTab).then(function(newTab) {
var find = getTab(newTab.$$tabId);
if (!find) {
// Add Tab
if (type !== null) {
TABS.arr.push(newTab);
}
TABS.map[newTab.$$tabId] = newTab;
} else {
// Replace tab
cleanTabScope(find);
angular.copy(newTab, find);
}
return selectTab(newTab.$$tabId);
}, function (error) {
$rootScope.$broadcast('$tabAddError', newTab, error);
});
};
/**
* Select an existing tab
* @param tabId tab id
* @returns {tab}
*/
function loadTabIntern(tab) {
return $q.when(tab).
then(function () {
// Start loading template
$rootScope.$broadcast('$tabLoadStart', tab);
var locals = angular.extend({}, tab.resolve),
template, templateUrl;
angular.forEach(locals, function (value, key) {
locals[key] = angular.isString(value) ?
$injector.get(value) : $injector.invoke(value);
});
if (angular.isDefined(template = tab.template)) {
if (angular.isFunction(template)) {
template = template(tab);
}
} else if (angular.isDefined(templateUrl = tab.templateUrl)) {
if (angular.isFunction(templateUrl)) {
templateUrl = templateUrl(tab);
}
templateUrl = $sce.getTrustedResourceUrl(templateUrl);
if (angular.isDefined(templateUrl)) {
tab.loadedTemplateUrl = templateUrl;
template = $http.get(templateUrl, {cache: $templateCache}).
then(function (response) {
return response.data;
});
}
}
if (angular.isDefined(template)) {
locals.$template = template;
}
return $q.all(locals);
}).then(function(locals) {
tab.locals = locals;
$rootScope.$broadcast('$tabLoadEnd', tab);
return tab;
});
}
/**
* Select an existing tab
* @param tabId tab id
* @returns {tab}
*/
function selectTab(tabId) {
var next = getTab(tabId),
last = getActiveTab();
if (next && last && next.$$tabId === last.$$tabId) {
$rootScope.$broadcast('$tabUpdate', last);
} else if (next) {
$rootScope.$broadcast('$tabChangeStart', next, last);
if (last) {
last.$selected = false;
}
next.$selected = true;
TABS.activeTab = next;
utils.remove(TABS.history, function (id) {
return tabId === id;
});
TABS.history.push(tabId);
$rootScope.$broadcast('$tabChangeSuccess', next, last);
} else {
$rootScope.$broadcast('$tabChangeError', next, 'Cloud not found tab with id #' + tabId);
}
return next;
}
// Add welcome tab
addTab(null);
/**
* Public API
*/
return {
addTab: addTab,
getTabs: getTabs,
getTab: getTab,
removeTab: removeTab,
selectTab: selectTab,
getActiveTab: getActiveTab
};
}];
})
.directive('tabView', ["$uiTabs", "$anchorScroll", "$animate", function ($uiTabs, $anchorScroll, $animate) {
return {
restrict: 'ECA',
terminal: true,
priority: 400,
transclude: 'element',
link: function (scope, $element, attr, ctrl, $transclude) {
var currentScope,
currentElement,
previousElement,
autoScrollExp = attr.autoscroll,
onloadExp = attr.onload || '',
elems = {};
function onTabRemoveSuccess(event, tab) {
if (tab.$selected === false) {
var elem = elems[tab.$$tabId];
if (elem) {
delete elems[tab.$$tabId];
elem.remove();
elem = null;
}
}
}
function cleanupLastView() {
var id = currentElement && currentElement.data('$$tabId');
var tab = $uiTabs.getTab(id);
if (previousElement) {
previousElement.remove();
previousElement = null;
}
if (currentScope && tab === undefined) {
currentScope.$destroy();
currentScope = null;
}
if (currentElement) {
if (tab) {
$animate.addClass(currentElement, 'ng-hide');
previousElement = null;
} else {
$animate.leave(currentElement, function () {
previousElement = null;
});
previousElement = currentElement;
currentElement = null;
}
}
}
function onTabChangeSuccess(event, currentTab) {
var elem = elems[currentTab.$$tabId];
if (elem) {
$animate.removeClass(elem, 'ng-hide');
cleanupLastView();
currentElement = elem;
return;
}
var locals = currentTab && currentTab.locals,
template = locals && locals.$template;
if (angular.isDefined(template)) {
var newScope = scope.$new();
newScope.$$tabId = currentTab.$$tabId;
if (currentTab.$volatile !== false) {
newScope.$data = currentTab.$data;
}
newScope.$setTabDirty = function () {
currentTab.$dirty = true;
};
// Note: This will also link all children of tab-view that were contained in the original
// html. If that content contains controllers, ... they could pollute/change the scope.
// However, using ng-view on an element with additional content does not make sense...
// Note: We can't remove them in the cloneAttchFn of $transclude as that
// function is called before linking the content, which would apply child
// directives to non existing elements.
var clone = $transclude(newScope, function (clone) {
$animate.enter(clone, null, currentElement || $element, function onNgViewEnter() {
if (angular.isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
$anchorScroll();
}
});
cleanupLastView();
});
currentElement = clone;
currentScope = newScope;
if (currentTab.$volatile === false) {
currentElement.data('$$tabId', currentTab.$$tabId);
elems[currentTab.$$tabId] = currentElement;
currentTab.scope = newScope;
}
newScope.$emit('$tabContentLoaded');
newScope.$eval(onloadExp);
} else {
cleanupLastView();
}
}
scope.$on('$tabChangeSuccess', onTabChangeSuccess);
scope.$on('$tabRemoveSuccess', onTabRemoveSuccess);
}
};
}])
.directive('tabView', ["$compile", "$controller", "$uiTabs", function ($compile, $controller, $uiTabs) {
return {
restrict: 'ECA',
priority: -400,
link: function (scope, $element) {
var current = $uiTabs.getActiveTab(),
locals = current.locals;
scope.$$currentTab = current;
$element.html(locals.$template);
$element.addClass('ui-tab-system-view');
var link = $compile($element.contents());
if (current.controller) {
locals.$scope = scope;
var controller = $controller(current.controller, locals);
if (current.controllerAs) {
scope[current.controllerAs] = controller;
}
$element.data('$ngControllerController', controller);
$element.children().data('$ngControllerController', controller);
}
link(scope);
},
controller: ["$scope", function ($scope) {
this.$$getCurrentTab = function () {
return $scope.$$currentTab;
};
}]
};
}])
.directive('closeUiTab', function () {
return {
restrict: 'ECA',
priority: -400,
require: '^tabView',
link: function (scope, $element, attr, tabViewCtrl) {
$element.on('click', function () {
scope.$apply(function() {
tabViewCtrl.$$getCurrentTab().close();
});
});
}
};
})
.directive('closeUiTabHeader', function () {
return {
restrict: 'ECA',
priority: -401,
link: function (scope, $element, attr) {
$element.on('click', function () {
scope.$apply(function() {
scope.tab.close();
});
});
}
};
})
.directive('tabHeaderItem', ["$http", "$templateCache", "$compile", "$sce", "$q", function ($http, $templateCache, $compile, $sce, $q) {
return {
restrict: 'EA',
scope: {
index: '=',
tab: '='
},
priority: -402,
link: function (scope, element, attrs) {
var template, templateUrl;
if (attrs.type === 'menu') {
template = scope.tab.tabHeaderMenuItemTemplate;
templateUrl = scope.tab.tabHeaderMenuItemTemplateUrl;
} else {
template = scope.tab.tabHeaderItemTemplate;
templateUrl = scope.tab.tabHeaderItemTemplateUrl;
}
if (angular.isDefined(template)) {
if (angular.isFunction(template)) {
template = template(tab);
}
} else if (angular.isDefined(templateUrl)) {
if (angular.isFunction(templateUrl)) {
templateUrl = templateUrl(tab);
}
templateUrl = $sce.getTrustedResourceUrl(templateUrl);
if (angular.isDefined(templateUrl)) {
//tab.loadedTemplateUrl = templateUrl;
template = $http.get(templateUrl, {cache: $templateCache}).
then(function (response) {
return response.data;
});
}
}
$q.when(template).then(function(tplContent) {
element.replaceWith($compile(tplContent.trim())(scope));
});
/* xxxx
$http.get(tplUrl, {cache: $templateCache}).success(function (tplContent) {
element.replaceWith($compile(tplContent.trim())(scope));
});*/
}
};
}])
.directive('tabHeader', ["$uiTabs", "$window", "$timeout", "utils", function ($uiTabs, $window, $timeout, utils) {
return {
restrict: 'ECA',
priority: -400,
template: '<div class="ui-tab-header" ui-tab-menu-dropdown>\n <div class="ui-tab-header-wrapper">\n <ul class="ui-tab-header-container">\n <li class="ui-tab-header-item" ng-class="{active: tab.$selected}" data-ng-repeat="tab in tabs" data-ng-click="selectTab(tab, $index)">\n <span tab-header-item type="tab" tab="tab" index="$index"></span>\n </li>\n </ul>\n </div>\n\n <span class="ui-tab-header-menu-toggle" ui-tab-menu-dropdown-toggle ng-show="showTabMenuHandler"></span>\n <div class="ui-tab-header-menu">\n <ul>\n <li class="ui-tab-header-menu-item" data-ng-repeat="tab in tabs" data-ng-click="selectTab(tab, $index)">\n <span tab-header-item type="menu" tab="tab" index="$index"></span>\n </li>\n </ul>\n </div>\n</div>\n',
scope: {},
controller: function() {},
link: function (scope, elem, attr) {
var container = elem.find('ul.ui-tab-header-container');
var wrapper = elem.find('div.ui-tab-header-wrapper');
var lastSelectedIndex;
scope.tabs = $uiTabs.getTabs();
scope.selectTab = function (tab, index) {
$uiTabs.selectTab(tab.$$tabId);
scrollToTab(index);
};
scope.closeTab = function (tab) {
$uiTabs.removeTab(tab.$$tabId);
};
scope.$watchCollection('tabs', function (tabs) {
$timeout(function () {
var index = tabs.indexOf($uiTabs.getActiveTab());
if (index !== -1) {
scrollToTab(index);
}
});
});
var scrollToTab = function (index) {
var left;
if (container.outerWidth() + container.position().left < wrapper.innerWidth()) {
// Trim space in the right (when deletion or window resize)
left = Math.min((wrapper.innerWidth() - container.outerWidth() ), 0);
}
scope.showTabMenuHandler = wrapper.innerWidth() < container.outerWidth();
if (index !== undefined) {
var li = elem.find('li.ui-tab-header-item:nth-child(' + (index + 1) + ')');
var leftOffset = container.position().left;
if (leftOffset + li.position().left < 0) {
// Scroll to active tab at left
left = -li.position().left;
} else {
// Scroll to active tab at right
var liOffset = li.position().left + li.outerWidth() + leftOffset;
if (liOffset > wrapper.innerWidth()) {
left = wrapper.innerWidth() + leftOffset - liOffset;
}
}
}
if (left !== undefined) {
container.css({left: left});
}
lastSelectedIndex = index;
};
var w = angular.element($window);
w.bind('resize', utils.debounce(function (event) {
scope.$apply(scrollToTab(lastSelectedIndex));
}, 200));
}
};
}])
.constant('dropdownConfig', {
openClass: 'open'
})
.service('dropdownService', ['$document', function ($document) {
var openScope = null;
this.open = function (dropdownScope) {
if (!openScope) {
$document.bind('click', closeDropdown);
$document.bind('keydown', escapeKeyBind);
}
if (openScope && openScope !== dropdownScope) {
openScope.isOpen = false;
}
openScope = dropdownScope;
};
this.close = function (dropdownScope) {
if (openScope === dropdownScope) {
openScope = null;
$document.unbind('click', closeDropdown);
$document.unbind('keydown', escapeKeyBind);
}
};
var closeDropdown = function (evt) {
// This method may still be called during the same mouse event that
// unbound this event handler. So check openScope before proceeding.
if (!openScope) {
return;
}
var toggleElement = openScope.getToggleElement();
if (evt && toggleElement && toggleElement[0].contains(evt.target)) {
return;
}
openScope.$apply(function () {
openScope.isOpen = false;
});
};
var escapeKeyBind = function (evt) {
if (evt.which === 27) {
openScope.focusToggleElement();
closeDropdown();
}
};
}])
.controller('DropdownController', ['$scope', '$attrs', '$parse', 'dropdownConfig', 'dropdownService', '$animate', function ($scope, $attrs, $parse, dropdownConfig, dropdownService, $animate) {
var self = this,
scope = $scope.$new(), // create a child scope so we are not polluting original one
openClass = dropdownConfig.openClass,
getIsOpen,
setIsOpen = angular.noop,
toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop;
this.init = function (element) {
self.$element = element;
if ($attrs.isOpen) {
getIsOpen = $parse($attrs.isOpen);
setIsOpen = getIsOpen.assign;
$scope.$watch(getIsOpen, function (value) {
scope.isOpen = !!value;
});
}
};
this.toggle = function (open) {
scope.isOpen = arguments.length ? !!open : !scope.isOpen;
return scope.isOpen;
};
// Allow other directives to watch status
this.isOpen = function () {
return scope.isOpen;
};
scope.getToggleElement = function () {
return self.toggleElement;
};
scope.focusToggleElement = function () {
if (self.toggleElement) {
self.toggleElement[0].focus();
}
};
scope.$watch('isOpen', function (isOpen, wasOpen) {
$animate[isOpen ? 'addClass' : 'removeClass'](self.$element, openClass);
if (isOpen) {
scope.focusToggleElement();
dropdownService.open(scope);
} else {
dropdownService.close(scope);
}
setIsOpen($scope, isOpen);
if (angular.isDefined(isOpen) && isOpen !== wasOpen) {
toggleInvoker($scope, {open: !!isOpen});
}
});
$scope.$on('$locationChangeSuccess', function () {
scope.isOpen = false;
});
$scope.$on('$destroy', function () {
scope.$destroy();
});
}])
.directive('uiTabMenuDropdown', function () {
return {
controller: 'DropdownController',
link: function (scope, element, attrs, dropdownCtrl) {
dropdownCtrl.init(element);
}
};
})
.directive('uiTabMenuDropdownToggle', function () {
return {
require: '?^uiTabMenuDropdown',
priority: -500,
link: function (scope, element, attrs, dropdownCtrl) {
if (!dropdownCtrl) {
return;
}
dropdownCtrl.toggleElement = element;
var toggleDropdown = function (event) {
event.preventDefault();
if (!element.hasClass('disabled') && !attrs.disabled) {
scope.$apply(function () {
dropdownCtrl.toggle();
});
}
};
element.bind('click', toggleDropdown);
// WAI-ARIA
element.attr({'aria-haspopup': true, 'aria-expanded': false});
scope.$watch(dropdownCtrl.isOpen, function (isOpen) {
element.attr('aria-expanded', !!isOpen);
});
scope.$on('$destroy', function () {
element.unbind('click', toggleDropdown);
});
}
};
})
.run(["$templateCache", function($templateCache) {
$templateCache.put('src/templates/templateItemUrl.html',
'<span class="asterisk" ng-show="tab.$dirty">*</span>' +
'<span class="ui-tab-header-title">{{tab.title}}</span>' +
'<span class="ui-tab-header-close" close-ui-tab-header></span>'
);
$templateCache.put('src/templates/templateMenuItemUrl.html',
'<span class="ui-tab-header-menu-item-title">{{tab.title}}</span>'
);
}]);
'use strict';
angular.module('angular-tabs-utils', [])
.service('utils', function () {
return {
remove: function (array, callback) {
var index = -1,
length = array ? array.length : 0,
result = [];
while (++index < length) {
var value = array[index];
if (callback && callback(value, index, array)) {
result.push(value);
[].splice.call(array, index--, 1);
length--;
}
}
return result;
},
debounce: function (func, wait, immediate) {
var args,
result,
thisArg,
timeoutId;
function delayed() {
timeoutId = null;
if (!immediate) {
result = func.apply(thisArg, args);
}
}
return function () {
var isImmediate = immediate && !timeoutId;
args = arguments;
thisArg = this;
clearTimeout(timeoutId);
timeoutId = setTimeout(delayed, wait);
if (isImmediate) {
result = func.apply(thisArg, args);
}
return result;
};
}
};
}); | cagegit/DataTransFront | app/bower_components/angular-ui-tabs/dist/angular-tabs.js | JavaScript | mit | 30,352 |
// Deps is sort of a problem for us, maybe in the future we will ask the user to depend
// on modules for add-ons
var deps = ['ObjectPath'];
try {
//This throws an expection if module does not exist.
angular.module('ngSanitize');
deps.push('ngSanitize');
} catch (e) {}
try {
//This throws an expection if module does not exist.
angular.module('ui.sortable');
deps.push('ui.sortable');
} catch (e) {}
try {
//This throws an expection if module does not exist.
angular.module('angularSpectrumColorpicker');
deps.push('angularSpectrumColorpicker');
} catch (e) {}
angular.module('schemaForm', deps);
angular.module('schemaForm').provider('sfPath',
['ObjectPathProvider', function(ObjectPathProvider) {
var ObjectPath = {parse: ObjectPathProvider.parse};
// if we're on Angular 1.2.x, we need to continue using dot notation
if (angular.version.major === 1 && angular.version.minor < 3) {
ObjectPath.stringify = function(arr) {
return Array.isArray(arr) ? arr.join('.') : arr.toString();
};
} else {
ObjectPath.stringify = ObjectPathProvider.stringify;
}
// We want this to use whichever stringify method is defined above,
// so we have to copy the code here.
ObjectPath.normalize = function(data, quote) {
return ObjectPath.stringify(Array.isArray(data) ? data : ObjectPath.parse(data), quote);
};
this.parse = ObjectPath.parse;
this.stringify = ObjectPath.stringify;
this.normalize = ObjectPath.normalize;
this.$get = function() {
return ObjectPath;
};
}]);
/**
* @ngdoc service
* @name sfSelect
* @kind function
*
*/
angular.module('schemaForm').factory('sfSelect', ['sfPath', function(sfPath) {
var numRe = /^\d+$/;
/**
* @description
* Utility method to access deep properties without
* throwing errors when things are not defined.
* Can also set a value in a deep structure, creating objects when missing
* ex.
* var foo = Select('address.contact.name',obj)
* Select('address.contact.name',obj,'Leeroy')
*
* @param {string} projection A dot path to the property you want to get/set
* @param {object} obj (optional) The object to project on, defaults to 'this'
* @param {Any} valueToSet (opional) The value to set, if parts of the path of
* the projection is missing empty objects will be created.
* @returns {Any|undefined} returns the value at the end of the projection path
* or undefined if there is none.
*/
return function(projection, obj, valueToSet) {
if (!obj) {
obj = this;
}
//Support [] array syntax
var parts = typeof projection === 'string' ? sfPath.parse(projection) : projection;
if (typeof valueToSet !== 'undefined' && parts.length === 1) {
//special case, just setting one variable
obj[parts[0]] = valueToSet;
return obj;
}
if (typeof valueToSet !== 'undefined' &&
typeof obj[parts[0]] === 'undefined') {
// We need to look ahead to check if array is appropriate
obj[parts[0]] = parts.length > 2 && numRe.test(parts[1]) ? [] : {};
}
var value = obj[parts[0]];
for (var i = 1; i < parts.length; i++) {
// Special case: We allow JSON Form syntax for arrays using empty brackets
// These will of course not work here so we exit if they are found.
if (parts[i] === '') {
return undefined;
}
if (typeof valueToSet !== 'undefined') {
if (i === parts.length - 1) {
//last step. Let's set the value
value[parts[i]] = valueToSet;
return valueToSet;
} else {
// Make sure to create new objects on the way if they are not there.
// We need to look ahead to check if array is appropriate
var tmp = value[parts[i]];
if (typeof tmp === 'undefined' || tmp === null) {
tmp = numRe.test(parts[i + 1]) ? [] : {};
value[parts[i]] = tmp;
}
value = tmp;
}
} else if (value) {
//Just get nex value.
value = value[parts[i]];
}
}
return value;
};
}]);
angular.module('schemaForm').provider('schemaFormDecorators',
['$compileProvider', 'sfPathProvider', function($compileProvider, sfPathProvider) {
var defaultDecorator = '';
var directives = {};
var templateUrl = function(name, form) {
//schemaDecorator is alias for whatever is set as default
if (name === 'sfDecorator') {
name = defaultDecorator;
}
var directive = directives[name];
//rules first
var rules = directive.rules;
for (var i = 0; i < rules.length; i++) {
var res = rules[i](form);
if (res) {
return res;
}
}
//then check mapping
if (directive.mappings[form.type]) {
return directive.mappings[form.type];
}
//try default
return directive.mappings['default'];
};
var createDirective = function(name) {
$compileProvider.directive(name, ['$parse', '$compile', '$http', '$templateCache',
function($parse, $compile, $http, $templateCache) {
return {
restrict: 'AE',
replace: false,
transclude: false,
scope: true,
require: '?^sfSchema',
link: function(scope, element, attrs, sfSchema) {
//rebind our part of the form to the scope.
var once = scope.$watch(attrs.form, function(form) {
if (form) {
scope.form = form;
//ok let's replace that template!
//We do this manually since we need to bind ng-model properly and also
//for fieldsets to recurse properly.
var url = templateUrl(name, form);
$http.get(url, {cache: $templateCache}).then(function(res) {
var key = form.key ?
sfPathProvider.stringify(form.key).replace(/"/g, '"') : '';
var template = res.data.replace(
/\$\$value\$\$/g,
'model' + (key[0] !== '[' ? '.' : '') + key
);
element.html(template);
$compile(element.contents())(scope);
});
once();
}
});
//Keep error prone logic from the template
scope.showTitle = function() {
return scope.form && scope.form.notitle !== true && scope.form.title;
};
scope.listToCheckboxValues = function(list) {
var values = {};
angular.forEach(list, function(v) {
values[v] = true;
});
return values;
};
scope.checkboxValuesToList = function(values) {
var lst = [];
angular.forEach(values, function(v, k) {
if (v) {
lst.push(k);
}
});
return lst;
};
scope.buttonClick = function($event, form) {
if (angular.isFunction(form.onClick)) {
form.onClick($event, form);
} else if (angular.isString(form.onClick)) {
if (sfSchema) {
//evaluating in scope outside of sfSchemas isolated scope
sfSchema.evalInParentScope(form.onClick, {'$event': $event, form: form});
} else {
scope.$eval(form.onClick, {'$event': $event, form: form});
}
}
};
/**
* Evaluate an expression, i.e. scope.$eval
* but do it in sfSchemas parent scope sf-schema directive is used
* @param {string} expression
* @param {Object} locals (optional)
* @return {Any} the result of the expression
*/
scope.evalExpr = function(expression, locals) {
if (sfSchema) {
//evaluating in scope outside of sfSchemas isolated scope
return sfSchema.evalInParentScope(expression, locals);
}
return scope.$eval(expression, locals);
};
/**
* Evaluate an expression, i.e. scope.$eval
* in this decorators scope
* @param {string} expression
* @param {Object} locals (optional)
* @return {Any} the result of the expression
*/
scope.evalInScope = function(expression, locals) {
if (expression) {
return scope.$eval(expression, locals);
}
};
/**
* Error message handler
* An error can either be a schema validation message or a angular js validtion
* error (i.e. required)
*/
scope.errorMessage = function(schemaError) {
//User has supplied validation messages
if (scope.form.validationMessage) {
if (schemaError) {
if (angular.isString(scope.form.validationMessage)) {
return scope.form.validationMessage;
}
return scope.form.validationMessage[schemaError.code] ||
scope.form.validationMessage['default'];
} else {
return scope.form.validationMessage.number ||
scope.form.validationMessage['default'] ||
scope.form.validationMessage;
}
}
//No user supplied validation message.
if (schemaError) {
return schemaError.message; //use tv4.js validation message
}
//Otherwise we only have input number not being a number
return 'Not a number';
};
}
};
}
]);
};
var createManualDirective = function(type, templateUrl, transclude) {
transclude = angular.isDefined(transclude) ? transclude : false;
$compileProvider.directive('sf' + angular.uppercase(type[0]) + type.substr(1), function() {
return {
restrict: 'EAC',
scope: true,
replace: true,
transclude: transclude,
template: '<sf-decorator form="form"></sf-decorator>',
link: function(scope, element, attrs) {
var watchThis = {
'items': 'c',
'titleMap': 'c',
'schema': 'c'
};
var form = {type: type};
var once = true;
angular.forEach(attrs, function(value, name) {
if (name[0] !== '$' && name.indexOf('ng') !== 0 && name !== 'sfField') {
var updateForm = function(val) {
if (angular.isDefined(val) && val !== form[name]) {
form[name] = val;
//when we have type, and if specified key we apply it on scope.
if (once && form.type && (form.key || angular.isUndefined(attrs.key))) {
scope.form = form;
once = false;
}
}
};
if (name === 'model') {
//"model" is bound to scope under the name "model" since this is what the decorators
//know and love.
scope.$watch(value, function(val) {
if (val && scope.model !== val) {
scope.model = val;
}
});
} else if (watchThis[name] === 'c') {
//watch collection
scope.$watchCollection(value, updateForm);
} else {
//$observe
attrs.$observe(name, updateForm);
}
}
});
}
};
});
};
/**
* Create a decorator directive and its sibling "manual" use directives.
* The directive can be used to create form fields or other form entities.
* It can be used in conjunction with <schema-form> directive in which case the decorator is
* given it's configuration via a the "form" attribute.
*
* ex. Basic usage
* <sf-decorator form="myform"></sf-decorator>
**
* @param {string} name directive name (CamelCased)
* @param {Object} mappings, an object that maps "type" => "templateUrl"
* @param {Array} rules (optional) a list of functions, function(form) {}, that are each tried in
* turn,
* if they return a string then that is used as the templateUrl. Rules come before
* mappings.
*/
this.createDecorator = function(name, mappings, rules) {
directives[name] = {
mappings: mappings || {},
rules: rules || []
};
if (!directives[defaultDecorator]) {
defaultDecorator = name;
}
createDirective(name);
};
/**
* Creates a directive of a decorator
* Usable when you want to use the decorators without using <schema-form> directive.
* Specifically when you need to reuse styling.
*
* ex. createDirective('text','...')
* <sf-text title="foobar" model="person" key="name" schema="schema"></sf-text>
*
* @param {string} type The type of the directive, resulting directive will have sf- prefixed
* @param {string} templateUrl
* @param {boolean} transclude (optional) sets transclude option of directive, defaults to false.
*/
this.createDirective = createManualDirective;
/**
* Same as createDirective, but takes an object where key is 'type' and value is 'templateUrl'
* Useful for batching.
* @param {Object} mappings
*/
this.createDirectives = function(mappings) {
angular.forEach(mappings, function(url, type) {
createManualDirective(type, url);
});
};
/**
* Getter for directive mappings
* Can be used to override a mapping or add a rule
* @param {string} name (optional) defaults to defaultDecorator
* @return {Object} rules and mappings { rules: [],mappings: {}}
*/
this.directive = function(name) {
name = name || defaultDecorator;
return directives[name];
};
/**
* Adds a mapping to an existing decorator.
* @param {String} name Decorator name
* @param {String} type Form type for the mapping
* @param {String} url The template url
*/
this.addMapping = function(name, type, url) {
if (directives[name]) {
directives[name].mappings[type] = url;
}
};
//Service is just a getter for directive mappings and rules
this.$get = function() {
return {
directive: function(name) {
return directives[name];
},
defaultDecorator: defaultDecorator
};
};
//Create a default directive
createDirective('sfDecorator');
}]);
/**
* Schema form service.
* This service is not that useful outside of schema form directive
* but makes the code more testable.
*/
angular.module('schemaForm').provider('schemaForm',
['sfPathProvider', function(sfPathProvider) {
//Creates an default titleMap list from an enum, i.e. a list of strings.
var enumToTitleMap = function(enm) {
var titleMap = []; //canonical titleMap format is a list.
enm.forEach(function(name) {
titleMap.push({name: name, value: name});
});
return titleMap;
};
// Takes a titleMap in either object or list format and returns one in
// in the list format.
var canonicalTitleMap = function(titleMap, originalEnum) {
if (!angular.isArray(titleMap)) {
var canonical = [];
if (originalEnum) {
angular.forEach(originalEnum, function(value, index) {
canonical.push({name: titleMap[value], value: value});
});
} else {
angular.forEach(titleMap, function(name, value) {
canonical.push({name: name, value: value});
});
}
return canonical;
}
return titleMap;
};
var defaultFormDefinition = function(name, schema, options) {
var rules = defaults[schema.type];
if (rules) {
var def;
for (var i = 0; i < rules.length; i++) {
def = rules[i](name, schema, options);
//first handler in list that actually returns something is our handler!
if (def) {
return def;
}
}
}
};
//Creates a form object with all common properties
var stdFormObj = function(name, schema, options) {
options = options || {};
var f = options.global && options.global.formDefaults ?
angular.copy(options.global.formDefaults) : {};
if (options.global && options.global.supressPropertyTitles === true) {
f.title = schema.title;
} else {
f.title = schema.title || name;
}
if (schema.description) { f.description = schema.description; }
if (options.required === true || schema.required === true) { f.required = true; }
if (schema.maxLength) { f.maxlength = schema.maxLength; }
if (schema.minLength) { f.minlength = schema.maxLength; }
if (schema.readOnly || schema.readonly) { f.readonly = true; }
if (schema.minimum) { f.minimum = schema.minimum + (schema.exclusiveMinimum ? 1 : 0); }
if (schema.maximum) { f.maximum = schema.maximum - (schema.exclusiveMaximum ? 1 : 0); }
//Non standard attributes
if (schema.validationMessage) { f.validationMessage = schema.validationMessage; }
if (schema.enumNames) { f.titleMap = canonicalTitleMap(schema.enumNames, schema['enum']); }
f.schema = schema;
// Ng model options doesn't play nice with undefined, might be defined
// globally though
f.ngModelOptions = f.ngModelOptions || {};
return f;
};
var text = function(name, schema, options) {
if (schema.type === 'string' && !schema['enum']) {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'text';
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
//default in json form for number and integer is a text field
//input type="number" would be more suitable don't ya think?
var number = function(name, schema, options) {
if (schema.type === 'number') {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'number';
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
var integer = function(name, schema, options) {
if (schema.type === 'integer') {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'number';
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
var checkbox = function(name, schema, options) {
if (schema.type === 'boolean') {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'checkbox';
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
var select = function(name, schema, options) {
if (schema.type === 'string' && schema['enum']) {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'select';
if (!f.titleMap) {
f.titleMap = enumToTitleMap(schema['enum']);
}
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
var checkboxes = function(name, schema, options) {
if (schema.type === 'array' && schema.items && schema.items['enum']) {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'checkboxes';
if (!f.titleMap) {
f.titleMap = enumToTitleMap(schema.items['enum']);
}
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
var fieldset = function(name, schema, options) {
if (schema.type === 'object') {
var f = stdFormObj(name, schema, options);
f.type = 'fieldset';
f.items = [];
options.lookup[sfPathProvider.stringify(options.path)] = f;
//recurse down into properties
angular.forEach(schema.properties, function(v, k) {
var path = options.path.slice();
path.push(k);
if (options.ignore[sfPathProvider.stringify(path)] !== true) {
var required = schema.required && schema.required.indexOf(k) !== -1;
var def = defaultFormDefinition(k, v, {
path: path,
required: required || false,
lookup: options.lookup,
ignore: options.ignore
});
if (def) {
f.items.push(def);
}
}
});
return f;
}
};
var array = function(name, schema, options) {
if (schema.type === 'array') {
var f = stdFormObj(name, schema, options);
f.type = 'array';
f.key = options.path;
options.lookup[sfPathProvider.stringify(options.path)] = f;
var required = schema.required &&
schema.required.indexOf(options.path[options.path.length - 1]) !== -1;
// The default is to always just create one child. This works since if the
// schemas items declaration is of type: "object" then we get a fieldset.
// We also follow json form notatation, adding empty brackets "[]" to
// signify arrays.
var arrPath = options.path.slice();
arrPath.push('');
f.items = [defaultFormDefinition(name, schema.items, {
path: arrPath,
required: required || false,
lookup: options.lookup,
ignore: options.ignore,
global: options.global
})];
return f;
}
};
//First sorted by schema type then a list.
//Order has importance. First handler returning an form snippet will be used.
var defaults = {
string: [select, text],
object: [fieldset],
number: [number],
integer: [integer],
boolean: [checkbox],
array: [checkboxes, array]
};
var postProcessFn = function(form) { return form; };
/**
* Provider API
*/
this.defaults = defaults;
this.stdFormObj = stdFormObj;
this.defaultFormDefinition = defaultFormDefinition;
/**
* Register a post process function.
* This function is called with the fully merged
* form definition (i.e. after merging with schema)
* and whatever it returns is used as form.
*/
this.postProcess = function(fn) {
postProcessFn = fn;
};
/**
* Append default form rule
* @param {string} type json schema type
* @param {Function} rule a function(propertyName,propertySchema,options) that returns a form
* definition or undefined
*/
this.appendRule = function(type, rule) {
if (!defaults[type]) {
defaults[type] = [];
}
defaults[type].push(rule);
};
/**
* Prepend default form rule
* @param {string} type json schema type
* @param {Function} rule a function(propertyName,propertySchema,options) that returns a form
* definition or undefined
*/
this.prependRule = function(type, rule) {
if (!defaults[type]) {
defaults[type] = [];
}
defaults[type].unshift(rule);
};
/**
* Utility function to create a standard form object.
* This does *not* set the type of the form but rather all shared attributes.
* You probably want to start your rule with creating the form with this method
* then setting type and any other values you need.
* @param {Object} schema
* @param {Object} options
* @return {Object} a form field defintion
*/
this.createStandardForm = stdFormObj;
/* End Provider API */
this.$get = function() {
var service = {};
service.merge = function(schema, form, ignore, options, readonly) {
form = form || ['*'];
options = options || {};
// Get readonly from root object
readonly = readonly || schema.readonly || schema.readOnly;
var stdForm = service.defaults(schema, ignore, options);
//simple case, we have a "*", just put the stdForm there
var idx = form.indexOf('*');
if (idx !== -1) {
form = form.slice(0, idx)
.concat(stdForm.form)
.concat(form.slice(idx + 1));
}
//ok let's merge!
//We look at the supplied form and extend it with schema standards
var lookup = stdForm.lookup;
return postProcessFn(form.map(function(obj) {
//handle the shortcut with just a name
if (typeof obj === 'string') {
obj = {key: obj};
}
if (obj.key) {
if (typeof obj.key === 'string') {
obj.key = sfPathProvider.parse(obj.key);
}
}
//If it has a titleMap make sure it's a list
if (obj.titleMap) {
obj.titleMap = canonicalTitleMap(obj.titleMap);
}
//
if (obj.itemForm) {
obj.items = [];
var str = sfPathProvider.stringify(obj.key);
var stdForm = lookup[str];
angular.forEach(stdForm.items, function(item) {
var o = angular.copy(obj.itemForm);
o.key = item.key;
obj.items.push(o);
});
}
//extend with std form from schema.
if (obj.key) {
var strid = sfPathProvider.stringify(obj.key);
if (lookup[strid]) {
obj = angular.extend(lookup[strid], obj);
}
}
// Are we inheriting readonly?
if (readonly === true) { // Inheriting false is not cool.
obj.readonly = true;
}
//if it's a type with items, merge 'em!
if (obj.items) {
obj.items = service.merge(schema, obj.items, ignore, options, obj.readonly);
}
//if its has tabs, merge them also!
if (obj.tabs) {
angular.forEach(obj.tabs, function(tab) {
tab.items = service.merge(schema, tab.items, ignore, options, obj.readonly);
});
}
// Special case: checkbox
// Since have to ternary state we need a default
if (obj.type === 'checkbox' && angular.isUndefined(obj.schema['default'])) {
obj.schema['default'] = false;
}
return obj;
}));
};
/**
* Create form defaults from schema
*/
service.defaults = function(schema, ignore, globalOptions) {
var form = [];
var lookup = {}; //Map path => form obj for fast lookup in merging
ignore = ignore || {};
globalOptions = globalOptions || {};
if (schema.type === 'object') {
angular.forEach(schema.properties, function(v, k) {
if (ignore[k] !== true) {
var required = schema.required && schema.required.indexOf(k) !== -1;
var def = defaultFormDefinition(k, v, {
path: [k], // Path to this property in bracket notation.
lookup: lookup, // Extra map to register with. Optimization for merger.
ignore: ignore, // The ignore list of paths (sans root level name)
required: required, // Is it required? (v4 json schema style)
global: globalOptions // Global options, including form defaults
});
if (def) {
form.push(def);
}
}
});
} else {
throw new Error('Not implemented. Only type "object" allowed at root level of schema.');
}
return {form: form, lookup: lookup};
};
//Utility functions
/**
* Traverse a schema, applying a function(schema,path) on every sub schema
* i.e. every property of an object.
*/
service.traverseSchema = function(schema, fn, path, ignoreArrays) {
ignoreArrays = angular.isDefined(ignoreArrays) ? ignoreArrays : true;
path = path || [];
var traverse = function(schema, fn, path) {
fn(schema, path);
angular.forEach(schema.properties, function(prop, name) {
var currentPath = path.slice();
currentPath.push(name);
traverse(prop, fn, currentPath);
});
//Only support type "array" which have a schema as "items".
if (!ignoreArrays && schema.items) {
var arrPath = path.slice(); arrPath.push('');
traverse(schema.items, fn, arrPath);
}
};
traverse(schema, fn, path || []);
};
service.traverseForm = function(form, fn) {
fn(form);
angular.forEach(form.items, function(f) {
service.traverseForm(f, fn);
});
if (form.tabs) {
angular.forEach(form.tabs, function(tab) {
angular.forEach(tab.items, function(f) {
service.traverseForm(f, fn);
});
});
}
};
return service;
};
}]);
/* Common code for validating a value against its form and schema definition */
/* global tv4 */
angular.module('schemaForm').factory('sfValidator', [function() {
var validator = {};
/**
* Validate a value against its form definition and schema.
* The value should either be of proper type or a string, some type
* coercion is applied.
*
* @param {Object} form A merged form definition, i.e. one with a schema.
* @param {Any} value the value to validate.
* @return a tv4js result object.
*/
validator.validate = function(form, value) {
if (!form) {
return {valid: true};
}
var schema = form.schema;
if (!schema) {
return {valid: true};
}
// Input of type text and textareas will give us a viewValue of ''
// when empty, this is a valid value in a schema and does not count as something
// that breaks validation of 'required'. But for our own sanity an empty field should
// not validate if it's required.
if (value === '') {
value = undefined;
}
// Numbers fields will give a null value, which also means empty field
if (form.type === 'number' && value === null) {
value = undefined;
}
// Version 4 of JSON Schema has the required property not on the
// property itself but on the wrapping object. Since we like to test
// only this property we wrap it in a fake object.
var wrap = {type: 'object', 'properties': {}};
var propName = form.key[form.key.length - 1];
wrap.properties[propName] = schema;
if (form.required) {
wrap.required = [propName];
}
var valueWrap = {};
if (angular.isDefined(value)) {
valueWrap[propName] = value;
}
return tv4.validateResult(valueWrap, wrap);
};
return validator;
}]);
/**
* Directive that handles the model arrays
*/
angular.module('schemaForm').directive('sfArray', ['sfSelect', 'schemaForm', 'sfValidator',
function(sfSelect, schemaForm, sfValidator) {
var setIndex = function(index) {
return function(form) {
if (form.key) {
form.key[form.key.indexOf('')] = index;
}
};
};
return {
restrict: 'A',
scope: true,
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
var formDefCache = {};
// Watch for the form definition and then rewrite it.
// It's the (first) array part of the key, '[]' that needs a number
// corresponding to an index of the form.
var once = scope.$watch(attrs.sfArray, function(form) {
// An array model always needs a key so we know what part of the model
// to look at. This makes us a bit incompatible with JSON Form, on the
// other hand it enables two way binding.
var list = sfSelect(form.key, scope.model);
// Since ng-model happily creates objects in a deep path when setting a
// a value but not arrays we need to create the array.
if (angular.isUndefined(list)) {
list = [];
sfSelect(form.key, scope.model, list);
}
scope.modelArray = list;
// Arrays with titleMaps, i.e. checkboxes doesn't have items.
if (form.items) {
// To be more compatible with JSON Form we support an array of items
// in the form definition of "array" (the schema just a value).
// for the subforms code to work this means we wrap everything in a
// section. Unless there is just one.
var subForm = form.items[0];
if (form.items.length > 1) {
subForm = {
type: 'section',
items: form.items.map(function(item){
item.ngModelOptions = form.ngModelOptions;
item.readonly = form.readonly;
return item;
})
};
}
}
// We ceate copies of the form on demand, caching them for
// later requests
scope.copyWithIndex = function(index) {
if (!formDefCache[index]) {
if (subForm) {
var copy = angular.copy(subForm);
copy.arrayIndex = index;
schemaForm.traverseForm(copy, setIndex(index));
formDefCache[index] = copy;
}
}
return formDefCache[index];
};
scope.appendToArray = function() {
var len = list.length;
var copy = scope.copyWithIndex(len);
schemaForm.traverseForm(copy, function(part) {
if (part.key && angular.isDefined(part['default'])) {
sfSelect(part.key, scope.model, part['default']);
}
});
// If there are no defaults nothing is added so we need to initialize
// the array. undefined for basic values, {} or [] for the others.
if (len === list.length) {
var type = sfSelect('schema.items.type', form);
var dflt;
if (type === 'object') {
dflt = {};
} else if (type === 'array') {
dflt = [];
}
list.push(dflt);
}
// Trigger validation.
if (scope.validateArray) {
scope.validateArray();
}
return list;
};
scope.deleteFromArray = function(index) {
list.splice(index, 1);
// Trigger validation.
if (scope.validateArray) {
scope.validateArray();
}
return list;
};
// Always start with one empty form unless configured otherwise.
// Special case: don't do it if form has a titleMap
if (!form.titleMap && form.startEmpty !== true && list.length === 0) {
scope.appendToArray();
}
// Title Map handling
// If form has a titleMap configured we'd like to enable looping over
// titleMap instead of modelArray, this is used for intance in
// checkboxes. So instead of variable number of things we like to create
// a array value from a subset of values in the titleMap.
// The problem here is that ng-model on a checkbox doesn't really map to
// a list of values. This is here to fix that.
if (form.titleMap && form.titleMap.length > 0) {
scope.titleMapValues = [];
// We watch the model for changes and the titleMapValues to reflect
// the modelArray
var updateTitleMapValues = function(arr) {
scope.titleMapValues = [];
arr = arr || [];
form.titleMap.forEach(function(item) {
scope.titleMapValues.push(arr.indexOf(item.value) !== -1);
});
};
//Catch default values
updateTitleMapValues(scope.modelArray);
scope.$watchCollection('modelArray', updateTitleMapValues);
//To get two way binding we also watch our titleMapValues
scope.$watchCollection('titleMapValues', function(vals) {
if (vals) {
var arr = scope.modelArray;
// Apparently the fastest way to clear an array, readable too.
// http://jsperf.com/array-destroy/32
while (arr.length > 0) {
arr.shift();
}
form.titleMap.forEach(function(item, index) {
if (vals[index]) {
arr.push(item.value);
}
});
}
});
}
// If there is a ngModel present we need to validate when asked.
if (ngModel) {
var error;
scope.validateArray = function() {
// The actual content of the array is validated by each field
// so we settle for checking validations specific to arrays
// Since we prefill with empty arrays we can get the funny situation
// where the array is required but empty in the gui but still validates.
// Thats why we check the length.
var result = sfValidator.validate(
form,
scope.modelArray.length > 0 ? scope.modelArray : undefined
);
if (result.valid === false &&
result.error &&
(result.error.dataPath === '' ||
result.error.dataPath === '/' + form.key[form.key.length - 1])) {
// Set viewValue to trigger $dirty on field. If someone knows a
// a better way to do it please tell.
ngModel.$setViewValue(scope.modelArray);
error = result.error;
ngModel.$setValidity('schema', false);
} else {
ngModel.$setValidity('schema', true);
}
};
scope.$on('schemaFormValidate', scope.validateArray);
scope.hasSuccess = function() {
return ngModel.$valid && !ngModel.$pristine;
};
scope.hasError = function() {
return ngModel.$invalid;
};
scope.schemaError = function() {
return error;
};
}
once();
});
}
};
}
]);
/**
* A version of ng-changed that only listens if
* there is actually a onChange defined on the form
*
* Takes the form definition as argument.
* If the form definition has a "onChange" defined as either a function or
*/
angular.module('schemaForm').directive('sfChanged', function() {
return {
require: 'ngModel',
restrict: 'AC',
scope: false,
link: function(scope, element, attrs, ctrl) {
var form = scope.$eval(attrs.sfChanged);
//"form" is really guaranteed to be here since the decorator directive
//waits for it. But best be sure.
if (form && form.onChange) {
ctrl.$viewChangeListeners.push(function() {
if (angular.isFunction(form.onChange)) {
form.onChange(ctrl.$modelValue, form);
} else {
scope.evalExpr(form.onChange, {'modelValue': ctrl.$modelValue, form: form});
}
});
}
}
};
});
/*
FIXME: real documentation
<form sf-form="form" sf-schema="schema" sf-decorator="foobar"></form>
*/
angular.module('schemaForm')
.directive('sfSchema',
['$compile', 'schemaForm', 'schemaFormDecorators', 'sfSelect',
function($compile, schemaForm, schemaFormDecorators, sfSelect) {
var SNAKE_CASE_REGEXP = /[A-Z]/g;
var snakeCase = function(name, separator) {
separator = separator || '_';
return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
};
return {
scope: {
schema: '=sfSchema',
initialForm: '=sfForm',
model: '=sfModel',
options: '=sfOptions'
},
controller: ['$scope', function($scope) {
this.evalInParentScope = function(expr, locals) {
return $scope.$parent.$eval(expr, locals);
};
}],
replace: false,
restrict: 'A',
transclude: true,
require: '?form',
link: function(scope, element, attrs, formCtrl, transclude) {
//expose form controller on scope so that we don't force authors to use name on form
scope.formCtrl = formCtrl;
//We'd like to handle existing markup,
//besides using it in our template we also
//check for ng-model and add that to an ignore list
//i.e. even if form has a definition for it or form is ["*"]
//we don't generate it.
var ignore = {};
transclude(scope, function(clone) {
clone.addClass('schema-form-ignore');
element.prepend(clone);
if (element[0].querySelectorAll) {
var models = element[0].querySelectorAll('[ng-model]');
if (models) {
for (var i = 0; i < models.length; i++) {
var key = models[i].getAttribute('ng-model');
//skip first part before .
ignore[key.substring(key.indexOf('.') + 1)] = true;
}
}
}
});
//Since we are dependant on up to three
//attributes we'll do a common watch
var lastDigest = {};
scope.$watch(function() {
var schema = scope.schema;
var form = scope.initialForm || ['*'];
//The check for schema.type is to ensure that schema is not {}
if (form && schema && schema.type &&
(lastDigest.form !== form || lastDigest.schema !== schema) &&
Object.keys(schema.properties).length > 0) {
lastDigest.schema = schema;
lastDigest.form = form;
var merged = schemaForm.merge(schema, form, ignore, scope.options);
var frag = document.createDocumentFragment();
//make the form available to decorators
scope.schemaForm = {form: merged, schema: schema};
//clean all but pre existing html.
element.children(':not(.schema-form-ignore)').remove();
//Create directives from the form definition
angular.forEach(merged,function(obj,i){
var n = document.createElement(attrs.sfDecorator || snakeCase(schemaFormDecorators.defaultDecorator,'-'));
n.setAttribute('form','schemaForm.form['+i+']');
var slot;
try {
slot = element[0].querySelector('*[sf-insert-field="' + obj.key + '"]');
} catch(err) {
// field insertion not supported for complex keys
slot = null;
}
if(slot) {
slot.innerHTML = "";
slot.appendChild(n);
} else {
frag.appendChild(n);
}
});
element[0].appendChild(frag);
//compile only children
$compile(element.children())(scope);
//ok, now that that is done let's set any defaults
schemaForm.traverseSchema(schema, function(prop, path) {
if (angular.isDefined(prop['default'])) {
var val = sfSelect(path, scope.model);
if (angular.isUndefined(val)) {
sfSelect(path, scope.model, prop['default']);
}
}
});
}
});
}
};
}
]);
angular.module('schemaForm').directive('schemaValidate', ['sfValidator', function(sfValidator) {
return {
restrict: 'A',
scope: false,
// We want the link function to be *after* the input directives link function so we get access
// the parsed value, ex. a number instead of a string
priority: 1000,
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
//Since we have scope false this is the same scope
//as the decorator
scope.ngModel = ngModel;
var error = null;
var getForm = function() {
if (!form) {
form = scope.$eval(attrs.schemaValidate);
}
return form;
};
var form = getForm();
// Validate against the schema.
// Get in last of the parses so the parsed value has the correct type.
if (ngModel.$validators) { // Angular 1.3
ngModel.$validators.schema = function(value) {
var result = sfValidator.validate(getForm(), value);
error = result.error;
return result.valid;
};
} else {
// Angular 1.2
ngModel.$parsers.push(function(viewValue) {
form = getForm();
//Still might be undefined
if (!form) {
return viewValue;
}
var result = sfValidator.validate(form, viewValue);
if (result.valid) {
// it is valid
ngModel.$setValidity('schema', true);
return viewValue;
} else {
// it is invalid, return undefined (no model update)
ngModel.$setValidity('schema', false);
error = result.error;
return undefined;
}
});
}
// Listen to an event so we can validate the input on request
scope.$on('schemaFormValidate', function() {
if (ngModel.$validate) {
ngModel.$validate();
if (ngModel.$invalid) { // The field must be made dirty so the error message is displayed
ngModel.$dirty = true;
ngModel.$pristine = false;
}
} else {
ngModel.$setViewValue(ngModel.$viewValue);
}
});
//This works since we now we're inside a decorator and that this is the decorators scope.
//If $pristine and empty don't show success (even if it's valid)
scope.hasSuccess = function() {
return ngModel.$valid && (!ngModel.$pristine || !ngModel.$isEmpty(ngModel.$modelValue));
};
scope.hasError = function() {
return ngModel.$invalid && !ngModel.$pristine;
};
scope.schemaError = function() {
return error;
};
}
};
}]); | Korkki/seo | project/static/js/vendor/schema-form.js | JavaScript | mit | 46,226 |
export * from "./src/worldmap";
import * as ngworldmap from "./src/worldmap";
export default ngworldmap; | synarque/ng-worldmap | ng-worldmap/index.ts | TypeScript | mit | 105 |
using System;
using System.Collections.Generic;
using System.Net;
using Microsoft.TeamFoundation.Client;
namespace TfsMigrationTool.Utils
{
public static class ServiceFactory
{
private static readonly Dictionary<Type, object> ServiceCache = new Dictionary<Type, object>();
private static readonly NetworkCredential Credentials;
static ServiceFactory()
{
Credentials = TfsAuthorizer.Authenticate();
}
public static T Create<T>()
{
object service;
if (!ServiceCache.TryGetValue(typeof (T), out service))
{
var projectCollection = new TfsTeamProjectCollection(Config.TfsCollectionUrl, Credentials);
service = projectCollection.GetService<T>();
ServiceCache.Add(typeof (T), service);
}
return (T) service;
}
}
} | davidich/TfsMigrationTool | TfsMigrationTool/Utils/ServiceFactory.cs | C# | mit | 936 |