answer stringlengths 15 1.25M |
|---|
#![feature(test)]
extern crate test;
extern crate tinysegmenter;
use std::io::prelude::*;
use std::fs::File;
use test::Bencher;
#[bench]
fn run(b: &mut Bencher) {
let mut f =
File::open("benchmark/timemachineu8j.txt")
.expect("Failed to read a benchmark text.");
let mut s = String::new();
let _ = f.read_to_string(&mut s);
b.iter(|| tinysegmenter::tokenize(&s));
} |
<?php
require_once('./src/Location.inc.php');
$LocPar = new LocationParams();
$LocPar = $LocPar->setCity('Phagwara, Punjab');
try{
$Loc = new Location($LocPar);
$Loc->setRequestType(Location::BY_ADDRESS);
$Loc->init();
$Result = $Loc->getResult();
}catch(Exception $e){
echo $e->getMessage();
}finally{
if (isset($Result)) {
var_dump(@$Result);
}
}
?> |
This is a client for signing certificates with an ACME-server (currently only provided by letsencrypt) implemented as a relatively simple bash-script.
It uses the `openssl` utility for everything related to actually handling keys and certificates, so you need to have that installed.
Other dependencies are (for now): curl, sed
Perl no longer is a dependency.
The only remaining perl code in this repository is the script you can use to convert your existing letsencrypt-keyfile into something openssl (and this script) can read.
Current features:
- Signing of a list of domains
- Renewal if a certificate is about to expire
- Certificate revocation
Please keep in mind that this software and even the acme-protocol are relatively young and may still have some unresolved issues.
Feel free to report any issues you find with this script or contribute by submitting a pullrequest.
## Usage:
text
Usage: ./letsencrypt.sh [-h] [command [argument]] [parameter [argument]] [parameter [argument]] ...
Default command: help
Commands:
--cron (-c) Sign/renew non-existant/changed/expiring certificates.
--revoke (-r) path/to/cert.pem Revoke specified certificate
--help (-h) Show help text
--env (-e) Output configuration variables for use in other scripts
Parameters:
--domain (-d) domain.tld Use specified domain name instead of domains.txt, use multiple times for certificate with SAN names
--force (-x) force renew of certificate even if it is longer valid than value in RENEW_DAYS
--config (-f) path/to/config.sh Use specified config file
--privkey (-p) path/to/key.pem Use specified private key instead of account key (useful for revocation)
domains.txt
The file `domains.txt` should have the following format:
text
example.com www.example.com
example.net www.example.net wiki.example.net
This states that there should be two certificates `example.com` and `example.net`,
with the other domains in the corresponding line being their alternative names.
$WELLKNOWN / challenge-response
Boulder (acme-server) is looking for challenge responses under your domain in the `.well-known/acme-challenge` directory
This script uses `http-01`-type verification (for now) so you need to have the that directory available over normal http (no ssl).
A full URL would look like `http://example.org/.well-known/acme-challenge/<API key>`.
An example setup to get this to work would be:
nginx.conf:
location /.well-known/acme-challenge {
alias /var/www/letsencrypt;
}
config.sh:
bash
WELLKNOWN="/var/www/letsencrypt"
An alternative to setting the WELLKNOWN variable would be to create a symlink to the default location next to the script (or BASEDIR):
`ln -s /var/www/letsencrypt .acme-challenges`
## Import
import-account.pl
This perl-script can be used to import the account key from the original letsencrypt client.
You should copy `private_key.json` to the same directory as the script.
The json-file can be found in a subdirectory of `/etc/letsencrypt/accounts/acme-v01.api.letsencrypt.org/directory`.
Usage: `./import-account.pl`
import-certs.sh
This script can be used to import private keys and certificates created by the original letsencrypt client.
By default it expects the certificates to be found under `/etc/letsencrypt`, which is the default output directory of the original client.
You can change the path by setting LETSENCRYPT in your config file: ```LETSENCRYPT="/etc/letsencrypt"```.
Usage: `./import-certs.sh` |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>AntSim unittests</title>
<link rel="stylesheet" href="./js/external/qunit/qunit-2.4.0.css">
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="./js/external/qunit/qunit-2.4.0.js"></script>
<script src="./js/external/qunit/qunit-assert-close.js"></script>
<script src="./js/external/require.js"></script>
<script>
// QUnit is not yet loaded here
QUnit.config.hidepassed = true;
</script>
<script src="./js/globals.js"></script>
<script src="./js/test/action.js"></script>
<script src="./js/test/collider.js"></script>
<script src="./js/test/globals.js"></script>
</body>
</html> |
// <auto-generated>
// Auto-generated by StoneAPI, do not modify.
// </auto-generated>
namespace Dropbox.Api.Team
{
using sys = System;
using col = System.Collections.Generic;
using re = System.Text.RegularExpressions;
using enc = Dropbox.Api.Stone;
<summary>
<para>Argument for selecting a group and a list of users.</para>
</summary>
public class <API key>
{
#pragma warning disable 108
<summary>
<para>The encoder instance.</para>
</summary>
internal static enc.StructEncoder<<API key>> Encoder = new <API key>();
<summary>
<para>The decoder instance.</para>
</summary>
internal static enc.StructDecoder<<API key>> Decoder = new <API key>();
<summary>
<para>Initializes a new instance of the <see cref="<API key>" />
class.</para>
</summary>
<param name="group">Specify a group.</param>
<param name="users">A list of users that are members of <paramref name="group"
/>.</param>
public <API key>(GroupSelector @group,
UsersSelectorArg users)
{
if (@group == null)
{
throw new sys.<API key>("@group");
}
if (users == null)
{
throw new sys.<API key>("users");
}
this.Group = @group;
this.Users = users;
}
<summary>
<para>Initializes a new instance of the <see cref="<API key>" />
class.</para>
</summary>
<remarks>This is to construct an instance of the object when
deserializing.</remarks>
[sys.ComponentModel.EditorBrowsable(sys.ComponentModel.<API key>.Never)]
public <API key>()
{
}
<summary>
<para>Specify a group.</para>
</summary>
public GroupSelector Group { get; protected set; }
<summary>
<para>A list of users that are members of <see cref="Group" />.</para>
</summary>
public UsersSelectorArg Users { get; protected set; }
#region Encoder class
<summary>
<para>Encoder for <see cref="<API key>" />.</para>
</summary>
private class <API key> : enc.StructEncoder<<API key>>
{
<summary>
<para>Encode fields of given value.</para>
</summary>
<param name="value">The value.</param>
<param name="writer">The writer.</param>
public override void EncodeFields(<API key> value, enc.IJsonWriter writer)
{
WriteProperty("group", value.Group, writer, global::Dropbox.Api.Team.GroupSelector.Encoder);
WriteProperty("users", value.Users, writer, global::Dropbox.Api.Team.UsersSelectorArg.Encoder);
}
}
#endregion
#region Decoder class
<summary>
<para>Decoder for <see cref="<API key>" />.</para>
</summary>
private class <API key> : enc.StructDecoder<<API key>>
{
<summary>
<para>Create a new instance of type <see cref="<API key>" />.</para>
</summary>
<returns>The struct instance.</returns>
protected override <API key> Create()
{
return new <API key>();
}
<summary>
<para>Set given field.</para>
</summary>
<param name="value">The field value.</param>
<param name="fieldName">The field name.</param>
<param name="reader">The json reader.</param>
protected override void SetField(<API key> value, string fieldName, enc.IJsonReader reader)
{
switch (fieldName)
{
case "group":
value.Group = global::Dropbox.Api.Team.GroupSelector.Decoder.Decode(reader);
break;
case "users":
value.Users = global::Dropbox.Api.Team.UsersSelectorArg.Decoder.Decode(reader);
break;
default:
reader.Skip();
break;
}
}
}
#endregion
}
} |
"""
For using OpenGL to render to an off screen buffer
Ref:
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from OpenGL.GL import *
from OpenGL.raw.GL.VERSION import GL_1_1,GL_1_2, GL_3_0
class OffScreenRender(object):
def __init__(self, width=1920, height=1080):
super(OffScreenRender, self).__init__()
self._width = width
self._height = height
self._fbo = None
self._render_buf = None
self._init_fbo()
self._oldViewPort = (ctypes.c_int*4)*4
def __enter__(self):
self.activate()
def __exit__(self, type, value, traceback):
self.deactivate()
return False
def __del__(self):
self._cleanup()
super(OffScreenRender, self).__del__()
def activate(self):
glBindFramebuffer(GL_FRAMEBUFFER, self._fbo)
self._oldViewPort = glGetIntegerv(GL_VIEWPORT)
side = min(self._width, self._height)
glViewport(int((self._width - side)/2), int((self._height - side)/2), side, side)
def deactivate(self):
glBindFramebuffer(GL_FRAMEBUFFER, 0)
glViewport(*self._oldViewPort)
def read_into(self, buf, x=0, y=0, width=None, height=None):
glReadBuffer(<API key>)
width = width is not None or self._width,
height = height is not None or self._height,
glReadPixels(0,
0,
width,
height,
GL_BGRA,
#GL_RGBA, alot faster, but incorrect :()
GL_UNSIGNED_BYTE,
buf)
#outputType=None)
#GL_1_1.glReadPixels(
def get_size(self):
return self._width*self._height*4
def _init_fbo(self, depth=True):
fbo = glGenFramebuffers(1)
self._fbo = fbo
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo)
render_buf = glGenRenderbuffers(1)
self._render_buf = render_buf
glBindRenderbuffer(GL_RENDERBUFFER, render_buf)
<API key>(GL_RENDERBUFFER, GL_RGBA8, self._width, self._height)
<API key>(GL_DRAW_FRAMEBUFFER, <API key>, GL_RENDERBUFFER, render_buf)
if depth:
depth = glGenRenderbuffers(1)
self._depth = depth
glBindRenderbuffer(GL_RENDERBUFFER, depth)
<API key>(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, self._width, self._height)
glBindRenderbuffer(GL_RENDERBUFFER, 0)
<API key>(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth)
assert <API key> == <API key>(GL_DRAW_FRAMEBUFFER)
glBindFramebuffer(GL_FRAMEBUFFER, 0);
def _cleanup(self):
if self._fbo is not None:
<API key>(self._fbo)
self._fbo = None
if self._render_buf is not None:
<API key>(self._render_buf)
self._render_buf = None |
from <API key>.web.Home_Auto import app
def run_webserver():
app.run(host='0.0.0.0', port=9000, use_reloader=False) |
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace Onliner.iOS.Tabbed
{
public class Application
{
// This is the main entry point of the application.
static void Main (string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
UIApplication.Main (args, null, "AppDelegate");
}
}
} |
(function() {
'use strict';
var express = require('express');
var router = express.Router();
// var mongojs = require('mongojs');
// var db = mongojs('myApp', ['myCollections']);
router.get('/', function(req, res) {
res.render('dist/index');
});
module.exports = router;
}()); |
/*
* Echo server for a single client
*/
import "net"
import "cli"
import "log"
import "threads"
int main()
{
const char *addr = "0.0.0.0:7000";
conn_t *l = net_listen("tcp", addr);
if(!l) {
fatal("listen failed: %s", net_error());
}
logmsg("listening at %s", addr);
while(1) {
conn_t *s = net_accept(l);
if(!s) {
err("accept error: %s", net_error());
continue;
}
thr_t *t = thr_new(process_client, s);
assert(t);
thr_detach(t);
}
net_close(l);
return 0;
}
void *process_client(void *arg)
{
conn_t *c = (conn_t *) arg;
logmsg("%s connected", net_addr(c));
char buf[256] = {0};
while(1) {
int len = net_read(c, buf, sizeof(buf));
if(len == -1) {
err("read error");
break;
}
if(len == 0) {
break;
}
if(net_write(c, buf, len) < len) {
err("write error");
break;
}
}
logmsg("%s disconnected", net_addr(c));
net_close(c);
return NULL;
} |
# The default settings for new alerts
Alert_defaults = { email: true, show: true }
# This is a class which will facilitate the generation of Alerts and the automation of sending out alert emails.
class Alerter
class << self
require 'pony'
# This fxn will add an alert to the database
# @param [String] [Hash] Takes a message string, and also accepts Hash keys which will modify the default behavior as defined in the Alert_defaults constant {Alert_defaults}
def create(string, opts = {})
@@opts = Alert_defaults.merge(opts)
if @@opts != Alert_defaults
options = @@opts.to_s.gsub(/\{|\}/, '')
Alert.create({:description => string}.merge(options))
else
Alert.create(:description => string)
end
end
# This fxn will delete the specified entry in the database
# @param [Integer] a number which represents the id for the Alert to be destroyed
def delete(num)
Alert.get(num).destroy
end
# This fxn will use the "Pony" gem to send out an alert email to the specified address. This fxn will include all the alert text for every entry in the database for which the email column has a true value. Once the email is sent, that collection of DB Alerts will have the email column altered to ensure each alert is only sent once.
def send_email(email_address, subject = "Generic QC Alerts", admin_email = "Administrator@YourLocalMetricSite.changethis")
body_text = "Attn: According to the filter settings you've configured, we found the following alerts while running on ## FILE NAME? ##"
to_send = Alert.all(:email => true)
to_send.each do |alert|
body_text << <API key>(alert)
end
body_text << "For more information, visit the ## WEBADDRESS ## "
# Send the email
Pony.mail(to: email_address, from: admin_email, subject: subject, :body => body_text)
to_send.update(:email => false)
end
# This function controls the output format for the alert message.
# @param [Alert] Alert class
# @return Nothing
def <API key>(alert)
"At #{alert.created_at} we found #{alert.description}"
end
end # class << self
end # Alert |
package O2::Dispatch::ModPerlGlobals::Context;
use strict;
use Tie::Scalar;
our @ISA = qw(Tie::StdScalar);
sub TIESCALAR {
my ($className) = @_;
return bless {}, $className;
}
sub FETCH {
my ($obj) = @_;
my $context = $obj->{ $ENV{O2REQUESTID} };
if (!$context) {
require O2::Context;
$context = O2::Context->new();
$obj->STORE($context);
}
return $context;
}
sub STORE {
my ($obj, $context) = @_;
$obj->{ $ENV{O2REQUESTID} } = $context;
}
sub DESTROY {
my ($obj) = @_;
}
1; |
import moment from 'moment';
import {Factory} from 'ember-cli-mirage';
export default Factory.extend({
createdAt() { return moment().toISOString(); },
createdBy: 1,
name(i) { return `Label ${i}`; },
slug(i) { return `label-${i}`; },
updatedAt() { return moment().toISOString(); },
updatedBy: 1,
count() {
// this gets updated automatically by the label serializer
return {members: 0};
}
}); |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StardewValley.Objects;
namespace StardewValleyMP.States
{
// Are these even in the game? There isn't really any reference to them, and I don't remember
// anything you use a key to unlock. I certainly don't see any in my save file.
public class DoorState : State
{
public int motion;
public bool locked;
public DoorState(Door door)
{
motion = door.doorMotion;
locked = door.locked;
}
public override bool <API key>(State obj)
{
DoorState state = obj as DoorState;
if (state == null) return false;
if ( motion != state.motion ) return true;
if ( locked != state.locked ) return true;
return false;
}
}
} |
package wolf.node;
import wolf.analysis.*;
@SuppressWarnings("nls")
public final class <API key> extends PFunction
{
private PNativeUnaryOp _nativeUnaryOp_;
private TLParen _lParen_;
private PArg _arg_;
private TRParen _rParen_;
public <API key>()
{
// Constructor
}
public <API key>(
@SuppressWarnings("hiding") PNativeUnaryOp _nativeUnaryOp_,
@SuppressWarnings("hiding") TLParen _lParen_,
@SuppressWarnings("hiding") PArg _arg_,
@SuppressWarnings("hiding") TRParen _rParen_)
{
// Constructor
setNativeUnaryOp(_nativeUnaryOp_);
setLParen(_lParen_);
setArg(_arg_);
setRParen(_rParen_);
}
@Override
public Object clone()
{
return new <API key>(
cloneNode(this._nativeUnaryOp_),
cloneNode(this._lParen_),
cloneNode(this._arg_),
cloneNode(this._rParen_));
}
@Override
public void apply(Switch sw)
{
((Analysis) sw).<API key>(this);
}
public PNativeUnaryOp getNativeUnaryOp()
{
return this._nativeUnaryOp_;
}
public void setNativeUnaryOp(PNativeUnaryOp node)
{
if(this._nativeUnaryOp_ != null)
{
this._nativeUnaryOp_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._nativeUnaryOp_ = node;
}
public TLParen getLParen()
{
return this._lParen_;
}
public void setLParen(TLParen node)
{
if(this._lParen_ != null)
{
this._lParen_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._lParen_ = node;
}
public PArg getArg()
{
return this._arg_;
}
public void setArg(PArg node)
{
if(this._arg_ != null)
{
this._arg_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._arg_ = node;
}
public TRParen getRParen()
{
return this._rParen_;
}
public void setRParen(TRParen node)
{
if(this._rParen_ != null)
{
this._rParen_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._rParen_ = node;
}
@Override
public String toString()
{
return ""
+ toString(this._nativeUnaryOp_)
+ toString(this._lParen_)
+ toString(this._arg_)
+ toString(this._rParen_);
}
@Override
void removeChild(@SuppressWarnings("unused") Node child)
{
// Remove child
if(this._nativeUnaryOp_ == child)
{
this._nativeUnaryOp_ = null;
return;
}
if(this._lParen_ == child)
{
this._lParen_ = null;
return;
}
if(this._arg_ == child)
{
this._arg_ = null;
return;
}
if(this._rParen_ == child)
{
this._rParen_ = null;
return;
}
throw new RuntimeException("Not a child.");
}
@Override
void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild)
{
// Replace child
if(this._nativeUnaryOp_ == oldChild)
{
setNativeUnaryOp((PNativeUnaryOp) newChild);
return;
}
if(this._lParen_ == oldChild)
{
setLParen((TLParen) newChild);
return;
}
if(this._arg_ == oldChild)
{
setArg((PArg) newChild);
return;
}
if(this._rParen_ == oldChild)
{
setRParen((TRParen) newChild);
return;
}
throw new RuntimeException("Not a child.");
}
} |
import pytest
pytestmark = pytest.mark.page('font.html')
class TestFont(object):
def <API key>(self, browser):
assert browser.font(index=0).exists
def <API key>(self, browser):
assert browser.font(index=0).color == '#ff00ff'
def <API key>(self, browser):
assert browser.font(index=0).face == 'Helvetica'
def <API key>(self, browser):
assert browser.font(index=0).size == '12'
def <API key>(self, browser):
assert len(browser.fonts()) == 1 |
Credits = function (game) {
this.game = game;
this.screenName = 'creditScreen';
this.image = 'assets/screenshots/credits.png';
};
Credits.prototype.preload = function(){
game.load.image(this.screenName, this.image);
};
Credits.prototype.create = function() {
var bg = game.add.sprite(0, 0, this.screenName);
game.input.onDown.add(function() {
var fadeout = game.add.tween(bg).to( { alpha: 0 }, 500, Phaser.Easing.Linear.None, true, 0, 0, true);
fadeout.onComplete.add(function() {
game.state.start('menu', Menu);
});
});
var keySelect = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
keySelect.onDown.add(function () {
game.state.start('menu');
});
}; |
<?php
/*$app->get('/', function () use ($app) {
return $app->version();
});*/
$app->get('products', 'ProductsController@index');
$app->get('products/{id}', 'ProductsController@show');
$app->post('products', 'ProductsController@create');
$app->get('stores', 'StoresController@index');
$app->get('reviews', 'ReviewsController@index'); |
import * as React from 'react';
export interface FooterProps {
children?: React.ReactNode;
className?: string;
showDivider?: boolean;
noPadding?: boolean;
}
export default class Footer extends React.PureComponent<FooterProps> {} |
package sample;
import javax.faces.bean.ManagedBean;
@ManagedBean(name="welcomeBean")
public class IndexPage {
private String greeting = "Hello, World";
/**
* @return the greeting
*/
public String getGreeting() {
return greeting;
}
/**
* @param greeting the greeting to set
*/
public void setGreeting(final String greeting) {
this.greeting = greeting;
}
} |
CMS.ui.attach.fileUpload = function(){
var all_input = $('input.file-upload');
all_input.each(function(){
var input = $(this);
input.change(function(){
var el = $(this);
var val = $(this).val();
var bar = $('.upload-bar');
var preview_area = $(this).parents('.file-upload-wrapper').find('.preview .preview-new');
if(!val)
return;
bar.empty().html('<div class="progress"><div class="bar"></div></div>');
bar = $('.upload-bar .bar');
$.upload5(CMS.settings.web_root + 'file_upload',this,function(data,code){
if(code != 200){
CMS.ui.modal('Не удалось загрузить файл');
return;
}
data = JSON.parse(data);
if(!data.status){
CMS.ui.modal('Загрузка файла не удалась. Попробуйте еще раз.');
return;
}
if(data.fmessage)
CMS.ui.modal(data.fmessage);
if(data.message)
CMS.ui.modal(Base64.decode(data.message));
preview_area.html(data.data);
el.val('');
},function(percent,bu,bt){
bar.css('width',percent + '%');
bu = parseInt(bu/1024);
bt = parseInt(bt/1024);
bar.text(bu + 'кб / ' + bt + 'кб');
});
});
});
$('.delete-file').live('click',function(){
var link = $(this).parent().find('a.file-upload-item');
$(this).after('<input type="hidden" name="delete_file[]" value="'+ link.attr('href') + '" />');
link.parent().css({opacity:0.5});
});
} |
#include "deleterowcommand.h"
DeleteRowCommand::DeleteRowCommand(StatsTableModel &tableModel, std::set<int> deletedRows, QUndoCommand * parent)
:QUndoCommand(parent), m_tableModel(tableModel), m_deletedRows(deletedRows)
{
}
void DeleteRowCommand::redo()
{
auto model = m_tableModel.statsModel();
StatsKeyValueModel newModel;
for (size_t i = 0; i < model.size(); ++i)
{
if (m_deletedRows.count(i))
{
m_restoredValues[i]= std::make_pair(model.key(i), model.value(i));
continue;
}
newModel.append(model.key(i), model.value(i));
}
m_tableModel.setStatsModel(newModel);
}
void DeleteRowCommand::undo()
{
auto model = m_tableModel.statsModel();
StatsKeyValueModel newModel;
std::map<int, t_row>::iterator it = m_restoredValues.begin();
for (size_t i = 0; i < model.size(); ++i)
{
if (m_restoredValues.count(i))
{
newModel.append(it->second.first, it->second.second);
++it;
}
newModel.append(model.key(i), model.value(i));
}
while (it != m_restoredValues.end())
{
newModel.append(it->second.first, it->second.second);
++it;
}
m_tableModel.setStatsModel(newModel);
} |
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<meta name="<API key>" content="yes">
<meta name="<API key>" content="yes">
<title>KISSY Decorated Simple Tree</title>
<link href="/kissy/build/css/dpl/base.css" rel="stylesheet"/>
<link href="../../../button/assets/dpl.css" rel="stylesheet"/>
<link href="../../assets/dpl.css" rel="stylesheet"/>
</head>
<body>
<div class="container">
<h1>KISSY Decorated Simple Tree</h1>
<a href="javascript:void(0)" id="expandAll" class="ks-button"></a>
<a href="javascript:void(0)" id="collapseAll" class="ks-button"></a>
<div id="treeContainer" style="width: 200px;margin: 20px 0;">
<div id='root' class="ks-tree">
<div class="ks-tree-node-row ks-tree-row">
<div class="<API key> ks-tree-expand-icon"></div>
<div class="ks-tree-node-icon ks-tree-icon"></div>
<span class="<API key> ks-tree-content"></span>
</div>
<div class="<API key> ks-tree-children" >
<div class="ks-tree-node">
<div class="ks-tree-node-row">
<div class="<API key>"></div>
<div class="ks-tree-node-icon"></div>
<span class="<API key>"></span>
</div>
<div class="<API key>">
<div class="ks-tree-node">
<div class="ks-tree-node-row">
<div class="<API key>"></div>
<div class="ks-tree-node-icon"></div>
<span class="<API key>"></span>
</div>
<div class="<API key>"></div>
</div>
<div class="ks-tree-node ks-tree-node-folder">
<div class="ks-tree-node-row">
<div class="<API key>"></div>
<div class="ks-tree-node-icon"></div>
<span class="<API key>"></span>
</div>
<div class="<API key>"></div>
</div>
</div>
</div>
<div class="ks-tree-node">
<div class="ks-tree-node-row">
<div class="<API key>"></div>
<div class="ks-tree-node-icon"></div>
<span class="<API key>"></span>
</div>
<div class="<API key>"></div>
</div>
</div>
</div>
</div>
<hr/>
<script src="/kissy/build/seed-debug.js"></script>
<script src="/gen/dev.js"></script>
<script>
KISSY.use("tree,node", function (S, Tree,$) {
var tree = new Tree({
expanded: true,
// showRootNode:false,
srcNode: "#root"
});
tree.render();
tree.on("click", function (e) {
S.log("action : " + e.target.get("content"));
});
$("#expandAll").on("click", function () {
tree.expandAll();
});
$("#collapseAll").on("click", function () {
tree.collapseAll();
});
});
</script>
</div>
</body>
</html> |
var config = require('../../config');
var express = require('express');
module.exports = function (app) {
// ## Vendor Middleware
app.use(express.compress());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.cookieSession(config.session));
app.use(express.csrf());
app.use(express.static(__dirname + '/../../../public'));
// ## App Middleware
app.use(require('./cache-buster'));
app.use(require('./template-helpers'));
app.use(require('./url-normalizer'));
}; |
title: "Remember kids, always wear your safety belt"
excerpt: "PaperFaces portrait of @pedroloo drawn with Paper for iOS on an iPad."
image:
path: &image /assets/images/<API key>.jpg
feature: *image
thumbnail: /assets/images/<API key>.jpg
categories: [paperfaces]
tags: [portrait, illustration, Paper for iOS]
PaperFaces portrait of [@pedroloo](https://twitter.com/pedroloo).
* **Stylus:** None
* **Application:** [Paper by FiftyThree for iOS](http:
{% figure caption:"Work in progress screenshots (Paper for iOS)." class:"gallery-2-col" %}
[](/assets/images/<API key>.jpg)
[](/assets/images/<API key>.jpg)
[](/assets/images/<API key>.jpg)
[](/assets/images/<API key>.jpg)
{% endfigure %} |
package com.epita.mti.datemine.tools.auth;
import java.util.UUID;
/**
* @author leduc_t
*/
public class AuthToken {
/**
* The token string.
*/
private String token;
/**
* The account id.
*/
private long accountID = 0;
/**
* The creation time in millisecond.
*/
private long timeCreated;
public AuthToken(long accountID) {
this.accountID = accountID;
this.token = UUID.randomUUID().toString();
this.timeCreated = System.currentTimeMillis();
}
public AuthToken(String token, long accountID, long timeCreated) {
this.token = token;
this.accountID = accountID;
this.timeCreated = timeCreated;
}
public String getToken() {
return token;
}
public long getAccountID() {
return accountID;
}
public long getTimeCreated() {
return timeCreated;
}
} |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Testj extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('User_model');
$this->load->model('Feed_model');
//$this->output->set_content_type('application/json');
}
public function TestUser()
{
//$this->output->set_content_type('application/json');
if(true==$this->User_model->register("email","password111")){
echo "all_userdata:<\br>";
var_dump($this->session->all_userdata());
}
echo "login : expected true \n";
var_dump( $this->User_model->login("email","password111") );
echo "logout,expected:no uid \n";
$this->User_model->logout();
var_dump($this->session->all_userdata());
}
public function TestFeed($uid){
$this->User_model->login("222","54250"); |
<div layout="column" ng-controller="tiposInserirCtrl" ng-init="consultar()">
<md-toolbar>
<div class="md-toolbar-tools">
<md-button ng-click="toggleLeft()" class="md-button" hide-gt-md="" aria-label="Menu">
<md-icon md-svg-icon="img/icons/menu.svg"></md-icon>
</md-button>
<h2>
<span>{{name}}</span>
</h2>
<md-button class="md-icon-button botao-font-au" aria-label="Aumentar/Diminuir Fonte" onclick="aumentaFonte()">
<md-tooltip md-direction="left">Botão para aumentar de tamanho de Fonte</md-tooltip>
<md-icon md-svg-icon="./img/<API key>.svg"></md-icon>
</md-button>
<md-button class="md-icon-button <API key>" aria-label="Auto contraste" onclick="aplicaAutoContraste()">
<md-tooltip md-direction="left">Botão para ajuste de Auto Contraste</md-tooltip>
<md-icon md-svg-icon="./img/<API key>.svg"></md-icon>
</md-button>
<md-button class="md-icon-button botao-font-dm" aria-label="Aumentar/Diminuir Fonte" onclick="diminuiFonte()">
<md-tooltip md-direction="left">Botão para diminuir de tamanho de Fonte</md-tooltip>
<md-icon md-svg-icon="./img/<API key>.svg"></md-icon>
</md-button>
</div>
</md-toolbar>
<div class="spaceToolbar"></div>
<md-content class="md-padding">
<md-card>
<md-card-content>
<form name="form" ng-submit="inserir()">
<md-input-container class="md-block">
<label>Nome</label>
<input required ng-model="tipos.nome" type="text">
</md-input-container>
<md-input-container class="md-block">
<label>Valor por hora</label>
<input required ng-model="tipos.valorporhora" ui-money-mask="2" currency-symbol="R$">
</md-input-container>
<md-input-container class="md-block">
<label>Valor por mês</label>
<input required ng-model="tipos.valorpormes" ui-money-mask="2" currency-symbol="R$">
</md-input-container>
<md-button type="submit" value="submit" ng-disabled="form.$invalid" class="md-raised md-primary right">Salvar</md-button>
<md-button type="button" class="md-raised right" ng-click="cancelar()">Cancelar</md-button>
</form>
</md-card-content>
</md-card>
</md-content>
</div> |
import assert from 'power-assert';
import lib from '../src';
describe('sample-package', () => {
it('is defined', () => {
assert(lib);
});
}); |
# <API key>: true
class <API key> < ActiveRecord::Migration[6.0]
def change
remove_index :loyalty_points, :character_id
end
end |
<!DOCTYPE html>
<html>
<head>
<title>Login page</title>
<link href="style/main.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" href="favicon.ico">
<link rel="apple-touch-icon" href="meta/apple-touch-icon.png">
<meta name="<API key>" content="yes">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0, maximum-scale=1, user-scalable=no, minimal-ui">
</head>
<body>
<div class="container">
<div class="heading">
<h1 class="title">2048</h1>
<div class="scores-container">
<div class="best-container">0</div>
<div id="registered">coucou</div>
</div>
</div>
<div class="above-game">
<p class="game-intro">Join the numbers and get to the <strong>2048 tile!</strong></p>
<a class="restart-button" href="game.html">Start Game</a>
</div>
<div class="">
<table>
<tr>
<th>User</th>
<th>Score</th>
</tr>
<tr>
<td>Julien</td>
<td>4242</td>
</tr>
<tr>
<td>Bastien</td>
<td>3232</td>
</tr>
</table>
</div>
</div>
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript">
document.addEventListener("deviceready", deviceReady, true);
function deviceReady() {
var weixin = cordova.require("cordova/plugin/weixin-phonegap");
weixin.registerApp("wx9284e4364c980ec2");
}
</script>
</body>
</html> |
module Greedy
class Stream
BASE_PATH = "stream/contents/"
CHANGE_STATE_PATH = "user/-/state/com.google/edit-tag"
attr_accessor :entries, :feeds, :last_update_token
# Instantiate a new Google Reader stream of entries based on a given entry state
def initialize(username, password, in_state = nil, in_options = {})
@connection = Greedy::Connection.new(username, password, in_options[:connection_name] || "Greedy::Stream")
reset!(in_state, in_options)
end
# Wipe the stream and reinitialize with the given state
def reset!(in_state = nil, in_options = {})
@state = in_state || @state || Greedy::Entry::States::READING_LIST
@options = in_options
@entries = pull!(endpoint(@state), @options)
@feeds = distill_feeds_from @entries
end
# Continue fetching earlier entries from where the last request left off
def continue!
return [] unless @continuation_token
new_entries = pull!(endpoint(@state), @options.merge(:c => @continuation_token))
@entries.concat new_entries
new_entries
end
# Continue fetching later entries from where the last request left off
def update!
new_entries = pull!(endpoint(@state), @options.merge(:ot => @last_update_token))
@entries = new_entries + @entries
new_entries
end
def change_state_for(entry, state)
@connection.post((BASE_PATH + CHANGE_STATE_PATH), { :a => state,
:i => entry.google_item_id,
:s => entry.feed.google_feed_id })
end
def share_all!
@entries.each { |e| e.share! }
end
def mark_all_as_read!
@entries.each { |e| e.mark_as_read! }
end
protected
# Retrieve entries based on the provided path and options
def pull! path, options
hash = @connection.fetch(path, options) || { 'items' => [] }
@continuation_token = hash['continuation'] unless options[:ot]
@last_update_token = hash['updated'] unless options[:c]
hash["items"].collect do |entry_hash|
Greedy::Entry.new entry_hash, self
end
end
# Accepts an array of entries and sets an array of feeds for the stream
def distill_feeds_from entry_list
feeds = entry_list.collect { |e| e.feed }.uniq
entry_list.each do |e|
f = feeds.find { |f| f.google_feed_id == e.feed.google_feed_id }
f.entries.push(e) if f
f.entries.uniq!
end
feeds
end
# Determine the unique URL segment for a given state
def endpoint(state)
File.join BASE_PATH, state
end
end
end |
// Name: pen.cpp
// Purpose:
// Id: $Id: pen.cpp,v 1.11 2004/05/23 20:52:46 JS Exp $
// Licence: wxWindows licence
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma implementation "pen.h"
#endif
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#include "wx/pen.h"
#include "wx/bitmap.h"
#include "wx/colour.h"
#include "wx/mgl/private.h"
// wxPen
class wxPenRefData: public wxObjectRefData
{
public:
wxPenRefData();
wxPenRefData(const wxPenRefData& data);
int m_width;
int m_style;
wxColour m_colour;
wxBitmap m_stipple;
pixpattern24_t m_pixPattern;
// not used by wxMGL, but we want to preserve values
int m_joinStyle;
int m_capStyle;
int m_countDashes;
wxDash *m_dash;
};
wxPenRefData::wxPenRefData()
{
m_width = 1;
m_style = wxSOLID;
m_joinStyle = wxJOIN_ROUND;
m_capStyle = wxCAP_ROUND;
m_dash = (wxDash*) NULL;
m_countDashes = 0;
int x, y, c;
for (y = 0; y < 8; y++)
for (x = 0; x < 8; x++)
for (c = 0; c < 3; c++)
m_pixPattern.p[x][y][c] = 0;
}
wxPenRefData::wxPenRefData(const wxPenRefData& data)
{
m_style = data.m_style;
m_width = data.m_width;
m_joinStyle = data.m_joinStyle;
m_capStyle = data.m_capStyle;
m_colour = data.m_colour;
m_countDashes = data.m_countDashes;
m_dash = data.m_dash;
m_stipple = data.m_stipple;
int x, y, c;
for (y = 0; y < 8; y++)
for (x = 0; x < 8; x++)
for (c = 0; c < 3; c++)
m_pixPattern.p[x][y][c] = data.m_pixPattern.p[x][y][c];
}
#define M_PENDATA ((wxPenRefData *)m_refData)
<API key>(wxPen,wxGDIObject)
wxPen::wxPen(const wxColour &colour, int width, int style)
{
m_refData = new wxPenRefData();
M_PENDATA->m_width = width;
M_PENDATA->m_style = style;
M_PENDATA->m_colour = colour;
}
wxPen::wxPen(const wxBitmap& stipple, int width)
{
wxCHECK_RET( stipple.Ok(), _T("invalid bitmap") );
wxCHECK_RET( stipple.GetWidth() == 8 && stipple.GetHeight() == 8,
_T("stipple bitmap must be 8x8") );
m_refData = new wxPenRefData();
M_PENDATA->m_width = width;
M_PENDATA->m_style = wxSTIPPLE;
M_PENDATA->m_stipple = stipple;
<API key>(stipple, &(M_PENDATA->m_pixPattern), NULL);
}
wxPen::wxPen(const wxPen& pen)
{
Ref(pen);
}
wxPen& wxPen::operator = (const wxPen& pen)
{
if (*this == pen) return (*this);
Ref(pen);
return *this;
}
bool wxPen::operator == (const wxPen& pen) const
{
return m_refData == pen.m_refData;
}
bool wxPen::operator != (const wxPen& pen) const
{
return m_refData != pen.m_refData;
}
void wxPen::SetColour(const wxColour &colour)
{
AllocExclusive();
M_PENDATA->m_colour = colour;
}
void wxPen::SetDashes(int number_of_dashes, const wxDash *dash)
{
AllocExclusive();
M_PENDATA->m_countDashes = number_of_dashes;
M_PENDATA->m_dash = (wxDash *)dash; /* TODO */
}
void wxPen::SetColour(int red, int green, int blue)
{
AllocExclusive();
M_PENDATA->m_colour.Set(red, green, blue);
}
void wxPen::SetCap(int capStyle)
{
AllocExclusive();
M_PENDATA->m_capStyle = capStyle;
}
void wxPen::SetJoin(int joinStyle)
{
AllocExclusive();
M_PENDATA->m_joinStyle = joinStyle;
}
void wxPen::SetStyle(int style)
{
AllocExclusive();
M_PENDATA->m_style = style;
}
void wxPen::SetStipple(const wxBitmap& stipple)
{
wxCHECK_RET( stipple.Ok(), _T("invalid bitmap") );
wxCHECK_RET( stipple.GetWidth() == 8 && stipple.GetHeight() == 8,
_T("stipple bitmap must be 8x8") );
AllocExclusive();
M_PENDATA->m_stipple = stipple;
<API key>(stipple, &(M_PENDATA->m_pixPattern), NULL);
}
void wxPen::SetWidth(int width)
{
AllocExclusive();
M_PENDATA->m_width = width;
}
int wxPen::GetDashes(wxDash **ptr) const
{
*ptr = (M_PENDATA ? (wxDash*)M_PENDATA->m_dash : (wxDash*) NULL);
return (M_PENDATA ? M_PENDATA->m_countDashes : 0);
}
int wxPen::GetDashCount() const
{
return (M_PENDATA->m_countDashes);
}
wxDash* wxPen::GetDash() const
{
return (wxDash*)M_PENDATA->m_dash;
}
int wxPen::GetCap() const
{
wxCHECK_MSG( Ok(), -1, wxT("invalid pen") );
return M_PENDATA->m_capStyle;
}
int wxPen::GetJoin() const
{
wxCHECK_MSG( Ok(), -1, wxT("invalid pen") );
return M_PENDATA->m_joinStyle;
}
int wxPen::GetStyle() const
{
wxCHECK_MSG( Ok(), -1, wxT("invalid pen") );
return M_PENDATA->m_style;
}
int wxPen::GetWidth() const
{
wxCHECK_MSG( Ok(), -1, wxT("invalid pen") );
return M_PENDATA->m_width;
}
wxColour &wxPen::GetColour() const
{
wxCHECK_MSG( Ok(), wxNullColour, wxT("invalid pen") );
return M_PENDATA->m_colour;
}
wxBitmap *wxPen::GetStipple() const
{
wxCHECK_MSG( Ok(), NULL, wxT("invalid pen") );
return &(M_PENDATA->m_stipple);
}
void* wxPen::GetPixPattern() const
{
wxCHECK_MSG( Ok(), NULL, wxT("invalid pen") );
return (void*)&(M_PENDATA->m_pixPattern);
}
bool wxPen::Ok() const
{
return (m_refData != NULL);
}
wxObjectRefData *wxPen::CreateRefData() const
{
return new wxPenRefData;
}
wxObjectRefData *wxPen::CloneRefData(const wxObjectRefData *data) const
{
return new wxPenRefData(*(wxPenRefData *)data);
} |
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class <API key> extends CI_Model {
function __construct() {
parent::__construct();
}
public function <API key>($data) {
$record = array(
'<API key>' => date('Y-m-d H:i:s'),
'accepted_car_owner' => 1,
'state' => 1
);
$request_data = $this-><API key>($data['id']);
if ($request_data['owner_response_time'] == "") {
$record['owner_response_time'] = strtotime($record['<API key>']) - strtotime($request_data['creation_time']);
}
$this->db->where('id', $data['id']);
$this->db->where('car_id', $data['car_id']);
$this->db->where('car_user_id', $data['car_user_id']);
$this->db->where('accepted_car_owner', 0);
/* other condition check */
$this->db->where('<API key>', 0);
$this->db->update('<API key>', $record);
if ($this->db->affected_rows() == 1) {
return true;
}
return false;
}
public function <API key>($data) {
$record = array(
'<API key>' => date('Y-m-d H:i:s'),
'<API key>' => 1,
'state' => 0
);
$request_data = $this-><API key>($data['id']);
if ($request_data['owner_response_time'] == "") {
$record['owner_response_time'] = strtotime($record['<API key>']) - strtotime($request_data['creation_time']);
}
$this->db->where('id', $data['id']);
$this->db->where('car_id', $data['car_id']);
$this->db->where('car_user_id', $data['car_user_id']);
$this->db->where('pickup_confirmed', 0);
/* other condition check */
$this->db->where('<API key>', 0);
$this->db->update('<API key>', $record);
if ($this->db->affected_rows() == 1) {
/* set owner response time to calculate response time of owner */
return true;
}
return false;
}
public function <API key>($data) {
$record = array(
'<API key>' => date('Y-m-d H:i:s'),
'<API key>' => 1,
'state' => 0
);
$this->db->where('id', $data['id']);
$this->db->where('car_id', $data['car_id']);
$this->db->where('car_renter_id', $data['car_renter_id']);
/* other condition check */
$this->db->where('<API key>', 0);
$this->db->where('pickup_confirmed', 0);
$this->db->update('<API key>', $record);
if ($this->db->affected_rows() == 1) {
return true;
}
return false;
}
/*
* this function is used to get all incoming requests to perticuler car of a car owner
*/
public function <API key>($data) {
$this->db->where('car_user_id', $data['car_user_id']);
$this->db->where('car_id', $data['car_id']);
$this->db->where('<API key>', 0);
$this->db->where('<API key>', 0);
$this->db->where('auto_cancel_state', 0);
$this->db->where("car_from > '" . date("Y-m-d H:i:s") . "'");
return $this->db->get('<API key>')->result_array();
}
public function <API key>($data) {
$this->db->where('car_user_id', $data['car_user_id']);
$this->db->where('accepted_car_owner', 0);
$this->db->where('<API key>', 0);
$this->db->where('<API key>', 0);
$this->db->where('auto_cancel_state', 0);
$this->db->where("car_from > '" . date("Y-m-d H:i:s") . "'");
return $this->db->get('<API key>')->result_array();
}
public function <API key>($data) {
$this->db->where('car_renter_id', $data['car_renter_id']);
$this->db->where('accepted_car_owner', 0);
$this->db->where('<API key>', 0);
$this->db->where('<API key>', 0);
$this->db->where('auto_cancel_state', 0);
$this->db->where("car_from > '" . date("Y-m-d H:i:s") . "'");
return $this->db->get('<API key>')->result_array();
}
public function <API key>($data) {
$req_data = $this-><API key>($data['id']);
$booking_data = array(
'request_id_fk' => $req_data['id'],
'car_owner_id' => $req_data['car_user_id'],
'car_requester_id' => $req_data['car_renter_id'],
'transaction_action' => 'non_show_renter',
'action_time' => date('Y-m-d H:i:s'),
'transaction_type' => 'to_renter'
);
$this->db->insert('urend_booking_meta', $booking_data);
//if($this->db->update('<API key>',$record)){
return true;
return false;
}
public function <API key>($data) {
$req_data = $this-><API key>($data['id']);
$booking_data = array(
'request_id_fk' => $req_data['id'],
'car_owner_id' => $req_data['car_user_id'],
'car_requester_id' => $req_data['car_renter_id'],
'transaction_action' => 'non_show_owner',
'action_time' => date('Y-m-d H:i:s'),
'transaction_type' => 'to_renter'
);
$this->db->insert('urend_booking_meta', $booking_data);
return true;
}
public function <API key>($data) {
$req_data = $this-><API key>($data['id']);
$booking_data = array(
'request_id_fk' => $req_data['id'],
'car_owner_id' => $req_data['car_user_id'],
'car_requester_id' => $req_data['car_renter_id'],
'transaction_action' => '<API key>',
'action_time' => date('Y-m-d H:i:s'),
'transaction_type' => 'to_renter'
);
$this->db->insert('urend_booking_meta', $booking_data);
return true;
}
public function <API key>($data) {
$req_data = $this-><API key>($data['id']);
$booking_data = array(
'request_id_fk' => $req_data['id'],
'car_owner_id' => $req_data['car_user_id'],
'car_requester_id' => $req_data['car_renter_id'],
'transaction_action' => '<API key>',
'action_time' => date('Y-m-d H:i:s'),
'transaction_type' => 'to_renter'
);
$this->db->insert('urend_booking_meta', $booking_data);
return true;
}
public function <API key>($data) {
$req_data = $this-><API key>($data['id']);
$booking_data = array(
'request_id_fk' => $req_data['id'],
'car_owner_id' => $req_data['car_user_id'],
'car_requester_id' => $req_data['car_renter_id'],
'transaction_action' => '<API key>',
'action_time' => date('Y-m-d H:i:s'),
'transaction_type' => 'to_renter'
);
$this->db->insert('urend_booking_meta', $booking_data);
return true;
}
public function <API key>($data) {
$req_data = $this-><API key>($data['id']);
$booking_data = array(
'request_id_fk' => $req_data['id'],
'car_owner_id' => $req_data['car_user_id'],
'car_requester_id' => $req_data['car_renter_id'],
'transaction_action' => '<API key>',
'action_time' => date('Y-m-d H:i:s'),
'transaction_type' => 'to_renter'
);
$this->db->insert('urend_booking_meta', $booking_data);
return true;
}
public function <API key>($data) {
$where = '(car_renter_id="' . $data['user_id'] . '" or car_user_id = "' . $data['user_id'] . '")';
$this->db->where($where);
$this->db->where('<API key>', 0);
$this->db->where('<API key>', 0);
$this->db->where('accepted_car_owner', 1);
$this->db->where('<API key>', 0);
$this->db->where('auto_cancel_state', 0);
$this->db->order_by("id", "DESC");
return $this->db->get('<API key>')->result_array();
}
public function <API key>($data) {
$where = '(car_renter_id="' . $data['user_id'] . '" or car_user_id = "' . $data['user_id'] . '" )';
$this->db->where($where);
$date = date("Y-m-d H:i:s");
$this->db->where('( <API key> = "1" or <API key> = "1" or auto_cancel_state = 1 )');
return $this->db->get('<API key>')->result_array();
}
public function <API key>($data) {
$where = '(car_renter_id="' . $data['user_id'] . '" or car_user_id = "' . $data['user_id'] . '" )';
$this->db->where($where);
$this->db->where('( pickup_confirmed = "1" and <API key> = "1" )');
return $this->db->get('<API key>')->result_array();
}
public function mark_renter_delayed($data) {
$req_data = $this-><API key>($data['id']);
$booking_data = array(
'request_id_fk' => $req_data['id'],
'car_owner_id' => $req_data['car_user_id'],
'car_requester_id' => $req_data['car_renter_id'],
'transaction_action' => 'mark_renter_delayed',
'action_time' => date('Y-m-d H:i:s'),
'transaction_type' => 'to_renter'
);
if ($this->db->insert('urend_booking_meta', $booking_data)) {
$this->db->where('id', $req_data['id']);
$data = array(
'auto_cancel_state' => 1);
$this->db->update('<API key>', $data);
return true;
}
return false;
}
public function mark_owner_delayed($data) {
$req_data = $this-><API key>($data['id']);
$booking_data = array(
'request_id_fk' => $req_data['id'],
'car_owner_id' => $req_data['car_user_id'],
'car_requester_id' => $req_data['car_renter_id'],
'transaction_action' => 'mark_owner_delayed',
'action_time' => date('Y-m-d H:i:s'),
'transaction_type' => 'to_renter'
);
if ($this->db->insert('urend_booking_meta', $booking_data)) {
$this->db->where('id', $req_data['id']);
$data = array(
'auto_cancel_state' => 1);
$this->db->update('<API key>', $data);
return true;
}
return false;
}
public function <API key>($data) {
$record = array(
"user_id" => $data['car_owner_id'],
"car_id" => $data['car_id'],
"request_id" => $data['request_id'],
"car_condition" => $data['car_condition'],
"meter_reading" => $data['car_meter_reading'],
"verify_car_dl" => $data['verify_renter_dl'],
"remarks" => $data['car_remarks'],
"info_by" => 'owner',
"submission_time" => date('Y-m-d H:i:s')
);
if ($this->db->insert('<API key>', $record)) {
return $this->db->insert_id();
}
return false;
}
public function <API key>($data) {
$record = array(
"user_id" => $data['car_renter_id'],
"car_id" => $data['car_id'],
"request_id" => $data['request_id'],
"meter_reading" => $data['car_meter_reading'],
"remarks" => $data['car_remarks'],
"info_by" => 'requester',
"submission_time" => date('Y-m-d H:i:s')
);
/*
"renter_insurence_id"=> $data['renter_insurence_id'],
"<API key>"=> $data['<API key>'],
"car_condition"=> $data['car_condition'],
*/
if ($this->db->insert('<API key>', $record)) {
/* set pickup confirmed here */
$insert_id = $this->db->insert_id();
/* get owner last form filling time */
$<API key> = $this-><API key>($data['request_id']);
if (count($<API key>) > 0) {
$diff = strtotime($record['submission_time']) - strtotime($<API key>['submission_time']);
$diff_minutes = $diff / 60; /* get time difference in minutes */
if ($diff_minutes < 5) {
$this->confirm_pickup($data['request_id']);
return $insert_id;
}
}
}
return false;
}
/* this is very important function and pickup will be confirmed after hitting this */
private function confirm_pickup($request_id) {
$record = array(
"pickup_confirmed" => "1"
);
$this->db->where('id', $request_id);
$this->db->update('<API key>', $record);
}
/* this is very important function and pickup will be confirmed after hitting this */
private function <API key>($request_id) {
$record = array(
"<API key>" => "1"
);
$this->db->where('id', $request_id);
$this->db->update('<API key>', $record);
}
/*
* this function is used to to get booking transaction record w.r.t. primary booking id
*/
public function <API key>($request_id) {
$sel = "(100 - (discount_weekly*100)/(car_daily_price*7)) as <API key> ,
(100 - (discount_monthly*100)/(car_daily_price*30)) as <API key> ";
$this->db->select("* , $sel");
$this->db->where('id', $request_id);
$return = ( $return = $this->db->get('<API key>')->row_array()) ? $return : array();
if (count($return) > 0) {
$action = $this-><API key>($request_id);
return array_merge($return, $action);
} else {
return array();
}
}
public function <API key>($request_id) {
$query = $this->db->query("select * from urend_booking_meta where request_id_fk = '$request_id' group by transaction_action , transaction_type ");
$result = $query->result_array();
$return['<API key>'] = $return['<API key>'] = array();
if (count($result)) {
foreach ($result as $val) {
if ($val['transaction_type'] == "to_renter") {
$action = $val['transaction_action'];
$return['<API key>'][$action] = $val['action_time'];
}
if ($val['transaction_type'] == "to_owner") {
$action = $val['transaction_action'];
$return['<API key>'][$action] = $val['action_time'];
}
}
}
return $return;
}
public function <API key>($request_id) {
$query = $this->db->query("select * from urend_booking_meta where request_id_fk = '$request_id' group by transaction_action , transaction_type ");
return $query->result_array();
}
public function <API key>($data) {
$req_data = $this-><API key>($data['id']);
$booking_data = array(
'request_id_fk' => $req_data['id'],
'car_owner_id' => $req_data['car_user_id'],
'car_requester_id' => $req_data['car_renter_id'],
'transaction_action' => '<API key>',
'action_time' => date('Y-m-d H:i:s'),
'transaction_type' => 'to_owner'
);
$this->db->insert('urend_booking_meta', $booking_data);
return true;
}
public function <API key>($data) {
$req_data = $this-><API key>($data['id']);
$booking_data = array(
'request_id_fk' => $req_data['id'],
'car_owner_id' => $req_data['car_user_id'],
'car_requester_id' => $req_data['car_renter_id'],
'transaction_action' => '<API key>',
'action_time' => date('Y-m-d H:i:s'),
'transaction_type' => 'to_owner'
);
$this->db->insert('urend_booking_meta', $booking_data);
return true;
}
public function <API key>($data) {
$req_data = $this-><API key>($data['id']);
$booking_data = array(
'request_id_fk' => $req_data['id'],
'car_owner_id' => $req_data['car_user_id'],
'car_requester_id' => $req_data['car_renter_id'],
'transaction_action' => '<API key>',
'action_time' => date('Y-m-d H:i:s'),
'transaction_type' => 'to_owner'
);
$this->db->insert('urend_booking_meta', $booking_data);
return true;
}
public function <API key>($data) {
$req_data = $this-><API key>($data['id']);
$booking_data = array(
'request_id_fk' => $req_data['id'],
'car_owner_id' => $req_data['car_user_id'],
'car_requester_id' => $req_data['car_renter_id'],
'transaction_action' => '<API key>',
'action_time' => date('Y-m-d H:i:s'),
'transaction_type' => 'to_owner'
);
$this->db->insert('urend_booking_meta', $booking_data);
return true;
}
public function <API key>($data) {
$req_data = $this-><API key>($data['id']);
$booking_data = array(
'request_id_fk' => $req_data['id'],
'car_owner_id' => $req_data['car_user_id'],
'car_requester_id' => $req_data['car_renter_id'],
'transaction_action' => 'non_show_renter',
'action_time' => date('Y-m-d H:i:s'),
'transaction_type' => 'to_owner'
);
$this->db->insert('urend_booking_meta', $booking_data);
return true;
}
public function <API key>($data) {
$req_data = $this-><API key>($data['id']);
$booking_data = array(
'request_id_fk' => $req_data['id'],
'car_owner_id' => $req_data['car_user_id'],
'car_requester_id' => $req_data['car_renter_id'],
'transaction_action' => 'non_show_owner',
'action_time' => date('Y-m-d H:i:s'),
'transaction_type' => 'to_owner'
);
$this->db->insert('urend_booking_meta', $booking_data);
return true;
}
public function <API key>($data) {
$req_data = $this-><API key>($data['id']);
$booking_data = array(
'request_id_fk' => $req_data['id'],
'car_owner_id' => $req_data['car_user_id'],
'car_requester_id' => $req_data['car_renter_id'],
'transaction_action' => 'mark_renter_delayed',
'action_time' => date('Y-m-d H:i:s'),
'transaction_type' => 'to_owner'
);
$this->db->insert('urend_booking_meta', $booking_data);
return true;
}
public function <API key>($data) {
$req_data = $this-><API key>($data['id']);
$booking_data = array(
'request_id_fk' => $req_data['id'],
'car_owner_id' => $req_data['car_user_id'],
'car_requester_id' => $req_data['car_renter_id'],
'transaction_action' => 'mark_owner_delayed',
'action_time' => date('Y-m-d H:i:s'),
'transaction_type' => 'to_owner'
);
$this->db->insert('urend_booking_meta', $booking_data);
return true;
}
public function <API key>($data) {
$record = array(
"user_id" => $data['car_owner_id'],
"car_id" => $data['car_id'],
"request_id" => $data['request_id'],
"car_condition" => $data['car_condition'],
"meter_reading" => $data['car_meter_reading'],
"info_by" => 'owner',
"transaction_type" => 'to_owner',
"damage_type" => $data['damage_type'],
"submission_time" => date('Y-m-d H:i:s')
);
if ($this->db->insert('<API key>', $record)) {
$insert_id = $this->db->insert_id();
//$this-><API key>($data['request_id']);
//return $insert_id;
$<API key> = $this-><API key>($data['request_id']);
if (count($<API key>) > 0) {
$diff = strtotime($record['submission_time']) - strtotime($<API key>['submission_time']);
$diff_minutes = $diff / 60;
if ($diff_minutes < 5) {
$this-><API key>($data['request_id']);
return $insert_id;
}
}
}
return false;
}
public function <API key>($data) {
$record = array(
"user_id" => $data['car_renter_id'],
"car_id" => $data['car_id'],
"request_id" => $data['request_id'],
"car_condition" => $data['car_condition'],
"meter_reading" => $data['car_meter_reading'],
"info_by" => 'requester',
"damage_type" => $data['damage_type'],
"transaction_type" => 'to_owner',
"remarks" => $data['remarks'],
"submission_time" => date('Y-m-d H:i:s')
);
if ($this->db->insert('<API key>', $record)) {
$insert_id = $this->db->insert_id();
return $insert_id;
}
return false;
}
public function <API key>($booking_info_id, $image) {
$data['booking_info_id'] = $booking_info_id;
$data['image_name'] = $image;
$this->db->insert('<API key>', $data);
}
public function rate_car($data) {
$this->db->where('booking_request_id',$data['booking_request_id']);
$this->db->where('car_id',$data['car_id']);
$this->db->where('given_by',$data['given_by']);
$record = $this->db->get('urend_car_rating')->row_array();
if($record){
$this->db->where('id', $record['id']);
$this->db->delete('urend_car_rating');
}
$this->db->insert('urend_car_rating', $data);
}
public function rate_user($data) {
$this->db->insert('urend_user_rating', $data);
}
public function return_save_claim($data) {
$this->db->insert('urend_car_claim', $data);
$return = $this->db->insert_id();
$req_data = $this-><API key>($data['booking_id']);
$booking_data = array(
'request_id_fk' => $req_data['id'],
'car_owner_id' => $req_data['car_user_id'],
'car_requester_id' => $req_data['car_renter_id'],
'transaction_action' => 'owner_claim_for_car',
'action_time' => date('Y-m-d H:i:s'),
'transaction_type' => 'to_owner'
);
$this->db->insert('urend_booking_meta', $booking_data);
return $return;
}
public function <API key>($booking_id, $image) {
$data['booking_id'] = $booking_id;
$data['image_name'] = $image;
$this->db->insert('<API key>', $data);
}
/* while sending */
public function <API key>($booking_id) {
$query = $this->db->query("SELECT * FROM <API key>
WHERE request_id = $booking_id and
transaction_type = 'to_renter' and
info_by = 'owner'
order by id desc limit 0,1 ");
$result = $query->row_array();
if (count($result) > 0) {
$diff = strtotime(date('Y-m-d H:i:s')) - strtotime($result['submission_time']);
$diff_minutes = $diff / 60; /* get time difference in minutes */
if ($diff_minutes > 5) {
return array();
}
}
return $result;
}
/* while sending */
public function <API key>($booking_id) {
$query = $this->db->query("SELECT * FROM <API key>
WHERE request_id = $booking_id and
transaction_type = 'to_renter' and
info_by = 'requester' order by id desc limit 0,1 ");
return $result = $query->row_array();
}
/* while getting */
public function <API key>($booking_id) {
$query = $this->db->query("SELECT * FROM <API key>
WHERE request_id = $booking_id and
transaction_type = 'to_owner' and
info_by = 'owner' order by id desc limit 0,1 ");
return $result = $query->row_array();
}
/* while sending */
public function <API key>($booking_id) {
$query = $this->db->query("SELECT * FROM <API key>
WHERE request_id = $booking_id and
transaction_type = 'to_owner' and
info_by = 'requester' order by id desc limit 0,1 ");
return $result = $query->row_array();
}
/*
* this function to used to get information about a user last booking to perticuler car
*/
public function <API key>($data) {
$this->db->where('car_renter_id', $data['car_renter_id']);
$this->db->where('car_id', $data['car_id']);
$this->db->order_by("id", "desc");
$this->db->limit(1, 0);
return $this->db->get('<API key>')->row_array();
}
public function <API key>($data){
$info = array(
"booking_id" => $data['booking_id'],
"booking_amount"=>$data['booking_amount'],
"transaction_id" =>$data['transaction_id'] ,
"creation_time"=> time()
);
$this->db->insert('<API key>',$info);
}
public function <API key>($booking_id){
$this->db->where('booking_id', $booking_id);
$this->db->limit(1, 0);
return $this->db->get('<API key>')->row_array();
}
public function info_pickup_booking($id){
$query = $this->db->query("SELECT * FROM <API key>
WHERE request_id = $id and
transaction_type = 'to_renter' and
info_by = 'requester' order by id desc limit 0,1 ");
$result['pickup_renter'] = $query->row_array();
if(count($result['pickup_renter']) > 0 ){
$query = $this->db->query("SELECT * ,
IF (image_name!='', concat('" . base_url('uploads/car_booking_images') . "/', image_name),'') as image_name
FROM <API key>
WHERE booking_info_id = ".$result['pickup_renter']['id'] ."" );
$result['pickup_renter']['images'] = $query->result_array();
}
$query = $this->db->query("SELECT * FROM <API key>
WHERE request_id = $id and
transaction_type = 'to_renter' and
info_by = 'owner' order by id desc limit 0,1 ");
$result['pickup_owner'] = $query->row_array();
if(count($result['pickup_owner']) > 0 ){
$query = $this->db->query("SELECT * ,
IF (image_name!='', concat('" . base_url('uploads/car_booking_images') . "/', image_name),'') as image_name
FROM <API key>
WHERE booking_info_id = ".$result['pickup_owner']['id'] ."" );
$result['pickup_owner']['images'] = $query->result_array();
}
return $result;
}
public function <API key>($id){
$query = $this->db->query("SELECT * FROM <API key>
WHERE request_id = $id and
transaction_type = 'to_owner' and
info_by = 'requester' order by id desc limit 0,1 ");
$result['dropoff_renter'] = $query->row_array();
if(count($result['dropoff_renter']) > 0 ){
$query = $this->db->query("SELECT * ,
IF (image_name!='', concat('" . base_url('uploads/car_booking_images') . "/', image_name),'') as image_name
FROM <API key>
WHERE booking_info_id = ".$result['dropoff_renter']['id'] ."" );
$result['dropoff_renter']['images'] = $query->result_array();
}
$query = $this->db->query("SELECT * FROM <API key>
WHERE request_id = $id and
transaction_type = 'to_owner' and
info_by = 'owner' order by id desc limit 0,1 ");
$result['dropoff_owner'] = $query->row_array();
if(count($result['dropoff_owner']) > 0 ){
$query = $this->db->query("SELECT * ,
IF (image_name!='', concat('" . base_url('uploads/car_booking_images') . "/', image_name),'') as image_name
FROM <API key>
WHERE booking_info_id = ".$result['dropoff_owner']['id'] ."" );
$result['dropoff_owner']['images'] = $query->result_array();
}
return $result;
}
// save transaction
public function insert_transaction($data){
$this->db->insert('booking_payout', $data);
}
public function update_transaction($data){
$this->db->where('id',$data['id']);
$this->db->update('booking_payout', $data);
}
public function <API key>($booking_id){
$this->db->where('booking_id',$booking_id);
return $this->db->get('booking_payout')->result_array();
}
public function <API key>($booking_id){
$data = array('status'=>1);
$result = $this->db->where('booking_id',$booking_id)->update('<API key>',$data);
return $result;
}
} |
layout: post
date: '2015-08-23'
title: "Mori Lee Bridesmaids 31043 Short One Shoulder Chiffon Dress"
category: Mori Lee
tags: [Mori Lee]
Mori Lee Bridesmaids 31043 Short One Shoulder Chiffon Dress
Just **$228.99**
<p>Mori lee 31043 is a one shoulder style short bridesmaid dress with ruchedbodice and a full A-Line skirt.</p>
<p><span style="line-height: 1.4;">Fabric:Chiffon</span></p>
<p>
<p>
<a href="https:
<!-- break --><a href="https:
<a href="https:
<a href="https:
<a href="https:
Buy it: [https: |
using ElectronicObserver.Backfire.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElectronicObserver.Backfire.Observer.kcsapi.api_req_hensei {
public class combined : APIBase {
public override bool IsRequestSupported { get { return true; } }
public override bool IsResponseSupported { get { return true; } }
public override void OnRequestReceived( Dictionary<string, string> data ) {
KCDatabase.Instance.Fleet.LoadFromRequest( APIName, data );
base.OnRequestReceived( data );
}
public override string APIName {
get { return "api_req_hensei/combined"; }
}
}
} |
#ifndef IO_H
#define IO_H
#include <stdbool.h>
#include <stdint.h>
#include <avr/io.h>
#include "timers.h"
#include "mq.h"
#include "_io.h"
extern bool last_state_down[3];
extern bool steady_state[3];
extern bool key_repeating[3];
extern uint16_t state_change_clock[3];
extern uint16_t <API key>[3];
extern uint16_t <API key>[3];
inline void handle_keys(void) __attribute__((always_inline));
inline void handle_keys(void)
{
for (uint8_t key = 0; key < 3; key++) {
bool down = key_down(key);
if (down != last_state_down[key]) {
// State change
last_state_down[key] = down;
steady_state[key] = false;
state_change_clock[key] = clock_count;
}
else if (down && (clock_count - state_change_clock[key] > (key_repeating[key] ? <API key>[key] : <API key>[key]))) {
// Autorepeat
state_change_clock[key] = clock_count;
mq_put(msg_create(M_KEY_REPEAT, key));
key_repeating[key] = true;
}
else if (!steady_state[key] && clock_count - state_change_clock[key] > DEBOUNCE_TIME) {
// Debounce period over and key in same state
mq_put(msg_create(down ? M_KEY_DOWN : M_KEY_UP, key));
steady_state[key] = true;
if (!down)
key_repeating[key] = false;
}
}
}
#endif /* IO_H */ |
<?php
class <API key> extends <API key> {
public function __construct() {
$this->_blockGroup = 'sagepayreporting';
$this->_controller = '<API key>';
parent::__construct();
$this->_updateButton('save', 'label', Mage::helper('sagepayreporting')->__('Add'));
}
public function getHeaderText() {
return Mage::helper('sagepayreporting')->__('White List IP Address');
}
/**
* Get form action URL
*
* @return string
*/
public function getFormActionUrl() {
return $this->getUrl('*/' . $this->_controller . '/save', array('_current' => true));
}
} |
<!DOCTYPE html>
<!--[if IE]><![endif]-->
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Class Scope
</title>
<meta name="viewport" content="width=device-width">
<meta name="title" content="Class Scope
">
<meta name="generator" content="docfx 2.9.3.0">
<link rel="shortcut icon" href="../favicon.ico">
<link rel="stylesheet" href="../styles/docfx.vendor.css">
<link rel="stylesheet" href="../styles/docfx.css">
<link rel="stylesheet" href="../styles/main.css">
<meta property="docfx:navrel" content="../toc.html">
<meta property="docfx:tocrel" content="toc.html">
</head>
<body data-spy="scroll" data-target="#affix">
<div id="wrapper">
<header>
<nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../index.html">
<img id="logo" class="svg" src="../logo.svg" alt="">
</a>
</div>
<div class="collapse navbar-collapse" id="navbar">
<form class="navbar-form navbar-right" role="search" id="search">
<div class="form-group">
<input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">
</div>
</form>
</div>
</div>
</nav>
<div class="subnav navbar navbar-default">
<div class="container hide-when-search" id="breadcrumb">
<ul class="breadcrumb">
<li></li>
</ul>
</div>
</div>
</header>
<div role="main" class="container body-content hide-when-search">
<div class="sidenav hide-when-search">
<a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a>
<div class="sidetoggle collapse" id="sidetoggle">
<div id="sidetoc"></div>
</div>
</div>
<div class="article row grid-right">
<div class="col-md-10">
<article class="content wrap" id="_content">
<h1 id="<API key>" data-uid="Bifrost.CodeGeneration.JavaScript.Scope">Class Scope
</h1>
<div class="markdown level0 summary"><p>Represents a scope, typically used when you want to assign something within a scope</p>
</div>
<div class="markdown level0 conceptual"></div>
<div class="inheritance">
<h5>Inheritance</h5>
<div class="level0"><span class="xref">System.Object</span></div>
<div class="level1"><a class="xref" href="Bifrost.CodeGeneration.LanguageElement.html">LanguageElement</a></div>
<div class="level2"><span class="xref">Scope</span></div>
</div>
<div class="inheritedMembers">
<h5>Inherited Members</h5>
<div>
<a class="xref" href="Bifrost.CodeGeneration.LanguageElement.html#<API key>">LanguageElement.Children</a>
</div>
<div>
<a class="xref" href="Bifrost.CodeGeneration.LanguageElement.html#<API key>">LanguageElement.Parent</a>
</div>
<div>
<a class="xref" href="Bifrost.CodeGeneration.LanguageElement.html#Bifrost_CodeGeneration_LanguageElement_AddChild_Bifrost_CodeGeneration_ILanguageElement_">LanguageElement.AddChild(ILanguageElement)</a>
</div>
<div>
<a class="xref" href="Bifrost.CodeGeneration.LanguageElement.html#Bifrost_CodeGeneration_LanguageElement_WriteChildren_Bifrost_CodeGeneration_ICodeWriter_">LanguageElement.WriteChildren(ICodeWriter)</a>
</div>
<div>
<span class="xref">System.Object.ToString()</span>
</div>
<div>
<span class="xref">System.Object.Equals(System.Object)</span>
</div>
<div>
<span class="xref">System.Object.Equals(System.Object, System.Object)</span>
</div>
<div>
<span class="xref">System.Object.ReferenceEquals(System.Object, System.Object)</span>
</div>
<div>
<span class="xref">System.Object.GetHashCode()</span>
</div>
<div>
<span class="xref">System.Object.GetType()</span>
</div>
<div>
<span class="xref">System.Object.MemberwiseClone()</span>
</div>
</div>
<h6><strong>Namespace</strong>:Bifrost.CodeGeneration.JavaScript</h6>
<h6><strong>Assembly</strong>:Bifrost.dll</h6>
<h5 id="<API key>">Syntax</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public class Scope : LanguageElement, ILanguageElement</code></pre>
</div>
<h3 id="constructors">Constructors
</h3>
<span class="small pull-right mobile-hide">
<span class="divider">|</span>
<a href="https:
</span>
<span class="small pull-right mobile-hide">
<a href="https://github.com/dolittle/Bifrost/blob/master/Source/Bifrost/CodeGeneration/JavaScript/Scope.cs/#L16">View Source</a>
</span>
<a id="<API key>" data-uid="Bifrost.CodeGeneration.JavaScript.Scope.#ctor*"></a>
<h4 id="<API key>" data-uid="Bifrost.CodeGeneration.JavaScript.Scope.#ctor(System.String)">Scope(String)</h4>
<div class="markdown level1 summary"><p>Initializes a new instance of a <a class="xref" href="Bifrost.CodeGeneration.JavaScript.Scope.html">Scope</a></p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public Scope(string name)</code></pre>
</div>
<h5 class="parameters">Parameters</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="xref">System.String</span></td>
<td><span class="parametername">name</span></td>
<td><p>Name of scope</p>
</td>
</tr>
</tbody>
</table>
<h3 id="properties">Properties
</h3>
<span class="small pull-right mobile-hide">
<span class="divider">|</span>
<a href="https:
</span>
<span class="small pull-right mobile-hide">
<a href="https://github.com/dolittle/Bifrost/blob/master/Source/Bifrost/CodeGeneration/JavaScript/Scope.cs/#L24">View Source</a>
</span>
<a id="<API key>" data-uid="Bifrost.CodeGeneration.JavaScript.Scope.Name*"></a>
<h4 id="<API key>" data-uid="Bifrost.CodeGeneration.JavaScript.Scope.Name">Name</h4>
<div class="markdown level1 summary"><p>Gets or sets the name of the scope</p>
</div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public string Name { get; set; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="xref">System.String</span></td>
<td></td>
</tr>
</tbody>
</table>
<h3 id="methods">Methods
</h3>
<span class="small pull-right mobile-hide">
<span class="divider">|</span>
<a href="https:
</span>
<span class="small pull-right mobile-hide">
<a href="https://github.com/dolittle/Bifrost/blob/master/Source/Bifrost/CodeGeneration/JavaScript/Scope.cs/#L28">View Source</a>
</span>
<a id="<API key>" data-uid="Bifrost.CodeGeneration.JavaScript.Scope.Write*"></a>
<h4 id="Bifrost_CodeGeneration_JavaScript_Scope_Write_Bifrost_CodeGeneration_ICodeWriter_" data-uid="Bifrost.CodeGeneration.JavaScript.Scope.Write(Bifrost.CodeGeneration.ICodeWriter)">Write(ICodeWriter)</h4>
<div class="markdown level1 summary"></div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public override void Write(ICodeWriter writer)</code></pre>
</div>
<h5 class="parameters">Parameters</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><a class="xref" href="Bifrost.CodeGeneration.ICodeWriter.html">ICodeWriter</a></td>
<td><span class="parametername">writer</span></td>
<td></td>
</tr>
</tbody>
</table>
<h5 class="overrides">Overrides</h5>
<div><a class="xref" href="Bifrost.CodeGeneration.LanguageElement.html#<API key>">LanguageElement.Write(ICodeWriter)</a></div>
<h3 id="extensionmethods">Extension Methods</h3>
<div>
<a class="xref" href="Bifrost.Concepts.ConceptExtensions.html#<API key>">ConceptExtensions.IsConcept(Object)</a>
</div>
<div>
<a class="xref" href="Bifrost.Concepts.ConceptExtensions.html#<API key>">ConceptExtensions.GetConceptValue(Object)</a>
</div>
<div>
<a class="xref" href="Bifrost.Dynamic.DynamicExtensions.html#<API key>">DynamicExtensions.AsExpandoObject(Object)</a>
</div>
<div>
<a class="xref" href="Bifrost.Extensions.MethodCalls.html
</div>
<div>
<a class="xref" href="Bifrost.Extensions.MethodCalls.html
</div>
<div>
<a class="xref" href="Bifrost.Extensions.MethodCalls.html
</div>
<div>
<a class="xref" href="Bifrost.Extensions.MethodCalls.html
</div>
<div>
<a class="xref" href="Bifrost.Extensions.MethodCalls.html#<API key>">MethodCalls.Generics<T>(T)</a>
</div>
<div>
<a class="xref" href="Bifrost.CodeGeneration.JavaScript.ScopeExtensions.html#Bifrost_CodeGeneration_JavaScript_ScopeExtensions_FunctionCall_Bifrost_CodeGeneration_JavaScript_Scope_System_Action_Bifrost_CodeGeneration_JavaScript_FunctionCall__">ScopeExtensions.FunctionCall(Scope, Action<FunctionCall>)</a>
</div>
</article>
</div>
<div class="hidden-sm col-md-2" role="complementary">
<div class="sideaffix">
<div class="contribution">
<ul class="nav">
<li>
<a href="https:
</li>
<li>
<a href="https://github.com/dolittle/Bifrost/blob/master/Source/Bifrost/CodeGeneration/JavaScript/Scope.cs/#L10" class="contribution-link">View Source</a>
</li>
</ul>
</div>
<nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix">
<!-- <p><a class="back-to-top" href="#top">Back to top</a><p> -->
</nav>
</div>
</div>
</div>
</div>
<footer>
<div class="grad-bottom"></div>
<div class="footer">
<div class="container">
<span class="pull-right">
<a href="#top">Back to top</a>
</span>
Copyright © 2008-2017 Dolittle
</div>
</div>
</footer>
</div>
<script type="text/javascript" src="../styles/docfx.vendor.js"></script>
<script type="text/javascript" src="../styles/docfx.js"></script>
<script type="text/javascript" src="../styles/main.js"></script>
</body>
</html> |
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
body {
margin: 0 auto;
line-height: 1.7em;
}
.l-box {
padding: 1em;
}
.header {
margin: 0 0;
}
.header .pure-menu {
padding: 0.5em;
}
.header .pure-menu li a:hover,
.header .pure-menu li a:focus {
background: none;
border: none;
color: #aaa;
}
body .primary-button {
background: #02a6eb;
color: #fff;
}
.splash {
margin: 2em auto 0;
padding: 3em 0.5em;
background: #eee;
}
.splash .splash-head {
font-size: 300%;
margin: 0em 0;
line-height: 1.2em;
}
.splash .splash-subhead {
color: #999;
font-weight: 300;
line-height: 1.4em;
}
.splash .primary-button {
font-size: 150%;
}
.content .content-subhead {
color: #999;
padding-bottom: 0.3em;
text-transform: uppercase;
margin: 0;
border-bottom: 2px solid #eee;
display: inline-block;
}
.content .content-ribbon {
margin: 3em;
border-bottom: 1px solid #eee;
}
.ribbon {
background: #eee;
text-align: center;
padding: 2em;
color: #999;
}
.ribbon h2 {
display: inline;
font-weight: normal;
}
.footer {
background: #111;
color: #666;
text-align: center;
padding: 1em;
font-size: 80%;
} |
#!/usr/bin/env python3
import os
import logging
import <API key>
import download_notices
import parse_notice_tweets
import <API key>
#logging.basicConfig(level=logging.DEBUG)
for path in ['store/table_pages', 'store/notices', 'store/tweets']:
if not os.path.exists(path):
os.mkdirs(path)
withheld_tweets = (tweet
for table_page in <API key>.fetch_table_pages()
for notice in download_notices.fetch_notices(table_page)
for tweet in parse_notice_tweets.parse_tweets_from(notice)
if <API key>.is_withheld(tweet))
for t in withheld_tweets: print(t) |
<?php
/**
* Import entity product model
*
* @category Mage
* @package Mage_ImportExport
* @author Magento Core Team <core@magentocommerce.com>
*/
class <API key> extends <API key>
{
/**
* Configuration key for product type
*/
const <API key> = 'global/importexport/<API key>';
/**
* Size of bunch - part of products to save in one step.
*/
const BUNCH_SIZE = 20;
/**
* Value that means all entities (e.g. websites, groups etc.)
*/
const VALUE_ALL = 'all';
/**
* Default Scope
*/
const SCOPE_DEFAULT = 1;
/**
* Website Scope
*/
const SCOPE_WEBSITE = 2;
/**
* Store Scope
*/
const SCOPE_STORE = 0;
/**
* Null Scope
*/
const SCOPE_NULL = -1;
/**#@+
* Permanent column names.
*
* Names that begins with underscore is not an attribute. This name convention is for
* to avoid interference with same attribute name.
*/
const COL_STORE = '_store';
/**
* Col Attr Set
*/
const COL_ATTR_SET = '_attribute_set';
/**
* Col Type
*/
const COL_TYPE = '_type';
/**
* Col Category
*/
const COL_CATEGORY = '_category';
/**
* Col Root Category
*/
const COL_ROOT_CATEGORY = '_root_category';
/**
* Col Sku
*/
const COL_SKU = 'sku';
/**#@+
* Error codes.
*/
const ERROR_INVALID_SCOPE = 'invalidScope';
/**
* Error - invalid website
*/
const <API key> = 'invalidWebsite';
/**
* Error - invalid store
*/
const ERROR_INVALID_STORE = 'invalidStore';
/**
* Error - invalid attr set
*/
const <API key> = 'invalidAttrSet';
/**
* Error - invalid type
*/
const ERROR_INVALID_TYPE = 'invalidType';
/**
* Error - invalid category
*/
const <API key> = 'invalidCategory';
/**
* Error - value is required
*/
const <API key> = 'isRequired';
/**
* Error - type changed
*/
const ERROR_TYPE_CHANGED = 'typeChanged';
/**
* Error - sku is empty
*/
const ERROR_SKU_IS_EMPTY = 'skuEmpty';
/**
* Error - no default row
*/
const <API key> = 'noDefaultRow';
/**
* Error - change type
*/
const ERROR_CHANGE_TYPE = 'changeProductType';
/**
* Error - duplicate scope
*/
const <API key> = 'duplicateScope';
/**
* Error - duplicate sku
*/
const ERROR_DUPLICATE_SKU = 'duplicateSKU';
/**
* Error - change attr set
*/
const <API key> = 'changeAttrSet';
/**
* Error - type unsupported
*/
const <API key> = '<API key>';
/**
* Error - row is orphan
*/
const ERROR_ROW_IS_ORPHAN = 'rowIsOrphan';
/**
* Error - invalid tier price qty
*/
const <API key> = '<API key>';
/**
* Error - invalid tier price site
*/
const <API key> = '<API key>';
/**
* Error - invalid tier price group
*/
const <API key> = '<API key>';
/**
* Error - tier data incomplete
*/
const <API key> = '<API key>';
/**
* Error - invalid group price site
*/
const <API key> = '<API key>';
/**
* Error - invalid group price group
*/
const <API key> = '<API key>';
/**
* Error - group price data incompelte
*/
const <API key> = '<API key>';
/**
* Error - sku not found for delete
*/
const <API key> = 'skuNotFoundToDelete';
/**
* Error - super products sku not found
*/
const <API key> = '<API key>';
/**
* Error - invalid product sku
*/
const <API key> = 'invalidSku';
/**
* Pairs of attribute set ID-to-name.
*
* @var array
*/
protected $_attrSetIdToName = array();
/**
* Pairs of attribute set name-to-ID.
*
* @var array
*/
protected $_attrSetNameToId = array();
/**
* Categories text-path to ID hash.
*
* @var array
*/
protected $_categories = array();
/**
* Categories text-path to ID hash with roots checking.
*
* @var array
*/
protected $<API key> = array();
/**
* Customer groups ID-to-name.
*
* @var array
*/
protected $_customerGroups = array();
/**
* Attributes with index (not label) value.
*
* @var array
*/
protected $<API key> = array(
'status',
'tax_class_id',
'visibility',
'<API key>',
'custom_design'
);
/**
* Links attribute name-to-link type ID.
*
* @var array
*/
protected $_linkNameToId = array(
'_links_related_' => <API key>::LINK_TYPE_RELATED,
'_links_crosssell_' => <API key>::LINK_TYPE_CROSSSELL,
'_links_upsell_' => <API key>::LINK_TYPE_UPSELL
);
/**
* Validation failure message template definitions
*
* @var array
*/
protected $_messageTemplates = array(
self::ERROR_INVALID_SCOPE => 'Invalid value in Scope column',
self::<API key> => 'Invalid value in Website column (website does not exists?)',
self::ERROR_INVALID_STORE => 'Invalid value in Store column (store does not exists?)',
self::<API key> => 'Invalid value for Attribute Set column (set does not exists?)',
self::ERROR_INVALID_TYPE => 'Product Type is invalid or not supported',
self::<API key> => 'Category does not exists',
self::<API key> => "Required attribute '%s' has an empty value",
self::ERROR_TYPE_CHANGED => 'Trying to change type of existing products',
self::ERROR_SKU_IS_EMPTY => 'SKU is empty',
self::<API key> => 'Default values row does not exists',
self::ERROR_CHANGE_TYPE => 'Product type change is not allowed',
self::<API key> => 'Duplicate scope',
self::ERROR_DUPLICATE_SKU => 'Duplicate SKU',
self::<API key> => 'Product attribute set change is not allowed',
self::<API key> => 'Product type is not supported',
self::ERROR_ROW_IS_ORPHAN => 'Orphan rows that will be skipped due default row errors',
self::<API key> => 'Tier Price data price or quantity value is invalid',
self::<API key> => 'Tier Price data website is invalid',
self::<API key> => 'Tier Price customer group ID is invalid',
self::<API key> => 'Tier Price data is incomplete',
self::<API key> => 'Product with specified SKU not found',
self::<API key> => 'Product with specified super products SKU not found',
self::<API key> => 'Invalid value in SKU column. HTML tags are not allowed'
);
/**
* Dry-runned products information from import file.
*
* [SKU] => array(
* 'type_id' => (string) product type
* 'attr_set_id' => (int) product attribute set ID
* 'entity_id' => (int) product ID (value for new products will be set after entity save)
* 'attr_set_code' => (string) attribute set code
* )
*
* @var array
*/
protected $_newSku = array();
/**
* Existing products SKU-related information in form of array:
*
* [SKU] => array(
* 'type_id' => (string) product type
* 'attr_set_id' => (int) product attribute set ID
* 'entity_id' => (int) product ID
* 'supported_type' => (boolean) is product type supported by current version of import module
* )
*
* @var array
*/
protected $_oldSku = array();
/**
* Column names that holds values with particular meaning.
*
* @var array
*/
protected $<API key> = array(
'_store', '_attribute_set', '_type', self::COL_CATEGORY, self::COL_ROOT_CATEGORY, '_product_websites',
'_tier_price_website', '<API key>', '_tier_price_qty', '_tier_price_price',
'_links_related_sku', '<API key>', '<API key>', '_group_price_price',
'<API key>', '<API key>', '<API key>', '_links_upsell_sku',
'<API key>', '<API key>', '_custom_option_type', '<API key>',
'<API key>', '<API key>', '_custom_option_sku', '<API key>',
'<API key>', '<API key>', '<API key>',
'<API key>', '<API key>', '<API key>',
'<API key>', '<API key>', '_media_attribute_id', '_media_image', '_media_lable',
'_media_position', '_media_is_disabled'
);
/**
* Column names that holds images files names
*
* @var array
*/
protected $_imagesArrayKeys = array(
'_media_image', 'image', 'small_image', 'thumbnail'
);
/**
* Permanent entity columns.
*
* @var array
*/
protected $<API key> = array(self::COL_SKU);
/**
* Array of supported product types as keys with appropriate model object as value.
*
* @var array
*/
protected $_productTypeModels = array();
/**
* All stores code-ID pairs.
*
* @var array
*/
protected $_storeCodeToId = array();
/**
* Store ID to its website stores IDs.
*
* @var array
*/
protected $<API key> = array();
/**
* Website code-to-ID
*
* @var array
*/
protected $_websiteCodeToId = array();
/**
* Website code to store code-to-ID pairs which it consists.
*
* @var array
*/
protected $<API key> = array();
/**
* Media files uploader
*
* @var <API key>
*/
protected $_fileUploader;
/**
* url_key attribute id
*
* @var int
*/
protected $_urlKeyAttributeId;
/**
* Constructor.
*
*/
public function __construct()
{
parent::__construct();
$this->_initWebsites()
->_initStores()
->_initAttributeSets()
->_initTypeModels()
->_initCategories()
->_initSkus()
->_initCustomerGroups();
}
/**
* Delete products.
*
* @return <API key>
*/
protected function _deleteProducts()
{
$productEntityTable = Mage::getModel('importexport/<API key>')->getEntityTable();
while ($bunch = $this->_dataSourceModel->getNextBunch()) {
$idToDelete = array();
foreach ($bunch as $rowNum => $rowData) {
if ($this->validateRow($rowData, $rowNum) && self::SCOPE_DEFAULT == $this->getRowScope($rowData)) {
$idToDelete[] = $this->_oldSku[$rowData[self::COL_SKU]]['entity_id'];
}
}
if ($idToDelete) {
$this->_connection->query(
$this->_connection->quoteInto(
"DELETE FROM `{$productEntityTable}` WHERE `entity_id` IN (?)", $idToDelete
)
);
}
}
return $this;
}
/**
* Create Product entity from raw data.
*
* @throws Exception
* @return bool Result of operation.
*/
protected function _importData()
{
if (<API key>::BEHAVIOR_DELETE == $this->getBehavior()) {
$this->_deleteProducts();
} else {
$this->_saveProducts();
$this->_saveStockItem();
$this->_saveLinks();
$this->_saveCustomOptions();
foreach ($this->_productTypeModels as $productType => $productTypeModel) {
$productTypeModel->saveData();
}
}
Mage::dispatchEvent('<API key>', array('adapter' => $this));
return true;
}
/**
* Initialize attribute sets code-to-id pairs.
*
* @return <API key>
*/
protected function _initAttributeSets()
{
foreach (Mage::getResourceModel('eav/<API key>')
->setEntityTypeFilter($this->_entityTypeId) as $attributeSet) {
$this->_attrSetNameToId[$attributeSet->getAttributeSetName()] = $attributeSet->getId();
$this->_attrSetIdToName[$attributeSet->getId()] = $attributeSet->getAttributeSetName();
}
return $this;
}
/**
* Initialize categories text-path to ID hash.
*
* @return <API key>
*/
protected function _initCategories()
{
$collection = Mage::getResourceModel('catalog/category_collection')->addNameToResult();
/* @var $collection <API key> */
foreach ($collection as $category) {
$structure = explode('/', $category->getPath());
$pathSize = count($structure);
if ($pathSize > 1) {
$path = array();
for ($i = 1; $i < $pathSize; $i++) {
$path[] = $collection->getItemById($structure[$i])->getName();
}
$rootCategoryName = array_shift($path);
if (!isset($this-><API key>[$rootCategoryName])) {
$this-><API key>[$rootCategoryName] = array();
}
$index = implode('/', $path);
$this-><API key>[$rootCategoryName][$index] = $category->getId();
if ($pathSize > 2) {
$this->_categories[$index] = $category->getId();
}
}
}
return $this;
}
/**
* Initialize customer groups.
*
* @return <API key>
*/
protected function _initCustomerGroups()
{
foreach (Mage::getResourceModel('customer/group_collection') as $customerGroup) {
$this->_customerGroups[$customerGroup->getId()] = true;
}
return $this;
}
/**
* Initialize existent product SKUs.
*
* @return <API key>
*/
protected function _initSkus()
{
$columns = array('entity_id', 'type_id', 'attribute_set_id', 'sku');
foreach (Mage::getModel('catalog/product')-><API key>($columns) as $info) {
$typeId = $info['type_id'];
$sku = $info['sku'];
$this->_oldSku[$sku] = array(
'type_id' => $typeId,
'attr_set_id' => $info['attribute_set_id'],
'entity_id' => $info['entity_id'],
'supported_type' => isset($this->_productTypeModels[$typeId])
);
}
return $this;
}
/**
* Initialize stores hash.
*
* @return <API key>
*/
protected function _initStores()
{
foreach (Mage::app()->getStores() as $store) {
$this->_storeCodeToId[$store->getCode()] = $store->getId();
$this-><API key>[$store->getId()] = $store->getWebsite()->getStoreIds();
}
return $this;
}
/**
* Initialize product type models.
*
* @throws Exception
* @return <API key>
*/
protected function _initTypeModels()
{
$config = Mage::getConfig()->getNode(self::<API key>)->asCanonicalArray();
foreach ($config as $type => $typeModel) {
$model = Mage::getModel($typeModel, array($this, $type));
if (!$model) {
Mage::throwException("Entity type model '{$typeModel}' is not found");
}
if (! $model instanceof <API key>) {
Mage::throwException(
Mage::helper('importexport')->__('Entity type model must be an instance of <API key>')
);
}
if ($model->isSuitable()) {
$this->_productTypeModels[$type] = $model;
}
$this-><API key> = array_merge(
$this-><API key>,
$model-><API key>()
);
}
// remove doubles
$this-><API key> = array_unique($this-><API key>);
return $this;
}
/**
* Initialize website values.
*
* @return <API key>
*/
protected function _initWebsites()
{
/** @var $website <API key> */
foreach (Mage::app()->getWebsites() as $website) {
$this->_websiteCodeToId[$website->getCode()] = $website->getId();
$this-><API key>[$website->getCode()] = array_flip($website->getStoreCodes());
}
return $this;
}
/**
* Check product category validity.
*
* @param array $rowData
* @param int $rowNum
* @return bool
*/
protected function <API key>(array $rowData, $rowNum)
{
$emptyCategory = empty($rowData[self::COL_CATEGORY]);
$emptyRootCategory = empty($rowData[self::COL_ROOT_CATEGORY]);
$hasCategory = $emptyCategory ? false : isset($this->_categories[$rowData[self::COL_CATEGORY]]);
$category = $emptyRootCategory ? null : $this-><API key>[$rowData[self::COL_ROOT_CATEGORY]];
if (!$emptyCategory && !$hasCategory
|| !$emptyRootCategory && !isset($category)
|| !$emptyRootCategory && !$emptyCategory && !isset($category[$rowData[self::COL_CATEGORY]])
) {
$this->addRowError(self::<API key>, $rowNum);
return false;
}
return true;
}
/**
* Check product website belonging.
*
* @param array $rowData
* @param int $rowNum
* @return bool
*/
protected function <API key>(array $rowData, $rowNum)
{
if (!empty($rowData['_product_websites']) && !isset($this->_websiteCodeToId[$rowData['_product_websites']])) {
$this->addRowError(self::<API key>, $rowNum);
return false;
}
return true;
}
/**
* Set valid attribute set and product type to rows with all scopes
* to ensure that existing products doesn't changed.
*
* @param array $rowData
* @return array
*/
protected function _prepareRowForDb(array $rowData)
{
$rowData = parent::_prepareRowForDb($rowData);
static $lastSku = null;
if (<API key>::BEHAVIOR_DELETE == $this->getBehavior()) {
return $rowData;
}
if (self::SCOPE_DEFAULT == $this->getRowScope($rowData)) {
$lastSku = $rowData[self::COL_SKU];
}
if (isset($this->_oldSku[$lastSku])) {
$rowData[self::COL_ATTR_SET] = $this->_newSku[$lastSku]['attr_set_code'];
$rowData[self::COL_TYPE] = $this->_newSku[$lastSku]['type_id'];
}
return $rowData;
}
/**
* Check tier price data validity.
*
* @param array $rowData
* @param int $rowNum
* @return bool
*/
protected function _isTierPriceValid(array $rowData, $rowNum)
{
if ((isset($rowData['_tier_price_website']) && strlen($rowData['_tier_price_website']))
|| (isset($rowData['<API key>']) && strlen($rowData['<API key>']))
|| (isset($rowData['_tier_price_qty']) && strlen($rowData['_tier_price_qty']))
|| (isset($rowData['_tier_price_price']) && strlen($rowData['_tier_price_price']))
) {
if (!isset($rowData['_tier_price_website']) || !isset($rowData['<API key>'])
|| !isset($rowData['_tier_price_qty']) || !isset($rowData['_tier_price_price'])
|| !strlen($rowData['_tier_price_website']) || !strlen($rowData['<API key>'])
|| !strlen($rowData['_tier_price_qty']) || !strlen($rowData['_tier_price_price'])
) {
$this->addRowError(self::<API key>, $rowNum);
return false;
} elseif ($rowData['_tier_price_website'] != self::VALUE_ALL
&& !isset($this->_websiteCodeToId[$rowData['_tier_price_website']])) {
$this->addRowError(self::<API key>, $rowNum);
return false;
} elseif ($rowData['<API key>'] != self::VALUE_ALL
&& !isset($this->_customerGroups[$rowData['<API key>']])) {
$this->addRowError(self::<API key>, $rowNum);
return false;
} elseif ($rowData['_tier_price_qty'] <= 0 || $rowData['_tier_price_price'] <= 0) {
$this->addRowError(self::<API key>, $rowNum);
return false;
}
}
return true;
}
/**
* Check group price data validity.
*
* @param array $rowData
* @param int $rowNum
* @return bool
*/
protected function _isGroupPriceValid(array $rowData, $rowNum)
{
if ((isset($rowData['<API key>']) && strlen($rowData['<API key>']))
|| (isset($rowData['<API key>']) && strlen($rowData['<API key>']))
|| (isset($rowData['_group_price_price']) && strlen($rowData['_group_price_price']))
) {
if (!isset($rowData['<API key>']) || !isset($rowData['<API key>'])
|| !strlen($rowData['<API key>']) || !strlen($rowData['<API key>'])
|| !strlen($rowData['_group_price_price'])
) {
$this->addRowError(self::<API key>, $rowNum);
return false;
} elseif ($rowData['<API key>'] != self::VALUE_ALL
&& !isset($this->_websiteCodeToId[$rowData['<API key>']])
) {
$this->addRowError(self::<API key>, $rowNum);
return false;
} elseif ($rowData['<API key>'] != self::VALUE_ALL
&& !isset($this->_customerGroups[$rowData['<API key>']])
) {
$this->addRowError(self::<API key>, $rowNum);
return false;
}
}
return true;
}
/**
* Check super products SKU
*
* @param array $rowData
* @param int $rowNum
* @return bool
*/
protected function <API key>($rowData, $rowNum)
{
if (!empty($rowData['_super_products_sku'])
&& (!isset($this->_oldSku[$rowData['_super_products_sku']])
&& !isset($this->_newSku[$rowData['_super_products_sku']])
)
) {
$this->addRowError(self::<API key>, $rowNum);
return false;
}
return true;
}
/**
* Check product sku data.
*
* @param array $rowData
* @param int $rowNum
* @return bool
*/
protected function _isProductSkuValid(array $rowData, $rowNum)
{
if (isset($rowData['sku']) && $rowData['sku'] != Mage::helper('core')->stripTags($rowData['sku'])) {
$this->addRowError(self::<API key>, $rowNum);
return false;
}
return true;
}
/**
* Custom options save.
*
* @return <API key>
*/
protected function _saveCustomOptions()
{
/** @var $coreResource <API key> */
$coreResource = Mage::getSingleton('core/resource');
$productTable = $coreResource->getTableName('catalog/product');
$optionTable = $coreResource->getTableName('catalog/product_option');
$priceTable = $coreResource->getTableName('catalog/<API key>');
$titleTable = $coreResource->getTableName('catalog/<API key>');
$typePriceTable = $coreResource->getTableName('catalog/<API key>');
$typeTitleTable = $coreResource->getTableName('catalog/<API key>');
$typeValueTable = $coreResource->getTableName('catalog/<API key>');
$nextOptionId = Mage::getResourceHelper('importexport')-><API key>($optionTable);
$nextValueId = Mage::getResourceHelper('importexport')-><API key>($typeValueTable);
$priceIsGlobal = Mage::helper('catalog')->isPriceGlobal();
$type = null;
$typeSpecific = array(
'date' => array('price', 'sku'),
'date_time' => array('price', 'sku'),
'time' => array('price', 'sku'),
'field' => array('price', 'sku', 'max_characters'),
'area' => array('price', 'sku', 'max_characters'),
//'file' => array('price', 'sku', 'file_extension', 'image_size_x', 'image_size_y'),
'drop_down' => true,
'radio' => true,
'checkbox' => true,
'multiple' => true
);
$<API key> = array();
$lastStoreId = null;
$lastProductId = null;
$currentValueId = null;
while ($bunch = $this->_dataSourceModel->getNextBunch()) {
$customOptions = array(
'product_id' => array(),
$optionTable => array(),
$priceTable => array(),
$titleTable => array(),
$typePriceTable => array(),
$typeTitleTable => array(),
$typeValueTable => array()
);
$flagNewOption = true;
$firstKeyOption = null;
foreach ($bunch as $rowNum => $rowData) {
$this->_filterRowData($rowData);
if (!$this-><API key>($rowData, $rowNum)) {
continue;
}
if (self::SCOPE_DEFAULT == $this->getRowScope($rowData)) {
$productId = $this->_newSku[$rowData[self::COL_SKU]]['entity_id'];
} elseif (!isset($productId)) {
continue;
}
if ($lastProductId != $productId) {
$lastStoreId = <API key>::DEFAULT_STORE_ID;
$currentValueId = null;
$lastProductId = $productId;
}
if (!empty($rowData['<API key>'])) {
if (!isset($this->_storeCodeToId[$rowData['<API key>']])) {
continue;
}
$storeId = $this->_storeCodeToId[$rowData['<API key>']];
} else {
$storeId = <API key>::DEFAULT_STORE_ID;
}
if (!empty($rowData['_custom_option_type'])) { // get CO type if its specified
if (!isset($typeSpecific[$rowData['_custom_option_type']])) {
$type = null;
continue;
}
$type = $rowData['_custom_option_type'];
$rowIsMain = true;
} else {
if (null === $type) {
continue;
}
$rowIsMain = false;
}
if (!isset($customOptions['product_id'][$productId])) { // for update product entity table
$customOptions['product_id'][$productId] = array(
'entity_id' => $productId,
'has_options' => 0,
'required_options' => 0,
'updated_at' => now()
);
}
if ($rowIsMain) {
$solidParams = array(
'option_id' => $nextOptionId,
'sku' => '',
'max_characters' => 0,
'file_extension' => null,
'image_size_x' => 0,
'image_size_y' => 0,
'product_id' => $productId,
'type' => $type,
'is_require' => empty($rowData['<API key>']) ? 0 : 1,
'sort_order' => empty($rowData['<API key>'])
? 0 : abs($rowData['<API key>'])
);
if (true !== $typeSpecific[$type]) { // simple option may have optional params
$priceTableRow = array(
'option_id' => $nextOptionId,
'store_id' => <API key>::DEFAULT_STORE_ID,
'price' => 0,
'price_type' => 'fixed'
);
foreach ($typeSpecific[$type] as $paramSuffix) {
if (isset($rowData['_custom_option_' . $paramSuffix])) {
$data = $rowData['_custom_option_' . $paramSuffix];
if (array_key_exists($paramSuffix, $solidParams)) {
$solidParams[$paramSuffix] = $data;
} elseif ('price' == $paramSuffix) {
if ('%' == substr($data, -1)) {
$priceTableRow['price_type'] = 'percent';
}
$priceTableRow['price'] = (float) rtrim($data, '%');
}
}
}
$customOptions[$priceTable][] = $priceTableRow;
}
$customOptions[$optionTable][] = $solidParams;
$customOptions['product_id'][$productId]['has_options'] = 1;
if (!empty($rowData['<API key>'])) {
$customOptions['product_id'][$productId]['required_options'] = 1;
}
$prevOptionId = $nextOptionId++; // increment option id, but preserve value for $typeValueTable
}
if ($typeSpecific[$type] === true && !empty($rowData['<API key>'])) {
if (empty($rowData['<API key>'])) {
// complex CO option row
$customOptions[$typeValueTable][$prevOptionId][] = array(
'option_type_id' => $nextValueId,
'sort_order' => empty($rowData['<API key>'])
? 0 : abs($rowData['<API key>']),
'sku' => !empty($rowData['<API key>'])
? $rowData['<API key>'] : ''
);
if (!isset($customOptions[$typeTitleTable][$nextValueId][0])) { // ensure default title is set
$customOptions[$typeTitleTable][$nextValueId][0] = $rowData['<API key>'];
}
$customOptions[$typeTitleTable][$nextValueId][$storeId] = $rowData['<API key>'];
if (!empty($rowData['<API key>'])) {
$typePriceRow = array(
'price' => (float) rtrim($rowData['<API key>'], '%'),
'price_type' => 'fixed'
);
if ('%' == substr($rowData['<API key>'], -1)) {
$typePriceRow['price_type'] = 'percent';
}
if ($priceIsGlobal) {
$customOptions[$typePriceTable][$nextValueId][0] = $typePriceRow;
} else {
// ensure default price is set
if (!isset($customOptions[$typePriceTable][$nextValueId][0])) {
$customOptions[$typePriceTable][$nextValueId][0] = $typePriceRow;
}
$customOptions[$typePriceTable][$nextValueId][$storeId] = $typePriceRow;
}
}
if ($flagNewOption) {
$firstKeyOption = $nextValueId;
$flagNewOption = false;
}
$nextValueId++;
} else {
$flagNewOption = true;
if ($lastStoreId != $storeId) {
if (!$firstKeyOption) {
reset($customOptions[$typeTitleTable]);
$firstKeyOption = key($customOptions[$typeTitleTable]);
}
$currentValueId = $firstKeyOption;
$lastStoreId = $storeId;
} else {
$currentValueId++;
}
$defaultValue = $customOptions[$typeTitleTable][$currentValueId][0];
if ($defaultValue != $rowData['<API key>']) {
$customOptions[$typeTitleTable][$currentValueId][$storeId]
= $rowData['<API key>'];
}
}
}
if (!empty($rowData['<API key>'])) {
if (!isset($customOptions[$titleTable][$prevOptionId][0])) { // ensure default title is set
$customOptions[$titleTable][$prevOptionId][0] = $rowData['<API key>'];
}
$customOptions[$titleTable][$prevOptionId][$storeId] = $rowData['<API key>'];
}
}
$productIds = array_keys($customOptions['product_id']);
$productIds = array_diff($productIds, $<API key>);
if ($this->getBehavior() != <API key>::BEHAVIOR_APPEND
&& !empty($productIds)
) { // remove old data?
$this->_connection->delete(
$optionTable,
$this->_connection->quoteInto('product_id IN (?)', $productIds)
);
}
// if complex options does not contain values - ignore them
foreach ($customOptions[$optionTable] as $key => $optionData) {
if ($typeSpecific[$optionData['type']] === true
&& !isset($customOptions[$typeValueTable][$optionData['option_id']])
) {
unset($customOptions[$optionTable][$key], $customOptions[$titleTable][$optionData['option_id']]);
}
}
if ($customOptions[$optionTable]) {
$this->_connection->insertMultiple($optionTable, $customOptions[$optionTable]);
}
$titleRows = array();
foreach ($customOptions[$titleTable] as $optionId => $storeInfo) {
foreach ($storeInfo as $storeId => $title) {
$titleRows[] = array('option_id' => $optionId, 'store_id' => $storeId, 'title' => $title);
}
}
if ($titleRows) {
$this->_connection->insertOnDuplicate($titleTable, $titleRows, array('title'));
}
if ($customOptions[$priceTable]) {
$this->_connection->insertOnDuplicate(
$priceTable,
$customOptions[$priceTable],
array('price', 'price_type')
);
}
$typeValueRows = array();
foreach ($customOptions[$typeValueTable] as $optionId => $optionInfo) {
foreach ($optionInfo as $row) {
$row['option_id'] = $optionId;
$typeValueRows[] = $row;
}
}
if ($typeValueRows) {
$this->_connection->insertMultiple($typeValueTable, $typeValueRows);
}
$optionTypePriceRows = array();
$optionTypeTitleRows = array();
foreach ($customOptions[$typePriceTable] as $optionTypeId => $storesData) {
foreach ($storesData as $storeId => $row) {
$row['option_type_id'] = $optionTypeId;
$row['store_id'] = $storeId;
$optionTypePriceRows[] = $row;
}
}
foreach ($customOptions[$typeTitleTable] as $optionTypeId => $storesData) {
foreach ($storesData as $storeId => $title) {
$optionTypeTitleRows[] = array(
'option_type_id' => $optionTypeId,
'store_id' => $storeId,
'title' => $title
);
}
}
if ($optionTypePriceRows) {
$this->_connection->insertOnDuplicate(
$typePriceTable,
$optionTypePriceRows,
array('price', 'price_type')
);
}
if ($optionTypeTitleRows) {
$this->_connection->insertOnDuplicate($typeTitleTable, $optionTypeTitleRows, array('title'));
}
if ($productIds) { // update product entity table to show that product has options
$<API key> = $customOptions['product_id'];
foreach ($<API key> as $key => $value) {
if (!in_array($key, $productIds)) {
unset($<API key>[$key]);
}
}
$this->_connection->insertOnDuplicate(
$productTable,
$<API key>,
array('has_options', 'required_options', 'updated_at')
);
}
$<API key> = array_merge($<API key>, $productIds);
}
return $this;
}
/**
* Gather and save information about product links.
* Must be called after ALL products saving done.
*
* @return <API key>
*/
protected function _saveLinks()
{
$resource = Mage::getResourceModel('catalog/product_link');
$mainTable = $resource->getMainTable();
$positionAttrId = array();
/** @var <API key> $adapter */
$adapter = $this->_connection;
// pre-load 'position' attributes ID for each link type once
foreach ($this->_linkNameToId as $linkName => $linkId) {
$select = $adapter->select()
->from(
$resource->getTable('catalog/<API key>'),
array('id' => '<API key>')
)
->where('link_type_id = :link_id AND <API key> = :position');
$bind = array(
':link_id' => $linkId,
':position' => 'position'
);
$positionAttrId[$linkId] = $adapter->fetchOne($select, $bind);
}
$nextLinkId = Mage::getResourceHelper('importexport')-><API key>($mainTable);
while ($bunch = $this->_dataSourceModel->getNextBunch()) {
$productIds = array();
$linkRows = array();
$positionRows = array();
foreach ($bunch as $rowNum => $rowData) {
$this->_filterRowData($rowData);
if (!$this-><API key>($rowData, $rowNum)) {
continue;
}
if (self::SCOPE_DEFAULT == $this->getRowScope($rowData)) {
$sku = $rowData[self::COL_SKU];
}
foreach ($this->_linkNameToId as $linkName => $linkId) {
if (isset($rowData[$linkName . 'sku'])) {
$productId = $this->_newSku[$sku]['entity_id'];
$productIds[] = $productId;
$linkedSku = $rowData[$linkName . 'sku'];
if ((isset($this->_newSku[$linkedSku]) || isset($this->_oldSku[$linkedSku]))
&& $linkedSku != $sku) {
if (isset($this->_newSku[$linkedSku])) {
$linkedId = $this->_newSku[$linkedSku]['entity_id'];
} else {
$linkedId = $this->_oldSku[$linkedSku]['entity_id'];
}
$linkKey = "{$productId}-{$linkedId}-{$linkId}";
if (!isset($linkRows[$linkKey])) {
$linkRows[$linkKey] = array(
'link_id' => $nextLinkId,
'product_id' => $productId,
'linked_product_id' => $linkedId,
'link_type_id' => $linkId
);
if (!empty($rowData[$linkName . 'position'])) {
$positionRows[] = array(
'link_id' => $nextLinkId,
'<API key>' => $positionAttrId[$linkId],
'value' => $rowData[$linkName . 'position']
);
}
$nextLinkId++;
}
}
}
}
}
if (<API key>::BEHAVIOR_APPEND != $this->getBehavior() && $productIds) {
$adapter->delete(
$mainTable,
$adapter->quoteInto('product_id IN (?)', array_unique($productIds))
);
}
if ($linkRows) {
$adapter->insertOnDuplicate(
$mainTable,
$linkRows,
array('link_id')
);
$adapter-><API key>($mainTable, $nextLinkId);
}
if ($positionRows) { // process linked product positions
$adapter->insertOnDuplicate(
$resource-><API key>('int'),
$positionRows,
array('value')
);
}
}
return $this;
}
/**
* Save product attributes.
*
* @param array $attributesData
* @return <API key>
*/
protected function <API key>(array $attributesData)
{
foreach ($attributesData as $tableName => $skuData) {
$tableData = array();
foreach ($skuData as $sku => $attributes) {
$productId = $this->_newSku[$sku]['entity_id'];
foreach ($attributes as $attributeId => $storeValues) {
foreach ($storeValues as $storeId => $storeValue) {
$tableData[] = array(
'entity_id' => $productId,
'entity_type_id' => $this->_entityTypeId,
'attribute_id' => $attributeId,
'store_id' => $storeId,
'value' => $storeValue
);
}
if ($attributeId == $this-><API key>()) {
/*
If the store based values are not provided for a particular store,
we default to the default scope values.
In this case, remove all the existing store based values stored in the table.
*/
$where = $this->_connection->quoteInto('store_id NOT IN (?)', array_keys($storeValues)) .
$this->_connection->quoteInto(' AND attribute_id = ?', $attributeId) .
$this->_connection->quoteInto(' AND entity_id = ?', $productId) .
$this->_connection->quoteInto(' AND entity_type_id = ?', $this->_entityTypeId);
$this->_connection->delete(
$tableName, $where
);
}
}
}
$this->_connection->insertOnDuplicate($tableName, $tableData, array('value'));
}
return $this;
}
/**
* Save product categories.
*
* @param array $categoriesData
* @return <API key>
*/
protected function <API key>(array $categoriesData)
{
static $tableName = null;
if (!$tableName) {
$tableName = Mage::getModel('importexport/<API key>')-><API key>();
}
if ($categoriesData) {
$categoriesIn = array();
$delProductId = array();
foreach ($categoriesData as $delSku => $categories) {
$productId = $this->_newSku[$delSku]['entity_id'];
$delProductId[] = $productId;
foreach (array_keys($categories) as $categoryId) {
$categoriesIn[] = array('product_id' => $productId, 'category_id' => $categoryId, 'position' => 1);
}
}
if (<API key>::BEHAVIOR_APPEND != $this->getBehavior()) {
$this->_connection->delete(
$tableName,
$this->_connection->quoteInto('product_id IN (?)', $delProductId)
);
}
if ($categoriesIn) {
$this->_connection->insertOnDuplicate($tableName, $categoriesIn, array('position'));
}
}
return $this;
}
/**
* Update and insert data in entity table.
*
* @param array $entityRowsIn Row for insert
* @param array $entityRowsUp Row for update
* @return <API key>
*/
protected function _saveProductEntity(array $entityRowsIn, array $entityRowsUp)
{
static $entityTable = null;
if (!$entityTable) {
$entityTable = Mage::getModel('importexport/<API key>')->getEntityTable();
}
if ($entityRowsUp) {
$this->_connection->insertOnDuplicate(
$entityTable,
$entityRowsUp,
array('updated_at')
);
}
if ($entityRowsIn) {
$this->_connection->insertMultiple($entityTable, $entityRowsIn);
$newProducts = $this->_connection->fetchPairs($this->_connection->select()
->from($entityTable, array('sku', 'entity_id'))
->where('sku IN (?)', array_keys($entityRowsIn))
);
foreach ($newProducts as $sku => $newId) { // fill up entity_id for new products
$this->_newSku[$sku]['entity_id'] = $newId;
}
}
return $this;
}
/**
* Gather and save information about product entities.
*
* @return <API key>
*/
protected function _saveProducts()
{
$priceIsGlobal = Mage::helper('catalog')->isPriceGlobal();
$productLimit = null;
$productsQty = null;
while ($bunch = $this->_dataSourceModel->getNextBunch()) {
$entityRowsIn = array();
$entityRowsUp = array();
$attributes = array();
$websites = array();
$categories = array();
$tierPrices = array();
$groupPrices = array();
$mediaGallery = array();
$<API key> = array();
$previousType = null;
$<API key> = null;
foreach ($bunch as $rowNum => $rowData) {
$this->_filterRowData($rowData);
if (!$this->validateRow($rowData, $rowNum)) {
continue;
}
$rowScope = $this->getRowScope($rowData);
if (self::SCOPE_DEFAULT == $rowScope) {
$rowSku = $rowData[self::COL_SKU];
// 1. Entity phase
if (isset($this->_oldSku[$rowSku])) { // existing row
$entityRowsUp[] = array(
'updated_at' => now(),
'entity_id' => $this->_oldSku[$rowSku]['entity_id']
);
} else { // new row
if (!$productLimit || $productsQty < $productLimit) {
$entityRowsIn[$rowSku] = array(
'entity_type_id' => $this->_entityTypeId,
'attribute_set_id' => $this->_newSku[$rowSku]['attr_set_id'],
'type_id' => $this->_newSku[$rowSku]['type_id'],
'sku' => $rowSku,
'created_at' => now(),
'updated_at' => now()
);
$productsQty++;
} else {
$rowSku = null; // sign for child rows to be skipped
$this->_rowsToSkip[$rowNum] = true;
continue;
}
}
} elseif (null === $rowSku) {
$this->_rowsToSkip[$rowNum] = true;
continue; // skip rows when SKU is NULL
} elseif (self::SCOPE_STORE == $rowScope) { // set necessary data from SCOPE_DEFAULT row
$rowData[self::COL_TYPE] = $this->_newSku[$rowSku]['type_id'];
$rowData['attribute_set_id'] = $this->_newSku[$rowSku]['attr_set_id'];
$rowData[self::COL_ATTR_SET] = $this->_newSku[$rowSku]['attr_set_code'];
}
if (!empty($rowData['_product_websites'])) { // 2. Product-to-Website phase
$websites[$rowSku][$this->_websiteCodeToId[$rowData['_product_websites']]] = true;
}
// 3. Categories phase
$categoryPath = empty($rowData[self::COL_CATEGORY]) ? '' : $rowData[self::COL_CATEGORY];
if (!empty($rowData[self::COL_ROOT_CATEGORY])) {
$categoryId = $this-><API key>[$rowData[self::COL_ROOT_CATEGORY]][$categoryPath];
$categories[$rowSku][$categoryId] = true;
} elseif (!empty($categoryPath)) {
$categories[$rowSku][$this->_categories[$categoryPath]] = true;
}
if (!empty($rowData['_tier_price_website'])) { // 4.1. Tier prices phase
$tierPrices[$rowSku][] = array(
'all_groups' => $rowData['<API key>'] == self::VALUE_ALL,
'customer_group_id' => ($rowData['<API key>'] == self::VALUE_ALL)
? 0 : $rowData['<API key>'],
'qty' => $rowData['_tier_price_qty'],
'value' => $rowData['_tier_price_price'],
'website_id' => (self::VALUE_ALL == $rowData['_tier_price_website'] || $priceIsGlobal)
? 0 : $this->_websiteCodeToId[$rowData['_tier_price_website']]
);
}
if (!empty($rowData['<API key>'])) { // 4.2. Group prices phase
$groupPrices[$rowSku][] = array(
'all_groups' => $rowData['<API key>'] == self::VALUE_ALL,
'customer_group_id' => ($rowData['<API key>'] == self::VALUE_ALL)
? 0 : $rowData['<API key>'],
'value' => $rowData['_group_price_price'],
'website_id' => (self::VALUE_ALL == $rowData['<API key>'] || $priceIsGlobal)
? 0 : $this->_websiteCodeToId[$rowData['<API key>']]
);
}
foreach ($this->_imagesArrayKeys as $imageCol) {
if (!empty($rowData[$imageCol])) { // 5. Media gallery phase
if (!array_key_exists($rowData[$imageCol], $<API key>)) {
$<API key>[$rowData[$imageCol]] = $this->_uploadMediaFiles($rowData[$imageCol]);
}
$rowData[$imageCol] = $<API key>[$rowData[$imageCol]];
}
}
if (!empty($rowData['_media_image'])) {
$mediaGallery[$rowSku][] = array(
'attribute_id' => isset($rowData['_media_attribute_id']) ? $rowData['_media_attribute_id'] : '',
'label' => isset($rowData['_media_lable']) ? $rowData['_media_lable'] : '',
'position' => isset($rowData['_media_position']) ? $rowData['_media_position'] : '',
'disabled' => isset($rowData['_media_is_disabled']) ? $rowData['_media_is_disabled'] : '',
'value' => $rowData['_media_image']
);
}
// 6. Attributes phase
$rowStore = self::SCOPE_STORE == $rowScope ? $this->_storeCodeToId[$rowData[self::COL_STORE]] : 0;
$productType = isset($rowData[self::COL_TYPE]) ? $rowData[self::COL_TYPE] : null;
if (!is_null($productType)) {
$previousType = $productType;
}
if (isset($rowData[self::COL_ATTR_SET]) && !is_null($rowData[self::COL_ATTR_SET])) {
$<API key> = $rowData[<API key>::COL_ATTR_SET];
}
if (self::SCOPE_NULL == $rowScope) {
// for multiselect attributes only
if (!is_null($<API key>)) {
$rowData[<API key>::COL_ATTR_SET] = $<API key>;
}
if (is_null($productType) && !is_null($previousType)) {
$productType = $previousType;
}
if (is_null($productType)) {
continue;
}
}
$rowData = $this->_productTypeModels[$productType]-><API key>(
$rowData,
!isset($this->_oldSku[$rowSku]) && (self::SCOPE_DEFAULT == $rowScope)
);
try {
$attributes = $this->_prepareAttributes($rowData, $rowScope, $attributes, $rowSku, $rowStore);
} catch (Exception $e) {
Mage::logException($e);
continue;
}
}
$this->_saveProductEntity($entityRowsIn, $entityRowsUp)
-><API key>($websites)
-><API key>($categories)
-><API key>($tierPrices)
-><API key>($groupPrices)
->_saveMediaGallery($mediaGallery)
-><API key>($attributes);
}
return $this;
}
/**
* Retrieve pattern for time formatting
*
* @return string
*/
protected function _getStrftimeFormat()
{
return Varien_Date::<API key>(Varien_Date::<API key>, true, true);
}
/**
* Retrieve attribute by specified code
*
* @param string $code
* @return <API key>
*/
protected function _getAttribute($code)
{
$attribute = Mage::getSingleton('importexport/<API key>')->getAttribute($code);
$backendModelName = (string)Mage::getConfig()->getNode(
'global/importexport/import/catalog_product/attributes/' . $attribute->getAttributeCode() . '/backend_model'
);
if (!empty($backendModelName)) {
$attribute->setBackendModel($backendModelName);
}
return $attribute;
}
/**
* Prepare attributes data
*
* @param array $rowData
* @param int $rowScope
* @param array $attributes
* @param string|null $rowSku
* @param int $rowStore
* @return array
*/
protected function _prepareAttributes($rowData, $rowScope, $attributes, $rowSku, $rowStore)
{
$product = Mage::getModel('importexport/<API key>', $rowData);
foreach ($rowData as $attrCode => $attrValue) {
$attribute = $this->_getAttribute($attrCode);
if ('multiselect' != $attribute->getFrontendInput()
&& self::SCOPE_NULL == $rowScope
) {
continue; // skip attribute processing for SCOPE_NULL rows
}
$attrId = $attribute->getId();
$backModel = $attribute->getBackendModel();
$attrTable = $attribute->getBackend()->getTable();
$storeIds = array(0);
if ('datetime' == $attribute->getBackendType() && strtotime($attrValue)) {
$attrValue = gmstrftime($this->_getStrftimeFormat(), strtotime($attrValue));
} elseif ('url_key' == $attribute->getAttributeCode()) {
if (empty($attrValue)) {
$attrValue = $product->formatUrlKey($product->getName());
}
} elseif ($backModel) {
$attribute->getBackend()->beforeSave($product);
$attrValue = $product->getData($attribute->getAttributeCode());
}
if (self::SCOPE_STORE == $rowScope) {
if (self::SCOPE_WEBSITE == $attribute->getIsGlobal()) {
// check website defaults already set
if (!isset($attributes[$attrTable][$rowSku][$attrId][$rowStore])) {
$storeIds = $this-><API key>[$rowStore];
} else {
$storeIds = array($rowStore);
}
} elseif (self::SCOPE_STORE == $attribute->getIsGlobal()) {
$storeIds = array($rowStore);
}
}
foreach ($storeIds as $storeId) {
if ('multiselect' == $attribute->getFrontendInput()) {
if (!isset($attributes[$attrTable][$rowSku][$attrId][$storeId])) {
$attributes[$attrTable][$rowSku][$attrId][$storeId] = '';
} else {
$attributes[$attrTable][$rowSku][$attrId][$storeId] .= ',';
}
$attributes[$attrTable][$rowSku][$attrId][$storeId] .= $attrValue;
} else {
$attributes[$attrTable][$rowSku][$attrId][$storeId] = $attrValue;
}
}
$attribute->setBackendModel($backModel); // restore 'backend_model' to avoid 'default' setting
}
return $attributes;
}
/**
* Save product tier prices.
*
* @param array $tierPriceData
* @return <API key>
*/
protected function <API key>(array $tierPriceData)
{
static $tableName = null;
if (!$tableName) {
$tableName = Mage::getModel('importexport/<API key>')
->getTable('catalog/<API key>');
}
if ($tierPriceData) {
$tierPriceIn = array();
$delProductId = array();
foreach ($tierPriceData as $delSku => $tierPriceRows) {
$productId = $this->_newSku[$delSku]['entity_id'];
$delProductId[] = $productId;
foreach ($tierPriceRows as $row) {
$row['entity_id'] = $productId;
$tierPriceIn[] = $row;
}
}
if (<API key>::BEHAVIOR_APPEND != $this->getBehavior()) {
$this->_connection->delete(
$tableName,
$this->_connection->quoteInto('entity_id IN (?)', $delProductId)
);
}
if ($tierPriceIn) {
$this->_connection->insertOnDuplicate($tableName, $tierPriceIn, array('value'));
}
}
return $this;
}
/**
* Save product group prices.
*
* @param array $groupPriceData
* @return <API key>
*/
protected function <API key>(array $groupPriceData)
{
static $tableName = null;
if (!$tableName) {
$tableName = Mage::getModel('importexport/<API key>')
->getTable('catalog/<API key>');
}
if ($groupPriceData) {
$groupPriceIn = array();
$delProductId = array();
foreach ($groupPriceData as $delSku => $groupPriceRows) {
$productId = $this->_newSku[$delSku]['entity_id'];
$delProductId[] = $productId;
foreach ($groupPriceRows as $row) {
$row['entity_id'] = $productId;
$groupPriceIn[] = $row;
}
}
if (<API key>::BEHAVIOR_APPEND != $this->getBehavior()) {
$this->_connection->delete(
$tableName,
$this->_connection->quoteInto('entity_id IN (?)', $delProductId)
);
}
if ($groupPriceIn) {
$this->_connection->insertOnDuplicate($tableName, $groupPriceIn, array('value'));
}
}
return $this;
}
/**
* Returns an object for upload a media files
*/
protected function _getUploader()
{
if (is_null($this->_fileUploader)) {
$this->_fileUploader = new <API key>();
$this->_fileUploader->init();
$tmpDir = Mage::getConfig()->getOptions()->getMediaDir() . '/import';
$destDir = Mage::getConfig()->getOptions()->getMediaDir() . '/catalog/product';
if (!is_writable($destDir)) {
@mkdir($destDir, 0777, true);
}
if (!$this->_fileUploader->setTmpDir($tmpDir)) {
Mage::throwException("File directory '{$tmpDir}' is not readable.");
}
if (!$this->_fileUploader->setDestDir($destDir)) {
Mage::throwException("File directory '{$destDir}' is not writable.");
}
}
return $this->_fileUploader;
}
/**
* Uploading files into the "catalog/product" media folder.
* Return a new file name if the same file is already exists.
*
* @param string $fileName
* @return string
*/
protected function _uploadMediaFiles($fileName)
{
try {
$res = $this->_getUploader()->move($fileName);
return $res['file'];
} catch (Exception $e) {
return '';
}
}
/**
* Save product media gallery.
*
* @param array $mediaGalleryData
* @return <API key>
*/
protected function _saveMediaGallery(array $mediaGalleryData)
{
if (empty($mediaGalleryData)) {
return $this;
}
static $<API key> = null;
static $mediaValueTableName = null;
static $productId = null;
if (!$<API key>) {
$<API key> = Mage::getModel('importexport/<API key>')
->getTable('catalog/<API key>');
}
if (!$mediaValueTableName) {
$mediaValueTableName = Mage::getModel('importexport/<API key>')
->getTable('catalog/<API key>');
}
foreach ($mediaGalleryData as $productSku => $mediaGalleryRows) {
$productId = $this->_newSku[$productSku]['entity_id'];
$insertedGalleryImgs = array();
if (<API key>::BEHAVIOR_APPEND != $this->getBehavior()) {
$this->_connection->delete(
$<API key>,
$this->_connection->quoteInto('entity_id IN (?)', $productId)
);
}
foreach ($mediaGalleryRows as $insertValue) {
if (!in_array($insertValue['value'], $insertedGalleryImgs)) {
$valueArr = array(
'attribute_id' => $insertValue['attribute_id'],
'entity_id' => $productId,
'value' => $insertValue['value']
);
$this->_connection
->insertOnDuplicate($<API key>, $valueArr, array('entity_id'));
$insertedGalleryImgs[] = $insertValue['value'];
}
$newMediaValues = $this->_connection->fetchPairs($this->_connection->select()
->from($<API key>, array('value', 'value_id'))
->where('entity_id IN (?)', $productId)
);
if (array_key_exists($insertValue['value'], $newMediaValues)) {
$insertValue['value_id'] = $newMediaValues[$insertValue['value']];
}
$valueArr = array(
'value_id' => $insertValue['value_id'],
'store_id' => <API key>::DEFAULT_STORE_ID,
'label' => $insertValue['label'],
'position' => $insertValue['position'],
'disabled' => $insertValue['disabled']
);
try {
$this->_connection
->insertOnDuplicate($mediaValueTableName, $valueArr, array('value_id'));
} catch (Exception $e) {
$this->_connection->delete(
$<API key>, $this->_connection->quoteInto('value_id IN (?)', $newMediaValues)
);
}
}
}
return $this;
}
/**
* Save product websites.
*
* @param array $websiteData
* @return <API key>
*/
protected function <API key>(array $websiteData)
{
static $tableName = null;
if (!$tableName) {
$tableName = Mage::getModel('importexport/<API key>')-><API key>();
}
if ($websiteData) {
$websitesData = array();
$delProductId = array();
foreach ($websiteData as $delSku => $websites) {
$productId = $this->_newSku[$delSku]['entity_id'];
$delProductId[] = $productId;
foreach (array_keys($websites) as $websiteId) {
$websitesData[] = array(
'product_id' => $productId,
'website_id' => $websiteId
);
}
}
if (<API key>::BEHAVIOR_APPEND != $this->getBehavior()) {
$this->_connection->delete(
$tableName,
$this->_connection->quoteInto('product_id IN (?)', $delProductId)
);
}
if ($websitesData) {
$this->_connection->insertOnDuplicate($tableName, $websitesData);
}
}
return $this;
}
/**
* Returns resource model
*
* @param string $resourceModelName
* @return Object
*/
protected function getResourceModel($resourceModelName)
{
return Mage::getResourceModel($resourceModelName);
}
/**
* Returns helper
*
* @param string $helperName
* @return <API key>
*/
protected function getHelper($helperName)
{
return Mage::helper($helperName);
}
/**
* Returns model
*
* @param string $modelName
* @return bool|<API key>
*/
protected function getModel($modelName)
{
return Mage::getModel($modelName);
}
/**
* Stock item saving.
*
* @return <API key>
*/
protected function _saveStockItem()
{
$defaultStockData = array(
'manage_stock' => 1,
'<API key>' => 1,
'qty' => 0,
'min_qty' => 0,
'use_config_min_qty' => 1,
'min_sale_qty' => 1,
'<API key>' => 1,
'max_sale_qty' => 10000,
'<API key>' => 1,
'is_qty_decimal' => 0,
'backorders' => 0,
'<API key>' => 1,
'notify_stock_qty' => 1,
'<API key>' => 1,
'<API key>' => 0,
'<API key>' => 1,
'qty_increments' => 0,
'<API key>' => 1,
'is_in_stock' => 0,
'low_stock_date' => null,
'<API key>' => 0,
'is_decimal_divided' => 0
);
$entityTable = $this->getResourceModel('cataloginventory/stock_item')->getMainTable();
$helper = $this->getHelper('catalogInventory');
while ($bunch = $this->getNextBunch()) {
$stockData = array();
// Format bunch to stock data rows
foreach ($bunch as $rowNum => $rowData) {
$this->_filterRowData($rowData);
if (!$this-><API key>($rowData, $rowNum)) {
continue;
}
// only SCOPE_DEFAULT can contain stock data
if (self::SCOPE_DEFAULT != $this->getRowScope($rowData)) {
continue;
}
$row = array();
$row['product_id'] = $this->_newSku[$rowData[self::COL_SKU]]['entity_id'];
$row['stock_id'] = 1;
/** @var $stockItem <API key> */
$stockItem = $this->getModel('cataloginventory/stock_item');
$stockItem->loadByProduct($row['product_id']);
$existStockData = $stockItem->getData();
$row = array_merge(
$defaultStockData,
array_intersect_key($existStockData, $defaultStockData),
array_intersect_key($rowData, $defaultStockData),
$row
);
$stockItem->setData($row);
unset($row);
if ($helper->isQty($this->_newSku[$rowData[self::COL_SKU]]['type_id'])) {
if ($stockItem->verifyNotification()) {
$stockItem->setLowStockDate(Mage::app()->getLocale()
->date(null, null, null, false)
->toString(Varien_Date::<API key>)
);
}
$stockItem-><API key>((int) !$stockItem->verifyStock());
} else {
$stockItem->setQty(0);
}
$stockData[] = $stockItem->unsetOldData()->getData();
}
// Insert rows
if ($stockData) {
$this->_connection->insertOnDuplicate($entityTable, $stockData);
}
}
return $this;
}
/**
* Removes empty keys in case value is null or empty string
*
* @param array $rowData
*/
protected function _filterRowData(&$rowData)
{
$rowData = array_filter($rowData, 'strlen');
// Exceptions - for sku - put them back in
if (!isset($rowData[self::COL_SKU])) {
$rowData[self::COL_SKU] = null;
}
}
/**
* Atttribute set ID-to-name pairs getter.
*
* @return array
*/
public function getAttrSetIdToName()
{
return $this->_attrSetIdToName;
}
/**
* DB connection getter.
*
* @return <API key>
*/
public function getConnection()
{
return $this->_connection;
}
/**
* EAV entity type code getter.
*
* @abstract
* @return string
*/
public function getEntityTypeCode()
{
return 'catalog_product';
}
/**
* New products SKU data.
*
* @return array
*/
public function getNewSku()
{
return $this->_newSku;
}
/**
* Get next bunch of validatetd rows.
*
* @return array|null
*/
public function getNextBunch()
{
return $this->_dataSourceModel->getNextBunch();
}
/**
* Existing products SKU getter.
*
* @return array
*/
public function getOldSku()
{
return $this->_oldSku;
}
/**
* Obtain scope of the row from row data.
*
* @param array $rowData
* @return int
*/
public function getRowScope(array $rowData)
{
if (isset($rowData[self::COL_SKU]) && strlen(trim($rowData[self::COL_SKU]))) {
return self::SCOPE_DEFAULT;
} elseif (empty($rowData[self::COL_STORE])) {
return self::SCOPE_NULL;
} else {
return self::SCOPE_STORE;
}
}
/**
* All website codes to ID getter.
*
* @return array
*/
public function getWebsiteCodes()
{
return $this->_websiteCodeToId;
}
/**
* Validate data row.
*
* @param array $rowData
* @param int $rowNum
* @return boolean
*/
public function validateRow(array $rowData, $rowNum)
{
static $sku = null; // SKU is remembered through all product rows
if (isset($this->_validatedRows[$rowNum])) { // check that row is already validated
return !isset($this->_invalidRows[$rowNum]);
}
$this->_validatedRows[$rowNum] = true;
if (isset($this->_newSku[$rowData[self::COL_SKU]])) {
$this->addRowError(self::ERROR_DUPLICATE_SKU, $rowNum);
return false;
}
$rowScope = $this->getRowScope($rowData);
// BEHAVIOR_DELETE use specific validation logic
if (<API key>::BEHAVIOR_DELETE == $this->getBehavior()) {
if (self::SCOPE_DEFAULT == $rowScope && !isset($this->_oldSku[$rowData[self::COL_SKU]])) {
$this->addRowError(self::<API key>, $rowNum);
return false;
}
return true;
}
$this->_validate($rowData, $rowNum, $sku);
if (self::SCOPE_DEFAULT == $rowScope) { // SKU is specified, row is SCOPE_DEFAULT, new product block begins
$this-><API key> ++;
$sku = $rowData[self::COL_SKU];
if (isset($this->_oldSku[$sku])) { // can we get all necessary data from existant DB product?
// check for supported type of existing product
if (isset($this->_productTypeModels[$this->_oldSku[$sku]['type_id']])) {
$this->_newSku[$sku] = array(
'entity_id' => $this->_oldSku[$sku]['entity_id'],
'type_id' => $this->_oldSku[$sku]['type_id'],
'attr_set_id' => $this->_oldSku[$sku]['attr_set_id'],
'attr_set_code' => $this->_attrSetIdToName[$this->_oldSku[$sku]['attr_set_id']]
);
} else {
$this->addRowError(self::<API key>, $rowNum);
$sku = false; // child rows of legacy products with unsupported types are orphans
}
} else { // validate new product type and attribute set
if (!isset($rowData[self::COL_TYPE])
|| !isset($this->_productTypeModels[$rowData[self::COL_TYPE]])
) {
$this->addRowError(self::ERROR_INVALID_TYPE, $rowNum);
} elseif (!isset($rowData[self::COL_ATTR_SET])
|| !isset($this->_attrSetNameToId[$rowData[self::COL_ATTR_SET]])
) {
$this->addRowError(self::<API key>, $rowNum);
} elseif (!isset($this->_newSku[$sku])) {
$this->_newSku[$sku] = array(
'entity_id' => null,
'type_id' => $rowData[self::COL_TYPE],
'attr_set_id' => $this->_attrSetNameToId[$rowData[self::COL_ATTR_SET]],
'attr_set_code' => $rowData[self::COL_ATTR_SET]
);
}
if (isset($this->_invalidRows[$rowNum])) {
// mark SCOPE_DEFAULT row as invalid for future child rows if product not in DB already
$sku = false;
}
}
} else {
if (null === $sku) {
$this->addRowError(self::ERROR_SKU_IS_EMPTY, $rowNum);
} elseif (false === $sku) {
$this->addRowError(self::ERROR_ROW_IS_ORPHAN, $rowNum);
} elseif (self::SCOPE_STORE == $rowScope && !isset($this->_storeCodeToId[$rowData[self::COL_STORE]])) {
$this->addRowError(self::ERROR_INVALID_STORE, $rowNum);
}
}
if (!isset($this->_invalidRows[$rowNum])) {
// set attribute set code into row data for followed attribute validation in type model
$rowData[self::COL_ATTR_SET] = $this->_newSku[$sku]['attr_set_code'];
$rowAttributesValid = $this->_productTypeModels[$this->_newSku[$sku]['type_id']]->isRowValid(
$rowData, $rowNum, !isset($this->_oldSku[$sku])
);
if (!$rowAttributesValid && self::SCOPE_DEFAULT == $rowScope) {
$sku = false; // mark SCOPE_DEFAULT row as invalid for future child rows
}
}
return !isset($this->_invalidRows[$rowNum]);
}
/**
* Common validation
*
* @param array $rowData
* @param int $rowNum
* @param string|false|null $sku
*/
protected function _validate($rowData, $rowNum, $sku)
{
$this-><API key>($rowData, $rowNum);
$this-><API key>($rowData, $rowNum);
$this->_isTierPriceValid($rowData, $rowNum);
$this->_isGroupPriceValid($rowData, $rowNum);
$this-><API key>($rowData, $rowNum);
$this->_isProductSkuValid($rowData, $rowNum);
}
/**
* Get array of affected products
*
* @return array
*/
public function <API key>()
{
$productIds = array();
while ($bunch = $this->_dataSourceModel->getNextBunch()) {
foreach ($bunch as $rowNum => $rowData) {
if (!$this-><API key>($rowData, $rowNum)) {
continue;
}
if (!isset($this->_newSku[$rowData[self::COL_SKU]]['entity_id'])) {
continue;
}
$productIds[] = $this->_newSku[$rowData[self::COL_SKU]]['entity_id'];
}
}
return $productIds;
}
/**
* Get product url_key attribute id
*
* @return null|int
*/
protected function <API key>()
{
if ($this->_urlKeyAttributeId === null) {
$adapter = $this->getConnection();
$resource = $this->getResourceModel('eav/entity_attribute');
$select = $adapter->select()
->from(
$resource->getMainTable(),
array('attribute_id')
)
->where('attribute_code = ?', 'url_key')
->where('entity_type_id = ?', $this->_entityTypeId);
$this->_urlKeyAttributeId = $adapter->fetchOne($select);
}
return $this->_urlKeyAttributeId;
}
} |
// TOLStarsView.h
// DeveloperAdsDemo
#import <UIKit/UIKit.h>
@interface TOLStarsView : UIView
- (instancetype)<API key>:(UIImage *)fullStarsImage emptyStars:(UIImage *)emptyStarsImage;
- (void)setPercentage:(CGFloat)percentage;
@end |
# import copy
# import sys
import unittest
from rdflib.graph import Graph
# from rdflib.namespace import NamespaceManager
from rdflib import (
# RDF,
# RDFS,
Namespace,
# Variable,
# Literal,
# URIRef,
# BNode
)
from rdflib.util import first
from FuXi.Rete.RuleStore import (
# N3RuleStore,
SetupRuleStore
)
# from FuXi.Rete import ReteNetwork
# from FuXi.Horn.PositiveConditions import <API key>
# from FuXi.Rete.RuleStore import N3RuleStore
# from FuXi.Rete.Util import generateTokenSet
from FuXi.Syntax.InfixOWL import *
from FuXi.DLP import (
SKOLEMIZED_CLASS_NS,
# MapDLPtoNetwork,
# <API key>
)
EX_NS = Namespace('http://example.com/')
EX = <API key>(EX_NS)
class <API key>(unittest.TestCase):
def setUp(self):
self.ontGraph = Graph()
self.ontGraph.bind('ex', EX_NS)
self.ontGraph.bind('owl', OWL_NS)
Individual.factoryGraph = self.ontGraph
def <API key>(self):
conjunct = EX.Foo & (EX.Omega | EX.Alpha)
(EX.Bar) += conjunct
ruleStore, ruleGraph, network = SetupRuleStore(
makeNetwork=True)
rules = network.<API key>(
self.ontGraph,
derivedPreds=[EX_NS.Bar],
addPDSemantics=False,
constructNetwork=False)
self.assertEqual(
repr(rules),
'set([Forall ?X ( ex:Bar(?X) :- And( ex:Foo(?X) ex:Alpha(?X) ) ), Forall ?X ( ex:Bar(?X) :- And( ex:Foo(?X) ex:Omega(?X) ) )])')
self.assertEqual(len(rules),
2,
"There should be 2 rules")
# def <API key>(self):
# someProp = Property(EX_NS.someProp)
# conjunct = EX.Foo & (someProp|only|EX.Omega)
# conjunct.identifier = EX_NS.Bar
# ruleStore,ruleGraph,network=SetupRuleStore(makeNetwork=True)
# self.failUnlessRaises(<API key>,
# network.<API key>,
# self.ontGraph,
# derivedPreds=[EX_NS.Bar],
# addPDSemantics=False,
# constructNetwork=False)
def <API key>(self):
(EX.Foo).equivalentClass = [EX.Bar]
self.assertEqual(repr(Class(EX_NS.Foo)),
"Class: ex:Foo EquivalentTo: ex:Bar")
ruleStore, ruleGraph, network = SetupRuleStore(
makeNetwork=True)
rules = network.<API key>(
self.ontGraph,
addPDSemantics=False,
constructNetwork=False)
self.assertEqual(
repr(rules),
'set([Forall ?X ( ex:Bar(?X) :- ex:Foo(?X) ), Forall ?X ( ex:Foo(?X) :- ex:Bar(?X) )])')
self.assertEqual(len(rules),
2,
"There should be 2 rules")
def <API key>(self):
someProp = Property(EX_NS.someProp)
existential = someProp | some | EX.Omega
existential += EX.Foo
self.assertEqual(
repr(Class(EX_NS.Foo)),
"Class: ex:Foo SubClassOf: ( ex:someProp SOME ex:Omega )")
ruleStore, ruleGraph, network = SetupRuleStore(
makeNetwork=True)
rules = network.<API key>(
self.ontGraph,
addPDSemantics=False,
constructNetwork=False)
# self.assertEqual(len(rules),
# "There should be 1 rule: %s"%rules)
# rule=rules[0]
# self.assertEqual(repr(rule.formula.body),
# "ex:Foo(?X)")
# self.assertEqual(len(rule.formula.head.formula),
def <API key>(self):
someProp = Property(EX_NS.someProp)
leftGCI = (someProp | value | EX.fish) & EX.Bar
foo = EX.Foo
foo += leftGCI
self.assertEqual(repr(leftGCI),
'ex:Bar THAT ( ex:someProp VALUE <http://example.com/fish> )')
ruleStore, ruleGraph, network = SetupRuleStore(makeNetwork=True)
rules = network.<API key>(
self.ontGraph,
addPDSemantics=False,
constructNetwork=False)
self.assertEqual(
repr(rules),
"set([Forall ?X ( ex:Foo(?X) :- " + \
"And( ex:someProp(?X ex:fish) ex:Bar(?X) ) )])")
def testNestedConjunct(self):
nestedConj = (EX.Foo & EX.Bar) & EX.Baz
(EX.Omega) += nestedConj
ruleStore, ruleGraph, network = SetupRuleStore(makeNetwork=True)
rules = network.<API key>(
self.ontGraph,
addPDSemantics=False,
constructNetwork=False)
for rule in rules:
if rule.formula.head.arg[-1] == EX_NS.Omega:
self.assertEqual(len(rule.formula.body), 2)
skolemPredicate = [term.arg[-1]
for term in rule.formula.body
if term.arg[-1].find(SKOLEMIZED_CLASS_NS) != -1]
self.assertEqual(len(skolemPredicate), 1,
"Couldn't find skolem unary predicate!")
else:
self.assertEqual(len(rule.formula.body), 2)
skolemPredicate = rule.formula.head.arg[-1]
self.failUnless(
skolemPredicate.find(SKOLEMIZED_CLASS_NS) != -1,
"Head should be a unary skolem predicate")
skolemPredicate = skolemPredicate[0]
def testOtherForm(self):
contains = Property(EX_NS.contains)
locatedIn = Property(EX_NS.locatedIn)
topConjunct = (
EX.Cath &
(contains | some |
(EX.MajorStenosis & (locatedIn | value | EX_NS.LAD))) &
(contains | some |
(EX.MajorStenosis & (locatedIn | value | EX_NS.RCA))))
(EX.NumDisV2D) += topConjunct
from FuXi.DLP.DLNormalization import NormalFormReduction
NormalFormReduction(self.ontGraph)
ruleStore, ruleGraph, network = SetupRuleStore(makeNetwork=True)
rules = network.<API key>(
self.ontGraph,
derivedPreds=[EX_NS.NumDisV2D],
addPDSemantics=False,
constructNetwork=False)
from FuXi.Rete.Magic import PrettyPrintRule
for rule in rules:
PrettyPrintRule(rule)
def testOtherForm2(self):
<API key> = Property(EX_NS.<API key>)
ITALeft = EX.ITALeft
ITALeft += (
<API key> | some | EnumeratedClass(members=[
EX_NS.<API key>,
EX_NS.<API key>]))
from FuXi.DLP.DLNormalization import NormalFormReduction
self.assertEquals(
repr(Class(first(ITALeft.subSumpteeIds()))),
"Some Class SubClassOf: Class: ex:ITALeft ")
NormalFormReduction(self.ontGraph)
self.assertEquals(
repr(Class(first(ITALeft.subSumpteeIds()))),
'Some Class SubClassOf: Class: ex:ITALeft . EquivalentTo: ( ( ex:<API key> VALUE <http:
if __name__ == '__main__':
unittest.main() |
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.<API key> = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.<API key> = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.<API key> = true
# temporarily disable Rails default printing of backtrace whenn pages are 404 or 500
config.<API key> = false
# Raises error for missing translations
# config.action_view.<API key> = true
# turn off deep_munge
# security flaw is minimal when turning it off for `provides`
config.action_dispatch.perform_deep_munge = false
end |
$(document).ready(function () {
$('select[id*="addressForm_country"]').click(function () {
url = $(this).parent().parent().parent().parent().data('countryurl');
$.ajax({
url: url,
type: "post",
dataType: "json",
data: "country="+$(this).val(),
success: function (result) {
selectTag = $('select[id*="addressForm_state"]');
selectTag.html();
// Test to see if JSON Response is Empty
if (!$.isEmptyObject(result)) {
selectTag.attr('disabled', false);
selectTag.removeClass('error');
selectTag.parent().parent().removeClass('error');
$('div[id^="addressForm_state"] > div > span[class*="help-block"]').hide();
$('div[class="symfony-form-errors"]').hide();
} else {
selectTag.attr('disabled', true);
}
selectOptions = '<option value="" disabled="disabled">Please select a state</option>';
$.each(result, function (index, element) {
selectOptions = selectOptions + '<option value="'+element.id+'">'+element.name+'</option>';
});
selectTag.html(selectOptions);
}
});
});
$('select[id*="addressForm_state"]').change(function () {
if ($(this).hasClass('error')) {
$(this).removeClass('error');
$(this).parent().parent().removeClass('error');
$('div[id^="addressForm_state"] > div > span[class*="help-block"]').hide();
$('div[class="symfony-form-errors"]').hide();
}
});
}); |
const series = require('./series');
const parallel = require('./parallel');
const batch = require('./batch');
// A sample promise which takes an argument
function promise(name) {
console.log('Begin task', name);
return new Promise((resolve) => {
setTimeout(() => {
console.log('Finish task', name);
return resolve();
}, 1000);
});
}
// Let's dance & sing some song
series(promise).then(() => parallel(promise)).then(() => batch(promise)); |
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M10 12c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zM6 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12-8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm-4 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm4-4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-4-4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-4-4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z" />
, 'GrainOutlined'); |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.CognitiveServices.Vision.Face
{
using Models;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
<summary>
Extension methods for <API key>.
</summary>
public static partial class <API key>
{
<summary>
Create an empty large face list with user-specified largeFaceListId, name,
an optional userData and recognitionModel.
<br /> Large face list is a list of faces, up to 1,000,000 faces, and
used by [Face - Find
Similar](/docs/services/<API key>/operations/<API key>).
<br /> After creation, user should use [LargeFaceList Face -
Add](/docs/services/<API key>/operations/<API key>)
to import the faces and [LargeFaceList -
Train](/docs/services/<API key>/operations/<API key>)
to make it ready for [Face -
FindSimilar](/docs/services/<API key>/operations/<API key>).
Faces are stored on server until [LargeFaceList -
Delete](/docs/services/<API key>/operations/<API key>)
is called.
<br /> Find Similar is used for scenario like finding celebrity-like
faces, similar face filtering, or as a light way face identification. But
if the actual use is to identify person, please use
[PersonGroup](/docs/services/<API key>/operations/<API key>)
/
[LargePersonGroup](/docs/services/<API key>/operations/<API key>)
and [Face -
Identify](/docs/services/<API key>/operations/<API key>).
<br />
* Free-tier subscription quota: 64 large face lists.
* S0-tier subscription quota: 1,000,000 large face lists.
<br />
'recognitionModel' should be specified to associate with this large face
list. The default value for 'recognitionModel' is 'recognition_01', if the
latest model needed, please explicitly specify the model you need in this
parameter. New faces that are added to an existing large face list will use
the recognition model that's already associated with the collection.
Existing face features in a large face list can't be updated to features
extracted by another version of recognition model.
</summary>
<param name='operations'>
The operations group for this extension method.
</param>
<param name='largeFaceListId'>
Id referencing a particular large face list.
</param>
<param name='name'>
User defined name, maximum length is 128.
</param>
<param name='userData'>
User specified data. Length should not exceed 16KB.
</param>
<param name='recognitionModel'>
Possible values include: 'recognition_01', 'recognition_02'
</param>
<param name='cancellationToken'>
The cancellation token.
</param>
public static async Task CreateAsync(this <API key> operations, string largeFaceListId, string name = default(string), string userData = default(string), string recognitionModel = default(string), Cancellation<API key> = default(CancellationToken))
{
(await operations.<API key>(largeFaceListId, name, userData, recognitionModel, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
<summary>
Retrieve a large face list’s largeFaceListId, name, userData and
recognitionModel.
</summary>
<param name='operations'>
The operations group for this extension method.
</param>
<param name='largeFaceListId'>
Id referencing a particular large face list.
</param>
<param name='<API key>'>
A value indicating whether the operation should return 'recognitionModel'
in response.
</param>
<param name='cancellationToken'>
The cancellation token.
</param>
public static async Task<LargeFaceList> GetAsync(this <API key> operations, string largeFaceListId, bool? <API key> = false, Cancellation<API key> = default(CancellationToken))
{
using (var _result = await operations.<API key>(largeFaceListId, <API key>, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
<summary>
Update information of a large face list.
</summary>
<param name='operations'>
The operations group for this extension method.
</param>
<param name='largeFaceListId'>
Id referencing a particular large face list.
</param>
<param name='name'>
User defined name, maximum length is 128.
</param>
<param name='userData'>
User specified data. Length should not exceed 16KB.
</param>
<param name='cancellationToken'>
The cancellation token.
</param>
public static async Task UpdateAsync(this <API key> operations, string largeFaceListId, string name = default(string), string userData = default(string), Cancellation<API key> = default(CancellationToken))
{
(await operations.<API key>(largeFaceListId, name, userData, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
<summary>
Delete an existing large face list according to faceListId. Persisted face
images in the large face list will also be deleted.
</summary>
<param name='operations'>
The operations group for this extension method.
</param>
<param name='largeFaceListId'>
Id referencing a particular large face list.
</param>
<param name='cancellationToken'>
The cancellation token.
</param>
public static async Task DeleteAsync(this <API key> operations, string largeFaceListId, Cancellation<API key> = default(CancellationToken))
{
(await operations.<API key>(largeFaceListId, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
<summary>
Retrieve the training status of a large face list (completed or ongoing).
</summary>
<param name='operations'>
The operations group for this extension method.
</param>
<param name='largeFaceListId'>
Id referencing a particular large face list.
</param>
<param name='cancellationToken'>
The cancellation token.
</param>
public static async Task<TrainingStatus> <API key>(this <API key> operations, string largeFaceListId, Cancellation<API key> = default(CancellationToken))
{
using (var _result = await operations.<API key>(largeFaceListId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
<summary>
List large face lists’ information of largeFaceListId, name, userData and
recognitionModel. <br />
To get face information inside largeFaceList use [LargeFaceList Face -
Get](/docs/services/<API key>/operations/<API key>)<br
/>
* Large face lists are stored in alphabetical order of largeFaceListId.
* "start" parameter (string, optional) is a user-provided largeFaceListId
value that returned entries have larger ids by string comparison. "start"
set to empty to indicate return from the first item.
* "top" parameter (int, optional) specifies the number of entries to
return. A maximal of 1000 entries can be returned in one call. To fetch
more, you can specify "start" with the last retuned entry’s Id of the
current call.
<br />
For example, total 5 large person lists: "list1", ..., "list5".
<br /> "start=&top=" will return all 5 lists.
<br /> "start=&top=2" will return "list1", "list2".
<br /> "start=list2&top=3" will return "list3", "list4", "list5".
</summary>
<param name='operations'>
The operations group for this extension method.
</param>
<param name='<API key>'>
A value indicating whether the operation should return 'recognitionModel'
in response.
</param>
<param name='cancellationToken'>
The cancellation token.
</param>
public static async Task<IList<LargeFaceList>> ListAsync(this <API key> operations, bool? <API key> = false, Cancellation<API key> = default(CancellationToken))
{
using (var _result = await operations.<API key>(<API key>, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
<summary>
Queue a large face list training task, the training task may not be started
immediately.
</summary>
<param name='operations'>
The operations group for this extension method.
</param>
<param name='largeFaceListId'>
Id referencing a particular large face list.
</param>
<param name='cancellationToken'>
The cancellation token.
</param>
public static async Task TrainAsync(this <API key> operations, string largeFaceListId, Cancellation<API key> = default(CancellationToken))
{
(await operations.<API key>(largeFaceListId, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
<summary>
Delete an existing face from a large face list (given by a persistedFaceId
and a largeFaceListId). Persisted image related to the face will also be
deleted.
</summary>
<param name='operations'>
The operations group for this extension method.
</param>
<param name='largeFaceListId'>
Id referencing a particular large face list.
</param>
<param name='persistedFaceId'>
Id referencing a particular persistedFaceId of an existing face.
</param>
<param name='cancellationToken'>
The cancellation token.
</param>
public static async Task DeleteFaceAsync(this <API key> operations, string largeFaceListId, System.Guid persistedFaceId, Cancellation<API key> = default(CancellationToken))
{
(await operations.<API key>(largeFaceListId, persistedFaceId, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
<summary>
Retrieve information about a persisted face (specified by persistedFaceId
and its belonging largeFaceListId).
</summary>
<param name='operations'>
The operations group for this extension method.
</param>
<param name='largeFaceListId'>
Id referencing a particular large face list.
</param>
<param name='persistedFaceId'>
Id referencing a particular persistedFaceId of an existing face.
</param>
<param name='cancellationToken'>
The cancellation token.
</param>
public static async Task<PersistedFace> GetFaceAsync(this <API key> operations, string largeFaceListId, System.Guid persistedFaceId, Cancellation<API key> = default(CancellationToken))
{
using (var _result = await operations.<API key>(largeFaceListId, persistedFaceId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
<summary>
Update a persisted face's userData field.
</summary>
<param name='operations'>
The operations group for this extension method.
</param>
<param name='largeFaceListId'>
Id referencing a particular large face list.
</param>
<param name='persistedFaceId'>
Id referencing a particular persistedFaceId of an existing face.
</param>
<param name='userData'>
User-provided data attached to the face. The size limit is 1KB.
</param>
<param name='cancellationToken'>
The cancellation token.
</param>
public static async Task UpdateFaceAsync(this <API key> operations, string largeFaceListId, System.Guid persistedFaceId, string userData = default(string), Cancellation<API key> = default(CancellationToken))
{
(await operations.<API key>(largeFaceListId, persistedFaceId, userData, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
<summary>
Add a face to a large face list. The input face is specified as an image
with a targetFace rectangle. It returns a persistedFaceId representing the
added face, and persistedFaceId will not expire.
</summary>
<param name='operations'>
The operations group for this extension method.
</param>
<param name='largeFaceListId'>
Id referencing a particular large face list.
</param>
<param name='url'>
Publicly reachable URL of an image
</param>
<param name='userData'>
User-specified data about the face for any purpose. The maximum length is
1KB.
</param>
<param name='targetFace'>
A face rectangle to specify the target face to be added to a person in the
format of "targetFace=left,top,width,height". E.g.
"targetFace=10,10,100,100". If there is more than one face in the image,
targetFace is required to specify which face to add. No targetFace means
there is only one face detected in the entire image.
</param>
<param name='cancellationToken'>
The cancellation token.
</param>
public static async Task<PersistedFace> AddFaceFromUrlAsync(this <API key> operations, string largeFaceListId, string url, string userData = default(string), IList<int> targetFace = default(IList<int>), Cancellation<API key> = default(CancellationToken))
{
using (var _result = await operations.<API key>(largeFaceListId, url, userData, targetFace, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
<summary>
List all faces in a large face list, and retrieve face information
(including userData and persistedFaceIds of registered faces of the face).
</summary>
<param name='operations'>
The operations group for this extension method.
</param>
<param name='largeFaceListId'>
Id referencing a particular large face list.
</param>
<param name='start'>
Starting face id to return (used to list a range of faces).
</param>
<param name='top'>
Number of faces to return starting with the face id indicated by the
'start' parameter.
</param>
<param name='cancellationToken'>
The cancellation token.
</param>
public static async Task<IList<PersistedFace>> ListFacesAsync(this <API key> operations, string largeFaceListId, string start = default(string), int? top = default(int?), Cancellation<API key> = default(CancellationToken))
{
using (var _result = await operations.<API key>(largeFaceListId, start, top, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
<summary>
Add a face to a large face list. The input face is specified as an image
with a targetFace rectangle. It returns a persistedFaceId representing the
added face, and persistedFaceId will not expire.
</summary>
<param name='operations'>
The operations group for this extension method.
</param>
<param name='largeFaceListId'>
Id referencing a particular large face list.
</param>
<param name='image'>
An image stream.
</param>
<param name='userData'>
User-specified data about the face for any purpose. The maximum length is
1KB.
</param>
<param name='targetFace'>
A face rectangle to specify the target face to be added to a person in the
format of "targetFace=left,top,width,height". E.g.
"targetFace=10,10,100,100". If there is more than one face in the image,
targetFace is required to specify which face to add. No targetFace means
there is only one face detected in the entire image.
</param>
<param name='cancellationToken'>
The cancellation token.
</param>
public static async Task<PersistedFace> <API key>(this <API key> operations, string largeFaceListId, Stream image, string userData = default(string), IList<int> targetFace = default(IList<int>), Cancellation<API key> = default(CancellationToken))
{
using (var _result = await operations.<API key>(largeFaceListId, image, userData, targetFace, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
} |
input[type="button"]:focus,
input[type="submit"]:focus {
outline: none !important;
} /*forms*/
a.focus {
outline: none !important;
}
body {
margin-bottom: 80px;
}
.page-header {
margin-top: 0;
}
.panel-body {
padding-top: 0;
}
img.icon {
width: 20%;
height: 20%;
padding: 1em;
}
img.about {
width: 15%;
height: 15%;
}
#personal-pic {
border-radius: 15px 50px 30px;
} |
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="it">
<head>
<!-- Generated by javadoc (version 1.7.0_03) on Wed Dec 04 15:38:03 CET 2013 -->
<title>Uses of Class jade.core.sam.SAMProxy (JADE v4.3.1 API)</title>
<meta name="date" content="2013-12-04">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class jade.core.sam.SAMProxy (JADE v4.3.1 API)";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../jade/core/sam/SAMProxy.html" title="class in jade.core.sam">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?jade/core/sam/\class-useSAMProxy.html" target="_top">Frames</a></li>
<li><a href="SAMProxy.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<h2 title="Uses of Class jade.core.sam.SAMProxy" class="title">Uses of Class<br>jade.core.sam.SAMProxy</h2>
</div>
<div class="classUseContainer">No usage of jade.core.sam.SAMProxy</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../jade/core/sam/SAMProxy.html" title="class in jade.core.sam">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?jade/core/sam/\class-useSAMProxy.html" target="_top">Frames</a></li>
<li><a href="SAMProxy.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip-navbar_bottom">
</a></div>
<p class="legalCopy"><small><center>These are the official <i><a href=http://jade.tilab.com target=top>JADE</a></i> API. For these API backward compatibility is guaranteed accross JADE versions</center></small></p>
</body>
</html> |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using DG.Tweening;
using LunarConsolePlugin;
using MoreMountains.NiceVibrations;
using Newtonsoft.Json;
using Polyglot;
using Proyecto26;
using Tayx.Graphy;
using Cysharp.Threading.Tasks;
using LiteDB;
using Sentry;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
public class Context : <API key><Context>
{
public int forceUploadScore = -1;
public float forceUploadAccuracy = -1f;
public const string VersionName = "2.1.1";
public const int VersionCode = 107;
public static string MockApiUrl;
public static CdnRegion CdnRegion => Player.Settings.CdnRegion;
public static string ApiUrl => Application.isEditor ? (MockApiUrl ?? CdnRegion.GetApiUrl()) : CdnRegion.GetApiUrl();
public static string WebsiteUrl => CdnRegion.GetWebsiteUrl();
public static string BundleRemoteBaseUrl
{
get
{
if (Application.isEditor && Instance.<API key>)
{
return $"file://{Application.dataPath.Replace("/Assets", "")}/AssetBundles";
}
else
{
return $"{CdnRegion.<API key>()}/platforms";
}
}
}
public static string StoreUrl => CdnRegion.GetStoreUrl();
public static string BundleRemoteFullUrl
{
get
{
#if UNITY_ANDROID
return $"{BundleRemoteBaseUrl}/Android/";
#elif UNITY_IOS
return $"{BundleRemoteBaseUrl}/iOS/";
#else
throw new <API key>();
#endif
}
}
public const string OfficialAccountId = "cytoid";
public const int ReferenceWidth = 1920;
public const int ReferenceHeight = 1080;
public const int LevelThumbnailWidth = 576;
public const int <API key> = 360;
public const int <API key> = 576;
public const int <API key> = 216;
public static int AndroidVersionCode = -1;
public static readonly <API key> PreSceneChanged = new <API key>();
public static readonly <API key> PostSceneChanged = new <API key>();
public static readonly UnityEvent <API key> = new UnityEvent();
public static bool IsInitialized { get; private set; }
public static readonly LevelEvent
<API key> = new LevelEvent(); // TODO: This feels definitely unnecessary. Integrate with screen?
public static readonly UnityEvent OnLanguageChanged = new UnityEvent();
public static readonly <API key> <API key> = new <API key>();
public static string UserDataPath;
public static string <API key>;
public static int InitialWidth;
public static int InitialHeight;
public static int <API key> { get; private set; }
public static AudioManager AudioManager;
public static ScreenManager ScreenManager;
public static readonly Library Library = new Library();
public static readonly FontManager FontManager = new FontManager();
public static readonly LevelManager LevelManager = new LevelManager();
public static readonly CharacterManager CharacterManager = new CharacterManager();
public static readonly BundleManager BundleManager = new BundleManager();
public static readonly AssetMemory AssetMemory = new AssetMemory();
public static LiteDatabase Database
{
get => database ?? (database = CreateDatabase());
private set => database = value;
}
private static LiteDatabase database;
private static bool <API key> = false;
public static Level SelectedLevel
{
get => selectedLevel;
set
{
selectedLevel = value;
<API key>.Invoke(value);
}
}
public static Difficulty SelectedDifficulty = Difficulty.Easy;
public static Difficulty PreferredDifficulty = Difficulty.Easy;
public static HashSet<Mod> SelectedMods = new HashSet<Mod>();
public static GameMode SelectedGameMode;
public static InitializationState InitializationState;
public static GameState GameState;
public static TierState TierState;
public static readonly Player Player = new Player();
public static readonly OnlinePlayer OnlinePlayer = new OnlinePlayer();
public static GameErrorState GameErrorState;
private static bool offline;
private static Level selectedLevel;
private static GraphyManager graphyManager;
private static Stack<Intent> <API key> = new Stack<Intent>();
public bool <API key> = true;
protected override void Awake()
{
base.Awake();
if (GameObject.<API key>("Context").Length > 1)
{
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
<API key>();
}
private static void OnLowMemory()
{
// TODO: This pops up on startup on iOS, lol
/*if (SceneManager.GetActiveScene().name == "Navigation")
{
Resources.UnloadUnusedAssets();
AudioManager.Get("ActionError").Play(ignoreDsp: true);
LoopAudioPlayer.Instance.StopAudio(0);
Dialog.PromptAlert("DIALOG_LOW_MEMORY".Get());
}*/
// TODO: Investigate on this
// Resources.UnloadUnusedAssets();
return;
AssetMemory.DisposeAllAssets();
if (SceneManager.GetActiveScene().name == "Navigation")
{
AudioManager.Get("ActionError").Play(ignoreDsp: true);
ScreenManager.History.Clear();
ScreenManager.ChangeScreen(MainMenuScreen.Id, ScreenTransition.In);
Dialog.PromptAlert("DIALOG_LOW_MEMORY".Get());
}
}
private void OnApplicationQuit()
{
Database?.Dispose();
}
private async void <API key>()
{
if (Application.platform == RuntimePlatform.Android)
{
// Get Android version
using (var version = new AndroidJavaClass("android.os.Build$VERSION")) {
AndroidVersionCode = version.GetStatic<int>("SDK_INT");
print("Android version code: " + AndroidVersionCode);
}
}
LunarConsole.SetConsoleEnabled(true); // Enable startup debug
InitializationState = new InitializationState();
UserDataPath = Application.persistentDataPath;
if (Application.platform == RuntimePlatform.Android)
{
var dir = <API key>();
if (dir == null)
{
Application.Quit();
return;
}
UserDataPath = dir + "/Cytoid";
}
else if (Application.platform == RuntimePlatform.IPhonePlayer)
{
// iOS 13 fix
<API key> = UserDataPath
.Replace("Documents/", "")
.Replace("Documents", "") + "/tmp/me.tigerhix.cytoid-Inbox/";
}
print("User data path: " + UserDataPath);
#if UNITY_EDITOR
Application.runInBackground = true;
#endif
if (SceneManager.GetActiveScene().name == "Navigation") StartupLogger.Instance.Initialize();
Debug.Log($"Package name: {Application.identifier}");
Application.lowMemory += OnLowMemory;
Application.targetFrameRate = 120;
Input.gyro.enabled = true;
DOTween.defaultEaseType = Ease.OutCubic;
UnityEngine.Screen.sleepTimeout = SleepTimeout.NeverSleep;
JsonConvert.DefaultSettings = () => new <API key>
{
Converters = new List<JsonConverter>
{
new UnityColorConverter()
},
<API key> = <API key>.Ignore
};
BsonMapper.Global.RegisterType
(
color => "#" + ColorUtility.ToHtmlStringRGB(color),
s => s.AsString.ToColor()
);
FontManager.LoadFonts();
if (Application.platform == RuntimePlatform.Android)
{
try
{
// Create an empty folder if it doesn't already exist
Directory.CreateDirectory(UserDataPath);
File.Create(UserDataPath + "/.nomedia").Dispose();
// Create and delete test file
var file = UserDataPath + "/" + Path.GetRandomFileName();
File.Create(file);
File.Delete(file);
}
catch (Exception e)
{
Debug.LogError(e);
Dialog.PromptUnclosable("<API key>".Get(
"<API key>".Get()));
return;
}
}
try
{
var timer = new BenchmarkTimer("LiteDB");
Database = CreateDatabase();
// Database.Checkpoint();
timer.Time();
}
catch (Exception e)
{
Debug.LogError(e);
Dialog.Instantiate().Also(it =>
{
it.UseNegativeButton = false;
it.UsePositiveButton = false;
it.Message =
"<API key>".Get(
"<API key>".Get());
}).Open();
return;
}
// LiteDB warm-up
Library.Initialize();
// Load settings
Player.Initialize();
// Initialize audio
var audioConfig = AudioSettings.GetConfiguration();
<API key> = audioConfig.dspBufferSize;
if (Application.isEditor)
{
audioConfig.dspBufferSize = 2048;
}
else if (Application.platform == RuntimePlatform.Android && Player.Settings.<API key> > 0)
{
audioConfig.dspBufferSize = Player.Settings.<API key>;
}
AudioSettings.Reset(audioConfig);
await UniTask.WaitUntil(() => AudioManager != null);
AudioManager.Initialize();
InitialWidth = UnityEngine.Screen.width;
InitialHeight = UnityEngine.Screen.height;
<API key>();
SelectedMods = new HashSet<Mod>(Player.Settings.EnabledMods);
PreSceneChanged.AddListener(OnPreSceneChanged);
PostSceneChanged.AddListener(OnPostSceneChanged);
OnLanguageChanged.AddListener(FontManager.UpdateSceneTexts);
Localization.Instance.SelectLanguage((Language) Player.Settings.Language);
OnLanguageChanged.Invoke();
// TODO: Add standalone support?
#if UNITY_IOS || UNITY_ANDROID
await BundleManager.Initialize();
#endif
if (Player.ShouldOneShot(StringKey.FirstLaunch))
{
Player.SetTrigger(StringKey.FirstLaunch);
}
switch (SceneManager.GetActiveScene().name)
{
case "Navigation":
if (Player.ShouldTrigger(StringKey.FirstLaunch, false))
{
InitializationState.FirstLaunchPhase = FirstLaunchPhase.GlobalCalibration;
// Global calibration
SelectedGameMode = GameMode.GlobalCalibration;
var sceneLoader = new SceneLoader("Game");
await sceneLoader.Load();
sceneLoader.Activate();
}
else
{
await <API key>();
}
break;
case "Game":
break;
}
await UniTask.DelayFrame(0);
graphyManager = GraphyManager.Instance;
<API key>();
IsInitialized = true;
<API key>.Invoke();
LunarConsole.SetConsoleEnabled(Player.Settings.UseDeveloperConsole);
<API key> = true;
}
private static async UniTask <API key>()
{
InitializationState.IsInitialized = true;
Debug.Log("Initializing character asset");
var timer = new BenchmarkTimer("Character");
if (await CharacterManager.SetActiveCharacter(CharacterManager.SelectedCharacterId) == null)
{
// Reset to default
CharacterManager.SelectedCharacterId = null;
MainMenuScreen.<API key> = true;
await CharacterManager.SetActiveCharacter(CharacterManager.SelectedCharacterId);
}
timer.Time();
await UniTask.WaitUntil(() => ScreenManager != null);
ScreenManager.ChangeScreen(<API key>.Id, ScreenTransition.None);
/*if (false)
{
ScreenManager.ChangeScreen(<API key>.Id, ScreenTransition.None);
}
if (false)
{
// Load f.fff
await LevelManager.<API key>(LevelType.User,
new List<string> {UserDataPath + "/f.fff/level.json"});
SelectedLevel = LevelManager.LoadedLocalLevels.Values.First();
SelectedDifficulty = Difficulty.Parse(SelectedLevel.Meta.charts[0].type);
ScreenManager.ChangeScreen("GamePreparation", ScreenTransition.None);
}
if (false)
{
// Load result
await LevelManager.<API key>(LevelType.User, new List<string>
{UserDataPath + "/fizzest.sentimental.crisis/level.json"});
SelectedLevel = LevelManager.LoadedLocalLevels.Values.First();
SelectedDifficulty =
Difficulty.Parse(LevelManager.LoadedLocalLevels.Values.First().Meta.charts.First().type);
ScreenManager.ChangeScreen(ResultScreen.Id, ScreenTransition.None);
}
if (false)
{
// Load result
ScreenManager.ChangeScreen(TierResultScreen.Id, ScreenTransition.None);
}*/
}
public async UniTask DetectServerCdn()
{
if (!Player.ShouldOneShot("Detect Server CDN")) return;
Debug.Log("Detecting server CDN");
if (Distribution == Distribution.Global)
{
var resolved = false;
var startTime = DateTimeOffset.Now;
RestClient.Get<RegionInfo>(new RequestHelper
{
Uri = "https://services.cytoid.io/ping",
Timeout = 5,
EnableDebug = true
}).Then(it =>
{
Player.Settings.CdnRegion = it.countryCode == "CN" ? CdnRegion.MainlandChina : CdnRegion.International;
resolved = true;
}).CatchRequestError(error =>
{
Debug.LogWarning(error);
RestClient.Get(new RequestHelper
{
Uri = "https://api.cytoid.cn/ping",
Timeout = 5,
EnableDebug = true
}).Then(x => { Player.Settings.CdnRegion = CdnRegion.MainlandChina; }).CatchRequestError(x =>
{
Debug.LogWarning(x);
Player.ClearOneShot("Detect Server CDN");
}).Finally(() => resolved = true);
});
await UniTask.WaitUntil(() => resolved || DateTimeOffset.Now - startTime > TimeSpan.FromSeconds(10));
if (!resolved)
{
Player.Settings.CdnRegion = CdnRegion.MainlandChina;
}
}
else if (Distribution == Distribution.TapTap)
{
Player.Settings.CdnRegion = CdnRegion.MainlandChina;
}
Debug.Log($"Detected: {Player.Settings.CdnRegion}");
}
public async UniTask CheckServerCdn()
{
void SwitchToOffline()
{
Toast.Enqueue(Toast.Status.Success, "<API key>".Get());
SetOffline(true);
OnlinePlayer.FetchProfile().Then(it =>
{
if (it == null)
{
OnlinePlayer.Deauthenticate();
}
else
{
OnlinePlayer.LastProfile = it;
OnlinePlayer.IsAuthenticated = true;
}
}).Catch(exception => throw new <API key>()); // Impossible
}
var resolved = false;
var startTime = DateTimeOffset.Now;
Debug.Log("Checking server CDN");
if (Player.Settings.CdnRegion == CdnRegion.MainlandChina)
{
RestClient.Get(new RequestHelper
{
Uri = "https://api.cytoid.cn/ping",
Timeout = 5,
EnableDebug = true
}).Then(_ =>
{
resolved = true;
}).CatchRequestError(error =>
{
Debug.LogWarning("Could not connect to CN");
Debug.LogWarning(error);
RestClient.Get<RegionInfo>(new RequestHelper
{
Uri = "https://services.cytoid.io/ping",
Timeout = 5,
EnableDebug = true
}).Then(it =>
{
resolved = true;
Player.Settings.CdnRegion = CdnRegion.International;
Dialog.PromptAlert("\n");
Player.SetTrigger("Reset Server CDN To CN");
}).CatchRequestError(it =>
{
Debug.LogWarning("Could not connect to IO");
Debug.LogWarning(it);
SwitchToOffline();
}).Finally(() => resolved = true);
});
await UniTask.WaitUntil(() => resolved || DateTimeOffset.Now - startTime > TimeSpan.FromSeconds(10));
}
else if (Player.Settings.CdnRegion == CdnRegion.International)
{
RestClient.Get<RegionInfo>(new RequestHelper
{
Uri = "https://services.cytoid.io/ping",
Timeout = 5,
EnableDebug = true
}).CatchRequestError(it =>
{
Debug.LogWarning("Could not connect to IO");
Debug.LogWarning(it);
SwitchToOffline();
}).Finally(() => resolved = true);
await UniTask.WaitUntil(() => resolved || DateTimeOffset.Now - startTime > TimeSpan.FromSeconds(5));
}
}
public static void OnPreSceneChanged(string prev, string next)
{
switch (prev)
{
case "Navigation" when next == "Game":
Input.gyro.enabled = false;
// Save history
<API key> = new Stack<Intent>(ScreenManager.History);
break;
}
}
public static async void OnPostSceneChanged(string prev, string next)
{
switch (prev)
{
case "Navigation" when next == "Game":
OnlinePlayer.IsAuthenticating = false;
CharacterManager.<API key>();
BundleManager.ReleaseAll();
break;
case "Game" when next == "Navigation":
{
Input.gyro.enabled = true;
AudioManager.Initialize();
<API key>();
if (InitializationState.IsDuringFirstLaunch())
{
switch (InitializationState.FirstLaunchPhase)
{
case FirstLaunchPhase.GlobalCalibration:
// Proceed to basic tutorial
InitializationState.FirstLaunchPhase = FirstLaunchPhase.BasicTutorial;
SelectedGameMode = GameMode.Practice;
SelectedLevel = await LevelManager.<API key>(BuiltInData.TutorialLevelId,
LevelType.BuiltIn, true);
SelectedDifficulty = Difficulty.Easy;
SelectedMods.Clear();
Player.Settings.DisplayBoundaries = true;
var sceneLoader = new SceneLoader("Game");
await UniTask.WhenAll(sceneLoader.Load(), UniTask.Delay(TimeSpan.FromSeconds(1f)));
sceneLoader.Activate();
break;
case FirstLaunchPhase.BasicTutorial:
// Save the high score, but let's not show the results screen
if (GameState.IsCompleted)
{
var record = GameState.Level.Record;
record.<API key>(GameState.Difficulty);
record.<API key>(GameState.Mode, GameState.Difficulty,
(int) GameState.Score, GameState.Accuracy);
GameState.Level.SaveRecord();
}
Player.ClearTrigger(StringKey.FirstLaunch);
InitializationState.FirstLaunchPhase = FirstLaunchPhase.Completed;
await UniTask.Delay(TimeSpan.FromSeconds(1f));
// Initialize navigation like normal
await <API key>();
break;
default:
throw new <API key>();
}
}
else
{
// Wait until character is loaded
await CharacterManager.<API key>();
// Restore history
ScreenManager.History = new Stack<Intent>(<API key>);
var gotoResult = false;
var isSpecialGameMode = false;
if (TierState != null)
{
if (TierState.CurrentStage.IsCompleted)
{
gotoResult = true;
// Show tier break screen
ScreenManager.ChangeScreen(TierBreakScreen.Id, ScreenTransition.None,
<API key>: false);
}
else
{
TierState = null;
OnlinePlayer.LastFullProfile = null; // Allow full profile to update
// Show tier selection screen
ScreenManager.ChangeScreen(ScreenManager.PeekHistory(), ScreenTransition.None,
<API key>: false);
}
}
else if (GameState != null)
{
if (GameState.Mode == GameMode.GlobalCalibration)
{
isSpecialGameMode = true;
// Clear history and just go to main menu
ScreenManager.History = new Stack<Intent>();
ScreenManager.ChangeScreen(MainMenuScreen.Id, ScreenTransition.In);
}
else
{
var usedAuto = GameState.Mods.Contains(Mod.Auto) || GameState.Mods.Contains(Mod.AutoDrag) ||
GameState.Mods.Contains(Mod.AutoHold) ||
GameState.Mods.Contains(Mod.AutoFlick);
if (GameState.IsCompleted &&
(GameState.Mode == GameMode.Standard || GameState.Mode == GameMode.Practice) &&
!usedAuto)
{
gotoResult = true;
OnlinePlayer.LastFullProfile = null; // Allow full profile to update
// Show result screen
ScreenManager.ChangeScreen(ResultScreen.Id, ScreenTransition.None,
<API key>: false);
}
else
{
// Show game preparation screen
ScreenManager.ChangeScreen(ScreenManager.PeekHistory(), ScreenTransition.None,
<API key>: false);
}
}
}
else
{
// There must have been an error, show last screen
ScreenManager.ChangeScreen(ScreenManager.PeekHistory(), ScreenTransition.None,
<API key>: false);
}
if (!gotoResult && !isSpecialGameMode)
{
var backdrop = NavigationBackdrop.Instance;
backdrop.IsVisible = false;
backdrop.IsBlurred = true;
backdrop.FadeBrightness(1);
}
if (GameErrorState != null)
{
Dialog.PromptAlert(GameErrorState.Message);
GameErrorState = null;
}
}
break;
}
}
FontManager.UpdateSceneTexts();
// Database.Checkpoint();
}
public static void Haptic(HapticTypes type, bool menu)
{
if (!Application.isEditor && Application.platform == RuntimePlatform.IPhonePlayer)
{
if (!(menu ? Player.Settings.MenuTapticFeedback : Player.Settings.HitTapticFeedback)) return;
MMVibrationManager.Haptic(type);
}
}
public static void SetAutoRotation(bool autoRotation)
{
if (autoRotation)
{
UnityEngine.Screen.<API key> = true;
UnityEngine.Screen.<API key> = true;
}
else
{
if (UnityEngine.Screen.orientation != ScreenOrientation.LandscapeLeft)
UnityEngine.Screen.<API key> = false;
if (UnityEngine.Screen.orientation != ScreenOrientation.LandscapeRight)
UnityEngine.Screen.<API key> = false;
}
}
public string <API key>()
{
if (Application.platform != RuntimePlatform.Android) return "";
return AndroidVersionCode <= 29 ? <API key>() : Application.persistentDataPath;
}
public string <API key>()
{
try
{
using (var javaClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
using (var activityClass = javaClass.GetStatic<AndroidJavaObject>("currentActivity"))
{
return activityClass.Call<AndroidJavaObject>("<API key>")
.Call<string>("getAbsolutePath");
}
}
}
catch (Exception e)
{
Debug.LogError("Could not get Android storage path: " + e.Message);
return null;
}
}
public static void <API key>()
{
print("Profiler display: " + Player.Settings.DisplayProfiler);
if (graphyManager == null) return;
if (Player.Settings.DisplayProfiler)
{
graphyManager.Enable();
graphyManager.FpsModuleState = GraphyManager.ModuleState.FULL;
graphyManager.RamModuleState = GraphyManager.ModuleState.FULL;
graphyManager.AudioModuleState = GraphyManager.ModuleState.FULL;
}
else
{
graphyManager.Disable();
}
}
public static void <API key>()
{
var quality = Player.Settings.GraphicsQuality;
switch (quality)
{
case GraphicsQuality.Ultra:
case GraphicsQuality.High:
UnityEngine.Screen.SetResolution(InitialWidth, InitialHeight, FullScreenMode.ExclusiveFullScreen);
break;
case GraphicsQuality.Medium:
UnityEngine.Screen.SetResolution((int) (InitialWidth * 0.7f),
(int) (InitialHeight * 0.7f), FullScreenMode.ExclusiveFullScreen);
break;
case GraphicsQuality.Low:
UnityEngine.Screen.SetResolution((int) (InitialWidth * 0.5f),
(int) (InitialHeight * 0.5f), FullScreenMode.ExclusiveFullScreen);
break;
case GraphicsQuality.VeryLow:
UnityEngine.Screen.SetResolution((int) (InitialWidth * 0.3f),
(int) (InitialHeight * 0.3f), FullScreenMode.ExclusiveFullScreen);
break;
}
var backdrop = NavigationBackdrop.Instance;
if (backdrop != null)
{
backdrop.HighQuality = quality >= GraphicsQuality.High;
}
}
public static void <API key>(bool blocksRaycasts)
{
if (ScreenManager == null) return;
if (ScreenManager.ActiveScreenId != null)
{
ScreenManager.ActiveScreen.SetBlockRaycasts(blocksRaycasts);
}
if (ProfileWidget.Instance != null)
{
var currentScreenId = ScreenManager.ActiveScreenId;
blocksRaycasts = blocksRaycasts
&& !ProfileWidget.HiddenScreenIds.Contains(currentScreenId)
&& !ProfileWidget.StaticScreenIds.Contains(currentScreenId);
ProfileWidget.Instance.canvasGroup.blocksRaycasts = blocksRaycasts;
ProfileWidget.Instance.canvasGroup.interactable = blocksRaycasts;
}
}
public static bool <API key>()
{
return SceneManager.GetActiveScene().name == "Navigation" && !Player.Settings.UseMenuTransitions;
}
public static bool IsOffline() => offline;
public static bool IsOnline() => !IsOffline();
public static void SetOffline(bool offline)
{
Context.offline = offline;
<API key>.Invoke(offline);
}
private void OnApplicationFocus(bool hasFocus)
{
if (<API key> && !hasFocus && Database != null)
{
// Database.Checkpoint();
Database.Dispose();
Database = null;
}
}
private void OnApplicationPause(bool pauseStatus)
{
if (<API key> && pauseStatus && Database != null)
{
// Database.Checkpoint();
Database.Dispose();
Database = null;
}
}
private static LiteDatabase CreateDatabase()
{
var dbPath = Path.Combine(Application.persistentDataPath, "Cytoid.db");
LiteDatabase NewDatabase()
{
return new LiteDatabase(
new ConnectionString
{
Filename = dbPath,
Connection = ConnectionType.Direct
}
);
}
LiteDatabase db = null;
try
{
db = NewDatabase();
}
catch (Exception e)
{
Debug.Log(e);
Debug.Log($"Could not read {dbPath}");
}
if (db?.GetCollection<LocalPlayerSettings>("settings").FindOne(Query.All()) != null)
{
// Is there too many backups already?
var snapshots = Directory.GetFiles(Application.persistentDataPath, ".snapshot-*").ToList();
snapshots.Sort(string.CompareOrdinal);
if (snapshots.Count > 5)
{
snapshots.Take(snapshots.Count - 5).ForEach(File.Delete);
Debug.Log($"Removed {snapshots.Count - 5} obsolete snapshots");
}
// Make a backup
File.Copy(dbPath, Path.Combine(Application.persistentDataPath, ".snapshot-" + DateTimeOffset.UtcNow.<API key>()), true);
Debug.Log("Database snapshot complete");
}
else
{
// Is there backups?
var snapshots = Directory.GetFiles(Application.persistentDataPath, ".snapshot-*").ToList();
if (snapshots.Count == 0) return db ?? NewDatabase();
db?.Dispose();
File.Delete(dbPath);
snapshots.Sort((a, b) => string.CompareOrdinal(b, a));
string rolledBackFrom = null;
foreach (var snapshotPath in snapshots)
{
Debug.Log($"Rolling back from {snapshotPath}");
File.Copy(snapshotPath, dbPath, true);
LiteDatabase snapshotDb = null;
try
{
snapshotDb = new LiteDatabase(
new ConnectionString
{
Filename = dbPath,
Connection = ConnectionType.Direct
}
);
}
catch (Exception e)
{
Debug.Log(e);
Debug.Log($"Could not read {snapshotPath}");
}
if (snapshotDb?.GetCollection<LocalPlayerSettings>("settings").FindOne(Query.All()) != null)
{
db = snapshotDb;
Debug.Log("Rollback success");
rolledBackFrom = snapshotPath;
break;
}
Debug.Log($"Could not roll back from {snapshotPath}");
snapshotDb?.Dispose();
File.Delete(snapshotPath);
}
if (rolledBackFrom == null) {
return NewDatabase();
}
}
return db;
}
public static Distribution Distribution
{
get
{
switch (Application.identifier)
{
case "me.tigerhix.cytoid": return Distribution.Global;
case "me.tigerhix.cytoid.cn": return Distribution.TapTap;
}
throw new <API key>();
}
}
}
public enum Distribution
{
Global, TapTap
}
public class <API key> : UnityEvent<bool>
{
}
public class GameErrorState
{
public string Message;
public Exception Exception;
} |
import json
from pprint import pprint
from sys import argv
jsonFile = argv[1]
with open(jsonFile) as data_file:
data = json.load(data_file)
for i in range(0, data['resultCount']):
if data['results'][i]['trackCount'] != 1:
print(data['results'][i]['collectionName']), data['results'][i]['releaseDate']
# sort by release date
pprint(data) |
// 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,
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// included in all copies or substantial portions of the Software.
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// 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.
/*global define: true*/
"use strict";
define("dummy", function () {
return {
index: function (api) {
api.use("mojito-addon-render", function () {
api.render({msg: "dummy"}, "dummy-tmpls", "index");
});
}
};
}); |
package toybroker
import (
"errors"
"reflect"
"testing"
)
func <API key>(t *testing.T) {
var err error
mb1 := <API key>("foo", 0)
mb2 := <API key>("bar", 0)
mb1.Set(1, []byte{1, 2, 3})
mb1.Set(2, []byte{4, 5, 6})
mb2.Set(1, []byte{7, 8, 9})
if len(mb1.List()) != 2 {
err = errors.New("mb1.List()")
}
if !reflect.DeepEqual(mb1.Get(1), []byte{1, 2, 3}) {
err = errors.New("mb1.Get(1)")
}
if !reflect.DeepEqual(mb1.Get(2), []byte{4, 5, 6}) {
err = errors.New("mb1.Get(2)")
}
if len(mb2.List()) != 1 {
err = errors.New("mb2.List()")
}
mb2.SetRetrySeconds(3600)
if len(mb2.List()) == 0 {
err = errors.New("mb2.SetRetrySeconds()")
}
mb1.Delete(1)
if len(mb1.List()) != 1 {
err = errors.New("mb1.Delete()")
}
if mb1.Get(1) != nil {
err = errors.New("mb1.Get(1) is not nil")
}
if err != nil {
t.Error(err.Error())
}
} |
CREATE TABLE `<API key>` (
`ID` bigint NOT NULL AUTO_INCREMENT PRIMARY KEY,
`idGroup` bigint NOT NULL,
`prefix` varchar(100) NOT NULL,
`iVersion` bigint NOT NULL
) ENGINE='InnoDB' COLLATE 'utf8_unicode_ci';
ALTER TABLE `<API key>`
ADD INDEX `idGroup` (`idGroup`);
CREATE TABLE `<API key>` (
`historyID` bigint NOT NULL AUTO_INCREMENT PRIMARY KEY,
`ID` bigint NOT NULL,
`idGroup` bigint NOT NULL,
`prefix` varchar(100) NOT NULL,
`iVersion` bigint NOT NULL,
`iNextVersion` bigint NULL,
`bDeleted` tinyint NOT NULL DEFAULT '0'
) ENGINE='InnoDB' COLLATE 'utf8_unicode_ci'; |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::MediaServices::Mgmt::V2018_07_01
# AssetFilters
class AssetFilters
include MsRestAzure
# Creates and initializes a new instance of the AssetFilters class.
# @param client service class for accessing basic functionality.
def initialize(client)
@client = client
end
# @return [AzureMediaServices] reference to the AzureMediaServices
attr_reader :client
# List Asset Filters
# List Asset Filters associated with the specified Asset.
# @param resource_group_name [String] The name of the resource group within the
# Azure subscription.
# @param account_name [String] The Media Services account name.
# @param asset_name [String] The Asset name.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
# @return [Array<AssetFilter>] operation results.
def list(resource_group_name, account_name, asset_name, custom_headers:nil)
first_page = list_as_lazy(resource_group_name, account_name, asset_name, custom_headers:custom_headers)
first_page.get_all_items
end
# List Asset Filters
# List Asset Filters associated with the specified Asset.
# @param resource_group_name [String] The name of the resource group within the
# Azure subscription.
# @param account_name [String] The Media Services account name.
# @param asset_name [String] The Asset name.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
# @return [MsRestAzure::<API key>] HTTP response information.
def list_with_http_info(resource_group_name, account_name, asset_name, custom_headers:nil)
list_async(resource_group_name, account_name, asset_name, custom_headers:custom_headers).value!
end
# List Asset Filters
# List Asset Filters associated with the specified Asset.
# @param resource_group_name [String] The name of the resource group within the
# Azure subscription.
# @param account_name [String] The Media Services account name.
# @param asset_name [String] The Asset name.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
def list_async(resource_group_name, account_name, asset_name, custom_headers:nil)
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'account_name is nil' if account_name.nil?
fail ArgumentError, 'asset_name is nil' if asset_name.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['<API key>'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}/assetFilters'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::<API key>, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'accountName' => account_name,'assetName' => asset_name},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.<API key> = http_response['<API key>'] unless http_response['<API key>'].nil?
result.client_request_id = http_response['<API key>'] unless http_response['<API key>'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::MediaServices::Mgmt::V2018_07_01::Models::<API key>.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::<API key>.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
# Get an Asset Filter.
# Get the details of an Asset Filter associated with the specified Asset.
# @param resource_group_name [String] The name of the resource group within the
# Azure subscription.
# @param account_name [String] The Media Services account name.
# @param asset_name [String] The Asset name.
# @param filter_name [String] The Asset Filter name
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
# @return [AssetFilter] operation results.
def get(resource_group_name, account_name, asset_name, filter_name, custom_headers:nil)
response = get_async(resource_group_name, account_name, asset_name, filter_name, custom_headers:custom_headers).value!
response.body unless response.nil?
end
# Get an Asset Filter.
# Get the details of an Asset Filter associated with the specified Asset.
# @param resource_group_name [String] The name of the resource group within the
# Azure subscription.
# @param account_name [String] The Media Services account name.
# @param asset_name [String] The Asset name.
# @param filter_name [String] The Asset Filter name
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
# @return [MsRestAzure::<API key>] HTTP response information.
def get_with_http_info(resource_group_name, account_name, asset_name, filter_name, custom_headers:nil)
get_async(resource_group_name, account_name, asset_name, filter_name, custom_headers:custom_headers).value!
end
# Get an Asset Filter.
# Get the details of an Asset Filter associated with the specified Asset.
# @param resource_group_name [String] The name of the resource group within the
# Azure subscription.
# @param account_name [String] The Media Services account name.
# @param asset_name [String] The Asset name.
# @param filter_name [String] The Asset Filter name
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
def get_async(resource_group_name, account_name, asset_name, filter_name, custom_headers:nil)
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'account_name is nil' if account_name.nil?
fail ArgumentError, 'asset_name is nil' if asset_name.nil?
fail ArgumentError, 'filter_name is nil' if filter_name.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['<API key>'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}/assetFilters/{filterName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::<API key>, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'accountName' => account_name,'assetName' => asset_name,'filterName' => filter_name},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200 || status_code == 404
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.<API key> = http_response['<API key>'] unless http_response['<API key>'].nil?
result.client_request_id = http_response['<API key>'] unless http_response['<API key>'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::MediaServices::Mgmt::V2018_07_01::Models::AssetFilter.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::<API key>.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
# Create or update an Asset Filter
# Creates or updates an Asset Filter associated with the specified Asset.
# @param resource_group_name [String] The name of the resource group within the
# Azure subscription.
# @param account_name [String] The Media Services account name.
# @param asset_name [String] The Asset name.
# @param filter_name [String] The Asset Filter name
# @param parameters [AssetFilter] The request parameters
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
# @return [AssetFilter] operation results.
def create_or_update(resource_group_name, account_name, asset_name, filter_name, parameters, custom_headers:nil)
response = <API key>(resource_group_name, account_name, asset_name, filter_name, parameters, custom_headers:custom_headers).value!
response.body unless response.nil?
end
# Create or update an Asset Filter
# Creates or updates an Asset Filter associated with the specified Asset.
# @param resource_group_name [String] The name of the resource group within the
# Azure subscription.
# @param account_name [String] The Media Services account name.
# @param asset_name [String] The Asset name.
# @param filter_name [String] The Asset Filter name
# @param parameters [AssetFilter] The request parameters
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
# @return [MsRestAzure::<API key>] HTTP response information.
def <API key>(resource_group_name, account_name, asset_name, filter_name, parameters, custom_headers:nil)
<API key>(resource_group_name, account_name, asset_name, filter_name, parameters, custom_headers:custom_headers).value!
end
# Create or update an Asset Filter
# Creates or updates an Asset Filter associated with the specified Asset.
# @param resource_group_name [String] The name of the resource group within the
# Azure subscription.
# @param account_name [String] The Media Services account name.
# @param asset_name [String] The Asset name.
# @param filter_name [String] The Asset Filter name
# @param parameters [AssetFilter] The request parameters
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
def <API key>(resource_group_name, account_name, asset_name, filter_name, parameters, custom_headers:nil)
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'account_name is nil' if account_name.nil?
fail ArgumentError, 'asset_name is nil' if asset_name.nil?
fail ArgumentError, 'filter_name is nil' if filter_name.nil?
fail ArgumentError, 'parameters is nil' if parameters.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['<API key>'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::MediaServices::Mgmt::V2018_07_01::Models::AssetFilter.mapper()
request_content = @client.serialize(request_mapper, parameters)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}/assetFilters/{filterName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::<API key>, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'accountName' => account_name,'assetName' => asset_name,'filterName' => filter_name},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:put, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200 || status_code == 201
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.<API key> = http_response['<API key>'] unless http_response['<API key>'].nil?
result.client_request_id = http_response['<API key>'] unless http_response['<API key>'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::MediaServices::Mgmt::V2018_07_01::Models::AssetFilter.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::<API key>.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
# Deserialize Response
if status_code == 201
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::MediaServices::Mgmt::V2018_07_01::Models::AssetFilter.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::<API key>.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
# Delete an Asset Filter.
# Deletes an Asset Filter associated with the specified Asset.
# @param resource_group_name [String] The name of the resource group within the
# Azure subscription.
# @param account_name [String] The Media Services account name.
# @param asset_name [String] The Asset name.
# @param filter_name [String] The Asset Filter name
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
def delete(resource_group_name, account_name, asset_name, filter_name, custom_headers:nil)
response = delete_async(resource_group_name, account_name, asset_name, filter_name, custom_headers:custom_headers).value!
nil
end
# Delete an Asset Filter.
# Deletes an Asset Filter associated with the specified Asset.
# @param resource_group_name [String] The name of the resource group within the
# Azure subscription.
# @param account_name [String] The Media Services account name.
# @param asset_name [String] The Asset name.
# @param filter_name [String] The Asset Filter name
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
# @return [MsRestAzure::<API key>] HTTP response information.
def <API key>(resource_group_name, account_name, asset_name, filter_name, custom_headers:nil)
delete_async(resource_group_name, account_name, asset_name, filter_name, custom_headers:custom_headers).value!
end
# Delete an Asset Filter.
# Deletes an Asset Filter associated with the specified Asset.
# @param resource_group_name [String] The name of the resource group within the
# Azure subscription.
# @param account_name [String] The Media Services account name.
# @param asset_name [String] The Asset name.
# @param filter_name [String] The Asset Filter name
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
def delete_async(resource_group_name, account_name, asset_name, filter_name, custom_headers:nil)
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'account_name is nil' if account_name.nil?
fail ArgumentError, 'asset_name is nil' if asset_name.nil?
fail ArgumentError, 'filter_name is nil' if filter_name.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['<API key>'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}/assetFilters/{filterName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::<API key>, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'accountName' => account_name,'assetName' => asset_name,'filterName' => filter_name},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:delete, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200 || status_code == 204
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.<API key> = http_response['<API key>'] unless http_response['<API key>'].nil?
result.client_request_id = http_response['<API key>'] unless http_response['<API key>'].nil?
result
end
promise.execute
end
# Update an Asset Filter
# Updates an existing Asset Filter associated with the specified Asset.
# @param resource_group_name [String] The name of the resource group within the
# Azure subscription.
# @param account_name [String] The Media Services account name.
# @param asset_name [String] The Asset name.
# @param filter_name [String] The Asset Filter name
# @param parameters [AssetFilter] The request parameters
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
# @return [AssetFilter] operation results.
def update(resource_group_name, account_name, asset_name, filter_name, parameters, custom_headers:nil)
response = update_async(resource_group_name, account_name, asset_name, filter_name, parameters, custom_headers:custom_headers).value!
response.body unless response.nil?
end
# Update an Asset Filter
# Updates an existing Asset Filter associated with the specified Asset.
# @param resource_group_name [String] The name of the resource group within the
# Azure subscription.
# @param account_name [String] The Media Services account name.
# @param asset_name [String] The Asset name.
# @param filter_name [String] The Asset Filter name
# @param parameters [AssetFilter] The request parameters
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
# @return [MsRestAzure::<API key>] HTTP response information.
def <API key>(resource_group_name, account_name, asset_name, filter_name, parameters, custom_headers:nil)
update_async(resource_group_name, account_name, asset_name, filter_name, parameters, custom_headers:custom_headers).value!
end
# Update an Asset Filter
# Updates an existing Asset Filter associated with the specified Asset.
# @param resource_group_name [String] The name of the resource group within the
# Azure subscription.
# @param account_name [String] The Media Services account name.
# @param asset_name [String] The Asset name.
# @param filter_name [String] The Asset Filter name
# @param parameters [AssetFilter] The request parameters
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
def update_async(resource_group_name, account_name, asset_name, filter_name, parameters, custom_headers:nil)
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'account_name is nil' if account_name.nil?
fail ArgumentError, 'asset_name is nil' if asset_name.nil?
fail ArgumentError, 'filter_name is nil' if filter_name.nil?
fail ArgumentError, 'parameters is nil' if parameters.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['<API key>'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::MediaServices::Mgmt::V2018_07_01::Models::AssetFilter.mapper()
request_content = @client.serialize(request_mapper, parameters)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}/assetFilters/{filterName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::<API key>, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'accountName' => account_name,'assetName' => asset_name,'filterName' => filter_name},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:patch, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.<API key> = http_response['<API key>'] unless http_response['<API key>'].nil?
result.client_request_id = http_response['<API key>'] unless http_response['<API key>'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::MediaServices::Mgmt::V2018_07_01::Models::AssetFilter.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::<API key>.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
# List Asset Filters
# List Asset Filters associated with the specified Asset.
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
# @return [<API key>] operation results.
def list_next(next_page_link, custom_headers:nil)
response = list_next_async(next_page_link, custom_headers:custom_headers).value!
response.body unless response.nil?
end
# List Asset Filters
# List Asset Filters associated with the specified Asset.
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
# @return [MsRestAzure::<API key>] HTTP response information.
def <API key>(next_page_link, custom_headers:nil)
list_next_async(next_page_link, custom_headers:custom_headers).value!
end
# List Asset Filters
# List Asset Filters associated with the specified Asset.
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
def list_next_async(next_page_link, custom_headers:nil)
fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['<API key>'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{nextLink}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::<API key>, times: 3, retry: 0.02], [:cookie_jar]],
<API key>: {'nextLink' => next_page_link},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.<API key> = http_response['<API key>'] unless http_response['<API key>'].nil?
result.client_request_id = http_response['<API key>'] unless http_response['<API key>'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::MediaServices::Mgmt::V2018_07_01::Models::<API key>.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::<API key>.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
# List Asset Filters
# List Asset Filters associated with the specified Asset.
# @param resource_group_name [String] The name of the resource group within the
# Azure subscription.
# @param account_name [String] The Media Services account name.
# @param asset_name [String] The Asset name.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
# @return [<API key>] which provide lazy access to pages of the
# response.
def list_as_lazy(resource_group_name, account_name, asset_name, custom_headers:nil)
response = list_async(resource_group_name, account_name, asset_name, custom_headers:custom_headers).value!
unless response.nil?
page = response.body
page.next_method = Proc.new do |next_page_link|
list_next_async(next_page_link, custom_headers:custom_headers)
end
page
end
end
end
end |
<?php
declare(strict_types=1);
namespace AlphaVantage\Api;
use AlphaVantage\Exception\RuntimeException;
use AlphaVantage\Options;
use GuzzleHttp\Client;
use function array_filter;
use function GuzzleHttp\json_decode;
use function http_build_query;
use function array_merge;
use function rtrim;
/**
* Class AbstractApi
* @package AlphaVantage\Api
*/
class AbstractApi
{
public const DATA_TYPE_JSON = 'json';
public const DATA_TYPE_CSV = 'csv';
/** @var Options */
protected $options;
/** @var Client */
protected $client;
/**
* AbstractApi constructor.
* @param Options $options
*/
public function __construct(Options $options)
{
$this->options = $options;
$this->client = new Client();
}
/**
* @param string $functionName
* @param null|string $symbolName
* @param array $params
* @return array
*/
protected function get(string $functionName, string $symbolName = null, array $params = [])
{
unset($params['functions'], $params['function'], $params['apikey']);
$params = array_filter($params, function ($p) {
return !empty($p);
});
$basicData = [
'function' => $functionName,
];
if (null !== $symbolName) {
$basicData['symbol'] = $symbolName;
}
$httpQuery = http_build_query(
array_merge(
$basicData,
$params,
[
'apikey' => $this->options->getApiKey(),
]
)
);
$response = $this->client->get($this->getApiUri() . $httpQuery);
$result = json_decode($response->getBody()->getContents(), true);
if (isset($result['Error Message'])) {
throw new RuntimeException($result['Error Message'], $response->getStatusCode());
} elseif (isset($result['Note'])) {
throw new RuntimeException($result['Note'], $response->getStatusCode());
}
return $result;
}
/**
* @return string
*/
protected function getApiUri(): string
{
return rtrim($this->options->getApiUrl(), '/') . '/query?';
}
} |
package org.cen.com;
/**
* Exception to check the expected data lenght.
*/
public class <API key> extends <API key> {
private static final long serialVersionUID = 1L;
public <API key>(int expected, int actual) {
super("Data length is : " + actual + " but expected is : " + expected);
}
} |
#pragma once
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <iosfwd>
#include <memory>
#include <ostream>
#include <utility>
#include <windows.h>
#include <winnt.h>
#include <hadesmem/config.hpp>
#include <hadesmem/detail/assert.hpp>
#include <hadesmem/error.hpp>
#include <hadesmem/pelib/dos_header.hpp>
#include <hadesmem/pelib/pe_file.hpp>
#include <hadesmem/process.hpp>
#include <hadesmem/read.hpp>
#include <hadesmem/write.hpp>
namespace hadesmem
{
enum class PeDataDir : std::uint32_t
{
Export,
Import,
Resource,
Exception,
Security,
BaseReloc,
Debug,
Architecture,
GlobalPTR,
TLS,
LoadConfig,
BoundImport,
IAT,
DelayImport,
COMDescriptor,
Reserved
};
class NtHeaders
{
public:
explicit NtHeaders(Process const& process, PeFile const& pe_file)
: process_{&process},
pe_file_{&pe_file},
base_{CalculateBase(*process_, *pe_file_)}
{
UpdateRead();
EnsureValid();
}
explicit NtHeaders(Process&& process, PeFile const& pe_file) = delete;
explicit NtHeaders(Process const& process, PeFile&& pe_file) = delete;
explicit NtHeaders(Process&& process, PeFile&& pe_file) = delete;
PVOID GetBase() const noexcept
{
return base_;
}
void UpdateRead()
{
if (pe_file_->Is64())
{
data_64_ = Read<IMAGE_NT_HEADERS64>(*process_, base_);
}
else
{
data_32_ = Read<IMAGE_NT_HEADERS32>(*process_, base_);
}
}
void UpdateWrite()
{
if (pe_file_->Is64())
{
Write(*process_, base_, data_64_);
}
else
{
Write(*process_, base_, data_32_);
}
}
bool IsValid() const
{
if (pe_file_->Is64())
{
return IMAGE_NT_SIGNATURE == GetSignature() &&
<API key> == GetMagic() &&
<API key> == GetMachine();
}
else
{
return IMAGE_NT_SIGNATURE == GetSignature() &&
<API key> == GetMagic() &&
<API key> == GetMachine();
}
}
void EnsureValid() const
{
if (!IsValid())
{
<API key>(
Error{} << ErrorString{"NT headers signature invalid."});
}
}
DWORD GetSignature() const
{
if (pe_file_->Is64())
{
return data_64_.Signature;
}
else
{
return data_32_.Signature;
}
}
WORD GetMachine() const
{
if (pe_file_->Is64())
{
return data_64_.FileHeader.Machine;
}
else
{
return data_32_.FileHeader.Machine;
}
}
WORD GetNumberOfSections() const
{
if (pe_file_->Is64())
{
return data_64_.FileHeader.NumberOfSections;
}
else
{
return data_32_.FileHeader.NumberOfSections;
}
}
DWORD GetTimeDateStamp() const
{
if (pe_file_->Is64())
{
return data_64_.FileHeader.TimeDateStamp;
}
else
{
return data_32_.FileHeader.TimeDateStamp;
}
}
DWORD <API key>() const
{
if (pe_file_->Is64())
{
return data_64_.FileHeader.<API key>;
}
else
{
return data_32_.FileHeader.<API key>;
}
}
DWORD GetNumberOfSymbols() const
{
if (pe_file_->Is64())
{
return data_64_.FileHeader.NumberOfSymbols;
}
else
{
return data_32_.FileHeader.NumberOfSymbols;
}
}
WORD <API key>() const
{
if (pe_file_->Is64())
{
return data_64_.FileHeader.<API key>;
}
else
{
return data_32_.FileHeader.<API key>;
}
}
WORD GetCharacteristics() const
{
if (pe_file_->Is64())
{
return data_64_.FileHeader.Characteristics;
}
else
{
return data_32_.FileHeader.Characteristics;
}
}
WORD GetMagic() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.Magic;
}
else
{
return data_32_.OptionalHeader.Magic;
}
}
BYTE <API key>() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.MajorLinkerVersion;
}
else
{
return data_32_.OptionalHeader.MajorLinkerVersion;
}
}
BYTE <API key>() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.MinorLinkerVersion;
}
else
{
return data_32_.OptionalHeader.MinorLinkerVersion;
}
}
DWORD GetSizeOfCode() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.SizeOfCode;
}
else
{
return data_32_.OptionalHeader.SizeOfCode;
}
}
DWORD <API key>() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.<API key>;
}
else
{
return data_32_.OptionalHeader.<API key>;
}
}
DWORD <API key>() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.<API key>;
}
else
{
return data_32_.OptionalHeader.<API key>;
}
}
DWORD <API key>() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.AddressOfEntryPoint;
}
else
{
return data_32_.OptionalHeader.AddressOfEntryPoint;
}
}
DWORD GetBaseOfCode() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.BaseOfCode;
}
else
{
return data_32_.OptionalHeader.BaseOfCode;
}
}
DWORD GetBaseOfData() const
{
if (pe_file_->Is64())
{
<API key>(
Error{} << ErrorString{"Invalid field for architecture."});
}
else
{
return data_32_.OptionalHeader.BaseOfData;
}
}
ULONGLONG GetImageBase() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.ImageBase;
}
else
{
return data_32_.OptionalHeader.ImageBase;
}
}
DWORD GetSectionAlignment() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.SectionAlignment;
}
else
{
return data_32_.OptionalHeader.SectionAlignment;
}
}
DWORD GetFileAlignment() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.FileAlignment;
}
else
{
return data_32_.OptionalHeader.FileAlignment;
}
}
WORD <API key>() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.<API key>;
}
else
{
return data_32_.OptionalHeader.<API key>;
}
}
WORD <API key>() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.<API key>;
}
else
{
return data_32_.OptionalHeader.<API key>;
}
}
WORD <API key>() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.MajorImageVersion;
}
else
{
return data_32_.OptionalHeader.MajorImageVersion;
}
}
WORD <API key>() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.MinorImageVersion;
}
else
{
return data_32_.OptionalHeader.MinorImageVersion;
}
}
WORD <API key>() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.<API key>;
}
else
{
return data_32_.OptionalHeader.<API key>;
}
}
WORD <API key>() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.<API key>;
}
else
{
return data_32_.OptionalHeader.<API key>;
}
}
DWORD <API key>() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.Win32VersionValue;
}
else
{
return data_32_.OptionalHeader.Win32VersionValue;
}
}
DWORD GetSizeOfImage() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.SizeOfImage;
}
else
{
return data_32_.OptionalHeader.SizeOfImage;
}
}
DWORD GetSizeOfHeaders() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.SizeOfHeaders;
}
else
{
return data_32_.OptionalHeader.SizeOfHeaders;
}
}
DWORD GetCheckSum() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.CheckSum;
}
else
{
return data_32_.OptionalHeader.CheckSum;
}
}
WORD GetSubsystem() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.Subsystem;
}
else
{
return data_32_.OptionalHeader.Subsystem;
}
}
WORD <API key>() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.DllCharacteristics;
}
else
{
return data_32_.OptionalHeader.DllCharacteristics;
}
}
ULONGLONG <API key>() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.SizeOfStackReserve;
}
else
{
return data_32_.OptionalHeader.SizeOfStackReserve;
}
}
ULONGLONG <API key>() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.SizeOfStackCommit;
}
else
{
return data_32_.OptionalHeader.SizeOfStackCommit;
}
}
ULONGLONG <API key>() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.SizeOfHeapReserve;
}
else
{
return data_32_.OptionalHeader.SizeOfHeapReserve;
}
}
ULONGLONG GetSizeOfHeapCommit() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.SizeOfHeapCommit;
}
else
{
return data_32_.OptionalHeader.SizeOfHeapCommit;
}
}
DWORD GetLoaderFlags() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.LoaderFlags;
}
else
{
return data_32_.OptionalHeader.LoaderFlags;
}
}
DWORD <API key>() const
{
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.NumberOfRvaAndSizes;
}
else
{
return data_32_.OptionalHeader.NumberOfRvaAndSizes;
}
}
DWORD <API key>() const
{
DWORD const num_rvas_and_sizes = <API key>();
return (std::min)(num_rvas_and_sizes, 0x10UL);
}
DWORD <API key>(PeDataDir data_dir) const
{
if (static_cast<DWORD>(data_dir) >= <API key>())
{
<API key>(Error{}
<< ErrorString{"Invalid data dir."});
}
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.DataDirectory[static_cast<std::uint32_t>(
data_dir)].VirtualAddress;
}
else
{
return data_32_.OptionalHeader.DataDirectory[static_cast<std::uint32_t>(
data_dir)].VirtualAddress;
}
}
DWORD <API key>(PeDataDir data_dir) const
{
if (static_cast<DWORD>(data_dir) >= <API key>())
{
<API key>(Error{}
<< ErrorString{"Invalid data dir."});
}
if (pe_file_->Is64())
{
return data_64_.OptionalHeader.DataDirectory[static_cast<std::uint32_t>(
data_dir)].Size;
}
else
{
return data_32_.OptionalHeader.DataDirectory[static_cast<std::uint32_t>(
data_dir)].Size;
}
}
void SetSignature(DWORD signature)
{
if (pe_file_->Is64())
{
data_64_.Signature = signature;
}
else
{
data_32_.Signature = signature;
}
}
void SetMachine(WORD machine)
{
if (pe_file_->Is64())
{
data_64_.FileHeader.Machine = machine;
}
else
{
data_32_.FileHeader.Machine = machine;
}
}
void SetNumberOfSections(WORD number_of_sections)
{
if (pe_file_->Is64())
{
data_64_.FileHeader.NumberOfSections = number_of_sections;
}
else
{
data_32_.FileHeader.NumberOfSections = number_of_sections;
}
}
void SetTimeDateStamp(DWORD time_date_stamp)
{
if (pe_file_->Is64())
{
data_64_.FileHeader.TimeDateStamp = time_date_stamp;
}
else
{
data_32_.FileHeader.TimeDateStamp = time_date_stamp;
}
}
void <API key>(DWORD <API key>)
{
if (pe_file_->Is64())
{
data_64_.FileHeader.<API key> = <API key>;
}
else
{
data_32_.FileHeader.<API key> = <API key>;
}
}
void SetNumberOfSymbols(DWORD number_of_symbols)
{
if (pe_file_->Is64())
{
data_64_.FileHeader.NumberOfSymbols = number_of_symbols;
}
else
{
data_32_.FileHeader.NumberOfSymbols = number_of_symbols;
}
}
void <API key>(WORD <API key>)
{
if (pe_file_->Is64())
{
data_64_.FileHeader.<API key> = <API key>;
}
else
{
data_32_.FileHeader.<API key> = <API key>;
}
}
void SetCharacteristics(WORD characteristics)
{
if (pe_file_->Is64())
{
data_64_.FileHeader.Characteristics = characteristics;
}
else
{
data_32_.FileHeader.Characteristics = characteristics;
}
}
void SetMagic(WORD magic)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.Magic = magic;
}
else
{
data_32_.OptionalHeader.Magic = magic;
}
}
void <API key>(BYTE <API key>)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.MajorLinkerVersion = <API key>;
}
else
{
data_32_.OptionalHeader.MajorLinkerVersion = <API key>;
}
}
void <API key>(BYTE <API key>)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.MinorLinkerVersion = <API key>;
}
else
{
data_32_.OptionalHeader.MinorLinkerVersion = <API key>;
}
}
void SetSizeOfCode(DWORD size_of_code)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.SizeOfCode = size_of_code;
}
else
{
data_32_.OptionalHeader.SizeOfCode = size_of_code;
}
}
void <API key>(DWORD <API key>)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.<API key> = <API key>;
}
else
{
data_32_.OptionalHeader.<API key> = <API key>;
}
}
void <API key>(DWORD <API key>)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.<API key> =
<API key>;
}
else
{
data_32_.OptionalHeader.<API key> =
<API key>;
}
}
void <API key>(DWORD <API key>)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.AddressOfEntryPoint = <API key>;
}
else
{
data_32_.OptionalHeader.AddressOfEntryPoint = <API key>;
}
}
void SetBaseOfCode(DWORD base_of_code)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.BaseOfCode = base_of_code;
}
else
{
data_32_.OptionalHeader.BaseOfCode = base_of_code;
}
}
void SetBaseOfData(DWORD base_of_data)
{
if (pe_file_->Is64())
{
<API key>(
Error{} << ErrorString{"Invalid field for architecture."});
}
else
{
data_32_.OptionalHeader.BaseOfData = base_of_data;
}
}
void SetImageBase(ULONGLONG image_base)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.ImageBase = image_base;
}
else
{
data_32_.OptionalHeader.ImageBase = static_cast<ULONG>(image_base);
}
}
void SetSectionAlignment(DWORD section_alignment)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.SectionAlignment = section_alignment;
}
else
{
data_32_.OptionalHeader.SectionAlignment = section_alignment;
}
}
void SetFileAlignment(DWORD file_alignment)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.FileAlignment = file_alignment;
}
else
{
data_32_.OptionalHeader.FileAlignment = file_alignment;
}
}
void <API key>(WORD <API key>)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.<API key> =
<API key>;
}
else
{
data_32_.OptionalHeader.<API key> =
<API key>;
}
}
void <API key>(WORD <API key>)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.<API key> =
<API key>;
}
else
{
data_32_.OptionalHeader.<API key> =
<API key>;
}
}
void <API key>(WORD major_image_version)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.MajorImageVersion = major_image_version;
}
else
{
data_32_.OptionalHeader.MajorImageVersion = major_image_version;
}
}
void <API key>(WORD minor_image_version)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.MinorImageVersion = minor_image_version;
}
else
{
data_32_.OptionalHeader.MinorImageVersion = minor_image_version;
}
}
void <API key>(WORD <API key>)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.<API key> = <API key>;
}
else
{
data_32_.OptionalHeader.<API key> = <API key>;
}
}
void <API key>(WORD <API key>)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.<API key> = <API key>;
}
else
{
data_32_.OptionalHeader.<API key> = <API key>;
}
}
void <API key>(DWORD win32_version_value)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.Win32VersionValue = win32_version_value;
}
else
{
data_32_.OptionalHeader.Win32VersionValue = win32_version_value;
}
}
void SetSizeOfImage(DWORD size_of_image)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.SizeOfImage = size_of_image;
}
else
{
data_32_.OptionalHeader.SizeOfImage = size_of_image;
}
}
void SetSizeOfHeaders(DWORD size_of_headers)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.SizeOfHeaders = size_of_headers;
}
else
{
data_32_.OptionalHeader.SizeOfHeaders = size_of_headers;
}
}
void SetCheckSum(DWORD checksum)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.CheckSum = checksum;
}
else
{
data_32_.OptionalHeader.CheckSum = checksum;
}
}
void SetSubsystem(WORD subsystem)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.Subsystem = subsystem;
}
else
{
data_32_.OptionalHeader.Subsystem = subsystem;
}
}
void <API key>(WORD dll_characteristics)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.DllCharacteristics = dll_characteristics;
}
else
{
data_32_.OptionalHeader.DllCharacteristics = dll_characteristics;
}
}
void <API key>(ULONGLONG <API key>)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.SizeOfStackReserve = <API key>;
}
else
{
data_32_.OptionalHeader.SizeOfStackReserve =
static_cast<ULONG>(<API key>);
}
}
void <API key>(ULONGLONG <API key>)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.SizeOfStackCommit = <API key>;
}
else
{
data_32_.OptionalHeader.SizeOfStackCommit =
static_cast<ULONG>(<API key>);
}
}
void <API key>(ULONGLONG <API key>)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.SizeOfHeapReserve = <API key>;
}
else
{
data_32_.OptionalHeader.SizeOfHeapReserve =
static_cast<ULONG>(<API key>);
}
}
void SetSizeOfHeapCommit(ULONGLONG size_of_heap_commit)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.SizeOfHeapCommit = size_of_heap_commit;
}
else
{
data_32_.OptionalHeader.SizeOfHeapCommit =
static_cast<ULONG>(size_of_heap_commit);
}
}
void SetLoaderFlags(DWORD loader_flags)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.LoaderFlags = loader_flags;
}
else
{
data_32_.OptionalHeader.LoaderFlags = loader_flags;
}
}
void <API key>(DWORD <API key>)
{
if (pe_file_->Is64())
{
data_64_.OptionalHeader.NumberOfRvaAndSizes = <API key>;
}
else
{
data_32_.OptionalHeader.NumberOfRvaAndSizes = <API key>;
}
}
void <API key>(PeDataDir data_dir,
DWORD <API key>)
{
if (static_cast<DWORD>(data_dir) >= <API key>())
{
<API key>(Error{}
<< ErrorString{"Invalid data dir."});
}
if (pe_file_->Is64())
{
data_64_.OptionalHeader.DataDirectory[static_cast<std::uint32_t>(
data_dir)].VirtualAddress =
<API key>;
}
else
{
data_32_.OptionalHeader.DataDirectory[static_cast<std::uint32_t>(
data_dir)].VirtualAddress =
<API key>;
}
}
void <API key>(PeDataDir data_dir, DWORD data_directory_size)
{
if (static_cast<DWORD>(data_dir) >= <API key>())
{
<API key>(Error{}
<< ErrorString{"Invalid data dir."});
}
if (pe_file_->Is64())
{
data_64_.OptionalHeader.DataDirectory[static_cast<std::uint32_t>(
data_dir)].Size =
data_directory_size;
}
else
{
data_32_.OptionalHeader.DataDirectory[static_cast<std::uint32_t>(
data_dir)].Size =
data_directory_size;
}
}
private:
PBYTE CalculateBase(Process const& process, PeFile const& pe_file) const
{
DosHeader dos_header{process, pe_file};
return static_cast<PBYTE>(dos_header.GetBase()) +
dos_header.GetNewHeaderOffset();
}
Process const* process_;
PeFile const* pe_file_;
std::uint8_t* base_;
IMAGE_NT_HEADERS32 data_32_ = IMAGE_NT_HEADERS32{};
IMAGE_NT_HEADERS64 data_64_ = IMAGE_NT_HEADERS64{};
};
inline bool operator==(NtHeaders const& lhs,
NtHeaders const& rhs) noexcept
{
return lhs.GetBase() == rhs.GetBase();
}
inline bool operator!=(NtHeaders const& lhs,
NtHeaders const& rhs) noexcept
{
return !(lhs == rhs);
}
inline bool operator<(NtHeaders const& lhs,
NtHeaders const& rhs) noexcept
{
return lhs.GetBase() < rhs.GetBase();
}
inline bool operator<=(NtHeaders const& lhs,
NtHeaders const& rhs) noexcept
{
return lhs.GetBase() <= rhs.GetBase();
}
inline bool operator>(NtHeaders const& lhs,
NtHeaders const& rhs) noexcept
{
return lhs.GetBase() > rhs.GetBase();
}
inline bool operator>=(NtHeaders const& lhs,
NtHeaders const& rhs) noexcept
{
return lhs.GetBase() >= rhs.GetBase();
}
inline std::ostream& operator<<(std::ostream& lhs, NtHeaders const& rhs)
{
std::locale const old = lhs.imbue(std::locale::classic());
lhs << static_cast<void*>(rhs.GetBase());
lhs.imbue(old);
return lhs;
}
inline std::wostream& operator<<(std::wostream& lhs, NtHeaders const& rhs)
{
std::locale const old = lhs.imbue(std::locale::classic());
lhs << static_cast<void*>(rhs.GetBase());
lhs.imbue(old);
return lhs;
}
inline ULONGLONG GetRuntimeBase(Process const& process, PeFile const& pe_file)
{
switch (pe_file.GetType())
{
case PeFileType::Image:
return reinterpret_cast<ULONGLONG>(pe_file.GetBase());
case PeFileType::Data:
return NtHeaders(process, pe_file).GetImageBase();
}
<API key>(false);
return 0;
}
} |
<html>
<head>
<meta charset="utf-8">
<meta name="format-detection" content="telephone=no">
<meta name="viewport" content="user-scalable=no, width=device-width, height=device-height">
<title>YunoFav</title>
<meta name="robots" content="noindex, nofollow">
<link rel="stylesheet" href="/yunohost/sso/assets/css/ynh-style.css">
<link rel="shortcut icon" href="/yunohost/sso/assets/icons/favicon.ico">
<link rel="apple-touch-icon" sizes="57x57" href="/yunohost/sso/assets/icons/<API key>.png">
<link rel="apple-touch-icon" sizes="114x114" href="/yunohost/sso/assets/icons/<API key>.png">
<link rel="apple-touch-icon" sizes="72x72" href="/yunohost/sso/assets/icons/<API key>.png">
<link rel="apple-touch-icon" sizes="144x144" href="/yunohost/sso/assets/icons/<API key>.png">
<link rel="apple-touch-icon" sizes="60x60" href="/yunohost/sso/assets/icons/<API key>.png">
<link rel="apple-touch-icon" sizes="120x120" href="/yunohost/sso/assets/icons/<API key>.png">
<link rel="apple-touch-icon" sizes="76x76" href="/yunohost/sso/assets/icons/<API key>.png">
<link rel="apple-touch-icon" sizes="152x152" href="/yunohost/sso/assets/icons/<API key>.png">
<link rel="icon" type="image/png" href="/yunohost/sso/assets/icons/favicon-196x196.png" sizes="196x196">
<link rel="icon" type="image/png" href="/yunohost/sso/assets/icons/favicon-160x160.png" sizes="160x160">
<link rel="icon" type="image/png" href="/yunohost/sso/assets/icons/favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="/yunohost/sso/assets/icons/favicon-16x16.png" sizes="16x16">
<link rel="icon" type="image/png" href="/yunohost/sso/assets/icons/favicon-32x32.png" sizes="32x32">
<meta name="<API key>" content="#41444f">
<meta name="<API key>" content="/mstile-144x144.png">
<style>
.form {
display:none;
height:230px;
width:400px;
position: absolute;
margin-left: auto;
margin-right: auto;
top:80px;
background:aliceblue ;
position: absolute;
left: 0;
right: 0;
z-index: 1;
padding: 7px 15px 0 15px;
opacity: .9;
}
.close {
position: absolute;
top: 5px;
right:5px;
background-position: center center;
background-repeat: no-repeat;
background-image: url("close.png");
width:20px;
height:20px;
opacity:.5;
cursor: pointer;
display:block;
}
.close:hover {
opacity:1;
}
#edit {
display:none;
}
#favmenu {
color: #bbb;
margin: 2%;
}
#favmenu a {
color: #fff;
}
#favmenu a:hover {
text-decoration:underline;
}
#zone {
margin:2% 4%;
}
label {
width: 50px;
text-align: right;
cursor: default;
display: inline-block;
padding: 0;
background: transparent;
color: #000;
font-size: 1em;
margin-top: 0;
font-family: sans-serif;
font-weight: normal;
}
button, input, select, textarea {
margin: 5px 0 0 0;
}
input[type=submit] {
cursor: pointer;
}
.purplebg {
background: #9B59B6!important;
}
#ecol {
cursor: pointer;width:200px;height: 25px;display: inline-block;margin-top: 5px;border: 2px inset;margin-bottom: -7px;
}
.menu {position:absolute;display:none;border: thin solid #808080; cursor: pointer;width:200px; background-color:white;margin-top: 25px;}
.menu div:hover { opacity:1; }
.menu div {width:200px;height: 25px; opacity:.8;}
</style>
<script>
//Global vars
var doc = [];
var codix = new Object();
couleur={
"lightbluebg" :"#6A93D4",
"bluebg" :"#3498DB",
"darkbluebg" :"#34495E",
"purpledarkbg":"#8E44AD",
"purplebg" :"#9B59B6",
"pinkbg" :"#D66D92",
"lightpinkbg" :"#F76F87",
"redbg" :"#E74C3C",
"orangebg" :"#F39C12",
"yellowbg" :"#F1C40F",
"lightyellow" :"#FFC973",
"lightgreen" :"#77CF11",
"greenbg" :"#2ECC71",
"turquoisebg" :"#1ABC9C"
}
//color menu
function show(menu,e) {
document.getElementById(menu).style.display = 'inline';
}
//record on server
function record() {
text=JSON.stringify(doc);
req.open("POST", "fav.php", true);
req.setRequestHeader("Content-type", "application/json");
req.send(text);
}
// hide color menu
function hide(popmenu,e) {
if(e){
var target= e.currentTarget||e.srcElement;
var child= e.relatedTarget||e.toElement
if (child) {
while(child.parentElement){
if(target==child)return ; // coince la bulle
child=child.parentElement;
}
}
}
popmenu.style.display = 'none';
}
// (Re)Init and (re)draw
function setzone()
{
var length=doc.tiles.length;
document.getElementById("zone").innerHTML = "";
options = " disabled >(choose)</option>";
codix={};
for(i = 0; i < length; i++)
{
codix[doc.tiles[i].atom]=i;
document.getElementById("zone").innerHTML += "<li><a class="+doc.tiles[i].color+" disableAjax' href='"+doc.tiles[i].target+"'><span class='first-letter' data-first-letter='"+doc.tiles[i].atom+"'></span><span class='name'>"+doc.tiles[i].label+"</span></a></li>";
options += "<option>"+doc.tiles[i].atom+"</option>";
}
document.getElementById("seledit").innerHTML = "<option id='selini'"+options;
document.getElementById("selmoveto").innerHTML = "<option id='selmini'"+options+"<option>(last)</option>";
codix["(last)"]=i;
codix["(choose)"]=0;
}
// Hide form
function hideml(ca) {
ca.parentNode.style.display="none";
}
// Show form with appropriate fields
function choiceml(opt) {
if (opt == 'Add'){
disp="none";
nodisp="inline";
} else {
disp="inline";
nodisp="none";
}
document.getElementById("titedit").innerHTML=opt;
document.getElementById("eact").innerHTML=opt;
document.getElementById("butedit").value=opt;
document.getElementById("seledit").style.display=disp;
document.getElementById("eact").style.display=disp;
document.getElementById("divedit").style.display=nodisp;
document.getElementById("moveto").style.display=nodisp;
document.getElementById("ecol").className="lightbluebg";
document.getElementById("encod").value="";
document.getElementById("elbl").value="";
document.getElementById("etgt").value="";
document.getElementById("edit").style.display="block";
document.getElementById("selini").selected = true;
document.getElementById("selmini").selected = true;
}
// Pick up selected color
function scol(colbox,ca) {
document.getElementById(colbox).className=ca.className;
hideml(ca);
return false;
}
// Move a tile
function movtile() {
if(document.getElementById("titedit").innerHTML=="Move"){
from=codix[document.getElementById("seledit").value];
to=codix[document.getElementById("selmoveto").value];
if(to>from) to
what = doc.tiles[from];
doc.tiles.splice(from, 1);
doc.tiles.splice(to, 0, what);
record();
document.getElementById("edit").style.display="none";
}
return false;
}
// On selected tile
function showedit() {
choice=document.getElementById("seledit").value;
if (choice!="(choose)") {
what=doc.tiles[codix[choice]];
document.getElementById("encod").value="";
disp="inline";
switch(document.getElementById("titedit").innerHTML) {
case "Suppress":
doc.tiles.splice(codix[choice],1);
record();
document.getElementById("edit").style.display="none";
break;
case "Move":
document.getElementById("moveto").style.display="inline";
break;
case "Update":
document.getElementById("encod").value=what["atom"];
disp="none";
case "Duplicate":
document.getElementById("divedit").style.display="inline";
document.getElementById("seledit").style.display="none";
document.getElementById("moveto").style.display=disp;
document.getElementById("eact").style.display="none";
document.getElementById("elbl").value=what["label"];
document.getElementById("etgt").value=what["target"];
document.getElementById("ecol").className=what["color"];
break;
default:
}
}
return false;
}
// On form submit
function edtile(ca) {
atom=document.getElementById("encod").value;
latom=atom.length;
if(latom<1 || latom>3) {
alert("The code of the tile must be 1 to 3 characters long.");
} else if(typeof codix[atom] != 'undefined' && atom != document.getElementById("seledit").value) {
alert("The code you chose for the tile already exists.");
} else {
what={"color": document.getElementById("ecol").className, "atom": atom, "label": document.getElementById("elbl").value, "target": document.getElementById("etgt").value};
if (document.getElementById("titedit").innerHTML=="Update") {
doc.tiles[codix[document.getElementById("seledit").value]]=what;
} else {
doc.tiles.splice(codix[document.getElementById("selmoveto").value],0,what);
}
record();
ca.style.display="none";
}
return false;
}
// Call back function for Ajax
function monCode()
{
if (req.readyState == 4) {
text=req.responseText;
try {
JSON.parse(text);
} catch (e) {
text = '{"tiles": []}';
}
doc = JSON.parse(text);
setzone();
}
}
// Ajax
var req = new XMLHttpRequest();
req.open("GET", "fav.json", true);
req.onreadystatechange = monCode;
</script>
</head>
<body onLoad='req.send(null);'>
<div id="favmenu">These are your <span style="font-size:200%">favourite links</span>. You may want to <a href="javascript:void(0)" onclick="choiceml('Add');">add</a>, <a href="javascript:void(0)" onclick="choiceml('Suppress');">suppress</a>, <a href="javascript:void(0)" onclick="choiceml('Move');">move</a>, <a href="javascript:void(0)" onclick="choiceml('Update');">update</a> or <a href="javascript:void(0)" onclick="choiceml('Duplicate');">duplicate</a> one.
</div>
<ul class="ul-reset listing-apps col colNomarge sourceProBold" id="zone"></ul>
<form id="edit" class="form" onsubmit="return edtile(this);">
<a class="close" href='javascript:void(0)' onClick='hideml(this);'>
</a>
<span style="font-size: 200%;"><span id="titedit"></span> a tile</span><br>
<span id="eact"></span>
<select id="seledit" onChange="return showedit();">
</select>
<span id="divedit">
<label>Code:</label> <input type="text" id="encod" style="width:50px;" value=""><br>
<label>Label:</label> <input type="text" id="elbl" style="width:300px;" value=""><br>
<label>Target:</label> <input type="text" id="etgt" style="width:300px;" value=""><br>
<label>Color:</label>
<div id="eeltmenu" class="menu" onMouseOut="hide(this,event)">
<div onclick="scol('ecol',this)" class="lightbluebg"></div>
<div onclick="scol('ecol',this)" class="bluebg"></div>
<div onclick="scol('ecol',this)" class="darkbluebg"></div>
<div onclick="scol('ecol',this)" class="purpledarkbg"></div>
<div onclick="scol('ecol',this)" class="purplebg"></div>
<div onclick="scol('ecol',this)" class="pinkbg"></div>
<div onclick="scol('ecol',this)" class="lightpinkbg"></div>
<div onclick="scol('ecol',this)" class="redbg"></div>
<div onclick="scol('ecol',this)" class="orangebg"></div>
<div onclick="scol('ecol',this)" class="yellowbg"></div>
<div onclick="scol('ecol',this)" class="lightyellow"></div>
<div onclick="scol('ecol',this)" class="lightgreen"></div>
<div onclick="scol('ecol',this)" class="greenbg"></div>
<div onclick="scol('ecol',this)" class="turquoisebg"></div>
</div>
<div type="text" id="ecol" onclick="return show('eeltmenu',event);"></div>
<br>
<input type="submit" id="butedit">
</span>
<span id="moveto">
before
<select id="selmoveto" onChange="return movtile();">
</select>
</span>
</form>
</body>
</html> |
<?php
echo 'one';
?> |
"use strict";
angular.module('IssueTrackingSystem.Issues.Issues', [])
.factory('issues', [
'$http',
'$q',
'BASE_URL',
function ($http, $q, BASE_URL) {
function getMyIssues(pageSize, pageNumber, orderBy) {
var pageSize = pageSize || 5,
pageNumber = pageNumber || 1,
orderBy = orderBy || 'DueDate',
deferred = $q.defer();
$http.get(BASE_URL +
'issues/me?pageSize=' +
pageSize +
'&pageNumber=' +
pageNumber +
'&orderBy=' +
orderBy)
.then(function (response) {
deferred.resolve(response.data.Issues);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
function addIssue(issue) {
var deferred = $q.defer();
$http.post(BASE_URL + 'issues/', issue)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error.data.error_description);
});
return deferred.promise;
}
function editIssue(id, issue) {
var deferred = $q.defer();
$http.put(BASE_URL + 'issues/' + id, issue)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error.data.error_description);
});
return deferred.promise;
}
function changeStatus(id, statusId) {
var deferred = $q.defer();
$http.put(BASE_URL + 'issues/' + id + '/changestatus?statusid=' + statusId)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error.data.error_description);
});
return deferred.promise;
}
function getIssueById(id) {
var deferred = $q.defer();
$http.get(BASE_URL + 'issues/' + id)
.then(function (response) {
deferred.resolve(response.data);
},function (error) {
deferred.reject(error.data.error_description);
});
return deferred.promise;
}
function getIssueComments(id) {
var deferred = $q.defer();
$http.get(BASE_URL + 'issues/' + id + '/comments')
.then(function (response) {
deferred.resolve(response.data);
},function (error) {
deferred.reject(error.data.error_description);
});
return deferred.promise;
}
function addCommentToIssue(id, comment) {
var deferred = $q.defer();
$http.post(BASE_URL + 'issues/' + id + '/comments', comment)
.then(function (response) {
deferred.resolve(response.data);
},function (error) {
deferred.reject(error.data.error_description);
});
return deferred.promise;
}
return {
getMyIssues: getMyIssues,
addIssue: addIssue,
editIssue: editIssue,
changeStatus: changeStatus,
getIssueById: getIssueById,
getIssueComments: getIssueComments,
addCommentToIssue: addCommentToIssue
};
}
]); |
require 'ffi'
require 'benchmark'
module LibGo
extend FFI::Library
ffi_lib './libgo_example_2.so'
attach_function :fib, [:int], :int
end
def fib(i)
return i if i < 2
return fib(i-2)+fib(i-1)
end
LibGo.fib(1)
n=10000
Benchmark.bm(15) do |x|
(2..14).step(2).each do |num|
puts "-"*60
x.report("fib #{num} golang "){ n.times{ LibGo.fib(num) }}
x.report("fib #{num} ruby"){ n.times{ fib(num); }}
end
end |
#pragma once
#include "core/narukami.h"
#include "core/texture.h"
#include "core/spectrum.h"
NARUKAMI_BEGIN
template <class T>
class ConstantTexture : public Texture<T>
{
private:
T _value;
public:
ConstantTexture(const T& v):_value(v){}
virtual T sample(const Point2f &uv) const override
{
return _value;
}
};
typedef ConstantTexture<float> <API key>;
typedef ConstantTexture<Spectrum> <API key>;
NARUKAMI_END |
var supportVibrate = 'vibrate' in navigator;
if (supportVibrate) {
// vibrate for one second
navigator.vibrate(2000);
// vibrate for 2 secs, wait for 5 secs, then again vibrate for 2 secs
navigator.vibrate([2000, 5000, 2000]);
// Either of these stop vibration
navigator.vibrate(0);
navigator.vibrate([]);
// Continued vibration with setInterval and clearInterval
var vibrateInterval;
// starts vibration
function startVibration(duration){
navigator.vibrate(duration);
}
// stop vibration
function stopVibration () {
// clear interval and stop persistent vibration
if(vibrateInterval) clearInterval(vibrateInterval);
navigator.vibrate(0);
}
// start persistent vibration at given duration and interval
// Assumes a number value is given
function <API key>(duration, interval){
vibrateInterval = setInterval(function(){
startVibration(duration);
}, interval);
}
var startBtn = document.querySelector('#start');
var stopBtn = document.querySelector('#stop');
startBtn.addEventListener('click', function(){
<API key>(2000, 3000);
}, false);
stopBtn.addEventListener('click', function(){
stopVibration();
}, false);
} else {
alert('Vibration API is not supported');
} |
class Subscription < ActiveRecord::Base
has_many :videos, through: :video_views
has_many :video_views
scope :between, lambda {|start, finish|
where{ (start_date >= start) & (end_date <= finish)}
}
def price_per_video(video_ids=[], amount)
average_price = amount / video_ids.length
<API key>(video_ids, average_price)
end
def <API key>(array, price)
rows = array.zip( [price]*array.size)
hash = rows.map{ |r| Hash[r[0].to_s => r[1]]}
hash.inject(Hash.new(0)) {|memo, subhash| subhash.each {|prod, value| memo[prod] += value}; memo}
end
def price_for_duration(start, finish)
duration = start - finish
price * (duration / total_duration)
end
def total_duration
start_date - end_date
end
end |
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta content='IE=edge,chrome=1' http-equiv='X-UA-Compatible'>
<title>
Welcome to Middleman
</title>
<link href="/stylesheets/normalize.css" rel="stylesheet" type="text/css" /><link href="/stylesheets/all.css" rel="stylesheet" type="text/css" />
<script src="/javascripts/all.js" type="text/javascript"></script>
</head>
<body class='index'>
<div id='container'>
<section class='hero'>
<div class='blackener'></div>
<header>
<p>
a landing page template
by
<a href='http://montadigital.com'>Monta Digital</a>
</p>
</header>
<h1>Product Launch</h1>
<h2>Differentiated from competition</h2>
<form>
<input placeholder='My e-mail address' type='text'>
<input type='submit' value='Keep me in the loop'>
</form>
<div class='form_incentive'>
<img src='/images/arrow.png'>
<p>
We promise to e-mail you only twice. Once for confirmation, and
once for the product launch.
</p>
</div>
<span class='chevron bottom'></span>
</section>
<section>
<h1>We plan to launch a website</h1>
<img class='centerbottom' src='/images/Browser.svg'>
<p>
Donec placerat nibh eu aliquam facilisis. Morbi congue accumsan malesuada.
</p>
<p>
<a href="#">Nibh eu</a>
</p>
</section>
<section class='leftimage'>
<h1>... and a mobile app</h1>
<div class='left'>
<img src='/images/mobile.svg'>
<p>
Image Caption
</p>
</div>
<div class='right'>
<p>
Donec placerat nibh eu aliquam facilisis. Morbi congue accumsan malesuada.
</p>
<ul>
<li>One reason why it is great...</li>
<li>... is that it is mobile ...</li>
<li>... and it is an app!</li>
</ul>
<p>
<a href="#">Morbi congue</a>
</p>
</div>
</section>
<section class='rightimage'>
<h1>What about images on the right?</h1>
<p>
Glad you asked! We have you covered.
</p>
<div class='left'>
<p>
Donec placerat nibh eu aliquam facilisis. Morbi congue accumsan malesuada.
</p>
<ul>
<li>One reason why it is great...</li>
<li>... is that it is mobile ...</li>
<li>... and it is an app!</li>
</ul>
<p>
<a href="#">Check this out</a>
</p>
</div>
<div class='right'>
<img src='/images/mobile.svg'>
<p>
Image Caption
</p>
</div>
</section>
<section class='twoimages'>
<h1>Here are two images to clinch the deal</h1>
<div class='left'>
<img src='/images/Modal.svg'>
<p>
Image Caption
</p>
</div>
<div class='right'>
<img src='/images/Modal.svg'>
<p>
Image Caption
</p>
</div>
</section>
<section class='finalform'>
<p>We can notify you when Product becomes available. We promise not to spam you!</p>
<form>
<input placeholder='My e-mail address' type='text'>
<input type='submit' value='Keep me in the loop'>
</form>
</section>
<footer>
<p>
helped out by
<a href='http://github.com/montadigital.com/lando'>lando</a>
</p>
</footer>
</div>
<style>
/* line 1, (__TEMPLATE__) */
section.leftimage > .right {
float: right;
width: 25%;
padding-right: 24%; }
/* line 6, (__TEMPLATE__) */
section.leftimage > .left {
float: left;
width: 49%; }
/* line 10, (__TEMPLATE__) */
section.leftimage > div.left > * {
width: 40%;
text-align: center;
display: block;
margin-right: 10%;
margin-left: auto; }
/* line 19, (__TEMPLATE__) */
section.rightimage > .left {
float: left;
width: 25%;
padding-left: 24%; }
/* line 24, (__TEMPLATE__) */
section.rightimage > .right {
float: right;
width: 49%; }
/* line 28, (__TEMPLATE__) */
section.rightimage > div.right > * {
width: 40%;
text-align: center;
display: block;
margin-right: auto;
margin-left: 10%; }
/* line 36, (__TEMPLATE__) */
section.twoimages > .right {
float: right;
width: 49%; }
/* line 40, (__TEMPLATE__) */
section.twoimages > .left {
float: left;
width: 49%; }
/* line 44, (__TEMPLATE__) */
section.twoimages > div.right > * {
width: 40%;
text-align: center;
display: block;
margin-right: auto;
margin-left: 10%; }
/* line 51, (__TEMPLATE__) */
section.twoimages > div.left > * {
width: 40%;
text-align: center;
display: block;
margin-right: 10%;
margin-left: auto; }
/* line 59, (__TEMPLATE__) */
section > img.centerbottom {
width: 35%;
display: block;
margin: 0 auto; }
/* line 64, (__TEMPLATE__) */
.chevron::before {
border-style: solid;
border-width: 0.25em 0.25em 0 0;
content: '';
display: inline-block;
height: 0.45em;
left: 0.15em;
position: relative;
top: 0.15em;
transform: rotate(-45deg);
vertical-align: top;
width: 0.45em; }
/* line 78, (__TEMPLATE__) */
.chevron.right:before {
left: 0;
transform: rotate(45deg); }
/* line 83, (__TEMPLATE__) */
.chevron.bottom:before {
top: 0;
transform: rotate(135deg); }
/* line 88, (__TEMPLATE__) */
.chevron.left:before {
left: 0.25em;
transform: rotate(-135deg); }
/* line 93, (__TEMPLATE__) */
* {
font-family: 'Open Sans', sans; }
/* line 96, (__TEMPLATE__) */
header a {
color: white; }
/* line 99, (__TEMPLATE__) */
footer a {
color: #4A4A4A; }
/* line 102, (__TEMPLATE__) */
footer {
overflow: hidden;
text-align: center;
font-size: 10px;
background: white;
margin: 20px 0;
color: #4A4A4A; }
/* line 110, (__TEMPLATE__) */
header {
left: 0;
top: 0;
text-align: center;
font-size: 10px;
position: absolute;
background: rgba(0, 0, 0, 0.8);
color: white;
width: 100%;
z-index: 1; }
/* line 137, (__TEMPLATE__) */
section {
width: 100%;
background: white;
overflow: hidden; }
/* line 143, (__TEMPLATE__) */
#container {
width: 100%;
height: 100%;
position: fixed;
perspective: 1px;
overflow-x: hidden;
overflow-y: scroll; }
/* line 152, (__TEMPLATE__) */
section.after-hero {
background-color: #fe3c40;
/* padding-top:5vh; */ }
/* line 157, (__TEMPLATE__) */
.blackener {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.25);
z-index: -1; }
/* line 167, (__TEMPLATE__) */
section.hero > .chevron {
color: white;
position: absolute;
left: 50%;
bottom: 15px; }
/* line 174, (__TEMPLATE__) */
section.finalform {
margin-top: 80px;
margin-bottom: 80px;
display: -webkit-box;
/* OLD - iOS 6-, Safari 3.1-6 */
display: -moz-box;
/* OLD - Firefox 19- (buggy but mostly works) */
display: -ms-flexbox;
/* TWEENER - IE 10 */
display: -webkit-flex;
display: flex;
justify-content: center;
-<API key>: center;
-webkit-box-align: center;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
flex-direction: column; }
/* line 180, (__TEMPLATE__) */
section.hero {
position: relative;
display: -webkit-box;
/* OLD - iOS 6-, Safari 3.1-6 */
display: -moz-box;
/* OLD - Firefox 19- (buggy but mostly works) */
display: -ms-flexbox;
/* TWEENER - IE 10 */
display: -webkit-flex;
display: flex;
justify-content: center;
-<API key>: center;
-webkit-box-align: center;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
flex-direction: column;
background-image: url(/images/hero.jpg);
background-size: cover;
background-position: 50% 50%;
transform: translateZ(-1px) scale(2);
top: 0;
height: 100vh;
position: relative;
z-index: -1000; }
/* line 193, (__TEMPLATE__) */
.form_incentive {
margin-top: 20px;
left: 10%;
width: 40%;
position: relative; }
/* line 199, (__TEMPLATE__) */
.form_incentive > p {
font-family: 'Annie Use Your Telescope', cursive;
color: white;
font-size: 18px; }
/* line 205, (__TEMPLATE__) */
.form_incentive > img {
width: 50px;
float: left;
margin-right: 10px; }
/* line 211, (__TEMPLATE__) */
.hero > h1 {
margin: 0; }
/* line 214, (__TEMPLATE__) */
.hero > h2 {
margin-top: 0;
color: white;
font-size: 30px;
text-transform: uppercase;
font-weight: 300;
text-shadow: 0 1px rgba(0, 0, 0, 0.5); }
/* line 222, (__TEMPLATE__) */
.hero > form {
padding: 10px;
border-radius: 10px;
background: rgba(0, 0, 0, 0.5); }
/* line 227, (__TEMPLATE__) */
form > input {
width: 50%; }
/* line 228, (__TEMPLATE__) */
.hero > form > input[type=text],
.finalform > form > input[type=text] {
border-radius: 5px;
border: 1px solid #A4A4A4;
font-family: 'Open Sans', sans;
padding: 5px;
width: 200px; }
/* line 236, (__TEMPLATE__) */
form {
text-align: center; }
/* line 237, (__TEMPLATE__) */
.hero > form > input[type=submit],
.finalform > form > input[type=submit] {
background: #E27319;
border: 0;
width: 150px;
padding: 5px 15px;
font-weight: bold;
color: white;
border-radius: 5px; }
/* line 248, (__TEMPLATE__) */
section a {
color: #E27319; }
/* line 251, (__TEMPLATE__) */
section.hero a {
color: white; }
/* line 255, (__TEMPLATE__) */
section > h1 {
text-align: center;
font-size: 40px; }
/* line 260, (__TEMPLATE__) */
section > p {
text-align: center; }
/* line 264, (__TEMPLATE__) */
section {
font-size: 12px; }
</style>
<style>
/* line 1, (__TEMPLATE__) */
.hero > h1 {
font-family: "Cabin", sans-serif;
color: white;
font-size: 80px;
font-weight: 400;
text-shadow: 0 1px rgba(0, 0, 0, 0.5); }
</style>
</body>
</html> |
Imports System.Threading
Friend NotInheritable Class Program
Private Sub New()
End Sub
''' <summary>
''' The main entry point for the application. |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<meta name="_token" content="{{csrf_token()}}">
<title>{{Config::get('scaffenger.config.title')}}</title>
<!-- Bootstrap Core CSS -->
<link href="{!! asset('vendor/wislem/scaffenger/css/bootstrap.css') !!}" rel="stylesheet">
<!-- Custom CSS -->
<link href="{!! asset('vendor/wislem/scaffenger/vendor/font-awesome/css/font-awesome.min.css') !!}" rel="stylesheet">
<link href="{!! asset('vendor/wislem/scaffenger/vendor/summernote/summernote.css') !!}" rel="stylesheet">
<link href="{!! asset('vendor/wislem/scaffenger/vendor/summernote/summernote-bs3.css') !!}" rel="stylesheet">
<link href="{{ asset('vendor/wislem/scaffenger/css/plugins.css') }}" rel="stylesheet"/>
<link href="{!! asset('vendor/wislem/scaffenger/css/app.css') !!}" rel="stylesheet">
<!-- Icons -->
<!-- The following icons can be replaced with your own, they are used by desktop and mobile browsers -->
<link rel="shortcut icon" href="{{asset('vendor/wislem/scaffenger/img/favicon.png')}}">
<link rel="apple-touch-icon" href="{{asset('vendor/wislem/scaffenger/img/icon57.png')}}" sizes="57x57">
<link rel="apple-touch-icon" href="{{asset('vendor/wislem/scaffenger/img/icon72.png')}}" sizes="72x72">
<link rel="apple-touch-icon" href="{{asset('vendor/wislem/scaffenger/img/icon76.png')}}" sizes="76x76">
<link rel="apple-touch-icon" href="{{asset('vendor/wislem/scaffenger/img/icon114.png')}}" sizes="114x114">
<link rel="apple-touch-icon" href="{{asset('vendor/wislem/scaffenger/img/icon120.png')}}" sizes="120x120">
<link rel="apple-touch-icon" href="{{asset('vendor/wislem/scaffenger/img/icon144.png')}}" sizes="144x144">
<link rel="apple-touch-icon" href="{{asset('vendor/wislem/scaffenger/img/icon152.png')}}" sizes="152x152">
<link rel="apple-touch-icon" href="{{asset('vendor/wislem/scaffenger/img/icon180.png')}}" sizes="180x180">
<!-- END Icons -->
@yield('css')
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:
<!--[if lt IE 9]>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]
</head>
<body>
<div id="wrapper">
<!-- Sidebar -->
@include('scaffenger::partials.sidebar')
<!-- /#sidebar-wrapper -->
<!-- Page Content -->
<div id="<API key>">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<p><a href="#menu-toggle" class="btn btn-sm btn-default" id="menu-toggle"><i class="fa fa-fw fa-navicon"></i></a></p>
@yield('content')
</div>
</div>
</div>
</div>
<!-- /#<API key> -->
</div>
<!-- /#wrapper -->
<!-- jQuery -->
<script src="{!! asset('vendor/wislem/scaffenger/js/jquery.js') !!}"></script>
<script>
var baseUrl = '{{Config::get('app.url')}}';
var _token = $('meta[name="_token"]').attr('content');
var <API key> = '{{Config::get('scaffenger.config.<API key>')}}';
var <API key> = '{{Config::get('scaffenger.config.<API key>')}}';
</script>
<!-- Bootstrap Core JavaScript -->
<script src="{!! asset('vendor/wislem/scaffenger/js/bootstrap.min.js') !!}"></script>
<script src="{!! asset('vendor/wislem/scaffenger/vendor/summernote/summernote.min.js') !!}"></script>
<script src="{!! asset('vendor/wislem/scaffenger/vendor/summernote/<API key>.js') !!}"></script>
<script src="{!! asset('vendor/wislem/scaffenger/vendor/summernote/<API key>.js') !!}"></script>
<script src="{!! asset('vendor/wislem/scaffenger/js/plugins.js') !!}"></script>
<script src="{!! asset('vendor/wislem/scaffenger/js/app.js') !!}"></script>
@yield('js')
</body>
</html> |
import React, {Component} from 'react';
import './style.css';
import {NavLink} from 'react-router-dom';
import axios from 'axios';
import $ from 'jquery';
import Navbar from '../navbar/index3';
class BasicForm extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
e.target.classList.add('active');
this.setState({
[e.target.name]: e.target.value
});
this.showInputError(e.target.name)
}
handleSubmit(e) {
e.preventDefault();
console.log('component state', JSON.stringify(this.state));
if (!this.showFormErrors()) {
console.log('form is invalid: do not submit');
} else {
console.log('form is valid: submit');
var email = $('#input_email').val();
var password = $('#input_password').val();
axios.post('http://localhost:9000/signin', {
email: email,
password: password
}).then(function(response) {
if (response.status = 200) {
console.log(response);
alert("Masuk ke akun berhasil!");
window.location.href = '/dashboard';
} else {
console.log(response);
alert("Data tidak cocok!");
}
}).catch(function(error) {
console.log(error);
});
}
}
showFormErrors() {
const inputs = document.querySelectorAll('input');
let isFormValid = true;
inputs.forEach(input => {
input.classList.add('active');
const isInputValid = this.showInputError(input.name);
if (!isInputValid) {
isFormValid = false;
}
});
return isFormValid;
}
showInputError(refName) {
const validity = this.refs[refName].validity;
const label = document.getElementById(`${refName}Label`).textContent;
const error = document.getElementById(`${refName}Error`);
const isPassword = refName.indexOf('password') !== -1;
const isPasswordConfirm = refName === 'passwordConfirm';
if (isPasswordConfirm) {
if (this.refs.password.value !== this.refs.passwordConfirm.value) {
this.refs.passwordConfirm.setCustomValidity('Passwords do not match');
} else {
this.refs.passwordConfirm.setCustomValidity('');
}
}
if (!validity.valid) {
if (validity.valueMissing) {
error.textContent = `${label} is a required field`;
} else if (validity.typeMismatch) {
error.textContent = `${label} should be a valid email address`;
} else if (isPassword && validity.patternMismatch) {
error.textContent = `${label} should be longer than 4 chars`;
} else if (isPasswordConfirm && validity.customError) {
error.textContent = 'Passwords do not match';
}
return false;
}
error.textContent = '';
return true;
}
render() {
return (
<form novalidate>
<div className="form-group">
<label id="usernameLabel">Email</label>
<input id="input_email" className="form-control" type="email" name="username" ref="username" value={this.state.username} onChange={this.handleChange} required/>
<div className="error" id="usernameError"/>
</div>
<div className="form-group">
<label id="passwordLabel">Password</label>
<input id="input_password" className="form-control" type="password" name="password" ref="password" value={this.state.password} onChange={this.handleChange} pattern=".{5,}" required/>
<div className="error" id="passwordError"/>
</div>
<button className="btn btn-primary" onClick={this.handleSubmit}>submit</button>
</form>
);
}
}
class Signin extends Component {
render() {
return (
<div className="login">
<Navbar/>
<div className="row">
<div className="col-md-6 col-sm-6 col-xs-12">
<div className="login-banner">
<div className="login-banner-title">Gabung Sekarang di CCC!</div>
<div className="<API key>">Tingkatkan skillmu di Code Course Camp. Perbanyak peluang untuk mengejar cita-citamu!</div>
</div>
</div>
<div className="col-md-6 col-sm-6 col-xs-12">
<div className="login-form">
<div className="login-form-title">Masuk Akun</div>
<div className="row">
<div className="col-md-5 col-sm-5 col-xs-7">
<div className="login-form-subtitle">Belum punya akun?</div>
</div>
<div className="col-md-7 col-sm-7 col-xs-5">
<NavLink className="login-form-subtitle" id="login-text" to="/auth">Daftar</NavLink>
</div>
</div>
<BasicForm/>
</div>
</div>
</div>
</div>
);
}
}
export default Signin; |
// OSDataParser.h
// OSLibrary
#import <Foundation/Foundation.h>
@interface OSDataParser : NSObject
- (id)parse:(NSData*)data;
@end |
#subheader {background: url(../images/colours/brown/lhcorner.gif) right bottom no-repeat;}
#main-bg {background: url(../images/colours/brown/mcorner.gif) right top no-repeat;}
#side-border-left{background: url(../images/colours/brown/lscorner.gif) right top no-repeat;}
#side-border-right{background: url(../images/colours/brown/rscorner.gif) left top no-repeat;}
#side-border-left, #side-border-right, .admin-message{background-color: #5d5038;}
.textbox, .button, .bbcode, #main-bg, .tbl-border, .pagenav a:hover{background-color: #927828;}
.tbl-border{border-color: #927828;}
#main-bg .textbox, #main-bg .button, .tbl1, #mainheader, #subheader a:hover, #subheader .active a, #userbar a:hover, .pagenav span{background-color : #795c04;}
.tbl2, .poll {background: #806205;}
.forum-caption, .quote, #subheader, #userbar, #navigation a:hover, .pagenav a{background-color: #554103;} |
var balltop=0 , bouncetime=1000,p=0;
$(document).ready(function(){
$(".main section").hide();
$("nav a").click(function(){
$(".main section").hide();
$(".main section:eq(" + $(this).index() + ")").fadeIn();
});
$("nav a:eq(0)").click();
if($(window).width()>=480){
$("nav").hover(function(){
$(".arrow").fadeOut();
},
function(){
$(".arrow").delay(300).fadeIn();
}
);
}
else{
$('nav').hover(function(){});
}
var bouncetime = 1000;
var ballheight = 20;
var ballsize = 80;
balltop =480;
var n=15;
ballbounce();
function ballbounce() {
blink();
$('#creatures').animate({'bottom':balltop}, bouncetime, 'easeOutQuad', function() {
if(p<12)
{$('figure').delay(900).animate({'height':70+p*1.1},90);
}
$('#creatures').animate({'bottom':ballheight}, bouncetime, 'easeInQuad', function() {
if(p<12)
{$('figure').animate({'height':90},100);}
if(document.height>document.width)
var e= Math.sqrt(1-Math.pow(document.width/document.height,2));//calculating e
else
var e= Math.sqrt(1-Math.pow(document.height/document.width,2));//calculating e
var b= document.height/(n-2), b2=Math.pow(b,2);
var x2= Math.pow($('.cursor').position().left,2), y2=Math.pow($('.cursor').position().top,2);
for( i=1;i<=n;i++){
var a1= Math.pow(i,2)*b2/(1-Math.pow(e,2));
var a2= Math.pow(i+1,2)*b2/(1-Math.pow(e,2));
if (x2/a1+y2/(Math.pow(i,2)*b2)-1 >0 && x2/a2+y2/(Math.pow(i+1,2)*b2)-1 <=0) {
if(i<=12) {
p=i;
// bouncetime=1000;
$('figure').removeClass('nervous');
balltop=480/Math.sqrt(i);
$('.mouth').animate({'height':45-3*i})
break;
}
if(i>=13) {
p=i;
balltop=30;
// bouncetime=1;
// $('figure').removeClass('nervous');
$('.mouth').animate({'height':9+2*i})
$('figure').addClass('nervous');
break;
}
}
if(x2/a1+y2/(Math.pow(1,2)*b2)-1 <0)
{ $('figure').removeClass('nervous');
balltop=480;
}
if(x2/a2+y2/(Math.pow(n,2)*b2)-1 >0)
{ p=n;
balltop= 30;
// $('.mouth').animate({'height':39})
$('figure').addClass('nervous');
}
}
ballbounce();
});
});
}
function blink() {
$('.eye').animate({'height':0},100,function(){
$('.eye').animate({'height':15},100);
});
}
setInterval(blink,5000);
$(document).mousemove(function(h){
$(".cursor").css('top',h.pageY);
$(".cursor").css('left',h.pageX);
});
$("#myButton span").hide();
$(".myButton").click(function(){
$("#myButton span").fadeIn();
return true;
});
}); |
#ifndef SEQDB_H
#define SEQDB_H
#include <string>
#include <vector>
#include <map>
//bool parse_file(const char* csFile, StringVec &vNames, SeqVec &vSeqs);
class seq_db
{
public:
typedef std::string sequence;
typedef std::string name;
typedef std::pair<name, sequence> value_type;
typedef std::vector<value_type>::size_type size_type;
typedef std::map<name, size_type> name_map;
inline bool add(const name& id, const sequence& s)
{
std::pair<name_map::iterator, bool> p = data_map.insert(make_pair(id, size()));
if(p.second)
data_vec.push_back(make_pair(id, s));
else
data_vec[p.first->second].second.append(s);
return p.second;
}
inline void append(size_type idx, const sequence& s)
{
data_vec[idx].second.append(s);
}
inline size_type size() const { return data_vec.size(); }
inline const value_type& operator[](size_type sz) const
{
return data_vec[sz];
}
inline void clear()
{
data_vec.clear();
data_map.clear();
}
bool parse_file(const char *csfile, bool bappend=false);
protected:
std::vector<value_type> data_vec;
name_map data_map;
};
#endif |
/**
* Provides requirement naming strategies.
*/
package com.agilarity.osmo.requirement.name; |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JsFrame.js example - Create a window inside a window</title>
<link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet'>
<link rel="stylesheet" href="../../../index.css">
</head>
<body>
<h2><a href="../../../index.html">JSFrame.js examples</a><span> Create a window inside a window</span>
</h2>
<span>If you want to nest frames like window-in-window, call setFrameInFrame(true) on the parent frame</span>
<div style="font-size: 16px; color: white; position: fixed; right: 20px; bottom: 10px">
<a href="https://github.com/riversun/JSFrame.js/tree/master/public/examples/v160/window-in-window"
title="View source for this page on GitHub" target="_blank">View source on GitHub</a>
</div>
<script src="../../../jsframe.js"></script>
<script>
const parentJsFrame = new JSFrame();
const HTML = '<img style="margin: auto;position: absolute;top: 0;left: 0;right: 0;bottom: 0;width:100%;height:auto;user-select: none" ' +
'src="https://upload.wikimedia.org/wikipedia/commons/e/ec/<API key>.jpg">';
const parentFrame = parentJsFrame.create({
name: `Win0`,
title: `I'm a parent.`,
left: 20,
top: 100,
width: 640,
clientHeight: 480,
style: {
backgroundColor: 'rgba(0,0,0,1.0)',
overflow: 'hidden'
},
appearanceName: 'yosemite',
html: `<div id="<API key>" style="width:100%;height:100%;">${HTML}</div>`,
});
parentFrame.setControl({
maximizeButton: 'zoomButton',
maximizeParam: {
fullScreen: true,
restoreKey: 'Escape',
},
demaximizeButton: 'dezoomButton',
deminimizeButton: 'deminimizeButton',
hideButton: 'minimizeButton',
hideParam: {
align: 'ABSOLUTE',
offset: {
x: 0, y: 0,
},
duration: 300
},
dehideParam: {
duration: 300
},
styleDisplay: 'inline',
animation: true,
animationDuration: 100,//The whole animation duration(millisec)
});
// If you want to nest frames like window-in-window, call setFrameInFrame(true) on the parent frame.
parentFrame.setFrameInFrame(true);
parentFrame.control.on('maximized', (frame, info) => {
parentJsFrame.showToast({
html: `Double click ParentWindow to restore`,
align: 'top',
duration: 2000,
});
frame.on('#<API key>', 'dblclick', function(_frame, e) {
_frame.control.doCommand('restore');
});
});
parentFrame.show();
const childJsFrame = new JSFrame({ parentElement: document.querySelector('#<API key>') });
const CHILD_HTML = `<div id="<API key>" style="width:100%;height:100%;">
<img id="child-image" style="margin: auto;position: absolute;top: 0;left: 0;right: 0;bottom: 0;width:100%;height:auto;user-select: none" src="https://upload.wikimedia.org/wikipedia/commons/3/3f/<API key>.jpg">
</div>`;
const childFrame = childJsFrame.create({
name: `Win0-0`,
title: `I'm a child`,
left: 20,
top: 20,
width: 400,
clientHeight: 300,
style: {
backgroundColor: 'rgba(0,0,0,1.0)',
overflow: 'hidden'
},
appearanceName: 'yosemite',
html: CHILD_HTML,
});
childFrame.setFrameInFrame(true);
childFrame.setControl({
maximizeButton: 'zoomButton',
maximizeParam: {
fullScreen: true,
restoreKey: 'Escape',
matchParent: true
},
demaximizeButton: 'dezoomButton',
deminimizeButton: 'deminimizeButton',
hideButton: 'minimizeButton',
hideParam: {
align: 'ABSOLUTE',
offset: {
x: 0, y: 0,
},
duration: 300
},
dehideParam: {
duration: 300
},
styleDisplay: 'inline',
animation: true,
animationDuration: 100,//The whole animation duration(millisec)
});
childFrame.control.on('maximized', (frame, info) => {
parentJsFrame.showToast({
html: `Double click ChildWindow to restore`,
align: 'top',
duration: 2000,
});
frame.on('#child-image', 'dblclick', function(_frame, e) {
e.stopPropagation();
_frame.control.doCommand('restore');
});
});
childFrame.show();
const grandchildJsFrame = new JSFrame({ parentElement: document.querySelector('#<API key>') });
const GRAND_CHILD_HTML = '<img id="grandchild-image" style="margin: auto;position: absolute;top: 0;left: 0;right: 0;bottom: 0;width:100%;height:auto;user-select: none" ' +
'src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Yokohama_bay_bridge.jpg/<API key>.jpg">';
const grandchildFrame = grandchildJsFrame.create({
name: `Win0-0-0`,
title: `I'm a grandchild`,
left: 20,
top: 20,
width: 240,
clientHeight: 180,
style: {
backgroundColor: 'rgba(0,0,0,1.0)',
overflow: 'hidden'
},
appearanceName: 'yosemite',
html: GRAND_CHILD_HTML,
});
grandchildFrame.setFrameInFrame(true);
grandchildFrame.setControl({
maximizeButton: 'zoomButton',
maximizeParam: {
fullScreen: true,
restoreKey: 'Escape',
matchParent: true
},
demaximizeButton: 'dezoomButton',
deminimizeButton: 'deminimizeButton',
hideButton: 'minimizeButton',
hideParam: {
align: 'ABSOLUTE',
offset: {
x: 0, y: 0,
},
duration: 300
},
dehideParam: {
duration: 300
},
styleDisplay: 'inline',
animation: true,
animationDuration: 100,//The whole animation duration(millisec)
});
grandchildFrame.control.on('maximized', (frame, info) => {
parentJsFrame.showToast({
html: `Double click ChildWindow to restore`,
align: 'top',
duration: 2000,
});
frame.on('#grandchild-image', 'dblclick', function(_frame, e) {
e.stopPropagation();
_frame.control.doCommand('restore');
});
});
grandchildFrame.show();
</script>
</body>
</html> |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="ApiGen 2.8.0" />
<title>Class LogicException | Webcook translator</title>
<script type="text/javascript" src="resources/combined.js?2072791610"></script>
<script type="text/javascript" src="elementlist.js?924972180"></script>
<link rel="stylesheet" type="text/css" media="all" href="resources/style.css?3505392360" />
</head>
<body>
<div id="left">
<div id="menu">
<a href="index.html" title="Overview"><span>Overview</span></a>
<div id="groups">
<h3>Namespaces</h3>
<ul>
<li class="active"><a href="namespace-PHP.html">PHP</a>
</li>
<li><a href="namespace-Webcook.html">Webcook<span></span></a>
<ul>
<li><a href="namespace-Webcook.Translator.html">Translator<span></span></a>
<ul>
<li><a href="namespace-Webcook.Translator.Results.html">Results</a>
</li>
<li><a href="namespace-Webcook.Translator.Services.html">Services</a>
</li>
</ul></li></ul></li>
</ul>
</div>
<hr />
<div id="elements">
<h3>Exceptions</h3>
<ul>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="class-Exception.html">Exception</a></li>
<li class="active"><a href="<API key>.html">LogicException</a></li>
</ul>
</div>
</div>
</div>
<div id="splitter"></div>
<div id="right">
<div id="rightInner">
<form id="search">
<input type="hidden" name="cx" value="" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" class="text" />
<input type="submit" value="Search" />
</form>
<div id="navigation">
<ul>
<li>
<a href="index.html" title="Overview"><span>Overview</span></a>
</li>
<li>
<a href="namespace-PHP.html" title="Summary of PHP"><span>Namespace</span></a>
</li>
<li class="active">
<span>Class</span> </li>
</ul>
<ul>
<li>
<a href="tree.html" title="Tree view of classes, interfaces, traits and exceptions"><span>Tree</span></a>
</li>
</ul>
<ul>
</ul>
</div>
<div id="content" class="class">
<h1>Class LogicException</h1>
<dl class="tree">
<dd style="padding-left:0px">
<a href="class-Exception.html"><span>Exception</span></a>
</dd>
<dd style="padding-left:30px">
<img src="resources/inherit.png" alt="Extended by" />
<b><span>LogicException</span></b>
</dd>
</dl>
<div>
<h4>Direct known subclasses</h4>
<a href="<API key>.html"><API key></a>
</div>
<div>
<h4>Indirect known subclasses</h4>
<a href="<API key>.html"><API key></a>
</div>
<div class="info">
<b>PHP Extension:</b> <a href="http://php.net/manual/book.spl.php" title="Go to PHP documentation">SPL</a><br />
<b>Documented at</b> <a href="http://php.net/manual/class.logicexception.php" title="Go to PHP documentation">php.net</a><br />
</div>
<table class="summary inherited">
<caption>Methods inherited from <a href="class-Exception.html#methods">Exception</a></caption>
<tr>
<td><code>
<a href="class-Exception.html
<a href="class-Exception.html
<a href="class-Exception.html#_getCode">getCode()</a>,
<a href="class-Exception.html#_getFile">getFile()</a>,
<a href="class-Exception.html#_getLine">getLine()</a>,
<a href="class-Exception.html#_getMessage">getMessage()</a>,
<a href="class-Exception.html#_getPrevious">getPrevious()</a>,
<a href="class-Exception.html#_getTrace">getTrace()</a>,
<a href="class-Exception.html#_getTraceAsString">getTraceAsString()</a>
</code></td>
</tr>
</table>
<table class="summary inherited">
<caption>Properties inherited from <a href="class-Exception.html#properties">Exception</a></caption>
<tr>
<td><code>
<a href="class-Exception.html#$code"><var>$code</var></a>,
<a href="class-Exception.html#$file"><var>$file</var></a>,
<a href="class-Exception.html#$line"><var>$line</var></a>,
<a href="class-Exception.html#$message"><var>$message</var></a>
</code></td>
</tr>
</table>
</div>
<div id="footer">
Webcook translator API documentation generated by <a href="http://apigen.org">ApiGen 2.8.0</a>
</div>
</div>
</div>
</body>
</html> |
package youtube
import (
"github.com/Go-Docker-Hackathon/team-iDareX/vendor/db/mongo"
"labix.org/v2/mgo/bson"
"fmt"
)
var WorkQueue = make(chan WorkRequest, 100)
func Collector(url , formatId string) {
C := mongo.Connect()
C.Update(bson.M{"fetchurl": url}, bson.M{"$set": bson.M{"status": 1}}) // start download
fmt.Println("mongodb start download")
work := WorkRequest{ Url: url, FormatId: formatId}
WorkQueue <- work
} |
How does tracking and adding changes make developers' lives easier?
Tracking and adding changes in this way prevents version conflicts between team members, and allows developers to revert their project to an earlier state.
What is a commit?
A commit is the saved state of a project.
What are the best practices for commit messages?
Commit messages should be written in the imperative. They should have a header below 50 characters long, and a brief body that goes into further detail and is no more than 72 characters wide.
What does the HEAD^ argument mean?
HEAD refers to the latest commit on the branch you currently have checked out.
What are the 3 stages of a git change and how do you move a file from one stage to the other?
Stage 1: Untracked. Type "git add [filename]" to stage the file.
Stage 2: Staged/tracked. Type "git commit" to save the staged files to a new...
Stage 3: Commit. The saved snapshot of your branch.
Write a handy cheatsheet of the commands you need to commit your changes?
Committing changes:
1- Save document in editor
2- git add [filename]
3- git commit
What is a pull request and how do you create and merge one?
A pull request is step 1 in merging your branch with the next one down on GitHub. You create one by clicking the "Compare & pull request" button on a branch you just uploaded. Pick the base branch and the branch to be merged, and fill in the title and description. Click "Create pull request" to finalize.
You (or another developer) can then merge the changes. On the pull request page, click the "Merge pull request" button, and then confirm by clicking "Confirm merge."
Why are pull requests preferred when working with teams?
Without having someone centrally overseeing and approving merges, you'd have the same kind of chaos as if you weren't using version control at all. You'd have multiple people coming in and merging their changes into the master branch and possibly breaking one another's work. |
<?php
namespace HB\BlogBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\<API key>\Configuration\Route;
use Sensio\Bundle\<API key>\Configuration\Template;
class DefaultController extends Controller {
/**
* @Route("/", name="home")
* @Template()
*/
public function indexAction() {
return array();
}
/**
* @Route("/hello/{name}")
* @Template()
*/
public function helloAction($name) {
return array('name' => $name);
}
} |
package edu.cornell.gobii.gdi.forms;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolTip;
import org.eclipse.wb.swt.SWTResourceManager;
import org.gobiiproject.gobiiapimodel.payload.PayloadEnvelope;
import org.gobiiproject.gobiiapimodel.restresources.common.RestUri;
import org.gobiiproject.gobiiapimodel.types.<API key>;
import org.gobiiproject.gobiiclient.core.gobii.GobiiClientContext;
import org.gobiiproject.gobiiclient.core.gobii.<API key>;
import org.gobiiproject.gobiimodel.headerlesscontainer.AnalysisDTO;
import org.gobiiproject.gobiimodel.headerlesscontainer.ContactDTO;
import org.gobiiproject.gobiimodel.headerlesscontainer.EntityPropertyDTO;
import org.gobiiproject.gobiimodel.types.GobiiProcessType;
import edu.cornell.gobii.gdi.main.App;
import edu.cornell.gobii.gdi.services.Controller;
import edu.cornell.gobii.gdi.services.IDs;
import edu.cornell.gobii.gdi.utils.FormUtils;
import edu.cornell.gobii.gdi.utils.Utils;
import edu.cornell.gobii.gdi.utils.WizardUtils;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.apache.log4j.Logger;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
public class FrmAnalyses extends AbstractFrm{
private static Logger log = Logger.getLogger(FrmAnalyses.class.getName());
private Text txtName;
private Text txtProgram;
private Text txtProgramVersion;
private Text txtAlgorithm;
private Text txtSourceName;
private Text txtSourceVersion;
private Text txtSourceURL;
private String config;
private StyledText memoDescription;
private Combo cbType;
private Combo cbReference;
private Table tbParameters;
private TableViewer viewerParameters;
private int currentAnalysisId=0;
protected Integer <API key>=0;
/**
* Create the composite.
* @param parent
* @param style
*/
public FrmAnalyses(final Shell shell, Composite parent, int style, final String config) {
super(shell, parent, style);
this.config = config;
GridLayout gridLayout = (GridLayout) cmpForm.getLayout();
gridLayout.numColumns = 2;
cbList.setText("*Select Analysis Type");
lblCbList.setText("Analysis Types:");
Label lblName = new Label(cmpForm, SWT.NONE);
lblName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblName.setText("*Analysis Name:");
txtName = new Text(cmpForm, SWT.BORDER);
txtName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
txtName.addFocusListener(new FocusListener() {
ToolTip tip = new ToolTip(shell, SWT.BALLOON);
@Override
public void focusGained(FocusEvent e) {
// TODO Auto-generated method stub
if(cbList.getSelectionIndex()<0){
Point loc = cbList.toDisplay(cbList.getLocation());
tip.setMessage("Please select an Analysis Type before creating or updating an entry.");
tip.setLocation(loc.x + cbList.getSize().x , loc.y-cbList.getSize().y/2);
tip.setVisible(true);
}
}
@Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub
tip.setVisible(false);
}
});
Label lblNewLabel = new Label(cmpForm, SWT.NONE);
memoDescription = new StyledText(cmpForm, SWT.BORDER | SWT.WRAP);
memoDescription.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 3));
Label lblAnalysis = new Label(cmpForm, SWT.NONE);
lblAnalysis.setLayoutData(new GridData(SWT.RIGHT, SWT.BOTTOM, false, false, 1, 1));
lblAnalysis.setText("Analysis");
Label lblDescription = new Label(cmpForm, SWT.NONE);
lblDescription.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false, 1, 1));
lblDescription.setText("Description:");
Label lblType = new Label(cmpForm, SWT.NONE);
lblType.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblType.setText("*Type:");
cbType = new Combo(cmpForm, SWT.NONE);
cbType.setEnabled(false);
cbType.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Label lblProgram = new Label(cmpForm, SWT.NONE);
lblProgram.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblProgram.setText("Program:");
txtProgram = new Text(cmpForm, SWT.BORDER);
txtProgram.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Label lblProgramVersion = new Label(cmpForm, SWT.NONE);
lblProgramVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblProgramVersion.setText("Program Version:");
txtProgramVersion = new Text(cmpForm, SWT.BORDER);
txtProgramVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Label lblAlgorithm = new Label(cmpForm, SWT.NONE);
lblAlgorithm.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblAlgorithm.setText("Algorithm:");
txtAlgorithm = new Text(cmpForm, SWT.BORDER);
txtAlgorithm.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Label lblSource = new Label(cmpForm, SWT.NONE);
lblSource.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblSource.setText("Source:");
Group grpSource = new Group(cmpForm, SWT.NONE);
grpSource.setLayout(new GridLayout(2, false));
grpSource.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
Label lblSourceName = new Label(grpSource, SWT.NONE);
lblSourceName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblSourceName.setText("Name:");
txtSourceName = new Text(grpSource, SWT.BORDER);
txtSourceName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Label lblSourceVersion = new Label(grpSource, SWT.NONE);
lblSourceVersion.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblSourceVersion.setText("Version:");
txtSourceVersion = new Text(grpSource, SWT.BORDER);
txtSourceVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Label lblUri = new Label(grpSource, SWT.NONE);
lblUri.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblUri.setText("URI:");
txtSourceURL = new Text(grpSource, SWT.BORDER);
txtSourceURL.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Label lblParameters = new Label(cmpForm, SWT.NONE);
lblParameters.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblParameters.setText("Parameters:");
viewerParameters = new TableViewer(cmpForm, SWT.BORDER | SWT.CHECK | SWT.FULL_SELECTION);
tbParameters = viewerParameters.getTable();
tbParameters.setLinesVisible(true);
tbParameters.setHeaderVisible(true);
GridData gd_tbParameters = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
gd_tbParameters.minimumHeight = 100;
gd_tbParameters.heightHint = 115;
tbParameters.setLayoutData(gd_tbParameters);
TableViewerColumn tableViewerColumn = new TableViewerColumn(viewerParameters, SWT.NONE);
TableColumn tblclmnParameter = tableViewerColumn.getColumn();
tblclmnParameter.setWidth(150);
tblclmnParameter.setText("Parameter");
TableViewerColumn tableViewerColumn_1 = new TableViewerColumn(viewerParameters, SWT.NONE);
TableColumn tblclmnValue = tableViewerColumn_1.getColumn();
tblclmnValue.setWidth(100);
tblclmnValue.setText("Value");
new Label(cmpForm, SWT.NONE);
tbParameters.addListener(SWT.MouseDown, event -> {
TableEditor editor = new TableEditor(tbParameters);
// The editor must have the same size as the cell and must
// not be any smaller than 50 pixels.
editor.horizontalAlignment = SWT.LEFT;
editor.grabHorizontal = true;
editor.minimumWidth = 50;
Control oldEditor = editor.getEditor();
if (oldEditor != null)
oldEditor.dispose();
Point pt = new Point(event.x, event.y);
TableItem item = tbParameters.getItem(pt);
if (item == null)
return;
Text newEditor = new Text(tbParameters, SWT.NONE);
int EDITABLECOLUMN = -1;
for (int i = 0; i < tbParameters.getColumnCount(); i++) {
Rectangle rect = item.getBounds(i);
if (rect.contains(pt)) {
EDITABLECOLUMN = i;
break;
}
}
final int col = EDITABLECOLUMN;
if(col < 0) return;
newEditor.setText(item.getText(col));
Listener textListener = new Listener() {
public void handleEvent(final Event e) {
switch (e.type) {
case SWT.FocusOut:
item.setText(col, newEditor.getText());
newEditor.dispose();
break;
case SWT.Traverse:
switch (e.detail) {
case SWT.TRAVERSE_RETURN:
item
.setText(col, newEditor.getText());
// FALL THROUGH
case SWT.TRAVERSE_ESCAPE:
newEditor.dispose();
e.doit = false;
}
break;
}
}
};
newEditor.addListener(SWT.FocusOut, textListener);
newEditor.addListener(SWT.Traverse, textListener);
newEditor.selectAll();
newEditor.setFocus();
editor.setEditor(newEditor, item, col);
});
Group group = new Group(cmpForm, SWT.NONE);
group.setLayout(new GridLayout(2, false));
GridData gd_group = new GridData(SWT.FILL, SWT.TOP, false, false, 1, 1);
gd_group.heightHint = 48;
group.setLayoutData(gd_group);
Button btnNewParameter = new Button(group, SWT.NONE);
btnNewParameter.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
btnNewParameter.<API key>(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
@SuppressWarnings("unused")
TableItem item = new TableItem(tbParameters, SWT.NONE);
}
});
btnNewParameter.setText("New Parameter");
Button btnDeleteParameter = new Button(group, SWT.NONE);
btnDeleteParameter.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
btnDeleteParameter.<API key>(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
<API key>(false);
}
});
btnDeleteParameter.setText("Delete Parameter");
Label lblReference = new Label(cmpForm, SWT.NONE);
lblReference.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblReference.setText("Reference:");
cbReference = new Combo(cmpForm, SWT.NONE);
cbReference.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
new Label(cmpForm, SWT.NONE);
<API key>(cbReference);
Button btnAddNew = new Button(cmpForm, SWT.NONE);
btnAddNew.<API key>(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
try{
if(!validate(true)) return;
AnalysisDTO analysisDTO = new AnalysisDTO();
analysisDTO.setAnalysisName(txtName.getText());
analysisDTO.setAnlaysisTypeId(<API key>);
analysisDTO.<API key>(memoDescription.getText());
analysisDTO.setProgram(txtProgram.getText());
analysisDTO.setProgramVersion(txtProgramVersion.getText());
analysisDTO.setAlgorithm(txtAlgorithm.getText());
analysisDTO.setSourceName(txtSourceName.getText());
analysisDTO.setSourceUri(txtSourceURL.getText());
analysisDTO.setSourceVersion(txtSourceVersion.getText());
analysisDTO.setStatusId(1);
if(cbReference.getSelectionIndex() > -1){
String ref = (String) cbReference.getData(cbReference.getItem(cbReference.getSelectionIndex()));
analysisDTO.setReferenceId(Integer.parseInt(ref));
}
for(TableItem item : tbParameters.getItems()){
EntityPropertyDTO prop = new EntityPropertyDTO();
if(item.getText(0).isEmpty()) continue;
prop.setPropertyName(item.getText(0));
prop.setPropertyValue(item.getText(1));
analysisDTO.getParameters().add(prop);
}
PayloadEnvelope<AnalysisDTO> payloadEnvelope = new PayloadEnvelope<>(analysisDTO,
GobiiProcessType.CREATE);
<API key><AnalysisDTO> restResource = new <API key><>(GobiiClientContext.getInstance(null, false)
.getUriFactory()
.resourceColl(<API key>.URL_ANALYSIS));
PayloadEnvelope<AnalysisDTO> resultEnvelope = restResource.post(AnalysisDTO.class,
payloadEnvelope);
if(Controller.getDTOResponse(shell, resultEnvelope.getHeader(), memInfo, true)){
<API key>(FormUtils.getIdFromFormList(cbList));
currentAnalysisId = resultEnvelope.getPayload().getData().get(0).getAnalysisId();
selectedName = txtName.getText();
FormUtils.selectRowById(tbList, currentAnalysisId);
};
}catch(Exception err){
Utils.log(shell, memInfo, log, "Error saving analysis", err);
}
}
});
btnAddNew.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
btnAddNew.setText("Add New");
new Label(cmpForm, SWT.NONE);
Button btnUpdate = new Button(cmpForm, SWT.NONE);
btnUpdate.<API key>(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
try{
if(!validate(false)) return;
if(!FormUtils.updateForm(getShell(), "Analysis", selectedName)) return;
AnalysisDTO analysisDTO = new AnalysisDTO();
analysisDTO.setAnalysisId(currentAnalysisId);
analysisDTO.setAnalysisName(txtName.getText());
analysisDTO.setAnlaysisTypeId(<API key>);
analysisDTO.<API key>(memoDescription.getText());
analysisDTO.setProgram(txtProgram.getText());
analysisDTO.setProgramVersion(txtProgramVersion.getText());
analysisDTO.setAlgorithm(txtAlgorithm.getText());
analysisDTO.setSourceName(txtSourceName.getText());
analysisDTO.setSourceUri(txtSourceURL.getText());
analysisDTO.setSourceVersion(txtSourceVersion.getText());
analysisDTO.setStatusId(1);
if(cbReference.getSelectionIndex() > -1){
String ref = (String) cbReference.getData(cbReference.getItem(cbReference.getSelectionIndex()));
analysisDTO.setReferenceId(Integer.parseInt(ref));
}
for(TableItem item : tbParameters.getItems()){
EntityPropertyDTO prop = new EntityPropertyDTO();
if(item.getText(0).isEmpty()) continue;
prop.setPropertyName(item.getText(0));
prop.setPropertyValue(item.getText(1));
analysisDTO.getParameters().add(prop);
}
RestUri restUri = GobiiClientContext.getInstance(null, false).getUriFactory().<API key>(<API key>.URL_ANALYSIS);
restUri.setParamValue("id", Integer.toString(currentAnalysisId));
<API key><AnalysisDTO> restResourceById = new <API key><>(restUri);
restResourceById.setParamValue("id", analysisDTO.getAnalysisId().toString());
PayloadEnvelope<AnalysisDTO> analysisDTOResponse = restResourceById.put(
AnalysisDTO.class, new PayloadEnvelope<>(analysisDTO, GobiiProcessType.UPDATE));
if(Controller.getDTOResponse(shell, analysisDTOResponse.getHeader(), memInfo, true)){
<API key>(<API key>);
FormUtils.selectRowById(tbList, currentAnalysisId);
};
}catch(Exception err){
Utils.log(shell, memInfo, log, "Error saving analysis", err);
}
}
});
btnUpdate.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
btnUpdate.setText("Update");
new Label(cmpForm, SWT.NONE);
Button btnClearFields = new Button(cmpForm, SWT.NONE);
btnClearFields.<API key>(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
<API key>();
if(<API key>==0) cbType.setText("");
// currentAnalysisId=0;
}
});
btnClearFields.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
btnClearFields.setText("Clear Fields");
}
@Override
protected void checkSubclass() {
// Disable the check that prevents subclassing of SWT components
}
@Override
protected void createContent() {
// TODO Auto-generated method stub
<API key>();
<API key>();
cbList.addListener (SWT.Selection, new Listener() {
public void handleEvent(Event e) {
String selected = cbList.getText(); //single selection
cbType.setText(selected);
<API key>();
currentAnalysisId=0;
<API key> = FormUtils.getIdFromFormList(cbList);
<API key>(<API key>); //retrieve and display projects by contact Id
}
});
btnRefresh.<API key>(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
tbList.removeAll();
Integer id = FormUtils.getIdFromFormList(cbList);
if(id>0){
FormUtils.<API key>(Controller.getAnalysisTypes(), cbList, id);
<API key>(id);
<API key>(cbType, id);
}
else{
<API key>();
<API key>();
cbType.removeAll();
cbList.setText("*Select Analysis Type");
}
<API key>(cbReference);
<API key>();
currentAnalysisId=0;
}
});
tbList.addListener (SWT.Selection, new Listener() {
public void handleEvent(Event e) {
String selected = tbList.getSelection()[0].getText(); //single selection
selectedName = selected;
<API key>();
<API key>(FormUtils.getIdFromTableList(tbList)); //retrieve and display projects by contact Id
}
protected void <API key>(int analysisId) {
currentAnalysisId = analysisId;
try {
RestUri restUri = GobiiClientContext.getInstance(null, false).getUriFactory().<API key>(<API key>.URL_ANALYSIS);
restUri.setParamValue("id", Integer.toString(analysisId));
<API key><AnalysisDTO> restResource = new <API key><>(restUri);
PayloadEnvelope<AnalysisDTO> dtoRequestAnalysis = restResource.get(AnalysisDTO.class);
AnalysisDTO analysisDTOResponse = dtoRequestAnalysis.getPayload().getData().get(0);
//displayDetails
selectedName = analysisDTOResponse.getAnalysisName();
txtName.setText(analysisDTOResponse.getAnalysisName());
if(analysisDTOResponse.<API key>()!=null) memoDescription.setText(analysisDTOResponse.<API key>());
<API key>(cbType, analysisDTOResponse.getAnlaysisTypeId());
if(analysisDTOResponse.getProgram() != null) txtProgram.setText(analysisDTOResponse.getProgram());
if(analysisDTOResponse.getProgramVersion()!=null) txtProgramVersion.setText(analysisDTOResponse.getProgramVersion());
if(analysisDTOResponse.getAlgorithm()!=null) txtAlgorithm.setText(analysisDTOResponse.getAlgorithm());
if(analysisDTOResponse.getSourceName()!=null) txtSourceName.setText(analysisDTOResponse.getSourceName());
if(analysisDTOResponse.getSourceVersion()!=null) txtSourceVersion.setText(analysisDTOResponse.getSourceVersion());
if(analysisDTOResponse.getSourceUri()!=null) txtSourceURL.setText(analysisDTOResponse.getSourceUri());
if(analysisDTOResponse.getReferenceId()!=null){
for(int i=0; i<cbReference.getItemCount(); i++){
String ref = cbReference.getItem(i);
Integer refId = Integer.parseInt((String) cbReference.getData(ref));
if(refId == analysisDTOResponse.getReferenceId()){
cbReference.select(i);
break;
}
}
}
for(EntityPropertyDTO property : analysisDTOResponse.getParameters()){
TableItem item = new TableItem(tbParameters, SWT.NONE);
String prop = property.getPropertyName();
String val = property.getPropertyValue() == null ? "" : property.getPropertyValue();
item.setText(new String[]{prop, val});
}
} catch (Exception e) {
Utils.log(log, "Error getting analysis details", e);
}
// <API key>(projectDTO.getProperties(), table);
}
});
}
private void <API key>() {
try{
txtName.setText("");
memoDescription.setText("");
txtProgram.setText("");
txtProgramVersion.setText("");
txtAlgorithm.setText("");
txtSourceName.setText("");
txtSourceVersion.setText("");
txtSourceURL.setText("");
cbReference.deselectAll();
cbReference.setText("");
<API key>(true);
}catch(Exception e){
Utils.log(shell, memInfo, log, "Error clearing fields", e);
}
}
private void <API key>(boolean deleteAll){
try{
for(TableItem item : tbParameters.getItems()){
if(deleteAll || item.getChecked()){
// Text txt1 = (Text) item.getData("0"); txt1.dispose();
// Text txt2 = (Text) item.getData("1"); txt2.dispose();
item.dispose();
}
}
}catch(Exception e){
Utils.log(shell, memInfo, log, "Error clearing parameter details from form", e);
}
}
protected void <API key>(int analysisTypeId) {
try{
tbList.removeAll();
FormUtils.entrySetToTable(Controller.<API key>(analysisTypeId), tbList);
}catch(Exception e){
Utils.log(shell, memInfo, log, "Error retrieving analysis names", e);
}
}
private void <API key>() {
try{
FormUtils.entrySetToCombo(Controller.getAnalysisTypes(), cbList);
cbList.setText("*Select Analysis Type");
}catch(Exception e){
Utils.log(shell, memInfo, log, "Error retrieving analysis types", e);
}
}
protected void <API key>(Combo comboReference, Integer referenceId) {
try{
FormUtils.<API key>(Controller.getReferenceNames(), comboReference, referenceId);
}catch(Exception e){
Utils.log(shell, memInfo, log, "Error retrieving reference", e);
}
}
protected void <API key>(Combo comboReference){
try{
FormUtils.entrySetToCombo(Controller.getReferenceNames(), comboReference);
}catch(Exception e){
Utils.log(shell, memInfo, log, "Error retrieving references", e);
}
}
private void <API key>() {
try{
FormUtils.entrySetToTable(Controller.getAnalysisNames(), tbList);
}catch(Exception e){
Utils.log(shell, memInfo, log, "Error retrieving analysis names", e);
}
}
private void <API key>(Combo combo, Integer typeId) {
try{
FormUtils.<API key>(Controller.getAnalysisTypes(), combo, typeId);
}catch(Exception e){
Utils.log(shell, memInfo, log, "Error retrieving analysis types", e);
}
}
private boolean validate(boolean isNew){
boolean successful = true;
String message = null;
MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
if(txtName.getText().isEmpty()){
message = "Name field is required!";
successful = false;
}else if(cbList.getSelectionIndex() < 0){
message = "Analysis Type field is required!";
successful = false;
}else if(!isNew && currentAnalysisId==0){
message = "'"+txtName.getText()+"' is recognized as a new value. Please use Add instead.";
successful = false;
}else{
if(isNew || !txtName.getText().equalsIgnoreCase(selectedName)){
for(int i=0; i<tbList.getItemCount(); i++){
if(tbList.getItem(i).getText(0).equalsIgnoreCase(txtName.getText())){
successful = false;
message = "Name of analysis already exists for this Analysis Type";
break;
}
}
}
}
if(!successful){
dialog.setMessage(message);
dialog.open();
}
return successful;
}
} |
class Mc::Blast::<API key> < Mc::BaseController
before_action :set_request, only: [:show, :edit, :update, :destroy]
def index
# Makeshift authorization. Need to improve
if current_member.role.name === "pcell"
@blast_requests = BlastRequest.all
else
@blast_requests = BlastRequest.where(member_id: current_member.id)
end
end
def show
end
def new
@blast_request = BlastRequest.new
end
def create
@blast_request = BlastRequest.new(request_params)
@blast_request.requester = current_member
respond_to do |format|
if @blast_request.save
format.html { redirect_to <API key>(@blast_request), notice: 'Blast request was successfully created.' }
format.json { render :show, status: :created, location: @blast_request }
else
format.html { render :new }
format.json { render json: @blast_request.errors, status: :<API key> }
end
end
end
def update
respond_to do |format|
if @blast_request.update(request_params)
format.html { redirect_to <API key>(@blast_request), notice: 'Blast request was successfully updated.' }
format.json { render :show, status: :ok, location: @test }
else
format.html { render :edit }
format.json { render json: @blast_request.errors, status: :<API key> }
end
end
end
# DELETE /tests/1
# DELETE /tests/1.json
def destroy
@blast_request.destroy
respond_to do |format|
format.html { redirect_to <API key>, notice: 'Blast request was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_request
@blast_request = BlastRequest.find(params[:id])
end
def request_params
params.require(:blast_request).permit(:image, :text, :status)
end
end |
<html>
<head>
</head>
<body>
</body>
</html> |
<!doctype html>
<html class="default no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>DT_BoneFollower | demofile</title>
<meta name="description" content="Documentation for demofile">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../assets/css/main.css">
</head>
<body>
<header>
<div class="tsd-page-toolbar">
<div class="container">
<div class="table-wrap">
<div class="table-cell" id="tsd-search" data-index="../assets/js/search.json" data-base="..">
<div class="field">
<label for="tsd-search-field" class="tsd-widget search no-caption">Search</label>
<input id="tsd-search-field" type="text" />
</div>
<ul class="results">
<li class="state loading">Preparing search index...</li>
<li class="state failure">The search index is not available</li>
</ul>
<a href="../index.html" class="title">demofile</a>
</div>
<div class="table-cell" id="tsd-widgets">
<div id="tsd-filter">
<a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a>
<div class="tsd-filter-group">
<div class="tsd-select" id="<API key>">
<span class="tsd-select-label">All</span>
<ul class="tsd-select-list">
<li data-value="public">Public</li>
<li data-value="protected">Public/Protected</li>
<li data-value="private" class="selected">All</li>
</ul>
</div>
<input type="checkbox" id="<API key>" checked />
<label class="tsd-widget" for="<API key>">Inherited</label>
<input type="checkbox" id="<API key>" checked />
<label class="tsd-widget" for="<API key>">Externals</label>
<input type="checkbox" id="<API key>" />
<label class="tsd-widget" for="<API key>">Only exported</label>
</div>
</div>
<a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a>
</div>
</div>
</div>
</div>
<div class="tsd-page-title">
<div class="container">
<ul class="tsd-breadcrumb">
<li>
<a href="../globals.html">Globals</a>
</li>
<li>
<a href="../modules/_sendtabletypes_.html">"sendtabletypes"</a>
</li>
<li>
<a href="_sendtabletypes_.dt_bonefollower.html">DT_BoneFollower</a>
</li>
</ul>
<h1>Interface DT_BoneFollower</h1>
</div>
</div>
</header>
<div class="container container-main">
<div class="row">
<div class="col-8 col-content">
<section class="tsd-panel tsd-hierarchy">
<h3>Hierarchy</h3>
<ul class="tsd-hierarchy">
<li>
<span class="target">DT_BoneFollower</span>
</li>
</ul>
</section>
<section class="tsd-panel-group tsd-index-group">
<h2>Index</h2>
<section class="tsd-panel tsd-index-panel">
<div class="tsd-index-content">
<section class="tsd-index-section ">
<h3>Properties</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-property <API key>"><a href="_sendtabletypes_.dt_bonefollower.html#m_modelindex" class="tsd-kind-icon">m_<wbr>model<wbr>Index</a></li>
<li class="tsd-kind-property <API key>"><a href="_sendtabletypes_.dt_bonefollower.html#m_solidindex" class="tsd-kind-icon">m_<wbr>solid<wbr>Index</a></li>
</ul>
</section>
</div>
</section>
</section>
<section class="tsd-panel-group tsd-member-group ">
<h2>Properties</h2>
<section class="tsd-panel tsd-member tsd-kind-property <API key>">
<a name="m_modelindex" class="tsd-anchor"></a>
<h3>m_<wbr>model<wbr>Index</h3>
<div class="tsd-signature tsd-kind-icon">m_<wbr>model<wbr>Index<span class="<API key>">:</span> <span class="tsd-signature-type">number</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/saul/demofile/blob/b4d2298/src/sendtabletypes.ts#L375">src/sendtabletypes.ts:375</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property <API key>">
<a name="m_solidindex" class="tsd-anchor"></a>
<h3>m_<wbr>solid<wbr>Index</h3>
<div class="tsd-signature tsd-kind-icon">m_<wbr>solid<wbr>Index<span class="<API key>">:</span> <span class="tsd-signature-type">number</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/saul/demofile/blob/b4d2298/src/sendtabletypes.ts#L376">src/sendtabletypes.ts:376</a></li>
</ul>
</aside>
</section>
</section>
</div>
<div class="col-4 col-menu menu-sticky-wrap menu-highlight">
<nav class="tsd-navigation primary">
<ul>
<li class="globals ">
<a href="../globals.html"><em>Globals</em></a>
</li>
<li class="current tsd-kind-module">
<a href="../modules/_sendtabletypes_.html">"sendtabletypes"</a>
</li>
</ul>
</nav>
<nav class="tsd-navigation secondary menu-sticky">
<ul class="before-current">
</ul>
<ul class="current">
<li class="current tsd-kind-interface <API key>">
<a href="_sendtabletypes_.dt_bonefollower.html" class="tsd-kind-icon">DT_<wbr><wbr>Bone<wbr>Follower</a>
<ul>
<li class=" tsd-kind-property <API key>">
<a href="_sendtabletypes_.dt_bonefollower.html#m_modelindex" class="tsd-kind-icon">m_<wbr>model<wbr>Index</a>
</li>
<li class=" tsd-kind-property <API key>">
<a href="_sendtabletypes_.dt_bonefollower.html#m_solidindex" class="tsd-kind-icon">m_<wbr>solid<wbr>Index</a>
</li>
</ul>
</li>
</ul>
<ul class="after-current">
</ul>
</nav>
</div>
</div>
</div>
<footer class="with-border-bottom">
<div class="container">
<h2>Legend</h2>
<div class="tsd-legend-group">
<ul class="tsd-legend">
<li class="<API key>"><span class="tsd-kind-icon">Object literal</span></li>
<li class="tsd-kind-variable"><span class="tsd-kind-icon">Variable</span></li>
<li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li>
<li class="tsd-kind-function <API key>"><span class="tsd-kind-icon">Function with type parameter</span></li>
<li class="tsd-kind-type-alias"><span class="tsd-kind-icon">Type alias</span></li>
<li class="tsd-kind-type-alias <API key>"><span class="tsd-kind-icon">Type alias with type parameter</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li>
<li class="tsd-kind-interface <API key>"><span class="tsd-kind-icon">Interface with type parameter</span></li>
<li class="tsd-kind-property <API key>"><span class="tsd-kind-icon">Property</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li>
<li class="tsd-kind-class <API key>"><span class="tsd-kind-icon">Class with type parameter</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li>
</ul>
</div>
</div>
</footer>
<div class="container tsd-generator">
<p>Generated using <a href="https://typedoc.org/" target="_blank">TypeDoc</a></p>
</div>
<div class="overlay"></div>
<script src="../assets/js/main.js"></script>
</body>
</html> |
#!/bin/bash
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# all copies or substantial portions of the Software.
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# 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.
sudo cp ./hip.lang /usr/share/gtksourceview-3.0/language-specs |
<?php
namespace PHPExiftool\Driver\Tag\Ricoh;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class RedGain extends AbstractTag
{
protected $Id = 'Rg';
protected $Name = 'RedGain';
protected $FullName = 'Ricoh::Text';
protected $GroupName = 'Ricoh';
protected $g0 = 'MakerNotes';
protected $g1 = 'Ricoh';
protected $g2 = 'Camera';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Red Gain';
protected $flag_Permanent = true;
} |
#ifndef <API key>
#define <API key>
#include <utility>
namespace bid
{
namespace pop_front_detail
{
struct arbitrary_visitor
{
template<class T>
void operator()(T&&)
{}
};
template<class Range>
struct <API key>
{
typedef char (&no)[1];
typedef char (&yes)[2];
template<class>
using yes_wrapper = yes;
template<class R>
static yes_wrapper<decltype(std::declval<R>().pop_front_impl(arbitrary_visitor{}))> test(void*);
// this does not work for some reason, maybe compiler bug?
//static yes_wrapper<decltype(std::declval<R>().pop_front([](auto&&){}))> test(void*);
template<class R>
static no test(...);
static constexpr bool value = sizeof(test<Range>(0)) == sizeof(yes);
};
}
template<class Range>
using has_pop_front = std::integral_constant<bool, pop_front_detail::<API key><Range>::value>;
}
#endif |
export type ToThrowAnyError = (<API key>?: any) => boolean;
declare global {
namespace jasmine {
interface Matchers<T> {
toThrowAnyError: ToThrowAnyError;
}
}
}
export const toThrowAnyError: ToThrowAnyError = (actual) => {
try {
actual();
return false;
} catch (err) {
return true;
}
}; |
require 'socket'
require 'openssl'
module <API key>
def self.extended(base)
# Added device_token attribute if not included by acts_as_pushable
unless base.respond_to?(:<API key>)
base.class_eval do
attr_accessor :device_token
end
end
end
APN_PORT = 2195
@@apn_cert = nil
@@apn_host = nil
def self.apn_enviroment
@@apn_enviroment
end
def self.apn_development?
@@apn_enviroment != :production
end
def self.apn_production?
@@apn_enviroment == :production
end
def self.apn_enviroment= enviroment
@@apn_enviroment = enviroment.to_sym
@@apn_host = self.apn_production? ? "gateway.push.apple.com" : "gateway.sandbox.push.apple.com"
cert = self.apn_production? ? "apn_production.pem" : "apn_development.pem"
path = File.join(File.expand_path(RAILS_ROOT), "config", "certs", cert)
@@apn_cert = File.exists?(path) ? File.read(path) : nil
raise "Missing apple push notification certificate in #{path}" unless @@apn_cert
end
self.apn_enviroment = :development
def send_notification options
raise "Missing apple push notification certificate" unless @@apn_cert
ctx = OpenSSL::SSL::SSLContext.new
ctx.key = OpenSSL::PKey::RSA.new(@@apn_cert)
ctx.cert = OpenSSL::X509::Certificate.new(@@apn_cert)
s = TCPSocket.new(@@apn_host, APN_PORT)
ssl = OpenSSL::SSL::SSLSocket.new(s, ctx)
ssl.sync = true
ssl.connect
ssl.write(self.<API key>(options))
ssl.close
s.close
rescue SocketError => error
raise "Error while sending notifications: #{error}"
end
def self.send_notification token, options = {}
d = Object.new
d.extend <API key>
d.device_token = token
d.send_notification options
end
protected
def <API key> options
json = <API key>::apple_json_array options
message = "\0\0 #{self.device_token_hexa}\0#{json.length.chr}#{json}"
raise "The maximum size allowed for a notification payload is 256 bytes." if message.size.to_i > 256
message
end
def device_token_hexa
# Use `device_token` as the method to get the token from
# unless it is overridde from acts_as_pushable
apn_token_field = "device_token"
if respond_to?(:<API key>)
apn_token_field = <API key>[:device_token_field]
end
token = send(apn_token_field.to_sym)
raise "Cannot send push notification without device token" if !token || token.empty?
[token.delete(' ')].pack('H*')
end
def self.apple_json_array options
result = {}
result['aps'] = {}
result['aps']['alert'] = options[:alert].to_s if options[:alert]
result['aps']['badge'] = options[:badge].to_i if options[:badge]
result['aps']['sound'] = options[:sound] if options[:sound] and options[:sound].is_a? String
result['aps']['sound'] = 'default' if options[:sound] and options[:sound].is_a? TrueClass
result.to_json
end
end
require File.dirname(__FILE__) + "/<API key>/acts_as_pushable" |
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Case</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<style media="screen">
body {
background-color: #404040;
}
/*li {
background-color: #acccda;
border-radius: 6px;
margin: 1px;
}*/
li {
color: #fff;
}
#sss:hover {
/*-webkit-filter: invert(100%) !important;*/
/*color: black;*/
}
#PetStore {
}
</style>
</head>
<body>
<div class="container" style="font-weight: bold;">
<h3></h3>
<ul class="nav nav-tabs">
<li style="background-color: #acccda;margin-left: 1px;border-radius: 5px;" class="active"><i class="fa fa-home fa-2x" style="padding: 6px;"></i></li>
<li class="dropdown" style="background-color: #acccda;margin-left: 1px;border-radius: 5px;">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Community<span class="caret"></span></a>
<ul class = "dropdown-menu">
<li><a href="#">Recent Activity</a></li>
<li class="divider"></li>
<li><a href="#">Member Forum</a></li>
<li class="divider"></li>
<li><a href="#">Member List</a></li>
<li class="divider"></li>
<li><a href="#">Member Groups</a></li>
</ul>
</li>
<li id="sss" style="background-color: #acccda;margin-left: 1px;border-radius: 5px;"><a href="#">Pet Help</a></li>
<li style="background-color: #acccda;margin-left: 1px;border-radius: 5px;"><a href="#">Pets for Sale</a></li>
<li style="background-color: #acccda;margin-left: 1px;border-radius: 5px;"><a href="#">Pet Services</a></li>
</ul>
</div>
</body>
</html> |
import React from 'react';
import PropTypes from 'prop-types';
import styles from './FilePicker.scss';
import WixComponent from '../BaseComponents/WixComponent';
import Add from '../Icons/dist/components/Add';
import uniqueId from 'lodash/uniqueId';
/**
* File picker component
*/
class FilePicker extends WixComponent {
constructor(props) {
super(props);
this.state = {
selectedFileName: props.subLabel
};
this.id = props.id || uniqueId('file_picker_input_');
}
onChooseFile(file) {
const {maxSize, onChange} = this.props;
if (file) {
onChange(file);
if (file.size <= maxSize) {
this.setState({selectedFileName: file.name});
}
}
}
render() {
const {header, mainLabel, supportedFormats, error, errorMessage} = this.props;
return (
<div>
{header && (<span className={styles.header}>{header}</span>)}
<label className={styles.label} htmlFor={this.id}>
<div className={styles.icon}><Add width="42" height="42"/></div>
<div className={styles.content}>
<span className={styles.cta} data-hook="main-label">{mainLabel}</span>
<span className={styles.info} data-hook="sub-label">{this.state.selectedFileName}</span>
{error && <span className={styles.error} data-hook="filePicker-error">{errorMessage}</span>}
</div>
</label>
<input id={this.id} className={styles.input} type="file" accept={supportedFormats} onChange={e => this.onChooseFile(e.target.files[0])}/>
</div>
);
}
}
FilePicker.displayName = 'FilePicker';
FilePicker.defaultProps = {
mainLabel: 'Choose File',
subLabel: 'No file chosen (Max size 5 MB)',
onChange: () => {},
supportedFormats: '*',
errorMessage: '',
maxSize: 5000000 //5MB
};
FilePicker.propTypes = {
/** Some text that will appear above the Icon */
header: PropTypes.string,
/** Callback function for when a file is uploaded */
onChange: PropTypes.func,
/** Some text that will appear as a main label besides the Icon */
mainLabel: PropTypes.string,
/** Some text that will appear as a sub label besides the Icon */
subLabel: PropTypes.string,
/** supported formats seperated by comma (.png, .pdf) */
supportedFormats: PropTypes.string,
/** Max size of file allowed */
maxSize: PropTypes.number,
/** should present error */
error: PropTypes.bool,
/** error message to present */
errorMessage: PropTypes.string,
/** id for the filePicker */
id: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
};
export default FilePicker; |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE CPP #-}
module Data.Bson.Types
( RegexOption(..)
, RegexOptions
, Value(..)
, Binary(..)
, ObjectId(..)
, Document
, Array
, Label
, Field
) where
import Data.Int (Int32, Int64)
import Data.Time.Clock (UTCTime)
import Data.Time.Format ()
import Data.Typeable (Typeable)
import Data.Word (Word32, Word16)
import qualified Data.ByteString as S
import Data.BitSet.Word (BitSet)
import Data.Vector (Vector)
import Data.Word.Word24 (Word24)
import Data.Text (Text)
import Data.UUID (UUID)
import {-# SOURCE #-} Data.Bson.Document (Document)
-- | Options for 'ValueRegex', constructors order is important because
-- it's binary representation should be encoded in alphabetical order.
data RegexOption = <API key>
| <API key>
| <API key>
| RegexOptionDotall
| RegexOptionUnicode
| RegexOptionVerbose
deriving (Eq, Show, Typeable, Enum)
type RegexOptions = BitSet RegexOption
-- | A value is one of the following types of values
data Value = ValueDouble {-# UNPACK #-} !Double
| ValueString {-# UNPACK #-} !Text
| ValueDocument !Document
| ValueArray {-# UNPACK #-} !Array
| ValueBinary !Binary
| ValueObjectId {-# UNPACK #-} !ObjectId
| ValueBool !Bool
| ValueUtcTime {-# UNPACK #-} !UTCTime
| ValueNull
| ValueRegex {-# UNPACK #-} !Text !RegexOptions
| ValueJavascript {-# UNPACK #-} !Text
| <API key> {-# UNPACK #-} !Text !Document
| ValueInt32 {-# UNPACK #-} !Int32
| ValueInt64 {-# UNPACK #-} !Int64
| ValueTimestamp {-# UNPACK #-} !Int64
| ValueMin
| ValueMax
deriving (Eq, Show, Typeable)
type Label = Text
type Array = Vector Value
type Field = (Label, Value)
data ObjectId = ObjectId
{ objectIdTime :: {-# UNPACK #-} !Word32
, objectIdMachine :: {-# UNPACK #-} !Word24
, objectIdPid :: {-# UNPACK #-} !Word16
, objectIdInc :: {-# UNPACK #-} !Word24
} deriving (Eq, Show, Typeable)
data Binary = BinaryGeneric {-# UNPACK #-} !S.ByteString
| BinaryFunction {-# UNPACK #-} !S.ByteString
| BinaryUuid {-# UNPACK #-} !UUID
| BinaryMd5 {-# UNPACK #-} !S.ByteString
| BinaryUserDefined {-# UNPACK #-} !S.ByteString
deriving (Eq, Show, Typeable) |
package com.yotadevices.sdk.template;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import com.yotadevices.sdk.R;
abstract class WidgetBuilder {
protected PendingIntent <API key>;
abstract RemoteViews apply(Context context);
protected RemoteViews apply(Context context, RemoteViews remoteViews) {
remoteViews.<API key>(R.id.widget_root, <API key>);
return remoteViews;
}
public void setMaxViewActivity(PendingIntent intent) {
<API key> = intent;
}
} |
Sphinx Search docker file
======================
Version: **2.2.3-beta**
You can read [the official changelog](http://sphinxsearch.com/bugs/changelog_page.php) for details on changes.
## Content
A Sphinx Search instance builded from source.
Supports:
- stemming (via libstemmer, [link](http://snowball.tartarus.org/download.php))
- xml (with expat and iconv)
- postgresql
- mysql
- odbc
- regular expression filter (via RE2 engine, version 2015-11-01, [link](https://github.com/google/re2))
- lemmatization
- `/var/diz/sphinx/ru.pak` (russian dict)
- `/var/diz/sphinx/en.pak` (english dict)
- `/var/diz/sphinx/de.pak` (deutsch dict)
Exposed ports
* `9312` for client connections
* `9306` for SQL connections
Mount points
This image provides some directories for configurations, logs and other files:
* `/var/idx/sphinx`
* `/var/log/sphinx`
* `/var/lib/sphinx`
* `/var/run/sphinx`
* `/var/diz/sphinx`
All this directories are **data volumes**.
Scripts
The available scripts are:
* `searchd.sh`, to start `searchd` in the foreground (needed also for real-time indexes)
* `indexall.sh`, to index all the plain indexes (i.e., `indexer --all`) defined in the configuration
## Path
Both scripts and Sphinx Search's tools (e.g., the `spelldump` tool) are available from the PATH.
To list all Sphinx Search's tool you can execute:
docker run -it leodido/sphinxsearch:2.2.3-beta ls /usr/local/bin
# indexer indextool searchd spelldump wordbreaker
## Installation
You can clone this repository and manually build it.
cd dockerfiles/sphinxsearch\:2.2.3-beta
docker build -t leodido/sphinxsearch:2.2.3-beta .
Otherwise you can pull this image from docker index.
docker pull leodido/sphinxsearch:2.2.3-beta
## Usage
The simplest use case is to start a Sphinx Search container, attach to it and do whatever you want with it:
docker run -i -t leodido/sphinxsearch:2.2.3-beta /bin/bash
Daemonized usage (1)
Assume that we want to index our documents into some real-time indexes.
Given a Sphinx Search configuration file (e.g., `sphinx.conf`) in our current directory (i.e., `$PWD`), we have to share its content with the container using docker option `-v`.
We also want to link to exposed `9306` port to query Sphinx Search from the host machine.
So, the command to run a **daemonized instance** of this container is:
SS=$(docker run -i -t -v $PWD:/usr/local/etc -p 9306 -d leodido/sphinxsearch:2.2.3-beta searchd.sh)
Now we want to see to which host address it has been linked:
docker port $SS 9306 # which returns 49174
And eventually try to connect to it:
mysql -h 0.0.0.0 -P 49174
We can now index documents into our Sphinx Search container or perform queries against it.
Daemonized usage (2)
Assume that we want to index our documents into some plain indexes.
We need:
1. the data source files (e.g. XML files structured as demanded by the Sphinx Search's xmlpipe2 driver)
2. a valid Sphinx Search configuration file that defines our plain indexes and their sources
3. a way to querying Sphinx Search from the host machine (e.g., using IP `127.0.0.1` and port `9306`)
So, assuming that in our current directory (i.e., `$PWD`) we have these files, we run a daemonized instance of Sphinx Search as follow:
docker run -i -t -v $PWD:/usr/local/etc -p 127.0.0.1:9306:9306 -d leodido/sphinxsearch:2.2.3-beta indexall.sh
This way we have indexed our documents and started serving queries.
Again, if you want to query from the host machine:
mysql -h 127.0.0.1 -P 9306
[.default;
* volume.level = 50;
* volume.mute = false;
*/
class Volume extends EventEmitter {
_level: number;
_mute: boolean;
constructor() {
super();
this._level = util.getintprop('persist.silk.volume.level', 0);
this._mute = util.getboolprop('persist.silk.volume.mute', false);
util.propWatcher.on('persist.silk.volume.mute', this._onMuteChange.bind(this));
util.propWatcher.on('persist.silk.volume.level', this._onLevelChange.bind(this));
}
/**
* Gets the current volume level (0..100). Note that the value returned is
* unaffected by the active mute setting.
*
* @memberof silk-volume
* @instance
*/
get level(): number {
return this._level;
}
/**
* Sets the current volume level (0..100)
*
* @memberof silk-volume
* @instance
*/
set level(newlevel: number): void {
if (newlevel < 0 || newlevel > 100) {
throw new Error(`Invalid volume level: ${newlevel}`);
}
this._level = newlevel;
util.setprop('persist.silk.volume.level', newlevel);
/**
* Emitted when the volume level changes
*
* @event level
* @param {number} Level volume level
* @memberof silk-volume
* @instance
*/
this._throwyEmit('level', newlevel);
}
/**
* Gets the current volume mute
*
* @memberof silk-volume
* @instance
*/
get mute(): boolean {
return this._mute;
}
/**
* Sets the current volume mute
*
* @memberof silk-volume
* @instance
*/
set mute(newmute: boolean): void {
this._mute = newmute;
util.setprop('persist.silk.volume.mute', newmute);
/**
* Emitted when the volume mute changes
*
* @event mute
* @param {bool} Mute enabled or disabled
* @memberof silk-volume
* @instance
*/
this._throwyEmit('mute', newmute);
}
/**
* Emit an event, and re-throw any exceptions to the process once the current
* call stack is unwound.
*
* @private
*/
// Legitimate use of 'any' here based on the fact that Flow's library
// definition for EventEmitter uses it.
// <API key> flowtype/no-weak-types
_throwyEmit(eventName: string, ...args: Array<any>): void {
try {
this.emit(eventName, ...args);
} catch (err) {
process.nextTick(() => {
util.processthrow(err.stack || err);
});
}
}
/**
* External notification of mute change
*
* @private
*/
_onMuteChange() {
const mute = util.getboolprop('persist.silk.volume.mute', false);
if (mute !== this._mute) {
this.mute = mute;
}
}
/**
* External notification of level change
*
* @private
*/
_onLevelChange() {
const level = util.getintprop('persist.silk.volume.level', 0);
if (level !== this._level) {
this.level = level;
}
}
}
let volume = new Volume();
export default volume; |
using System;
using Sophie.Core.VM;
namespace Sophie.Core.Objects
{
public sealed class ObjClass : Obj
{
private const int InitialMethodSize = 256;
public static ObjClass ClassClass;
public int NumFields;
public readonly ObjString Name;
public Method[] Methods;
public ObjClass Superclass;
public bool IsSealed;
// Creates a new class object as well as its associated metaclass.
public ObjClass(ObjClass superclass, int numFields, ObjString name)
{
Methods = new Method[InitialMethodSize];
Superclass = superclass;
NumFields = numFields;
Name = name;
// Create the metaclass.
ObjString metaclassName = MakeString(name + " metaclass");
ObjClass metaclass = new ObjClass(0, metaclassName) { ClassObj = ClassClass };
// Metaclasses always inherit Class and do not parallel the non-metaclass
// hierarchy.
metaclass.BindSuperclass(ClassClass);
ClassObj = metaclass;
BindSuperclass(superclass);
}
// Creates a new "raw" class. It has no metaclass or superclass whatsoever.
// This is only used for bootstrapping the initial Object and Class classes,
// which are a little special.
public ObjClass(int numFields, ObjString name)
{
Methods = new Method[InitialMethodSize];
NumFields = numFields;
Name = name;
}
// Makes [superclass] the superclass of [subclass], and causes subclass to
// inherit its methods. This should be called before any methods are defined
// on subclass.
public void BindSuperclass(ObjClass sc)
{
if (sc == null)
{
throw new Exception("Must have superclass.");
}
Superclass = sc;
// Include the superclass in the total number of fields.
NumFields += sc.NumFields;
// Inherit methods from its superclass.
Methods = new Method[sc.Methods.Length];
sc.Methods.CopyTo(Methods,0);
}
public void BindMethod(int symbol, Method method)
{
if (symbol >= Methods.Length)
{
ResizeMethods(symbol);
}
Methods[symbol] = method;
}
private void ResizeMethods(int symbol)
{
int i = Methods.Length;
while (i <= symbol)
i *= 2;
Method[] m = new Method[i];
Methods.CopyTo(m,0);
Methods = m;
}
}
public delegate bool Primitive(SophieVM vm, Obj[] stack, int argStart);
public enum MethodType
{
// A primitive method implemented in the VM.
// this can directly manipulate the fiber's stack.
Primitive,
// A normal user-defined method.
Block,
// Special call type
Call
};
public sealed class Method : Obj
{
public MethodType MType;
// The method function itself. The [type] determines which field of the union
// is used.
public Primitive Primitive;
// May be a [ObjFn] or [ObjClosure].
public Obj Obj;
} ;
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace <API key>
{
public class Program
{
public static void Main(string[] args)
{
var instance = new Derived();
Console.ReadKey();
}
}
} |
# -*- coding: UTF-8 -*-
"""Tornado forms: simple form validation.
Utility classes.
"""
import functools
def decapitalize(string):
"""Turn MinLength into minLength for JS"""
if not string:
return string
return "{0}{1}".format(string[:1].lower(), string[1:])
class ErrorList(list):
"""List of form errors
On __str__, returns the first item.
"""
def __str__(self):
try:
return str(self[0])
except IndexError:
return ''
class FormError(Exception):
"""Form validation error.
"""
def __init__(self, message, code=None, params=None):
self.message = message
self.params = params
def __str__(self):
if self.params:
return self.message.format(**self.params)
else:
return self.message
def with_form(form=None, name='form'):
"""Decorator for `tornado.web.RequestHandler` methods.
Automatically sets up the form class given as `self._name_`
"""
def decorator(method):
assert form is not None, "Form instance required."
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
form.bind(self, name=name)
return method(self, *args, **kwargs)
return wrapper
return decorator |
/* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.uccollaborationlib;
import com.wilutions.com.*;
/**
* <API key>.
* <API key> Interface
*/
@CoInterface(guid="{<API key>}")
public interface <API key> extends IDispatch {
static boolean __typelib__loaded = __TypeLib.load();
@DeclDISPID(500) public void onOnNameChanged(final IGroup _eventSource, final <API key> _eventData) throws ComException;
@DeclDISPID(501) public void onOnContactAdded(final IGroup _eventSource, final <API key> _eventData) throws ComException;
@DeclDISPID(502) public void onOnContactRemoved(final IGroup _eventSource, final <API key> _eventData) throws ComException;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.