code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
//
// RegionContainerViewController.h
// MH4U Dex
//
// Created by Joseph Goldberg on 3/6/15.
// Copyright (c) 2015 Joseph Goldberg. All rights reserved.
//
#import <UIKit/UIKit.h>
@class Region;
@interface RegionContainerViewController : UIViewController
@property (nonatomic, strong) Region *region;
@end
| Java |
---
layout: post
title: "Welcome to Jekyll!"
date: 2015-12-13 00:34:28 -0600
author: kyletaylored
category: jekyll
image: get-started-with-jekyll.png
---
You’ll find this post in your `_posts` directory. Go ahead and edit it and re-build the site to see your changes. You can rebuild the site in many different ways, but the most common way is to run `jekyll serve`, which launches a web server and auto-regenerates your site when a file is updated.
To add new posts, simply add a file in the `_posts` directory that follows the convention `YYYY-MM-DD-name-of-post.ext` and includes the necessary front matter. Take a look at the source for this post to get an idea about how it works.
Jekyll also offers powerful support for code snippets:
{% highlight ruby %}
def print_hi(name)
puts "Hi, #{name}"
end
print_hi('Tom')
#=> prints 'Hi, Tom' to STDOUT.
{% endhighlight %}
Check out the [Jekyll docs][jekyll-docs] for more info on how to get the most out of Jekyll. File all bugs/feature requests at [Jekyll’s GitHub repo][jekyll-gh]. If you have questions, you can ask them on [Jekyll Talk][jekyll-talk].
[jekyll-docs]: http://jekyllrb.com/docs/home
[jekyll-gh]: https://github.com/jekyll/jekyll
[jekyll-talk]: https://talk.jekyllrb.com/
| Java |
# cooper document with one key example
class RevisionedObject
include Cooper::Document
revision_field :key, type: String
end
describe 'Updating documents' do
let(:object) do
RevisionedObject.new
end
it 'works like Mongoid::Document' do
object.key = 'value0'
object.save
object.update_attributes(key: 'value1')
expect(object.key).to eq 'value1'
end
end
| Java |
<?php
namespace BackendBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class DefaultControllerTest extends WebTestCase
{
public function testIndex()
{
$client = static::createClient();
$crawler = $client->request('GET', '/');
$this->assertContains('Hello World', $client->getResponse()->getContent());
}
}
| Java |
# AIT_MAIKON
マイコン演習最終課題<br>
詳しくはwiki見て
| Java |
---
title: The “Example” of Rest
date: 07/09/2021
---
Besides the examples we already have looked at, this idea of types and symbols can apply to the biblical concept of rest as well. To see this, we go to the New Testament book of Hebrews.
`Read Hebrews 4:1–11. What is the remaining promise of entering His rest referring to? How does Israel’s experience during the Exodus and the wilderness wanderings offer additional insights into the idea of entering into God’s rest?`
The theme of perseverance and faithfulness is very important here. Though talking about the seventh-day Sabbath, the main focus of these verses (and what came before; see Hebrews 3:7–19) is really a call for God’s people to be persevering in faith; that is, to remain faithful to the Lord and the gospel.
These passages remind the reader to take the lessons learned from God’s leading in the past seriously, “so that no one may fall by the same sort of disobedience” (Heb. 4:11, ESV). Pay attention, this is an opportunity! Israel did hear the gospel, the text continues, but the Word did not profit them. Instead of having their faith strengthened by trust and obedience, they chose rebellion (compare with Heb. 3:7–15), and thus, they never experienced the rest that God wanted for them.
Hebrews 4:3 points to the close relationship between faith and rest. We can enter into His rest only when we believe and trust the One who promised rest and who can deliver on this promise, and that is, of course, Jesus Christ.
`Read Hebrews 4:3 again. What was the main problem with the people referred to? What lesson can we take from this for ourselves, we who have had the “gospel . . . preached to us as well as to them” (Heb. 4:2, NKJV)?`
The early Christian community accepted God’s prior revelation (what we call the “Old Testament”) and believed that Jesus Christ was the Lamb of God, the Sacrifice for their sins. And by faith in the Sacrifice, they could experience salvation in Jesus and the rest that we are offered in Him.
`How can an understanding of what it means to be saved by the blood of Jesus help us enter into the kind of rest that we can have in Jesus, knowing that we are saved by grace and not by works?`
---
#### Additional Reading: Selected Quotes from Ellen G. White
There remaineth therefore a rest to the people of God. For he that is entered into his rest, he also hath ceased from his own works, as God [did] from his. Let us labour therefore to enter into that rest, lest any man fall after the same example of unbelief. [Hebrews 4:9–11].
The rest here spoken of is the rest of grace, obtained by following the prescription, Labor diligently. Those who learn of Jesus His meekness and lowliness find rest in the experience of practicing His lessons. It is not in indolence, in selfish ease and pleasure-seeking, that rest is obtained. Those who are unwilling to give the Lord faithful, earnest, loving service will not find spiritual rest in this life or in the life to come. Only from earnest labor comes peace and joy in the Holy Spirit—happiness on earth and glory hereafter.—Ellen G. White Comments, in _The SDA Bible Commentary_, vol. 7, p. 928.
Rest is found when all self-justification, all reasoning from a selfish standpoint, is put away. Entire self-surrender, an acceptance of His ways, is the secret of perfect rest in His love. Do just what He has told you to do, and be assured that God will do all that He has said He would do. Have you come to Him, renouncing all your makeshifts, all your unbelief, all your self-righteousness? Come just as you are, weak, helpless, and ready to die.
What is the “rest” promised?—It is the consciousness that God is true, that He never disappoints the one who comes to Him. His pardon is full and free, and His acceptance means rest to the soul, rest in His love.—_Our High Calling_, p. 97.
We shall be saved eternally when we enter in through the gates into the city. Then we may rejoice that we are saved, eternally saved. But until then we need to heed the injunction of the apostle, and to “fear, lest, a promise being left us of entering into his rest, any of us should seem to come short of it” (Hebrews 4:1). Having a knowledge of Canaan, singing the songs of Canaan, rejoicing in the prospect of entering into Canaan, did not bring the children of Israel into the vineyards and olive groves of the Promised Land. They could make it theirs in truth only by occupation, by complying with the conditions, by exercising living faith in God, by appropriating His promises to themselves.
Christ is the author and finisher of our faith, and when we yield to His hand we shall steadily grow in grace and in the knowledge of our Lord and Saviour. We shall make progress until we reach the full stature of men and women in Christ. Faith works by love, and purifies the soul, expelling the love of sin that leads to rebellion against, and transgression of, the law of God.—_That I May Know Him_, p. 162. | Java |
using System;
using System.Net;
using Microsoft.Extensions.Logging;
namespace CakesNoteProxy
{
public static class NoteProxyConfigure
{
public static ILoggerFactory LoggerFactory;
public static class NoteApi
{
public static string SiteFqdn { get; private set; }
public static string UserId { get; private set; }
public static bool IsIntro { get; private set; }
static NoteApi()
{
SiteFqdn = "https://note.mu";
UserId = "info";
IsIntro = true;
}
public static void SetGlobal(string noteSiteFqdn)
{
if ( noteSiteFqdn!=null)
SiteFqdn = noteSiteFqdn;
}
public static void SetMyNote(string noteUserId, bool isIntro)
{
if (noteUserId != null)
UserId = noteUserId;
IsIntro = isIntro;
}
public static readonly string ApiRoot = "/api/v1";
}
public static class NoteCache
{
public static int CachedItemsCountHardLimit = 50;
public static TimeSpan MonitoringThreadInterval = TimeSpan.FromSeconds(12);
public static TimeSpan CacheLifecycleTimeSpan = TimeSpan.FromSeconds(720);
public static double CacheLifecycleSpeculativeExecutionRate = 0.8;
}
}
}
| Java |
module HealthSeven::V2_5
class Rq1 < ::HealthSeven::Segment
# Anticipated Price
attribute :anticipated_price, St, position: "RQ1.1"
# Manufacturer Identifier
attribute :manufacturer_identifier, Ce, position: "RQ1.2"
# Manufacturer's Catalog
attribute :manufacturer_s_catalog, St, position: "RQ1.3"
# Vendor ID
attribute :vendor_id, Ce, position: "RQ1.4"
# Vendor Catalog
attribute :vendor_catalog, St, position: "RQ1.5"
# Taxable
attribute :taxable, Id, position: "RQ1.6"
# Substitute Allowed
attribute :substitute_allowed, Id, position: "RQ1.7"
end
end | Java |
using System;
using Lunt.IO;
namespace Lunt
{
/// <summary>
/// Represent a dependency to an asset.
/// </summary>
public sealed class AssetDependency
{
private readonly FilePath _path;
private readonly long _fileSize;
private readonly string _checksum;
/// <summary>
/// Gets the path of the dependency.
/// </summary>
/// <value>The path of the dependency.</value>
public FilePath Path
{
get { return _path; }
}
/// <summary>
/// Gets the file size of the dependency.
/// </summary>
/// <value>The file size of the dependency.</value>
public long FileSize
{
get { return _fileSize; }
}
/// <summary>
/// Gets the checksum of the dependency.
/// </summary>
/// <value>The checksum of the dependency.</value>
public string Checksum
{
get { return _checksum; }
}
/// <summary>
/// Initializes a new instance of the <see cref="AssetDependency" /> class.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="fileSize">The file size.</param>
/// <param name="checksum">The checksum.</param>
public AssetDependency(FilePath path, long fileSize, string checksum)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
if (checksum == null)
{
throw new ArgumentNullException("checksum");
}
_path = path;
_fileSize = fileSize;
_checksum = checksum;
}
}
} | Java |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "liste.h"
#include "atl.h"
#include "es.h"
#define FILE_ATLETI "atleti.txt"
#define FILE_ESERCIZI "esercizi.txt"
#define MAX_NOME 25
#define LUNG_CODICE 5
#define non_strutturato ;;
#ifdef _WIN32
#define F_CLEAR "cls"
#else
#define F_CLEAR "clear"
#endif
Atleta inputCercaAtleta(Lista);
void makeDotTxt(char*, char*);
FILE *inputStampaSuFile();
int main() {
FILE *fp, *fEs;
Atleta tmpAtl=newAtleta();
Lista atleti=newAtlCollection();
tabellaEs esercizi=newEsCollection();
char uInput[100], fileTxt[10];
char codice[LUNG_CODICE+1], nome[MAX_NOME+1], cognome[MAX_NOME+1];
char categoria[MAX_NOME+1], data[11];
int scelta=-1;
int x,y;
// file ESERCIZI
if ((fp=fopen(FILE_ESERCIZI, "r"))==NULL){
printf("Errore! Impossibile aprire il file \"%s\"!\n", FILE_ESERCIZI);
exit(1);
}
caricaEsercizi(esercizi, fp);
fclose(fp);
// -------------------------------------------------------------------------
// file degli ATLETI (riciclo fp)
if ((fp=fopen(FILE_ATLETI, "r"))==NULL){
printf("Errore! Impossibile aprire il file \"%s\"!\n", FILE_ATLETI);
exit(1);
}
caricaAtleti(atleti, fp);
fclose(fp);
// menu'
for(non_strutturato) {
system(F_CLEAR);
puts("01. Stampa contenuto anagrafica");
puts("02. Stampa gli atleti divisi per categoria");
puts("03. Aggiornamento monte ore settimanali");
puts("04. Ricerca atleta per codice o cognome parziale");
puts("05. Aggiungi un atleta");
puts("06. Cancella un atleta");
for (x=80; x-->0; printf("-")); puts(""); // linea orizzontale
puts("07. Caricare / salvare esercizi di un atleta");
puts("08. Modificare set / ripetizioni di un esercizio di un atleta");
puts("09. Aggiungi un esercizio");
puts("10. Cancella un esercizio");
for (x=80; x-->0; printf("-")); puts("");
puts("0. Esci");
puts("");
printf("> ");
scanf("%d", &scelta);
switch (scelta) {
case 0:
return 0;
case 1: // stampa contetnuto anagrafica
fp=inputStampaSuFile();
stampaAnagrafica(atleti, fp);
if (fp!=stdout) fclose(fp);
break;
case 2: // stamapa divisi per categoria
stampaPerCategoria(atleti);
break;
case 3: // aggiornamento monte ore settimanli
if ((tmpAtl=inputCercaAtleta(atleti))==NULL) break;
printf("Monte ore attuali: %d\n", getOreAtleta(tmpAtl));
printf("Nuovo monte ore: ");
scanf("%d", &x);
modificaOreAtl(tmpAtl, x);
puts("Monte ore aggiornato correttamente!");
break;
case 4: // ricerca atleta
inputCercaAtleta(atleti);
break;
case 5: // aggiungi atleta
printf("Codice: ");
scanf("%s", codice);
printf("Nome: ");
scanf("%s", nome);
printf("Cognome: ");
scanf("%s", cognome);
printf("Cateogria: ");
scanf("%s", categoria);
printf("Data : ");
scanf("%s", data);
printf("Monte ore: ");
scanf("%d", &x);
aggiungiAtletaByPar(atleti, codice, nome, cognome, categoria, data, x);
puts("Atleta aggiunto correttamente!");
break;
case 6: // cancellazione atleta
if ((tmpAtl=inputCercaAtleta(atleti))==NULL) break;
printf("Rimuovere l'atleta trovato? [s/n] ");
scanf("%s", uInput);
if (tolower(uInput[0])=='s') {
cancellaAtleta(atleti, tmpAtl);
puts("Atleta cancellato con successo!");
}
break;
case 7:
// caricare / salvare esericizi per un atleta
if ((tmpAtl=inputCercaAtleta(atleti))==NULL) break;
if (eserciziCaricatiAtl(tmpAtl)) {
// se gli esercizi sono già stati caricati
fp=inputStampaSuFile();
stampaTuttiEs(getListaEsercizi(tmpAtl), fp);
break;
}
//else: cerco di caricare il piano esercizi per l'altleta
makeDotTxt(fileTxt, getCodiceAtleta(tmpAtl));
if ((fEs=fopen(fileTxt, "r"))!=NULL) {
// se ho trovato un file con il codice dell'atleta...
caricaPianoEsercizi(getListaEsercizi(tmpAtl), esercizi, fEs);
puts("Piano degli esercizi caricato correttamente");
fclose(fEs);
} else {
printf("Non ho trovato un piano esercizi per %s\n",
getCodiceAtleta(tmpAtl));
}
break;
case 8:
// modificare il numero di set/ripetizioni
if ((tmpAtl=inputCercaAtleta(atleti))==NULL) break;
if (!eserciziCaricatiAtl(tmpAtl)){
printf("Esercizi non caricati per \"%s\"", getCodiceAtleta(tmpAtl));
break;
}
// se gli esercizi sono già stati caricati
printf("Nome dell'esercizio per modificare set/ripetizioni: ");
scanf("%s", uInput);
printf("Nuovo n* set: "); scanf("%d", &x);
printf("Nuovo n* ripetizioni: "); scanf("%d", &y);
if(modificaPianoEsByName(getListaEsercizi(tmpAtl), uInput, x, y)){
puts("Modifiche effettuate con successo!");
} else {
puts("Errore! Esercizio non trovato.");
}
break;
case 9:
// aggiunta di un esercizio
// ho bisogno sia dei set/ripetizioni da mettere nella lista, sia
// dell'esercizio da far pountare quindi del nome, della
// categoria e del tipo di esercizio
if ((tmpAtl=inputCercaAtleta(atleti))==NULL) break;
printf("Nome dell'esercizio da aggiungere: ");
scanf("%s", uInput);
printf("Nuovo n* set: "); scanf("%d", &x);
printf("Nuovo n* ripetizioni: "); scanf("%d", &y);
if(aggiungiEs(getListaEsercizi(tmpAtl), esercizi, uInput, x, y)) {
puts("Esercizio aggiunto con successo!");
} else {
printf("Impossibile trovare l'esercizio \"%s\"!\n", uInput);
}
break;
case 10:
// cancellazione di un esercizio
if ((tmpAtl=inputCercaAtleta(atleti))==NULL) break;
if (!eserciziCaricatiAtl(tmpAtl)){
printf("Esercizi non caricati per \"%s\"", getCodiceAtleta(tmpAtl));
break;
}
// se gli esercizi sono già stati caricati
printf("Nome dell'esercizio da cancellare: ");
scanf("%s", uInput);
// scorro tutti gli elementi della lista con p=head della lista
if (cancellaPianoEsByName(getListaEsercizi(tmpAtl), uInput))
puts("Esercizio cancellato con successo!");
else
puts("Errore! Esercizio non trovato!");
break;
default:
puts("Comando non trovato.");
}
getc(stdin); // prendo il ritorno a capo della scanf
printf("\nPremere invio per tornare al menu'... ");
getc(stdin); // aspetto che l'utente prema invio
}
return 0;
}
Atleta inputCercaAtleta(Lista l) {
char c[MAX_NOME+1];
Atleta atl;
printf("Codice o cognome parziale dell'atleta: ");
scanf("%s", c);
if ((atl=cercaAtleta(l, c))!=NULL) {
stampaAtleta(atl, stdout);
return atl;
} else {
puts("Atleta non trovato");
return NULL;
}
}
FILE *inputStampaSuFile() {
FILE *fp;
char c[3], f[100];
printf("Stampa su file? [s/n] ");
scanf("%s", c);
if (tolower(c[0])=='s') {
printf("Inserisci il nome del file: ");
scanf("%s", f);
if ((fp=fopen(f, "w"))==NULL) {
printf("Errore! Impossibile aprire il file \"%s\"", f);
printf("Stampo a video...\n");
return stdout;
} else {
return fp;
}
} else {
return stdout;
}
}
void makeDotTxt(char *dst, char *src) {
strcpy(dst, src);
strcat(dst, ".txt");
}
| Java |
#include "ofQuickTimeGrabber.h"
#include "ofUtils.h"
#if !defined(TARGET_LINUX) && !defined(MAC_OS_X_VERSION_10_7)
//---------------------------------
#ifdef OF_VIDEO_CAPTURE_QUICKTIME
//---------------------------------
//--------------------------------------------------------------
static ComponentResult frameIsGrabbedProc(SGChannel sgChan, short nBufferNum, Boolean *pbDone, long lRefCon);
static ComponentResult frameIsGrabbedProc(SGChannel sgChan, short nBufferNum, Boolean *pbDone, long lRefCon){
ComponentResult err = SGGrabFrameComplete( sgChan, nBufferNum, pbDone );
bool * havePixChanged = (bool *)lRefCon;
*havePixChanged = true;
return err;
}
//---------------------------------
#endif
//---------------------------------
//--------------------------------------------------------------------
ofQuickTimeGrabber::ofQuickTimeGrabber(){
//---------------------------------
#ifdef OF_VIDEO_CAPTURE_QUICKTIME
//---------------------------------
initializeQuicktime();
bSgInited = false;
gSeqGrabber = nullptr;
offscreenGWorldPixels = nullptr;
//---------------------------------
#endif
//---------------------------------
// common
bIsFrameNew = false;
bVerbose = false;
bGrabberInited = false;
bChooseDevice = false;
deviceID = 0;
//width = 320; // default setting
//height = 240; // default setting
//pixels = nullptr;
attemptFramerate = -1;
}
//--------------------------------------------------------------------
ofQuickTimeGrabber::~ofQuickTimeGrabber(){
close();
//---------------------------------
#ifdef OF_VIDEO_CAPTURE_QUICKTIME
//---------------------------------
if (offscreenGWorldPixels != nullptr){
delete[] offscreenGWorldPixels;
offscreenGWorldPixels = nullptr;
}
//---------------------------------
#endif
//---------------------------------
}
//--------------------------------------------------------------------
void ofQuickTimeGrabber::setVerbose(bool bTalkToMe){
bVerbose = bTalkToMe;
}
//--------------------------------------------------------------------
void ofQuickTimeGrabber::setDeviceID(int _deviceID){
deviceID = _deviceID;
bChooseDevice = true;
}
//--------------------------------------------------------------------
void ofQuickTimeGrabber::setDesiredFrameRate(int framerate){
attemptFramerate = framerate;
}
//---------------------------------------------------------------------------
bool ofQuickTimeGrabber::setPixelFormat(ofPixelFormat pixelFormat){
//note as we only support RGB we are just confirming that this pixel format is supported
if( pixelFormat == OF_PIXELS_RGB ){
return true;
}
ofLogWarning("ofQuickTimeGrabber") << "setPixelFormat(): requested pixel format " << pixelFormat << " not supported";
return false;
}
//---------------------------------------------------------------------------
ofPixelFormat ofQuickTimeGrabber::getPixelFormat() const {
//note if you support more than one pixel format you will need to return a ofPixelFormat variable.
return OF_PIXELS_RGB;
}
//--------------------------------------------------------------------
bool ofQuickTimeGrabber::setup(int w, int h){
//---------------------------------
#ifdef OF_VIDEO_CAPTURE_QUICKTIME
//---------------------------------
//---------------------------------- 1 - open the sequence grabber
if( !qtInitSeqGrabber() ){
ofLogError("ofQuickTimeGrabber") << "initGrabber(): unable to initialize the seq grabber";
return false;
}
//---------------------------------- 2 - set the dimensions
//width = w;
//height = h;
MacSetRect(&videoRect, 0, 0, w, h);
//---------------------------------- 3 - buffer allocation
// Create a buffer big enough to hold the video data,
// make sure the pointer is 32-byte aligned.
// also the rgb image that people will grab
offscreenGWorldPixels = (unsigned char*)malloc(4 * w * h + 32);
pixels.allocate(w, h, OF_IMAGE_COLOR);
#if defined(TARGET_OSX) && defined(__BIG_ENDIAN__)
QTNewGWorldFromPtr (&(videogworld), k32ARGBPixelFormat, &(videoRect), nullptr, nullptr, 0, (offscreenGWorldPixels), 4 * w);
#else
QTNewGWorldFromPtr (&(videogworld), k24RGBPixelFormat, &(videoRect), nullptr, nullptr, 0, (pixels.getPixels()), 3 * w);
#endif
LockPixels(GetGWorldPixMap(videogworld));
SetGWorld (videogworld, nullptr);
SGSetGWorld(gSeqGrabber, videogworld, nil);
//---------------------------------- 4 - device selection
bool didWeChooseADevice = bChooseDevice;
bool deviceIsSelected = false;
//if we have a device selected then try first to setup
//that device
if(didWeChooseADevice){
deviceIsSelected = qtSelectDevice(deviceID, true);
if(!deviceIsSelected && bVerbose)
ofLogError("ofQuickTimeGrabber") << "initGrabber(): unable to open device[" << deviceID << "], will attempt other devices";
}
//if we couldn't select our required device
//or we aren't specifiying a device to setup
//then lets try to setup ANY device!
if(deviceIsSelected == false){
//lets list available devices
listDevices();
setDeviceID(0);
deviceIsSelected = qtSelectDevice(deviceID, false);
}
//if we still haven't been able to setup a device
//we should error and stop!
if( deviceIsSelected == false){
goto bail;
}
//---------------------------------- 5 - final initialization steps
OSStatus err;
err = SGSetChannelUsage(gVideoChannel,seqGrabPreview);
if ( err != noErr ) goto bail;
//----------------- callback method for notifying new frame
err = SGSetChannelRefCon(gVideoChannel, (long)&bHavePixelsChanged );
if(!err) {
VideoBottles vb;
/* get the current bottlenecks */
vb.procCount = 9;
err = SGGetVideoBottlenecks(gVideoChannel, &vb);
if (!err) {
myGrabCompleteProc = NewSGGrabCompleteBottleUPP(frameIsGrabbedProc);
vb.grabCompleteProc = myGrabCompleteProc;
/* add our GrabFrameComplete function */
err = SGSetVideoBottlenecks(gVideoChannel, &vb);
}
}
err = SGSetChannelBounds(gVideoChannel, &videoRect);
if ( err != noErr ) goto bail;
err = SGPrepare(gSeqGrabber, true, false); //theo swapped so preview is true and capture is false
if ( err != noErr ) goto bail;
err = SGStartPreview(gSeqGrabber);
if ( err != noErr ) goto bail;
bGrabberInited = true;
loadSettings();
if( attemptFramerate >= 0 ){
err = SGSetFrameRate(gVideoChannel, IntToFixed(attemptFramerate) );
if ( err != noErr ){
ofLogError("ofQuickTimeGrabber") << "initGrabber: couldn't setting framerate to " << attemptFramerate << ": OSStatus " << err;
}
}
ofLogNotice("ofQuickTimeGrabber") << " inited grabbed ";
ofLogNotice("ofQuickTimeGrabber") << "-------------------------------------";
// we are done
return true;
//--------------------- (bail) something's wrong -----
bail:
ofLogError("ofQuickTimeGrabber") << "***** ofQuickTimeGrabber error *****";
ofLogError("ofQuickTimeGrabber") << "------------------------------------";
//if we don't close this - it messes up the next device!
if(bSgInited) qtCloseSeqGrabber();
bGrabberInited = false;
return false;
//---------------------------------
#else
//---------------------------------
return false;
//---------------------------------
#endif
//---------------------------------
}
//--------------------------------------------------------------------
bool ofQuickTimeGrabber::isInitialized() const{
return bGrabberInited;
}
//--------------------------------------------------------------------
vector<ofVideoDevice> ofQuickTimeGrabber::listDevices() const{
vector <ofVideoDevice> devices;
//---------------------------------
#ifdef OF_VIDEO_CAPTURE_QUICKTIME
//---------------------------------
bool bNeedToInitGrabberFirst = false;
if (!bSgInited) bNeedToInitGrabberFirst = true;
//if we need to initialize the grabbing component then do it
if( bNeedToInitGrabberFirst ){
if( !qtInitSeqGrabber() ){
return devices;
}
}
ofLogNotice("ofQuickTimeGrabber") << "-------------------------------------";
/*
//input selection stuff (ie multiple webcams)
//from http://developer.apple.com/samplecode/SGDevices/listing13.html
//and originally http://lists.apple.com/archives/QuickTime-API/2008/Jan/msg00178.html
*/
SGDeviceList deviceList;
SGGetChannelDeviceList (gVideoChannel, sgDeviceListIncludeInputs, &deviceList);
unsigned char pascalName[64];
unsigned char pascalNameInput[64];
//this is our new way of enumerating devices
//quicktime can have multiple capture 'inputs' on the same capture 'device'
//ie the USB Video Class Video 'device' - can have multiple usb webcams attached on what QT calls 'inputs'
//The isight for example will show up as:
//USB Video Class Video - Built-in iSight ('input' 1 of the USB Video Class Video 'device')
//Where as another webcam also plugged whill show up as
//USB Video Class Video - Philips SPC 1000NC Webcam ('input' 2 of the USB Video Class Video 'device')
//this means our the device ID we use for selection has to count both capture 'devices' and their 'inputs'
//this needs to be the same in our init grabber method so that we select the device we ask for
int deviceCount = 0;
ofLogNotice("ofQuickTimeGrabber") << "listing available capture devices";
for(int i = 0 ; i < (*deviceList)->count ; ++i)
{
SGDeviceName nameRec;
nameRec = (*deviceList)->entry[i];
SGDeviceInputList deviceInputList = nameRec.inputs;
int numInputs = 0;
if( deviceInputList ) numInputs = ((*deviceInputList)->count);
memcpy(pascalName, (*deviceList)->entry[i].name, sizeof(char) * 64);
//this means we can use the capture method
if(nameRec.flags != sgDeviceNameFlagDeviceUnavailable){
//if we have a capture 'device' (qt's word not mine - I would prefer 'system' ) that is ready to be used
//we go through its inputs to list all physical devices - as there could be more than one!
for(int j = 0; j < numInputs; j++){
//if our 'device' has inputs we get their names here
if( deviceInputList ){
SGDeviceInputName inputNameRec = (*deviceInputList)->entry[j];
memcpy(pascalNameInput, inputNameRec.name, sizeof(char) * 64);
}
ofLogNotice() << "device [" << deviceCount << "] " << p2cstr(pascalName) << " - " << p2cstr(pascalNameInput);
ofVideoDevice vd;
vd.id = deviceCount;
vd.deviceName = p2cstr(pascalName);
vd.bAvailable = true;
devices.push_back(vd);
//we count this way as we need to be able to distinguish multiple inputs as devices
deviceCount++;
}
}else{
ofLogNotice("ofQuickTimeGrabber") << "(unavailable) device [" << deviceCount << "] " << p2cstr(pascalName);
ofVideoDevice vd;
vd.id = deviceCount;
vd.deviceName = p2cstr(pascalName);
vd.bAvailable = false;
devices.push_back(vd);
deviceCount++;
}
}
ofLogNotice("ofQuickTimeGrabber") << "-------------------------------------";
//if we initialized the grabbing component then close it
if( bNeedToInitGrabberFirst ){
qtCloseSeqGrabber();
}
//---------------------------------
#endif
//---------------------------------
return devices;
}
//--------------------------------------------------------------------
void ofQuickTimeGrabber::update(){
//---------------------------------
#ifdef OF_VIDEO_CAPTURE_QUICKTIME
//---------------------------------
if (bGrabberInited == true){
SGIdle(gSeqGrabber);
// set the top pixel alpha = 0, so we can know if it
// was a new frame or not..
// or else we will process way more than necessary
// (ie opengl is running at 60fps +, capture at 30fps)
if (bHavePixelsChanged){
#if defined(TARGET_OSX) && defined(__BIG_ENDIAN__)
convertPixels(offscreenGWorldPixels, pixels.getPixels(), width, height);
#endif
}
}
// newness test for quicktime:
if (bGrabberInited == true){
bIsFrameNew = false;
if (bHavePixelsChanged == true){
bIsFrameNew = true;
bHavePixelsChanged = false;
}
}
//---------------------------------
#endif
//---------------------------------
}
//---------------------------------------------------------------------------
ofPixels& ofQuickTimeGrabber::getPixels(){
return pixels;
}
//---------------------------------------------------------------------------
const ofPixels& ofQuickTimeGrabber::getPixels() const {
return pixels;
}
//---------------------------------------------------------------------------
bool ofQuickTimeGrabber::isFrameNew() const {
return bIsFrameNew;
}
//--------------------------------------------------------------------
float ofQuickTimeGrabber::getWidth() const {
return pixels.getWidth();
}
//--------------------------------------------------------------------
float ofQuickTimeGrabber::getHeight() const {
return pixels.getHeight();
}
//--------------------------------------------------------------------
void ofQuickTimeGrabber::clearMemory(){
pixels.clear();
}
//--------------------------------------------------------------------
void ofQuickTimeGrabber::close(){
//---------------------------------
#ifdef OF_VIDEO_CAPTURE_QUICKTIME
//---------------------------------
qtCloseSeqGrabber();
DisposeSGGrabCompleteBottleUPP(myGrabCompleteProc);
//---------------------------------
#endif
//---------------------------------
clearMemory();
}
//--------------------------------------------------------------------
void ofQuickTimeGrabber::videoSettings(void){
//---------------------------------
#ifdef OF_VIDEO_CAPTURE_QUICKTIME
//---------------------------------
Rect curBounds, curVideoRect;
ComponentResult err;
// Get our current state
err = SGGetChannelBounds (gVideoChannel, &curBounds);
if (err != noErr){
ofLogError("ofQuickTimeGrabber") << "videoSettings(): couldn't get get channel bounds: ComponentResult " << err;
return;
}
err = SGGetVideoRect (gVideoChannel, &curVideoRect);
if (err != noErr){
ofLogError("ofQuickTimeGrabber") << "videoSettings(): couldn't get video rect: ComponentResult " << err;
return;
}
// Pause
err = SGPause (gSeqGrabber, true);
if (err != noErr){
ofLogError("ofQuickTimeGrabber") << "videoSettings(): couldn't set pause: ComponentResult " << err;
return;
}
#ifdef TARGET_OSX
//load any saved camera settings from file
loadSettings();
static SGModalFilterUPP gSeqGrabberModalFilterUPP = NewSGModalFilterUPP(SeqGrabberModalFilterUPP);
ComponentResult result = SGSettingsDialog(gSeqGrabber, gVideoChannel, 0, nil, 0, gSeqGrabberModalFilterUPP, nil);
if (result != noErr){
ofLogError("ofQuickTimeGrabber") << "videoSettings(): settings dialog error: ComponentResult " << err;
return;
}
//save any changed settings to file
saveSettings();
#else
SGSettingsDialog(gSeqGrabber, gVideoChannel, 0, nil, seqGrabSettingsPreviewOnly, nullptr, 0);
#endif
SGSetChannelBounds(gVideoChannel, &videoRect);
SGPause (gSeqGrabber, false);
//---------------------------------
#endif
//---------------------------------
}
//--------------------------------------------------------------------
#ifdef TARGET_OSX
//--------------------------------------------------------------------
//---------------------------------------------------------------------
bool ofQuickTimeGrabber::saveSettings(){
if (bGrabberInited != true) return false;
ComponentResult err;
UserData mySGVideoSettings = nullptr;
// get the SGChannel settings cofigured by the user
err = SGGetChannelSettings(gSeqGrabber, gVideoChannel, &mySGVideoSettings, 0);
if ( err != noErr ){
ofLogError("ofQuickTimeGrabber") << "saveSettings(): couldn't get camera settings: ComponentResult " << err;
return false;
}
string pref = "ofVideoSettings-"+deviceName;
CFStringRef cameraString = CFStringCreateWithCString(kCFAllocatorDefault,pref.c_str(),kCFStringEncodingMacRoman);
//get the settings using the key "ofVideoSettings-the name of the device"
SaveSettingsPreference( cameraString, mySGVideoSettings);
DisposeUserData(mySGVideoSettings);
return true;
}
//---------------------------------------------------------------------
bool ofQuickTimeGrabber::loadSettings(){
if (bGrabberInited != true || deviceName.length() == 0) return false;
ComponentResult err;
UserData mySGVideoSettings = nullptr;
// get the settings using the key "ofVideoSettings-the name of the device"
string pref = "ofVideoSettings-"+deviceName;
CFStringRef cameraString = CFStringCreateWithCString(kCFAllocatorDefault,pref.c_str(),kCFStringEncodingMacRoman);
GetSettingsPreference(cameraString, &mySGVideoSettings);
if (mySGVideoSettings){
Rect curBounds, curVideoRect;
//we need to make sure the dimensions don't get effected
//by our preferences
// Get our current state
err = SGGetChannelBounds (gVideoChannel, &curBounds);
if (err != noErr){
ofLogError("ofQuickTimeGrabber") << "loadSettings(): couldn't set channel bounds: ComponentResult " << err;
}
err = SGGetVideoRect (gVideoChannel, &curVideoRect);
if (err != noErr){
ofLogError("ofQuickTimeGrabber") << "loadSettings(): couldn't set video rect: ComponentResult " << err;
}
// use the saved settings preference to configure the SGChannel
err = SGSetChannelSettings(gSeqGrabber, gVideoChannel, mySGVideoSettings, 0);
if ( err != noErr ) {
ofLogError("ofQuickTimeGrabber") << "loadSettings(): couldn't set channel settings: ComponentResult " << err;
return false;
}
DisposeUserData(mySGVideoSettings);
// Pause
err = SGPause (gSeqGrabber, true);
if (err != noErr){
ofLogError("ofQuickTimeGrabber") << "loadSettings(): couldn't set pause: ComponentResult " << err;
}
SGSetChannelBounds(gVideoChannel, &videoRect);
SGPause (gSeqGrabber, false);
}else{
ofLogWarning("ofQuickTimeGrabber") << "loadSettings(): no camera settings to load";
return false;
}
return true;
}
//------------------------------------------------------
bool ofQuickTimeGrabber::qtInitSeqGrabber(){
if (bSgInited != true){
OSErr err = noErr;
ComponentDescription theDesc;
Component sgCompID;
// this crashes when we get to
// SGNewChannel
// we get -9405 as error code for the channel
// -----------------------------------------
// gSeqGrabber = OpenDefaultComponent(SeqGrabComponentType, 0);
// this seems to work instead (got it from hackTV)
// -----------------------------------------
theDesc.componentType = SeqGrabComponentType;
theDesc.componentSubType = nullptr;
theDesc.componentManufacturer = 'appl';
theDesc.componentFlags = nullptr;
theDesc.componentFlagsMask = nullptr;
sgCompID = FindNextComponent (nullptr, &theDesc);
// -----------------------------------------
if (sgCompID == nullptr){
ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): findNextComponent did not return a valid component";
return false;
}
gSeqGrabber = OpenComponent(sgCompID);
err = GetMoviesError();
if (gSeqGrabber == nullptr || err) {
ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): couldn't get default sequence grabber component: OSErr " << err;
return false;
}
err = SGInitialize(gSeqGrabber);
if (err != noErr) {
ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): can't initialize sequence grabber component: OSErr " << err;
return false;
}
err = SGSetDataRef(gSeqGrabber, 0, 0, seqGrabDontMakeMovie);
if (err != noErr) {
ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): can't set the destination data reference: OSErr " << err;
return false;
}
// windows crashes w/ out gworld, make a dummy for now...
// this took a long time to figure out.
err = SGSetGWorld(gSeqGrabber, 0, 0);
if (err != noErr) {
ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): setting up the gworld: OSErr " << err;
return false;
}
err = SGNewChannel(gSeqGrabber, VideoMediaType, &(gVideoChannel));
if (err != noErr) {
ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): couldn't create a new channel: OSErr " << err;
ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): check if you have any qt capable cameras attached";
return false;
}
bSgInited = true;
return true;
}
return false;
}
//--------------------------------------------------------------------
bool ofQuickTimeGrabber::qtCloseSeqGrabber(){
if (gSeqGrabber != nullptr){
SGStop (gSeqGrabber);
CloseComponent (gSeqGrabber);
gSeqGrabber = nullptr;
bSgInited = false;
return true;
}
return false;
}
//--------------------------------------------------------------------
bool ofQuickTimeGrabber::qtSelectDevice(int deviceNumber, bool didWeChooseADevice){
//note - check for memory freeing possibly needed for the all SGGetChannelDeviceList mac stuff
// also see notes in listDevices() regarding new enunemeration method.
//Generate a device list and enumerate
//all devices availble to the channel
SGDeviceList deviceList;
SGGetChannelDeviceList(gVideoChannel, sgDeviceListIncludeInputs, &deviceList);
unsigned char pascalName[64];
unsigned char pascalNameInput[64];
int numDevices = (*deviceList)->count;
if(numDevices == 0){
ofLogError("ofQuickTimeGrabber") << "no capture devices found";
return false;
}
int deviceCount = 0;
for(int i = 0 ; i < numDevices; ++i)
{
SGDeviceName nameRec;
nameRec = (*deviceList)->entry[i];
SGDeviceInputList deviceInputList = nameRec.inputs;
int numInputs = 0;
if( deviceInputList ) numInputs = ((*deviceInputList)->count);
memcpy(pascalName, (*deviceList)->entry[i].name, sizeof(char) * 64);
memset(pascalNameInput, 0, sizeof(char)*64);
//this means we can use the capture method
if(nameRec.flags != sgDeviceNameFlagDeviceUnavailable){
//if we have a capture 'device' (qt's word not mine - I would prefer 'system' ) that is ready to be used
//we go through its inputs to list all physical devices - as there could be more than one!
for(int j = 0; j < numInputs; j++){
//if our 'device' has inputs we get their names here
if( deviceInputList ){
SGDeviceInputName inputNameRec = (*deviceInputList)->entry[j];
memcpy(pascalNameInput, inputNameRec.name, sizeof(char) * 64);
}
//if the device number matches we try and setup the device
//if we didn't specifiy a device then we will try all devices till one works!
if( deviceCount == deviceNumber || !didWeChooseADevice ){
ofLogNotice("ofQuickTimeGrabber") << "attempting to open device [" << deviceCount << "] "
<< p2cstr(pascalName) << " - " << p2cstr(pascalNameInput);
OSErr err1 = SGSetChannelDevice(gVideoChannel, pascalName);
OSErr err2 = SGSetChannelDeviceInput(gVideoChannel, j);
int successLevel = 0;
//if there were no errors then we have opened the device without issue
if ( err1 == noErr && err2 == noErr){
successLevel = 2;
}
//parameter errors are not fatal so we will try and open but will caution the user
else if ( (err1 == paramErr || err1 == noErr) && (err2 == noErr || err2 == paramErr) ){
successLevel = 1;
}
//the device is opened!
if ( successLevel > 0 ){
deviceName = (char *)p2cstr(pascalName);
deviceName += "-";
deviceName += (char *)p2cstr(pascalNameInput);
if(successLevel == 2){
ofLogNotice("ofQuickTimeGrabber") << "device " << deviceName << " opened successfully";
}
else{
ofLogWarning("ofQuickTimeGrabber") << "device " << deviceName << " opened with some paramater errors, should be fine though!";
}
//no need to keep searching - return that we have opened a device!
return true;
}else{
//if we selected a device in particular but failed we want to go through the whole list again - starting from 0 and try any device.
//so we return false - and try one more time without a preference
if( didWeChooseADevice ){
ofLogWarning("ofQuickTimeGrabber") << "problems setting device [" << deviceNumber << "] "
<< p2cstr(pascalName) << " - " << p2cstr(pascalNameInput) << " *****";
return false;
}else{
ofLogWarning("ofQuickTimeGrabber") << "unable to open device, trying next device";
}
}
}
//we count this way as we need to be able to distinguish multiple inputs as devices
deviceCount++;
}
}else{
//ofLogError("ofQuickTimeGrabber") << "(unavailable) device [" << deviceCount << "] " << p2cstr(pascalName);
deviceCount++;
}
}
return false;
}
//---------------------------------
#endif
//---------------------------------
#endif
| Java |
# frozen_string_literal: true
require 'spec_helper'
describe 'logging' do
it "should have a logger" do
expect(Dummy).to respond_to(:logger)
end
it "should be able to log debug methods" do
expect(Dummy.logger).to respond_to(:debug)
end
it "should be settable" do
expect(Dummy).to respond_to(:logger=)
log = double
Dummy.logger = log
expect(Dummy.logger).to eq(log)
end
end
| Java |
//
// RepeatExpression.h
// iLogo
//
// Created by Yuhua Mai on 10/27/13.
// Copyright (c) 2013 Yuhua Mai. All rights reserved.
//
#import "ScopedExpression.h"
//#import "Expression.h"
@interface RepeatExpression : ScopedExpression
{
Expression *variableExpression;
NSMutableArray *commandExpression;
}
- (void)convert:(NSMutableArray*)commandList;
- (NSMutableArray*)evaluate:(TurtleCommand*)lastTurtleCommand;
@end
| Java |
// Copyright (c) 2015-2018 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.
#include "ofp/tablestatus.h"
#include "ofp/writable.h"
using namespace ofp;
bool TableStatus::validateInput(Validation *context) const {
size_t length = context->length();
if (length < sizeof(TableStatus) + sizeof(TableDesc)) {
log_debug("TableStatus too small", length);
return false;
}
size_t remainingLength = length - sizeof(TableStatus);
context->setLengthRemaining(remainingLength);
// FIXME: make sure there is only one table?
return table().validateInput(context);
}
UInt32 TableStatusBuilder::send(Writable *channel) {
UInt8 version = channel->version();
UInt32 xid = channel->nextXid();
UInt16 msgLen = UInt16_narrow_cast(sizeof(msg_) + table_.writeSize(channel));
msg_.header_.setVersion(version);
msg_.header_.setLength(msgLen);
msg_.header_.setXid(xid);
channel->write(&msg_, sizeof(msg_));
table_.write(channel);
channel->flush();
return xid;
}
| Java |
@charset "UTF-8";
/* MFG Labs iconset 1.0
-------------------------------------------------------
License
-------------------------------------------------------
• The MFG Labs iconset font is licensed under the SIL Open Font License - http://scripts.sil.org/OFL
• MFG Labs inconset CSS files are licensed under the MIT License -
http://opensource.org/licenses/mit-license.html
• The MFG Labs iconset pictograms are licensed under the CC BY 3.0 License - http://creativecommons.org/licenses/by/3.0/
• Attribution is no longer required in Font Awesome 3.0, but much appreciated:
MFG Labs inconset by MFG Labs
Contact
-------------------------------------------------------
Email: martin.charpentier@mfglabs.com
Twitter: http://twitter.com/mfg_labs
*/
@font-face {
font-family: 'mfg_labs_iconsetregular';
src: url("/fonts/mfglabs/mfglabsiconset-webfont.eot");
src: url("/fonts/mfglabs/mfglabsiconset-webfont.eot?#iefix") format("embedded-opentype"), url("/fonts/mfglabs/mfglabsiconset-webfont.woff") format("woff"), url("/fonts/mfglabs/mfglabsiconset-webfont.ttf") format("truetype"), url("/fonts/mfglabs/mfglabsiconset-webfont.svg#mfg_labs_iconsetregular") format("svg");
font-weight: normal;
font-style: normal; }
i, .icon {
font-family: 'mfg_labs_iconsetregular';
font-style: normal;
speak: none;
font-weight: normal;
font-size: 1em;
-webkit-font-smoothing: antialiased; }
.icon2x {
font-size: 2em; }
.icon3x {
font-size: 3em; }
/* style exemples */
.gradient {
color: #999;
text-shadow: 1px 1px 1px rgba(27, 27, 27, 0.19);
background-image: -webkit-gradient(linear, left top, left bottom, from(#b6b6b6), to(#3c3c3c));
background-clip: text;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
transition: all 0.1s ease-in-out; }
.gradient:hover, .gradient .current {
color: #eee;
text-shadow: 0px 0px 3px rgba(255, 255, 255, 0.25);
background-image: -webkit-gradient(linear, left top, left bottom, from(white), to(#bbbbbb)); }
/* MFG Labs iconset uses the Unicode Private Use Area (PUA) to ensure screen
readers do not read off random characters that represent icons.
We also use semantic unicode when they are available for the icon we provide. */
.icon-cloud:before {
content: "\2601"; }
.icon-at:before {
content: "\0040"; }
.icon-plus:before {
content: "\002B"; }
.icon-minus:before {
content: "\2212"; }
.icon-arrow_up:before {
content: "\2191"; }
.icon-arrow_down:before {
content: "\2193"; }
.icon-arrow_right:before {
content: "\2192"; }
.icon-arrow_left:before {
content: "\2190"; }
.icon-chevron_down:before {
content: "\f004"; }
.icon-chevron_up:before {
content: "\f005"; }
.icon-chevron_right:before {
content: "\f006"; }
.icon-chevron_left:before {
content: "\f007"; }
.icon-reorder:before {
content: "\f008"; }
.icon-list:before {
content: "\f009"; }
.icon-reorder_square:before {
content: "\f00a"; }
.icon-reorder_square_line:before {
content: "\f00b"; }
.icon-coverflow:before {
content: "\f00c"; }
.icon-coverflow_line:before {
content: "\f00d"; }
.icon-pause:before {
content: "\f00e"; }
.icon-play:before {
content: "\f00f"; }
.icon-step_forward:before {
content: "\f010"; }
.icon-step_backward:before {
content: "\f011"; }
.icon-fast_forward:before {
content: "\f012"; }
.icon-fast_backward:before {
content: "\f013"; }
.icon-cloud_upload:before {
content: "\f014"; }
.icon-cloud_download:before {
content: "\f015"; }
.icon-data_science:before {
content: "\f016"; }
.icon-data_science_black:before {
content: "\f017"; }
.icon-globe:before {
content: "\f018"; }
.icon-globe_black:before {
content: "\f019"; }
.icon-math_ico:before {
content: "\f01a"; }
.icon-math:before {
content: "\f01b"; }
.icon-math_black:before {
content: "\f01c"; }
.icon-paperplane_ico:before {
content: "\f01d"; }
.icon-paperplane:before {
content: "\f01e"; }
.icon-paperplane_black:before {
content: "\f01f"; }
/* \f020 doesn't work in Safari. all shifted one down */
.icon-color_balance:before {
content: "\f020"; }
.icon-star:before {
content: "\2605"; }
.icon-star_half:before {
content: "\f022"; }
.icon-star_empty:before {
content: "\2606"; }
.icon-star_half_empty:before {
content: "\f024"; }
.icon-reload:before {
content: "\f025"; }
.icon-heart:before {
content: "\2665"; }
.icon-heart_broken:before {
content: "\f028"; }
.icon-hashtag:before {
content: "\f029"; }
.icon-reply:before {
content: "\f02a"; }
.icon-retweet:before {
content: "\f02b"; }
.icon-signin:before {
content: "\f02c"; }
.icon-signout:before {
content: "\f02d"; }
.icon-download:before {
content: "\f02e"; }
.icon-upload:before {
content: "\f02f"; }
.icon-placepin:before {
content: "\f031"; }
.icon-display_screen:before {
content: "\f032"; }
.icon-tablet:before {
content: "\f033"; }
.icon-smartphone:before {
content: "\f034"; }
.icon-connected_object:before {
content: "\f035"; }
.icon-lock:before {
content: "\F512"; }
.icon-unlock:before {
content: "\F513"; }
.icon-camera:before {
content: "\F4F7"; }
.icon-isight:before {
content: "\f039"; }
.icon-video_camera:before {
content: "\f03a"; }
.icon-random:before {
content: "\f03b"; }
.icon-message:before {
content: "\F4AC"; }
.icon-discussion:before {
content: "\f03d"; }
.icon-calendar:before {
content: "\F4C5"; }
.icon-ringbell:before {
content: "\f03f"; }
.icon-movie:before {
content: "\f040"; }
.icon-mail:before {
content: "\2709"; }
.icon-pen:before {
content: "\270F"; }
.icon-settings:before {
content: "\9881"; }
.icon-measure:before {
content: "\f044"; }
.icon-vector:before {
content: "\f045"; }
.icon-vector_pen:before {
content: "\2712"; }
.icon-mute_on:before {
content: "\f047"; }
.icon-mute_off:before {
content: "\f048"; }
.icon-home:before {
content: "\2302"; }
.icon-sheet:before {
content: "\f04a"; }
.icon-arrow_big_right:before {
content: "\21C9"; }
.icon-arrow_big_left:before {
content: "\21C7"; }
.icon-arrow_big_down:before {
content: "\21CA"; }
.icon-arrow_big_up:before {
content: "\21C8"; }
.icon-dribbble_circle:before {
content: "\f04f"; }
.icon-dribbble:before {
content: "\f050"; }
.icon-facebook_circle:before {
content: "\f051"; }
.icon-facebook:before {
content: "\f052"; }
.icon-git_circle_alt:before {
content: "\f053"; }
.icon-git_circle:before {
content: "\f054"; }
.icon-git:before {
content: "\f055"; }
.icon-octopus:before {
content: "\f056"; }
.icon-twitter_circle:before {
content: "\f057"; }
.icon-twitter:before {
content: "\f058"; }
.icon-google_plus_circle:before {
content: "\f059"; }
.icon-google_plus:before {
content: "\f05a"; }
.icon-linked_in_circle:before {
content: "\f05b"; }
.icon-linked_in:before {
content: "\f05c"; }
.icon-instagram:before {
content: "\f05d"; }
.icon-instagram_circle:before {
content: "\f05e"; }
.icon-mfg_icon:before {
content: "\f05f"; }
.icon-xing:before {
content: "\F532"; }
.icon-xing_circle:before {
content: "\F533"; }
.icon-mfg_icon_circle:before {
content: "\f060"; }
.icon-user:before {
content: "\f061"; }
.icon-user_male:before {
content: "\f062"; }
.icon-user_female:before {
content: "\f063"; }
.icon-users:before {
content: "\f064"; }
.icon-file_open:before {
content: "\F4C2"; }
.icon-file_close:before {
content: "\f067"; }
.icon-file_alt:before {
content: "\f068"; }
.icon-file_close_alt:before {
content: "\f069"; }
.icon-attachment:before {
content: "\f06a"; }
.icon-check:before {
content: "\2713"; }
.icon-cross_mark:before {
content: "\274C"; }
.icon-cancel_circle:before {
content: "\F06E"; }
.icon-check_circle:before {
content: "\f06d"; }
.icon-magnifying:before {
content: "\F50D"; }
.icon-inbox:before {
content: "\f070"; }
.icon-clock:before {
content: "\23F2"; }
.icon-stopwatch:before {
content: "\23F1"; }
.icon-hourglass:before {
content: "\231B"; }
.icon-trophy:before {
content: "\f074"; }
.icon-unlock_alt:before {
content: "\F075"; }
.icon-lock_alt:before {
content: "\F510"; }
.icon-arrow_doubled_right:before {
content: "\21D2"; }
.icon-arrow_doubled_left:before {
content: "\21D0"; }
.icon-arrow_doubled_down:before {
content: "\21D3"; }
.icon-arrow_doubled_up:before {
content: "\21D1"; }
.icon-link:before {
content: "\f07B"; }
.icon-warning:before {
content: "\2757"; }
.icon-warning_alt:before {
content: "\2755"; }
.icon-magnifying_plus:before {
content: "\f07E"; }
.icon-magnifying_minus:before {
content: "\f07F"; }
.icon-white_question:before {
content: "\2754"; }
.icon-black_question:before {
content: "\2753"; }
.icon-stop:before {
content: "\f080"; }
.icon-share:before {
content: "\f081"; }
.icon-eye:before {
content: "\f082"; }
.icon-trash_can:before {
content: "\f083"; }
.icon-hard_drive:before {
content: "\f084"; }
.icon-information_black:before {
content: "\f085"; }
.icon-information_white:before {
content: "\f086"; }
.icon-printer:before {
content: "\f087"; }
.icon-letter:before {
content: "\f088"; }
.icon-soundcloud:before {
content: "\f089"; }
.icon-soundcloud_circle:before {
content: "\f08A"; }
.icon-anchor:before {
content: "\2693"; }
.icon-female_sign:before {
content: "\2640"; }
.icon-male_sign:before {
content: "\2642"; }
.icon-joystick:before {
content: "\F514"; }
.icon-high_voltage:before {
content: "\26A1"; }
.icon-fire:before {
content: "\F525"; }
.icon-newspaper:before {
content: "\F4F0"; }
.icon-chart:before {
content: "\F526"; }
.icon-spread:before {
content: "\F527"; }
.icon-spinner_1:before {
content: "\F528"; }
.icon-spinner_2:before {
content: "\F529"; }
.icon-chart_alt:before {
content: "\F530"; }
.icon-label:before {
content: "\F531"; }
.icon-brush:before {
content: "\E000"; }
.icon-refresh:before {
content: "\E001"; }
.icon-node:before {
content: "\E002"; }
.icon-node_2:before {
content: "\E003"; }
.icon-node_3:before {
content: "\E004"; }
.icon-link_2_nodes:before {
content: "\E005"; }
.icon-link_3_nodes:before {
content: "\E006"; }
.icon-link_loop_nodes:before {
content: "\E007"; }
.icon-node_size:before {
content: "\E008"; }
.icon-node_color:before {
content: "\E009"; }
.icon-layout_directed:before {
content: "\E010"; }
.icon-layout_radial:before {
content: "\E011"; }
.icon-layout_hierarchical:before {
content: "\E012"; }
.icon-node_link_direction:before {
content: "\E013"; }
.icon-node_link_short_path:before {
content: "\E014"; }
.icon-node_cluster:before {
content: "\E015"; }
.icon-display_graph:before {
content: "\E016"; }
.icon-node_link_weight:before {
content: "\E017"; }
.icon-more_node_links:before {
content: "\E018"; }
.icon-node_shape:before {
content: "\E00A"; }
.icon-node_icon:before {
content: "\E00B"; }
.icon-node_text:before {
content: "\E00C"; }
.icon-node_link_text:before {
content: "\E00D"; }
.icon-node_link_color:before {
content: "\E00E"; }
.icon-node_link_shape:before {
content: "\E00F"; }
.icon-credit_card:before {
content: "\F4B3"; }
.icon-disconnect:before {
content: "\F534"; }
.icon-graph:before {
content: "\F535"; }
.icon-new_user:before {
content: "\F536"; }
html {
font-size: 12pt;
font-family: 'PT Sans', Helvetica, Arial, sans-serif;
overflow-y: scroll; }
body {
padding: 0;
margin: 0; }
a {
color: #006DCE;
text-decoration: none;
border-bottom: 1px solid #006DCE; }
a.pseudo {
border-bottom-style: dashed; }
i.icon {
color: #006DCE;
cursor: pointer; }
i.icon.warning {
color: #C70000; }
a.pseudo.warning {
color: #C70000;
border-bottom-color: #C70000; }
button {
border: 1px solid #E8E8E8;
background: #FBFBFB;
border-radius: 7px;
padding: 10px 15px;
margin: 5px;
font-weight: bold;
color: #5F5F5F; }
button:disabled {
color: #5F5F5F; }
button.warning {
border: 1px solid #8C0000;
background: #CA0000;
color: white; }
input, textarea, .pseudo-input-text {
border-radius: 5px;
border: 1px solid #E8E8E8;
padding: 0.3rem 0.5rem;
font-size: 1rem; }
.arrow-up, .arrow-down, .arrow-right, .arrow-left {
width: 0;
height: 0;
border-width: 5px;
border-style: solid;
border-color: transparent; }
.arrow-up {
border-top: none;
border-bottom-color: black; }
.arrow-down {
border-top-color: black;
border-bottom: none; }
.arrow-right {
border-left-color: black;
border-right: none; }
.arrow-left {
border-right-color: black;
border-left: none; }
/****************/
.logo {
text-align: center;
padding: 3rem 3rem 3rem 3rem;
font-weight: bold;
font-size: 1.5rem; }
.logo__title__span {
padding: 1rem;
letter-spacing: 0.75rem;
background: #EEEFAA; }
.category-picker__category {
cursor: pointer;
padding: 0 5px; }
.category-picker__category__title {
display: inline; }
.category-picker__category__empty {
font-style: italic; }
.category-picker__category--selected .category-picker__category__title {
border-bottom: none;
color: inherit; }
.category-picker__category--selected .category-picker__category__empty {
background: #EEEFAA; }
.category-picker__category--selected {
background: #EEEFAA; }
.edit-expense {
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column; }
.edit-expense > table > tbody > tr > td {
vertical-align: top; }
.edit-expense__row {
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row; }
.edit-expense__row > table {
margin: 0 1rem; }
.edit-expense__field__label {
font-weight: bold; }
.edit-expense__field__input {
padding-bottom: 1rem; }
.edit-expense__category-picker-wrapper {
border: 1px solid #E8E8E8;
border-radius: 5px;
padding: 0; }
.edit-expense__category-picker-wrapper > .category-picker > .category-picker__category:first-child {
border-radius: 5px 5px 0 0; }
.edit-expense__category-picker-wrapper > .category-picker > .category-picker__category:last-child {
border-radius: 0 0 5px 5px; }
.edit-expense__controls {
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center; }
.edit-category-list__category__title {
display: inline;
font-weight: bold; }
.edit-category-list__category--selected .edit-category-list__category__title {
background: #EEEFAA;
border-bottom: none;
color: inherit; }
.edit-category-list__category__controls {
opacity: 0.075;
display: inline; }
.edit-category-list__category__content {
display: inline-block;
padding: 0.4rem 0.4rem; }
.edit-category-list__category:hover .edit-category-list__category__content {
background: #EEEFAA; }
.edit-category-list .edit-category-list__category:hover .edit-category-list__category__controls {
opacity: 1; }
.edit-category-list__children {
padding-left: 20px; }
.edit-category-list__empty {
font-style: italic; }
.edit-category-list__new-root-category {
margin: 1rem 0; }
.edit-category-list__new-root-category .edit-category-list__new-root-category__link.pseudo {
margin: 0; }
.edit-category-list a.pseudo {
font-size: 0.8rem;
margin: 0 0.8rem; }
.edit-category-list i.icon {
font-size: 0.8rem;
margin: 0 0.8rem; }
.modal-container {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.72);
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
z-index: 9999; }
.modal-container__column {
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column; }
.modal-container__column__cell {
background: white;
border-radius: 4px;
padding: 0.5rem; }
.modal-container__msg {
margin: 1rem; }
.modal-container__msg.warning {
color: #C70000; }
.modal-container__controls {
text-align: center;
margin: 1rem 0 0; }
.wait-indicator {
position: fixed;
top: 0;
left: 0;
background: orange;
width: 100%;
text-align: center;
font-size: 0.70rem;
color: white;
font-weight: bold;
opacity: 0.65;
padding: 0.25rem 0; }
.error-panel {
position: fixed;
top: 0;
left: 0;
background: #CE0000;
width: 100%;
text-align: center;
font-size: 0.70rem;
color: white;
font-weight: bold;
opacity: 0.75;
padding: 0.25rem 0;
z-index: 9999; }
.user-panel {
position: fixed;
top: 0;
right: 20px;
background: #EEEFAA;
text-align: center;
font-size: 0.70rem;
color: white;
font-weight: bold;
padding: 0.5rem 0.75rem; }
.tabs-container__labels {
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center; }
.tabs-container__labels__label {
padding: 0.5rem 1rem;
display: inline-block;
border-radius: 5px;
margin: 0 5px; }
.tabs-container__labels__label--active {
background: #EEEFAA; }
.tabs-container__content {
padding: 1rem;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center; }
.history {
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
/* Customize category picker for filters */ }
.history__title {
font-weight: bold;
margin: 1rem 0; }
.history__filters {
width: 200px;
padding: 0rem 0rem 0rem 1rem; }
.history__results {
width: 600px; }
.history__year-month-filter__year {
font-weight: bold;
margin: 0.5rem 0 0 0; }
.history__year-month-filter__month {
margin: 0.25rem 1rem; }
.history__year-month-filter__item--active span {
background: #EEEFAA; }
.history__current-filter {
margin: 1rem 0;
font-size: 0.75rem;
color: #999;
font-style: italic; }
.history__filters .category-picker__category {
margin: 0.1rem 0.3rem;
padding: 0.2rem;
cursor: pointer; }
.history__filters .category-picker__category__title {
display: inline;
border-bottom: 1px dashed #006DCE;
color: #006DCE; }
.history__filters .category-picker__category__empty {
font-style: italic; }
.history__filters .category-picker__category--selected .category-picker__category__title {
background: #EEEFAA;
border-bottom: none;
color: inherit; }
.history__filters .category-picker__children {
padding-left: 20px; }
.empty-history-msg {
margin: 1rem;
font-style: italic; }
.expense-list__group__title {
font-weight: bold;
margin: 1rem 0; }
.expense-list .expense-list__expense {
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
padding: 0 0 1rem 0; }
.expense-list .expense-list__expense__time {
margin: 0rem 1rem;
color: #ABABAB;
font-size: 0.5rem;
font-style: italic;
line-height: 1.5rem; }
.expense-list .expense-list__expense__amount {
font-style: italic;
font-weight: bold;
display: inline; }
.expense-list .expense-list__expense__desc1 {
font-size: 1rem;
display: inline; }
.expense-list .expense-list__expense__desc2 {
color: #ABABAB;
font-size: 0.75rem;
font-style: italic; }
.expense-list .expense-list__expense__controls {
visibility: hidden;
padding-left: 1rem; }
.expense-list .expense-list__expense__controls a.pseudo {
margin: 0 1rem;
font-size: 0.8rem; }
.expense-list .expense-list__expense:hover .expense-list__expense__controls {
visibility: visible; }
.confirm-dialog {
padding: 1rem; }
.confirm-dialog__msg {
font-weight: bold;
text-align: center; }
.confirm-dialog__controls {
text-align: center;
padding: 1rem 0.5rem 0rem 0.5rem; }
.confirm-dialog__controls > button {
margin: 0 0.25rem; }
.drop-down-container {
position: relative; }
.drop-down-container__bg {
position: fixed;
background: rgba(0, 0, 0, 0.25);
width: 100%;
height: 100%;
top: 0;
left: 0; }
.drop-down-container__body {
position: absolute;
z-index: 99999;
top: 0;
left: 0;
padding: 1rem;
border-radius: 4px;
background: white;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); }
.sum-table-statistics__year__month {
font-weight: bold;
padding: 0.8rem 0.8rem;
text-align: right; }
.sum-table-statistics__year__category {
font-style: italic;
padding: 0.25rem 0.8rem; }
.sum-table-statistics__year__value {
padding: 0.25rem 0.8rem;
white-space: nowrap;
text-align: right; }
.sum-table-statistics__year__value__dif {
font-size: 0.75rem; }
.sum-table-statistics__year__value__dif--plus {
color: red; }
.sum-table-statistics__year__value__dif--minus {
color: green; }
.sum-table-statistics__year__value__dif--zero {
color: #dedede; }
.sum-table-statistics__year__total__title {
font-style: italic;
font-weight: bold;
padding: 0.25rem 0.8rem 0.25rem 0; }
.sum-table-statistics__year__total__value {
padding: 0.25rem 0.8rem;
white-space: nowrap;
text-align: right;
font-weight: bold; }
.sum-table-statistics__year__total__dif {
font-size: 0.75rem; }
.sum-table-statistics__year__total__dif--plus {
color: red; }
.sum-table-statistics__year__total__dif--minus {
color: green; }
.sum-table-statistics__controls {
margin: 1rem 0; }
.unauthorized {
margin: auto 0; }
.unauthorized__caption {
font-size: 1.5rem;
text-align: center;
padding: 1rem; }
.unauthorized__button {
text-align: center; }
.unauthorized__button a {
border: 0; }
.date-time-picker .modal-container__column__cell {
padding: 0; }
.date-time-picker__modal-content {
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
-webkit-align-items: stretch;
-ms-flex-align: stretch;
align-items: stretch; }
.date-time-picker__modal-content__section {
border-bottom: 1px dashed #D6D6D6;
padding: 1rem;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center; }
.date-time-picker__modal-content__section:last-child {
border-bottom: none; }
.date-time-picker__modal-content__controls {
padding: 0.2rem; }
.date-time-picker .pseudo-input-text {
cursor: pointer; }
.date-picker {
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center; }
.date-picker__months__title {
font-weight: bold;
padding: 0 1rem; }
.date-picker__calendar {
margin: 0.75rem 0; }
.date-picker__calendar__header {
font-weight: bold; }
.date-picker__calendar__cell {
text-align: center;
padding: 0.2rem 0.3rem;
cursor: default; }
.date-picker__calendar__cell--active {
background: #EEEFAA; }
.date-picker__calendar__cell--another-month {
color: black;
opacity: 0.20; }
.date-picker__calendar__cell--weekend {
color: #DC0000; }
.time-picker {
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row; }
.time-picker__input {
font-size: 2rem;
width: 40px;
text-align: center;
border: none; }
.v-counter {
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
-webkit-align-items: stretch;
-ms-flex-align: stretch;
align-items: stretch;
margin: 0.2rem; }
.v-counter__middle {
border-left: 1px solid #E8E8E8;
border-right: 1px solid #E8E8E8;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row; }
.v-counter__button {
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
margin: 0;
outline: none; }
.v-counter__button--up {
border-radius: 5px 5px 0 0; }
.v-counter__button--down {
border-radius: 0 0 5px 5px; }
.h-counter {
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-align-items: stretch;
-ms-flex-align: stretch;
align-items: stretch;
margin: 0.2rem; }
.h-counter__middle {
border-bottom: 1px solid #E8E8E8;
border-top: 1px solid #E8E8E8;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column; }
.h-counter__button {
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
margin: 0;
outline: none; }
.h-counter__button--up {
border-radius: 0 5px 5px 0; }
.h-counter__button--down {
border-radius: 5px 0 0 5px; }
.h-counter__button--up, .h-counter__button--down {
padding: 6px 10px; }
| Java |
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Post It App</title>
<link rel="apple-touch-icon" sizes="57x57" href="/icon2015/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/icon2015/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/icon2015/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/icon2015/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/icon2015/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/icon2015/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/icon2015/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/icon2015/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/icon2015/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="/icon2015/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="/icon2015/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="/icon2015/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="/icon2015/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/icon2015/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<link rel="stylesheet" type="text/css" href="css/main.css"/>
<link rel="stylesheet" type="text/css" href="bower_components/font-awesome/css/font-awesome.css"/>
</head>
<body>
<div class="fullpage title imgbackground">
<div class="title-text">
Post IT app
<p>
Partner offer
</p>
</div>
<a href="#content" class="arrow-down arrow-animation"><i class="fa fa-arrow-down"></i></a>
</div>
<div id="content">
<div class="container">
<div class="row">
<div class="text-center" style="padding-bottom:5vh;">
<h1>Hi!</h1>
</div>
<div class="col-md-offset-2 col-md-8 text-center">
<p>
<b>Post IT app</b> has for aim to get youth interested in IT and to empower them in providing the
basic IT
concepts, <i>all without programming</i>.
</p>
<p>For the last two years, we have conducted a workshop for high school students, in which we teach them
how to create business models and paper prototypes of applications.
</p>
<p>One of our main objectives is to train tomorrow’s decision makers in the digital world.
</p>
<p> Our second main objective is to question the stereotypical image of IT: we want to show that IT is a
fun, challenging and creative field which can be explored regardless of gender, background,
personality traits of skills!
</p>
<p style="padding-top:1em; padding-bottom:0.5em;">
A part of:
</p>
<a href="http://gbgtechweek.com" style="margin-left:3em"><img src="img/Gbgtechweek_solid.png"></a>
</div>
</div>
</div>
</div>
<div class="onepage walker imgbackground" id="frågor">
<div class="container">
<div class="row">
<div class="col-md-offset-1 col-md-11" style="padding-bottom:4vh">
<h1 style="padding-bottom:3vh">
Packages
</h1>
</div>
<div class="col-md-offset-1 col-md-5" style="padding-bottom:4vh">
<h4 class="gloria">Bronze Partnership <br> 1000kr</h4>
<p>Small Logo in our video *</p>
<p>Small Logo and explanatory text as a sponsor on social media</p>
<p>Small Logo and name on our website *</p>
<p>Small Logo in presentation</p>
</div>
<div class="col-md-5" style="padding-bottom:4vh">
<h4 class="gloria">Silver Partnership <br> 3000kr</h4>
<p>
<small>Everything in partnership bronze +</small>
</p>
<p>Silver sponsor on our website</p>
<p>Logo and explanatory text as a sponsor on social media</p>
<p>Logo in our presentation and an expressed thanks</p>
</div>
</div>
<div class="row">
<div class="col-md-offset-1 col-md-5" style="padding-bottom:4vh">
<h4 class="gloria">Gold Partnership <br> 6000kr</h4>
<p>
<small>Everything in silver Partnership +</small>
</p>
<p>Big and clear thank you in the presentation</p>
<p>2 seconds video time with a large logo *</p>
<p>Slogans and medium sized logo on T-Shirts! *</p>
</div>
<div class="col-md-5" style="padding-bottom:4vh">
<h4 class="gloria">Platinum Partnership <br> 10000kr</h4>
<p>
<small>Everything in gold Partnership +</small>
</p>
<p> 4 second special video time with a large logo *</p>
<p>Very clear communication that you are a co-organizer who made all that extra cool possible!</p>
<p> The opportunity to pitch a whole minute!</p>
</div>
</div>
<div class="row">
<div class=" col-md-10" style="padding-bottom:4vh">
<p>* Video and Tshirt requires that we reach our financial target of 20 000 SEK.</p>
<p>PS: in the Silver, Gold and Platinum packages, we provide you with the possibility to distribute
advertising goodies to our students.</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="js/main.js"></script>
<script>
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-61692156-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
| Java |
#!/bin/sh
# CYBERWATCH SAS - 2017
#
# Security fix for USN-2950-5
#
# Security announcement date: 2016-05-25 00:00:00 UTC
# Script generation date: 2017-01-01 21:05:27 UTC
#
# Operating System: Ubuntu 14.04 LTS
# Architecture: x86_64
#
# Vulnerable packages fix on version:
# - samba:2:4.3.9+dfsg-0ubuntu0.14.04.3
#
# Last versions recommanded by security team:
# - samba:2:4.3.11+dfsg-0ubuntu0.14.04.4
#
# CVE List:
# - CVE-2015-5370
# - CVE-2016-2110
# - CVE-2016-2111
# - CVE-2016-2112
# - CVE-2016-2113
# - CVE-2016-2114
# - CVE-2016-2115
# - CVE-2016-2118
#
# More details:
# - https://www.cyberwatch.fr/vulnerabilites
#
# Licence: Released under The MIT License (MIT), See LICENSE FILE
sudo apt-get install --only-upgrade samba=2:4.3.11+dfsg-0ubuntu0.14.04.4 -y
| Java |
require 'delegate'
module Bizflow
module BusinessModel
class SimpleWrapper < SimpleDelegator
def self.wrap(item)
new item
end
def self.wraps(items)
res = items.map do |item|
new item
end
res
end
end
end
end | Java |
class Solution {
public int solution(int[] A) {
int[] temArray = new int[A.length + 2];
for (int i = 0; i < A.length; i++) {
temArray[A[i]] = 1;
}
for (int i = 1; i < temArray.length + 1; i++) {
if(temArray[i] == 0){
return i;
}
}
return A[A.length - 1] + 1;
}
}
| Java |
function EditMovieCtrl(MovieService,$stateParams) {
// ViewModel
const edit = this;
edit.title = 'Edit Movies' + $stateParams.id;
edit.back = function(){
window.history.back()
}
edit.checker = function(bool){
if(bool=='true')
return true;
if(bool=='false')
return false;
}
edit.click = function(bool,key){
edit.data[key] = !bool
}
MovieService.getID($stateParams.id).then(function(results){
if(results.status===404)
edit.data.movies='not found'
edit.data = results
})
// MovieService.get().then(function(results){
// edit.movies = results
// })
edit.processForm = function(){
MovieService.put(edit.data).then(function(res){
console.log(res)
})
}
}
EditMovieCtrl.$inject=['MovieService','$stateParams']
export default {
name: 'EditMovieCtrl',
fn: EditMovieCtrl
};
| Java |
# CGGameCircle
Marmalade Lua Binding for Game Circle
| Java |
/**
* @fileoverview Rule to require or disallow line breaks inside braces.
* @author Toru Nagashima
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
let astUtils = require("../ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
// Schema objects.
let OPTION_VALUE = {
oneOf: [
{
enum: ["always", "never"]
},
{
type: "object",
properties: {
multiline: {
type: "boolean"
},
minProperties: {
type: "integer",
minimum: 0
}
},
additionalProperties: false,
minProperties: 1
}
]
};
/**
* Normalizes a given option value.
*
* @param {string|Object|undefined} value - An option value to parse.
* @returns {{multiline: boolean, minProperties: number}} Normalized option object.
*/
function normalizeOptionValue(value) {
let multiline = false;
let minProperties = Number.POSITIVE_INFINITY;
if (value) {
if (value === "always") {
minProperties = 0;
} else if (value === "never") {
minProperties = Number.POSITIVE_INFINITY;
} else {
multiline = Boolean(value.multiline);
minProperties = value.minProperties || Number.POSITIVE_INFINITY;
}
} else {
multiline = true;
}
return {multiline: multiline, minProperties: minProperties};
}
/**
* Normalizes a given option value.
*
* @param {string|Object|undefined} options - An option value to parse.
* @returns {{ObjectExpression: {multiline: boolean, minProperties: number}, ObjectPattern: {multiline: boolean, minProperties: number}}} Normalized option object.
*/
function normalizeOptions(options) {
if (options && (options.ObjectExpression || options.ObjectPattern)) {
return {
ObjectExpression: normalizeOptionValue(options.ObjectExpression),
ObjectPattern: normalizeOptionValue(options.ObjectPattern)
};
}
let value = normalizeOptionValue(options);
return {ObjectExpression: value, ObjectPattern: value};
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "enforce consistent line breaks inside braces",
category: "Stylistic Issues",
recommended: false
},
fixable: "whitespace",
schema: [
{
oneOf: [
OPTION_VALUE,
{
type: "object",
properties: {
ObjectExpression: OPTION_VALUE,
ObjectPattern: OPTION_VALUE
},
additionalProperties: false,
minProperties: 1
}
]
}
]
},
create: function(context) {
let sourceCode = context.getSourceCode();
let normalizedOptions = normalizeOptions(context.options[0]);
/**
* Reports a given node if it violated this rule.
*
* @param {ASTNode} node - A node to check. This is an ObjectExpression node or an ObjectPattern node.
* @param {{multiline: boolean, minProperties: number}} options - An option object.
* @returns {void}
*/
function check(node) {
let options = normalizedOptions[node.type];
let openBrace = sourceCode.getFirstToken(node);
let closeBrace = sourceCode.getLastToken(node);
let first = sourceCode.getTokenOrCommentAfter(openBrace);
let last = sourceCode.getTokenOrCommentBefore(closeBrace);
let needsLinebreaks = (
node.properties.length >= options.minProperties ||
(
options.multiline &&
node.properties.length > 0 &&
first.loc.start.line !== last.loc.end.line
)
);
/*
* Use tokens or comments to check multiline or not.
* But use only tokens to check whether line breaks are needed.
* This allows:
* var obj = { // eslint-disable-line foo
* a: 1
* }
*/
first = sourceCode.getTokenAfter(openBrace);
last = sourceCode.getTokenBefore(closeBrace);
if (needsLinebreaks) {
if (astUtils.isTokenOnSameLine(openBrace, first)) {
context.report({
message: "Expected a line break after this opening brace.",
node: node,
loc: openBrace.loc.start,
fix: function(fixer) {
return fixer.insertTextAfter(openBrace, "\n");
}
});
}
if (astUtils.isTokenOnSameLine(last, closeBrace)) {
context.report({
message: "Expected a line break before this closing brace.",
node: node,
loc: closeBrace.loc.start,
fix: function(fixer) {
return fixer.insertTextBefore(closeBrace, "\n");
}
});
}
} else {
if (!astUtils.isTokenOnSameLine(openBrace, first)) {
context.report({
message: "Unexpected line break after this opening brace.",
node: node,
loc: openBrace.loc.start,
fix: function(fixer) {
return fixer.removeRange([
openBrace.range[1],
first.range[0]
]);
}
});
}
if (!astUtils.isTokenOnSameLine(last, closeBrace)) {
context.report({
message: "Unexpected line break before this closing brace.",
node: node,
loc: closeBrace.loc.start,
fix: function(fixer) {
return fixer.removeRange([
last.range[1],
closeBrace.range[0]
]);
}
});
}
}
}
return {
ObjectExpression: check,
ObjectPattern: check
};
}
};
| Java |
import random, math
import gimp_be
#from gimp_be.utils.quick import qL
from gimp_be.image.layer import editLayerMask
from effects import mirror
import numpy as np
import UndrawnTurtle as turtle
def brushSize(size=-1):
""""
Set brush size
"""
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if size < 1:
size = random.randrange(2, ((image.height + image.width) / 8))
gimp_be.pdb.gimp_context_set_brush_size(size)
# Set brush opacity
def brushOpacity(op=-1):
if op == -1:
op = random.randrange(15, 100)
gimp_be.pdb.gimp_brushes_set_opacity(op)
return op
# Set random brush color no parameters set random
def brushColor(r1=-1, g1=-1, b1=-1, r2=-1, g2=-1, b2=-1):
if not r1 == -1:
gimp_be.pdb.gimp_context_set_foreground((r1, g1, b1))
if not r2 == -1:
gimp_be.pdb.gimp_context_set_background((r2, g2, b2))
elif r1 == -1:
r1 = random.randrange(0, 255)
g1 = random.randrange(0, 255)
b1 = random.randrange(0, 255)
r2 = random.randrange(0, 255)
g2 = random.randrange(0, 255)
b2 = random.randrange(0, 255)
gimp_be.pdb.gimp_context_set_foreground((r1, g1, b1))
gimp_be.pdb.gimp_context_set_background((r2, g2, b2))
return (r1, g1, b1, r2, g2, b2)
#set gray scale color
def grayColor(gray_color):
gimp_be.pdb.gimp_context_set_foreground((gray_color, gray_color, gray_color))
# Set random brush
def randomBrush():
num_brushes, brush_list = gimp_be.pdb.gimp_brushes_get_list('')
brush_pick = brush_list[random.randrange(0, len(brush_list))]
gimp_be.pdb.gimp_brushes_set_brush(brush_pick)
return brush_pick
# Set random brush dynamics
def randomDynamics():
dynamics_pick = random.choice(gimp_be.pdb.gimp_dynamics_get_list('')[1])
gimp_be.pdb.gimp_context_set_dynamics(dynamics_pick)
return dynamics_pick
def qL():
# quick new layer
gimp_be.addNewLayer()
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
gimp_be.pdb.gimp_edit_fill(drawable, 1)
def drawLine(points):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
gimp_be.pdb.gimp_paintbrush_default(drawable, len(points), points)
def drawSpiral(n=140, angle=61, step=10, center=[]):
coord=[]
nt=turtle.Turtle()
if center == []:
image = gimp_be.gimp.image_list()[0]
center=[image.width/2,image.height/2]
for step in range(n):
coord.append(int(nt.position()[0]*10)+center[0])
coord.append(int(nt.position()[1]*10)+center[1])
nt.forward(step)
nt.left(angle)
coord.append(int(nt.position()[0]*10)+center[0])
coord.append(int(nt.position()[1]*10)+center[1])
drawLine(coord)
def drawRays(rays=32, rayLength=100, centerX=0, centerY=0):
""""
draw N rays from center in active drawable with current brush
"""
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if centerX == 0:
centerX = image.width/2
if centerY == 0:
centerY = image.height/2
ray_gap = int(360.0/rays)
for ray in range(0,rays):
ctrlPoints = centerX, centerY, centerX + rayLength * math.sin(math.radians(ray*ray_gap)), centerY + rayLength * math.cos(math.radians(ray*ray_gap))
drawLine(ctrlPoints)
def drawRandomRays(rays=32, length=100, centerX=0, centerY=0,noise=0.3):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if centerX == 0:
centerX = image.width/2
if centerY == 0:
centerY = image.height/2
ray_gap = 360.0/rays
for ray in range(0,rays):
rayLength=random.choice(range(int(length-length*noise),int(length+length*noise)))
random_angle=random.choice(np.arange(0.0,360.0,0.01))
ctrlPoints = [ centerX, centerY, centerX + int(rayLength * math.sin(math.radians(random_angle))), int(centerY + rayLength * math.cos(math.radians(random_angle)))]
drawLine(ctrlPoints)
def spikeBallStack(depth=20, layer_mode=6, flatten=0):
for x in range(1,depth):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
qL()
gimp_be.pdb.gimp_layer_set_mode(gimp_be.pdb.gimp_image_get_active_layer(image), layer_mode)
drawRandomRays(rays=random.choice([32,64,128,4]), length=(image.height/2-image.height/12), centerX=image.width/2, centerY=image.height/2,noise=random.choice([0.3,0.1,0.8]))
if flatten:
if not x%flatten:
gimp_be.pdb.gimp_image_flatten(image)
def randomStrokes(num = 4, opt = 1):
"""
Draw random strokes of random size and random position
"""
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
r = random.randrange
for loopNum in range(0, num):
if opt == 1:
brushSize(35)
drawLine(ctrlPoints)
# draw random color bars, opt 3 uses random blend
def drawBars(barNum=10, opt=3):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
barWidth =image.width/ barNum
barLeft = 0
color = -1
for loopNum in range(0, barNum):
gimp_be.pdb.gimp_image_select_rectangle(image, 2, barLeft, 0, barWidth, image.height)
barLeft = barLeft + barWidth
if opt == 3:
randomBlend()
elif opt == 2:
color = brushColor()
gimp_be.pdb.gimp_edit_bucket_fill_full(drawable, 0, 0, 100, 0, 1, 0, gimp_be.SELECT_CRITERION_COMPOSITE, 0, 0)
else:
gimp_be.pdb.gimp_edit_bucket_fill_full(drawable, 0, 0, 100, 0, 1, 0, gimp_be.SELECT_CRITERION_COMPOSITE, 0, 0)
gimp_be.pdb.gimp_selection_none(image)
return (barNum, opt, color)
# draw carbon nano tube
def drawCNT():
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
drawSinWave(1, 4, image.height * .42, 0, image.height / 2)
gimp_be.pdb.gimp_paintbrush(drawable, 0, 4, (0, (image.height - 80),image.width, (image.height - 80)), 0, 0)
gimp_be.pdb.gimp_paintbrush(drawable, 0, 4, (0, 80,image.width, 80), 0, 0)
# draw sine wave
def drawSinWave(bar_space=32, bar_length=-1, mag=70, x_offset=-1, y_offset=-1):
image = gimp_be.gimp.image_list()[0]
if y_offset == -1:
y_offset = image.height/2
if x_offset == -1:
x_offset = 0
if bar_length == -1:
bar_length = image.height/6
steps = image.width / bar_space
x = 0
for cStep in range(0, steps):
x = cStep * bar_space + x_offset
y = int(round(math.sin(x) * mag) + y_offset)
ctrlPoints = x, int(y - round(bar_length / 2)), x, int(y + round(bar_length / 2))
drawLine(ctrlPoints)
# draw sine wave
def drawSinWaveDouble(barSpace, barLen, mag):
image = gimp_be.gimp.image_list()[0]
steps =image.width/ barSpace
x = 0
for cStep in range(1, steps):
x = cStep * barSpace
y = int(abs(round(math.sin(x) * mag + image.height / 2)))
ctrlPoints = x, int(y - round(barLen / 2)), x, int(y + round(barLen / 2))
drawLine(ctrlPoints)
# draw a single brush point
def drawBrush(x1, y1):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
ctrlPoints = (x1, y1, x1, y1)
drawLine(ctrlPoints)
# draw multiple brush points
def drawMultiBrush(brush_strokes=24):
image = gimp_be.gimp.image_list()[0]
grid_width=image.width/int(math.sqrt(brush_strokes))
grid_height=image.height/int(math.sqrt(brush_strokes))
coord_x=0
coord_y = 0
for i in range(0, int(math.sqrt(brush_strokes))):
coord_x = coord_x + grid_width
for x in range(0, int(math.sqrt(brush_strokes))):
coord_y = coord_y + grid_height
drawBrush(coord_x, coord_y)
coord_y = 0
#draw grid of dots, this is for remainder mapping, this incomplete and temp. ####====DONT FORGET
def dotGrid():
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
for i in range(10,image.width-10,20):
for x in range(10, image.height-10,20):
grayColor(abs(i^3-x^3)%256)
drawBrush(i+10,x+10)
# draws random dots, opt does random color
def randomCircleFill(num=20, size=100, opt=3, sq=1):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
for loopNum in range(0, num):
cirPar = [random.randrange(0,image.width), random.randrange(0, image.height), random.randrange(10, size),
random.randrange(10, size)]
if opt % 2 == 0:
brushColor()
if sq:
gimp_be.pdb.gimp_ellipse_select(image, cirPar[0], cirPar[1], cirPar[2], cirPar[2], 2, 1, 0, 0)
else:
gimp_be.pdb.gimp_ellipse_select(image, cirPar[0], cirPar[1], cirPar[2], cirPar[3], 2, 1, 0, 0)
if opt % 3 == 3:
randomBlend()
else:
gimp_be.pdb.gimp_edit_bucket_fill_full(drawable, 0, 0, 100, 0, 1, 0, gimp_be.SELECT_CRITERION_COMPOSITE, 0, 0)
gimp_be.pdb.gimp_selection_none(image)
def randomRectFill(num=20, size=100, opt=3, sq=0):
# draws square, opt does random color
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
selectMode = 2
if opt % 5 == 0:
selectMode = 0
for loopNum in range(0, num):
if opt % 2 == 0:
brushColor()
rectPar = [random.randrange(0,image.width), random.randrange(0, image.height), random.randrange(10, size),
random.randrange(10, size)]
if sq:
gimp_be.pdb.gimp_image_select_rectangle(image, 2, rectPar[0], rectPar[1], rectPar[2], rectPar[2])
else:
gimp_be.pdb.gimp_image_select_rectangle(image, 2, rectPar[0], rectPar[1], rectPar[2], rectPar[3])
if opt % 3 == 0:
randomBlend()
else:
gimp_be.pdb.gimp_edit_bucket_fill_full(drawable, 0, 0, 100, 0, 1, 0, gimp_be.SELECT_CRITERION_COMPOSITE, 0, 0)
gimp_be.pdb.gimp_selection_none(image)
def randomBlend():
# Random Blend tool test
blend_mode = 0
paint_mode = 0
gradient_type = random.randrange(0, 10)
opacity = random.randrange(20, 100)
offset = 0
repeat = random.randrange(0, 2)
reverse = 0
supersample = 0
max_depth = random.randrange(1, 9)
threshold = 0
threshold = random.randrange(0, 1)
dither = 0
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
brushColor()
x1 = random.randrange(0,image.width)
y1 = random.randrange(0, image.height)
x2 = random.randrange(0,image.width)
y2 = random.randrange(0, image.height)
gimp_be.pdb.gimp_blend(drawable, blend_mode, paint_mode, gradient_type, opacity, offset, repeat, reverse, supersample, max_depth, threshold, dither, x1, y1, x2, y2)
def randomPoints(num=12):
d = []
for x in range(num):
d.append(choice(range(boarder,image.width-boarder)))
d.append(choice(range(boarder,image.height-boarder)))
return d
def drawInkBlot(option=''):
image=gimp_be.gimp.image_list()[0]
layer=gimp_be.pdb.gimp_image_get_active_layer(image)
if 'trippy' in option:
layer_copy = gimp_be.pdb.gimp_layer_copy(layer, 0)
gimp_be.pdb.gimp_image_add_layer(image, layer_copy,1)
randomBlend()
mask = gimp_be.pdb.gimp_layer_create_mask(layer,5)
gimp_be.pdb.gimp_image_add_layer_mask(image, layer,mask)
editLayerMask(1)
randomCircleFill(num=15,size=800)
brushColor(255,255,255)
randomCircleFill(num=50,size=100)
randomCircleFill(num=5,size=300)
brushColor(0)
randomCircleFill(num=20,size=600)
randomCircleFill(num=50,size=400)
randomCircleFill(num=100,size=100)
brushColor(255,255,255)
randomCircleFill(num=50,size=100)
brushColor(0)
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
brushSize()
strokes=[random.randrange(0,image.width/2),random.randrange(0,image.height),random.randrange(0,image.width/2),random.randrange(0,image.height)]
gimp_be.pdb.gimp_smudge(drawable, random.choice([1,5,10,50,100]), len(strokes), strokes)
brushSize()
strokes=[random.randrange(0,image.width/2),random.randrange(0,image.height),random.randrange(0,image.width/2),random.randrange(0,image.height)]
gimp_be.pdb.gimp_smudge(drawable, random.choice([1,5,10,50,100]), len(strokes), strokes)
mirror('h')
if 'trippy' in option and random.choice([0,1]):
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
gimp_be.pdb.gimp_invert(drawable)
editLayerMask(0)
def inkBlotStack(depth=16,layer_mode=6, flatten=0):
for x in range(1,depth):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
qL()
gimp_be.pdb.gimp_layer_set_mode(gimp_be.pdb.gimp_image_get_active_layer(image), layer_mode)
drawInkBlot()
if flatten:
if not x%flatten:
flatten()
def gridCenters(grid=[]):
if grid==[]:
grid=[4,3]
image = gimp_be.gimp.image_list()[0]
row_width = image.width/(grid[0])
columb_height = image.height/(grid[1])
tile_centers = []
for row in range(0,grid[0]):
for columb in range(0,grid[1]):
tile_centers.append([row_width*row+row_width/2,columb_height*columb+columb_height/2])
return tile_centers
def tile(grid=[],option="mibd",irregularity=0.3):
image=gimp_be.gimp.image_list()[0]
layer=gimp_be.pdb.gimp_image_get_active_layer(image)
if grid==[]:
if image.height == image.width:
grid=[4,4]
elif image.height < image.width:
grid=[3,4]
else:
grid=[4,3]
if "m" in option:
mask = gimp_be.pdb.gimp_layer_create_mask(layer,0)
gimp_be.pdb.gimp_image_add_layer_mask(image, layer,mask)
editLayerMask(1)
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
grid_spacing = image.width/grid[0]
tile_centers=gridCenters(grid)
if irregularity > 0.0:
i_tiles=[]
for tile in tile_centers:
tile[0]=tile[0]+random.randrange((-1*int(grid_spacing*irregularity)),int(grid_spacing*irregularity))
tile[1]=tile[1]+random.randrange((-1*int(grid_spacing*irregularity)),int(grid_spacing*irregularity))
i_tiles.append(tile)
tile_centers=i_tiles
if "b" in option:
randomBrush()
if "d" in option:
randomDynamics()
brushSize(grid_spacing)
brushColor(0,0,0)
for tile in tile_centers:
if "m" in option:
editLayerMask(1)
if irregularity == 0:
gimp_be.pdb.gimp_paintbrush_default(drawable, len(tile), tile)
elif random.randrange(50.0*irregularity)+random.randrange(50.0*irregularity)>50.0:
randomDynamics()
else:
gimp_be.pdb.gimp_paintbrush_default(drawable, len(tile), tile)
if "g" in option:
gimp_be.pdb.plug_in_gauss(image, drawable, 20.0, 20.0, 0)
if "w" in option:
gimp_be.pdb.plug_in_whirl_pinch(image, drawable, 90, 0.0, 1.0)
if "i" in option:
gimp_be.pdb.gimp_invert(drawable)
if "m" in option:
editLayerMask(0)
def drawAkuTree(branches=6,tree_height=0, position=0):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if position==0:
position=[]
position.append(random.randrange(image.width))
position.append(random.randrange(4*tree_height/3, 3*image.height/4))
if tree_height == 0:
tree_height=random.randrange(position[1]/3, position[1]-position[1]/25)
print 'position:' + str(position)
#draw trunk
trunk=[position[0],position[1],position[0],position[1]-tree_height]
trunk_size=tree_height/40+3
print str(trunk)
print 'tree_height: ' + str(tree_height)
print 'trunk size: ' + str(trunk_size)
brushSize(trunk_size)
drawLine(trunk)
for node in range(branches):
node_base=[position[0],position[1]-((node*tree_height+1)/branches+tree_height/25+random.randrange(-1*tree_height/12,tree_height/12))]
base_length=tree_height/25
node_end=[]
if node%2==0:
node_end=[node_base[0]+base_length/2,node_base[1]-base_length/2]
brushSize(2*trunk_size/3)
drawLine([node_base[0],node_base[1],node_end[0],node_end[1]])
brushSize(trunk_size/3)
drawLine([node_end[0],node_end[1],node_end[0],node_end[1]-tree_height/12-(tree_height/48)])
else:
node_end=[node_base[0]-base_length/2,node_base[1]-base_length/2]
brushSize(2*trunk_size/3)
drawLine([node_base[0],node_base[1],node_end[0],node_end[1]])
brushSize(trunk_size/3)
drawLine([node_end[0],node_end[1],node_end[0],node_end[1]-(tree_height/12)])
def drawAkuForest(num=25):
for x in range(num):
drawAkuTree()
# draw a tree
def drawTree(x1=-1, y1=-1, angle=270, depth=9, recursiondepth=0):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if x1 == -1:
x1 = image.width/2
if y1 == -1:
y1 = image.height/2
x2 = x1 + int(math.cos(math.radians(angle)) * depth * 10.0)
y2 = y1 + int(math.sin(math.radians(angle)) * depth * 10.0)
ctrlPoints = (x1, y1, x2, y2)
if recursiondepth <= 2:
brushColor(87, 53, 12)
elif depth == 1:
brushColor(152, 90, 17)
elif depth <= 3:
brushColor(7, 145, 2)
brushSize(depth * 4 + 5)
gimp_be.pdb.gimp_paintbrush_default(drawable, len(ctrlPoints), ctrlPoints)
if depth > 0:
drawTree(x2, y2, angle - 20, depth - 1, recursiondepth + 1)
drawTree(x2, y2, angle + 20, depth - 1, recursiondepth + 1)
# draw a tree with 3 branches per node
def drawTriTree(x1=-1, y1=-1, angle=270, depth=6, recursiondepth=0, size=10):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if x1 == -1:
x1 = image.width/2
if y1 == -1:
y1 = image.height/2
if depth:
x2 = x1 + int(math.cos(math.radians(angle)) * depth * size) + random.randrange(-12, 12)
y2 = y1 + int(math.sin(math.radians(angle)) * depth * size) + random.randrange(-12, 12)
ctrlPoints = (x1, y1, x2, y2)
brushSize(depth + int(size/10))
brushColor()
gimp_be.pdb.gimp_paintbrush_default(drawable, len(ctrlPoints), ctrlPoints)
drawTriTree(x2, y2, angle - 30, depth - 1, recursiondepth + 1,size)
drawTriTree(x2, y2, angle, depth - 1, recursiondepth + 1,size)
drawTriTree(x2, y2, angle + 30, depth - 1, recursiondepth + 1,size)
# draw random color tri-tree
def drawColorTriTree(x1=-1, y1=-1, angle=270, depth=9, recursiondepth=0):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if x1 == -1:
x1 = image.width/2
if y1 == -1:
y1 = image.height/2
brushSize(depth + 1)
if depth:
x2 = x1 + int(math.cos(math.radians(angle)) * depth * 10.0) + random.randrange(-12, 12)
y2 = y1 + int(math.sin(math.radians(angle)) * depth * 10.0) + random.randrange(-12, 12)
ctrlPoints = (x1, y1, x2, y2)
gimp_be.pdb.gimp_paintbrush_default(drawable, len(ctrlPoints), ctrlPoints)
drawColorTriTree(x2, y2, angle - 20 + random.choice(-10, -5, 0, 5, 10), depth - 1, recursiondepth + 1)
drawColorTriTree(x2, y2, angle + random.choice(-10, -5, 0, 5, 10), depth - 1, recursiondepth + 1)
drawColorTriTree(x2, y2, angle + 20 + random.choice(-10, -5, 0, 5, 10), depth - 1, recursiondepth + 1)
# draw a tree
def drawOddTree(x1=-1, y1=-1, angle=270, depth=9, recursiondepth=0):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if x1 == -1:
x1 = image.width/2
if y1 == -1:
y1 = image.height/2
brushSize((depth * 8 + 30))
if depth:
x2 = x1 + int(math.cos(math.radians(angle)) * depth * 10.0)
y2 = y1 + int(math.sin(math.radians(angle)) * depth * 10.0)
ctrlPoints = (x1, y1, x2, y2)
gimp_be.pdb.gimp_paintbrush_default(drawable, len(ctrlPoints), ctrlPoints)
if not random.randrange(0, 23) == 23:
drawTree(x2, y2, angle - 20, depth - 1, recursiondepth + 1)
if depth % 2 == 0:
drawTree(x2, y2, angle + 20, depth - 1, recursiondepth + 1)
if (depth + 1) % 4 == 0:
drawTree(x2, y2, angle + 20, depth - 1, recursiondepth + 1)
if depth == 5:
drawTree(x2, y2, angle - 45, depth - 1, recursiondepth + 1)
drawTree(x2, y2, angle + 45, depth - 1, recursiondepth + 1)
# draw a tree
def drawForestTree(x1=-1, y1=-1, angle=270, depth=7, size=10, recursiondepth=0):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if x1 == -1:
x1 = image.width/2
if y1 == -1:
y1 = image.height/2
if depth:
x2 = x1 + int(math.cos(math.radians(angle)) * depth * 10.0)
y2 = y1 + int(math.sin(math.radians(angle)) * depth * 10.0)
ctrlPoints = (x1, y1, x2, y2)
brushSize(depth * depth * (int(size / ((image.height - y1)) / image.height)) + 4)
gimp_be.pdb.gimp_paintbrush_default(drawable, len(ctrlPoints), ctrlPoints)
if not random.randrange(0, 23) == 23:
drawForestTree(x2, y2, angle - 20, depth - 1, size, recursiondepth + 1)
if random.randrange(0, 23) == 23:
drawForestTree(x2, y2, angle - random.randrange(-30, 30), depth - 1, size, recursiondepth + 1)
drawForestTree(x2, y2, angle - random.randrange(-30, 30), depth - 1, size, recursiondepth + 1)
drawForestTree(x2, y2, angle - random.randrange(-30, 30), depth - 1, size, recursiondepth + 1)
else:
drawForestTree(x2, y2, angle - random.randrange(15, 50), depth - 1, size, recursiondepth + 1)
if depth % 2 == 0:
drawForestTree(x2, y2, angle + 20, depth - 1, size, recursiondepth + 1)
if (depth + 1) % 4 == 0:
drawForestTree(x2, y2, angle + 20, depth - 1, size, recursiondepth + 1)
if depth == 5:
drawForestTree(x2, y2, angle - 45, depth - 1, size, recursiondepth + 1)
drawForestTree(x2, y2, angle + 45, depth - 1, size, recursiondepth + 1)
# draw a series of trees with a y position based on depth
def drawForest(trees, options):
image = gimp_be.gimp.image_list()[0]
for tree in range(0, trees):
y1 = 2 * (image.height / 3) + random.randrange(-1 * (image.height / 5), image.height / 5)
x1 = random.randrange(image.width / 20, 19 * (image.width / 20))
angle = random.randrange(250, 290)
size = (y1 / (2.0 * (image.height / 3.0) + (image.height / 5.0))) + 4
depth = random.randrange(3, 7)
drawForestTree(x1, y1, angle, depth, size)
#draws polygon of N sides at a x-y location
def drawPolygon(sides=5,size=300,x_pos=0,y_pos=0, angle_offset=0):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if y_pos==0:
y_pos=image.height/2
if x_pos==0:
x_pos=image.width/2
degree_between_points=360/sides
points_list=[]
for x in range(0,sides+1):
point_degree=degree_between_points*x+angle_offset
points_list.append(int(round(math.sin(math.radians(point_degree))*size))+x_pos)
points_list.append(int(round(math.cos(math.radians(point_degree))*size))+y_pos)
fade_out=0
method=0
gradient_length=0
gimp_be.pdb.gimp_paintbrush(drawable, fade_out, len(points_list), points_list, method, gradient_length)
#draw a grid of polygons of N sides
def drawPolygonGrid(size=60,sides=3, angle_offset=0):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if sides%2 == 1 or sides>4:
for y in range(0-image.height/10,image.height+image.height/10, size):
x_loop=0
for x in range(0-image.width/10, image.width+image.width/10, size):
if x_loop%2==1:
drawPolygon(sides,size-size/2,x-(size/2),y,360/sides)
else:
drawPolygon(sides,size-size/2,x,y,0)
x_loop=x_loop+1
else:
for x in range(0-image.height/10,image.height+image.height/10, size):
for y in range(0-image.width/10, image.width+image.width/10, size):
drawPolygon(sides,size/3,x,y,0)
degree_between_points=360/sides
points_list=[]
for x in range(0,sides+1):
point_degree=math.radians(degree_between_points*x+angle_offset)
points_list.append(int(round(math.sin(point_degree)*size)))
points_list.append(int(round(math.cos(point_degree)*size)))
fade_out=0
method=0
gradient_length=0
gimp_be.pdb.gimp_paintbrush(drawable, fade_out, len(points_list), points_list, method, gradient_length)
def drawFrygon(sides=5,size=300,x_pos=0,y_pos=0, angle_offset=0):
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.pdb.gimp_image_active_drawable(image)
if y_pos==0:
y_pos=image.height/2
if x_pos==0:
x_pos=image.width/2
degree_between_points=360/sides
points_list=[]
for x in range(0,sides+1):
point_degree=degree_between_points*x+angle_offset
points_list.append(int(round(math.sin(point_degree)*size))+y_pos)
points_list.append(int(round(math.cos(point_degree)*size))+x_pos)
fade_out=0
method=0
gradient_length=0
gimp_be.pdb.gimp_paintbrush(drawable, fade_out, len(points_list), points_list, method, gradient_length)
def drawFrygonGrid(size=120,sides=13):
global height, width
if sides%2 == 1:
for x in range(0,height,size):
x_deep=0
for y in range(0, width,size):
if x_deep%2==1:
drawFrygon(sides,size,x,y-(size/2),0)
else:
drawFrygon(sides,size,x,y,0)
x_deep=x_deep+1
else:
for x in range(0,height, size):
for y in range(0, width, size):
drawFrygon(sides,size,x,y,0)
| Java |
import {Option} from "./option";
export class HelpOption extends Option {
/**
*
*/
constructor() {
super();
this.shortName = 'h';
this.longName = 'help';
this.argument = '';
}
}
| Java |
import * as React from 'react';
import { createIcon } from '../Icon';
export const ShieldIcon = createIcon(
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />,
'ShieldIcon'
);
| Java |
"use strict";
var GLOBAL_MOUNT_POINT_MAX = Math.pow(2, 53);
var util = {
uuid: function(){
return Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX);
}
};
module.exports = util; | Java |
<?php
namespace ToyLang\Core\Lexer;
use ToyLang\Core\Lexer\Token\Token;
use ToyLang\Core\Lexer\Token\TokenType;
interface Lexer
{
/**
* @param TokenType $tokenType
* @return $this
*/
public function addTokenType(TokenType $tokenType);
/**
* @param TokenType[] $tokenTypes
* @return $this
*/
public function addTokenTypes($tokenTypes);
/**
* @param $input
* @return Token[]
*/
public function tokenize($input);
}
| Java |
//
// HomeDateContainerView.h
// XQDemo
//
// Created by XiangqiTu on 15-4-13.
//
//
#import <UIKit/UIKit.h>
@interface HomeDateContainerView : UIView
- (void)caculateDateWithTimestamp:(NSString *)timestamp;
@end
| Java |
require 'test_helper'
class CustomerQuestionshipTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| Java |
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* A DisplayObjectContainer represents a collection of display objects.
* It is the base class of all display objects that act as a container for other objects.
*
* @class DisplayObjectContainer
* @extends DisplayObject
* @constructor
*/
PIXI.DisplayObjectContainer = function()
{
PIXI.DisplayObject.call( this );
/**
* [read-only] The of children of this container.
*
* @property children
* @type Array<DisplayObject>
* @readOnly
*/
this.children = [];
}
// constructor
PIXI.DisplayObjectContainer.prototype = Object.create( PIXI.DisplayObject.prototype );
PIXI.DisplayObjectContainer.prototype.constructor = PIXI.DisplayObjectContainer;
/**
* Adds a child to the container.
*
* @method addChild
* @param child {DisplayObject} The DisplayObject to add to the container
*/
PIXI.DisplayObjectContainer.prototype.addChild = function(child)
{
if(child.parent != undefined)
{
//// COULD BE THIS???
child.parent.removeChild(child);
// return;
}
child.parent = this;
this.children.push(child);
// update the stage refference..
if(this.stage)
{
var tmpChild = child;
do
{
if(tmpChild.interactive)this.stage.dirty = true;
tmpChild.stage = this.stage;
tmpChild = tmpChild._iNext;
}
while(tmpChild)
}
// LINKED LIST //
// modify the list..
var childFirst = child.first
var childLast = child.last;
var nextObject;
var previousObject;
// this could be wrong if there is a filter??
if(this._filters || this._mask)
{
previousObject = this.last._iPrev;
}
else
{
previousObject = this.last;
}
nextObject = previousObject._iNext;
// always true in this case
// need to make sure the parents last is updated too
var updateLast = this;
var prevLast = previousObject;
while(updateLast)
{
if(updateLast.last == prevLast)
{
updateLast.last = child.last;
}
updateLast = updateLast.parent;
}
if(nextObject)
{
nextObject._iPrev = childLast;
childLast._iNext = nextObject;
}
childFirst._iPrev = previousObject;
previousObject._iNext = childFirst;
// need to remove any render groups..
if(this.__renderGroup)
{
// being used by a renderTexture.. if it exists then it must be from a render texture;
if(child.__renderGroup)child.__renderGroup.removeDisplayObjectAndChildren(child);
// add them to the new render group..
this.__renderGroup.addDisplayObjectAndChildren(child);
}
}
/**
* Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown
*
* @method addChildAt
* @param child {DisplayObject} The child to add
* @param index {Number} The index to place the child in
*/
PIXI.DisplayObjectContainer.prototype.addChildAt = function(child, index)
{
if(index >= 0 && index <= this.children.length)
{
if(child.parent != undefined)
{
child.parent.removeChild(child);
}
child.parent = this;
if(this.stage)
{
var tmpChild = child;
do
{
if(tmpChild.interactive)this.stage.dirty = true;
tmpChild.stage = this.stage;
tmpChild = tmpChild._iNext;
}
while(tmpChild)
}
// modify the list..
var childFirst = child.first;
var childLast = child.last;
var nextObject;
var previousObject;
if(index == this.children.length)
{
previousObject = this.last;
var updateLast = this;
var prevLast = this.last;
while(updateLast)
{
if(updateLast.last == prevLast)
{
updateLast.last = child.last;
}
updateLast = updateLast.parent;
}
}
else if(index == 0)
{
previousObject = this;
}
else
{
previousObject = this.children[index-1].last;
}
nextObject = previousObject._iNext;
// always true in this case
if(nextObject)
{
nextObject._iPrev = childLast;
childLast._iNext = nextObject;
}
childFirst._iPrev = previousObject;
previousObject._iNext = childFirst;
this.children.splice(index, 0, child);
// need to remove any render groups..
if(this.__renderGroup)
{
// being used by a renderTexture.. if it exists then it must be from a render texture;
if(child.__renderGroup)child.__renderGroup.removeDisplayObjectAndChildren(child);
// add them to the new render group..
this.__renderGroup.addDisplayObjectAndChildren(child);
}
}
else
{
throw new Error(child + " The index "+ index +" supplied is out of bounds " + this.children.length);
}
}
/**
* [NYI] Swaps the depth of 2 displayObjects
*
* @method swapChildren
* @param child {DisplayObject}
* @param child2 {DisplayObject}
* @private
*/
PIXI.DisplayObjectContainer.prototype.swapChildren = function(child, child2)
{
if(child === child2) {
return;
}
var index1 = this.children.indexOf(child);
var index2 = this.children.indexOf(child2);
if(index1 < 0 || index2 < 0) {
throw new Error("swapChildren: Both the supplied DisplayObjects must be a child of the caller.");
}
this.removeChild(child);
this.removeChild(child2);
if(index1 < index2)
{
this.addChildAt(child2, index1);
this.addChildAt(child, index2);
}
else
{
this.addChildAt(child, index2);
this.addChildAt(child2, index1);
}
}
/**
* Returns the Child at the specified index
*
* @method getChildAt
* @param index {Number} The index to get the child from
*/
PIXI.DisplayObjectContainer.prototype.getChildAt = function(index)
{
if(index >= 0 && index < this.children.length)
{
return this.children[index];
}
else
{
throw new Error(child + " Both the supplied DisplayObjects must be a child of the caller " + this);
}
}
/**
* Removes a child from the container.
*
* @method removeChild
* @param child {DisplayObject} The DisplayObject to remove
*/
PIXI.DisplayObjectContainer.prototype.removeChild = function(child)
{
var index = this.children.indexOf( child );
if ( index !== -1 )
{
// unlink //
// modify the list..
var childFirst = child.first;
var childLast = child.last;
var nextObject = childLast._iNext;
var previousObject = childFirst._iPrev;
if(nextObject)nextObject._iPrev = previousObject;
previousObject._iNext = nextObject;
if(this.last == childLast)
{
var tempLast = childFirst._iPrev;
// need to make sure the parents last is updated too
var updateLast = this;
while(updateLast.last == childLast)
{
updateLast.last = tempLast;
updateLast = updateLast.parent;
if(!updateLast)break;
}
}
childLast._iNext = null;
childFirst._iPrev = null;
// update the stage reference..
if(this.stage)
{
var tmpChild = child;
do
{
if(tmpChild.interactive)this.stage.dirty = true;
tmpChild.stage = null;
tmpChild = tmpChild._iNext;
}
while(tmpChild)
}
// webGL trim
if(child.__renderGroup)
{
child.__renderGroup.removeDisplayObjectAndChildren(child);
}
child.parent = undefined;
this.children.splice( index, 1 );
}
else
{
throw new Error(child + " The supplied DisplayObject must be a child of the caller " + this);
}
}
/*
* Updates the container's children's transform for rendering
*
* @method updateTransform
* @private
*/
PIXI.DisplayObjectContainer.prototype.updateTransform = function()
{
if(!this.visible)return;
PIXI.DisplayObject.prototype.updateTransform.call( this );
for(var i=0,j=this.children.length; i<j; i++)
{
this.children[i].updateTransform();
}
} | Java |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<title>TSA Website Design</title>
</head>
<body>
<div id="background">
<img src="dscovrblured.jpg" class="stretch">
</div>
<nav id="mainNav" class="navbar navbar-inverse navbar-fixed-top">
<div align="center" class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar1" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Navigation Toggle</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<!--<a class="navbar-brand page-scroll" href="index.html">Privatization of Space Exploration</a>-->
</div>
<div style="text-align:center" class="collapse navbar-collapse" id="navbar1">
<ul class="nav navbar-nav navbar-right">
<li>
<a class="page-scroll" href="index.html">Home</a>
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#b2">Space Enterprises
<span class="caret"></span></a>
<ul class="dropdown-menu">
<li>
<a href="#b21">SpaceX</a>
</li>
<li>
<a href="#b22">Blue Origin</a>
</li>
<li>
<a href="#b23">Vigin Galactic</a>
</li>
<li>
<a href="#b24">XCOR</a>
</li>
<li>
<a href="#b25">Starchaser Industries</a>
</li>
<li>
<a href="#b26">Bigelow Aerospace</a>
</li>
<li>
<a href="#b27">Lockheed Martin</a>
</li>
<li>
<a href="#b28">Orbital ATK</a>
</li>
<li>
<a href="#b29">Scaled Composites</a>
</li>
</ul>
</li>
<li>
<a class="page-scroll" href="#b2">Timeline of Events</a>
</li>
<li>
<a class="page-scroll" href="#b3">Evolution of Vehicles</a>
</li>
<li>
<a class="page-scroll" href="#d4">Careers & Interviews</a>
</li>
<li>
<a class="page-scroll" href="#d5">Impacts and Advantages</a>
</li>
<li>
<a class="page-scroll" href="#d6">Careers & Interviews</a>
</li>
<li>
<a class="page-scroll" href="#d7">Resources</a>
</li>
</ul>
</div>
</div>
</nav>
<p>
<div class="container-fluid">
<div class="row">
<a href="aboutspacex.html">
<img src="spacexheaderwithlogofaded.png" class="img-responsive">
</a>
</div> <!---NIEN--->
</div>
</p>
<div class="container">
<div class="panel panel-default">
<div class="panel-body">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae sapien id est dignissim venenatis. Maecenas quis gravida ipsum, a pharetra nisi. Etiam ornare arcu eu diam luctus convallis. Cras dictum diam augue, sed porttitor nibh euismod ac. Proin ullamcorper, velit ac rutrum fermentum, nunc urna bibendum augue, in scelerisque nisl sapien ac nunc. Ut id faucibus lorem, vel finibus mi. Nunc pharetra elit non libero dictum venenatis. Vestibulum vel massa in odio viverra maximus quis eu velit. Nulla auctor ut ligula at dapibus. Ut id tincidunt orci. Sed et consequat urna. Cras eu consequat dolor. Integer fringilla at nisl eu venenatis.
Ut vulputate accumsan mauris, vel porttitor nunc maximus non. Morbi convallis ornare laoreet. Maecenas sagittis consequat consectetur. Mauris placerat dignissim neque quis lacinia. Phasellus ut dapibus mi, sit amet pretium leo. Praesent eget placerat nisl. Duis dictum nisi vitae maximus hendrerit. Pellentesque porta neque ac malesuada volutpat. Morbi quis erat nisl. Quisque eros sem, molestie et fermentum eu, efficitur ac mi. Sed euismod ipsum enim, ultrices sodales nisl auctor eget. Etiam vel mi convallis, vulputate magna a, dictum enim.
Cras eleifend lorem placerat tortor venenatis, non venenatis dolor lacinia. Morbi augue massa, interdum at neque nec, congue pretium libero. Aenean tempor pellentesque hendrerit. Morbi eget dui lectus. Suspendisse potenti. Suspendisse non enim faucibus, condimentum tellus eget, posuere sem. Aenean volutpat luctus tincidunt. Vestibulum at cursus turpis, in vestibulum nunc. Sed scelerisque erat in finibus auctor. Suspendisse euismod ante diam, in fermentum elit tempus vel.
Nulla auctor enim nec eros semper, nec sollicitudin libero pharetra. Fusce ut finibus neque. Fusce augue risus, semper a consectetur sit amet, congue a nunc. In mattis euismod sem at pretium. Nunc lacinia semper felis, non tincidunt magna placerat vitae. Quisque facilisis vel sapien sit amet vulputate. Nulla facilisi.
In vel tortor libero. Vestibulum pharetra congue metus, et vestibulum tellus ultrices quis. Phasellus vel eros et libero suscipit feugiat. Vivamus pretium malesuada vulputate. Suspendisse egestas metus sit amet dapibus ullamcorper. Quisque elementum tempus nulla id mattis. Quisque iaculis interdum erat, id varius lectus ultricies et. Aenean sit amet arcu rutrum, vulputate arcu ac, consequat nunc. Phasellus vel risus ante. Suspendisse efficitur felis neque, non semper sapien scelerisque ut. Fusce vel libero vitae enim tincidunt sollicitudin. Nunc id ligula cursus, fringilla lectus id, fermentum purus.
</div>
</div>
</div>
</body>
</html> | Java |
function ga() {}
var _gaq = []
| Java |
export { default } from 'ember-stripe-elements/components/stripe-card';
| Java |
<?php
return [
/**
*--------------------------------------------------------------------------
* Default Broadcaster
*--------------------------------------------------------------------------
*
* This option controls the default broadcaster that will be used by the
* framework when an event needs to be broadcast. You may set this to
* any of the connections defined in the "connections" array below.
*
* Supported: "pusher", "redis", "log", "null"
*
*/
'default' => env('BROADCAST_DRIVER', 'null'),
/**
*--------------------------------------------------------------------------
* Broadcast Connections
*--------------------------------------------------------------------------
*
* Here you may define all of the broadcast connections that will be used
* to broadcast events to other systems or over websockets. Samples of
* each available type of connection are provided inside this array.
*
*/
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'encrypted' => true,
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
'log' => [
'driver' => 'log',
],
'null' => [
'driver' => 'null',
],
],
];
| Java |
---
name: Bug report
about: Create a report to help us improve
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. use option '...'
3. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
**nibetaseries version**
Add the version of nibetaseries you are using
**Additional context**
Add any other context about the problem here.
| Java |
#include "binary_buffer.hpp"
#include <iterator>
#include <algorithm>
#include <sstream>
#include <boost/endian/conversion.hpp>
using boost::endian::native_to_big;
using boost::endian::big_to_native;
namespace {
using aria::byte;
template <typename P>
void append_bytes_to_vector(std::vector<byte> & vec, P primitive)
{
auto * begin = reinterpret_cast<byte *>(&primitive);
auto * end = begin + sizeof(primitive);
std::copy(begin, end, std::back_inserter(vec));
}
template <typename P>
P read_primitive_and_advance(const byte * buffer, size_t size, size_t & offset, const std::string & name)
{
size_t stride = sizeof(P);
if (offset + stride <= size) {
auto i = reinterpret_cast<const P *>(buffer + offset);
offset += stride;
return big_to_native(*i);
} else {
throw aria::internal::buffer_error("Insufficient bytes available to read " + name + ".");
}
}
}
aria::internal::buffer_error::buffer_error(const char *what)
: std::runtime_error(what)
{
}
aria::internal::buffer_error::buffer_error(const std::string &what)
: std::runtime_error(what)
{
}
void aria::internal::binary_buffer_writer::write_uint8(uint8_t i)
{
_bytes.push_back(static_cast<byte>(i));
}
void aria::internal::binary_buffer_writer::write_uint16(uint16_t i)
{
append_bytes_to_vector(_bytes, native_to_big(i));
}
void aria::internal::binary_buffer_writer::write_uint32(uint32_t i)
{
append_bytes_to_vector(_bytes, native_to_big(i));
}
void aria::internal::binary_buffer_writer::write_uint64(uint64_t i)
{
append_bytes_to_vector(_bytes, native_to_big(i));
}
void aria::internal::binary_buffer_writer::write_string(const std::string &str)
{
write_uint32(str.size());
for (auto c : str) {
_bytes.push_back(static_cast<byte>(c));
}
}
void aria::internal::binary_buffer_writer::write_bytes(const std::vector<aria::byte> &bytes)
{
write_uint32(bytes.size());
std::copy(bytes.begin(), bytes.end(), std::back_inserter(_bytes));
}
std::vector<aria::byte> aria::internal::binary_buffer_writer::take_buffer()
{
std::vector<byte> buffer;
_bytes.swap(buffer);
return buffer;
}
aria::internal::binary_buffer_reader::binary_buffer_reader(const std::vector<byte> * buffer)
: _buffer_start(buffer->data()), _buffer_size(buffer->size()), _offset(0)
{
}
uint8_t aria::internal::binary_buffer_reader::read_uint8()
{
return read_primitive_and_advance<uint8_t>(_buffer_start, _buffer_size, _offset, "uint8");
}
uint16_t aria::internal::binary_buffer_reader::read_uint16()
{
return read_primitive_and_advance<uint16_t>(_buffer_start, _buffer_size, _offset, "uint16");
}
uint32_t aria::internal::binary_buffer_reader::read_uint32()
{
return read_primitive_and_advance<uint32_t>(_buffer_start, _buffer_size, _offset, "uint32");
}
uint64_t aria::internal::binary_buffer_reader::read_uint64()
{
return read_primitive_and_advance<uint64_t>(_buffer_start, _buffer_size, _offset, "uint64");
}
std::string aria::internal::binary_buffer_reader::read_string()
{
uint32_t size;
try {
size = read_uint32();
} catch (buffer_error) {
throw buffer_error("Insufficient bytes available to read string size.");
}
if (_offset + size <= _buffer_size) {
auto data = reinterpret_cast<const char *>(_buffer_start + _offset);
_offset += size;
return std::string(data, size);;
} else {
assert(_offset <= _buffer_size);
auto available = _buffer_size - _offset;
std::stringstream ss;
ss << "Expected " << size << " bytes of string data, but only " << available
<< " available bytes in buffer.";
throw buffer_error(ss.str());
}
}
std::vector<byte> aria::internal::binary_buffer_reader::read_bytes()
{
uint32_t size;
try {
size = read_uint32();
} catch (buffer_error) {
throw buffer_error("Insufficient bytes available to read data size.");
}
if (_offset + size <= _buffer_size) {
auto data = _buffer_start + _offset;
_offset += size;
return std::vector<byte>(data, data + size);
} else {
assert(_offset <= _buffer_size);
auto available = _buffer_size - _offset;
std::stringstream ss;
ss << "Expected " << size << " bytes of data, but only " << available
<< " available bytes in buffer.";
throw buffer_error(ss.str());
}
}
| Java |
<pre><code class="css">h1(class='s-simple-title u-fs-h5x') Thumbnail Object
h2.s-simple-title--sub Default
.s-simple-objects.thumbnail
.o-thumb
img(class="o-thumb__item" src= "http://placehold.it/200")
.s-simple-code
include ../code/highlight/highlight-code-javascript.html
h2.s-simple-title--sub Thumbnail Rounded
.s-simple-objects.thumbnail
.o-thumb
img(class="o-thumb__item u-r-all" src= "http://placehold.it/200")
.s-simple-code
include ../code/highlight/highlight-code-javascript.html
h2.s-simple-title--sub Thumbnail Circle
.s-simple-objects.thumbnail
.o-thumb
img(class="o-thumb__item u-r-circle" src= "http://placehold.it/200")
.s-simple-code
include ../code/highlight/highlight-code-javascript.html</code></pre> | Java |
# Acknowledgements
This application makes use of the following third party libraries:
## AFNetworking
Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## AFOAuth2Manager
Copyright (c) 2011-2014 AFNetworking (http://afnetworking.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## AHKActionSheet
Copyright (c) 2014 Arkadiusz Holko <fastred@fastred.org>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## APAddressBook
Copyright (c) 2013 Alterplay
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## BBBadgeBarButtonItem
The MIT License (MIT)
Copyright (c) 2014 Tanguy Aladenise
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## CYRTextView
The MIT License (MIT)
Copyright (c) 2014 Cyrillian, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## DAKeyboardControl
# License
## MIT License
Copyright (c) 2012 Daniel Amitay (http://danielamitay.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## DHSmartScreenshot
The MIT License (MIT)
Copyright (c) 2013 David Hernandez
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## DTCoreText
Copyright (c) 2011, Oliver Drobnik All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
## DTFoundation
Copyright (c) 2011, Oliver Drobnik All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
## FDWaveformView
Copyright (c) 2015 William Entriken <github.com@phor.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## FreeStreamer
Copyright (c) 2011-2016 Matias Muhonen <mmu@iki.fi> 穆马帝
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The FreeStreamer framework bundles Reachability which is licensed under the following
license:
Copyright (c) 2011, Tony Million.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
## HMSegmentedControl
# License
## MIT License
Copyright (c) 2012 Hesham Abd-Elmegid (http://www.hesh.am)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## INTULocationManager
The MIT License (MIT)
Copyright (c) 2014-2015 Intuit Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## IQAudioRecorderController
The MIT License (MIT)
Copyright (c) 2015 Mohd Iftekhar Qurashi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## JDStatusBarNotification
Copyright © 2013 Markus Emrich
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
(MIT License)
## JSCoreBom
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## MBProgressHUD
Copyright © 2009-2016 Matej Bukovinski
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## NSGIF
The MIT License (MIT)
Copyright (c) 2015 Sebastian Dobrincu
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## NSHash
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
## OMGHTTPURLRQ
See README.markdown for full license text.
## PBJVision
The MIT License (MIT)
Copyright (c) 2013-present Patrick Piemonte
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## PHFComposeBarView
Copyright (C) 2013 Philipe Fatio
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## PHFDelegateChain
Copyright (C) 2012 Philipe Fatio
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## REMenu
Copyright (c) 2013 Roman Efimov (https://github.com/romaonthego).
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## RMActionController
The MIT License (MIT)
Copyright (c) 2015 Roland Moers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## RMDateSelectionViewController
Copyright (c) 2013-2015 Roland Moers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## Reachability
Copyright (c) 2011, Tony Million.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
## SBJson
Copyright (C) 2007-2015 Stig Brautaset. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
## SCSiriWaveformView
The MIT License (MIT)
Copyright (c) [2013] [Stefan Ceriu]
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## SDWebImage
Copyright (c) 2016 Olivier Poitrey rs@dailymotion.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## SVPullToRefresh
Copyright (C) 2012 Sam Vermette
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## SWFrameButton
The MIT License (MIT)
Copyright (c) 2014 Sarun Wongpatcharapakorn
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## SWTableViewCell
Copyright (c) 2013 Christopher Wendel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## SZTextView
Copyright (c) 2013 glaszig <glaszig@gmail.com>
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## TDOAuth
OHAI CocoaPods linter!
## TTTAttributedLabel
Copyright (c) 2011 Mattt Thompson (http://mattt.me/)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## TWMessageBarManager
Copyright (C) 2013 Terry Worona
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software" ), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## UICKeyChainStore
The MIT License
Copyright (c) 2011 kishikawa katsumi
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## libPhoneNumber-iOS
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Generated by CocoaPods - https://cocoapods.org
| Java |
# :floppy_disk: ghbackup
[](https://godoc.org/qvl.io/ghbackup)
[](https://travis-ci.org/qvl/ghbackup)
[](https://goreportcard.com/report/qvl.io/ghbackup)
Backup your GitHub repositories with a simple command-line application written in Go.
The simplest way to keep your repositories save:
1. [Install](#install) `ghbackup`
1. Get a token from https://github.com/settings/tokens
2. `ghbackup -secret token /path/to/backup/dir`
This will backup all repositories you have access to.
-----------------------------------
Embarrassing simple GitHub backup tool
Usage: ghbackup [flags] directory
directory path to save the repositories to
At least one of -account or -secret must be specified.
Flags:
-account string
GitHub user or organization name to get repositories from.
If not specified, all repositories the authenticated user has access to
will be loaded.
-secret string
Authentication secret for GitHub API.
Can use the users password or a personal access token (https://github.c
om/settings/tokens).
Authentication increases rate limiting (https://developer.github.com/v3
/#rate-limiting) and enables backup of private repositories.
-silent
Suppress all output
-version
Print binary version
For more visit https://qvl.io/ghbackup.
## Install
- Note that `ghbackup` uses `git` under the hood. Please make sure it is installed on your system.
- With [Go](https://golang.org/):
```
go get qvl.io/ghbackup
```
- With [Homebrew](http://brew.sh/):
```
brew install qvl/tap/ghbackup
```
- Download binary: https://github.com/qvl/ghbackup/releases
## Automation
Mostly, we like to setup backups to run automatically in an interval.
Let's setup `ghbackup` on a Linux server and make it run daily at 1am. This works similar on other platforms.
There are different tools to do this:
### systemd and sleepto
*Also see [this tutorial](https://jorin.me/automating-github-backup-with-ghbackup/).*
[systemd](https://freedesktop.org/wiki/Software/systemd/) runs on most Linux systems and using [sleepto](https://qvl.io/sleepto) it's easy to create a service to schedule a backup.
- Create a new unit file:
``` sh
sudo touch /etc/systemd/system/ghbackup.service && sudo chmod 644 $_
```
- Edit file:
```
[Unit]
Description=GitHub backup
After=network.target
[Service]
User=jorin
ExecStart=/PATH/TO/sleepto -hour 1 /PATH/TO/ghbackup -account qvl /home/USER/github
Restart=always
[Install]
WantedBy=multi-user.target
```
- Replace the paths with your options.
- Start service and enable it on boot:
``` sh
sudo systemctl daemon-reload
sudo systemctl enable --now ghbackup
```
- Check if service is running:
``` sh
systemctl status ghbackup
```
### Cron
Cron is a job scheduler that already runs on most Unix systems.
- Run `crontab -e`
- Add a new line and replace `NAME` and `DIR` with your options:
``` sh
0 1 * * * ghbackup -account NAME DIR
```
For example:
``` sh
0 1 * * * ghbackup -account qvl /home/qvl/backup-qvl
```
### Sending statistics
The last line of the output contains a summary.
You can use this to collect statistics about your backups.
An easy way would be to use a [Slack hook](https://api.slack.com/incoming-webhooks) and send it like this:
```sh
ghbackup -secret $GITHUB_TOKEN $DIR \
| tail -n1 \
| xargs -I%% curl -s -X POST --data-urlencode 'payload={"text": "%%"}' $SLACK_HOOK
```
## What happens?
Get all repositories of a GitHub account.
Save them to a folder.
Update already cloned repositories.
Best served as a scheduled job to keep your backups up to date!
## Limits
`ghbackup` is about repositories.
There are other solutions if you like to backup issues and wikis.
## Use as Go package
From another Go program you can directly use the `ghbackup` sub-package.
Have a look at the [GoDoc](https://godoc.org/qvl.io/ghbackup/ghbackup).
## Development
Make sure to use `gofmt` and create a [Pull Request](https://github.com/qvl/ghbackup/pulls).
### Releasing
Push a new Git tag and [GoReleaser](https://github.com/goreleaser/releaser) will automatically create a release.
## License
[MIT](./license)
| Java |
version https://git-lfs.github.com/spec/v1
oid sha256:a2aca9cd81f31f3e9e83559fdcfa84d3ee900090ee4baeb2bae129e9d06473eb
size 1264
| Java |
const exec = require('child_process').exec
const path = require('path')
const fs = require('fs')
const execPath = process.execPath
const binPath = path.dirname(execPath)
const dep = path.join(execPath, '../../lib/node_modules/dep')
const repository = 'https://github.com/depjs/dep.git'
const bin = path.join(dep, 'bin/dep.js')
process.stdout.write(
'exec: git' + [' clone', repository, dep].join(' ') + '\n'
)
exec('git clone ' + repository + ' ' + dep, (e) => {
if (e) throw e
process.stdout.write('link: ' + bin + '\n')
process.stdout.write(' => ' + path.join(binPath, 'dep') + '\n')
fs.symlink(bin, path.join(binPath, 'dep'), (e) => {
if (e) throw e
})
})
| Java |
using MongoDB.Driver;
namespace AspNet.Identity.MongoDB
{
public class IndexChecks
{
public static void EnsureUniqueIndexOnUserName<TUser>(IMongoCollection<TUser> users)
where TUser : IdentityUser
{
var userName = Builders<TUser>.IndexKeys.Ascending(t => t.UserName);
var unique = new CreateIndexOptions {Unique = true};
users.Indexes.CreateOneAsync(userName, unique);
}
public static void EnsureUniqueIndexOnRoleName<TRole>(IMongoCollection<TRole> roles)
where TRole : IdentityRole
{
var roleName = Builders<TRole>.IndexKeys.Ascending(t => t.Name);
var unique = new CreateIndexOptions {Unique = true};
roles.Indexes.CreateOneAsync(roleName, unique);
}
public static void EnsureUniqueIndexOnEmail<TUser>(IMongoCollection<TUser> users)
where TUser : IdentityUser
{
var email = Builders<TUser>.IndexKeys.Ascending(t => t.Email);
var unique = new CreateIndexOptions {Unique = true};
users.Indexes.CreateOneAsync(email, unique);
}
}
} | Java |
class SystemModule < ActiveRecord::Base
attr_accessible :name
def self.CUSTOMER
readonly.find_by_name("Customer")
end
def self.USER
readonly.find_by_name("User")
end
def self.CONTACT
readonly.find_by_name("Contact")
end
end
| Java |
# github-language-rainbow
Just look at the colors
| Java |
package org.aikodi.chameleon.support.statement;
import org.aikodi.chameleon.core.declaration.Declaration;
import org.aikodi.chameleon.core.element.ElementImpl;
import org.aikodi.chameleon.core.lookup.DeclarationSelector;
import org.aikodi.chameleon.core.lookup.LookupContext;
import org.aikodi.chameleon.core.lookup.LookupException;
import org.aikodi.chameleon.core.lookup.SelectionResult;
import org.aikodi.chameleon.core.validation.Valid;
import org.aikodi.chameleon.core.validation.Verification;
import org.aikodi.chameleon.oo.statement.ExceptionSource;
import org.aikodi.chameleon.oo.statement.Statement;
import org.aikodi.chameleon.util.association.Multi;
import java.util.Collections;
import java.util.List;
/**
* A list of statement expressions as used in the initialization clause of a for
* statement. It contains a list of statement expressions.
*
* @author Marko van Dooren
*/
public class StatementExprList extends ElementImpl implements ForInit, ExceptionSource {
public StatementExprList() {
}
/**
* STATEMENT EXPRESSIONS
*/
private Multi<StatementExpression> _statementExpressions = new Multi<StatementExpression>(this);
public void addStatement(StatementExpression statement) {
add(_statementExpressions, statement);
}
public void removeStatement(StatementExpression statement) {
remove(_statementExpressions, statement);
}
public List<StatementExpression> statements() {
return _statementExpressions.getOtherEnds();
}
@Override
public StatementExprList cloneSelf() {
return new StatementExprList();
}
public int getIndexOf(Statement statement) {
return statements().indexOf(statement) + 1;
}
public int getNbStatements() {
return statements().size();
}
@Override
public List<? extends Declaration> locallyDeclaredDeclarations() throws LookupException {
return declarations();
}
@Override
public List<? extends Declaration> declarations() throws LookupException {
return Collections.EMPTY_LIST;
}
@Override
public LookupContext localContext() throws LookupException {
return language().lookupFactory().createLocalLookupStrategy(this);
}
@Override
public <D extends Declaration> List<? extends SelectionResult<D>> declarations(DeclarationSelector<D> selector)
throws LookupException {
return Collections.emptyList();
}
@Override
public Verification verifySelf() {
return Valid.create();
}
}
| Java |
"use strict";
ace.define("ace/snippets/matlab", ["require", "exports", "module"], function (e, t, n) {
"use strict";
t.snippetText = undefined, t.scope = "matlab";
}); | Java |
(function(){
/**
* PubSub implementation (fast)
*/
var PubSub = function PubSub( defaultScope ){
if (!(this instanceof PubSub)){
return new PubSub( defaultScope );
}
this._topics = {};
this.defaultScope = defaultScope || this;
};
PubSub.prototype = {
/**
* Subscribe a callback (or callbacks) to a topic (topics).
*
* @param {String|Object} topic The topic name, or a config with key/value pairs of { topic: callbackFn, ... }
* @param {Function} fn The callback function (if not using Object as previous argument)
* @param {Object} scope (optional) The scope to bind callback to
* @param {Number} priority (optional) The priority of the callback (higher = earlier)
* @return {this}
*/
subscribe: function( topic, fn, scope, priority ){
var listeners = this._topics[ topic ] || (this._topics[ topic ] = [])
,orig = fn
,idx
;
// check if we're subscribing to multiple topics
// with an object
if ( Physics.util.isObject( topic ) ){
for ( var t in topic ){
this.subscribe( t, topic[ t ], fn, scope );
}
return this;
}
if ( Physics.util.isObject( scope ) ){
fn = Physics.util.bind( fn, scope );
fn._bindfn_ = orig;
} else if (!priority) {
priority = scope;
}
fn._priority_ = priority;
idx = Physics.util.sortedIndex( listeners, fn, '_priority_' );
listeners.splice( idx, 0, fn );
return this;
},
/**
* Unsubscribe function from topic
* @param {String} topic Topic name
* @param {Function} fn The original callback function
* @return {this}
*/
unsubscribe: function( topic, fn ){
var listeners = this._topics[ topic ]
,listn
;
if (!listeners){
return this;
}
for ( var i = 0, l = listeners.length; i < l; i++ ){
listn = listeners[ i ];
if ( listn._bindfn_ === fn || listn === fn ){
listeners.splice(i, 1);
break;
}
}
return this;
},
/**
* Publish data to a topic
* @param {Object|String} data
* @param {Object} scope The scope to be included in the data argument passed to callbacks
* @return {this}
*/
publish: function( data, scope ){
if (typeof data !== 'object'){
data = { topic: data };
}
var topic = data.topic
,listeners = this._topics[ topic ]
,l = listeners && listeners.length
;
if ( !topic ){
throw 'Error: No topic specified in call to world.publish()';
}
if ( !l ){
return this;
}
data.scope = data.scope || this.defaultScope;
while ( l-- ){
data.handler = listeners[ l ];
data.handler( data );
}
return this;
}
};
Physics.util.pubsub = PubSub;
})(); | Java |
function fixPosition() {
console.log($(window).scrollTop());
// if its anywhee but at the very top of the screen, fix it
if ($(window).scrollTop() >= headerHeight) { // magic number offset that just feels right to prevent the 'bounce'
// if (headPosition.top > 0){
$('body').addClass('js-fix-positions');
}
// otherwise, make sure its not fixed
else {
$('body').removeClass('js-fix-positions');
}
};
//Generate the weight guide meter with JS as its pretty useless without it, without some server side intervention
function createBasketWeightGuide(){
// create the element for the guide
$('.af__basket__weight-guide--label').after('<div class="js-af__weight-guide__wrapper"></div>');
$('.js-af__weight-guide__wrapper').append('<div class="js-af__weight-guide__meter"></div>');
$('.af__product__add-to-basket').submit(function(e){
e.preventDefault();
//var $multiplier=
weightGuideListener();
})
}
function weightGuideListener(){
var $bar = $('.js-af__weight-guide__meter');
//Didnt work as expected, so used this for speed: http://stackoverflow.com/questions/12945352/change-width-on-click-using-jquery
var $percentage = (100 * parseFloat($bar.css('width')) / parseFloat($bar.parent().css('width')) +10 + '%');
$bar.css("width", $percentage);
var $message = $('.af__basket__weight-guide--cta');
currentWidth=parseInt($percentage);
console.log(currentWidth);
// cannot use switch for less than
if (currentWidth <= 21 ){
$message.text('Plenty of room');
}
else if (currentWidth <= 45){
$bar.css('background-color', '#ee0');
}
else if (currentWidth <= 65){
$bar.css('background-color', '#c1ea39');
$message.text('Getting there...')
}
else if (currentWidth <= 80){
$message.text('Room for a little one?');
}
else if (currentWidth <= 89){
$message.text('Almost full!');
}
else if (currentWidth >= 95 && currentWidth <= 99){
$message.text('Lookin\' good!');
}
else if (currentWidth <= 99.9){
$bar.css('background-color', '#3ece38');
}
else {
$bar.css('background-color', '#d00');
$bar.css("width", "100%");
$message.text('(Delivery band 2 logic)');
}
}
function selectOnFocus(){
$('.af__product__add-to-basket input').focus(function(){
this.select();
})
};
$(document).ready(function(){
headerHeight=$('.af__header').outerHeight(); // icnludes padding and margins
scrollIntervalID = setInterval(fixPosition, 16); // = 60 FPS
createBasketWeightGuide();
selectOnFocus();
});
| Java |
<?php
return [
'@class' => 'Grav\\Common\\File\\CompiledYamlFile',
'filename' => '/Users/kenrickkelly/Sites/hokui/user/plugins/admin/languages/tlh.yaml',
'modified' => 1527231007,
'data' => [
'PLUGIN_ADMIN' => [
'LOGIN_BTN_FORGOT' => 'lIj',
'BACK' => 'chap',
'NORMAL' => 'motlh',
'YES' => 'HIja\'',
'NO' => 'Qo\'',
'DISABLED' => 'Qotlh'
]
]
];
| Java |
#!/usr/bin/env bash
# Run a raspberry pi as ulnoiot gateway (wifi router and mqtt_broker)
#
# To enable this,
# make sure ulnoiot-run script is porperly setup (for example in /home/pi/bin)
# add the following to the end of /etc/rc.local with adjusted location of the
# run-script:
# export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
# /home/pi/bin/ulnoiot exec /home/pi/ulnoiot/lib/system_boot/raspi-boot.sh"
#
# Also disable all network devices in /etc/network/interfaces apart lo and wlan1
# and make sure that wlan1 configuration looks like this (replace /home/pi/ulnoiot
# with the respective ULNOIOT_ROOT):
# allow-hotplug wlan1
# iface wlan1 inet manual
# pre-up /home/pi/bin/ulnoiot exec /home/pi/ulnoiot/lib/system_boot/raspi-pre-up.sh
# wpa-conf /run/uiot_wpa_supplicant.conf
[ "$ULNOIOT_ACTIVE" = "yes" ] || { echo "ulnoiot not active, aborting." 1>&2;exit 1; }
source "$ULNOIOT_ROOT/bin/read_boot_config"
# Try to guess user
if [[ $ULNOIOT_ROOT =~ '/home/([!/]+)/ulnoiot' ]]; then
ULNOIOT_USER=${BASH_REMATCH[1]}
else
ULNOIOT_USER=ulnoiot
fi
if [[ "ULNOIOT_AP_PASSWORD" ]]; then # pw was given, so start an accesspoint
# start accesspoint and mqtt_broker
(
sleep 15 # let network devices start
cd "$ULNOIOT_ROOT"
tmux new-session -d -n AP -s UIoTSvrs \
"./run" exec accesspoint \; \
new-window -d -n MQTT \
"./run" exec mqtt_broker \; \
new-window -d -n nodered \
su - $ULNOIOT_USER -c 'ulnoiot exec nodered_starter' \; \
new-window -d -n cloudcmd \
su - $ULNOIOT_USER -c 'ulnoiot exec cloudcmd_starter' \; \
new-window -d -n dongle \
su - $ULNOIOT_USER -c 'ulnoiot exec dongle_starter' \;
) &
fi # accesspoint check
| Java |
import React from 'react';
import ReactDOM from 'react-dom';
import _ from 'underscore';
import babel from 'babel-core/browser';
import esprima from 'esprima';
import escodegen from 'escodegen';
import estraverse from 'estraverse';
import Codemirror from 'react-codemirror';
import classNames from 'classnames';
import { iff, default as globalUtils } from 'app/utils/globalUtils';
import './styles/app.less';
import 'react-codemirror/node_modules/codemirror/lib/codemirror.css';
import 'react-codemirror/node_modules/codemirror/theme/material.css';
import 'app/modules/JsxMode';
const localStorage = window.localStorage;
const TAB_SOURCE = 'SOURCE';
const TAB_TRANSCODE = 'TRANSCODE';
const LiveDemoApp = React.createClass({
getInitialState() {
return {
sourceCode: '',
transCode: '',
transError: '',
tab: TAB_SOURCE,
func: function() { }
};
},
componentWillMount() {
this._setSource(localStorage.getItem('sourceCode') || '');
},
componentDidMount() {
this._renderPreview();
},
componentDidUpdate() {
this._renderPreview();
},
render() {
const {
sourceCode,
transCode,
tab,
transError
} = this.state;
const showSource = (tab === TAB_SOURCE);
const cmOptions = {
lineNumbers: true,
readOnly: !showSource,
mode: 'jsx',
theme: 'material',
tabSize: 2,
smartIndent: true,
indentWithTabs: false
};
const srcTabClassName = classNames({
'otsLiveDemoApp-tab': true,
'otsLiveDemoApp-active': showSource
});
const transTabClassName = classNames({
'otsLiveDemoApp-tab': true,
'otsLiveDemoApp-active': !showSource
});
console.log((transCode || transError));
return (
<div className='otsLiveDemoApp'>
<div className='otsLiveDemoApp-tabs'>
<button className={srcTabClassName} onClick={this._onSrcClick}>Source</button>
<button className={transTabClassName} onClick={this._onTransClick}>Transcode</button>
</div>
<div className='otsLiveDemoApp-src'>
<Codemirror
value={showSource ? sourceCode : (transCode || transError)}
onChange={this._onChangeEditor}
options={cmOptions}
/>
</div>
</div>
);
},
_onChangeEditor(value) {
const { tab } = this.state;
if (tab === TAB_SOURCE) {
this._setSource(value);
}
},
_onSrcClick() {
this.setState({
tab: TAB_SOURCE
});
},
_onTransClick() {
this.setState({
tab: TAB_TRANSCODE
});
},
_setSource(sourceCode) {
localStorage.setItem('sourceCode', sourceCode);
const dependencies = [];
let transCode;
let transError;
try {
const es5trans = babel.transform(sourceCode);
let uniqueId = 0;
estraverse.replace(es5trans.ast.program, {
enter(node, parent) {
if (
node.type === 'CallExpression' &&
node.callee.type === 'Identifier' &&
node.callee.name === 'require' &&
node.arguments.length === 1 &&
node.arguments[0].type === 'Literal'
) {
const dep = {
identifier: '__DEPENDENCY_'+ (uniqueId++) ,
depName: node.arguments[0].value
};
dependencies.push(dep);
return {
name: dep.identifier,
type: 'Identifier'
};
}
else if (
node.type === 'AssignmentExpression' &&
node.left.type === 'MemberExpression' &&
node.left.object.type === 'Identifier' &&
node.left.object.name === 'module' &&
node.left.property.type === 'Identifier' &&
node.left.property.name === 'exports'
) {
return {
type: 'ReturnStatement',
argument: node.right
}
}
}
});
transCode = escodegen.generate(es5trans.ast.program);
}
catch (e) {
const msg = 'Error transpiling source code: ';
transError = msg + e.toString();
globalUtils.error(msg, e);
}
this.setState({
sourceCode,
transCode,
transError
});
if (transCode) {
try {
const fnConstArgs = [{ what: 'aaa'}].concat(dependencies.map((dep) => {
return dep.identifier;
}));
fnConstArgs.push('exports');
fnConstArgs.push(transCode);
this.setState({
func: new (Function.prototype.bind.apply(Function, fnConstArgs))
});
}
catch(e) {
console.error('Runtime Error', e);
}
}
},
_renderPreview() {
const { func } = this.state;
const { Component, error } = (() => {
try {
return {
Component: func(React, {})
};
}
catch(e) {
return {
error: e
};
}
})();
try {
if (Component) {
ReactDOM.render(<Component />, document.getElementById('preview'));
}
else if (error) {
ReactDOM.render(<div className='otsLiveDemoApp-error'>{error.toString()}</div>, document.getElementById('preview'));
}
}
catch (e) {
globalUtils.error('Fatal error rendering preview: ', e);
}
}
});
ReactDOM.render(<LiveDemoApp />, document.getElementById('editor'));
// const newProgram = {
// type: 'Program',
// body: [
// {
// type: 'CallExpression',
// callee: {
// type: 'FunctionExpression',
// id: null,
// params: dependencies.map((dep) => {
// return {
// type: 'Identifier',
// name: dep.identifier
// }
// }),
// body: {
// type: 'BlockStatement',
// body: es5trans.ast.program.body
// }
// },
// arguments: []
// }
// ]
// }; | Java |
/** @babel */
/* eslint-env jasmine, atomtest */
/*
This file contains verifying specs for:
https://github.com/sindresorhus/atom-editorconfig/issues/118
*/
import fs from 'fs';
import path from 'path';
const testPrefix = path.basename(__filename).split('-').shift();
const projectRoot = path.join(__dirname, 'fixtures');
const filePath = path.join(projectRoot, `test.${testPrefix}`);
describe('editorconfig', () => {
let textEditor;
const textWithoutTrailingWhitespaces = 'I\nam\nProvidence.';
const textWithManyTrailingWhitespaces = 'I \t \nam \t \nProvidence.';
beforeEach(() => {
waitsForPromise(() =>
Promise.all([
atom.packages.activatePackage('editorconfig'),
atom.workspace.open(filePath)
]).then(results => {
textEditor = results[1];
})
);
});
afterEach(() => {
// remove the created fixture, if it exists
runs(() => {
fs.stat(filePath, (err, stats) => {
if (!err && stats.isFile()) {
fs.unlink(filePath);
}
});
});
waitsFor(() => {
try {
return fs.statSync(filePath).isFile() === false;
} catch (err) {
return true;
}
}, 5000, `removed ${filePath}`);
});
describe('Atom being set to remove trailing whitespaces', () => {
beforeEach(() => {
// eslint-disable-next-line camelcase
textEditor.getBuffer().editorconfig.settings.trim_trailing_whitespace = true;
// eslint-disable-next-line camelcase
textEditor.getBuffer().editorconfig.settings.insert_final_newline = false;
});
it('should strip trailing whitespaces on save.', () => {
textEditor.setText(textWithManyTrailingWhitespaces);
textEditor.save();
expect(textEditor.getText().length).toEqual(textWithoutTrailingWhitespaces.length);
});
});
});
| Java |
/*
* Generated by class-dump 3.3.4 (64 bit).
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard.
*/
#import <HomeSharing/HSRequest.h>
@interface HSItemDataRequest : HSRequest
{
}
+ (id)requestWithDatabaseID:(unsigned int)arg1 itemID:(unsigned long long)arg2 format:(id)arg3;
- (id)initWithDatabaseID:(unsigned int)arg1 itemID:(unsigned long long)arg2 format:(id)arg3;
@end
| Java |
/*
* Generated by class-dump 3.3.4 (64 bit).
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard.
*/
#import <Foundation/NSPredicateOperator.h>
@interface NSCompoundPredicateOperator : NSPredicateOperator
{
}
+ (id)notPredicateOperator;
+ (id)orPredicateOperator;
+ (id)andPredicateOperator;
- (_Bool)evaluatePredicates:(id)arg1 withObject:(id)arg2 substitutionVariables:(id)arg3;
- (_Bool)evaluatePredicates:(id)arg1 withObject:(id)arg2;
- (id)symbol;
- (id)predicateFormat;
- (id)copyWithZone:(struct _NSZone *)arg1;
@end
| Java |
import React from "react"
import { injectIntl } from "react-intl"
import { NavLink } from "react-router-dom"
import PropTypes from "prop-types"
import Styles from "./Navigation.css"
function Navigation({ intl }) {
return (
<ul className={Styles.list}>
<li><NavLink exact to="/" activeClassName={Styles.activeLink}>Home</NavLink></li>
<li><NavLink to="/redux" activeClassName={Styles.activeLink}>Redux</NavLink></li>
<li><NavLink to="/localization" activeClassName={Styles.activeLink}>Localization</NavLink></li>
<li><NavLink to="/markdown" activeClassName={Styles.activeLink}>Markdown</NavLink></li>
<li><NavLink to="/missing" activeClassName={Styles.activeLink}>Missing</NavLink></li>
</ul>
)
}
Navigation.propTypes = {
intl: PropTypes.object
}
export default injectIntl(Navigation)
| Java |
package main
import (
"bufio"
"os"
"fmt"
)
func main() {
counts := make(map[string]int)
fileReader, err := os.Open("words.txt")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer fileReader.Close()
scanner := bufio.NewScanner(fileReader)
// Set the split function for the scanning operation.
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
word := scanner.Text()
counts[word]++
}
if err := scanner.Err(); err != nil {
fmt.Fprintf(os.Stderr, "wordfreq: %v\n", err)
os.Exit(1)
}
fmt.Printf("word\t freq\n")
for c, n := range counts {
fmt.Printf("%q\t %d\n", c, n)
}
} | Java |
<?php
defined("_VALID_ACCESS") || die('Direct access forbidden');
$recordsets = Utils_RecordBrowserCommon::list_installed_recordsets();
$checkpoint = Patch::checkpoint('recordset');
$processed = $checkpoint->get('processed', array());
foreach ($recordsets as $tab => $caption) {
if (isset($processed[$tab])) {
continue;
}
$processed[$tab] = true;
Patch::require_time(3);
$tab = $tab . "_field";
$columns = DB::MetaColumnNames($tab);
if (!isset($columns['HELP'])) {
PatchUtil::db_add_column($tab, 'help', 'X');
}
$checkpoint->set('processed', $processed);
}
| Java |
const Marionette = require('backbone.marionette');
const MeterValuesView = require('./MeterValuesView.js');
module.exports = class EnergyMetersView extends Marionette.View {
template = Templates['capabilities/energy/meters'];
className() { return 'energy-meters'; }
regions() {
return {
metersByPeriod: '.metersByPeriod'
};
}
modelEvents() {
return {change: 'render'};
}
onRender() {
const metersView = new Marionette.CollectionView({
collection: this.model.metersByPeriod(),
childView: MeterValuesView
});
this.showChildView('metersByPeriod', metersView);
}
}
| Java |
//
// Copyright (c) 2017-2020 the rbfx project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#pragma once
#include <EASTL/utility.h>
#include "Tabs/Tab.h"
namespace Urho3D
{
class Asset;
class FileChange;
struct ResourceContextMenuArgs
{
ea::string resourceName_;
};
URHO3D_EVENT(E_RESOURCEBROWSERDELETE, ResourceBrowserDelete)
{
URHO3D_PARAM(P_NAME, Name); // String
}
/// Resource browser tab.
class ResourceTab : public Tab
{
URHO3D_OBJECT(ResourceTab, Tab)
public:
/// Construct.
explicit ResourceTab(Context* context);
/// Render content of tab window. Returns false if tab was closed.
bool RenderWindowContent() override;
/// Clear any user selection tracked by this tab.
void ClearSelection() override;
/// Serialize current user selection into a buffer and return it.
bool SerializeSelection(Archive& archive) override;
/// Signal set when user right-clicks a resource or folder.
Signal<void(const ResourceContextMenuArgs&)> resourceContextMenu_;
protected:
///
void OnLocateResource(StringHash, VariantMap& args);
/// Constructs a name for newly created resource based on specified template name.
ea::string GetNewResourcePath(const ea::string& name);
/// Select current item in attribute inspector.
void SelectCurrentItemInspector();
///
void OnEndFrame(StringHash, VariantMap&);
///
void OnResourceUpdated(const FileChange& change);
///
void ScanAssets();
///
void OpenResource(const ea::string& resourceName);
///
void RenderContextMenu();
///
void RenderDirectoryTree(const eastl::string& path = "");
///
void ScanDirTree(StringVector& result, const eastl::string& path);
///
void RenderDeletionDialog();
///
void StartRename();
///
bool RenderRenameWidget(const ea::string& icon = "");
/// Current open resource path.
ea::string currentDir_;
/// Current selected resource file name.
ea::string selectedItem_;
/// Assets visible in resource browser.
ea::vector<WeakPtr<Asset>> assets_;
/// Cache of directory names at current selected resource path.
StringVector currentDirs_;
/// Cache of file names at current selected resource path.
StringVector currentFiles_;
/// Flag which requests rescan of current selected resource path.
bool rescan_ = true;
/// Flag requesting to scroll to selection on next frame.
bool scrollToCurrent_ = false;
/// State cache.
ValueCache cache_{context_};
/// Frame at which rename started. Non-zero means rename is in-progress.
unsigned isRenamingFrame_ = 0;
/// Current value of text widget during rename.
ea::string renameBuffer_;
};
}
| Java |
const _ = require('lodash');
const en = {
modifiers: require('../../res/en').modifiers
};
const Types = require('../../lib/types');
const optional = {
optional: true
};
const repeatable = {
repeatable: true
};
const nullableNumber = {
type: Types.NameExpression,
name: 'number',
nullable: true
};
const nullableNumberOptional = _.extend({}, nullableNumber, optional);
const nullableNumberOptionalRepeatable = _.extend({}, nullableNumber, optional, repeatable);
const nullableNumberRepeatable = _.extend({}, nullableNumber, repeatable);
const nonNullableObject = {
type: Types.NameExpression,
name: 'Object',
nullable: false
};
const nonNullableObjectOptional = _.extend({}, nonNullableObject, optional);
const nonNullableObjectOptionalRepeatable = _.extend({}, nonNullableObject, optional, repeatable);
const nonNullableObjectRepeatable = _.extend({}, nonNullableObject, repeatable);
module.exports = [
{
description: 'nullable number',
expression: '?number',
parsed: nullableNumber,
described: {
en: {
simple: 'nullable number',
extended: {
description: 'number',
modifiers: {
nullable: en.modifiers.extended.nullable
},
returns: ''
}
}
}
},
{
description: 'postfix nullable number',
expression: 'number?',
newExpression: '?number',
parsed: nullableNumber,
described: {
en: {
simple: 'nullable number',
extended: {
description: 'number',
modifiers: {
nullable: en.modifiers.extended.nullable
},
returns: ''
}
}
}
},
{
description: 'non-nullable object',
expression: '!Object',
parsed: nonNullableObject,
described: {
en: {
simple: 'non-null Object',
extended: {
description: 'Object',
modifiers: {
nullable: en.modifiers.extended.nonNullable
},
returns: ''
}
}
}
},
{
description: 'postfix non-nullable object',
expression: 'Object!',
newExpression: '!Object',
parsed: nonNullableObject,
described: {
en: {
simple: 'non-null Object',
extended: {
description: 'Object',
modifiers: {
nullable: en.modifiers.extended.nonNullable
},
returns: ''
}
}
}
},
{
description: 'repeatable nullable number',
expression: '...?number',
parsed: nullableNumberRepeatable,
described: {
en: {
simple: 'nullable repeatable number',
extended: {
description: 'number',
modifiers: {
nullable: en.modifiers.extended.nullable,
repeatable: en.modifiers.extended.repeatable
},
returns: ''
}
}
}
},
{
description: 'postfix repeatable nullable number',
expression: '...number?',
newExpression: '...?number',
parsed: nullableNumberRepeatable,
described: {
en: {
simple: 'nullable repeatable number',
extended: {
description: 'number',
modifiers: {
nullable: en.modifiers.extended.nullable,
repeatable: en.modifiers.extended.repeatable
},
returns: ''
}
}
}
},
{
description: 'repeatable non-nullable object',
expression: '...!Object',
parsed: nonNullableObjectRepeatable,
described: {
en: {
simple: 'non-null repeatable Object',
extended: {
description: 'Object',
modifiers: {
nullable: en.modifiers.extended.nonNullable,
repeatable: en.modifiers.extended.repeatable
},
returns: ''
}
}
}
},
{
description: 'postfix repeatable non-nullable object',
expression: '...Object!',
newExpression: '...!Object',
parsed: nonNullableObjectRepeatable,
described: {
en: {
simple: 'non-null repeatable Object',
extended: {
description: 'Object',
modifiers: {
nullable: en.modifiers.extended.nonNullable,
repeatable: en.modifiers.extended.repeatable
},
returns: ''
}
}
}
},
{
description: 'postfix optional nullable number',
expression: 'number=?',
newExpression: '?number=',
parsed: nullableNumberOptional,
described: {
en: {
simple: 'optional nullable number',
extended: {
description: 'number',
modifiers: {
nullable: en.modifiers.extended.nullable,
optional: en.modifiers.extended.optional
},
returns: ''
}
}
}
},
{
description: 'postfix nullable optional number',
expression: 'number?=',
newExpression: '?number=',
parsed: nullableNumberOptional,
described: {
en: {
simple: 'optional nullable number',
extended: {
description: 'number',
modifiers: {
nullable: en.modifiers.extended.nullable,
optional: en.modifiers.extended.optional
},
returns: ''
}
}
}
},
{
description: 'postfix repeatable nullable optional number',
expression: '...number?=',
newExpression: '...?number=',
parsed: nullableNumberOptionalRepeatable,
described: {
en: {
simple: 'optional nullable repeatable number',
extended: {
description: 'number',
modifiers: {
nullable: en.modifiers.extended.nullable,
optional: en.modifiers.extended.optional,
repeatable: en.modifiers.extended.repeatable
},
returns: ''
}
}
}
},
{
description: 'postfix optional non-nullable object',
expression: 'Object=!',
newExpression: '!Object=',
parsed: nonNullableObjectOptional,
described: {
en: {
simple: 'optional non-null Object',
extended: {
description: 'Object',
modifiers: {
nullable: en.modifiers.extended.nonNullable,
optional: en.modifiers.extended.optional
},
returns: ''
}
}
}
},
{
description: 'postfix non-nullable optional object',
expression: 'Object!=',
newExpression: '!Object=',
parsed: nonNullableObjectOptional,
described: {
en: {
simple: 'optional non-null Object',
extended: {
description: 'Object',
modifiers: {
nullable: en.modifiers.extended.nonNullable,
optional: en.modifiers.extended.optional
},
returns: ''
}
}
}
},
{
description: 'postfix repeatable non-nullable optional object',
expression: '...Object!=',
newExpression: '...!Object=',
parsed: nonNullableObjectOptionalRepeatable,
described: {
en: {
simple: 'optional non-null repeatable Object',
extended: {
description: 'Object',
modifiers: {
nullable: en.modifiers.extended.nonNullable,
optional: en.modifiers.extended.optional,
repeatable: en.modifiers.extended.repeatable
},
returns: ''
}
}
}
}
];
| Java |
class ACLHelperMethod < ApplicationController
access_control :helper => :foo? do
allow :owner, :of => :foo
end
def allow
@foo = Foo.first
render inline: "<div><%= foo? ? 'OK' : 'AccessDenied' %></div>"
end
end
| Java |
<?php
namespace App\Application\Controllers\Traits;
trait HelpersTrait{
protected function checkIfArray($request){
return is_array($request) ? $request : [$request];
}
protected function createLog($action , $status , $messages = ''){
$data = [
'action' => $action,
'model' => $this->model->getTable(),
'status' => $status,
'user_id' => auth()->user()->id,
'messages' => $messages
];
$this->log->create($data);
}
} | Java |
/* 1023 组个最小数 (20 分)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
// 处理输入
int n = 10;
int quantities[n];
for (int i = 0; i < n; i++)
{
if (scanf("%d", &quantities[i]) != 1)
return EXIT_FAILURE;
}
// 组装数字
int nums[50] = {0};
int count = 0;
// 找到开头的数字
for (int i = 1; i < n; i++)
{
if (quantities[i] > 0)
{
nums[count] = i;
count++;
quantities[i]--;
break;
}
}
// 组装剩余的数字
for (int i = 0; i < n; i++)
{
while (quantities[i] > 0)
{
nums[count] = i;
count++;
quantities[i]--;
}
}
// 处理输出
for (int i = 0; i < count; i++)
{
printf("%d", nums[i]);
}
return EXIT_SUCCESS;
}
| Java |
<html><body>
<h4>Windows 10 x64 (19041.508)</h4><br>
<h2>_XPF_MCE_FLAGS</h2>
<font face="arial"> +0x000 MCG_CapabilityRW : Pos 0, 1 Bit<br>
+0x000 MCG_GlobalControlRW : Pos 1, 1 Bit<br>
+0x000 Reserved : Pos 2, 30 Bits<br>
+0x000 AsULONG : Uint4B<br>
</font></body></html> | Java |
angular.module('Reader.services.options', [])
.factory('options', function($rootScope, $q) {
var controllerObj = {};
options.onChange(function (changes) {
$rootScope.$apply(function () {
for (var property in changes) {
controllerObj[property] = changes[property].newValue;
}
});
});
return {
get: function (callback) {
options.get(function (values) {
$rootScope.$apply(function () {
angular.copy(values, controllerObj);
if (callback instanceof Function) {
callback(controllerObj);
}
});
});
return controllerObj;
},
set: function (values) {
options.set(values);
},
enableSync: options.enableSync,
isSyncEnabled: options.isSyncEnabled
};
}); | Java |
class UsersController < ApplicationController
def index
end
def show
@user = User.find(params[:id])
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update_attributes(user_params)
@user.geocode
else
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:city, :zip, :name)
end
end
| Java |
# blog
[](https://travis-ci.org/Lurk/blog)
Weekend project for self education
## backend configuration
create config.local.js on ./server directory with
```
module.exports = {
secret: 'some random text',
port: 3000,
greeting: 'blog server running on http://localhost:',
mongoose: 'mongodb://localhost/blog'
}
```
where:
- secret is random string and it should be defined for security reasons
- port is int, default is 3000
- greeting is text which will be printed on console when server starts successfully
- mongoose is mongodb connection string | Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="0;URL=../../openssl_sys/fn.SSL_CTX_set_read_ahead.html">
</head>
<body>
<p>Redirecting to <a href="../../openssl_sys/fn.SSL_CTX_set_read_ahead.html">../../openssl_sys/fn.SSL_CTX_set_read_ahead.html</a>...</p>
<script>location.replace("../../openssl_sys/fn.SSL_CTX_set_read_ahead.html" + location.search + location.hash);</script>
</body>
</html> | Java |
# TriDIYBio
Web site for TriDIYBio
## Workflow
Setup:
- `git clone https://github.com/Densaugeo/TriDIYBio.git`
- `npm install`
Making changes:
- `git pull`
- Make your changes and save files
- `node gen.js`
- `node test_server.js`
- `git commit -am "Commit message"`
- `npm run push`
| Java |
import Ember from 'ember';
import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
export default DS.RESTAdapter.extend(DataAdapterMixin, {
authorizer: 'authorizer:dspace',
initENVProperties: Ember.on('init', function() {
let ENV = this.container.lookupFactory('config:environment');
if (Ember.isPresent(ENV.namespace)) {
this.set('namespace', ENV.namespace);
}
if (Ember.isPresent(ENV.host)) {
this.set('host', ENV.host);
}
}),
//coalesceFindRequests: true, -> commented out, because it only works for some endpoints (e.g. items) and not others (e.g. communities)
ajax(url, type, hash) {
if (Ember.isEmpty(hash)) {
hash = {};
}
if (Ember.isEmpty(hash.data)) {
hash.data = {};
}
if (type === "GET") {
hash.data.expand = 'all'; //add ?expand=all to all GET calls
}
return this._super(url, type, hash);
}
});
| Java |
html {
height: 100%;
}
body {
background: #538eb8; /* For browsers that do not support gradients */
background: -webkit-linear-gradient(left top, #538eb8, #ffd044); /* For Safari 5.1 to 6.0 */
background: -o-linear-gradient(bottom right, #538eb8, #ffd044); /* For Opera 11.1 to 12.0 */
background: -moz-linear-gradient(bottom right, #538eb8, #ffd044); /* For Firefox 3.6 to 15 */
background: linear-gradient(to bottom right, #538eb8, #ffd044); /* Standard syntax */
}
.login-panel {
position:absolute;
top:25%;
left: 50%;
width: 400px;
transform: translate(-50%, -25%);
}
.form-login input[type="text"]
{
margin-bottom: -1px;
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
.form-login input[type="password"]
{
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.warning {
background-color: #fcf8e3;
}
.error {
background-color: #f2dede;
}
| Java |
function alertThanks (post) {
alert("Thanks for submitting a post!");
return post;
}
Telescope.callbacks.add("postSubmitClient", alertThanks);
| Java |
1. ping命令与ICMP 协议
ping」是用来探测本机与网络中另一主机之间是否可达的命令,如果两台主机之间ping不通,则表明这两台主机不能建立起连接。ping是定位网络通不通的一个重要手段。
ping 命令是基于 ICMP 协议来工作的,「 ICMP 」全称为 Internet 控制报文协议(Internet Control Message Protocol)。ping 命令会发送一份ICMP回显请求报文给目标主机,并等待目标主机返回ICMP回显应答。因为ICMP协议会要求目标主机在收到消息之后,必须返回ICMP应答消息给源主机,如果源主机在一定时间内收到了目标主机的应答,则表明两台主机之间网络是可达的。
详见:
- [每天都在用的Ping命令,它到底是什么?](https://zhuanlan.zhihu.com/p/45110873)
- [ICMP协议与ping原理](https://www.s0nnet.com/archives/icmp-ping)
2. telnet命令
telnet可以测试目的IP某个端口的连通性,假设目的IP为10.14.40.17,目的端口为22,telnet 10.14.40.17 22,如果进入一个可以输入指令的页面,则说明连通成功。如果最后报错,则说明连通失败。
详见:
- [利用Telnet进行HTTP访问过程的协议分析](https://zhuanlan.zhihu.com/p/61352013)
- [win10系统下用telnet完成一次简单的HTTP请求](https://blog.csdn.net/Mr_DouDo/article/details/79771303)
3. 调试线上代码的技巧
- 直接通过代理工具(fiddler、whistle等)将线上的静态资源请求代理到本地,这样就可以在本地调试线上环境的代码
- 直接在本地起个服务,然后将所有后台端口请求代理(fiddler、whistle等)到线上环境,这样也可以在本地调试线上环境的代码
- 如果是Vue的项目的话,可以通过以下方式开启调试模式
```
步骤如下:
1. 找到Vue构造函数如window.Vue(可以通过搜索Vue的某个实例方法,然后打个断点,将this(此时的this指向Vue)挂载到window上。Vue实例化挂载的元素节点的__vue__属性指向它的vue实例,也可以通过该实例去找Vue构造函数)
1.1. 或者可以找到挂载vue实例的dom节点, 通过${dom}.__vue__.constructor.super获取Vue构造函数
2. Vue.config.devtools=true
3. __VUE_DEVTOOLS_GLOBAL_HOOK__.emit('init', Vue)
```
那么只需要找到页面中的Vue,就可非常方便的打开开发者工具了。
在使用Vue源码的生命周期lifecycle.js代码中,Vue会将vm实例保存在$el元素的 __vue__ 对象上
```js
// @name Vue调试
// @description 在生产环境开启Vue.js devtools调试
(function () {
function findVueInstance($el) {
// console.log(`Finding Vue: ${$el.tagName}`)
let __vue__ = $el.__vue__;
if (__vue__) {
return __vue__;
} else {
let tagName = $el.tagName;
if (["SCRIPT", "STYLE"].indexOf(tagName) === -1) {
let children = [...$el.children];
children.some($child => {
__vue__ = findVueInstance($child);
return __vue__;
});
return __vue__;
} else {
return;
}
}
}
function getVue(obj) {
if (!!obj && obj._isVue) {
let $constructor = obj.constructor;
if (
$constructor.config &&
typeof $constructor.config.devtools === "boolean"
) {
return obj.constructor;
}
if (
$constructor.super &&
$constructor.super.config &&
typeof $constructor.super.config.devtools === "boolean"
) {
return $constructor.super;
}
}
return;
}
setTimeout(() => {
if (
typeof window.__VUE_DEVTOOLS_GLOBAL_HOOK__ === "object" &&
typeof __VUE_DEVTOOLS_GLOBAL_HOOK__.emit === "function"
) {
let $vm = findVueInstance(document.querySelector("body"));
let _Vue = getVue($vm);
if (_Vue) {
_Vue.config.devtools = true;
__VUE_DEVTOOLS_GLOBAL_HOOK__.emit("init", _Vue);
console.log(
`已启用Vue生产环境调试,如果无法看到Vue调试Tab,请关闭DevTools再打开`
);
}
}
}, 500);
})();
```
4. 利用Traceroute定位网络问题
- [路由追踪程序Traceroute分析与科普](https://www.freebuf.com/articles/network/118221.html)
5. 前端权限管理机制
6. 自定义事件需要额外传参
```
子组件:
this.emit('test', data);
父组件(arguments拿到原来子组件传过来的参数,后面部分继续额外传参):
<sub-item @test="doSth(arguments, 'another params')">
```
7. git Hooks
详见: https://git-scm.com/book/zh/v2/%E8%87%AA%E5%AE%9A%E4%B9%89-Git-Git-%E9%92%A9%E5%AD%90
https://segmentfault.com/a/1190000016357480
一般会在git的pre-commit钩子中进行lint检测,如果该钩子以非零值退出,Git 将放弃此次提交。
可以用 git commit --no-verify 来绕过这个环节
8. prop
prop 是单向数据流, 传进来的值,子组件不能改动,否则会报错。如果要在prop的基础上实现双向绑定,应该使用.sync修饰符,并且子组件要抛出对应的时间。如下:
```
// 父组件
<son-component :title.sync="title"></son-component>
// 子组件
this.$emit('update:title', newTitle)
```
9. git 设置对文件大小写敏感`
git 会根据操作系统的默认配置设置是否区分文件大小写, Windows和mac默认不区分文件名大小写的, linux默认区分大小写. 在Windows中, 当你创建一个文件后, 叫 readme.md 写入内容后 提交到线上代码仓库. 然后你在本地修改文件名为 Readme.md 接着你去提交, 发现代码没有变化.
为了避免这种情况,可以通过改变git的默认设置:
```bash
### 默认是true
git config --get core.ignorecase
## 更给设置
git config core.ignorecase false
```
10. RPC、HTTP服务的区别
RPC是远端过程调用,其调用协议通常包含传输协议和序列化协议。RPC的协议可以多种,包括TCP或者HTTP等形式都可以。RPC框架会在普通的协议传输上进一步面向服务进行封装。HTTP服务则只是一个狭义的某种协议的传输请求。
- [既然有 HTTP 请求,为什么还要用 RPC 调用?](https://www.zhihu.com/question/41609070)
- [深入理解 RPC](https://juejin.im/entry/57c866230a2b58006b204712)
- [聊聊 Node.js RPC(一)— 协议](https://www.yuque.com/egg/nodejs/dklip5)
- [聊聊 Node.js RPC(二)— 服务发现](https://www.yuque.com/egg/nodejs/mhgl9f)
11. peerDependencies
peerDependencies的目的是提示宿主环境去安装满足插件peerDependencies所指定依赖的包,然后在插件import或者require所依赖的包的时候,永远都是引用宿主环境统一安装的npm包,最终解决插件与所依赖包不一致的问题。
- [探讨npm依赖管理之peerDependencies](https://www.cnblogs.com/wonyun/p/9692476.html)
- [Peer Dependencies](https://nodejs.org/zh-cn/blog/npm/peer-dependencies/)
- [peerDependencies介绍及简析](https://arayzou.com/2016/06/23/peerDependencies%E4%BB%8B%E7%BB%8D%E5%8F%8A%E7%AE%80%E6%9E%90/)
12. 前端路由的原理
要想改变url并且页面不刷新,有以下方式:
1. 改变location的hash
2. 使用history的相关接口(pushState, replaceState, go, back, forward)
根据以上原理,通过监听hashchange事件(hash模式的路由)即可实现前端路由
通过监听popstate事件(history模式的路由)也可实现前端路由, 但有一点需要注意的是, popstate 事件只能监听除 history.pushState() 和 history.replaceState() 外 url 的变化, 所以还得对pushState和replaceState进行额外封装处理
- [彻底搞懂路由跳转:location 和 history 接口](https://segmentfault.com/a/1190000014120456)
- [MDN history](https://developer.mozilla.org/en-US/docs/Web/API/Window/history)
13. 如果想要改变页面url的query或者path而不引起刷新,可以使用history对象的相关接口,使用pushState和replaceState
- [MDN 在history中跳转]()
14. 前端大文件上传、切片上传(主要基于FileReader和Blob实现)、并行上传
- [前端大文件上传](https://juejin.im/post/5cf765275188257c6b51775f)
14. 理解DOMString、Document、FormData、Blob、File、ArrayBuffer数据类型
- [理解DOMString、Document、FormData、Blob、File、ArrayBuffer数据类型](https://www.zhangxinxu.com/wordpress/2013/10/understand-domstring-document-formdata-blob-file-arraybuffer/)
- [Blob对象](https://github.com/pfan123/Articles/issues/10)
- [细说Web API中的Blob](https://juejin.im/post/59e35d0e6fb9a045030f1f35)
- [前端图片canvas,file,blob,DataURL等格式转换](https://juejin.im/post/5b5187da51882519ec07fa41)
- [javascript处理二进制之ArrayBuffer](https://juejin.im/post/5c36a4ec6fb9a049d97566f2)
- [阮一峰 - 二进制数组](https://javascript.ruanyifeng.com/stdlib/arraybuffer.html)
- [MDN - ArrayBuffer](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
15. npm script和npm钩子的关系
[也许你不知道的npm-scripts](https://juejin.im/post/5caeffc6f265da03587bea9f)
[npm文档](https://docs.npmjs.com/misc/scripts)
[npm 相关知识点汇总](https://juejin.im/post/5d08d3d3f265da1b7e103a4d)
1. 用 githook、husky 和 lint-staged 构建代码检查工作流
- [官方文档 - 自定义 Git 钩子](https://git-scm.com/book/zh/v2/%E8%87%AA%E5%AE%9A%E4%B9%89-Git-Git-%E9%92%A9%E5%AD%90)
- [使用 Githook 实现团队 Coding Review 流程](https://www.jianshu.com/p/935409ce4c9a)
- [用 Git 钩子进行简单自动部署](https://aotu.io/notes/2017/04/10/githooks/index.html)
- [用 husky 和 lint-staged 构建超溜的代码检查工作流](https://segmentfault.com/a/1190000009546913)
- [【工具推荐】使用 husky 避免糟糕的 git commit](https://zhuanlan.zhihu.com/p/35913229)
- [手牵手使用Husky & Nodejs自定义你的Git钩子 ](https://github.com/PaicFE/blog/issues/10)
husky是一个npm包,安装后,可以快速的根据package.json配置创建git hook 脚本。yorkie是尤大从husky项目fork过来的进一步修改,并集成于vue-cli中,两者用法上的区别在以下:
Before
```json
{
"scripts": {
"precommit": "foo"
}
}
```
After
```json
{
"gitHooks": {
"pre-commit": "foo"
}
}
```
1. 快速打平数组的方法: join
对于多维数组,join会递归调用数组的toString方法将数组转换成字符串,再用分隔符隔开(没传分隔符默认是','),但分隔符只对最开始的第一维有效
```javascript
[[1,2, [7,8]], [3,4]].join() // 1,2,7,8,3,4
[[1,2, [7,8]], [3,4]].join('-') // 1,2,7,8-3,4
[[1,2, [7,8]], [3,4]].join().replace(/,/g, '-') // 1-2-7-8-3-4
[[1,2, [7,8]], [3,4]].toString() // 1,2,7,8,3,4
```
详见:
- [ES5/标准 ECMAScript 内置对象](https://www.w3.org/html/ig/zh/wiki/ES5/%E6%A0%87%E5%87%86_ECMAScript_%E5%86%85%E7%BD%AE%E5%AF%B9%E8%B1%A1#Array.prototype.join_.28separator.29)
18. nginx server_name的作用
在server_name这个配置中,nginx仅仅检查请求的“Host”头以决定该请求应由哪个虚拟主机来处理。如果Host头没有匹配任意一个虚拟主机,或者请求中根本没有包含Host头,那nginx会将请求分发到定义在此端口上的默认虚拟主机。在以上配置中,第一个被列出的虚拟主机即nginx的默认虚拟主机——这是nginx的默认行为。而且,可以显式地设置某个主机为默认虚拟主机,即在"listen"指令中设置"default_server"参数。
如果nginx中只配置一个server域的话,则nginx是不会去进行server_name的匹配的。因为只有一个server域,也就是这有一个虚拟主机,那么肯定是发送到该nginx的所有请求均是要转发到这一个域的,即便做一次匹配也是没有用的。还不如干脆直接就省了。如果一个http域的server域有多个,nginx才会根据$hostname去匹配server_name进而把请求转发到匹配的server域中。此时的匹配会按照匹配的优先级进行,一旦匹配成功进不会再进行匹配。
详见以下链接:
- [Nginx如何处理一个请求](https://tengine.taobao.org/nginx_docs/cn/docs/http/request_processing.html)
- [nginx 中通过server_name listen的方式配置多个服务器](https://blog.csdn.net/thlzjfefe/article/details/84489311)
- [理解Nginx中Server和Location的匹配逻辑](https://juejin.im/post/5c89f96f518825573a5e630b)
- [谁说前端不需要懂-Nginx反向代理与负载均衡](https://juejin.im/post/5b01336af265da0b8a67e5c9)
- [官方文档 - server_name](http://nginx.org/en/docs/http/server_names.html)
- [8分钟带你深入浅出搞懂Nginx](https://zhuanlan.zhihu.com/p/34943332)
19. 当用户最小化浏览器窗口或者切换到其他标签,可以通过Page Visibility API进行判断,这个 API 会发送一个 `visibilitychange` 事件,这样事件监听器就能感知到状态的变化了。对于一些页面定时请求,可以给予这个API进行判断,但页面切换和缩小的时候减小定时请求数,提高性能。不少视频网站也会根据这个API禁止防止用户进行切换。详见以下链接:
- [MDN Page Visibility API](https://developer.mozilla.org/zh-CN/docs/Web/API/Page_Visibility_API)
- [ifvisible.js, 对Visibility API的封装](https://github.com/serkanyersen/ifvisible.js)
20. Symbol
Symbol 主要的两个作用是:
- (1)防止属性名冲突
- (2)模拟私有属性
详见以下链接:
[JavaScript 为什么要有 Symbol 类型?](https://juejin.im/post/5c9042036fb9a070eb266fd6)
[ES6入门 - Symbol](http://es6.ruanyifeng.com/#docs/symbol)
[深入浅出 ES6(八):Symbols](https://www.infoq.cn/article/es6-in-depth-symbols)
21. 生成水印的方式(为了防止水印被上层的元素遮住,水印一般设置在顶层)
- (1) 通过canvas 对水印的文字生成图片,然后通过canvas.toDataURL将图片转换成base64的dataURL, 设为顶层水印元素的背景图(由于小程序中的canvas没有toDataURL方法, 可使用wx.canvasGetImageData接口获取其Uint8ClampedArray图像像素点数据, 然后通过upng.js库将其转换成base64)
- (2) 通过dom节点生成,即在顶层水印元素那里添加文字,设置成半透明显示
- 还有一要点是顶层元素需设置pointer-events:none
```javascript
// 常见的水印生成的canvas代码
let canvas
let ctx
// merge the default value
function mergeOptions(options) {
return Object.assign({
width: 250,
height: 80,
color: '#a0a0a0',
alpha: 0.8,
font: '10px Arial'
}, options)
}
/**
* alimask( text, options ) -> string
* - text (String): this text on water mask.
* - options(Object): water mask options.
* With keys:
{
width: 250,
height: 80,
color: '#ebebeb',
alpha: 0.8,
font: '10px Arial'
}
*
* return base64 of background water mask image.
* */
export default function(text, options) {
if (!canvas || !ctx) {
canvas = document.createElement('canvas')
ctx = canvas && canvas.getContext && canvas.getContext('2d')
if (!canvas || !ctx) return '' // if not exist also, then return blank.
}
const opts = mergeOptions(options)
const { width } = opts
const { height } = opts
canvas.width = width
canvas.height = height
ctx.clearRect(0, 0, width, height) // clear the canvas
// ctx.globalAlpha = 0 // backgroud is alpha
ctx.fillStyle = 'white' // no need because of alipha = 0;
ctx.fillRect(0, 0, width, height)
ctx.globalAlpha = opts.alpha // text alpha
ctx.fillStyle = opts.color
ctx.font = opts.font
ctx.textAlign = 'left'
ctx.textBaseline = 'bottom'
ctx.translate(width * 0.1, height * 0.9) // margin: 10
ctx.rotate(-Math.PI / 12) // 15 degree
ctx.fillText(text, 0, 0)
return canvas.toDataURL()
}
```
```css
/* canvas中的css代码 */
.watermark {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
pointer-events: none;
z-index: 9;
opacity: .1;
}
```
详见:
- [小程序--页面添加水印](https://juejin.im/post/5c8c8384e51d4509942b9249)
- [MDN - HTMLCanvasElement.toDataURL()](https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLCanvasElement/toDataURL)
- [mdn - pointer-events](https://developer.mozilla.org/zh-CN/docs/Web/CSS/pointer-events)
- [CSS3 pointer-events:none应用举例及扩展](https://www.zhangxinxu.com/wordpress/2011/12/css3-pointer-events-none-javascript/)
- [小程序官方文档 - wx.canvasGetImageData](https://developers.weixin.qq.com/miniprogram/dev/api/canvas/wx.canvasGetImageData.html)
22. 实现类似element UI的固定列
- [一起来聊聊table组件的固定列](https://blog.kaolafed.com/2017/12/25/%E4%B8%80%E8%B5%B7%E6%9D%A5%E8%81%8A%E8%81%8Atable%E7%BB%84%E4%BB%B6%E7%9A%84%E5%9B%BA%E5%AE%9A%E5%88%97/)
23. sass-loader的导入
webpack 提供一种解析文件的高级的机制。sass-loader 使用 Sass 的 custom importer 特性,将所有的 query 传递给 webpack 的解析引擎(resolving engine)。只要它们前面加上 ~,告诉 webpack 它不是一个相对路径,这样就可以 import 导入 node_modules 目录里面的 sass 模块:
```javascript
@import "~bootstrap/dist/css/bootstrap";
```
重要的是,只在前面加上 ~,因为 ~/ 会解析到主目录(home directory)。webpack 需要区分 bootstrap 和 ~bootstrap,因为 CSS 和 Sass 文件没有用于导入相关文件的特殊语法。@import "file" 与 @import "./file"; 这两种写法是相同的
```javascript
@import "~@/bootstrap/dist/css/bootstrap";
```
```javascript
{
resolve: {
alias: {
'@': resolve('src')
}
}
}
```
在以上例子中, @代表在webpack配置alias中的src目录, ~代表着项目根目录。
- [vue scss加载配置以及~@的使用](https://www.yuque.com/yiruans/qdnote/ur7d9q?language=en-us)
- [webpack中文文档 sass-loader](https://webpack.docschina.org/loaders/sass-loader/)
24. 禁止复制(或者修改复制的内容)
禁止操作:
```javascript
// 禁止右键菜单
document.body.oncontextmenu = e => {
console.log(e, '右键');
return false;
// e.preventDefault();
};
// 禁止文字选择
document.body.onselectstart = e => {
console.log(e, '文字选择');
return false;
// e.preventDefault();
};
// 禁止复制
document.body.oncopy = e => {
console.log(e, 'copy');
return false;
// e.preventDefault();
}
// 禁止剪切
document.body.oncut = e => {
console.log(e, 'cut');
return false;
// e.preventDefault();
};
// 禁止粘贴
document.body.onpaste = e => {
console.log(e, 'paste');
return false;
// e.preventDefault();
};
// css 禁止文本选择 这样不会触发js
body {
user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
```
修改操作:
```javascript
document.body.addEventListener('copy', function(e) {
const warningText = '数据管理内容禁止复制粘贴!'
let clipboardData = (e.clipboardData || window.clipboardData)
clipboardData.setData('text/plain', warningText)
console.warn(warningText)
e.preventDefault()
})
```
读取操作:
```javascript
let copyFont = window.getSelection(0).toString(); // 被复制的文字
```
* 详见[前端er怎样操作剪切复制以及禁止复制+破解等](https://juejin.im/post/5b66993ee51d451924734c35)
25. 计算指数时,可以使用 ** 运算符。
```javascript
// bad
const binary = Math.pow(2, 10);
// good
const binary = 2 ** 10;
```
26. webview中的input框被弹起的键盘遮挡的问题
```JavaScript
// 简单的判断
listenerKeyboardChange() {
if (IS_ANDROID) {
const originHeight = document.documentElement.clientHeight;
window.addEventListener('resize', (event) => {
const resizeheight = document.documentElement.clientHeight;
console.log('resize documentElement.clientHeight:', document.documentElement.clientHeight);
if (resizeheight < originHeight) {
console.log('Android 键盘已打开', event);
this.props.onKeyboardOpen(event);
} else {
console.log('Android 键盘已收起', event);
this.props.onKeyboardClose(event);
}
}, false);
}
if (IS_IOS) {
this.inputEle.current.addEventListener('focus', (event) => {
console.log('iOS 键盘已打开', event);
this.props.onKeyboardOpen(event);
}, false);
this.inputEle.current.addEventListener('blur', (event) => {
console.log('iOS 键盘已收起', event);
this.props.onKeyboardClose(event);
}, false);
}
}
```
更多参考:
* [如何用 js 获取虚拟键盘高度?(适用所有平台)](https://segmentfault.com/a/1190000010693229)
* [搜遍整个谷歌, 只有我是在认真解决安卓端hybrid app键盘遮挡输入框的问题](https://zhuanlan.zhihu.com/p/86582914)
27. CSS多行文字省略号
```css
overflow:hidden;
text-overflow:ellipsis;
display:-webkit-box;
-webkit-line-clamp:2; (两行文字)
-webkit-box-orient:vertical;
```
更多参考:
* [CSS单行、多行文本溢出显示省略号](https://segmentfault.com/a/1190000009262433)
28. js库实现按需加载的实现
```
import { Button } from 'antd';
```
像这样的形式导入某个组件, 通常情况下会加载整个antd组件库, 再从整个库中导入其中的Button组件, 这会影响应用的网络性能
所以一般可通过这种形式实现按需加载
```
import Button from 'antd/lib/button';
import 'antd/es/button/style'; // 或者 antd/es/button/style/css 加载 css 文件
```
但是如果你使用了 babel,那么可以使用 babel-plugin-import 来进行按需加载,加入这个插件后。你可以仍然这么写:
```
import { Button } from 'antd';
```
这个插件的作用是, 会帮你转换成 antd/lib/xxx 的写法。另外此插件配合 style 属性可以做到模块样式的按需自动加载。
详见如下:
* [官方文档 - antd 按需加载](https://ant.design/docs/react/getting-started-cn#%E6%8C%89%E9%9C%80%E5%8A%A0%E8%BD%BD)
* [实现antd的按需加载](https://segmentfault.com/a/1190000016430794)
* [babel-plugin-import](https://github.com/ant-design/babel-plugin-import)
* [你的Tree-Shaking并没什么卵用](https://zhuanlan.zhihu.com/p/32831172)
29. sideEffects
在一个纯粹的 ESM 模块世界中,识别出哪些文件有副作用很简单。然而,我们的项目无法达到这种纯度,所以,此时有必要向 webpack 的 compiler 提供提示哪些代码是“纯粹部分”。 —— 《webpack 文档》
注意:样式部分是有副作用的!即不应该被 tree-shaking!
若是直接声明 sideEffects 为 false,那么打包时将不包括样式!所以应该像下面这样配置:
```json
{
"sideEffects": [ "*.sass", "*.scss", "*.css" , "*.vue"]
}
```
参考, 以下内容部分已过期, 注意甄别:
- [体积减少80%!释放webpack tree-shaking的真正潜力](https://juejin.im/post/5b8ce49df265da438151b468)
- [Tree-Shaking性能优化实践 - 原理篇](https://juejin.im/post/5a4dc842518825698e7279a9)
- [Tree-Shaking性能优化实践 - 实践篇](https://juejin.im/post/5a4dca1d518825128654fa78)
29. nginx配置总结
* [Linux运维 | nginx访问控制与参数调优](https://segmentfault.com/a/1190000018505993)
* [Nginx 配置简述](https://www.barretlee.com/blog/2016/11/19/nginx-configuration-start/)
30. vscode 源码开发及调试
* [让 VSCode 在本地 Run 起来](https://www.barretlee.com/blog/2019/10/23/vscode-study-01-start/)
* [带你开发和调试 VS Code 源码](https://www.barretlee.com/blog/2019/11/01/vscode-study-02-debugging/)
31. nodejs 断点调试的原理
* [解密 VS Code 断点调试的原理](https://www.barretlee.com/blog/2019/11/15/vscode-study-03-debug-protocol/)
32. 检测项目中 dependencies 和 devdependencies 无用的依赖
* [depcheck 工具](https://www.npmjs.com/package/depcheck)
33. git rebase [branch]、git rebase、git merge --squash [branch]的区别
#### git rebase [branch]
```bash
# 假设当前为feature1分支, 而且master分支领先该feature若干的提交
git rebase master
```
* 首先,git 会找到 feature1 分支和master的共同源节点, 从该节点开始的feature1 分支 里面的每个 commit 取消掉;
* 其次,把上面的操作临时保存成 patch 文件,存在 .git/rebase 目录下;
* 然后,把 feature1 分支更新到最新的 master 分支;
* 最后,把上面保存的 patch 文件应用到 feature1 分支上;
* 中间如果有冲突需要处理完冲突再输入git rebase --continue完成最终合并
#### git rebase
```bash
git rebase -i h78df3
```
git rebase -i [log hashID]可以将当前分支中的多次提交合并成一个提交记录, 可以保持分支提交记录的整洁性.
#### git merge --squash [branch]
```bash
# 假设当前为master分支, 需要合并feature1的若干次提交
git merge --squash feature1
```
* 首先,git 会将feature1的所有改动迁移过来,但是并不迁移提交记录
* 输入git status, 会发现一堆来自feature1的新增改动
* 这个时候需要你手动输入git add和git commit完成提交, 提交记录和提交信息来源于你, 而不是feature1的owner
#### 总结
(1) git rebase 可以尽可能保持 master 分支干净整洁,并且易于识别 author
(2) git merge --squash 也可以保持 master 分支干净,但是 master 中 author 都是 maintainer,而不是原 owner
(3) merge 不能保持 master 分支干净,但是保持了所有的 commit history,大多数情况下都是不好的,个别情况挺好
(4) git rebase 会改写提交历史, 是个很危险的操作, 如果分支已经push到线上的话, 切记要慎重使用, 否则很容易引起代码冲突
参考:
- [merge squash 和 merge rebase 区别](https://liqiang.io/post/difference-between-merge-squash-and-rebase)
- [彻底搞懂 Git-Rebase](http://jartto.wang/2018/12/11/git-rebase/)
- [Learn Version Control with Git - Rebase 代替合并](https://www.git-tower.com/learn/git/ebook/cn/command-line/advanced-topics/rebase)
- [git merge –squash介绍](https://www.cnblogs.com/lookphp/p/5799533.html)
34. yaml配置文件教程
详见: [YAML 语言教程](http://www.ruanyifeng.com/blog/2016/07/yaml.html)
35. js、css加载监控与重试
- [CSS文件动态加载(续)—— 残酷的真相](https://www.cnblogs.com/chyingp/archive/2013/03/03/how-to-judge-if-stylesheet-loaded-successfully.html)
- [谈一谈CDN的JS,CSS文件加载出错主域名重试的问题](https://imweb.io/topic/5923bf009d67101c034e77ea)
36. 关于CDN、CDN回源、DNS、CNAME以及GSLB的一系列知识点
- [DNS 原理入门](http://www.ruanyifeng.com/blog/2016/06/dns.html)
- [关于 cdn、回源等问题一网打尽](https://juejin.im/post/5af46498f265da0b8d41f6a3#comment)
- [面向前端的CDN原理介绍](https://github.com/renaesop/blog/issues/1)
- [CDN工作原理(CNAME)](https://blog.csdn.net/heluan123132/article/details/73331511)
- [CDN与DNS知识汇总](http://hpoenixf.com/DNS%E4%B8%8ECDN%E7%9F%A5%E8%AF%86%E6%B1%87%E6%80%BB.html)
- [工程师最容易搞错的域名知识](https://juejin.im/post/5d37cf70e51d4510664d17d3)
- [这就是CDN回源原理和CDN多级缓存啊!](https://cloud.tencent.com/developer/article/1439913)
- [全局负载均衡GSLB学习笔记](https://jjayyyyyyy.github.io/2017/05/17/GSLB.html)
- [GSLB概要和实现原理](https://chongit.github.io/2015/04/15/GSLB%E6%A6%82%E8%A6%81%E5%92%8C%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/)
- [作为一名程序员,你真正了解CDN技术吗?](https://juejin.im/post/5dd3d57b51882521d417a33f)
- [CDN加速原理](https://www.jianshu.com/p/1dae6e1680ff)
- [也许是史上最全的一次CDN详解](https://zhuanlan.zhihu.com/p/28940451)
- [根域名的知识](http://www.ruanyifeng.com/blog/2018/05/root-domain.html)
如何找到离用户最近的 CDN 节点(CDN 是如何就近返回资源的)?
1)本地 DNS 服务器会将 static.xxx.example.cdn.com 会向第一层 GSLB 全局负载均衡发起请求,第一层全局负载均衡会根据用户所在运营商网络分析,比如移动运营商,返回 CNAME 到如 static.yd.example.cdn.com 域名地址。
2)本地 DNS 服务器会继续向第二层 GSLB 全局负载均衡发起请求,第二层全局负载均衡依据 DNS 地理位置判断,返回 SLB CDN 负载均衡地址。
3)本地 DNS 服务器从返回的多个 CDN 节点 IP 中,可以通过本地简单轮询的方式去选择一个 CDN IP 访问。
此时,最终通过 GSLB 全局负载均衡找到的这些 CDN 节点,就是离用户最近的 CDN 节点了。
37. 持续集成、持续交付、持续部署
- [持续集成是什么?](http://www.ruanyifeng.com/blog/2015/09/continuous-integration.html)
38. 网站全站升级https的流程:
- [HTTPS 升级指南](http://www.ruanyifeng.com/blog/2016/08/migrate-from-http-to-https.html)
39. 唤端(唤起app)的实现及相关原理
- [H5唤起APP指南(附开源唤端库)](https://juejin.im/post/5b7efb2ee51d45388b6af96c)
- [Web 唤起 Android app 的实现及原理](https://johnnyshieh.me/posts/web-evoke-app/)
- [Android 上玩转 DeepLink:如何最大程度的向 App 引流](https://medium.com/@zhoulujue/android-%E4%B8%8A%E7%8E%A9%E8%BD%AC-deeplink-%E5%A6%82%E4%BD%95%E6%9C%80%E5%A4%A7%E7%A8%8B%E5%BA%A6%E7%9A%84%E5%90%91-app-%E5%BC%95%E6%B5%81-5da646402c29)
40. 浅析a标签的download属性
- [浅析 HTML5 中的 download 属性](https://zhuanlan.zhihu.com/p/58888918)
41. 关于https、HSTS和mixed content
- [关于启用 HTTPS 的一些经验分享(一)](https://imququ.com/post/sth-about-switch-to-https.html)
- [MDN - MixedContent](https://developer.mozilla.org/zh-CN/docs/Security/MixedContent)
- [什么是混合内容?](https://developers.google.com/web/fundamentals/security/prevent-mixed-content/what-is-mixed-content?hl=zh-cn)
42. lerna管理前端packages
- [lerna管理前端packages的最佳实践](http://www.sosout.com/2018/07/21/lerna-repo.html)
- [Lerna 中文教程详解](https://juejin.im/post/5ced1609e51d455d850d3a6c)
43. Vue项目自动转换 px 为 rem,高保真还原设计图
- [Vue项目自动转换 px 为 rem,高保真还原设计图](https://juejin.im/post/5a716c4c6fb9a01cb42cac4b)
44. 解决 canvas 在高清屏中绘制模糊的问题
基础知识点:
- 要设置canvas的画布大小,使用的是 canvas.width 和 canvas.height;
- 要设置画布的实际渲染大小,使用的 style 属性或CSS设置的 width 和height,只是简单的对画布进行缩放。
2倍屏幕下示例代码:
```html
<canvas width="640" height="800" style="width:320px; height:400px"></canvas>
```
canvas的实际大小的640px × 800px,但是实际渲染到页面的大小是320px × 400px,相当于缩小一倍来显示。
45. 移动端开发适配注意事项
- [关于移动端适配,你必须要知道的](https://juejin.im/post/5cddf289f265da038f77696c#heading-0)
- [移动端适配方案-让分辨率来的更猛烈些吧!](https://juejin.im/post/5bc7fb9ef265da0acd20ebeb#heading-0)
46. 理解DOMString、Document、FormData、Blob、File、ArrayBuffer数据类型
- [理解DOMString、Document、FormData、Blob、File、ArrayBuffer数据类型](https://www.zhangxinxu.com/wordpress/2013/10/understand-domstring-document-formdata-blob-file-arraybuffer/)
47. 在大型分布式服务中, 请求会通过网关负载均衡到服务机器上, 如果定位一个请求错误, 要去所有机器的服务日志中一个一个地查, 会相当繁杂, 令人崩溃。处理这种情况一般有两种方式:
- 统一日志服务:通过接入, 将所有机器的日志上报到统一日志服务, 在统一日志服务的管理后台就能查看所有机器的日志, 还能对特定用户的日志进行染色处理。
- 系统批量工具: 可以通过系统批量工具(也是一个基础服务), 通过后台管理系统输入所有服务机器的IP及日志目录和相关命令, 可以针对所有机器执行该命令, 返回相关结果。
48. 磁盘的随机读写和顺序读写
- [SSD的随机读写与顺序读写?](https://www.zhihu.com/question/47544675/answer/303644115)
- [linux之磁盘随机读写和顺序读写](https://zhuanlan.zhihu.com/p/34895884)
- [磁盘IO的那些事](https://tech.meituan.com/2017/05/19/about-desk-io.html)
49. 单点登录(SSO)
- [单点登录(SSO)的设计&实现思路](https://segmentfault.com/a/1190000016738030)
详见:
- [解决 canvas 在高清屏中绘制模糊的问题](https://www.html.cn/archives/9297)
50. 复杂页面代码组织设计的一些思考(如一个可配置页的报表渲染引擎)
- 对于内部各种属性的赋值操作, 不可随意赋值, 必须收紧由赋值函数统一处理, 便于数据变化跟踪
- 多变的逻辑不应该在内部做各种类型判断写不同的逻辑, 宜暴露出接口给外部, 由外部根据业务需要做处理
- 分层结构, 越是内部的组件层, 功能越是内聚, 越是外部, 接口和限制更自由
- 数据的初试化往往有多种形式(比如从后台获取初试化配置的形式、外部组件传入初始化参数、url传入初试化参数等), 需要梳理出各种形式的优先级, 在外层组件(这些初始化逻辑往往比较多变, 侵入性比较强, 应该交给外层组件, 内层组件负责好自己独立功能点)处理这些初始化逻辑
51. 环比与同比的理解
环比和同比用于描述统计数据的变化情况。
- 环比:表示本次统计段与相连的上次统计段之间的比较。比如2010年中国第一季度GDP为G10-1亿元,第二季度GDP为G10-2亿元,则第二季度GDP环比增长(G10-2-G10-1)/G10-1;
- 同比:即同期相比,表示某个特定统计段今年与去年之间的比较。比如2009年中国第一季度GDP为G9-1亿元,则2010年第一季度的GDP同比增长为(G10-1-G9-1)/G9-1。
环比和同比在英文中没有单一单词对应的翻译。同比英文可翻译为 compare with the performance/figure/statistics last year, year-on-year ratio, increase/decrease on a year-on-year basis。而环比则只需把前面的year改为month或season即可。
52. httpDNS
主要为了解决传统DNS的以下问题:
- Local DNS 劫持:由于 HttpDns 是通过 IP 直接请求 HTTP 获取服务器 A 记录地址,不存在向本地运营商询问 domain 解析过程,所以从根本避免了劫持问题。
- 平均访问延迟下降:由于是 IP 直接访问省掉了一次 domain 解析过程,通过智能算法排序后找到最快节点进行访问。
- 用户连接失败率下降:通过算法降低以往失败率过高的服务器排序,通过时间近期访问过的数据提高服务器排序,通过历史访问成功记录提高服务器排序。
参考:
- [HttpDns 原理是什么](http://www.linkedkeeper.com/171.html)
- [全面理解DNS及HTTPDNS](https://juejin.im/post/5dc14f096fb9a04a6b204c6f#heading-1)
- [移动解析HTTPDNS](https://cloud.tencent.com/product/httpdns)
53. svg入门
- [SVG 图像入门教程](https://www.ruanyifeng.com/blog/2018/08/svg.html)
- [MDN - SVG](https://developer.mozilla.org/zh-CN/docs/Web/SVG)
- [理解SVG viewport,viewBox,preserveAspectRatio缩放](https://www.zhangxinxu.com/wordpress/2014/08/svg-viewport-viewbox-preserveaspectratio/)
54. 分布式系统的CAP定理
CAP指的是Consistency(一致性)、Availability(可用性)、Partition tolerance(分区容错性),Consistency 和 Availability 的矛盾, 不能同时成立.
- [CAP 定理的含义](http://www.ruanyifeng.com/blog/2018/07/cap.html)
55. JWT(JSON Web Token)
- [JSON Web Token 入门教程](http://www.ruanyifeng.com/blog/2018/07/json_web_token-tutorial.html)
56. make命令教程
- [make命令教程](http://www.ruanyifeng.com/blog/2015/02/make.html)
57. contenteditable 属性的隐藏坑
```html
<div id="container" contenteditable>
12324234
<span contenteditable="false"></span>
</div>
```
类似如上情况, 当一个contenteditable属性为true的元素内部有个contenteditable为false的元素的时候, 在chrome中全部删除container中的文字时, 光标会丢失, 无法找到该元素的编辑区域, 即无法再编辑该元素内的文字。而在firefox中, 当全部删除container中的文字时, 如果不主动移除光标, 还是可以添加内部文字, 如果在文字没有后主动移除光标, 则也是再也找不到可编辑区域。
58. GIF生成
参考:
- [纯前端实现可传图可字幕台词定制的GIF表情生成器](https://www.zhangxinxu.com/wordpress/2018/05/js-custom-gif-generate/)
59. 如何读懂火焰图?
- [如何读懂火焰图?](http://www.ruanyifeng.com/blog/2017/09/flame-graph.html)
60. js内存泄漏
- [JavaScript 内存泄漏教程](http://www.ruanyifeng.com/blog/2017/04/memory-leak.html)
61. 大型前端项目性能优化
- [Front-End Performance Checklist 2019 [PDF, Apple Pages, MS Word]](https://www.smashingmagazine.com/2019/01/front-end-performance-checklist-2019-pdf-pages/)
- [Front-End Performance Checklist 2020 [PDF, Apple Pages, MS Word]](https://www.smashingmagazine.com/2020/01/front-end-performance-checklist-2020-pdf-pages/)
- [(译)2019年前端性能优化清单 — 上篇](https://juejin.im/post/5c46cbaee51d453f45612a2c)
- [(译)2019年前端性能优化清单 — 中篇](https://juejin.im/post/5c471eaff265da616d547c8c)
- [(译)2019年前端性能优化清单 — 下篇](https://juejin.im/post/5c473cdae51d45518d4701ff)
62. service mesh
- [什么是Service Mesh](https://zhuanlan.zhihu.com/p/61901608)
- [什么是Service Mesh(服务网格)?](https://jimmysong.io/blog/what-is-a-service-mesh/)
63. 自定义h5的video播放器
- [自定义H5 video 播放器](https://juejin.im/post/5daef8b6e51d4524e60e0f6a)
64. html5 video和视频文件流
- [Does HTML5 <video> playback support the .avi format?](https://stackoverflow.com/questions/4129674/does-html5-video-playback-support-the-avi-format)
- [VIDEO ON THE WEB](http://diveintohtml5.info/video.html)
- [HTML5 video](https://en.wikipedia.org/wiki/HTML5_video)
- [Media type and format guide: image, audio, and video content](https://developer.mozilla.org/en-US/docs/Web/Media/Formats)
- [为什么视频网站的视频链接地址是blob?](https://juejin.im/post/5d1ea7a8e51d454fd8057bea)
- [H5直播入门(理论篇)](https://juejin.im/post/5aaa34475188253640012847)
- [三种视频流浏览器播放解决方案](https://juejin.im/post/5d8b57dc6fb9a04e024073c4)
- [MDN - MediaSource](https://developer.mozilla.org/zh-CN/docs/Web/API/MediaSource#Browser_compatibility)
65. 开发UI组件库
- [从0开始搭建一套前端UI组件库 — 01 开篇](https://uxfan.com/fe/vue.js/2019/07/20/build-frontend-ui-framework-from-very-beginning_01.html)
- [从0开始搭建一套前端UI组件库 — 02 环境搭建](https://uxfan.com/fe/vue.js/2019/07/22/build-frontend-ui-framework-from-very-beginning_02.html)
- [从0开始搭建一套前端UI组件库 — 03 全局统筹](https://uxfan.com/fe/vue.js/2019/07/25/build-frontend-ui-framework-from-very-beginning_03.html)
66. 中间表
- [多对多中间表详解 -- Django从入门到精通系列教程](https://www.cnblogs.com/feixuelove1009/p/8417714.html)
- [数据库中间表](https://blog.cto163.com/wordpress/%E4%B8%AD%E9%97%B4%E8%A1%A8/)
67. Flex Basis与Width的区别
- [[翻译]Flex Basis与Width的区别](https://www.jianshu.com/p/17b1b445ecd4)
- [The Difference Between Width and Flex Basis](https://mastery.games/post/the-difference-between-width-and-flex-basis/)
68. 为什么flex-box可用于div,但不能用于表格?
- [Why does flex-box work with a div, but not a table?](https://stackoverflow.com/questions/41421512/why-does-flex-box-work-with-a-div-but-not-a-table)
- [www.w3.org/TR/CSS2/tables](https://www.w3.org/TR/CSS2/tables.html#model)
69. SameSite cookies explained
- [SameSite cookies explained](https://web.dev/samesite-cookies-explained/?utm_source=devtools)
- [Reject insecure SameSite=None cookies](https://www.chromestatus.com/feature/5633521622188032)
70. fetch进行post请求为什么会首先发一个options 请求?
- [fetch进行post请求为什么会首先发一个options 请求?](https://www.zhihu.com/question/49250449/answer/118740346)
71. 流量劫持、网络劫持
- [应对流量劫持,前端能做哪些工作?](https://www.zhihu.com/question/35720092/answer/523563873)
72. 事件循环
- [从Chrome源码看事件循环](https://zhuanlan.zhihu.com/p/48522249)
- [Event Loop 这个循环你晓得么?(附GIF详解)](https://zhuanlan.zhihu.com/p/41543963)
- [详解JavaScript中的Event Loop(事件循环)机制](https://zhuanlan.zhihu.com/p/33058983)
73. ES module 和 commonjs的区别
区别:
1. commonJs是被加载的时候运行,esModule是编译的时候运行
2. commonJs输出的是值的浅拷贝,esModule输出值的引用
3. commentJs具有缓存。在第一次被加载时,会完整运行整个文件并输出一个对象,拷贝(浅拷贝)在内存中。下次加载文件时,直接从内存中取值
ES module 执行步骤:
1. 构造: 查找、下载并解析所有文件到模块记录中。
2. 实例化: 在内存中寻找一块区域来存储所有导出的变量(但还没有填充值)。然后让 export 和 import 都指向这些内存块。这个过程叫做链接(linking)。
3. 求值: 运行代码,在内存块中填入变量的实际值。
所以es module的export和import指向的是一个内存地址, 故这个地址的值变化的话, 引用这个地址的变量都会变化。
ES6 模块会在程序开始前先根据模块关系查找到所有模块,生成一个无环关系图,并将所有模块实例都创建好,这种方式天然地避免了循环引用的问题,当然也有模块加载缓存,重复 import 同一个模块,只会执行一次代码。
一些example
```js
// es module
// constants.js
export const test = {
aa: 1,
bb: {
cc: 'hello'
}
}
export let test2 = 2
setTimeout(() => {
test2 = undefined
test1.aa = 3
test1.bb.cc = 'bye'
console.log('test1', test1)
console.log('test2', test2)
}, 2000)
// index.js
import { test1, test2 } from './constants'
console.log('import1', test1)
console.log('import2', test2)
setTimeout(() => {
console.log('trigger1', test1)
console.log('trigger2', test2)
}, 4000)
// 输出
// import1 {"aa":1,"bb":{"cc":"hello"}}
// import2 2
// test1 {"aa":3,"bb":{"cc":"bye"}}
// test2 undefined
// trigger1 {"aa":3,"bb":{"cc":"bye"}}
// trigger2 undefined
```
```js
// commonjs
// constants.js
let test1 = {
aa: 1,
bb: {
cc: 'hello'
}
}
let test2 = 2
setTimeout(() => {
test1.aa = 2
test1.bb.cc = 'bye'
test2 = undefined
console.log('test1', test1)
console.log('test2', test2)
}, 1000)
module.exports = {
test1,
test2
}
// index.js
let constants = require('./constants');
console.log('require1', constants.test1)
console.log('require2', constants.test2)
setTimeout(() => {
console.log('trigger1', constants.test1)
console.log('trigger2', constants.test2)
}, 4000)
// 输出
// require1 {"aa":1,"bb":{"cc":"hello"}}
// require2 2
// test1 {"aa":2,"bb":{"cc":"bye"}}
// test2 undefined
// trigger1 {"aa":2,"bb":{"cc":"bye"}}
// trigger2 2
```
- [ES modules: A cartoon deep-dive](https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/)
- [漫画:深入浅出 ES 模块](https://zhuanlan.zhihu.com/p/36358695)
- [CommonJS 和 ES6 Module 究竟有什么区别?](https://juejin.im/post/6844904080955932680#heading-0)
- [Node.js 中的 require 是如何工作的?](https://juejin.im/post/6844903957752463374)
- [CommonJs 和 ESModule 的 区别整理](https://juejin.im/post/6844903598480965646)
- [深入理解es module](https://juejin.im/post/6844903834532200461)
- [What do ES6 modules export?](https://2ality.com/2015/07/es6-module-exports.html)
- [MDN - export](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export)
74. RegExp.prototype.exec()的一个坑
>exec() 方法在一个指定字符串中执行一个搜索匹配。返回一个结果数组或 null。
>
>在设置了 global 或 sticky 标志位的情况下(如 /foo/g or /foo/y),JavaScript RegExp 对象是有状态的。他们会将上次成功匹配后的位置记录在 lastIndex 属性中。使用此特性,exec() 可用来对单个字符串中的多次> 匹配结果进行逐条的遍历(包括捕获到的匹配),而相比之下, String.prototype.match() 只会返回匹配到的结果。
>
>如果你只是为了判断是否匹配(true或 false),可以使用 RegExp.test() 方法,或者 String.search() 方法。
- [MDN - RegExp.prototype.exec()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec)
- [js正则exec方法的一个诡异现象](https://www.jianshu.com/p/c6f4e0f732f8)
75. 关于git在win或者mac下对文件名大小写不敏感的问题处理:
方案一:
```bash
git mv -f OldFileNameCase newfilenamecase
```
方案二:
```bash
git config core.ignorecase false
```
- [How do I commit case-sensitive only filename changes in Git?](https://stackoverflow.com/questions/17683458/how-do-i-commit-case-sensitive-only-filename-changes-in-git)
76. 声明式与命令式编程
- 声明式编程( Declarative):只告诉你想要的结果(What),机器自己摸索过程(How)。典型例子就是html和sql,抽象成简单易懂的语法,让机器去执行里面的复杂渲染和查询逻辑。
- 命令式编程(Imperative):详细的命令机器怎么(How)去处理一件事情以达到你想要的结果(What)。一步一步告诉机器应该怎么做。
参考:
- [声明式编程和命令式编程有什么区别?](https://www.zhihu.com/question/22285830)
- [命令式编程(Imperative) vs声明式编程( Declarative)](https://zhuanlan.zhihu.com/p/34445114)
- [声明式编程和命令式编程的比较](https://www.aqee.net/post/imperative-vs-declarative.html)
- [声明式(declarative) vs 命令式(imperative)](https://lotabout.me/2020/Declarative-vs-Imperative-language/)
77. HTTP协议中的Transfer-Encoding
1. Transfer-Encoding,是一个 HTTP 头部字段,字面意思是「传输编码」。实际上,HTTP 协议中还有另外一个头部与编码有关:Content-Encoding(内容编码)。Content-Encoding 通常用于对实体内容进行压缩编码,目的是优化传输,例如用 gzip 压缩文本文件,能大幅减小体积。内容编码通常是选择性的,例如 jpg / png 这类文件一般不开启,因为图片格式已经是高度压缩过的,再压一遍没什么效果不说还浪费 CPU。而 Transfer-Encoding 则是用来改变报文格式,它不但不会减少实体内容传输大小,甚至还会使传输变大,那它的作用是什么呢?本文接下来主要就是讲这个。我们先记住一点,Content-Encoding 和 Transfer-Encoding 二者是相辅相成的,对于一个 HTTP 报文,很可能同时进行了内容编码和传输编码。
2. 在node server的应用中, 如果返回数据中不添加Content-Length头部的话, 会默认是Transfer-Encoding: chunked的形式。
3. chunked还是会给浏览器传输了每段chunk(数据段)的长度,但是偷偷藏在了报文当中,所以并没有显式地像content-length在头部声明。
4. nginx中转发接口请求过程中, 会默认将所接受的数据buffer起来(proxy_request_buffering on;), 等这个连接的数据发送完毕之后再彻底转发, 也就是不走Transfer-Encoding: chunked的形式, 而是接受完所有数据, 赋值content-length头部的形式。 如果期望走Transfer-Encoding: chunked的形式转发接口请求的话, 可以将proxy_request_buffering配置改成off。
参考:
- [为什么在HTTP的chunked模式下不需要设置长度](https://zhuanlan.zhihu.com/p/65816404)
- [MDN - Transfer-Encoding](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Transfer-Encoding)
- [HTTP 协议中的 Transfer-Encoding](https://imququ.com/post/transfer-encoding-header-in-http.html)
- [用了这么久HTTP, 你是否了解Content-Length?](https://blog.fundebug.com/2019/09/10/understand-http-content-length/)
78. IOC(Inversion of Control, 控制反转)
#### 起源
早在2004年,Martin Fowler就提出了“哪些方面的控制被反转了?”这个问题。他总结出是依赖对象的获得被反转了,因为大多数应用程序都是由两个或是更多的类通过彼此的合作来实现业务逻辑,这使得每个对象都需要获取与其合作的对象(也就是它所依赖的对象)的引用。如果这个获取过程要靠自身实现,那么这将导致代码高度耦合并且难以维护和调试。
#### 技术描述
Class A中用到了Class B的对象b,一般情况下,需要在A的代码中显式的new一个B的对象。
采用依赖注入技术之后,A的代码只需要定义一个私有的B对象,不需要直接new来获得这个对象,而是通过相关的容器控制程序来将B对象在外部new出来并注入到A类里的引用中。而具体获取的方法、对象被获取时的状态由配置文件(如XML)来指定。
#### 实现方法
实现控制反转主要有两种方式:依赖注入和依赖查找。两者的区别在于,前者是被动的接收对象,在类A的实例创建过程中即创建了依赖的B对象,通过类型或名称来判断将不同的对象注入到不同的属性中,而后者是主动索取相应类型的对象,获得依赖对象的时间也可以在代码中自由控制。
- [IoC原理](https://www.liaoxuefeng.com/wiki/1252599548343744/1282381977747489)
- [控制反转](https://zh.wikipedia.org/wiki/%E6%8E%A7%E5%88%B6%E5%8F%8D%E8%BD%AC)
- [浅谈IOC--说清楚IOC是什么](https://www.cnblogs.com/DebugLZQ/archive/2013/06/05/3107957.html)
- [从前端角度彻底搞懂 DIP、IoC、DI、JS](https://zhuanlan.zhihu.com/p/61018434)
- [面向复杂应用,Node.js中的IoC容器 -- Rockerjs/core](https://cloud.tencent.com/developer/article/1405995)
- [当IoC遇见了Node.js](https://www.infoq.cn/article/ioc-meet-nodejs)
- [五分钟掌握 JavaScript 中的 IoC](https://segmentfault.com/a/1190000022264251)
- [前端 IoC 理念入门](https://efe.baidu.com/blog/introduction-about-ioc-in-frontend/)
- [IOC在Nodejs上的初体验](https://juejin.im/post/6844903957366571016)
- [浅谈阿里 Node 框架 Midway 在企业产品中的应用实践](https://zhuanlan.zhihu.com/p/81072053)
79. package-lock.json 与 npm-shrinkwrap.json
在npm5之后,对于某一package.json文件,输入npm install,在相同时间点时总是可以得到相同的package-lock.json。当package.json中的依赖/子依赖的存在新的版本迭代时,则会忽略package-lock.json,并用新版本号覆盖package-lock.json。
项目开发过程中肯定会持续更新依赖包的版本,如果需要确定性的构建结果,可以尝试使用npm ci。
npm ci将会直接从package-lock.json安装依赖项,并仅使用package.json来验证是否存在不匹配的版本。 如果缺少任何依赖项或版本不兼容,则将抛出异常。
package-lock的主要用处总结如下:
- 1. package-lock的依赖目录和node_modules完全相同,因此可以通过package-lock了解依赖树的结构;
- 2. 保证不同开发者间的版本库依赖关系完全相同;
- 3. 允许npm跳过以前安装的依赖包的重复meta数据解析,显著减少安装耗时;
基于以上的特点,笔者极力推荐开发者在生产项目中上传package-lock文件,以避免不必要的版本冲突。
这里需要注意两点,一个是在根目录之外的任何地方都将被忽略,所以不会存在跨目录间package-lock互相干扰的问题;另一点是package-lock.json无法随着npm包一起被发布出去,因此开发npm包时是不能锁依赖版本的。
如果发npm包有锁版本的需要,可以在存在node_modules或package-lock时通过npm shrinkwrap创建npm-shrinkwrap.json。npm-shrinkwrap与package-lock的结构与内容完全一致,唯一的区别就是npm-shrinkwrap可以随npm包一起上传,从而达到锁版本的目的。
额外提一下,npm-shrinkwrap的创建强依赖于node_modules以及package-lock文件,如果不存在上述两个文件,则会创建一个空依赖的文件。如果已经存在package-lock,则会将其rename为npm-shrinkwrap;若只存在node_modules则会根据其结构创建npm-shrinkwrap。
如果package-lock.json和npm-shrinkwrap.json都存在于包的根目录中,则package-lock.json将被忽略。
80. package-lock.json中的dev
如果依赖项仅是顶层模块的devDependencies,或者是一个传递依赖项,则dev属性为true;对于既是顶层的开发依赖关系又是顶层的非开发依赖关系的传递依赖关系的依赖关系,则为false。
这里的传递依赖是指,如果A依赖B,B依赖C,则C就是A的一个传递依赖。
简单来说就是一旦开发依赖包被非开发依赖包依赖,则dev为false。
81. vue 中使用watch方法监听对象和数组的变化的时候, 对数组进行push操作和对Obj进行$set操作,虽然都可能触发watch事件,但是在callback返回的结果中,oldValue和newValue相同。那时因为对数组和对象的引用是同源的,虽然会触发数据watch,但是newValue和oldValue是同一个,解决方案是重新赋值对象或者数组。
- [$watch中的oldvalue和newValue](https://segmentfault.com/a/1190000010397584)
- [Vue watch 复杂对象变化,oldvalue 和 newValue 一致,解决办法。](https://blog.csdn.net/u011330018/article/details/107322733/?utm_medium=distribute.pc_relevant.none-task-blog-title-2&spm=1001.2101.3001.4242)
82. Path-to-RegExp
- [Path-to-RegExp](https://github.com/pillarjs/path-to-regexp/tree/v1.7.0)
83. vue-cli 分析
详见:
- [浅谈 vue-cli 扩展性和插件设计](https://juejin.im/post/5cedb26451882566477b7235)
- [vue-cli-analysis](https://kuangpf.com/vue-cli-analysis/foreword/)
- [【cli】这是看过最优秀的Vue-cli源码分析,绝对受益匪浅](https://juejin.cn/post/6844903586929868813)
84. ajax请求跨域携带cookie,cors支持ajax请求携带cookie
- [如何配置ajax请求跨域携带cookie,cors支持ajax请求携带cookie](https://cloud.tencent.com/developer/article/1467263)
85. 线程安全
- [【面试】如果你这样回答“什么是线程安全”,面试官都会对你刮目相看](https://www.cnblogs.com/lixinjie/p/a-answer-about-thread-safety-in-a-interview.html)
- [什么是线程安全以及如何实现?](https://segmentfault.com/a/1190000023187634)
86. js加载器的实现
- [[转]动态加载js文件的正确姿势](https://github.com/xiongwilee/blog/issues/8)
87. Protocol Buffers
- [在浏览器环境下使用Protocol Buffers协议](http://eux.baidu.com/blog/fe/%E6%B5%8F%E8%A7%88%E5%99%A8%E7%8E%AF%E5%A2%83%E4%B8%8B%E4%BD%BF%E7%94%A8Protocol%20Buffers)
- [Google Protocol Buffer 的使用和原理](https://www.ibm.com/developerworks/cn/linux/l-cn-gpb/index.html)
- [protobuf.js](https://github.com/protobufjs/protobuf.js)
88. SQL 外键
SQL 的主键和外键的作用:
外键取值规则:空值或参照的主键值
- (1)插入非空值时,如果主键值中没有这个值,则不能插入。
- (2)更新时,不能改为主键表中没有的值。
- (3)删除主键表记录时,可以在建外键时选定外键记录一起联删除还是拒绝删除。
- (4)更新主键记录时,同样有级联更新和拒绝执行的选择。
总的来说, 外键主要是起到约束的作用。在学院派的SQL范式中, 一般都推荐使用外键规范数据库。
然而, 在大部分互联网应用中, 一般都不会使用外键。因为现在传统SQL水平拓展一般都比较麻烦和复杂, 大部分互联网应用的数据层都是使用一主多从的部署方式(主库写从库读), 如果使用外键, 约束都在主库执行, 主库很容易成为性能瓶颈. 故在互联网应用中, 约束一般在应用层, 通过查询从库数据判断写入数据是否合法, 这样只需要水平拓展应用层的服务器(容易水平拓展), 就能达到约束的目的。
- [为什么数据库不应该使用外键](https://draveness.me/whys-the-design-database-foreign-key/)
- [SQL的主键和外键的作用](https://www.jianshu.com/p/394f8aa724f4)
- [关系模型 - 外键](https://www.liaoxuefeng.com/wiki/1177760294764384/1218728424164736)
- [大家设计数据库时使用外键吗?](https://www.zhihu.com/question/19600081)
89. 短链接服务的实现
目前比较流行的生成短码方法有:自增id、摘要算法、普通随机数。
- [如何实现一个短链接服务](https://www.cnblogs.com/rickiyang/p/12178644.html)
- [新浪短链接生成工具](https://www.sina.lt/)
- [短网址服务的原理是什么?](https://www.zhihu.com/question/19852154)
- [短网址(short URL)系统的原理及其实现](https://segmentfault.com/a/1190000012088345)
90. node应用docker部署的时候到底应不应该在容器内起个进程守护?
主流的观点是:
不应该在docker容器中起进程守护,这是因为:
- (1) 如果您使用pm2在每个容器中运行一个进程,则除了增加内存消耗之外,您不会获得太多收益。可以使用具有重新启动策略的纯docker重新启动。其他基于docker的环境(例如ECS或Kubernetes)也可以做到这一点。
- (2) 如果在docker容器中运行多个进程,将会使监视更加困难。CPU /内存指标不再对您的封闭环境直接可用。
- (3) 对于单个PM2进程的健康检查请求将会分配给各个worker进程,这很可能会隐藏不健康的目标。
- (4) pm2隐藏了worker的crash,你将很难从(云平台的)监控面板察觉到。
- (5) 负载均衡会变得更加复杂,因为你其实加多了一层负载均衡。
- (6) 在docker内运行多个进程也与docker的理念相违背的,即每个容器应该只保留一个进程。
更多见解:
```
PM2 本身可能比你 Node 的业务还复杂,出了问题不好 DEBUG,就像你和 log4js 一起用还得做兼容。其次,如果你的 Node 程序本身有问题,PM2 一直重启不成功,但是容器主进程是 PM2 一直在前台,定位问题就得进到容器。
有一种开发模式叫 let it crash,只有当一个程序退出了,你才知道隐藏的问题在哪里,而不是到处去做 try...catch,PM2 本身就是一种 try...catch。
补充答主第一个问题,Node.js 多进程模型是为了进程间通信更方便,一般采用 master-worker 的机制,worker 之间可以直接通过 master 通信。如果你用容器对进程进行隔离,就要借助第三方,如 mq 进行通信。
```
```
关于 Node.js 应用的稳定性,一般会有两种做法:
如果应用有异常情况没处理干净,挂掉就该挂掉,不重启。做好 TCP 端口监控的话,能及时发现问题,避免发生更大的事故。
使用 PM2、supervisor 这类进程管理工具,发现进程挂掉就立即重启。这样能保证大部分时间的可用性,但是对监控要求高一些,端口监控可能不太够用。
如果应用对稳定性的要求比较高,建议使用方案 1,可以早日让应用足够健壮。如果对稳定性没什么太高要求,比如 99% 的时间可用就行,可以使用方案 2 ,这也是大部分业务应用采用的做法。
关于是否应该使用多个进程来运行 Node.js 应用,我的经验是需要。
Node.js 应用对内存的要求比较高,如果使用 4 个 1c1g 的容器来运行,可能并不如 1 个 4c4g 的容器来运行稳定(比如某些接口 1g 内存会出现 oom)。如果负载均衡做的不好,你的 4 个 1c1g 的容器可能并不能达到 4c4g 的效果。之前我也做过这方面的压测,结果也能说明多核的 tps 会高一些,也更稳定一些。
如果只是想达到多进程运行 Node.js 应用的目的,PM2 可能略重,可以尝试使用 cfork 来代替。
```
- [what is the point of using pm2 and docker together?](https://stackoverflow.com/questions/51191378/what-is-the-point-of-using-pm2-and-docker-together)
91. VS Code 项目配置路径别名跳转
开发脚手架自定义路径别名的时候, vscode等编辑器无法识别这类自定义别名导致智能提示和智能跳转会失效, 可以通过以下方案处理.
- [VS Code 项目配置路径别名跳转](https://github.com/pfan123/Articles/issues/66)
- [vscode 开启对 webpack alias(文件别名) 引入的智能提示](https://blog.csdn.net/zzl1243976730/article/details/92820985) | Java |
"use strict";
var async = require('async');
var fs = require('fs');
var util = require('util');
var prompt = require('prompt');
var httpRequest = require('emsoap').subsystems.httpRequest;
var common = require('./common');
var mms = require('./mms');
var mmscmd = require('./mmscmd');
var deploy = require('./deploy');
var session; // MMS session
var modelFile = "sfmodel.json";
var externalSystemType = 'NODEX';
var externalSystem;
var accessAddress;
var credentials;
var mappedObjects;
var verboseLoggingForExternalSystem;
function afterAuth(cb) {
// munge mappedObjects as required
for (var name in mappedObjects) {
var map = mappedObjects[name];
if (!map.typeBindingProperties) {
map.typeBindingProperties = {};
for (var propName in map) {
switch(propName) {
case "target":
case "properties":
;
default:
map.typeBindingProperties[name] = map[name];
}
}
}
}
// invoke op to create model
session.directive(
{
op : "INVOKE",
targetType: "CdmExternalSystem",
name: "invokeExternal",
params: {
externalSystem: externalSystem,
opName : "createSfModel",
params : {
sfVersion : credentials.sfVersion,
externalSystem : externalSystem,
typeDescs : mappedObjects
}
}
},
function (err, result) {
if (err) {
return cb(err);
}
fs.writeFileSync(modelFile, JSON.stringify(result.results, null, 2));
mmscmd.execFile(modelFile,session, deploy.outputWriter, cb);
}
);
}
exports.deployModel = function deployModel(externalSystemName,mmsSession,cb) {
session = mmsSession;
externalSystem = externalSystemName;
var text;
if(!session.creds.externalCredentials) {
console.log("Profile must include externalCredentials");
process.exit(1);
}
credentials = session.creds.externalCredentials[externalSystemName];
if(!credentials) {
console.log("Profile does not provide externalCredentials for " + externalSystemName);
process.exit(1);
}
if(!credentials.oauthKey || !credentials.oauthSecret) {
console.log("externalSystemName for " + externalSystemName + " must contain the oAuth key and secret.");
}
accessAddress = credentials.host;
try {
text = fs.readFileSync("salesforce.json");
} catch(err) {
console.log('Error reading file salesforce.json:' + err);
process.exit(1);
}
try {
mappedObjects = JSON.parse(text);
} catch(err) {
console.log('Error parsing JSON in salesforce.json:' + err);
process.exit(1);
}
if(mappedObjects._verbose_logging_) {
verboseLoggingForExternalSystem = mappedObjects._verbose_logging_;
}
delete mappedObjects._verbose_logging_;
createExternalSystem(function(err) {
if (err) {
return cb(err);
}
var addr = common.global.session.creds.server + "/oauth/" + externalSystem + "/authenticate";
if (common.global.argv.nonInteractive) {
console.log("Note: what follows will fail unless Emotive has been authorized at " + addr);
afterAuth(cb);
}
else {
console.log("Please navigate to " + addr.underline + " with your browser");
prompt.start();
prompt.colors = false;
prompt.message = 'Press Enter when done';
prompt.delimiter = '';
var props = {
properties: {
q: {
description : ":"
}
}
}
prompt.get(props, function (err, result) {
if (err) {
return cb(err);
}
afterAuth(cb);
});
}
});
}
function createExternalSystem(cb) {
if (!session.creds.username)
{
console.log("session.creds.username was null");
process.exit(1);
}
if(verboseLoggingForExternalSystem) console.log('VERBOSE LOGGING IS ON FOR ' + externalSystem);
session.directive({
op: 'INVOKE',
targetType: 'CdmExternalSystem',
name: "updateOAuthExternalSystem",
params: {
name: externalSystem,
typeName: externalSystemType,
"oauthCredentials" : {
"oauthType": "salesforce",
"oauthKey": credentials.oauthKey,
"oauthSecret": credentials.oauthSecret
},
properties: {
proxyConfiguration: {verbose: verboseLoggingForExternalSystem, sfVersion: credentials.sfVersion},
globalPackageName : "sfProxy"
}
}
},
cb);
}
| Java |
#!/usr/bin/env python
# coding:utf-8
"""
Database operation module. This module is independent with web module.
"""
import time, logging
import db
class Field(object):
_count = 0
def __init__(self, **kw):
self.name = kw.get('name', None)
self.ddl = kw.get('ddl', '')
self._default = kw.get('default', None)
self.comment = kw.get('comment', '')
self.nullable = kw.get('nullable', False)
self.updatable = kw.get('updatable', True)
self.insertable = kw.get('insertable', True)
self.unique_key = kw.get('unique_key', False)
self.non_unique_key = kw.get('key', False)
self.primary_key = kw.get('primary_key', False)
self._order = Field._count
Field._count += 1
@property
def default(self):
d = self._default
return d() if callable(d) else d
def __str__(self):
s = ['<%s:%s,%s,default(%s),' % (self.__class__.__name__, self.name, self.ddl, self._default)]
self.nullable and s.append('N')
self.updatable and s.append('U')
self.insertable and s.append('I')
s.append('>')
return ''.join(s)
class StringField(Field):
def __init__(self, **kw):
if not 'default' in kw:
kw['default'] = ''
if not 'ddl' in kw:
kw['ddl'] = 'varchar(255)'
super(StringField, self).__init__(**kw)
class IntegerField(Field):
def __init__(self, **kw):
if not 'default' in kw:
kw['default'] = 0
if not 'ddl' in kw:
kw['ddl'] = 'bigint'
super(IntegerField, self).__init__(**kw)
class FloatField(Field):
def __init__(self, **kw):
if not 'default' in kw:
kw['default'] = 0.0
if not 'ddl' in kw:
kw['ddl'] = 'real'
super(FloatField, self).__init__(**kw)
class BooleanField(Field):
def __init__(self, **kw):
if not 'default' in kw:
kw['default'] = False
if not 'ddl' in kw:
kw['ddl'] = 'bool'
super(BooleanField, self).__init__(**kw)
class TextField(Field):
def __init__(self, **kw):
if not 'default' in kw:
kw['default'] = ''
if not 'ddl' in kw:
kw['ddl'] = 'text'
super(TextField, self).__init__(**kw)
class BlobField(Field):
def __init__(self, **kw):
if not 'default' in kw:
kw['default'] = ''
if not 'ddl' in kw:
kw['ddl'] = 'blob'
super(BlobField, self).__init__(**kw)
class VersionField(Field):
def __init__(self, name=None):
super(VersionField, self).__init__(name=name, default=0, ddl='bigint')
class DateTimeField(Field):
def __init__(self, **kw):
if 'ddl' not in kw:
kw['ddl'] = 'datetime'
super(DateTimeField, self).__init__(**kw)
class DateField(Field):
def __init__(self, **kw):
if 'ddl' not in kw:
kw['ddl'] = 'date'
super(DateField, self).__init__(**kw)
class EnumField(Field):
def __init__(self, **kw):
if 'ddl' not in kw:
kw['ddl'] = 'enum'
super(EnumField, self).__init__(**kw)
_triggers = frozenset(['pre_insert', 'pre_update', 'pre_delete'])
def _gen_sql(table_name, mappings):
pk, unique_keys, keys = None, [], []
sql = ['-- generating SQL for %s:' % table_name, 'create table `%s` (' % table_name]
for f in sorted(mappings.values(), lambda x, y: cmp(x._order, y._order)):
if not hasattr(f, 'ddl'):
raise StandardError('no ddl in field "%s".' % f)
ddl = f.ddl
nullable = f.nullable
has_comment = not (f.comment == '')
has_default = f._default is not None
left = nullable and ' `%s` %s' % (f.name, ddl) or ' `%s` %s not null' % (f.name, ddl)
mid = has_default and ' default \'%s\'' % f._default or None
right = has_comment and ' comment \'%s\',' % f.comment or ','
line = mid and '%s%s%s' % (left, mid, right) or '%s%s' % (left, right)
if f.primary_key:
pk = f.name
line = ' `%s` %s not null auto_increment,' % (f.name, ddl)
elif f.unique_key:
unique_keys.append(f.name)
elif f.non_unique_key:
keys.append(f.name)
sql.append(line)
for uk in unique_keys:
sql.append(' unique key(`%s`),' % uk)
for k in keys:
sql.append(' key(`%s`),' % k)
sql.append(' primary key(`%s`)' % pk)
sql.append(')ENGINE=InnoDB DEFAULT CHARSET=utf8;')
return '\n'.join(sql)
class ModelMetaclass(type):
"""
Metaclass for model objects.
"""
def __new__(cls, name, bases, attrs):
# skip base Model class:
if name == 'Model':
return type.__new__(cls, name, bases, attrs)
# store all subclasses info:
if not hasattr(cls, 'subclasses'):
cls.subclasses = {}
if not name in cls.subclasses:
cls.subclasses[name] = name
else:
logging.warning('Redefine class: %s', name)
logging.info('Scan ORMapping %s...', name)
mappings = dict()
primary_key = None
for k, v in attrs.iteritems():
if isinstance(v, Field):
if not v.name:
v.name = k
logging.debug('Found mapping: %s => %s' % (k, v))
# check duplicate primary key:
if v.primary_key:
if primary_key:
raise TypeError('Cannot define more than 1 primary key in class: %s' % name)
if v.updatable:
# logging.warning('NOTE: change primary key to non-updatable.')
v.updatable = False
if v.nullable:
# logging.warning('NOTE: change primary key to non-nullable.')
v.nullable = False
primary_key = v
mappings[k] = v
# check exist of primary key:
if not primary_key:
raise TypeError('Primary key not defined in class: %s' % name)
for k in mappings.iterkeys():
attrs.pop(k)
if '__table__' not in attrs:
attrs['__table__'] = name.lower()
attrs['__mappings__'] = mappings
attrs['__primary_key__'] = primary_key
attrs['__sql__'] = lambda self: _gen_sql(attrs['__table__'], mappings)
for trigger in _triggers:
if trigger not in attrs:
attrs[trigger] = None
return type.__new__(cls, name, bases, attrs)
class Model(dict):
"""
Base class for ORM.
>>> class User(Model):
... id = IntegerField(primary_key=True)
... name = StringField()
... email = StringField(updatable=False)
... passwd = StringField(default=lambda: '******')
... last_modified = FloatField()
... def pre_insert(self):
... self.last_modified = time.time()
>>> u = User(id=10190, name='Michael', email='orm@db.org')
>>> r = u.insert()
>>> u.email
'orm@db.org'
>>> u.passwd
'******'
>>> u.last_modified > (time.time() - 2)
True
>>> f = User.get(10190)
>>> f.name
u'Michael'
>>> f.email
u'orm@db.org'
>>> f.email = 'changed@db.org'
>>> r = f.update() # change email but email is non-updatable!
>>> len(User.find_all())
1
>>> g = User.get(10190)
>>> g.email
u'orm@db.org'
>>> r = g.mark_deleted()
>>> len(db.select('select * from user where id=10190'))
0
>>> import json
>>> print User().__sql__()
-- generating SQL for user:
create table `user` (
`id` bigint not null,
`name` varchar(255) not null,
`email` varchar(255) not null,
`passwd` varchar(255) not null,
`last_modified` real not null,
primary key(`id`)
);
"""
__metaclass__ = ModelMetaclass
def __init__(self, **kw):
super(Model, self).__init__(**kw)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
def __setattr__(self, key, value):
self[key] = value
@classmethod
def get(cls, key_name, key_value):
"""
Get by primary/unique key.
"""
d = db.select_one('select * from %s where %s=?' % (cls.__table__, key_name), key_value)
if not d:
# TODO: change to logging?
raise AttributeError("Can't find in [%s] where %s=[%s]" % (cls.__table__, key_name, key_value))
return cls(**d) if d else None
@classmethod
def find_first(cls, where, *args):
"""
Find by where clause and return one result. If multiple results found,
only the first one returned. If no result found, return None.
"""
d = db.select_one('select * from %s %s' % (cls.__table__, where), *args)
return cls(**d) if d else None
@classmethod
def find_all(cls, *args):
"""
Find all and return list.
"""
L = db.select('select * from `%s`' % cls.__table__)
return [cls(**d) for d in L]
@classmethod
def find_by(cls, cols, where, *args):
"""
Find by where clause and return list.
"""
L = db.select('select %s from `%s` %s' % (cols, cls.__table__, where), *args)
if cols.find(',') == -1 and cols.strip() != '*':
return [d[0] for d in L]
return [cls(**d) for d in L]
@classmethod
def count_all(cls):
"""
Find by 'select count(pk) from table' and return integer.
"""
return db.select_int('select count(`%s`) from `%s`' % (cls.__primary_key__.name, cls.__table__))
@classmethod
def count_by(cls, where, *args):
"""
Find by 'select count(pk) from table where ... ' and return int.
"""
return db.select_int('select count(`%s`) from `%s` %s' % (cls.__primary_key__.name, cls.__table__, where), *args)
def update(self):
self.pre_update and self.pre_update()
L = []
args = []
for k, v in self.__mappings__.iteritems():
if v.updatable:
if hasattr(self, k):
arg = getattr(self, k)
else:
arg = v.default
setattr(self, k, arg)
L.append('`%s`=?' % k)
args.append(arg)
pk = self.__primary_key__.name
args.append(getattr(self, pk))
db.update('update `%s` set %s where %s=?' % (self.__table__, ','.join(L), pk), *args)
return self
def delete(self):
self.pre_delete and self.pre_delete()
pk = self.__primary_key__.name
args = (getattr(self, pk), )
db.update('delete from `%s` where `%s`=?' % (self.__table__, pk), *args)
return self
def insert(self):
self.pre_insert and self.pre_insert()
params = {}
for k, v in self.__mappings__.iteritems():
if v.insertable:
if not hasattr(self, k):
setattr(self, k, v.default)
params[v.name] = getattr(self, k)
try:
db.insert('%s' % self.__table__, **params)
except Exception as e:
logging.info(e.args)
print "MySQL Model.insert() error: args=", e.args
# TODO !!! generalize ORM return package
# return {'status': 'Failure', 'msg': e.args, 'data': self}
raise
return self
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
db.create_engine('www-data', 'www-data', 'test')
db.update('drop table if exists user')
db.update('create table user (id int primary key, name text, email text, passwd text, last_modified real)')
import doctest
doctest.testmod()
| Java |
package cn.libery.calendar.MaterialCalendar;
import android.content.Context;
import java.util.Collection;
import java.util.HashSet;
import cn.libery.calendar.MaterialCalendar.spans.DotSpan;
/**
* Decorate several days with a dot
*/
public class EventDecorator implements DayViewDecorator {
private int color;
private HashSet<CalendarDay> dates;
public EventDecorator(int color, Collection<CalendarDay> dates) {
this.color = color;
this.dates = new HashSet<>(dates);
}
@Override
public boolean shouldDecorate(CalendarDay day) {
return dates.contains(day);
}
@Override
public void decorate(DayViewFacade view, Context context) {
view.addSpan(new DotSpan(4, color));
}
}
| Java |
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
// import Layout from '../../components/Layout';
const title = 'Admin Page';
const isAdmin = false;
export default {
path: '/admin',
children : [
require('./dashboard').default,
require('./library').default,
require('./setting').default,
// require('./editor').default,
require('./news').default,
require('./monngon').default,
require('./product').default,
require('./seo').default,
],
async action({store, next}) {
let user = store.getState().user
const route = await next();
// Provide default values for title, description etc.
route.title = `${route.title || 'Amdmin Page'}`;
return route;
},
};
| Java |
using System;
using System.Collections.Generic;
namespace HarmonyLib
{
/// <summary>Specifies the type of method</summary>
///
public enum MethodType
{
/// <summary>This is a normal method</summary>
Normal,
/// <summary>This is a getter</summary>
Getter,
/// <summary>This is a setter</summary>
Setter,
/// <summary>This is a constructor</summary>
Constructor,
/// <summary>This is a static constructor</summary>
StaticConstructor,
/// <summary>This targets the MoveNext method of the enumerator result</summary>
Enumerator
}
/// <summary>Specifies the type of argument</summary>
///
public enum ArgumentType
{
/// <summary>This is a normal argument</summary>
Normal,
/// <summary>This is a reference argument (ref)</summary>
Ref,
/// <summary>This is an out argument (out)</summary>
Out,
/// <summary>This is a pointer argument (&)</summary>
Pointer
}
/// <summary>Specifies the type of patch</summary>
///
public enum HarmonyPatchType
{
/// <summary>Any patch</summary>
All,
/// <summary>A prefix patch</summary>
Prefix,
/// <summary>A postfix patch</summary>
Postfix,
/// <summary>A transpiler</summary>
Transpiler,
/// <summary>A finalizer</summary>
Finalizer,
/// <summary>A reverse patch</summary>
ReversePatch
}
/// <summary>Specifies the type of reverse patch</summary>
///
public enum HarmonyReversePatchType
{
/// <summary>Use the unmodified original method (directly from IL)</summary>
Original,
/// <summary>Use the original as it is right now including previous patches but excluding future ones</summary>
Snapshot
}
/// <summary>Specifies the type of method call dispatching mechanics</summary>
///
public enum MethodDispatchType
{
/// <summary>Call the method using dynamic dispatching if method is virtual (including overriden)</summary>
/// <remarks>
/// <para>
/// This is the built-in form of late binding (a.k.a. dynamic binding) and is the default dispatching mechanic in C#.
/// This directly corresponds with the <see cref="System.Reflection.Emit.OpCodes.Callvirt"/> instruction.
/// </para>
/// <para>
/// For virtual (including overriden) methods, the instance type's most-derived/overriden implementation of the method is called.
/// For non-virtual (including static) methods, same behavior as <see cref="Call"/>: the exact specified method implementation is called.
/// </para>
/// <para>
/// Note: This is not a fully dynamic dispatch, since non-virtual (including static) methods are still called non-virtually.
/// A fully dynamic dispatch in C# involves using
/// the <see href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/reference-types#the-dynamic-type"><c>dynamic</c> type</see>
/// (actually a fully dynamic binding, since even the name and overload resolution happens at runtime), which <see cref="MethodDispatchType"/> does not support.
/// </para>
/// </remarks>
VirtualCall,
/// <summary>Call the method using static dispatching, regardless of whether method is virtual (including overriden) or non-virtual (including static)</summary>
/// <remarks>
/// <para>
/// a.k.a. non-virtual dispatching, early binding, or static binding.
/// This directly corresponds with the <see cref="System.Reflection.Emit.OpCodes.Call"/> instruction.
/// </para>
/// <para>
/// For both virtual (including overriden) and non-virtual (including static) methods, the exact specified method implementation is called, without virtual/override mechanics.
/// </para>
/// </remarks>
Call
}
/// <summary>The base class for all Harmony annotations (not meant to be used directly)</summary>
///
public class HarmonyAttribute : Attribute
{
/// <summary>The common information for all attributes</summary>
public HarmonyMethod info = new HarmonyMethod();
}
/// <summary>Annotation to define your Harmony patch methods</summary>
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Delegate | AttributeTargets.Method, AllowMultiple = true)]
public class HarmonyPatch : HarmonyAttribute
{
/// <summary>An empty annotation can be used together with TargetMethod(s)</summary>
///
public HarmonyPatch()
{
}
/// <summary>An annotation that specifies a class to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
///
public HarmonyPatch(Type declaringType)
{
info.declaringType = declaringType;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="argumentTypes">The argument types of the method or constructor to patch</param>
///
public HarmonyPatch(Type declaringType, Type[] argumentTypes)
{
info.declaringType = declaringType;
info.argumentTypes = argumentTypes;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
///
public HarmonyPatch(Type declaringType, string methodName)
{
info.declaringType = declaringType;
info.methodName = methodName;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyPatch(Type declaringType, string methodName, params Type[] argumentTypes)
{
info.declaringType = declaringType;
info.methodName = methodName;
info.argumentTypes = argumentTypes;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">Array of <see cref="ArgumentType"/></param>
///
public HarmonyPatch(Type declaringType, string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
{
info.declaringType = declaringType;
info.methodName = methodName;
ParseSpecialArguments(argumentTypes, argumentVariations);
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodType">The <see cref="MethodType"/></param>
///
public HarmonyPatch(Type declaringType, MethodType methodType)
{
info.declaringType = declaringType;
info.methodType = methodType;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodType">The <see cref="MethodType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyPatch(Type declaringType, MethodType methodType, params Type[] argumentTypes)
{
info.declaringType = declaringType;
info.methodType = methodType;
info.argumentTypes = argumentTypes;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodType">The <see cref="MethodType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">Array of <see cref="ArgumentType"/></param>
///
public HarmonyPatch(Type declaringType, MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
{
info.declaringType = declaringType;
info.methodType = methodType;
ParseSpecialArguments(argumentTypes, argumentVariations);
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="methodType">The <see cref="MethodType"/></param>
///
public HarmonyPatch(Type declaringType, string methodName, MethodType methodType)
{
info.declaringType = declaringType;
info.methodName = methodName;
info.methodType = methodType;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
///
public HarmonyPatch(string methodName)
{
info.methodName = methodName;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyPatch(string methodName, params Type[] argumentTypes)
{
info.methodName = methodName;
info.argumentTypes = argumentTypes;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">An array of <see cref="ArgumentType"/></param>
///
public HarmonyPatch(string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
{
info.methodName = methodName;
ParseSpecialArguments(argumentTypes, argumentVariations);
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="methodType">The <see cref="MethodType"/></param>
///
public HarmonyPatch(string methodName, MethodType methodType)
{
info.methodName = methodName;
info.methodType = methodType;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodType">The <see cref="MethodType"/></param>
///
public HarmonyPatch(MethodType methodType)
{
info.methodType = methodType;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodType">The <see cref="MethodType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyPatch(MethodType methodType, params Type[] argumentTypes)
{
info.methodType = methodType;
info.argumentTypes = argumentTypes;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodType">The <see cref="MethodType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">An array of <see cref="ArgumentType"/></param>
///
public HarmonyPatch(MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
{
info.methodType = methodType;
ParseSpecialArguments(argumentTypes, argumentVariations);
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyPatch(Type[] argumentTypes)
{
info.argumentTypes = argumentTypes;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">An array of <see cref="ArgumentType"/></param>
///
public HarmonyPatch(Type[] argumentTypes, ArgumentType[] argumentVariations)
{
ParseSpecialArguments(argumentTypes, argumentVariations);
}
void ParseSpecialArguments(Type[] argumentTypes, ArgumentType[] argumentVariations)
{
if (argumentVariations is null || argumentVariations.Length == 0)
{
info.argumentTypes = argumentTypes;
return;
}
if (argumentTypes.Length < argumentVariations.Length)
throw new ArgumentException("argumentVariations contains more elements than argumentTypes", nameof(argumentVariations));
var types = new List<Type>();
for (var i = 0; i < argumentTypes.Length; i++)
{
var type = argumentTypes[i];
switch (argumentVariations[i])
{
case ArgumentType.Normal:
break;
case ArgumentType.Ref:
case ArgumentType.Out:
type = type.MakeByRefType();
break;
case ArgumentType.Pointer:
type = type.MakePointerType();
break;
}
types.Add(type);
}
info.argumentTypes = types.ToArray();
}
}
/// <summary>Annotation to define the original method for delegate injection</summary>
///
[AttributeUsage(AttributeTargets.Delegate, AllowMultiple = true)]
public class HarmonyDelegate : HarmonyPatch
{
/// <summary>An annotation that specifies a class to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
///
public HarmonyDelegate(Type declaringType)
: base(declaringType) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="argumentTypes">The argument types of the method or constructor to patch</param>
///
public HarmonyDelegate(Type declaringType, Type[] argumentTypes)
: base(declaringType, argumentTypes) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
///
public HarmonyDelegate(Type declaringType, string methodName)
: base(declaringType, methodName) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyDelegate(Type declaringType, string methodName, params Type[] argumentTypes)
: base(declaringType, methodName, argumentTypes) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">Array of <see cref="ArgumentType"/></param>
///
public HarmonyDelegate(Type declaringType, string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
: base(declaringType, methodName, argumentTypes, argumentVariations) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
///
public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType)
: base(declaringType, MethodType.Normal)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType, params Type[] argumentTypes)
: base(declaringType, MethodType.Normal, argumentTypes)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">Array of <see cref="ArgumentType"/></param>
///
public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType, Type[] argumentTypes, ArgumentType[] argumentVariations)
: base(declaringType, MethodType.Normal, argumentTypes, argumentVariations)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
///
public HarmonyDelegate(Type declaringType, string methodName, MethodDispatchType methodDispatchType)
: base(declaringType, methodName, MethodType.Normal)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
///
public HarmonyDelegate(string methodName)
: base(methodName) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyDelegate(string methodName, params Type[] argumentTypes)
: base(methodName, argumentTypes) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">An array of <see cref="ArgumentType"/></param>
///
public HarmonyDelegate(string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
: base(methodName, argumentTypes, argumentVariations) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
///
public HarmonyDelegate(string methodName, MethodDispatchType methodDispatchType)
: base(methodName, MethodType.Normal)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies call dispatching mechanics for the delegate</summary>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
///
public HarmonyDelegate(MethodDispatchType methodDispatchType)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyDelegate(MethodDispatchType methodDispatchType, params Type[] argumentTypes)
: base(MethodType.Normal, argumentTypes)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">An array of <see cref="ArgumentType"/></param>
///
public HarmonyDelegate(MethodDispatchType methodDispatchType, Type[] argumentTypes, ArgumentType[] argumentVariations)
: base(MethodType.Normal, argumentTypes, argumentVariations)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyDelegate(Type[] argumentTypes)
: base(argumentTypes) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">An array of <see cref="ArgumentType"/></param>
///
public HarmonyDelegate(Type[] argumentTypes, ArgumentType[] argumentVariations)
: base(argumentTypes, argumentVariations) { }
}
/// <summary>Annotation to define your standin methods for reverse patching</summary>
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class HarmonyReversePatch : HarmonyAttribute
{
/// <summary>An annotation that specifies the type of reverse patching</summary>
/// <param name="type">The <see cref="HarmonyReversePatchType"/> of the reverse patch</param>
///
public HarmonyReversePatch(HarmonyReversePatchType type = HarmonyReversePatchType.Original)
{
info.reversePatchType = type;
}
}
/// <summary>A Harmony annotation to define that all methods in a class are to be patched</summary>
///
[AttributeUsage(AttributeTargets.Class)]
public class HarmonyPatchAll : HarmonyAttribute
{
}
/// <summary>A Harmony annotation</summary>
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class HarmonyPriority : HarmonyAttribute
{
/// <summary>A Harmony annotation to define patch priority</summary>
/// <param name="priority">The priority</param>
///
public HarmonyPriority(int priority)
{
info.priority = priority;
}
}
/// <summary>A Harmony annotation</summary>
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class HarmonyBefore : HarmonyAttribute
{
/// <summary>A Harmony annotation to define that a patch comes before another patch</summary>
/// <param name="before">The array of harmony IDs of the other patches</param>
///
public HarmonyBefore(params string[] before)
{
info.before = before;
}
}
/// <summary>A Harmony annotation</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class HarmonyAfter : HarmonyAttribute
{
/// <summary>A Harmony annotation to define that a patch comes after another patch</summary>
/// <param name="after">The array of harmony IDs of the other patches</param>
///
public HarmonyAfter(params string[] after)
{
info.after = after;
}
}
/// <summary>A Harmony annotation</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class HarmonyDebug : HarmonyAttribute
{
/// <summary>A Harmony annotation to debug a patch (output uses <see cref="FileLog"/> to log to your Desktop)</summary>
///
public HarmonyDebug()
{
info.debug = true;
}
}
/// <summary>Specifies the Prepare function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyPrepare : Attribute
{
}
/// <summary>Specifies the Cleanup function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyCleanup : Attribute
{
}
/// <summary>Specifies the TargetMethod function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyTargetMethod : Attribute
{
}
/// <summary>Specifies the TargetMethods function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyTargetMethods : Attribute
{
}
/// <summary>Specifies the Prefix function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyPrefix : Attribute
{
}
/// <summary>Specifies the Postfix function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyPostfix : Attribute
{
}
/// <summary>Specifies the Transpiler function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyTranspiler : Attribute
{
}
/// <summary>Specifies the Finalizer function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyFinalizer : Attribute
{
}
/// <summary>A Harmony annotation</summary>
///
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]
public class HarmonyArgument : Attribute
{
/// <summary>The name of the original argument</summary>
///
public string OriginalName { get; private set; }
/// <summary>The index of the original argument</summary>
///
public int Index { get; private set; }
/// <summary>The new name of the original argument</summary>
///
public string NewName { get; private set; }
/// <summary>An annotation to declare injected arguments by name</summary>
///
public HarmonyArgument(string originalName) : this(originalName, null)
{
}
/// <summary>An annotation to declare injected arguments by index</summary>
/// <param name="index">Zero-based index</param>
///
public HarmonyArgument(int index) : this(index, null)
{
}
/// <summary>An annotation to declare injected arguments by renaming them</summary>
/// <param name="originalName">Name of the original argument</param>
/// <param name="newName">New name</param>
///
public HarmonyArgument(string originalName, string newName)
{
OriginalName = originalName;
Index = -1;
NewName = newName;
}
/// <summary>An annotation to declare injected arguments by index and renaming them</summary>
/// <param name="index">Zero-based index</param>
/// <param name="name">New name</param>
///
public HarmonyArgument(int index, string name)
{
OriginalName = null;
Index = index;
NewName = name;
}
}
}
| Java |
<?php
namespace MyApplication\Navigation\Navigation;
interface NavigationControlFactory
{
/**
* @return NavigationControl
*/
function create();
}
| Java |
import pytest
from tests.base import Author, Post, Comment, Keyword, fake
def make_author():
return Author(
id=fake.random_int(),
first_name=fake.first_name(),
last_name=fake.last_name(),
twitter=fake.domain_word(),
)
def make_post(with_comments=True, with_author=True, with_keywords=True):
comments = [make_comment() for _ in range(2)] if with_comments else []
keywords = [make_keyword() for _ in range(3)] if with_keywords else []
author = make_author() if with_author else None
return Post(
id=fake.random_int(),
title=fake.catch_phrase(),
author=author,
author_id=author.id if with_author else None,
comments=comments,
keywords=keywords,
)
def make_comment(with_author=True):
author = make_author() if with_author else None
return Comment(id=fake.random_int(), body=fake.bs(), author=author)
def make_keyword():
return Keyword(keyword=fake.domain_word())
@pytest.fixture()
def author():
return make_author()
@pytest.fixture()
def authors():
return [make_author() for _ in range(3)]
@pytest.fixture()
def comments():
return [make_comment() for _ in range(3)]
@pytest.fixture()
def post():
return make_post()
@pytest.fixture()
def post_with_null_comment():
return make_post(with_comments=False)
@pytest.fixture()
def post_with_null_author():
return make_post(with_author=False)
@pytest.fixture()
def posts():
return [make_post() for _ in range(3)]
| Java |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="author" content="Aurelio De Rosa">
<title>Geolocation API Demo by Aurelio De Rosa</title>
<style>
*
{
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
body
{
max-width: 500px;
margin: 2em auto;
padding: 0 0.5em;
font-size: 20px;
}
h1
{
text-align: center;
}
.api-support
{
display: block;
}
.hidden
{
display: none;
}
.buttons-wrapper
{
text-align: center;
}
.button-demo
{
padding: 0.5em;
margin: 1em auto;
}
.g-info
{
font-weight: bold;
}
#log
{
height: 200px;
width: 100%;
overflow-y: scroll;
border: 1px solid #333333;
line-height: 1.3em;
}
.author
{
display: block;
margin-top: 1em;
}
</style>
</head>
<body>
<a href="http://code.tutsplus.com/tutorials/an-introduction-to-the-geolocation-api--cms-20071">Go back to the article</a>
<span id="g-unsupported" class="api-support hidden">API not supported</span>
<h1>Geolocation API</h1>
<div class="buttons-wrapper">
<button id="button-get-position" class="button-demo">Get current position</button>
<button id="button-watch-position" class="button-demo">Watch position</button>
<button id="button-stop-watching" class="button-demo">Stop watching position</button>
</div>
<h2>Information</h2>
<div id="g-information">
<ul>
<li>
Your position is <span id="latitude" class="g-info">unavailable</span>° latitude,
<span id="longitude" class="g-info">unavailable</span>° longitude (with an accuracy of
<span id="position-accuracy" class="g-info">unavailable</span> meters)
</li>
<li>
Your altitude is <span id="altitude" class="g-info">unavailable</span> meters
(with an accuracy of <span id="altitude-accuracy" class="g-info">unavailable</span> meters)
</li>
<li>You're <span id="heading" class="g-info">unavailable</span>° from the True north</li>
<li>You're moving at a speed of <span id="speed" class="g-info">unavailable</span>° meters/second</li>
<li>Data updated at <span id="timestamp" class="g-info">unavailable</span></li>
</ul>
</div>
<h3>Log</h3>
<div id="log"></div>
<button id="clear-log" class="button-demo">Clear log</button>
<small class="author">
Demo created by <a href="http://www.audero.it">Aurelio De Rosa</a>
(<a href="https://twitter.com/AurelioDeRosa">@AurelioDeRosa</a>).<br />
This demo is part of the <a href="https://github.com/AurelioDeRosa/HTML5-API-demos">HTML5 API demos repository</a>.
</small>
<script>
if (!(window.navigator && window.navigator.geolocation)) {
document.getElementById('g-unsupported').classList.remove('hidden');
['button-get-position', 'button-watch-position', 'button-stop-watching'].forEach(function(elementId) {
document.getElementById(elementId).setAttribute('disabled', 'disabled');
});
} else {
var log = document.getElementById('log');
var watchId = null;
var positionOptions = {
enableHighAccuracy: true,
timeout: 10 * 1000, // 10 seconds
maximumAge: 30 * 1000 // 30 seconds
};
function success(position) {
document.getElementById('latitude').innerHTML = position.coords.latitude;
document.getElementById('longitude').innerHTML = position.coords.longitude;
document.getElementById('position-accuracy').innerHTML = position.coords.accuracy;
document.getElementById('altitude').innerHTML = position.coords.altitude ? position.coords.altitude :
'unavailable';
document.getElementById('altitude-accuracy').innerHTML = position.coords.altitudeAccuracy ?
position.coords.altitudeAccuracy :
'unavailable';
document.getElementById('heading').innerHTML = position.coords.heading ? position.coords.heading :
'unavailable';
document.getElementById('speed').innerHTML = position.coords.speed ? position.coords.speed :
'unavailable';
document.getElementById('timestamp').innerHTML = (new Date(position.timestamp)).toString();
log.innerHTML = 'Position succesfully retrieved<br />' + log.innerHTML;
}
function error(positionError) {
log.innerHTML = 'Error: ' + positionError.message + '<br />' + log.innerHTML;
}
document.getElementById('button-get-position').addEventListener('click', function() {
navigator.geolocation.getCurrentPosition(success, error, positionOptions);
});
document.getElementById('button-watch-position').addEventListener('click', function() {
watchId = navigator.geolocation.watchPosition(success, error, positionOptions);
});
document.getElementById('button-stop-watching').addEventListener('click', function() {
if (watchId !== null) {
navigator.geolocation.clearWatch(watchId);
log.innerHTML = 'Stopped watching position<br />' + log.innerHTML;
}
});
document.getElementById('clear-log').addEventListener('click', function() {
log.innerHTML = '';
});
}
</script>
</body>
</html>
| Java |
<!DOCTYPE html>
<!--[if IEMobile 7 ]> <html class="no-js iem7"> <![endif]-->
<!--[if (gt IEMobile 7)|!(IEMobile)]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="cleartype" content="on">
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="img/touch/apple-touch-icon-144x144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="img/touch/apple-touch-icon-114x114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="img/touch/apple-touch-icon-72x72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="img/touch/apple-touch-icon-57x57-precomposed.png">
<link rel="shortcut icon" href="img/touch/apple-touch-icon.png">
<!-- Tile icon for Win8 (144x144 + tile color) -->
<meta name="msapplication-TileImage" content="img/touch/apple-touch-icon-144x144-precomposed.png">
<meta name="msapplication-TileColor" content="#222222">
<!-- For iOS web apps. Delete if not needed. https://github.com/h5bp/mobile-boilerplate/issues/94 -->
<!--
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="">
-->
<!-- This script prevents links from opening in Mobile Safari. https://gist.github.com/1042026 -->
<!--
<script>(function(a,b,c){if(c in b&&b[c]){var d,e=a.location,f=/^(a|html)$/i;a.addEventListener("click",function(a){d=a.target;while(!f.test(d.nodeName))d=d.parentNode;"href"in d&&(d.href.indexOf("http")||~d.href.indexOf(e.host))&&(a.preventDefault(),e.href=d.href)},!1)}})(document,window.navigator,"standalone")</script>
-->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/vendor/modernizr-2.6.2.min.js"></script>
</head>
<body>
Blablabla c'est moi Lisa
<script src="js/vendor/zepto.min.js"></script>
<script src="js/helper.js"></script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
var _gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1;
g.src=("https:"==location.protocol?"//ssl":"//www")+".google-analytics.com/ga.js";
s.parentNode.insertBefore(g,s)}(document,"script"));
</script>
</body>
</html>
| Java |
# Declaring a Function
def recurPowerNew(base, exp):
# Base case is when exp = 0
if exp <= 0:
return 1
# Recursive Call
elif exp % 2 == 0:
return recurPowerNew(base*base, exp/2)
return base * recurPowerNew(base, exp - 1)
| Java |
c rutina leemallab
c lee el fichero de control de lineas y longitudes de onda:'mallaobs'
c ntau : numero de puntos en tau
c tau : log10(tau)
c ntl : numero total de lineas
c nlin : indice de cada linea y de cada blend
c npas : numero de puntos en cada linea
c dlamda:cada delta de l.d.o. en ma
c nble :numero de blends de cada linea
subroutine leemalla2(mallaobs,ntl,nli,nliobs,nlin,npasobs,
& npas,dlamdaobs,dlamda,nble,nposi,indice)
include 'PARAMETER' !por kl
integer npasobs(*),npas(kl),nble(kl),nd(kl),nposi(*),nlin(kl),ndd(kl,kl),nblee(kl)
real*4 dlamdaobs(*),dlamda(kld),dini,dipa,difi,dinii(kl),dipaa(kl),difii(kt)
integer indice(*),nddd(50),blanco
character mallaobs*(*),mensajito*31
character*80 men1,men2,men3
character*100 control
common/canal/icanal
common/nombrecontrol/control
common/nciclos/nciclos
common/contraste/contr
men1=' '
men2=' '
men3=' '
if(contr.gt.-1.e5.and.nciclos.gt.0)then
ntl=ntl-1
nliobs=nliobs-1
end if
ican=57
mensajito=' containing the wavelength grid'
call cabecera(ican,mallaobs,mensajito,ifail)
if(ifail.eq.1)goto 999
jj=0
k=0
nli=0
numlin=0
do i=1,1000
call mreadmalla(ican,ntonto,nddd,ddinii,ddipaa,ddifii,ierror,blanco)
if(ierror.eq.1)goto 8 !si he llegado al final del fichero
if(blanco.ne.1)then
numlin=numlin+1
if(numlin.gt.kl.or.ntonto.gt.kl)then
men1='STOP: The number of lines in the wavelength grid is larger than the '
men2=' current limit. Decrease this number or change the PARAMETER file.'
call mensaje(2,men1,men2,men3)
end if
nblee(numlin)=ntonto
dinii(numlin)=ddinii
dipaa(numlin)=ddipaa
difii(numlin)=ddifii
do j=1,nblee(numlin)
ndd(numlin,j)=nddd(j)
enddo
endif !el de blanco.ne.1
enddo
8 close(ican)
ntl=numlin
c Ahora las ordenamos como en los perfiles:
do i=1,ntl !indice en los perfiles
icheck=0
do l=1,numlin !indice en la malla
c print*,'indice(i) vale',i,indice(i)
if(indice(i).eq.ndd(l,1).and.icheck.lt.1)then !he encontrado una
icheck=icheck+1
nble(i)=nblee(l)
do ll=1,nblee(l)
nd(ll)=ndd(l,ll)
enddo
dini=dinii(l)
dipa=dipaa(l)
difi=difii(l)
do j=1,nble(i)
jj=jj+1
nlin(jj)=nd(j)
c print*,'nlin,jj',jj,nlin(jj)
end do
ntlblends=jj
pasmin=1.e30
primero=dlamdaobs(k+1)
ultimo=dlamdaobs(k+npasobs(i))
do j=1,npasobs(i)-1
k=k+1
pasoobs=dlamdaobs(k+1)-dlamdaobs(k)
pasmin=min(pasmin,pasoobs) !cambio amin0 por min
end do
k=k+1
c if(dipa.gt.pasmin)dipa=pasmin !provisional!!!!
if(dini.gt.primero)dini=primero
if(difi.lt.ultimo)difi=ultimo
ntimes=int(pasmin/dipa) !numero de veces que la red fina divide a la obs
c dipa=pasmin/ntimes
n1=nint((primero-dini)/dipa) !numero de puntos anteriores
n2=nint((difi-ultimo)/dipa) !nuero de puntos posteriores
dini=primero-n1*dipa
difi=ultimo+n2*dipa
c print*,'primero,ultimo,n1,n2,dini,difi',primero,ultimo,n1,n2,dini,difi
npas(i)=(difi-dini)/dipa+1
if(10*( (difi-dini)/dipa+1 -int( (difi-dini)/dipa+1 ) ).gt..5) npas(i)=npas(i)+1
do j=1,npas(i)
nli=nli+1
dlamda(nli)=dini+(j-1)*dipa
c print*,'en la malla,la serie es',nli,dlamda(nli),dipa
end do
endif
end do !fin del do en l
if(icheck.eq.0)then
men1='STOP: There are lines in the observed/stray light profiles which'
men2=' do not appear in the wavelength grid.'
men3=' Check also the wavelength grid for missing : symbols.'
call mensaje(3,men1,men2,men3)
endif
9 enddo !fin del do en i
c print*,'pasos 1 y 2',npas(1),npas(2)
k=1
epsilon=dipa/2.
do i=1,nliobs
dd=dlamdaobs(i)
do while(k.lt.nli.and.dd.gt.dlamda(k)+epsilon)
k=k+1
end do
do while(k.lt.nli.and.dd.lt.dlamda(k)-epsilon)
k=k+1
end do
do while(k.lt.nli.and.dd.gt.dlamda(k)+epsilon)
k=k+1
end do
nposi(i)=k
end do
if(contr.gt.-1.e5.and.nciclos.gt.0)then
ntl=ntl+1
ntlblends=ntlblends+1
nlin(ntlblends)=0
npas(ntl)=1
nble(ntl)=1
nli=nli+1
nliobs=nliobs+1
dlamda(nli)=0.
nposi(nliobs)=nli
end if
212 print*,'Number of wavelengths in the wavelength grid : ',nli
close(ican)
return
c ------------------------------------------------------------------------
c Mensajes de error:
999 men1='STOP: The file containing the wavelength grid does NOT exist:'
men2=mallaobs
call mensaje(2,men1,men2,men3)
992 men1='STOP: Incorrect format in the file containing the wavelength grid:'
men2=mallaobs
call mensaje(2,men1,men2,men3)
end
| Java |
// flow-typed signature: 267f077135db8f8ca8e152b4b262406e
// flow-typed version: <<STUB>>/react-redux_v^5.0.4/flow_v0.46.0
/**
* This is an autogenerated libdef stub for:
*
* 'react-redux'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'react-redux' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'react-redux/dist/react-redux' {
declare module.exports: any;
}
declare module 'react-redux/dist/react-redux.min' {
declare module.exports: any;
}
declare module 'react-redux/es/components/connectAdvanced' {
declare module.exports: any;
}
declare module 'react-redux/es/components/Provider' {
declare module.exports: any;
}
declare module 'react-redux/es/connect/connect' {
declare module.exports: any;
}
declare module 'react-redux/es/connect/mapDispatchToProps' {
declare module.exports: any;
}
declare module 'react-redux/es/connect/mapStateToProps' {
declare module.exports: any;
}
declare module 'react-redux/es/connect/mergeProps' {
declare module.exports: any;
}
declare module 'react-redux/es/connect/selectorFactory' {
declare module.exports: any;
}
declare module 'react-redux/es/connect/verifySubselectors' {
declare module.exports: any;
}
declare module 'react-redux/es/connect/wrapMapToProps' {
declare module.exports: any;
}
declare module 'react-redux/es/index' {
declare module.exports: any;
}
declare module 'react-redux/es/utils/PropTypes' {
declare module.exports: any;
}
declare module 'react-redux/es/utils/shallowEqual' {
declare module.exports: any;
}
declare module 'react-redux/es/utils/Subscription' {
declare module.exports: any;
}
declare module 'react-redux/es/utils/verifyPlainObject' {
declare module.exports: any;
}
declare module 'react-redux/es/utils/warning' {
declare module.exports: any;
}
declare module 'react-redux/es/utils/wrapActionCreators' {
declare module.exports: any;
}
declare module 'react-redux/lib/components/connectAdvanced' {
declare module.exports: any;
}
declare module 'react-redux/lib/components/Provider' {
declare module.exports: any;
}
declare module 'react-redux/lib/connect/connect' {
declare module.exports: any;
}
declare module 'react-redux/lib/connect/mapDispatchToProps' {
declare module.exports: any;
}
declare module 'react-redux/lib/connect/mapStateToProps' {
declare module.exports: any;
}
declare module 'react-redux/lib/connect/mergeProps' {
declare module.exports: any;
}
declare module 'react-redux/lib/connect/selectorFactory' {
declare module.exports: any;
}
declare module 'react-redux/lib/connect/verifySubselectors' {
declare module.exports: any;
}
declare module 'react-redux/lib/connect/wrapMapToProps' {
declare module.exports: any;
}
declare module 'react-redux/lib/index' {
declare module.exports: any;
}
declare module 'react-redux/lib/utils/PropTypes' {
declare module.exports: any;
}
declare module 'react-redux/lib/utils/shallowEqual' {
declare module.exports: any;
}
declare module 'react-redux/lib/utils/Subscription' {
declare module.exports: any;
}
declare module 'react-redux/lib/utils/verifyPlainObject' {
declare module.exports: any;
}
declare module 'react-redux/lib/utils/warning' {
declare module.exports: any;
}
declare module 'react-redux/lib/utils/wrapActionCreators' {
declare module.exports: any;
}
declare module 'react-redux/src/components/connectAdvanced' {
declare module.exports: any;
}
declare module 'react-redux/src/components/Provider' {
declare module.exports: any;
}
declare module 'react-redux/src/connect/connect' {
declare module.exports: any;
}
declare module 'react-redux/src/connect/mapDispatchToProps' {
declare module.exports: any;
}
declare module 'react-redux/src/connect/mapStateToProps' {
declare module.exports: any;
}
declare module 'react-redux/src/connect/mergeProps' {
declare module.exports: any;
}
declare module 'react-redux/src/connect/selectorFactory' {
declare module.exports: any;
}
declare module 'react-redux/src/connect/verifySubselectors' {
declare module.exports: any;
}
declare module 'react-redux/src/connect/wrapMapToProps' {
declare module.exports: any;
}
declare module 'react-redux/src/index' {
declare module.exports: any;
}
declare module 'react-redux/src/utils/PropTypes' {
declare module.exports: any;
}
declare module 'react-redux/src/utils/shallowEqual' {
declare module.exports: any;
}
declare module 'react-redux/src/utils/Subscription' {
declare module.exports: any;
}
declare module 'react-redux/src/utils/verifyPlainObject' {
declare module.exports: any;
}
declare module 'react-redux/src/utils/warning' {
declare module.exports: any;
}
declare module 'react-redux/src/utils/wrapActionCreators' {
declare module.exports: any;
}
// Filename aliases
declare module 'react-redux/dist/react-redux.js' {
declare module.exports: $Exports<'react-redux/dist/react-redux'>;
}
declare module 'react-redux/dist/react-redux.min.js' {
declare module.exports: $Exports<'react-redux/dist/react-redux.min'>;
}
declare module 'react-redux/es/components/connectAdvanced.js' {
declare module.exports: $Exports<'react-redux/es/components/connectAdvanced'>;
}
declare module 'react-redux/es/components/Provider.js' {
declare module.exports: $Exports<'react-redux/es/components/Provider'>;
}
declare module 'react-redux/es/connect/connect.js' {
declare module.exports: $Exports<'react-redux/es/connect/connect'>;
}
declare module 'react-redux/es/connect/mapDispatchToProps.js' {
declare module.exports: $Exports<'react-redux/es/connect/mapDispatchToProps'>;
}
declare module 'react-redux/es/connect/mapStateToProps.js' {
declare module.exports: $Exports<'react-redux/es/connect/mapStateToProps'>;
}
declare module 'react-redux/es/connect/mergeProps.js' {
declare module.exports: $Exports<'react-redux/es/connect/mergeProps'>;
}
declare module 'react-redux/es/connect/selectorFactory.js' {
declare module.exports: $Exports<'react-redux/es/connect/selectorFactory'>;
}
declare module 'react-redux/es/connect/verifySubselectors.js' {
declare module.exports: $Exports<'react-redux/es/connect/verifySubselectors'>;
}
declare module 'react-redux/es/connect/wrapMapToProps.js' {
declare module.exports: $Exports<'react-redux/es/connect/wrapMapToProps'>;
}
declare module 'react-redux/es/index.js' {
declare module.exports: $Exports<'react-redux/es/index'>;
}
declare module 'react-redux/es/utils/PropTypes.js' {
declare module.exports: $Exports<'react-redux/es/utils/PropTypes'>;
}
declare module 'react-redux/es/utils/shallowEqual.js' {
declare module.exports: $Exports<'react-redux/es/utils/shallowEqual'>;
}
declare module 'react-redux/es/utils/Subscription.js' {
declare module.exports: $Exports<'react-redux/es/utils/Subscription'>;
}
declare module 'react-redux/es/utils/verifyPlainObject.js' {
declare module.exports: $Exports<'react-redux/es/utils/verifyPlainObject'>;
}
declare module 'react-redux/es/utils/warning.js' {
declare module.exports: $Exports<'react-redux/es/utils/warning'>;
}
declare module 'react-redux/es/utils/wrapActionCreators.js' {
declare module.exports: $Exports<'react-redux/es/utils/wrapActionCreators'>;
}
declare module 'react-redux/lib/components/connectAdvanced.js' {
declare module.exports: $Exports<'react-redux/lib/components/connectAdvanced'>;
}
declare module 'react-redux/lib/components/Provider.js' {
declare module.exports: $Exports<'react-redux/lib/components/Provider'>;
}
declare module 'react-redux/lib/connect/connect.js' {
declare module.exports: $Exports<'react-redux/lib/connect/connect'>;
}
declare module 'react-redux/lib/connect/mapDispatchToProps.js' {
declare module.exports: $Exports<'react-redux/lib/connect/mapDispatchToProps'>;
}
declare module 'react-redux/lib/connect/mapStateToProps.js' {
declare module.exports: $Exports<'react-redux/lib/connect/mapStateToProps'>;
}
declare module 'react-redux/lib/connect/mergeProps.js' {
declare module.exports: $Exports<'react-redux/lib/connect/mergeProps'>;
}
declare module 'react-redux/lib/connect/selectorFactory.js' {
declare module.exports: $Exports<'react-redux/lib/connect/selectorFactory'>;
}
declare module 'react-redux/lib/connect/verifySubselectors.js' {
declare module.exports: $Exports<'react-redux/lib/connect/verifySubselectors'>;
}
declare module 'react-redux/lib/connect/wrapMapToProps.js' {
declare module.exports: $Exports<'react-redux/lib/connect/wrapMapToProps'>;
}
declare module 'react-redux/lib/index.js' {
declare module.exports: $Exports<'react-redux/lib/index'>;
}
declare module 'react-redux/lib/utils/PropTypes.js' {
declare module.exports: $Exports<'react-redux/lib/utils/PropTypes'>;
}
declare module 'react-redux/lib/utils/shallowEqual.js' {
declare module.exports: $Exports<'react-redux/lib/utils/shallowEqual'>;
}
declare module 'react-redux/lib/utils/Subscription.js' {
declare module.exports: $Exports<'react-redux/lib/utils/Subscription'>;
}
declare module 'react-redux/lib/utils/verifyPlainObject.js' {
declare module.exports: $Exports<'react-redux/lib/utils/verifyPlainObject'>;
}
declare module 'react-redux/lib/utils/warning.js' {
declare module.exports: $Exports<'react-redux/lib/utils/warning'>;
}
declare module 'react-redux/lib/utils/wrapActionCreators.js' {
declare module.exports: $Exports<'react-redux/lib/utils/wrapActionCreators'>;
}
declare module 'react-redux/src/components/connectAdvanced.js' {
declare module.exports: $Exports<'react-redux/src/components/connectAdvanced'>;
}
declare module 'react-redux/src/components/Provider.js' {
declare module.exports: $Exports<'react-redux/src/components/Provider'>;
}
declare module 'react-redux/src/connect/connect.js' {
declare module.exports: $Exports<'react-redux/src/connect/connect'>;
}
declare module 'react-redux/src/connect/mapDispatchToProps.js' {
declare module.exports: $Exports<'react-redux/src/connect/mapDispatchToProps'>;
}
declare module 'react-redux/src/connect/mapStateToProps.js' {
declare module.exports: $Exports<'react-redux/src/connect/mapStateToProps'>;
}
declare module 'react-redux/src/connect/mergeProps.js' {
declare module.exports: $Exports<'react-redux/src/connect/mergeProps'>;
}
declare module 'react-redux/src/connect/selectorFactory.js' {
declare module.exports: $Exports<'react-redux/src/connect/selectorFactory'>;
}
declare module 'react-redux/src/connect/verifySubselectors.js' {
declare module.exports: $Exports<'react-redux/src/connect/verifySubselectors'>;
}
declare module 'react-redux/src/connect/wrapMapToProps.js' {
declare module.exports: $Exports<'react-redux/src/connect/wrapMapToProps'>;
}
declare module 'react-redux/src/index.js' {
declare module.exports: $Exports<'react-redux/src/index'>;
}
declare module 'react-redux/src/utils/PropTypes.js' {
declare module.exports: $Exports<'react-redux/src/utils/PropTypes'>;
}
declare module 'react-redux/src/utils/shallowEqual.js' {
declare module.exports: $Exports<'react-redux/src/utils/shallowEqual'>;
}
declare module 'react-redux/src/utils/Subscription.js' {
declare module.exports: $Exports<'react-redux/src/utils/Subscription'>;
}
declare module 'react-redux/src/utils/verifyPlainObject.js' {
declare module.exports: $Exports<'react-redux/src/utils/verifyPlainObject'>;
}
declare module 'react-redux/src/utils/warning.js' {
declare module.exports: $Exports<'react-redux/src/utils/warning'>;
}
declare module 'react-redux/src/utils/wrapActionCreators.js' {
declare module.exports: $Exports<'react-redux/src/utils/wrapActionCreators'>;
}
| Java |
import * as riot from 'riot'
import { init, compile } from '../../helpers/'
import TargetComponent from '../../../dist/tags/popup/su-popup.js'
describe('su-popup', function () {
let element, component
let spyOnMouseover, spyOnMouseout
init(riot)
const mount = opts => {
const option = Object.assign({
'onmouseover': spyOnMouseover,
'onmouseout': spyOnMouseout,
}, opts)
element = document.createElement('app')
riot.register('su-popup', TargetComponent)
const AppComponent = compile(`
<app>
<su-popup
tooltip="{ props.tooltip }"
data-title="{ props.dataTitle }"
data-variation="{ props.dataVariation }"
onmouseover="{ () => dispatch('mouseover') }"
onmouseout="{ () => dispatch('mouseout') }"
><i class="add icon"></i></su-popup>
</app>`)
riot.register('app', AppComponent)
component = riot.mount(element, option)[0]
}
beforeEach(function () {
spyOnMouseover = sinon.spy()
spyOnMouseout = sinon.spy()
})
afterEach(function () {
riot.unregister('su-popup')
riot.unregister('app')
})
it('is mounted', function () {
mount()
expect(component).to.be.ok
})
it('show and hide popup', function () {
mount({
tooltip: 'Add users to your feed'
})
expect(component.$('.content').innerHTML).to.equal('Add users to your feed')
expect(component.$('su-popup .ui.popup').classList.contains('nowrap')).to.equal(true)
fireEvent(component.$('su-popup .ui.popup'), 'mouseover')
expect(spyOnMouseover).to.have.been.calledOnce
expect(component.$('su-popup .ui.popup').classList.contains('visible')).to.equal(true)
expect(component.$('su-popup .ui.popup').classList.contains('hidden')).to.equal(false)
fireEvent(component.$('su-popup .ui.popup'), 'mouseout')
expect(spyOnMouseout).to.have.been.calledOnce
expect(component.$('su-popup .ui.popup').classList.contains('visible')).to.equal(false)
expect(component.$('su-popup .ui.popup').classList.contains('hidden')).to.equal(true)
})
it('header', function () {
mount({
tooltip: 'Add users to your feed',
dataTitle: 'Title'
})
expect(component.$('.header').innerHTML).to.equal('Title')
expect(component.$('.content').innerHTML).to.equal('Add users to your feed')
})
it('wide', function () {
mount({
tooltip: 'Add users to your feed',
dataVariation: 'wide'
})
expect(component.$('su-popup .ui.popup').classList.contains('wide')).to.equal(true)
expect(component.$('su-popup .ui.popup').classList.contains('nowrap')).to.equal(false)
})
})
| Java |
package app.components.semanticui
import japgolly.scalajs.react
import japgolly.scalajs.react.{Callback, Children}
import japgolly.scalajs.react.vdom.VdomNode
import scala.scalajs.js
object Menu {
val component = react.JsComponent[js.Object, Children.Varargs, Null](SemanticUiComponents.Menu)
def apply()(children: VdomNode*) = {
val props = js.Dynamic.literal(
)
component(props)(children:_*)
}
object Item {
val component = react.JsComponent[js.Object, Children.Varargs, Null](SemanticUiComponents.Menu.Item)
def apply(name: js.UndefOr[String] = js.undefined,
as: js.UndefOr[String] = js.undefined,
active: js.UndefOr[Boolean] = js.undefined,
onClick: Callback = Callback.empty,
position: js.UndefOr[Position.Value] = js.undefined,
)(children: VdomNode*) = {
val props = js.Dynamic.literal(
name = name,
as = as,
active = active,
onClick = onClick.toJsCallback,
position = position.map(Position.toStr),
)
component(props)(children:_*)
}
}
object Menu {
val component = react.JsComponent[js.Object, Children.Varargs, Null](SemanticUiComponents.Menu.Menu)
def apply(position: js.UndefOr[Position.Value] = js.undefined,
)(children: VdomNode*) = {
val props = js.Dynamic.literal(
position = position.map(Position.toStr),
)
component(props)(children:_*)
}
}
}
| Java |
require "graph_engine/engine"
module GraphEngine
end
| Java |
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { SharedModule, ExamplesRouterViewerComponent } from '../../../shared';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
@NgModule({
imports: [
SharedModule,
AppModule,
RouterModule.forChild([
{
path: '',
component: ExamplesRouterViewerComponent,
data: {
examples: [
{
title: 'Material Prefix and Suffix',
description: `
This demonstrates adding a material suffix and prefix for material form fields.
`,
component: AppComponent,
files: [
{
file: 'app.component.html',
content: require('!!highlight-loader?raw=true&lang=html!./app.component.html'),
filecontent: require('!!raw-loader!./app.component.html'),
},
{
file: 'app.component.ts',
content: require('!!highlight-loader?raw=true&lang=typescript!./app.component.ts'),
filecontent: require('!!raw-loader!./app.component.ts'),
},
{
file: 'addons.wrapper.ts',
content: require('!!highlight-loader?raw=true&lang=typescript!./addons.wrapper.ts'),
filecontent: require('!!raw-loader!./addons.wrapper.ts'),
},
{
file: 'addons.extension.ts',
content: require('!!highlight-loader?raw=true&lang=typescript!./addons.extension.ts'),
filecontent: require('!!raw-loader!./addons.extension.ts'),
},
{
file: 'app.module.ts',
content: require('!!highlight-loader?raw=true&lang=typescript!./app.module.ts'),
filecontent: require('!!raw-loader!./app.module.ts'),
},
],
},
],
},
},
]),
],
})
export class ConfigModule {}
| Java |
# docker images
This repository includes docker container images
| Java |
const jwt = require('jsonwebtoken');
const User = require('../models/User');
// import { port, auth } from '../../config';
/**
* The Auth Checker middleware function.
*/
module.exports = (req, res, next) => {
if (!req.headers.authorization) {
return res.status(401).end();
}
// get the last part from a authorization header string like "bearer token-value"
const token = req.headers.authorization.split(' ')[1];
// decode the token using a secret key-phrase
return jwt.verify(token, "React Starter Kit", (err, decoded) => {
// the 401 code is for unauthorized status
if (err) { return res.status(401).end(); }
const userId = decoded.sub;
// check if a user exists
return User.findById(userId, (userErr, user) => {
if (userErr || !user) {
return res.status(401).end();
}
return next();
});
});
};
| Java |
//10. Odd and Even Product
//You are given n integers (given in a single line, separated by a space).
//Write a program that checks whether the product of the odd elements is equal to the product of the even elements.
//Elements are counted from 1 to n, so the first element is odd, the second is even, etc.
using System;
class OddAndEvenProduct
{
static void Main()
{
Console.WriteLine("Odd And Even Product");
Console.Write("Enter a numbers in a single line separated with space: ");
string[] input = Console.ReadLine().Split();
int oddProduct = 1;
int evenProdduct = 1;
for (int index = 0; index < input.Length; index++)
{
int num = int.Parse(input[index]);
if (index %2 == 0 || index == 0)
{
oddProduct *= num;
}
else
{
evenProdduct *= num;
}
}
if (oddProduct == evenProdduct)
{
Console.WriteLine("yes");
Console.WriteLine("product = {0}", oddProduct);
}
else
{
Console.WriteLine("no");
Console.WriteLine("odd Product = {0}", oddProduct);
Console.WriteLine("even Product = {0}", evenProdduct);
}
}
}
| Java |
var Ringpop = require('ringpop');
var TChannel = require('TChannel');
var express = require('express');
var NodeCache = require('node-cache');
var cache = new NodeCache();
var host = '127.0.0.1'; // not recommended for production
var httpPort = process.env.PORT || 8080;
var port = httpPort - 5080;
var bootstrapNodes = ['127.0.0.1:3000'];
var tchannel = new TChannel();
var subChannel = tchannel.makeSubChannel({
serviceName: 'ringpop',
trace: false
});
var ringpop = new Ringpop({
app: 'yourapp',
hostPort: host + ':' + port,
channel: subChannel
});
ringpop.setupChannel();
ringpop.channel.listen(port, host, function onListen() {
console.log('TChannel is listening on ' + port);
ringpop.bootstrap(bootstrapNodes,
function onBootstrap(err) {
if (err) {
console.log('Error: Could not bootstrap ' + ringpop.whoami());
process.exit(1);
}
console.log('Ringpop ' + ringpop.whoami() + ' has bootstrapped!');
});
// This is how you wire up a handler for forwarded requests
ringpop.on('request', handleReq);
});
var server = express();
server.get('/*', onReq);
server.listen(httpPort, function onListen() {
console.log('Server is listening on ' + httpPort);
});
function extractKey(req) {
var urlParts = req.url.split('/');
if (urlParts.length < 3) return ''; // URL does not have 2 parts...
return urlParts[1];
}
function onReq(req, res) {
var key = extractKey(req);
if (ringpop.handleOrProxy(key, req, res)) {
handleReq(req, res);
}
}
function handleReq(req, res) {
cache.get(req.url, function(err, value) {
if (value == undefined) {
var key = extractKey(req);
var result = host + ':' + port + ' is responsible for ' + key;
cache.set(req.url, result, function(err, success) {
if (!err && success) {
res.end(result + ' NOT CACHED');
}
});
} else {
res.end(value + ' CACHED');
}
});
}
| Java |
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
const addIcon = (icon) => `<i class="fa fa-${icon}"></i>`
const headerTxt = (type) => {
switch (type) {
case 'error':
return `${addIcon('ban')} Error`
case 'warning':
return `${addIcon('exclamation')} Warning`
case 'success':
return `${addIcon('check')} Success`
default:
return `${addIcon('ban')} Error`
}
}
const createModal = (texto, type) => {
let modal = document.createElement('div')
modal.classList = 'modal-background'
let headertxt = 'Error'
let content = `
<div class="modal-frame">
<header class="modal-${type} modal-header">
<h4> ${headerTxt(type)} </h4>
<span id="closeModal">×</span>
</header>
<div class="modal-mssg"> ${texto} </div>
<button id="btnAcceptModal" class="btn modal-btn modal-${type}">Aceptar</button>
</div>
`
modal.innerHTML = content
document.body.appendChild(modal)
document.getElementById('btnAcceptModal').addEventListener('click', () => modal.remove())
document.getElementById('closeModal').addEventListener('click', () => modal.remove())
}
export const errorModal = (message) => createModal(message, 'error')
export const successModal = (message) => createModal(message, 'success')
export const warningModal = (message) => createModal(message, 'warning')
| Java |
<!DOCTYPE html>
<!-- Developed by Ruben Schulz - www.rubenschulz.nl -->
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='x-ua-compatible' content='ie=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<meta name='apple-mobile-web-app-title' content='VPS Health' />
<meta name='apple-mobile-web-app-capable' content='yes' />
<meta name='apple-mobile-web-app-status-bar-style' content='black'/>
<link href='images/favicon-32x32.png' type='image/png' rel='icon' sizes='32x32' />
<link href='images/favicon-16x16.png' type='image/png' rel='icon' sizes='16x16' />
<link href='images/apple-touch-icon.png' rel='apple-touch-icon' sizes='180x180' />
<link href='images/manifest.json' rel='manifest' />
<link rel='stylesheet' href='style/foundation/foundation.min.css'>
<link rel='stylesheet' href='style/app.css'>
<title>VPS Health</title>
</head>
<body>
<div class='grid-y medium-grid-frame'>
<header class='cell shrink'>
<div class='grid-x grid-padding-x'>
<h1 class='cell small-12 medium-8'>
<img src='images/logo.png'>
VPS Health
</h1>
<div class='cell small-12 medium-4 medium-text-right'>
<button id='delete_all_history' class='button small' type='button'>
Delete all history
</button>
</div>
</div>
</header>
<main class='cell medium-auto medium-cell-block-container'>
<div class='grid-x'>
<div class='cell medium-cell-block-y'>
<div class='grid-container fluid'>
<div id='vpsses' class='grid-x grid-margin-x vpsses'>
<div id='dummy' class='cell small-12 medium-6 large-3 vps hide' data-sort='0'>
<h2>VPS title</h2>
<h3>VPS hostname</h3>
<div class='stats grid-x'>
<div id='load_1' title='Load 1 minute' class='cell small-4 stat load' ><img src='images/load.png' ><span>-</span></div>
<div id='load_5' title='Load 5 minutes' class='cell small-4 stat load' ><img src='images/load.png' ><span>-</span></div>
<div id='load_15' title='Load 15 minutes' class='cell small-4 stat load' ><img src='images/load.png' ><span>-</span></div>
</div>
<div class='stats grid-x'>
<div id='cpu' title='CPU usage' class='cell small-4 stat cpu' ><img src='images/cpu.png' ><span>-</span></div>
<div id='memory' title='Memory usage' class='cell small-4 stat memory' ><img src='images/memory.png' ><span>-</span></div>
<div id='disk' title='Disk usage' class='cell small-4 stat disk' ><img src='images/disk.png' ><span>-</span></div>
</div>
<div class='stats grid-x'>
<div id='uptime' title='Uptime' class='cell small-8 stat uptime' ></div>
<div id='availability' title='Availability' class='cell small-4 stat availability'><img src='images/availability.png'><span>-</span></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class='reveal large vps_details' id='vps_details' data-vps-id='' data-reveal>
<h2>VPS title</h2>
<h3>VPS hostname</h3>
<button id='delete_vps_history' class='button small' type='button'>
Delete VPS history
</button>
<div class='stats grid-x'>
<div id='cpu' title='Total CPUs' class='cell small-4 stat cpu' ><img src='images/cpu.png' ><span>-</span></div>
<div id='memory' title='Total memory' class='cell small-4 stat memory'><img src='images/memory.png'><span>-</span></div>
<div id='disk' title='Total disk space' class='cell small-4 stat disk' ><img src='images/disk.png' ><span>-</span></div>
</div>
<div class='grid-x'>
<div class='cell small-12 large-6'>
<canvas id='history_load' data-label='Load %'></canvas>
</div>
<div class='cell small-12 large-6'>
<canvas id='history_availability' data-label='Availability %'></canvas>
</div>
</div>
<div class='grid-x'>
<div class='cell small-12 large-4'>
<canvas id='history_cpu' data-label='CPU usage %'></canvas>
</div>
<div class='cell small-12 large-4'>
<canvas id='history_memory' data-label='Memory usage %'></canvas>
</div>
<div class='cell small-12 large-4'>
<canvas id='history_disk' data-label='Disk usage %'></canvas>
</div>
</div>
<button class='close-button' type='button' data-close>
×
</button>
</div>
</main>
</div>
<script type='text/javascript' src='scripts/jquery/jquery-3.2.1.min.js'></script>
<script type='text/javascript' src='scripts/foundation/foundation.min.js'></script>
<script type='text/javascript' src='scripts/chart/chart.js'></script>
<script type='text/javascript' src='scripts/vps-health/vps-health-1.0.js'></script>
<script type='text/javascript' src='config.js'></script>
</body>
</html> | Java |
<?php
/*
* This file is part of Rocketeer
*
* (c) Maxime Fabre <ehtnam6@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
namespace Rocketeer\Services\History;
use Illuminate\Support\Collection;
/**
* Keeps a memory of everything that was outputed/ran
* and on which connections/stages.
*/
class History extends Collection
{
/**
* Get the history, flattened.
*
* @return string[]|string[][]
*/
public function getFlattenedHistory()
{
return $this->getFlattened('history');
}
/**
* Get the output, flattened.
*
* @return string[]|string[][]
*/
public function getFlattenedOutput()
{
return $this->getFlattened('output');
}
/**
* Reset the history/output.
*/
public function reset()
{
$this->items = [];
}
//////////////////////////////////////////////////////////////////////
////////////////////////////// HELPERS ///////////////////////////////
//////////////////////////////////////////////////////////////////////
/**
* Get a flattened list of a certain type.
*
* @param string $type
*
* @return string[]|string[][]
*/
protected function getFlattened($type)
{
$history = [];
foreach ($this->items as $class => $entries) {
$history = array_merge($history, $entries[$type]);
}
ksort($history);
return array_values($history);
}
}
| Java |
<?php
/**
* Created by PhpStorm.
* User: olivier
* Date: 01/02/15
* Time: 00:58
*/
namespace AppBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* BusinessServiceRepository
*/
class BusinessServiceRepository extends EntityRepository
{
public function findByRefList(array $refList)
{
$qb = $this->createQueryBuilder('s');
$qb->where($qb->expr()->in('s.ref', $refList));
return $qb->getQuery()->execute();
}
public function findEnabled()
{
return $this->findBy(array('enabled' => '1'));
}
/**
* get services enabled only by default or with a suffix if $filterEnabled=false
* @param bool $filterEnabled
* @return array
*/
public function getChoices($filterEnabled = true)
{
if ($filterEnabled) {
}
$qb = $this->createQueryBuilder('s');
$qb->select('s.ref, s.name, s.enabled');
$results = $qb->getQuery()->execute();
$choices = [];
foreach ($results as $item) {
if ($item['enabled'] === true) {
$choices[$item['ref']] = $item['name'];
} else {
if ($filterEnabled === false) {
$choices[$item['ref']] = sprintf('%s (désactivé)', $item['name']);
} else {
unset($choices[$item['ref']]);
}
}
}
return $choices;
}
} | Java |
package br.com.k19.android.cap3;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frame);
}
}
| Java |
---
title: HTTP 原理
date: 2017-12-31
categories: HTTP
---
# TCP/IP 协议参考模型

TCP/IP是全世界的计算机和网络设备常用的层次化分组交换网络协议集,属于参考模型的传输层,用于过滤掉每个计算机的差异性,隐藏相关弱点,向应用程序提供“相同的”服务接口。
# HTTP 概念
http 是数据传输协议(超文本传输协议),用来沟通客户端和服务器,是一种 client-server 协议,它是承载于 TCP/IP 之上。通常是由像浏览器这样的接受方发起的,像浏览器这样的客户端发出的消息叫做 requests,那么被服务端回应的消息就叫做 responses。
## 媒体资源
网络上的一切内容皆资源,无论是静态文件,还是动态生成的代码。
我们通过 ***媒体类型(数据类型标记)*** 来告诉接收端(一般指客户端),接收到的数据是什么类型,让接收端知道怎么才能处理该文件。
常见标记方式就是 ***MIME*** ,MIME描述了文件的主要类型以及特定子类型,例如:"Content-Type":"text/html",其中text描述的文件的主要类型是文本,而其特定类型是html文档!
## URI、URL、URN
URI(Uniform Resource Identifier) 统一资源标识符,它的作用就是在网络上唯一确定一个资源。它有两个子集:URL(Uniform Resource Location)和URN(Uniform Resource Name)。如果不特别声明,我们所说的URI就是指URL。URL 通过给出的地址指向网络资源,URN 通过给出的命名指向资源(就像 ISBN 对于一本书一样)。
## HTTP 事务
“一次http链接(不包括tcp/ip连接,只包括一次http消息发送与接收)”的整个过程,由请求命令和响应结果组成
## 消息
消息是http协议一种纯文本的数据格式,分为请求消息和响应消息,两种消息都具有类似的结构,分别由三个部分构成:起始行、首部、主体,起始行描述消息干了什么!首部描述消息传输的具体细节!主体描述传输的实际内容!
## HTTP 的组件系统
代理、缓存、网关、隧道及Agent代理
+ 代理代理位于客户端和服务器之间,接收所有客户端的HTTP请求,并把这些请求转发给服务器(可能会对请求进行修改之后转发)。对用户来说,这些应用程序就是一个代理,代表用户访问服务器。代理的主要作用有过滤、屏蔽等!(还有需要注意一点:代理既可以代表服务器对客户端进行响应,又可以代表客户端对服务器进行请求!)
+ 缓存:首先说明一下,缓存某种意义上来说也是一种代理服务器。它主要使用代表服务器对客户端进行响应。发送预先缓存好的资源的副本。这样会加快事务响应速度、同时也会减少服务器的负载、减轻带宽等问题!
+ 网关:网关是一种特殊的服务器,面对客户端时好像它就是服务器,而对于服务器,他又充当客户端的角色,它的主要作用是协议转换!例如HTTP/FTP网关。
+ 隧道:就是一个连接通道,用于在http信道上发送非http协议的资源。
+ Agent代理:就是我们平时所说的浏览器,以及web机器人、爬虫等!
| Java |
import {WidgetConfig} from '../shared/widget-config';
import {WidgetService} from '../shared/widget.service';
export class Widget {
title: string;
updateInterval: number = 1000;
widgetConfig: WidgetConfig;
titleUrl: string;
description: string;
constructor(private widgetService: WidgetService) {
}
getTitle(): string {
return this.title;
}
initWidget(widgetConfig: WidgetConfig) {
this.widgetConfig = widgetConfig;
this.title = widgetConfig.title;
this.titleUrl = widgetConfig.titleUrl;
this.description = widgetConfig.description;
this.triggerUpdate();
}
triggerUpdate() {
setInterval(() => {
this.updateWidgetData();
}, this.updateInterval);
}
updateWidgetData() {
this.widgetService.getWidgetData(this.widgetConfig).subscribe(
widgetData => {
if (widgetData.length > 0) {
this.updateData(widgetData);
}
},
error => console.error(error)
);
}
updateData(data: any) {
// log backend errors
for (const sourceData of data) {
if ((sourceData.data || {}).errors) {
sourceData.data.errors.forEach(error => console.error(error));
}
}
// custom logic is implemented by widgets
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.