text
stringlengths
2
100k
meta
dict
{ "name": "react-native-extended-stylesheet", "version": "0.12.0", "description": "Extended StyleSheets for React Native", "author": { "name": "Vitaliy Potapov", "email": "[email protected]" }, "main": "src/index.js", "types": "types/index.d.ts", "scripts": { "code": "npm run lint", "lint": "eslint src", "test": "jest --onlyChanged", "tt": "jest --coverage", "tr": "BABEL_ENV=runtyper jest --no-cache", "test:types": "tsc", "ci": "run-s code tt tr test:types", "sync-yarn-lock": "rm yarn.lock && yarn import && git add -A yarn.lock && (git diff-index --quiet HEAD -- yarn.lock || git commit -m'sync yarn.lock' --no-verify)", "coveralls": "coveralls < coverage/lcov.info", "prerelease": "run-s code tt tr test:types sync-yarn-lock", "postrelease": "git push --follow-tags --no-verify", "release": "npm version $VER && npm publish", "release-patch": "VER=patch npm run release", "release-minor": "VER=minor npm run release" }, "husky": { "hooks": { "pre-commit": "lint-staged", "pre-push": "run-s code tt tr test:types" } }, "repository": { "type": "git", "url": "git://github.com/vitalets/react-native-extended-stylesheet.git" }, "bugs": { "url": "https://github.com/vitalets/react-native-extended-stylesheet/issues" }, "dependencies": { "css-mediaquery": "^0.1.2", "object-resolve-path": "^1.1.0" }, "devDependencies": { "@babel/core": "^7.5.0", "@babel/runtime": "^7.5.0", "@types/react-native": "^0.60.0", "babel-eslint": "^10.0.2", "babel-plugin-runtyper": "^0.4.0", "coveralls": "^3.0.4", "eslint": "^6.0.1", "eslint-plugin-import": "^2.18.0", "eslint-plugin-react": "^7.14.2", "eslint-plugin-react-native": "^3.7.0", "husky": "^3.0.0", "jest": "^24.8.0", "lint-staged": "^9.0.2", "metro-react-native-babel-preset": "^0.55.0", "npm-run-all": "^4.1.5", "typescript": "^3.5.2" }, "lint-staged": { "*.js": "eslint" }, "jest": { "automock": false, "roots": [ "src" ] }, "keywords": [ "react", "react-native", "react-component", "react-native-component", "mobile", "ios", "android" ], "license": "MIT" }
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0 /* * linux/fs/filesystems.c * * Copyright (C) 1991, 1992 Linus Torvalds * * table of configured filesystems */ #include <linux/syscalls.h> #include <linux/fs.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/kmod.h> #include <linux/init.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/uaccess.h> /* * Handling of filesystem drivers list. * Rules: * Inclusion to/removals from/scanning of list are protected by spinlock. * During the unload module must call unregister_filesystem(). * We can access the fields of list element if: * 1) spinlock is held or * 2) we hold the reference to the module. * The latter can be guaranteed by call of try_module_get(); if it * returned 0 we must skip the element, otherwise we got the reference. * Once the reference is obtained we can drop the spinlock. */ static struct file_system_type *file_systems; static DEFINE_RWLOCK(file_systems_lock); /* WARNING: This can be used only if we _already_ own a reference */ struct file_system_type *get_filesystem(struct file_system_type *fs) { __module_get(fs->owner); return fs; } void put_filesystem(struct file_system_type *fs) { module_put(fs->owner); } static struct file_system_type **find_filesystem(const char *name, unsigned len) { struct file_system_type **p; for (p = &file_systems; *p; p = &(*p)->next) if (strncmp((*p)->name, name, len) == 0 && !(*p)->name[len]) break; return p; } /** * register_filesystem - register a new filesystem * @fs: the file system structure * * Adds the file system passed to the list of file systems the kernel * is aware of for mount and other syscalls. Returns 0 on success, * or a negative errno code on an error. * * The &struct file_system_type that is passed is linked into the kernel * structures and must not be freed until the file system has been * unregistered. */ int register_filesystem(struct file_system_type * fs) { int res = 0; struct file_system_type ** p; BUG_ON(strchr(fs->name, '.')); if (fs->next) return -EBUSY; write_lock(&file_systems_lock); p = find_filesystem(fs->name, strlen(fs->name)); if (*p) res = -EBUSY; else *p = fs; write_unlock(&file_systems_lock); return res; } EXPORT_SYMBOL(register_filesystem); /** * unregister_filesystem - unregister a file system * @fs: filesystem to unregister * * Remove a file system that was previously successfully registered * with the kernel. An error is returned if the file system is not found. * Zero is returned on a success. * * Once this function has returned the &struct file_system_type structure * may be freed or reused. */ int unregister_filesystem(struct file_system_type * fs) { struct file_system_type ** tmp; write_lock(&file_systems_lock); tmp = &file_systems; while (*tmp) { if (fs == *tmp) { *tmp = fs->next; fs->next = NULL; write_unlock(&file_systems_lock); synchronize_rcu(); return 0; } tmp = &(*tmp)->next; } write_unlock(&file_systems_lock); return -EINVAL; } EXPORT_SYMBOL(unregister_filesystem); #ifdef CONFIG_SYSFS_SYSCALL static int fs_index(const char __user * __name) { struct file_system_type * tmp; struct filename *name; int err, index; name = getname(__name); err = PTR_ERR(name); if (IS_ERR(name)) return err; err = -EINVAL; read_lock(&file_systems_lock); for (tmp=file_systems, index=0 ; tmp ; tmp=tmp->next, index++) { if (strcmp(tmp->name, name->name) == 0) { err = index; break; } } read_unlock(&file_systems_lock); putname(name); return err; } static int fs_name(unsigned int index, char __user * buf) { struct file_system_type * tmp; int len, res; read_lock(&file_systems_lock); for (tmp = file_systems; tmp; tmp = tmp->next, index--) if (index <= 0 && try_module_get(tmp->owner)) break; read_unlock(&file_systems_lock); if (!tmp) return -EINVAL; /* OK, we got the reference, so we can safely block */ len = strlen(tmp->name) + 1; res = copy_to_user(buf, tmp->name, len) ? -EFAULT : 0; put_filesystem(tmp); return res; } static int fs_maxindex(void) { struct file_system_type * tmp; int index; read_lock(&file_systems_lock); for (tmp = file_systems, index = 0 ; tmp ; tmp = tmp->next, index++) ; read_unlock(&file_systems_lock); return index; } /* * Whee.. Weird sysv syscall. */ SYSCALL_DEFINE3(sysfs, int, option, unsigned long, arg1, unsigned long, arg2) { int retval = -EINVAL; switch (option) { case 1: retval = fs_index((const char __user *) arg1); break; case 2: retval = fs_name(arg1, (char __user *) arg2); break; case 3: retval = fs_maxindex(); break; } return retval; } #endif int __init get_filesystem_list(char *buf) { int len = 0; struct file_system_type * tmp; read_lock(&file_systems_lock); tmp = file_systems; while (tmp && len < PAGE_SIZE - 80) { len += sprintf(buf+len, "%s\t%s\n", (tmp->fs_flags & FS_REQUIRES_DEV) ? "" : "nodev", tmp->name); tmp = tmp->next; } read_unlock(&file_systems_lock); return len; } #ifdef CONFIG_PROC_FS static int filesystems_proc_show(struct seq_file *m, void *v) { struct file_system_type * tmp; read_lock(&file_systems_lock); tmp = file_systems; while (tmp) { seq_printf(m, "%s\t%s\n", (tmp->fs_flags & FS_REQUIRES_DEV) ? "" : "nodev", tmp->name); tmp = tmp->next; } read_unlock(&file_systems_lock); return 0; } static int __init proc_filesystems_init(void) { proc_create_single("filesystems", 0, NULL, filesystems_proc_show); return 0; } module_init(proc_filesystems_init); #endif static struct file_system_type *__get_fs_type(const char *name, int len) { struct file_system_type *fs; read_lock(&file_systems_lock); fs = *(find_filesystem(name, len)); if (fs && !try_module_get(fs->owner)) fs = NULL; read_unlock(&file_systems_lock); return fs; } struct file_system_type *get_fs_type(const char *name) { struct file_system_type *fs; const char *dot = strchr(name, '.'); int len = dot ? dot - name : strlen(name); fs = __get_fs_type(name, len); if (!fs && (request_module("fs-%.*s", len, name) == 0)) { fs = __get_fs_type(name, len); WARN_ONCE(!fs, "request_module fs-%.*s succeeded, but still no fs?\n", len, name); } if (dot && fs && !(fs->fs_flags & FS_HAS_SUBTYPE)) { put_filesystem(fs); fs = NULL; } return fs; } EXPORT_SYMBOL(get_fs_type);
{ "pile_set_name": "Github" }
/** * Copyright 2006-2016 the original author or authors. * * 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. */ package org.mybatis.generator.eclipse.tests.harness.matchers.support; import org.mybatis.generator.eclipse.tests.harness.summary.AbstractSummary; public class InnerClassGetter implements InnerElementGetter { @Override public AbstractSummary getElement(AbstractSummary item, String matchString) { return item.getClassSummary(matchString); } }
{ "pile_set_name": "Github" }
import json class NatlasServiceError(Exception): def __init__(self, status_code: int, message: str, template: str = None): self.status_code = status_code self.message = message self.template = f"errors/{self.status_code}.html" if not template else template def __str__(self): return f"{self.status_code}: {self.message}" def get_dict(self): return {"status": self.status_code, "message": self.message} def get_json(self): return json.dumps(self.get_dict(), sort_keys=True, indent=4) class NatlasSearchError(NatlasServiceError): def __init__(self, e): self.status_code = 400 self.message = e.info["error"]["root_cause"][0]["reason"] self.template = "errors/search.html"
{ "pile_set_name": "Github" }
name: Set Date # Run once every day # If we run it on schedule, but only change the date stamp if the repo has changed, The date could be behind by up to a day. # We can't really try to change it with every push the way workflows are set up now, # because there is no way to control which workflows run first, so some builds will not have the updated date and will lag behind by one build. # https://help.github.com/en/actions/reference/events-that-trigger-workflows#triggering-new-workflows-using-a-personal-access-token # "When you use the repository's GITHUB_TOKEN to perform tasks on behalf of the GitHub Actions app, # events triggered by the GITHUB_TOKEN will not create a new workflow run." on: schedule: - cron: '0 0 * * *' jobs: update-date: runs-on: ubuntu-latest if: ${{ github.repository == 'rusefi/rusefi' }} steps: - uses: actions/checkout@v2 with: fetch-depth: 0 - name: Write Date File run: | echo -e -n "#pragma once\n#define VCS_DATE $(date "+%Y%m%d")\n" > ./firmware/controllers/date_stamp.h git config --local user.email "[email protected]" git config --local user.name "GitHub set-date Action" git commit -m "Update date" -a 2>&1 | grep -E '(nothing to commit|changed)' - name: Push changed date file uses: ad-m/github-push-action@master with: github_token: ${{ github.token }} branch: master
{ "pile_set_name": "Github" }
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package pkcs12 import ( "bytes" "crypto/cipher" "crypto/des" "crypto/x509/pkix" "encoding/asn1" "errors" "golang.org/x/crypto/pkcs12/internal/rc2" ) var ( oidPBEWithSHAAnd3KeyTripleDESCBC = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 3}) oidPBEWithSHAAnd40BitRC2CBC = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 6}) ) // pbeCipher is an abstraction of a PKCS#12 cipher. type pbeCipher interface { // create returns a cipher.Block given a key. create(key []byte) (cipher.Block, error) // deriveKey returns a key derived from the given password and salt. deriveKey(salt, password []byte, iterations int) []byte // deriveKey returns an IV derived from the given password and salt. deriveIV(salt, password []byte, iterations int) []byte } type shaWithTripleDESCBC struct{} func (shaWithTripleDESCBC) create(key []byte) (cipher.Block, error) { return des.NewTripleDESCipher(key) } func (shaWithTripleDESCBC) deriveKey(salt, password []byte, iterations int) []byte { return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 1, 24) } func (shaWithTripleDESCBC) deriveIV(salt, password []byte, iterations int) []byte { return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 2, 8) } type shaWith40BitRC2CBC struct{} func (shaWith40BitRC2CBC) create(key []byte) (cipher.Block, error) { return rc2.New(key, len(key)*8) } func (shaWith40BitRC2CBC) deriveKey(salt, password []byte, iterations int) []byte { return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 1, 5) } func (shaWith40BitRC2CBC) deriveIV(salt, password []byte, iterations int) []byte { return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 2, 8) } type pbeParams struct { Salt []byte Iterations int } func pbDecrypterFor(algorithm pkix.AlgorithmIdentifier, password []byte) (cipher.BlockMode, int, error) { var cipherType pbeCipher switch { case algorithm.Algorithm.Equal(oidPBEWithSHAAnd3KeyTripleDESCBC): cipherType = shaWithTripleDESCBC{} case algorithm.Algorithm.Equal(oidPBEWithSHAAnd40BitRC2CBC): cipherType = shaWith40BitRC2CBC{} default: return nil, 0, NotImplementedError("algorithm " + algorithm.Algorithm.String() + " is not supported") } var params pbeParams if err := unmarshal(algorithm.Parameters.FullBytes, &params); err != nil { return nil, 0, err } key := cipherType.deriveKey(params.Salt, password, params.Iterations) iv := cipherType.deriveIV(params.Salt, password, params.Iterations) block, err := cipherType.create(key) if err != nil { return nil, 0, err } return cipher.NewCBCDecrypter(block, iv), block.BlockSize(), nil } func pbDecrypt(info decryptable, password []byte) (decrypted []byte, err error) { cbc, blockSize, err := pbDecrypterFor(info.Algorithm(), password) if err != nil { return nil, err } encrypted := info.Data() if len(encrypted) == 0 { return nil, errors.New("pkcs12: empty encrypted data") } if len(encrypted)%blockSize != 0 { return nil, errors.New("pkcs12: input is not a multiple of the block size") } decrypted = make([]byte, len(encrypted)) cbc.CryptBlocks(decrypted, encrypted) psLen := int(decrypted[len(decrypted)-1]) if psLen == 0 || psLen > blockSize { return nil, ErrDecryption } if len(decrypted) < psLen { return nil, ErrDecryption } ps := decrypted[len(decrypted)-psLen:] decrypted = decrypted[:len(decrypted)-psLen] if bytes.Compare(ps, bytes.Repeat([]byte{byte(psLen)}, psLen)) != 0 { return nil, ErrDecryption } return } // decryptable abstracts a object that contains ciphertext. type decryptable interface { Algorithm() pkix.AlgorithmIdentifier Data() []byte }
{ "pile_set_name": "Github" }
/* * Copyright 2001-2013 Artima, Inc. * * 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. */ package org.scalatest.matchers.dsl import org.scalatest.matchers.should.Matchers._ import org.scalatest._ import org.scalatest.funspec.AnyFunSpec class ResultOfNoElementsOfApplicationSpec extends AnyFunSpec { describe("ResultOfNoElementsOfApplication ") { it("should have pretty toString when right is empty") { val result = new ResultOfNoElementsOfApplication(Vector.empty) result.toString should be ("noElementsOf (Vector())") } it("should have pretty toString when right contains 1 element") { val result = new ResultOfNoElementsOfApplication(Vector("Bob")) result.toString should be ("noElementsOf (Vector(\"Bob\"))") } it("should have pretty toString when right contains > 1 elements") { val result = new ResultOfNoElementsOfApplication(Vector("Bob", "Alice")) result.toString should be ("noElementsOf (Vector(\"Bob\", \"Alice\"))") } } }
{ "pile_set_name": "Github" }
/** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.mobile.activities.formdisplay; import android.widget.LinearLayout; import org.openmrs.mobile.activities.BasePresenterContract; import org.openmrs.mobile.activities.BaseView; import org.openmrs.mobile.models.Question; import org.openmrs.mobile.utilities.InputField; import org.openmrs.mobile.utilities.SelectOneField; import java.util.List; public interface FormDisplayContract { interface View { interface MainView extends BaseView<Presenter.MainPresenter> { void quitFormEntry(); void enableSubmitButton(boolean enabled); void showToast(String errorMessage); void showToast(); void showSuccessfulToast(); } interface PageView extends BaseView<Presenter.PagePresenter> { void attachSectionToView(LinearLayout linearLayout); void attachQuestionToSection(LinearLayout section, LinearLayout question); void createAndAttachNumericQuestionEditText(Question question, LinearLayout sectionLinearLayout); void createAndAttachSelectQuestionDropdown(Question question, LinearLayout sectionLinearLayout); void createAndAttachSelectQuestionRadioButton(Question question, LinearLayout sectionLinearLayout); LinearLayout createQuestionGroupLayout(String questionLabel); LinearLayout createSectionLayout(String sectionLabel); List<SelectOneField> getSelectOneFields(); List<InputField> getInputFields(); void setInputFields(List<InputField> inputFields); void setSelectOneFields(List<SelectOneField> selectOneFields); } } interface Presenter { interface MainPresenter extends BasePresenterContract { void createEncounter(); } interface PagePresenter extends BasePresenterContract { } } }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2012-2018 The Android Money Manager Ex Project Team * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.money.manager.ex.common; import android.app.Activity; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.DatabaseUtils; import android.graphics.Typeface; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; import android.text.TextUtils; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.mikepenz.google_material_typeface_library.GoogleMaterial; import com.money.manager.ex.Constants; import com.money.manager.ex.core.TransactionTypes; import com.money.manager.ex.core.UIHelper; import com.money.manager.ex.currency.CurrencyService; import com.money.manager.ex.database.ITransactionEntity; import com.money.manager.ex.datalayer.AccountTransactionRepository; import com.money.manager.ex.datalayer.Select; import com.money.manager.ex.datalayer.SplitCategoriesRepository; import com.money.manager.ex.domainmodel.AccountTransaction; import com.money.manager.ex.domainmodel.SplitCategory; import com.money.manager.ex.sync.SyncManager; import com.money.manager.ex.transactions.CheckingTransactionEditActivity; import com.money.manager.ex.R; import com.money.manager.ex.servicelayer.qif.QifExport; import com.money.manager.ex.transactions.EditTransactionActivityConstants; import com.money.manager.ex.search.SearchActivity; import com.money.manager.ex.adapter.AllDataAdapter; import com.money.manager.ex.adapter.AllDataAdapter.TypeCursor; import com.money.manager.ex.home.DrawerMenuItem; import com.money.manager.ex.home.DrawerMenuItemAdapter; import com.money.manager.ex.core.ExportToCsvFile; import com.money.manager.ex.database.QueryAllData; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import androidx.cursoradapter.widget.CursorAdapter; import androidx.fragment.app.Fragment; import androidx.loader.app.LoaderManager; import androidx.loader.content.Loader; import info.javaperformance.money.Money; import info.javaperformance.money.MoneyFactory; import timber.log.Timber; /** * Fragment that displays the transactions. */ public class AllDataListFragment extends BaseListFragment implements LoaderManager.LoaderCallbacks<Cursor>, IAllDataMultiChoiceModeListenerCallbacks { private static final String ARG_ACCOUNT_ID = "AccountId"; private static final String ARG_SHOW_FLOATING_BUTTON = "ShowFloatingButton"; public static AllDataListFragment newInstance(int accountId) { return newInstance(accountId, true); } /** * Create a new instance of AllDataListFragment with accountId params * * @param accountId Id of account to display. If generic shown set -1 * @return new instance AllDataListFragment */ public static AllDataListFragment newInstance(int accountId, boolean showFloatingButton) { AllDataListFragment fragment = new AllDataListFragment(); Bundle args = new Bundle(); args.putInt(ARG_ACCOUNT_ID, accountId); args.putBoolean(ARG_SHOW_FLOATING_BUTTON, showFloatingButton); fragment.setArguments(args); return fragment; } public static final int ID_LOADER_ALL_DATA_DETAIL = 1; public static final String KEY_ARGUMENTS_WHERE = "SearchResultFragment:ArgumentsWhere"; public static final String KEY_ARGUMENTS_SORT = "SearchResultFragment:ArgumentsSort"; public int AccountId = Constants.NOT_SET; private LinearLayout footer; private LoaderManager.LoaderCallbacks<Cursor> mSearResultFragmentLoaderCallbacks; private boolean mAutoStarLoader = true; private boolean mShowHeader = false; private boolean mShowBalance = false; private AllDataMultiChoiceModeListener mMultiChoiceModeListener; private View mListHeader = null; private Bundle mArguments; private boolean mShowFooter = false; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setEmptyText(getString(R.string.no_data)); setListShown(false); // Read arguments this.AccountId = getArguments().getInt(ARG_ACCOUNT_ID); // Read header indicator directly from the activity. // todo: make this a parameter or a property. if (getActivity() instanceof SearchActivity) { SearchActivity activity = (SearchActivity) getActivity(); setShownHeader(activity.ShowAccountHeaders); } // create adapter for data. AllDataAdapter adapter = new AllDataAdapter(getActivity(), null, TypeCursor.ALLDATA); adapter.setAccountId(this.AccountId); adapter.setShowAccountName(isShownHeader()); adapter.setShowBalanceAmount(isShownBalance()); // set multi-choice mode in the list view. mMultiChoiceModeListener = new AllDataMultiChoiceModeListener(); mMultiChoiceModeListener.setListener(this); getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); getListView().setMultiChoiceModeListener(mMultiChoiceModeListener); // e item click getListView().setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (getListAdapter() != null && getListAdapter() instanceof AllDataAdapter) { Cursor cursor = ((AllDataAdapter) getListAdapter()).getCursor(); if (cursor.moveToPosition(position - (mListHeader != null ? 1 : 0))) { startEditAccountTransactionActivity(cursor.getInt(cursor.getColumnIndex(QueryAllData.ID))); } } } }); // Header and footer must be added before setAdapter(). // Add a header to the list view if one exists. if (getListAdapter() == null) { if (mListHeader != null) getListView().addHeaderView(mListHeader); } if (this.mShowFooter) { renderFooter(); } // set adapter setListAdapter(adapter); // register context menu registerForContextMenu(getListView()); // set animation progress setListShown(false); boolean showAddButton = getArguments().getBoolean(ARG_SHOW_FLOATING_BUTTON); if (showAddButton) { // Show floating action button. setFloatingActionButtonVisible(true); attachFloatingActionButtonToListView(); } // start loader if asked to do so by the caller. if (isAutoStarLoader()) { loadData(); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return super.onCreateView(inflater, container, savedInstanceState); } // Loader event handlers @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { if (getSearchResultFragmentLoaderCallbacks() != null) getSearchResultFragmentLoaderCallbacks().onCreateLoader(id, args); //animation setListShown(false); switch (id) { case ID_LOADER_ALL_DATA_DETAIL: // compose selection and sort String selection = ""; if (args != null && args.containsKey(KEY_ARGUMENTS_WHERE)) { selection = args.getString(KEY_ARGUMENTS_WHERE); } // String[] whereParams = new String[0]; // if (args != null && args.containsKey(KEY_ARGUMENTS_WHERE_PARAMS)) { // ArrayList<String> whereParamsList = args.getStringArrayList(KEY_ARGUMENTS_WHERE_PARAMS); // whereParams = whereParamsList.toArray(whereParams); // } // set sort String sort = ""; if (args != null && args.containsKey(KEY_ARGUMENTS_SORT)) { sort = args.getString(KEY_ARGUMENTS_SORT); } // create loader QueryAllData allData = new QueryAllData(getActivity()); Select query = new Select(allData.getAllColumns()) .where(selection) .orderBy(sort); return new MmxCursorLoader(getActivity(), allData.getUri(), query); } return null; } @Override public void onLoaderReset(Loader<Cursor> loader) { LoaderManager.LoaderCallbacks<Cursor> parent = getSearchResultFragmentLoaderCallbacks(); if (parent != null) parent.onLoaderReset(loader); //((CursorAdapter) getListAdapter()).swapCursor(null); ((CursorAdapter) getListAdapter()).changeCursor(null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { LoaderManager.LoaderCallbacks<Cursor> parent = getSearchResultFragmentLoaderCallbacks(); if (parent != null) parent.onLoadFinished(loader, data); switch (loader.getId()) { case ID_LOADER_ALL_DATA_DETAIL: // Transactions list loaded. AllDataAdapter adapter = (AllDataAdapter) getListAdapter(); // adapter.swapCursor(data); adapter.changeCursor(data); if (isResumed()) { setListShown(true); if (data != null && data.getCount() <= 0 && getFloatingActionButton() != null) getFloatingActionButton().show(true); } else { setListShownNoAnimation(true); } // reset the transaction groups (account name collection) adapter.resetAccountHeaderIndexes(); // Show totals if (this.mShowFooter) { try { this.updateFooter(data); } catch (Exception e) { Timber.e(e, "displaying footer"); } } } } // End loader event handlers /** * Add options to the action bar of the host activity. * This is not called in ActionBar Activity, i.e. Search. * @param menu * @param inflater */ @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); Activity activity = getActivity(); if (activity == null) return; MenuItem itemExportToCsv = menu.findItem(R.id.menu_export_to_csv); if (itemExportToCsv != null) itemExportToCsv.setVisible(true); MenuItem itemSearch = menu.findItem(R.id.menu_search_transaction); if (itemSearch != null) { itemSearch.setVisible(!activity.getClass().getSimpleName() .equals(SearchActivity.class.getSimpleName())); } // show this on all transactions lists later? // show this menu only when on Search Activity for now. if (activity.getClass().getSimpleName().equals(SearchActivity.class.getSimpleName())) { // Add default menu options. todo: check why this is executed twice. // Includes menu item for .qif export MenuItem qifExport = menu.findItem(R.id.menu_qif_export); if (qifExport == null) { inflater.inflate(R.menu.menu_alldata_operations, menu); } } } /** * This is just to test: * http://stackoverflow.com/questions/15207305/getting-the-error-java-lang-illegalstateexception-activity-has-been-destroyed */ @Override public void onDetach() { super.onDetach(); try { Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager"); childFragmentManager.setAccessible(true); childFragmentManager.set(this, null); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } @Override public void onDestroy() { if (mMultiChoiceModeListener != null) mMultiChoiceModeListener.onDestroyActionMode(null); super.onDestroy(); } @Override public void onResume() { super.onResume(); } @Override public void onStop() { super.onStop(); try { MmxBaseFragmentActivity activity = (MmxBaseFragmentActivity) getActivity(); if (activity != null) { ActionBar actionBar = activity.getSupportActionBar(); if(actionBar != null) { View customView = actionBar.getCustomView(); if (customView != null) { actionBar.setCustomView(null); } } } } catch (Exception e) { Timber.e(e, "stopping the all-data fragment"); } } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.menu_export_to_csv) { exportDataToCSVFile(); return true; } if (itemId == R.id.menu_qif_export) { // export visible transactions. exportToQif(); } return super.onOptionsItemSelected(item); } @Override public String getSubTitle() { return null; } @Override public void onFloatingActionButtonClicked() { startEditAccountTransactionActivity(null); } // Multi-choice-mode listener callback handlers. /** * handler for multi-choice-mode listener */ @Override public void onMultiChoiceCreated(android.view.Menu menu) { getActivity().getMenuInflater().inflate(R.menu.menu_all_data_adapter, menu); } @Override public void onDestroyActionMode() { if (getListAdapter() != null && getListAdapter() instanceof AllDataAdapter) { AllDataAdapter adapter = (AllDataAdapter) getListAdapter(); adapter.clearPositionChecked(); adapter.notifyDataSetChanged(); } } @Override public void onDeleteClicked() { ArrayList<Integer> transIds = getTransactionIds(); showDialogDeleteCheckingAccount(transIds); } @Override public void onChangeTransactionStatusClicked() { ArrayList<Integer> transIds = getTransactionIds(); changeTransactionStatus(transIds); } @Override public void onTransactionStatusClicked(String status) { ArrayList<Integer> transIds = getTransactionIds(); if (setStatusCheckingAccount(convertArrayListToArray(transIds), status)) { ((AllDataAdapter) getListAdapter()).clearPositionChecked(); loadData(); } } @Override public void onSelectAllRecordsClicked() { selectAllRecords(); } @Override public void onDuplicateTransactionsClicked() { ArrayList<Integer> transIds = getTransactionIds(); showDuplicateTransactionView(transIds); } @Override public void onItemCheckedStateChanged(int position, boolean checked) { if (getListHeader() != null) { position--; } if (getListAdapter() != null && getListAdapter() instanceof AllDataAdapter) { AllDataAdapter adapter = (AllDataAdapter) getListAdapter(); adapter.setPositionChecked(position, checked); adapter.notifyDataSetChanged(); } } // Methods public void displayRunningBalances(HashMap<Integer, Money> balances) { AllDataAdapter adapter = getAllDataAdapter(); if(adapter == null) return; adapter.setBalances(balances); } /** * Export data to CSV file */ public void exportDataToCSVFile() { exportDataToCSVFile(""); } /** * Export data to CSV file * * @param prefixName prefix for the file */ public void exportDataToCSVFile(String prefixName) { ExportToCsvFile csv = new ExportToCsvFile(getActivity(), (AllDataAdapter) getListAdapter()); csv.setPrefixName(prefixName); csv.execute(); } /** * @return the mSearResultFragmentLoaderCallbacks */ public LoaderManager.LoaderCallbacks<Cursor> getSearchResultFragmentLoaderCallbacks() { return mSearResultFragmentLoaderCallbacks; } /** * @param searResultFragmentLoaderCallbacks the searResultFragmentLoaderCallbacks to set */ public void setSearResultFragmentLoaderCallbacks(LoaderManager.LoaderCallbacks<Cursor> searResultFragmentLoaderCallbacks) { this.mSearResultFragmentLoaderCallbacks = searResultFragmentLoaderCallbacks; } /** * @return the mAutoStarLoader */ public boolean isAutoStarLoader() { return mAutoStarLoader; } /** * @param mAutoStarLoader the mAutoStarLoader to set */ public void setAutoStarLoader(boolean mAutoStarLoader) { this.mAutoStarLoader = mAutoStarLoader; } /** * @return the mShowHeader */ public boolean isShownHeader() { return mShowHeader; } /** * Start loader into fragment */ public void loadData() { loadData(getLatestArguments()); } public void loadData(Bundle arguments) { // set the account id in the data adapter AllDataAdapter adapter = getAllDataAdapter(); if (adapter != null) { adapter.setAccountId(this.AccountId); adapter.setBalances(null); } // set the current arguments / account id setLatestArguments(arguments); // reload data with the latest arguments. getLoaderManager().restartLoader(ID_LOADER_ALL_DATA_DETAIL, arguments, this); } /** * @param mShownHeader the mShowHeader to set */ public void setShownHeader(boolean mShownHeader) { this.mShowHeader = mShownHeader; } public View getListHeader() { return mListHeader; } public void setListHeader(View mHeaderList) { this.mListHeader = mHeaderList; } /** * @return the mShowBalance */ public boolean isShownBalance() { return mShowBalance; } /** * @param mShownBalance the mShowBalance to set */ public void setShownBalance(boolean mShownBalance) { this.mShowBalance = mShownBalance; AllDataAdapter adapter = getAllDataAdapter(); if (adapter == null) { return; } adapter.setShowBalanceAmount(mShownBalance); } public void showTotalsFooter() { this.mShowFooter = true; } // Private methods. private void renderFooter() { this.footer = (LinearLayout) View.inflate(getActivity(), R.layout.item_generic_report_2_columns, null); TextView txtColumn1 = (TextView) footer.findViewById(R.id.textViewColumn1); TextView txtColumn2 = (TextView) footer.findViewById(R.id.textViewColumn2); txtColumn1.setText(R.string.total); txtColumn1.setTypeface(null, Typeface.BOLD_ITALIC); txtColumn2.setText(R.string.total); txtColumn2.setTypeface(null, Typeface.BOLD_ITALIC); ListView listView = getListView(); listView.addFooterView(footer); } private void updateFooter(Cursor data) { if (data == null) return; String display; // number of records display = Integer.toString(data.getCount()) + " " + getString(R.string.records) + ", "; // sum Money total = MoneyFactory.fromString("0"); if (data.getCount() != 0) { total = getTotalFromCursor(data); } TextView txtColumn2 = (TextView) this.footer.findViewById(R.id.textViewColumn2); CurrencyService currencyService = new CurrencyService(getContext()); display += currencyService.getBaseCurrencyFormatted(total); txtColumn2.setText(display); } private Money getTotalFromCursor(Cursor cursor) { Money total = MoneyFactory.fromString("0"); int originalPosition = cursor.getPosition(); AllDataAdapter adapter = getAllDataAdapter(); CurrencyService currencyService = new CurrencyService(getContext()); int baseCurrencyId = currencyService.getBaseCurrencyId(); ContentValues values = new ContentValues(); int currencyId; Money amount; Money converted; String transType; TransactionTypes transactionType; cursor.moveToPosition(Constants.NOT_SET); while(cursor.moveToNext()) { values.clear(); // Read needed data. DatabaseUtils.cursorStringToContentValues(cursor, adapter.TRANSACTIONTYPE, values); DatabaseUtils.cursorIntToContentValues(cursor, adapter.CURRENCYID, values); DatabaseUtils.cursorIntToContentValues(cursor, adapter.TOCURRENCYID, values); DatabaseUtils.cursorDoubleToCursorValues(cursor, adapter.AMOUNT, values); DatabaseUtils.cursorDoubleToCursorValues(cursor, adapter.TOAMOUNT, values); transType = values.getAsString(adapter.TRANSACTIONTYPE); transactionType = TransactionTypes.valueOf(transType); if (transactionType.equals(TransactionTypes.Transfer)) { currencyId = values.getAsInteger(adapter.TOCURRENCYID); amount = MoneyFactory.fromString(values.getAsString(adapter.TOAMOUNT)); } else { currencyId = values.getAsInteger(adapter.CURRENCYID); amount = MoneyFactory.fromString(values.getAsString(adapter.AMOUNT)); } converted = currencyService.doCurrencyExchange(baseCurrencyId, amount, currencyId); total = total.add(converted); } cursor.moveToPosition(originalPosition); return total; } private boolean setStatusCheckingAccount(int[] transId, String status) { // check if status = "U" convert to empty string if (TextUtils.isEmpty(status) || "U".equalsIgnoreCase(status)) status = ""; SyncManager sync = new SyncManager(getActivity()); // Pause synchronization while bulk processing. sync.disableAutoUpload(); for (int id : transId) { // content value for updates ContentValues values = new ContentValues(); // set new state values.put(ITransactionEntity.STATUS, status.toUpperCase()); AccountTransactionRepository repo = new AccountTransactionRepository(getActivity()); // update int updateResult = getActivity().getContentResolver().update(repo.getUri(), values, AccountTransaction.TRANSID + "=?", new String[]{Integer.toString(id)}); if (updateResult <= 0) { Toast.makeText(getActivity(), R.string.db_update_failed, Toast.LENGTH_LONG).show(); sync.enableAutoUpload(); sync.dataChanged(); return false; } } // Now notify Dropbox about modifications. sync.enableAutoUpload(); sync.dataChanged(); return true; } /** * @param transactionIds primary key of transaction */ private void showDialogDeleteCheckingAccount(final ArrayList<Integer> transactionIds) { // create alert binaryDialog and set title and message MaterialDialog.Builder alertDialog = new MaterialDialog.Builder(getContext()) .title(R.string.delete_transaction) .icon(new UIHelper(getActivity()).getIcon(GoogleMaterial.Icon.gmd_warning)) .content(getResources().getQuantityString(R.plurals.plurals_delete_transactions, transactionIds.size(), transactionIds.size())); // alert.setIcon(R.drawable.ic_action_warning_light); // set listener button positive alertDialog.positiveText(android.R.string.ok); alertDialog.onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { SyncManager sync = new SyncManager(getActivity()); // Pause sync notification while bulk processing. sync.disableAutoUpload(); for (int transactionId : transactionIds) { // First delete any splits. See if there are any split records. SplitCategoriesRepository splitRepo = new SplitCategoriesRepository(getActivity()); Cursor curSplit = getActivity().getContentResolver().query(splitRepo.getUri(), null, SplitCategory.TRANSID + "=" + Integer.toString(transactionId), null, SplitCategory.SPLITTRANSID); int splitCount = curSplit.getCount(); curSplit.close(); if (splitCount > 0) { int deleteResult = getActivity().getContentResolver().delete(splitRepo.getUri(), SplitCategory.TRANSID + "=?", new String[]{Integer.toString(transactionId)}); if (deleteResult != splitCount) { Toast.makeText(getActivity(), R.string.db_delete_failed, Toast.LENGTH_SHORT).show(); // Now notify Dropbox about modifications. sync.enableAutoUpload(); sync.dataChanged(); return; } } // Delete the transaction. AccountTransactionRepository repo = new AccountTransactionRepository(getActivity()); int deleteResult = getActivity().getContentResolver().delete(repo.getUri(), AccountTransaction.TRANSID + "=?", new String[]{Integer.toString(transactionId)}); if (deleteResult == 0) { Toast.makeText(getActivity(), R.string.db_delete_failed, Toast.LENGTH_SHORT).show(); // Now notify Dropbox about modifications. sync.enableAutoUpload(); sync.dataChanged(); return; } } // Now notify Dropbox about modifications. sync.enableAutoUpload(); sync.dataChanged(); // restart loader loadData(); } }); // set listener negative button alertDialog.negativeText(android.R.string.cancel); alertDialog.onNegative(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { dialog.cancel(); } }); alertDialog.build().show(); } /** * start the activity of transaction management * * @param transId null set if you want to do a new transaction, or transaction id */ private void startEditAccountTransactionActivity(Integer transId) { // create intent, set Account ID Intent intent = new Intent(getActivity(), CheckingTransactionEditActivity.class); //Set the source intent.putExtra(EditTransactionActivityConstants.KEY_TRANS_SOURCE, "AllDataListFragment.java"); // check transId not null if (transId != null) { intent.putExtra(EditTransactionActivityConstants.KEY_TRANS_ID, transId); intent.setAction(Intent.ACTION_EDIT); } else { intent.putExtra(EditTransactionActivityConstants.KEY_ACCOUNT_ID, this.AccountId); intent.setAction(Intent.ACTION_INSERT); } // launch activity startActivity(intent); } private AllDataAdapter getAllDataAdapter() { AllDataAdapter adapter = null; ListAdapter listAdapter = getListAdapter(); if (listAdapter != null && listAdapter instanceof AllDataAdapter) { adapter = (AllDataAdapter) getListAdapter(); } return adapter; } private void selectAllRecords() { AllDataAdapter adapter = getAllDataAdapter(); if(adapter == null) return; // Clear selection first. adapter.clearPositionChecked(); int numRecords = adapter.getCount(); for (int i = 0; i < numRecords; i++) { adapter.setPositionChecked(i, true); } adapter.notifyDataSetChanged(); } private ArrayList<Integer> getTransactionIds(){ final ArrayList<Integer> transIds = new ArrayList<>(); AllDataAdapter adapter = getAllDataAdapter(); if(adapter == null) return transIds; Cursor cursor = adapter.getCursor(); if (cursor != null) { // get checked items & count from the adapter, not from the list view. // List view only contains the one that was tapped, ignoring the Select All. // SparseBooleanArray positionChecked = getListView().getCheckedItemPositions(); SparseBooleanArray positionChecked = adapter.getPositionsChecked(); // int checkedItemsCount = getListView().getCheckedItemCount(); int checkedItemsCount = positionChecked.size(); for (int i = 0; i < checkedItemsCount; i++) { int position = positionChecked.keyAt(i); // This screws up the selection? // if (getListHeader() != null) // position--; if (cursor.moveToPosition(position)) { transIds.add(cursor.getInt(cursor.getColumnIndex(QueryAllData.ID))); } } } return transIds; } private void changeTransactionStatus(final ArrayList<Integer> transIds){ final DrawerMenuItemAdapter adapter = new DrawerMenuItemAdapter(getActivity()); // final Core core = new Core(getActivity().getApplicationContext()); final Boolean isDarkTheme = new UIHelper(getActivity()).isUsingDarkTheme(); // add status adapter.add(new DrawerMenuItem().withId(R.id.menu_none) .withText(getString(R.string.status_none)) .withIcon(isDarkTheme ? R.drawable.ic_action_help_dark : R.drawable.ic_action_help_light) .withShortcut("")); adapter.add(new DrawerMenuItem().withId(R.id.menu_reconciled) .withText(getString(R.string.status_reconciled)) .withIcon(isDarkTheme ? R.drawable.ic_action_done_dark : R.drawable.ic_action_done_light) .withShortcut("R")); adapter.add(new DrawerMenuItem().withId(R.id.menu_follow_up) .withText(getString(R.string.status_follow_up)) .withIcon(isDarkTheme ? R.drawable.ic_action_alarm_on_dark : R.drawable.ic_action_alarm_on_light) .withShortcut("F")); adapter.add(new DrawerMenuItem().withId(R.id.menu_duplicate) .withText(getString(R.string.status_duplicate)) .withIcon(isDarkTheme ? R.drawable.ic_action_copy_dark : R.drawable.ic_action_copy_light) .withShortcut("D")); adapter.add(new DrawerMenuItem().withId(R.id.menu_void) .withText(getString(R.string.status_void)) .withIcon(isDarkTheme ? R.drawable.ic_action_halt_dark : R.drawable.ic_action_halt_light) .withShortcut("V")); // open binaryDialog final MaterialDialog dialog = new MaterialDialog.Builder(getActivity()) .title(getString(R.string.change_status)) .adapter(adapter, null) .build(); ListView listView = dialog.getListView(); if (listView != null) listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { DrawerMenuItem item = adapter.getItem(position); switch (item.getId()) { case R.id.menu_none: case R.id.menu_reconciled: case R.id.menu_follow_up: case R.id.menu_duplicate: case R.id.menu_void: String status = item.getShortcut(); if (setStatusCheckingAccount(convertArrayListToArray(transIds), status)) { ((AllDataAdapter) getListAdapter()).clearPositionChecked(); loadData(); } } dialog.dismiss(); } }); dialog.show(); } private void showDuplicateTransactionView(ArrayList<Integer> transIds) { // validation int transactionCount = transIds.size(); if (transactionCount <= 0) return; int[] ids = convertArrayListToArray(transIds); Intent[] intents = new Intent[transactionCount]; for (int i = 0; i < transactionCount; i++) { intents[i] = new Intent(getActivity(), CheckingTransactionEditActivity.class); intents[i].putExtra(EditTransactionActivityConstants.KEY_TRANS_ID, ids[i]); intents[i].setAction(Intent.ACTION_PASTE); intents[i].putExtra(EditTransactionActivityConstants.KEY_TRANS_SOURCE, "AllDataListFragment.java"); } getActivity().startActivities(intents); } // end multi-choice-mode listener callback handlers. private void exportToQif(){ AllDataAdapter adapter = (AllDataAdapter) getListAdapter(); QifExport qif = new QifExport(getActivity()); qif.export(adapter); } private int[] convertArrayListToArray(ArrayList<Integer> list) { int[] result = new int[list.size()]; for (int i = 0; i < list.size(); i++) { result[i] = list.get(i); } return result; } /** * Returns the latest-set arguments. This is because the original arguments, when the * fragment was created, can not be altered. * But, when an account changes, we need to modify them. The new arguments are passed * through the call to loadData(). * @return */ private Bundle getLatestArguments() { if (mArguments == null) { mArguments = getArguments(); } return mArguments; } private void setLatestArguments(Bundle arguments) { mArguments = arguments; } }
{ "pile_set_name": "Github" }
# Client Samples The following table shows the sample sub-directories and their contents. Directory | Description ----------------| ------------- appliance | Samples for Appliance Management APIs common | Samples common helper classes and abstractions; This package does NOT contain any sample contentlibrary | Samples for Content Library APIs tagging | Samples for Tagging APIs vcenter | Samples for managing vSphere infrastructure and virtual machines sso | Samples for Platform Service Controller(PSC), SSO and Lookup Service APIs vmc | Samples for VMware Cloud on AWS Services
{ "pile_set_name": "Github" }
/* -------------------------------------------------------------------------- * * OpenMMDrude * * -------------------------------------------------------------------------- * * This is part of the OpenMM molecular simulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org. * * * * Portions copyright (c) 2013 Stanford University and the Authors. * * Authors: Peter Eastman * * Contributors: * * * * 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, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * * USE OR OTHER DEALINGS IN THE SOFTWARE. * * -------------------------------------------------------------------------- */ #include "openmm/serialization/DrudeForceProxy.h" #include "openmm/serialization/SerializationNode.h" #include "openmm/Force.h" #include "openmm/DrudeForce.h" #include <sstream> using namespace OpenMM; using namespace std; DrudeForceProxy::DrudeForceProxy() : SerializationProxy("DrudeForce") { } void DrudeForceProxy::serialize(const void* object, SerializationNode& node) const { node.setIntProperty("version", 1); const DrudeForce& force = *reinterpret_cast<const DrudeForce*>(object); SerializationNode& particles = node.createChildNode("Particles"); for (int i = 0; i < force.getNumParticles(); i++) { int p, p1, p2, p3, p4; double charge, polarizability, aniso12, aniso34; force.getParticleParameters(i, p, p1, p2, p3, p4, charge, polarizability, aniso12, aniso34); particles.createChildNode("Particle").setIntProperty("p", p).setIntProperty("p1", p1).setIntProperty("p2", p2).setIntProperty("p3", p3).setIntProperty("p4", p4) .setDoubleProperty("charge", charge).setDoubleProperty("polarizability", polarizability).setDoubleProperty("a12", aniso12).setDoubleProperty("a34", aniso34); } SerializationNode& pairs = node.createChildNode("ScreenedPairs"); for (int i = 0; i < force.getNumScreenedPairs(); i++) { int p1, p2; double thole; force.getScreenedPairParameters(i, p1, p2, thole); pairs.createChildNode("Pair").setIntProperty("p1", p1).setIntProperty("p2", p2).setDoubleProperty("thole", thole); } } void* DrudeForceProxy::deserialize(const SerializationNode& node) const { if (node.getIntProperty("version") != 1) throw OpenMMException("Unsupported version number"); DrudeForce* force = new DrudeForce(); try { const SerializationNode& particles = node.getChildNode("Particles"); for (auto& particle : particles.getChildren()) force->addParticle(particle.getIntProperty("p"), particle.getIntProperty("p1"), particle.getIntProperty("p2"), particle.getIntProperty("p3"), particle.getIntProperty("p4"), particle.getDoubleProperty("charge"), particle.getDoubleProperty("polarizability"), particle.getDoubleProperty("a12"), particle.getDoubleProperty("a34")); const SerializationNode& pairs = node.getChildNode("ScreenedPairs"); for (auto& pair : pairs.getChildren()) force->addScreenedPair(pair.getIntProperty("p1"), pair.getIntProperty("p2"), pair.getDoubleProperty("thole")); } catch (...) { delete force; throw; } return force; }
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; namespace Microsoft.Protocols.TestTools.StackSdk.Asn1 { /// <summary> /// Represents an BER ASN.1 encoding buffer. /// </summary> /// <remarks> /// This buffer is a reversed buffer. /// The data will be written to the front of the buffer each time its "Write" or "WriteByte" is invoked. /// </remarks> public class Asn1BerEncodingBuffer : IAsn1BerEncodingBuffer, IDisposable { private MemoryStream buffer; /// <summary> /// Initializes a new instance of the Asn1ReversedEncodingBuffer class that is empty and has a default capacity. /// </summary> /// <remarks> /// The capacity can expand automatically. /// </remarks> public Asn1BerEncodingBuffer() { buffer = new MemoryStream(); } /// <summary> /// Initializes a new instance of the Asn1ReversedEncodingBuffer class that is empty and has a user defined capacity. /// </summary> /// <param name="capacity">The initial capacity.</param> /// <remarks> /// The capacity can expand automatically. /// </remarks> public Asn1BerEncodingBuffer(int capacity) { buffer = new MemoryStream(capacity); } /// <summary> /// Gets the encoding result. /// </summary> public byte[] Data { get { byte[] result = buffer.ToArray(); Array.Reverse(result); return result; } } /// <summary> /// Writes a byte to the front of Data property. /// </summary> public void WriteByte(byte b) { //After Array.Reverse in Data property, its in the front. buffer.WriteByte(b); } /// <summary> /// Writes some bytes to the front of the buffer. /// </summary> /// <param name="bytes">An array that contains the bytes.</param> /// <param name="offset">The begin index of the bytes in the array.</param> /// <param name="count">The number of the bytes.</param> public void WriteBytes(byte[] bytes, int offset, int count) { //Write inversely. After Array.Reverse in Data property, the original order is retrieved. for (int i = offset + count - 1; i >= offset; i--) { buffer.WriteByte(bytes[i]); } } /// <summary> /// Write all the bytes in a byte array to the front of the buffer. /// </summary> /// <param name="bytes"></param> public void WriteBytes(byte[] bytes) { if (bytes != null) { WriteBytes(bytes, 0, bytes.Length); } } #region Dispose private bool disposed = false; /// <summary> /// Dispose method from IDisposable. /// </summary> /// <param name="disposing">Indicating whether the managed resources need to be disposed immediately.</param> protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { //managed resources are disposed here buffer.Dispose(); } //unmanaged resources are disposed here this.disposed = true; } } /// <summary> /// Dispose method that can be manually called. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Destructor which disposes the unmanaged resources. /// </summary> ~Asn1BerEncodingBuffer() { Dispose(false); } #endregion Dispose } }
{ "pile_set_name": "Github" }
<!--- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. --> <head> <title>Tutorial - Helix Agent</title> </head> ## [Helix Tutorial](./Tutorial.html): Helix Agent (for non-JVM systems) Not every distributed system is written on the JVM, but many systems would benefit from the cluster management features that Helix provides. To make a non-JVM system work with Helix, you can use the Helix Agent module. ### What is Helix Agent? Helix is built on the following assumption: if your distributed resource is modeled by a finite state machine, then Helix can tell participants when they should transition between states. In the Java API, this means implementing transition callbacks. In the Helix agent API, this means providing commands than can run for each transition. These commands could do anything behind the scenes; Helix only requires that they exit once the state transition is complete. ### Configuring Transition Commands Here's how to tell Helix which commands to run on state transitions: #### Java Using the Java API, first get a configuration scope (the Helix agent supports both cluster and resource scopes, picking resource first if it is available): ``` // Cluster scope HelixConfigScope scope = new HelixConfigScopeBuilder(ConfigScopeProperty.CLUSTER).forCluster(clusterName).build(); // Resource scope HelixConfigScope scope = new HelixConfigScopeBuilder(ConfigScopeProperty.RESOURCE).forCluster(clusterName).forResource(resourceName).build(); ``` Then, specify the command to run for each state transition: ``` // Get the configuration accessor ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient); // Specify the script for OFFLINE --> ONLINE CommandConfig.Builder builder = new CommandConfig.Builder(); CommandConfig cmdConfig = builder.setTransition("OFFLINE", "ONLINE").setCommand("simpleHttpClient.py OFFLINE-ONLINE") .setCommandWorkingDir(workingDir) .setCommandTimeout("5000L") // optional: ms to wait before failing .setPidFile(pidFile) // optional: for daemon-like systems that will write the process id to a file .build(); configAccessor.set(scope, cmdConfig.toKeyValueMap()); // Specify the script for ONLINE --> OFFLINE builder = new CommandConfig.Builder(); cmdConfig = builder.setTransition("ONLINE", "OFFLINE").setCommand("simpleHttpClient.py ONLINE-OFFLINE") .setCommandWorkingDir(workingDir) .build(); configAccessor.set(scope, cmdConfig.toKeyValueMap()); // Specify NOP for OFFLINE --> DROPPED builder = new CommandConfig.Builder(); cmdConfig = builder.setTransition("OFFLINE", "DROPPED") .setCommand(CommandAttribute.NOP.getName()) .build(); configAccessor.set(scope, cmdConfig.toKeyValueMap()); ``` In this example, we have a program called simpleHttpClient.py that we call for all transitions, only changing the arguments that are passed in. However, there is no requirement that each transition invoke the same program; this API allows running arbitrary commands in arbitrary directories with arbitrary arguments. Notice that that for the OFFLINE \-\-\> DROPPED transition, we do not run any command (specifically, we specify the NOP command). This just tells Helix that the system doesn't care about when things are dropped, and it can consider the transition already done. #### Command Line It is also possible to configure everything directly from the command line. Here's how that would look for cluster-wide configuration: ``` # Specify the script for OFFLINE --> ONLINE /helix-admin.sh --zkSvr localhost:2181 --setConfig CLUSTER clusterName OFFLINE-ONLINE.command="simpleHttpClient.py OFFLINE-ONLINE",OFFLINE-ONLINE.workingDir="/path/to/script", OFFLINE-ONLINE.command.pidfile="/path/to/pidfile" # Specify the script for ONLINE --> OFFLINE /helix-admin.sh --zkSvr localhost:2181 --setConfig CLUSTER clusterName ONLINE-OFFLINE.command="simpleHttpClient.py ONLINE-OFFLINE",ONLINE-OFFLINE.workingDir="/path/to/script", OFFLINE-ONLINE.command.pidfile="/path/to/pidfile" # Specify NOP for OFFLINE --> DROPPED /helix-admin.sh --zkSvr localhost:2181 --setConfig CLUSTER clusterName ONLINE-OFFLINE.command="nop" ``` Like in the Java configuration, it is also possible to specify a resource scope instead of a cluster scope: ``` # Specify the script for OFFLINE --> ONLINE /helix-admin.sh --zkSvr localhost:2181 --setConfig RESOURCE clusterName,resourceName OFFLINE-ONLINE.command="simpleHttpClient.py OFFLINE-ONLINE",OFFLINE-ONLINE.workingDir="/path/to/script", OFFLINE-ONLINE.command.pidfile="/path/to/pidfile" ``` ### Starting the Agent There should be an agent running for every participant you have running. Ideally, its lifecycle should match that of the participant. Here, we have a simple long-running participant called simpleHttpServer.py. Its only purpose is to record state transitions. Here are some ways that you can start the Helix agent: #### Java ``` // Start your application process ExternalCommand serverCmd = ExternalCommand.start(workingDir + "/simpleHttpServer.py"); // Start the agent Thread agentThread = new Thread() { @Override public void run() { while(!isInterrupted()) { try { HelixAgentMain.main(new String[] { "--zkSvr", zkAddr, "--cluster", clusterName, "--instanceName", instanceName, "--stateModel", "OnlineOffline" }); } catch (InterruptedException e) { LOG.info("Agent thread interrupted", e); interrupt(); } catch (Exception e) { LOG.error("Exception start helix-agent", e); } } } }; agentThread.start(); // Wait for the process to terminate (either intentionally or unintentionally) serverCmd.waitFor(); // Kill the agent agentThread.interrupt(); ``` #### Command Line ``` # Build Helix and start the agent mvn clean install -DskipTests chmod +x helix-agent/target/helix-agent-pkg/bin/* helix-agent/target/helix-agent-pkg/bin/start-helix-agent.sh --zkSvr zkAddr1,zkAddr2 --cluster clusterName --instanceName instanceName --stateModel OnlineOffline # Here, you can define your own logic to terminate this agent when your process terminates ... ``` ### Example [Here](https://git-wip-us.apache.org/repos/asf?p=helix.git;a=blob;f=helix-agent/src/test/java/org/apache/helix/agent/TestHelixAgent.java;h=ccf64ce5544207c7e48261682ea69945b71da7f1;hb=refs/heads/master) is a basic system that uses the Helix agent package. ### Notes As you may have noticed from the examples, the participant program and the state transition program are two different programs. The former is a _long-running_ process that is directly tied to the Helix agent. The latter is a process that only exists while a state transition is underway. Despite this, these two processes should be intertwined. The transition command will need to communicate to the participant to actually complete the state transition and the participant will need to communicate whether or not this was successful. The implementation of this protocol is the responsibility of the system.
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CustomHyperlinkToolTip { public class Employee { private string firstName; private DateTime birthDate; private int salary; public string FirstName { get { return this.firstName; } set { if (this.firstName != value) { this.firstName = value; } } } public DateTime BirthDate { get { return birthDate; } set { if (this.birthDate != value) { this.birthDate = value; } } } public int Salary { get { return salary; } set { if (this.salary != value) { this.salary = value; } } } public override string ToString() { return this.FirstName; } } }
{ "pile_set_name": "Github" }
using System; using BigMath; using Raksha.Crypto.Parameters; using Raksha.Math; using Raksha.Security; using Raksha.Utilities; namespace Raksha.Crypto.Generators { class DHKeyGeneratorHelper { internal static readonly DHKeyGeneratorHelper Instance = new DHKeyGeneratorHelper(); private DHKeyGeneratorHelper() { } internal BigInteger CalculatePrivate( DHParameters dhParams, SecureRandom random) { int limit = dhParams.L; if (limit != 0) { return new BigInteger(limit, random).SetBit(limit - 1); } BigInteger min = BigInteger.Two; int m = dhParams.M; if (m != 0) { min = BigInteger.One.ShiftLeft(m - 1); } BigInteger max = dhParams.P.Subtract(BigInteger.Two); BigInteger q = dhParams.Q; if (q != null) { max = q.Subtract(BigInteger.Two); } return BigIntegers.CreateRandomInRange(min, max, random); } internal BigInteger CalculatePublic( DHParameters dhParams, BigInteger x) { return dhParams.G.ModPow(x, dhParams.P); } } }
{ "pile_set_name": "Github" }
--- title: Clustering Reference --- ## Overview Multiple Kong nodes pointing to the same datastore **must** belong to the same "Kong cluster". A Kong cluster allows you to scale the system horizontally by adding more machines to handle a bigger load of incoming requests, and they all share the same data since they point to the same datastore. A Kong cluster can be created in one datacenter, or in multiple datacenters, in both cloud or on-premise environments. Kong will take care of joining and leaving a node automatically in a cluster, as long as the node is configured properly. ## 1. Introduction Generally speaking having multiple Kong nodes is a good practice for a number of reasons, including: * Scaling the system horizontally to process a greater number of incoming requests. * Scaling the system on multiple datacenter to provide a distributed low latency geolocalized service. * As a failure prevention response, so that even if a server crashes other Kong nodes can still process incoming requests without any downtime. <center> <img src="/assets/images/docs/clustering.png" style="height: 400px"/> </center> To make sure every Kong node can process requests properly, each node must point to the same datastore so that they can share the same data. This means for example that APIs, Consumers and Plugins created by a Kong node will also be available to other Kong nodes that are pointing to the same datastore. By doing so it doesn't matter which Kong node is being requested, as long as they all point to the same datastore every node will be able to retrieve the same data and thus process requests in the same way. ## 2. How does Kong clustering work? Every time a new Kong node is started, it must join other Kong nodes that are using the same datastore. This is done automatically given that the right configuration has been provided to Kong. Kong cluster settings are specified in the configuration file at the following entries: * [cluster_listen][cluster_listen] * [cluster_listen_rpc][cluster_listen_rpc] * [cluster][cluster] ### Why do we need Kong Clustering? To understand why a Kong Cluster is needed, we need to spend a few words on how Kong interacts with the datastore. Every time a new incoming API requests hits a Kong server, Kong loads some data from the datastore to understand how to proxy the request, load any associated plugin, authenticate the Consumer, and so on. Doing this on every request would be very expensive in terms of performance, because Kong would need to communicate with the datastore on every request and this would be extremely inefficient. To avoid querying the datastore every time, Kong tries to cache as much data as possible locally in-memory after the first time it has been requested. Because a local in-memory lookup is tremendously faster than communicating with the datastore every time, this allows Kong to have a good performance on every request. This works perfectly as long as data never changes, which is not the case with Kong. If the data changes in the datastore (because an API or a Plugin has been updated, for example), the previous in-memory cached version of the same data on each Kong node becomes immediately outdated. The Kong node will be unaware that the data changed on the datastore, unless something tells each Kong node that the data needs to be re-cached. By clustering Kong nodes together we are making each Kong node aware of the presence of every other node, and every time an operation changes the data on the datastore, the Kong node responsible for that change can tell all the other nodes to invalidate the local in-memory cache and fetch again the data from the datastore. This brings on the table very good performance, because Kong nodes will never talk to the datastore again unless they really have to. On the other side it introduces the concept of Kong Clustering, where we need to make sure that each node is aware of every other node so that they can communicate any change. Failure to do so would bring an inconsistency between the data effectively stored in the datastore, and the cached data store by each Kong node, leading to unexpected behavior. ## 3. Adding new nodes to a cluster Every Kong node that points to the same datastore needs to join in a cluster with the other nodes. A Kong Cluster is made of at least two Kong nodes pointing to the same datastore. Every time a new Kong node is being started it will register its first local, non-loopback, IPv4 address to the datastore. When another node is being started, it will query the datastore for nodes that have previously registered themselves, and join them using the IP address stored. If the auto-detected IP address is wrong, you can customize what address is being advertised to other nodes by using the `advertise` property in the [cluster settings][cluster]. A Kong node only needs to join one another node in a cluster, and it will automatically discover the entire cluster. ## 4. Removing nodes from a cluster Every time a new Kong node is stopped, that node will try to gracefully remove itself from the cluster. When a node has been successfully removed from a cluster, its state transitions from `alive` to `left`. To gracefully stop and remove a node from the cluster just execute the `kong quit` or `kong stop` CLI commands. When a node is not reachable for whatever reason, its state transitions to `failed`. Kong will automatically try to re-join a failed node just in case it becomes available again. You can exclude a failed node from the cluster in two ways: * Using the [`kong cluster force-leave`][cli-cluster] CLI command * Using the [API][cluster-api-remove]. Check the [Node Failures](#node-failures) paragraph for more info. ## 5. Checking the cluster state You can check the cluster state, its nodes and the state of each node in two ways. * By using the [`kong cluster members`][cli-cluster] CLI command. The output will include each node name, address and status in the cluster. The state can be `active` if a node is reachable, `failed` if it's status is currently unreachable or `left` if the node has been removed from the cluster. * Another way to check the state of the cluster is by making a request to the Admin API at the [cluster status endpoint][cluster-api-status]. ## 6. Network Assumptions When configuring a cluster in either a single or multi-datancer setup, you need to know that Kong works on the IP layer (hostnames are not supported, only IPs are allowed) and it expects a flat network topology without any NAT between the two datacenters. A common setup is having a VPN between the two datacenters such that the "flat" network assumption of Kong is not violated. Or by advertising public addresses using the `advertise` property in the [cluster settings][cluster] without jumping through the NAT. Kong will try to automatically determine the first non-loopback IPv4 address and share it with the other nodes, but you can override this address using the `advertise` property in the [cluster settings][cluster]. ## 7. Edge-case scenarios The implementation of the clustering feature of Kong is rather complex and may involve some edge case scenarios. ### Asynchronous join on concurrent node starts When multiple nodes are all being started simultaneously, a node may not be aware of the other nodes yet because the other nodes didn't have time to write their data to the datastore. To prevent this situation Kong implements by default a feature called "asynchronous auto-join". Asynchronous auto-join will check the datastore every 3 seconds for 60 seconds after a Kong node starts, and will join any node that may appear in those 60 seconds. This means that concurrent environments where multiple nodes are started simultaneously it could take up to 60 seconds for them to auto-join the cluster. ### Automatic cache purge on join Every time a new node joins the cluster, or a failed node re-joins the cluster, the cache for every node is purged and all the data is forced to be reloaded. This is to avoid inconsistencies between the data that has already been invalidated in the cluster, and the data stored on the node. This also means that after joining the cluster the new node's performance will be slower until the data has been re-cached into its memory. ### Node failures A node in the cluster can fail more multiple reasons, including networking problems or crashes. A node failure will also occur if Kong is not properly terminated by running `kong stop` or `kong quit`. When a node fails, Kong will lose the ability to communicate with it and the cluster will try to reconnect to the node. Its status will show up as `failed` when looking up the cluster health with [`kong cluster members`][cli-cluster]. To remove a `failed` node from the cluster, use the [`kong cluster force-leave`][cli-cluster] command, and its status will transition to `left`. The node data will persist for 1 hour in the datastore in case the node crashes, after which it will be removed from the datastore and new nodes will stop trying auto-joining it. ## 8. Problems and bug reports Clustering is a new feature introduced with Kong >= 0.6.x - if you experience any problem please contact us through our [Community Channels][community-channels]. [cluster_listen]: /{{page.kong_version}}/configuration/#cluster_listen [cluster_listen_rpc]: /{{page.kong_version}}/configuration/#cluster_listen_rpc [cluster]: /{{page.kong_version}}/configuration/#cluster [cli-cluster]: /{{page.kong_version}}/cli/#cluster [cluster-api-status]: /{{page.kong_version}}/admin-api/#retrieve-cluster-status [cluster-api-remove]: /{{page.kong_version}}/admin-api/#forcibly-remove-a-node [community-channels]: /community
{ "pile_set_name": "Github" }
<?php namespace app\shop\controller; use app\shop\controller\Base; class ShopDistributionUser extends Base { public $model; public function initialize() { $this->model = $this->getModel('shop_distribution_user'); parent::initialize(); } public function lists() { $this->assign('add_button', false); $this->assign('del_button', false); $this->assign('check_all', false); $param['mdm'] = input('mdm'); $res['title'] = '个人渠道'; $res['url'] = U ( 'Shop/ShopDistributionUser/lists', $param); $res['class'] = ACTION_NAME == 'lists' ? 'current' : ''; $nav[] = $res; $res['title'] = '粉丝统计'; $res['url'] = U ( 'Shop/ShopDistributionUser/statistics_lists', $param); $res['class'] = ACTION_NAME == 'statistics_lists' ? 'current' : ''; $nav[] = $res; // $res['title']='提成统计'; // $res['url']=U ( 'Shop/ShopDistributionUser/profit_details',$param); // $res ['class'] = ACTION_NAME == 'profit_details' ? 'current' : ''; // $nav[]=$res; $config = get_info_config('Shop'); if ($config['need_distribution'] == 1) { $res['title'] = '提现中心'; $res['url'] = U ( 'Shop/ShopDistributionUser/cashout_log_lists', $param); $res['class'] = ACTION_NAME == 'cashout_log_lists' ? 'current' : ''; $nav[] = $res; } $this->assign('nav', $nav); $map['wpid'] = get_wpid(); $did = I('did/d', 0); if ($did) { $duser = M('shop_distribution_user')->find($did); $lmap['uid|upper_user'] = $duser['uid']; $uids = M('shop_user_level_link')->where(wp_where($lmap))->column('uid'); if ($duser['level'] == 1) { $lmap['uid|upper_user'] = array('in', $uids); $uids = M('shop_user_level_link')->where(wp_where($lmap))->column('uid'); $lmap['uid|upper_user'] = array('in', $uids); } foreach ($uids as $k => $u) { if ($u != $duser['uid']) { $uidArr[] = $u; } } if (!empty($uidArr)) { $map['uid'] = array('in', $uidArr); } } $levelkey = I('level_key/d', 0); if ($levelkey) { $map['level'] = $levelkey; } $isCTime = I('is_ctime'); if ($isCTime) { $startVal = I('start_ctime', 0, 'strtotime'); $endVal = I('end_ctime', 0, 'strtotime'); $endVal = $endVal == 0 ? 0 : $endVal + 86400 - 1; if ($startVal && $endVal) { $startVal < $endVal && $map['ctime'] = array('between', array($startVal, $endVal)); $startVal > $endVal && $map['ctime'] = array('between', array($startVal, $endVal)); $startVal == $endVal && $map['ctime'] = array('egt', $startVal); } else if (!empty($startVal)) { $map['ctime'] = array('egt', $startVal); } else if (!empty($endVal)) { $map['ctime'] = array('elt', $endVal); } } $search = input('truename'); if ($search) { $this->assign('search', $search); $map1['truename'] = array( 'like', '%' . htmlspecialchars($search) . '%', ); $truename_follow_ids = D('common/User')->where(wp_where($map1))->column('uid'); // $truename_follow_ids = implode ( ',', $truename_follow_ids ); if (!empty($truename_follow_ids)) { $map['uid'] = array( 'in', $truename_follow_ids, ); } else { $map['id'] = 0; } unset($_REQUEST['truename']); } $map['is_delete'] = 0; session('common_condition', $map); $list_data = $this->_get_model_list($this->model); $typeName = $this->_get_level_name(); $dDao = D ( 'Shop/Distribution'); foreach ($list_data['list_data'] as &$vo) { $vo['level_key'] = $vo['level']; if ($vo['is_audit'] == 2) { $vo['level'] = '审核未通过'; } else { $vo['level'] = empty($vo['level']) ? '未审核' : $typeName[$vo['level']]; } $user = get_userinfo($vo['uid']); $duid = $vo['uid']; $vo['truename'] = $user['truename']; $vo['uid'] = $user['nickname']; $vo['mobile'] = $user['mobile']; $param['id'] = $vo['id']; $param['enable'] = $vo['enable']; $url = U ( 'Shop/ShopDistributionUser/changeEnable', $param); $vo['enable'] = $vo['enable'] == '0' ? "<a title='点击切换为启用' href='$url'>已禁用</a>" : "<a href='$url' title='点击切换为禁用'>已启用</a>"; if (!empty($vo['qr_code'])) { // $vo ['qr_code'] = "<a target='_blank' href='{$vo['qr_code']}'><img src='{$vo['qr_code']}' class='list_img'></a>"; continue; } $res = D('home/QrCode')->add_qr_code('QR_LIMIT_SCENE', 'Shop', $duid); if (!($res < 0)) { $map2['id'] = $vo['id']; M('shop_distribution_user')->where(wp_where($map2))->setField('qr_code', $res); $vo['qr_code'] = $res; $dDao->getDistributionUser($duid, true); // $vo ['qr_code'] = "<a target='_blank' href='{$vo['qr_code']}'><img src='{$vo['qr_code']}' class='list_img'></a>"; } } unset($list_data['list_grids']['is_audit']); $this->assign('typeName', $typeName); // dump($list_data['list_data']); $this->assign($list_data); $this->assign('model', $this->model['id']); $templateFile = $this->model['template_list'] ? $this->model['template_list'] : ''; return $this->fetch($templateFile); } public function edit() { $id = I('id', '0', 'intval'); if (IS_POST) { $data = input('post.'); // $data['ctime'] =time(); $this->_checkData($data, $id); $res = $this->_saveUserInfo(input('post.uid'), input('post.truename'), input('post.mobile')); $Model = D ($this->model ['name']); $data = $this->checkData($data, $this->model); $res = $Model->isUpdate(true)->save($data); if ($res) { D ( 'Shop/Distribution')->getDistributionUser(input('post.uid'), true); } // 清空缓存 method_exists($Model, 'clearCache') && $Model->clearCache($id, 'edit'); $this->success('保存' . $this->model['title'] . '成功!', U('lists?model=' . $this->model['name'], $this->get_param)); } else { $fields = get_model_attribute ( $this->model ); $cshop = $this->_get_stores(); $this->assign('stores', $cshop); // 获取数据 $data = M('shop_distribution_user')->where('id', $id)->find(); $userinfo = get_userinfo($data['uid']); $data['truename'] = $userinfo['truename']; $data['mobile'] = $userinfo['mobile']; $data['nickname'] = $userinfo['nickname']; $data['userimg'] = $userinfo['headimgurl']; $data || $this->error('数据不存在!'); $wpid = get_wpid(); if (isset($data['wpid']) && $wpid != $data['wpid']) { $this->error('非法访问!'); } $this->assign('fields', $fields); $this->assign('data', $data); $this->assign('is_edit', 1); return $this->fetch(); } } public function add() { if (IS_POST) { $data = input('post.'); // $data['ctime'] =time(); $this->_checkData($data); //添加二维码 $res = $this->_saveUserInfo(input('post.uid'), input('post.truename'), input('post.mobile')); $Model = D ($this->model ['name']); // 获取模型的字段信息 $data = $this->checkData($data, $this->model); $id = $Model->insertGetId($data); if ($res && $id) { // 清空缓存 method_exists($Model, 'clearCache') && $Model->clearCache($id, 'add'); $this->success('添加' . $this->model['title'] . '成功!', U('lists?model=' . $this->model['name'], $this->get_param)); } else { $this->error($Model->getError()); } } else { $cshop = $this->_get_stores(); $this->assign('stores', $cshop); $fields = get_model_attribute ( $this->model ); $this->assign('fields', $fields); $this->assign('is_edit', 0); return $this->fetch('edit'); } } public function _get_stores() { $cShop = M('stores')->where('wpid', WPID)->column('name','id'); return $cShop; } public function _checkData($data, $id = 0) { if (empty($data['truename'])) { $this->error('真实名字不能为空!'); } if (empty($data['mobile'])) { $this->error('手机号码不能为空!'); } if (!preg_match('/^\d{11}$/', $data['mobile'])) { $this->error('请输入正确的手机号码!'); } if (empty($data['uid'])) { $this->error('请指定微信名称'); } $map['wpid'] = get_wpid(); if (!$id) { $map['uid'] = $data['uid']; $res = M('shop_distribution_user')->where(wp_where($map))->value ('uid'); if ($res) { $this->error('该微信名称已经存在!'); } } else { $users = M('shop_distribution_user')->where(wp_where($map))->column('uid', 'id'); foreach ($users as $k => $u) { if ($k != $id) { if ($data['uid'] == $u) { $this->error('该微信名称已经存在!'); } } } } } public function _saveUserInfo($uid, $truename, $mobile) { $map['uid'] = $uid; $save['truename'] = $truename; $save['mobile'] = $mobile; $res = D('common/User')->where(wp_where($map))->update($save); D('common/User')->getUserInfo($uid, true); return $res; } public function changeEnable() { $map['id'] = I('id'); $enable = I('enable'); $save['enable'] = 1 - $enable; $res = M('shop_distribution_user')->where(wp_where($map))->update($save); $this->success('切换成功', U('lists?model=' . $this->model['name'])); } public function statistics_lists() { $param['mdm'] = input('mdm'); $res['title'] = '个人渠道'; $res['url'] = U ( 'Shop/ShopDistributionUser/lists', $param); $res['class'] = ACTION_NAME == 'lists' ? 'current' : ''; $nav[] = $res; $res['title'] = '粉丝统计'; $res['url'] = U ( 'Shop/ShopDistributionUser/statistics_lists', $param); $res['class'] = ACTION_NAME == 'statistics_lists' ? 'current' : ''; $nav[] = $res; // $res['title']='提成统计'; // $res['url']=U ( 'Shop/ShopDistributionUser/profit_details',$param); // $res ['class'] = ACTION_NAME == 'profit_details' ? 'current' : ''; // $nav[]=$res; $config = get_info_config('Shop'); if ($config['need_distribution'] == 1) { $res['title'] = '提现中心'; $res['url'] = U ( 'Shop/ShopDistributionUser/cashout_log_lists', $param); $res['class'] = ACTION_NAME == 'cashout_log_lists' ? 'current' : ''; $nav[] = $res; } $this->assign('nav', $nav); $this->assign('add_button', false); $this->assign('del_button', false); $this->assign('check_all', false); $this->assign('search_button', false); // $model=$this->getModel('shop_distribution_user'); // $list_data = $this->_get_model_list ( $model ); // dump($list_data); $grid['field'] = 'id'; $grid['title'] = '序号'; $list_grids[] = $grid; $grid['field'] = 'truename'; $grid['title'] = '分销用户'; $list_grids[] = $grid; $grid['field'] = 'follow_count'; $grid['title'] = '关注量'; $list_grids[] = $grid; $grid['field'] = 'male'; $grid['title'] = '男性'; $list_grids[] = $grid; $grid['field'] = 'fmale'; $grid['title'] = '女性'; $list_grids[] = $grid; $grid['field'] = 'ids'; $grid['title'] = '查看详情'; $list_grids[] = $grid; $list_data['list_grids'] = $list_grids; $isCTime = I('is_ctime'); if ($isCTime) { $startVal = I('start_ctime', 0, 'strtotime'); $endVal = I('end_ctime', 0, 'strtotime'); $endVal = $endVal == 0 ? 0 : $endVal + 86400 - 1; if ($startVal && $endVal) { $startVal < $endVal && $map['ctime'] = array('between', array($startVal, $endVal)); $startVal > $endVal && $map['ctime'] = array('between', array($startVal, $endVal)); $startVal == $endVal && $map['ctime'] = array('egt', $startVal); } else if (!empty($startVal)) { $map['ctime'] = array('egt', $startVal); } else if (!empty($endVal)) { $map['ctime'] = array('elt', $endVal); } } session('common_condition', $map); $model = $this->getModel('shop_distribution_user'); $user_data = $this->_get_model_list($model); $data = $user_data['list_data']; //获取关注量 $map1['wpid'] = get_wpid(); $followData = M('shop_statistics_follow')->where(wp_where($map1))->field('uid,duid')->select(); $wpid = get_wpid(); foreach ($followData as $f) { $userinfo = get_userinfo($f['uid']); if ($userinfo['has_subscribe'][$wpid] == 1) { $fcount[$f['duid']] += 1; } } //获取用户带来的粉丝 $fusers = M('shop_statistics_follow')->where(wp_where($map1))->column('duid', 'uid'); $male = 0; $fmale = 0; foreach ($fusers as $k => $fu) { $userinfo = get_userinfo($k); if ($userinfo['has_subscribe'][$wpid] == 1) { if ($userinfo['sex'] == 1) { //男 $countbysex[$fu]['mcount'] += 1; $male += 1; } else if ($userinfo['sex'] == 2) { //女 $countbysex[$fu]['fcount'] += 1; $fmale += 1; } } } $sexcount['male'] = $male; $sexcount['fmale'] = $fmale; $this->assign('pieSexCount', $sexcount); $param['mdm'] = input('mdm'); foreach ($data as &$vo) { $user = get_userinfo($vo['uid']); $vo['truename'] = $user['truename']; $vo['follow_count'] = intval($fcount[$vo['uid']]); $userArr[] = "'" . $vo['truename'] . "'"; $fcountArr[] = $vo['follow_count']; $vo['male'] = intval($countbysex[$vo['uid']]['mcount']); $vo['fmale'] = intval($countbysex[$vo['uid']]['fcount']); $url = U ( "Shop/ShopDistributionUser/show_details", array('duid' => $vo['uid'], 'mdm' => input('mdm'))); $param['duid'] = $vo['uid']; $furl = U ( 'Shop/ShopDistributionUser/get_user_from', $param); if ($vo['follow_count'] > 0) { $vo['ids'] = "<a data-duid='" . $vo['uid'] . "' class='details' href='$url'>查看详情</a> <a data-duid='" . $vo['uid'] . "' class='details' href='$furl'>粉丝详情</a> "; } else { $vo['ids'] = ""; } } $highcharts['xAxis'] = implode(',', $userArr); $highcharts['series'] = implode(',', $fcountArr); $this->assign('highcharts', $highcharts); $list_data['list_data'] = $data; $this->assign($list_data); $templateFile = $this->model['template_list'] ? $this->model['template_list'] : ''; return $this->fetch($templateFile); } //粉丝统计 public function show_details() { $param['mdm'] = input('mdm'); $res['title'] = '个人渠道'; $res['url'] = U ( 'Shop/ShopDistributionUser/lists', $param); $res['class'] = ACTION_NAME == 'lists' ? 'current' : ''; $nav[] = $res; $res['title'] = '粉丝统计'; $res['url'] = U ( 'Shop/ShopDistributionUser/statistics_lists', $param); $res['class'] = ACTION_NAME == 'statistics_lists' ? 'current' : ''; $nav[] = $res; // $res['title']='提成统计'; // $res['url']=U ( 'Shop/ShopDistributionUser/profit_details',$param); // $res ['class'] = ACTION_NAME == 'profit_details' ? 'current' : ''; // $nav[]=$res; $res['title'] = '查看详情数据'; $res['url'] = U ( 'Shop/ShopDistributionUser/show_details', $param); $res['class'] = ACTION_NAME == 'show_details' ? 'current' : ''; $nav[] = $res; $this->assign('nav', $nav); $this->assign('add_button', false); $this->assign('del_button', false); $this->assign('check_all', false); $this->assign('search_button', false); $grid['field'] = 'truename'; $grid['title'] = '用户名'; $list_grids[] = $grid; $grid['field'] = 'card_member'; $grid['title'] = '会员卡'; $list_grids[] = $grid; $grid['field'] = 'theday'; $grid['title'] = '日期'; $list_grids[] = $grid; $grid['field'] = 'fcount'; $grid['title'] = '女'; $list_grids[] = $grid; $grid['field'] = 'mcount'; $grid['title'] = '男'; $list_grids[] = $grid; $grid['field'] = 'num'; $grid['title'] = '关注量'; $list_grids[] = $grid; $list_data['list_grids'] = $list_grids; $map['duid'] = I('duid'); $map['wpid'] = get_wpid(); $fusers = M('shop_statistics_follow')->where(wp_where($map))->column("from_unixtime(ctime,'%Y-%m-%d') date", 'uid'); // $fcount=0; $wpid = get_wpid(); $userinfo = get_userinfo($map['duid']); $username = $userinfo['truename']; $map1['uid'] = $map['duid']; $cardMember = M('card_member')->where(wp_where($map1))->find(); if ($cardMember['number']) { $cardLevel = D ( 'Card/CardLevel')->getCardMemberLevel($map['duid']); $card = $cardMember['number'] . '<br/>' . $cardLevel['level']; } foreach ($fusers as $k => $v) { $user = get_userinfo($k); if ($user['has_subscribe'][$wpid] == 1) { $fcount[$v['date']]['theday'] = $v['date']; $fcount[$v['date']]['num'] += 1; if ($user['sex'] == 1) { $sexcount[$v['date']]['mcount'] += 1; } else if ($user['sex'] == 2) { $sexcount[$v['date']]['fcount'] += 1; } } } foreach ($fcount as $key => $vo) { $vo['card_member'] = $card; $vo['truename'] = $username; $vo['mcount'] = intval($sexcount[$key]['mcount']); $vo['fcount'] = intval($sexcount[$key]['fcount']); $vo['num'] = intval($vo['num']); $data[] = $vo; } $list_data['list_data'] = $data; $this->assign($list_data); return $this->fetch(); // $this->ajaxReturn($fcount); } //提成统计 public function profit_details() { $param['mdm'] = input('mdm'); $res['title'] = '个人渠道'; $res['url'] = U ( 'Shop/ShopDistributionUser/lists', $param); $res['class'] = ACTION_NAME == 'lists' ? 'current' : ''; $nav[] = $res; $res['title'] = '粉丝统计'; $res['url'] = U ( 'Shop/ShopDistributionUser/statistics_lists', $param); $res['class'] = ACTION_NAME == 'statistics_lists' ? 'current' : ''; $nav[] = $res; // $res['title']='提成统计'; // $res['url']=U ( 'Shop/ShopDistributionUser/profit_details',$param); // $res ['class'] = ACTION_NAME == 'profit_details' ? 'current' : ''; // $nav[]=$res; $this->assign('nav', $nav); $this->assign('add_button', false); $this->assign('del_button', false); $this->assign('check_all', false); $this->assign('search_button', false); $grid['field'] = 'id'; $grid['title'] = '序号'; $list_grids[] = $grid; $grid['field'] = 'truename'; $grid['title'] = '用户姓名'; $list_grids[] = $grid; $grid['field'] = 'card_member'; $grid['title'] = '会员卡号'; $list_grids[] = $grid; $grid['field'] = 'profit'; $grid['title'] = '提成金额(¥)'; $list_grids[] = $grid; $grid['field'] = 'fcount'; $grid['title'] = '增粉数量'; $list_grids[] = $grid; // $grid ['field'] = 'fans_gift_money'; // $grid ['title'] = '增粉赠送金额'; // $list_grids [] = $grid; // $grid ['field'] = 'fans_gift_score'; // $grid ['title'] = '增粉赠送积分'; // $list_grids [] = $grid; // $grid ['field'] = 'fans_gift_coupon'; // $grid ['title'] = '增粉赠送代金券(张)'; // $list_grids [] = $grid; $list_data['list_grids'] = $list_grids; // $model=$this->getModel('shop_distribution_user'); // $user_data = $this->_get_model_list ( $model ); // $data=$user_data['list_data']; $map['wpid'] = get_wpid(); $data = M('shop_distribution_user')->where(wp_where($map))->select(); //获取关注量 $map1['wpid'] = get_wpid(); $follows = M('shop_statistics_follow')->where(wp_where($map1))->field('uid,duid')->select(); $wpid = get_wpid(); foreach ($follows as $f) { $user = get_userinfo($f['uid']); if ($user['has_subscribe'][$wpid] == 1) { $fcount[$f['duid']] += 1; } } // $levels=M( 'card_level' )->where( wp_where($map) )->column('level', 'id'); foreach ($data as $k => &$vo) { $user = get_userinfo($vo['uid']); $map['uid'] = $vo['uid']; $cardMember = M('card_member')->where(wp_where($map))->find(); if ($cardMember['number']) { $cardLevel = D ( 'Card/CardLevel')->getCardMemberLevel($vo['uid']); $vo['card_member'] = $cardMember['number'] . '<br/>' . $cardLevel['level']; } $vo['truename'] = $user['truename']; $param['duid'] = $vo['uid']; $furl = U ( 'Shop/ShopDistributionUser/get_user_from', $param); $vo['fcount'] = intval($fcount[$vo['uid']]) == 0 ? 0 : "<a href='$furl' >" . intval($fcount[$vo['uid']]) . "</a>"; $profit = $this->_get_user_profit($vo['uid']); $purl = U ( 'Shop/ShopDistributionUser/get_profit_from', $param); $vo['profit'] = $profit == 0 ? 0 : "<a href='$purl' >" . $profit . "</a>"; $url = U ( "Shop/ShopDistributionUser/show_details", array('duid' => $vo['uid'])); // $vo['ids']="<a data-duid='".$vo['uid']."' class='details' href='$url'>查看详情</a>"; $vo['id'] = $k + 1; } $list_data['list_data'] = $data; $this->assign($list_data); return $this->fetch('show_details'); // $this->ajaxReturn($fcount); } public function _get_user_profit($uid) { $config = get_info_config('Shop'); $level = $config['level']; $total = 0; if ($level == 1) { //一级分佣 $map['wpid'] = get_wpid(); $map['uid'] = $uid; $map['profit_shop'] = 0; } else { $map1['wpid'] = get_wpid(); $map1['manager_id'] = $uid; $shopid = D ( 'Shop/Shop')->where(wp_where($map1))->value ('id'); if ($shopid) { $map['wpid'] = get_wpid(); $map['profit_shop'] = $shopid; } } $totals = M('shop_distribution_profit')->where(wp_where($map))->field('sum( profit ) totals')->select(); $total = wp_money_format($totals[0]['totals']); return $total; } //获取提成的来源 注释的内容为原先分销系统内容 public function get_profit_from() { $uid = I('duid/d', 0); $duserName = get_userinfo($uid, 'truename'); $is_duser = I('is_duser/d', 0); $param['mdm'] = input('mdm'); $res['title'] = '个人渠道'; $res['url'] = U ( 'Shop/ShopDistributionUser/lists', $param); $res['class'] = ACTION_NAME == 'lists' ? 'current' : ''; $nav[] = $res; $res['title'] = '粉丝统计'; $res['url'] = U ( 'Shop/ShopDistributionUser/statistics_lists', $param); $res['class'] = ACTION_NAME == 'statistics_lists' ? 'current' : ''; $nav[] = $res; // $res['title']='提成统计'; // $res['url']=U ( 'Shop/ShopDistributionUser/profit_details',$param); // $res ['class'] = ACTION_NAME == 'profit_details' ? 'current' : ''; // $nav[]=$res; $res['title'] = $duserName . ' 的提成详情'; $res['url'] = U ( 'Shop/ShopDistributionUser/get_profit_from', $param); $res['class'] = ACTION_NAME == 'get_profit_from' ? 'current' : ''; $nav[] = $res; $this->assign('nav', $nav); $bt['title'] = '返回'; $bt['url'] = U('duser_profit_analysis', array('mdm' => input('mdm'), 'duid' => $uid)); $btn[] = $bt; $this->assign('top_more_button', $btn); $this->assign('add_button', false); $this->assign('del_button', false); $this->assign('check_all', false); $this->assign('search_button', false); if ($is_duser) { $grid['field'] = 'upper_user'; $grid['title'] = '我的下级分销商 '; $list_grids[] = $grid; } else { $grid['field'] = 'upper_user'; $grid['title'] = '我的客户'; $list_grids[] = $grid; } if ($is_duser) { $grid['field'] = 'level'; $grid['title'] = '分销商等级'; $list_grids[] = $grid; $grid['field'] = 'followid'; $grid['title'] = '消费用户'; $list_grids[] = $grid; } $grid['field'] = 'order_number'; $grid['title'] = '订单号'; $list_grids[] = $grid; // $grid ['field'] = 'totals'; // $grid ['title'] = '用户消费金额'; // $list_grids [] = $grid; $grid['field'] = 'profit_precent'; $grid['title'] = '提成比例'; $list_grids[] = $grid; $grid['field'] = 'profit'; $grid['title'] = '提成金额'; $list_grids[] = $grid; $grid['field'] = 'time'; $grid['title'] = '交易时间'; $list_grids[] = $grid; $list_data['list_grids'] = $list_grids; $levelName = $this->_get_level_name(); $followMember = D ( 'Shop/Distribution')->get_follow_member($uid, 0); if (empty($is_duser)) { //客户带来的收益 $uidArr[] = $uid; $map['upper_user'] = array( 'in', $uidArr, ); $map['wpid'] = get_wpid(); if (!empty($followMember)) { $uuarr = getSubByKey($followMember, 'uid'); $map['uid'] = array('in', $uuarr); } else { $map['uid'] = 0; } } else { $uidArr = D ( 'Shop/Distribution')->get_duser_member($uid, 0); $map['duser'] = array('in', $uidArr); $map['upper_user'] = $uid; $map['wpid'] = get_wpid(); } // $config=get_info_config('Shop'); // $level = $config['level']; // if($level==1){ // $map['wpid']=get_wpid(); // $map['uid']=$uid; // $map['profit_shop']=0; // }else { // $map1['wpid']=get_wpid(); // $map1['manager_id']=$uid; // $shopid=D ( 'Shop/Shop')->where( wp_where($map1) )->value ('id'); // if ($shopid){ // $map['wpid']=get_wpid(); // $map['profit_shop']=$shopid; // } // } $profitData = M('shop_distribution_profit')->where(wp_where($map))->select(); $orderDao = D ( 'Shop/Order'); foreach ($profitData as $v) { $data['profit_precent'] = ($v['distribution_percent'] * 100) . '%'; $order = $orderDao->getInfo($v['order_id']); $data['totals'] = $order['total_price']; $data['profit'] = wp_money_format($v['profit']); $data['time'] = time_format($v['ctime']); $orderUrl = U ( 'Shop/Order/lists', array('order_id' => $order['id'])); $data['order_number'] = "<a href='$orderUrl' target='_blank' >" . $order['order_number'] . "</a>"; if ($is_duser) { $data['followid'] = get_userinfo($order['uid'], 'nickname'); $data['level'] = $levelName[$v['upper_level']]; $data['upper_user'] = get_userinfo($v['duser'], 'truename'); } else { $data['upper_user'] = get_userinfo($order['uid'], 'nickname'); } $datas[] = $data; } $list_data['list_data'] = $datas; $this->assign($list_data); return $this->fetch('show_details'); } public function get_user_from() { $param['mdm'] = input('mdm'); $res['title'] = '个人渠道'; $res['url'] = U ( 'Shop/ShopDistributionUser/lists', $param); $res['class'] = ACTION_NAME == 'lists' ? 'current' : ''; $nav[] = $res; $res['title'] = '粉丝统计'; $res['url'] = U ( 'Shop/ShopDistributionUser/statistics_lists', $param); $res['class'] = ACTION_NAME == 'statistics_lists' ? 'current' : ''; $nav[] = $res; // $res['title']='提成统计'; // $res['url']=U ( 'Shop/ShopDistributionUser/profit_details',$param); // $res ['class'] = ACTION_NAME == 'profit_details' ? 'current' : ''; // $nav[]=$res; $res['title'] = '粉丝详情'; $res['url'] = U ( 'Shop/ShopDistributionUser/get_user_from', $param); $res['class'] = ACTION_NAME == 'get_user_from' ? 'current' : ''; $nav[] = $res; $this->assign('nav', $nav); $this->assign('add_button', false); $this->assign('del_button', false); $this->assign('check_all', false); $this->assign('search_button', false); $grid['field'] = 'followid'; $grid['title'] = '带来的粉丝'; $list_grids[] = $grid; $grid['field'] = 'card_member'; $grid['title'] = '会员卡号'; $list_grids[] = $grid; $grid['field'] = 'sex'; $grid['title'] = '性别'; $list_grids[] = $grid; $grid['field'] = 'time'; $grid['title'] = '关注时间'; $list_grids[] = $grid; $list_data['list_grids'] = $list_grids; $map['duid'] = I('duid'); $map['wpid'] = get_wpid(); $duser = M('shop_statistics_follow')->where(wp_where($map))->column('ctime', 'uid'); $wpid = get_wpid(); foreach ($duser as $k => $v) { $data['card_member'] = ''; $user = get_userinfo($k); if ($user['has_subscribe'][$wpid] == 1) { $map1['uid'] = $k; $map1['wpid'] = $wpid; $cardMember = M('card_member')->where(wp_where($map1))->find(); $cardLevel = D ( 'Card/CardLevel')->getCardMemberLevel($k); if ($cardMember['number']) { $data['card_member'] = $cardMember['number'] . '<br/>' . $cardLevel['level']; } else { $data['card_member'] == '' && $data['card_member'] = '非会员'; } $data['followid'] = $user['nickname']; $data['sex'] = $user['sex'] == 1 ? '男' : '女'; $data['time'] = time_format($v); $datas[] = $data; } } $list_data['list_data'] = $datas; $this->assign($list_data); return $this->fetch('show_details'); } ///////////////////升级分销功能 新增函数///////////////////////// //分销用户设置分销商级别 public function set_user_level() { $dMap['id'] = $id = I('id'); if (empty($id)) { $this->error('找不到数据'); } if (IS_POST) { $dSave['is_audit'] = input('post.is_audit/d', 0); if ($dSave['is_audit'] == 1) { //审核通过 $dSave['level'] = input('post.level'); } else { $dSave['level'] = 0; } $uMap['uid'] = input('post.uid'); $uMap['wpid'] = get_wpid(); $userlevel = M('shop_user_level_link')->where(wp_where($uMap))->find(); if (!empty($userlevel)) { $saveData['level'] = $dSave['level']; $saveData['upper_user'] = input('post.upper_user'); $res1 = M('shop_user_level_link')->where(wp_where($uMap))->update($saveData); } else { if (!empty($dSave['level'])) { $addData['level'] = $dSave['level']; $addData['upper_user'] = input('post.upper_user'); $addData['uid'] = $uMap['uid']; $addData['cTime'] = time(); $addData['wpid'] = get_wpid(); $res1 = M('shop_user_level_link')->insert($addData); } } $res = M('shop_distribution_user')->where(wp_where($dMap))->update($dSave); if ($res!==false || $res1!==false) { D ( 'Shop/Distribution')->getDistributionUser($uMap['uid'], true); echo 1; } else { echo 0; } exit(); } else { $duser = M('shop_distribution_user')->where('id', $id)->find(); if (empty($duser['uid'])) { $this->error('找不到用户'); } $typeName = $this->_get_level_name(); //查询一二级分销商 $map['wpid'] = get_wpid(); $map['level'] = array('in', array(1, 2)); $map['uid'] = array('neq', $duser['uid']); $userLinks = M('shop_user_level_link')->where(wp_where($map))->select(); foreach ($userLinks as $vo) { $user = get_userinfo($vo['uid']); $vo['username'] = empty($user['truename']) ? $user['nickname'] : $user['truename']; $userdatas[$vo['level']][] = $vo; } if (!isset($userdatas[1])) { unset($typeName[2]); unset($typeName[3]); } else if (!isset($userdatas[2])) { unset($typeName[3]); } // dump($userLinks); $data['type_name'] = $typeName; $data['user_data'] = $userdatas; $data['duser'] = $duser; $this->assign($data); return $this->fetch(); } } //获取分销级别类型名称 public function _get_level_name() { $config = get_info_config('Shop'); $typeName = []; switch ($config['level']) { case 1: if ($config['level_name_1']) { $typeName[1] = $config['level_name_1']; } else { $typeName[1] = '一级分销商'; } break; case 2: if ($config['level_name_1']) { $typeName[1] = $config['level_name_1']; } else { $typeName[1] = '一级分销商'; } if ($config['level_name_2']) { $typeName[2] = $config['level_name_2']; } else { $typeName[2] = '二级分销商'; } break; case 3: if ($config['level_name_1']) { $typeName[1] = $config['level_name_1']; } else { $typeName[1] = '一级分销商'; } if ($config['level_name_2']) { $typeName[2] = $config['level_name_2']; } else { $typeName[2] = '二级分销商'; } if ($config['level_name_3']) { $typeName[3] = $config['level_name_3']; } else { $typeName[3] = '三级分销商'; } break; default: $typeName = null; break; } return $typeName; } //删除用户 使用is_delete 标识 public function do_del_duser() { $did = I('id'); $duser = M('shop_distribution_user')->where('id', $did)->find(); if (empty($duser)) { echo 0; exit(); } $lmap['uid|upper_user'] = $duser['uid']; $uids = M('shop_user_level_link')->where(wp_where($lmap))->column( 'uid' ); // 将该用户以下关系级别设置为0,相当于删除 if ($duser['level'] == 1) { $lmap['uid|upper_user'] = array( 'in', $uids, ); $uids = M('shop_user_level_link')->where(wp_where($lmap))->column( 'uid' ); $lmap['uid|upper_user'] = array( 'in', $uids, ); } else { $lmap['uid|upper_user'] = $duser['uid']; } // $lsave ['level'] = 0; // $res1 = M( 'shop_user_level_link' )->where ( wp_where( $lmap ) )->update ( $lsave ); $res1 = M('shop_user_level_link')->where(wp_where($lmap))->delete(); // if ($res1){ if (!empty($uids)) { $map['uid'] = array( 'in', $uids, ); } else { $map['uid'] = $duser['uid']; } // $save ['is_delete'] = 1; // $res = M( 'shop_distribution_user' )->where ( wp_where( $map ) )->update ( $save ); $res = M('shop_distribution_user')->where(wp_where($map))->delete(); if ($res) { $followMap['duid'] = $map['uid']; $followMap['wpid'] = get_wpid(); M('shop_statistics_follow')->where(wp_where($followMap))->delete(); $disDao = D ( 'Shop/Distribution'); foreach ($uids as $uid) { $disDao->getDistributionUser($uid, true); } echo 1; } else { echo -1; } // }else{ // echo -1; // } } public function user_detail() { $this->assign('del_button', false); $this->assign('check_all', false); $this->assign('add_button', false); $bt['title'] = '返回列表'; $bt['url'] = U('lists', array('mdm' => input('mdm'))); $btn[] = $bt; $this->assign('top_more_button', $btn); $param['mdm'] = input('mdm'); $res['title'] = '个人渠道'; $res['url'] = U ( 'Shop/ShopDistributionUser/lists', $param); $res['class'] = ACTION_NAME == 'lists' ? 'current' : ''; $nav[] = $res; $res['title'] = '用户详情'; $res['url'] = U ( 'Shop/ShopDistributionUser/user_detail', $param); $res['class'] = ACTION_NAME == 'user_detail' ? 'current' : ''; $nav[] = $res; $this->assign('nav', $nav); $grid['field'] = 'truename'; $grid['title'] = '姓名'; $list_grids[] = $grid; $grid['field'] = 'mobile'; $grid['title'] = '手机号'; $list_grids[] = $grid; $grid['field'] = 'wechat'; $grid['title'] = '微信号'; $list_grids[] = $grid; $grid['field'] = 'inviter'; $grid['title'] = '邀请人'; $list_grids[] = $grid; $grid['field'] = 'level'; $grid['title'] = '分销级别'; $list_grids[] = $grid; $grid['field'] = 'profit_money'; $grid['title'] = '收益金额'; $list_grids[] = $grid; $grid['field'] = 'now_money'; $grid['title'] = '现有金额'; $list_grids[] = $grid; $grid['field'] = 'member_count'; $grid['title'] = '我的团队'; $list_grids[] = $grid; $grid['field'] = 'coustom_count'; $grid['title'] = '我的客户'; $list_grids[] = $grid; $list_data['list_grids'] = $list_grids; $map['wpid'] = get_wpid(); $did = I('did/d', 0); $duid = I('duid/d', 0); if (empty($did) && empty($duid)) { $this->error('找不到该分销用户!'); } $dDao = D ( 'Shop/Distribution'); if ($did) { $duser = M('shop_distribution_user')->where('id', $did)->find(); } else { $duser = $dDao->getDistributionUser($duid); } $uidArr = $dDao->get_duser_member($duser['uid'], 0, 1); if (!empty($uidArr)) { $map['uid'][] = array( 'in', $uidArr, ); } else { $map['id'] = 0; } $search = input('truename'); if ($search) { $this->assign('search', $search); $map1['truename'] = array( 'like', '%' . htmlspecialchars($search) . '%', ); $truename_follow_ids = D('common/User')->where(wp_where($map1))->column( 'uid' ); // $truename_follow_ids = implode ( ',', $truename_follow_ids ); if (!empty($truename_follow_ids)) { $map['uid'][] = array( 'in', $truename_follow_ids, ); } else { $map['id'] = 0; } unset($_REQUEST['truename']); } $profitData = D ( 'Shop/Distribution')->get_duser_profit($duser['uid']); $map['is_delete'] = 0; $datas = M('shop_distribution_user')->where(wp_where($map))->select(); if (empty($datas)) { $datas[] = $duser; } else { array_unshift($datas, $duser); } // $list_data = $this->_get_model_list ( $this->model ); $typeName = $this->_get_level_name(); foreach ($datas as $vo) { $vo['level_key'] = $vo['level']; if ($vo['is_audit'] == 2) { $vo['level'] = '审核未通过'; } else { $vo['level'] = empty($vo['level']) ? '未审核' : $typeName[$vo['level']]; } $user = get_userinfo($vo['uid']); $vo['truename'] = $user['truename']; $vo['nickname'] = $user['nickname']; $vo['mobile'] = $user['mobile']; $profit = floatval($profitData[$vo['uid']]); // $vo ['profit_money'] = $vo ['profit_money']; $vo['profit_money'] = wp_money_format($profit); if ($vo['profit_money'] > 0) { $purl = U('duser_profit_analysis', array('duid' => $vo['uid'], 'mdm' => input('mdm'))); $vo['profit_money'] = "<a href='" . $purl . "' >" . $vo['profit_money'] . "</a>"; } $nowMoney = $dDao->get_duser_cashout($vo['uid']); $vo['now_money'] = wp_money_format($profit - $nowMoney); $vo['member_count'] = $dDao->get_duser_member($vo['uid']); $vo['coustom_count'] = $dDao->get_follow_member($vo['uid']); if ($vo['member_count'] != 0 && $vo['uid'] != $duser['uid']) { $lurl = U('user_detail', array('mdm' => input('mdm'), 'duid' => $vo['uid'])); $vo['member_count'] = "<a href='" . $lurl . "'>" . $vo['member_count'] . "</a>"; } if ($vo['coustom_count'] > 0) { $vo['coustom_count'] = "<a href='" . U('coustom_details', array('duid' => $vo['uid'], 'mdm' => input('mdm'))) . "'>" . $vo['coustom_count'] . "</a>"; } $list_data['list_data'][] = $vo; } $this->assign('search_key', 'truename'); $this->assign('search_url', U('user_detail', array( 'did' => $did, 'mdm' => input('mdm'), ))); $this->assign($list_data); return $this->fetch(); } //客户信息表 public function coustom_details() { $duid = I('duid/d', 0); $param['mdm'] = input('mdm'); $res['title'] = '个人渠道'; $res['url'] = U ( 'Shop/ShopDistributionUser/lists', $param); $res['class'] = ACTION_NAME == 'lists' ? 'current' : ''; $nav[] = $res; $dname = get_userinfo($duid, 'truename'); $res['title'] = $dname . ' 客户列表'; $res['url'] = ''; $res['class'] = ACTION_NAME == 'coustom_details' ? 'current' : ''; $nav[] = $res; $this->assign('nav', $nav); $bt['title'] = '返回详情列表'; $bt['url'] = U('user_detail', array('duid' => $duid, 'mdm' => input('mdm'))); $btn[] = $bt; $this->assign('top_more_button', $btn); $this->assign('add_button', false); $this->assign('del_button', false); $this->assign('check_all', false); $this->assign('search_button', false); $grid['field'] = 'nickname'; $grid['title'] = '昵称'; $list_grids[] = $grid; $grid['field'] = 'userface'; $grid['title'] = '头像'; $list_grids[] = $grid; $grid['field'] = 'sex'; $grid['title'] = '性别'; $list_grids[] = $grid; $list_data['list_grids'] = $list_grids; $uidArr = D ( 'Shop/Distribution')->get_follow_member($duid, 0); foreach ($uidArr as $uid) { $user = get_userinfo($uid['uid']); $data = []; $data['nickname'] = $user['nickname']; $data['userface'] = url_img_html($user['headimgurl']); $data['sex'] = $user['sex_name'] ? '保密' : $user['sex_name']; $datas[] = $data; } $list_data['list_data'] = $datas; $this->assign($list_data); return $this->fetch('show_details'); // $this->ajaxReturn($fcount); } //分销用户收益统计表 public function duser_profit_analysis() { $duid = I('duid/d', 0); $param['mdm'] = input('mdm'); $res['title'] = '个人渠道'; $res['url'] = U ( 'Shop/ShopDistributionUser/lists', $param); $res['class'] = ACTION_NAME == 'lists' ? 'current' : ''; $nav[] = $res; $res['title'] = '粉丝统计'; $res['url'] = U ( 'Shop/ShopDistributionUser/statistics_lists', $param); $res['class'] = ACTION_NAME == 'statistics_lists' ? 'current' : ''; $nav[] = $res; $dname = get_userinfo($duid, 'truename'); $res['title'] = $dname . ' 获利统计表'; $res['url'] = ''; $res['class'] = ACTION_NAME == 'duser_profit_analysis' ? 'current' : ''; $nav[] = $res; $this->assign('nav', $nav); $bt['title'] = '返回详情列表'; $bt['url'] = U('user_detail', array('duid' => $duid, 'mdm' => input('mdm'))); $btn[] = $bt; $this->assign('top_more_button', $btn); $this->assign('add_button', false); $this->assign('del_button', false); $this->assign('check_all', false); $this->assign('search_button', false); $grid['field'] = 'truename'; $grid['title'] = '分销用户'; $list_grids[] = $grid; $grid['field'] = 'level'; $grid['title'] = '分销等级'; $list_grids[] = $grid; $grid['field'] = 'coustom_profit'; $grid['title'] = '我的客户带来收益'; $list_grids[] = $grid; $grid['field'] = 'team_profit'; $grid['title'] = '下级分销商带来收益'; $list_grids[] = $grid; $grid['field'] = 'total_profit'; $grid['title'] = '总收益'; $list_grids[] = $grid; $list_data['list_grids'] = $list_grids; $dDao = D ( 'Shop/Distribution'); //获取下级 $uidArr = $dDao->get_duser_member($duid, 0, 1); if (empty($uidArr)) { $uidArr[] = $duid; } else { array_unshift($uidArr, $duid); //将用户本身插入到最前 } foreach ($uidArr as $uid) { $data = []; $data = $dDao->get_total_profit_from($uid); if ($data['coustom_profit'] > 0) { $data['coustom_profit'] = "<a href='" . U('get_profit_from', array('mdm' => input('mdm'), 'duid' => $uid)) . "' >" . wp_money_format($data['coustom_profit']) . "</a>"; } else { $data['coustom_profit'] = wp_money_format($data['coustom_profit']); } if ($data['team_profit'] > 0 && $uid != $duid) { $data['team_profit'] = "<a href='" . U('duser_profit_analysis', array('mdm' => input('mdm'), 'duid' => $uid)) . "' >" . wp_money_format($data['team_profit']) . "</a>"; } else if ($data['team_profit'] > 0 && $uid == $duid) { $data['team_profit'] = "<a href='" . U('get_profit_from', array('mdm' => input('mdm'), 'duid' => $uid, 'is_duser' => 1)) . "' >" . wp_money_format($data['team_profit']) . "</a>"; } else { $data['team_profit'] = wp_money_format($data['team_profit']); } $duser = $dDao->getDistributionUser($uid); $levelName = $this->_get_level_name(); $data['truename'] = get_userinfo($uid, 'truename'); $data['level'] = $levelName[$duser['level']]; $datas[] = $data; } // $uidArr = D ( 'Shop/Distribution') -> get_follow_member($duid, 0); // foreach ($uidArr as $uid){ // $user=get_userinfo($uid['uid']); // $data=[]; // $data['nickname'] = $user['nickname']; // $data['userface'] = url_img_html($user['headimgurl']); // $data['sex'] = $user['sex_name'] ?'保密':$user['sex_name']; // $datas[]= $data; // } $list_data['list_data'] = $datas; $this->assign($list_data); return $this->fetch(); // $this->ajaxReturn($fcount); } //分销提现记录表 public function cashout_log_lists() { $param['mdm'] = input('mdm'); $res['title'] = '个人渠道'; $res['url'] = U ( 'Shop/ShopDistributionUser/lists', $param); $res['class'] = ACTION_NAME == 'lists' ? 'current' : ''; $nav[] = $res; $res['title'] = '粉丝统计'; $res['url'] = U ( 'Shop/ShopDistributionUser/statistics_lists', $param); $res['class'] = ACTION_NAME == 'statistics_lists' ? 'current' : ''; $nav[] = $res; // $res['title']='提成统计'; // $res['url']=U ( 'Shop/ShopDistributionUser/profit_details',$param); // $res ['class'] = ACTION_NAME == 'profit_details' ? 'current' : ''; // $nav[]=$res; $config = get_info_config('Shop'); if ($config['need_distribution'] == 1) { $res['title'] = '提现中心'; $res['url'] = U ( 'Shop/ShopDistributionUser/cashout_log_lists', $param); $res['class'] = ACTION_NAME == 'cashout_log_lists' ? 'current' : ''; $nav[] = $res; } $this->assign('nav', $nav); $this->assign('del_button', false); $this->assign('add_button', false); $this->assign('check_all', false); $this->assign('search_key', 'truename'); $this->assign('placeholder', '输入分销商姓名搜索'); $searUrl = U('cashout_log_lists', $param); $this->assign('search_url', $searUrl); $grid['field'] = 'truename'; $grid['title'] = '分销商姓名'; $list_grids[] = $grid; $grid['field'] = 'mobile'; $grid['title'] = '手机号'; $list_grids[] = $grid; $grid['field'] = 'level'; $grid['title'] = '分销级别'; $list_grids[] = $grid; $grid['field'] = 'zfb_name'; $grid['title'] = '支付宝名称'; $list_grids[] = $grid; $grid['field'] = 'zfb_account'; $grid['title'] = '支付宝帐号'; $list_grids[] = $grid; $grid['field'] = 'amount'; $grid['title'] = '提现金额'; $list_grids[] = $grid; $grid['field'] = 'ctime'; $grid['title'] = '申请时间'; $list_grids[] = $grid; $grid['field'] = 'remark'; $grid['title'] = '备注'; $list_grids[] = $grid; $grid['field'] = 'status'; $grid['title'] = '状态'; $list_grids[] = $grid; $grid['field'] = 'ids'; $grid['title'] = '设置状态'; $list_grids[] = $grid; $search = input('truename'); if ($search) { $this->assign('search', $search); $map1['truename'] = array( 'like', '%' . htmlspecialchars($search) . '%', ); $truename_follow_ids = D('common/User')->where(wp_where($map1))->column( 'uid' ); // $truename_follow_ids = implode ( ',', $truename_follow_ids ); if (!empty($truename_follow_ids)) { $map['uid'] = array( 'in', $truename_follow_ids, ); } else { $map['id'] = 0; } unset($_REQUEST['truename']); } $status = I('status/d', 0); if ($status == 3) { $map['cashout_status'] = 0; } else if ($status == 1) { $map['cashout_status'] = 1; } else if ($status == 2) { $map['cashout_status'] = 2; } $map['wpid'] = get_wpid(); $list_data['list_data'] = M('shop_cashout_log')->where(wp_where($map))->select(); $list_data['list_grids'] = $list_grids; $dDao = D ( 'Shop/Distribution'); $levelName = $this->_get_level_name(); foreach ($list_data['list_data'] as &$vo) { $vo['ctime'] = time_format($vo['ctime']); $duser = $dDao->getDistributionUser($vo['uid']); $vo['zfb_name'] = $duser['zfb_name']; $vo['zfb_account'] = $duser['zfb_account']; $vo['level'] = $levelName[$duser['level']]; $userinfo = get_userinfo($vo['uid']); $vo['truename'] = $userinfo['truename']; $vo['mobile'] = $userinfo['mobile']; $vo['amount'] = wp_money_format($vo['cashout_amount']); if ($vo['cashout_status'] == 0) { $vo['status'] = '未处理'; $vo['ids'] = "<a onClick='set_status(" . $vo['id'] . ");' href='javascript:;' >设置状态</a>"; } else if ($vo['cashout_status'] == 1) { $vo['status'] = '提现成功'; $vo['ids'] = "--"; } else { $vo['status'] = '提现失败'; $vo['ids'] = "--"; } } $bt['title'] = '导出'; $bt['url'] = U('output', array('status' => $status, 'truename' => $search)); $btn[] = $bt; $this->assign('top_more_button', $btn); $this->assign($list_data); return $this->fetch(); } public function output() { $grid['field'] = 'truename'; $grid['title'] = '分销商姓名'; $list_grids[] = $grid; $grid['field'] = 'mobile'; $grid['title'] = '手机号'; $list_grids[] = $grid; $grid['field'] = 'level'; $grid['title'] = '分销级别'; $list_grids[] = $grid; $grid['field'] = 'amount'; $grid['title'] = '提现金额'; $list_grids[] = $grid; $grid['field'] = 'ctime'; $grid['title'] = '申请时间'; $list_grids[] = $grid; $grid['field'] = 'status'; $grid['title'] = '状态'; $list_grids[] = $grid; $search = input('truename'); if ($search) { $this->assign('search', $search); $map1['truename'] = array( 'like', '%' . htmlspecialchars($search) . '%', ); $truename_follow_ids = D('common/User')->where(wp_where($map1))->column( 'uid' ); // $truename_follow_ids = implode ( ',', $truename_follow_ids ); if (!empty($truename_follow_ids)) { $map['uid'] = array( 'in', $truename_follow_ids, ); } else { $map['id'] = 0; } unset($_REQUEST['truename']); } $status = I('status/d', 0); if ($status == 3) { $map['cashout_status'] = 0; } else if ($status == 1) { $map['cashout_status'] = 1; } else if ($status == 2) { $map['cashout_status'] = 2; } $map['wpid'] = get_wpid(); $list_data['list_data'] = M('shop_cashout_log')->where(wp_where($map))->select(); $list_data['list_grids'] = $list_grids; $dDao = D ( 'Shop/Distribution'); $levelName = $this->_get_level_name(); foreach ($list_data['list_grids'] as $vv) { $fields[] = $vv['field']; $titleArr[] = $vv['title']; } $dataArr[] = $titleArr; foreach ($list_data['list_data'] as $vo) { $duser = $dDao->getDistributionUser($vo['uid']); $userinfo = get_userinfo($vo['uid']); $dd['truename'] = $userinfo['truename']; $dd['mobile'] = $userinfo['mobile']; $dd['level'] = $levelName[$duser['level']]; $dd['amount'] = wp_money_format($vo['cashout_amount']); $dd['ctime'] = time_format($vo['ctime']); if ($vo['cashout_status'] == 0) { $dd['status'] = '未处理'; } else if ($vo['cashout_status'] == 1) { $dd['status'] = '提现成功'; } else { $dd['status'] = '提现失败'; } $dataArr[] = $dd; } require_once env('vendor_path') . 'out-csv.php'; export_csv($dataArr, 'card_member'); } public function set_cashout_status() { $id = I('id'); if (IS_POST) { $res = 0; $logs = M('shop_cashout_log')->where('id', $id)->find(); $save['cashout_status'] = input('post.is_status'); if ($save['cashout_status']) { $res = M('shop_cashout_log')->where(wp_where(array('id' => $id)))->update($save); } echo $res; exit(); } $this->assign('id', $id); return $this->fetch(); } }
{ "pile_set_name": "Github" }
# set warnreset=no increase=auto warnroot=no warnReset=no warnTree=no warnTSave=no warnBlkName=no errorStop=no errorBeep=no queryBeep=no; # execute 'trees/cetaceans.taxa.nex'; # cleartrees; # gett file = 'trees/cetaceans.mb.strict-clock.mcmc.trees' storebrlens=yes warntree=no rooted=yes storetreewts=yes from=151 mode=7; # treeinfo; # tstatus / full; # contree / strict=no showtree=no grpfreq=yes majrule=yes percent=50 usetreewts=yes; # [!SPLITS END] # ...............**..... 98304 98304 101 100.00 ...............**....* 2195456 2195456 101 100.00 .................**... 393216 393216 101 100.00 .....*..............*. 1048608 1048608 101 100.00 ...*........*......... 4104 4104 101 100.00 ...*.*.*...***......*. 1063080 1063080 101 100.00 ...***.*...***...**.*. 1456312 1456312 101 100.00 ...***.**..***...**.*. 1456568 1456568 101 100.00 .........**........... 1536 1536 101 100.00 ..*...........*....... 16388 16388 101 100.00 ..*...*.......*....... 16452 16452 101 100.00 .**...*.......*....... 16454 16454 101 100.00 .**...*..**...*....*.. 542278 542278 101 100.00 .********************* 4194302 4194302 101 100.00 ...*.*.*....**......*. 1061032 1061032 95 94.06 ...*........**........ 12296 12296 93 92.08 ...*.*.*...***...**.*. 1456296 1456296 89 88.12 .........**........*.. 525824 525824 87 86.14 ...*.*......**......*. 1060904 1060904 70 69.31 .**************..****. 1998846 1998846 60 59.41 .**...*..**...***..*.* 2737734 2737734 33 32.67 .**...*.......*....*.. 540742 540742 14 13.86 ...*...*....**........ 12424 12424 13 12.87 .....*.*............*. 1048736 1048736 11 10.89 ...***.**..***.****.** 3652024 3652024 8 7.92 ...***.*...***......*. 1063096 1063096 7 6.93 .....*.......*......*. 1056800 1056800 7 6.93 ...*...*....*......... 4232 4232 7 6.93 .......*...*.......... 2176 2176 6 5.94 ....*............**... 393232 393232 5 4.95 ...*...*...***........ 14472 14472 1 0.99
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_144) on Wed Sep 06 08:23:36 PDT 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class javax.json.bind.annotation.JsonbProperty (Java(TM) EE 8 Specification APIs)</title> <meta name="date" content="2017-09-06"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class javax.json.bind.annotation.JsonbProperty (Java(TM) EE 8 Specification APIs)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../javax/json/bind/annotation/JsonbProperty.html" title="annotation in javax.json.bind.annotation">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?javax/json/bind/annotation/class-use/JsonbProperty.html" target="_top">Frames</a></li> <li><a href="JsonbProperty.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class javax.json.bind.annotation.JsonbProperty" class="title">Uses of Class<br>javax.json.bind.annotation.JsonbProperty</h2> </div> <div class="classUseContainer">No usage of javax.json.bind.annotation.JsonbProperty</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../javax/json/bind/annotation/JsonbProperty.html" title="annotation in javax.json.bind.annotation">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?javax/json/bind/annotation/class-use/JsonbProperty.html" target="_top">Frames</a></li> <li><a href="JsonbProperty.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 1996-2017, <a href="http://www.oracle.com">Oracle</a> and/or its affiliates. All Rights Reserved. Use is subject to <a href="../../../../../doc-files/speclicense.html" target="_top">license terms</a>.</small></p> </body> </html>
{ "pile_set_name": "Github" }
reviewers: - colhom - csbell - irfanurrehman - madhusudancs - marun - mwielgus - nikhiljindal - quinton-hoole - shashidharatd approvers: - csbell - madhusudancs - mwielgus - nikhiljindal - quinton-hoole
{ "pile_set_name": "Github" }
interface wlan0 static ip_address=192.168.4.1/24 static routers=192.168.4.1 static domain_name_servers=192.168.4.1 nohook wpa_supplicant metric 400
{ "pile_set_name": "Github" }
# # SMBios Config Sample file # # Comments goes until CR/LF/CR+LF # # # For UTF-8 encoded file, the BOM (Byte Order Mark) at the start of the file # is supported (Windows Notepad can create or deal with this and display # the characters correctly if the fonts are installed). # Typically this would be the result of UTF-8 encoding bytes of the # unicode char U+FEFF, ie EF BB BF # # FW will ignore these bytes if present at the starting of the file # # Cfg version, if the data layout changes ever, Ignore for now. CFG:01.01 # # SMBIOS Version this config file's data is compatible with # This should have a matching entry to the FW supported version # Multiple entries are allowed, given that the field positions # listed in this file known to match for all these versions. # This should be verified by the config creator to make sure # the offsets match in all the versions listed below. FW does # NOT do *any* validation to offer maximum flexibility. # # VER:dd.dd # d : Decimal char # # Ignore for now. VER:02.03 VER:02.06 # # Fields definition # # All the field configuration values are comma seperated # # Type,Byte Offset,Data Type,Data # # Type : 2 chars in Hex format # Byte Offset : 2 chars in Hex (if XX ignored, used for strings only types) # Data Type : 1 char, 'I' for Integer type, 'S' for String type # Data : As many bytes to fill, following details for each data type # I : As many number of Hex chars can be given, one byte (2 hex chars) # are dealt at a time. Starts at the byte offset indicated, goes on # filling the data as much is presented in the config line. ie the # data should be in the order of its memory address. To keep # readability multiple config lines can be used with appropriate # offset. For filling the memory for WORD, DWORD, GUID fields the # byte stream should be formatted appropriately. Space can be used # to enhance readability (Space ignored only for integer types). # Number of chars should be even, if odd number of chars are listed # then the behavior is undefined. # # S : String in double Quotes. If Byte Offset is indicated then the # string in that offset is replaced. If Byte Offset is XX then its # config creator to make appended to the last string. But the string # offset should be available already after the structure in string # fields. # XX strings applicable only for tables added via this Config file # # # Type 1, Offset 04 System Manufacturer # 01,04,S,"Contoso" # Type 1, Offset 05 System Product Name # 01,05,S,"SecureSample" # Type 1, Product Serial Number # 01,07,S,"01234567890" # # Type 1, Offset 19 System SKU Number # 01,19,S,"SecureSampleSKU" # # Type 1, Offset 1B System Family # 01,1A,S,"ContosoFamily" # # Type 2, Offset 05 Baseboard Product # 02,05,S,"QCDB410C" # # Add System enclosure, Type 3 # ADD:03 16 0000 01 08 02 03 04 01 01 01 03 00000000 00 00 00 00 00 3100 3200 3300 3400 00 # # System Manufacturer # 03,04,S,"Qualcomm Inc" # # System Version # 03,06,S,"1.03" # # System enclosure or Chassis Serial number # 03,07,S,"254784521" # # System enclosure or Chassis Asset tag number # 03,08,S,"P004782" # # Type 17, Memory Device # #ADD:11 22 0000 0000 FEFF FFFF FFFF 0004 0A 00 00 00 13 0000 1502 01 02 03 04 00 00000000 1502 3100 3200 3300 3400 00 # Form factor 0x0E (offset), TSOP 0x0A # 11,0E,I,0A # Memory Type 0x12 (offset), DDR2 0x13 # 11,12,I,13 # Memory speed 0x15 (offset), 533MHz - 0x0215 # 11,15,I,0215 # Add the strings #11,17,S,"Hynix" #11,18,S,"9876385" #11,19,S,"P3456" #11,1A,S,"H9TKNNN2GDAPLR-NYM" # # Add binary blob as a new table type # All bytes are from LSB to MSB as many present, in Hex format # Similar to integer type. # # This example adds the Type 11 table with 5 strings, that are # populated later # # A fixed space buffer (currently 256 bytes, is configurable) is allocated for # binary table data. # ADD:0B 05 0000 05 3100 3200 3300 3400 3500 00 # # Type 11, OEM Strings # # Actual strings for above # # To add more strings, change the integer field in the Blob above # 0B,XX,S,"OEM String 1" 0B,XX,S,"OEM String 2" 0B,XX,S,"OEM String 3" 0B,XX,S,"OEM String 4" 0B,XX,S,"OEM String 5" # # Any other language strings that cannot represented in ASCII format # Should be in UTF-8 encoded format. The file also need to be saved with # UTF-8 encoding # # This is example string in Simplified chinese for "This is just an example" #0B,XX,S,"这仅仅是一个例子" # The is example string in Korean for "This is just an example" #0B,XX,S,"이것은 단지 예입니다" # # End of config # Blank line needed after the last config #
{ "pile_set_name": "Github" }
// Copyright (c) 2020 Private Internet Access, Inc. // // This file is part of the Private Internet Access Desktop Client. // // The Private Internet Access Desktop Client is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. // // The Private Internet Access Desktop Client is distributed in the hope that // it will be useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with the Private Internet Access Desktop Client. If not, see // <https://www.gnu.org/licenses/>. #include "tasks.h" #include "installer.h" #include "util.h" bool g_rebootAfterInstall = false; bool g_rebootBeforeInstall = false; #ifdef INSTALLER #define ERROR_MSG_SUFFIX_ABORT IDS_MB_SUFFIX_INSTALL_ABORT #define ERROR_MSG_SUFFIX_RETRY IDS_MB_SUFFIX_INSTALL_RETRY #define ERROR_MSG_SUFFIX_IGNORE IDS_MB_SUFFIX_INSTALL_IGNORE #define ERROR_MSG_SUFFIX_RETRYIGNORE IDS_MB_SUFFIX_INSTALL_RETRYIGNORE #else #define ERROR_MSG_SUFFIX_ABORT IDS_MB_SUFFIX_UNINSTALL_ABORT #define ERROR_MSG_SUFFIX_RETRY IDS_MB_SUFFIX_UNINSTALL_RETRY #define ERROR_MSG_SUFFIX_IGNORE IDS_MB_SUFFIX_UNINSTALL_IGNORE #define ERROR_MSG_SUFFIX_RETRYIGNORE IDS_MB_SUFFIX_UNINSTALL_RETRYIGNORE #endif ErrorType InstallerError::raise(ErrorType type, UIString str) { #ifdef UNINSTALLER type |= ShouldIgnore; #endif LOG("ERROR: %ls", str.str()); // Never display dialog boxes in silent mode if (g_silent || type & Silent) { if ((type & (Ignore | ShouldIgnore)) == (Ignore | ShouldIgnore)) return Ignore; goto abort; } // Skip ignorable errors in passive mode if (g_passive && (type & (Ignore | ShouldIgnore)) == (Ignore | ShouldIgnore)) return Ignore; UINT mbType; UINT msgSuffixId = 0; switch (type & (Ignore | Retry)) { case Ignore | Retry: mbType = MB_ICONWARNING | MB_CANCELTRYCONTINUE | (type & ShouldIgnore ? MB_DEFBUTTON3 : MB_DEFBUTTON2); msgSuffixId = ERROR_MSG_SUFFIX_RETRYIGNORE; break; case Ignore: mbType = MB_ICONWARNING | MB_YESNO; msgSuffixId = ERROR_MSG_SUFFIX_IGNORE; break; case Retry: mbType = MB_ICONWARNING | MB_RETRYCANCEL; msgSuffixId = ERROR_MSG_SUFFIX_RETRY; break; default: case Abort: mbType = MB_ICONERROR | MB_OK; msgSuffixId = ERROR_MSG_SUFFIX_ABORT; break; } switch (messageBox(str, IDS_MB_CAP_ERROR, msgSuffixId, mbType)) { default: case IDOK: case IDCANCEL: case IDABORT: case IDNO: abort: if (type & NoThrow) return Abort; else throw InstallerError(std::move(str)); case IDRETRY: case IDTRYAGAIN: return Retry; case IDYES: case IDCONTINUE: return Ignore; } } void InstallerError::abort(UIString str) { raise(Abort, std::move(str)); } CaptionTask::CaptionTask(UIString caption) : _caption(std::move(caption)) { } void CaptionTask::execute() { if (_caption) _listener->setCaption(_caption); }
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="en" > <head> <title>No encoding declaration</title> <link rel='author' title='Richard Ishida' href='mailto:[email protected]'> <link rel='help' href='http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream'> <link rel="stylesheet" type="text/css" href="./generatedtests.css"> <script src="http://w3c-test.org/resources/testharness.js"></script> <script src="http://w3c-test.org/resources/testharnessreport.js"></script> <meta name='flags' content='http'> <meta name="assert" content="A page with no encoding information in HTTP, BOM, XML declaration or meta element will be treated as UTF-8."> <style type='text/css'> .test div { width: 50px; }</style> <link rel="stylesheet" type="text/css" href="the-input-byte-stream/support/encodingtests-utf8.css"> </head> <body> <p class='title'>No encoding declaration</p> <div id='log'></div> <div class='test'><div id='box' class='ýäè'>&#xA0;</div></div> <div class='description'> <p class="assertion" title="Assertion">A page with no encoding information in HTTP, BOM, XML declaration or meta element will be treated as UTF-8.</p> <div class="notes"><p><p>The test on this page contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector <code>.test div.&#x00FD;&#x00E4;&#x00E8;</code>. This matches the sequence of bytes above when they are interpreted as UTF-8. If the class name matches the selector then the test will pass.</p></p> </div> </div> <div class="nexttest"><div><a href="generate?test=the-input-byte-stream-034">Next test</a></div><div class="doctype">HTML5</div> <p class="jump">the-input-byte-stream-015<br /><a href="/International/tests/html5/the-input-byte-stream/results-basics#basics" target="_blank">Result summary &amp; related tests</a><br /><a href="http://w3c-test.org/framework/details/i18n-html5/the-input-byte-stream-015" target="_blank">Detailed results for this test</a><br/> <a href="http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream" target="_blank">Link to spec</a></p> <div class='prereq'>Assumptions: <ul><li>The test is read from a server that supports HTTP.</li></ul></div> </div> <script> test(function() { assert_equals(document.getElementById('box').offsetWidth, 100); }, " "); </script> </body> </html>
{ "pile_set_name": "Github" }
# /******************************************************************************* # Copyright (c) 2019, Xilinx, Inc. # 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. Neither the name of the copyright holder 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 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. # # *******************************************************************************/ if { $::argc != 2 } { puts "ERROR: Application \"$::argv0\" requires 2 arguments!\n" puts "Usage: $::argv0 <xpfm_path> <xo_pathname>\n" exit } set xpfm_path [lindex $::argv 0] set xo_pathname [lindex $::argv 1] set pinfo [file join [pwd] "pinfo.json"] if {[file exists ${xpfm_path}]} { exec $::env(XILINX_SDX)/bin/platforminfo -j $pinfo -p ${xpfm_path} } if {[file exists "myadder2_ex"]} { file delete -force "myadder2_ex" } if {[file exists "project_2"]} { file delete -force "project_2" } if {![file exists $pinfo]} { puts "ERROR: $pinfo does not exist!" } set fid [open $pinfo r] set fpgapart "fpgaPart" while { ! [eof $fid] } { gets $fid line if { [regexp {([^:[:space:]]+): (.*),$} $line match left right] } { regsub -all {\"} $left {} left regsub -all {\"} $right {} right if { $left eq $fpgapart } { if { [string match {*:*} $right] } { set fields [split $right ":"] set f0 [lindex $fields 0] set f1 [lindex $fields 1] set f2 [lindex $fields 2] set f3 [lindex $fields 3] set f4 [lindex $fields 4] set partname "${f1}-${f2}${f3}-${f4}" puts "partname = $partname\n" break } } } } close $fid create_project project_2 project_2 -part $partname create_ip -name sdx_kernel_wizard -vendor xilinx.com -library ip -version 1.0 -module_name myadder2 set_property -dict [list CONFIG.Component_Name {myadder2} CONFIG.KERNEL_NAME {myadder2} CONFIG.KERNEL_CTRL {ap_ctrl_hs} CONFIG.NUM_INPUT_ARGS {0} CONFIG.NUM_M_AXI {0} CONFIG.NUM_AXIS {2} CONFIG.AXIS00_NAME {out} CONFIG.AXIS01_NAME {in}] [get_ips myadder2] generate_target {instantiation_template} [get_files myadder2.xci] set_property generate_synth_checkpoint false [get_files myadder2.xci] open_example_project -force -in_process -dir [pwd] [get_ips myadder2] # -------------------------------------------- # Start: RTL Kernel Packaging of Sources # source -notrace myadder2_ex/imports/package_kernel.tcl # Packaging project package_project myadder2_ex/myadder2 xilinx.com user myadder2 package_xo -xo_path myadder2_ex/sdx_imports/myadder2.xo -kernel_name myadder2 -ip_directory myadder2_ex/myadder2 -kernel_xml myadder2_ex/imports/kernel.xml -kernel_files myadder2_ex/imports/myadder2_cmodel.cpp # Complete: RTL Kernel Packaging of Sources # -------------------------------------------- set xo_path [file join [pwd] ${xo_pathname}] if {[file exists "myadder2_ex/sdx_imports/myadder2.xo"]} { file copy myadder2_ex/sdx_imports/myadder2.xo ${xo_path} } else { puts "ERROR: myadder2_ex/sdx_imports/myadder2.xo does not exist!\n" exit 1 }
{ "pile_set_name": "Github" }
import argparse parser = argparse.ArgumentParser() parser.add_argument('framework', type=str, help="The framework to evaluate as defined by default in resources/frameworks.yaml.") parser.add_argument('benchmark', type=str, nargs='?', default='test', help="The benchmark type to run as defined by default in resources/benchmarks/{benchmark}.yaml.") parser.add_argument('-m', '--mode', choices=['local', 'docker', 'aws'], default='local', help="The mode that specifies how/where the benchmark tasks will be running. Defaults to %(default)s.") parser.add_argument('-p', '--parallel', metavar='parallel_jobs', type=int, default=1, help="The number of jobs (i.e. tasks or folds) that can run in parallel. Defaults to %(default)s. " "Currently supported only in docker and aws mode.") args = parser.parse_args()
{ "pile_set_name": "Github" }
<?php namespace Illuminate\Database\Eloquent\Relations; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Support\Str; use InvalidArgumentException; class BelongsToMany extends Relation { use Concerns\InteractsWithPivotTable; /** * The intermediate table for the relation. * * @var string */ protected $table; /** * The foreign key of the parent model. * * @var string */ protected $foreignPivotKey; /** * The associated key of the relation. * * @var string */ protected $relatedPivotKey; /** * The key name of the parent model. * * @var string */ protected $parentKey; /** * The key name of the related model. * * @var string */ protected $relatedKey; /** * The "name" of the relationship. * * @var string */ protected $relationName; /** * The pivot table columns to retrieve. * * @var array */ protected $pivotColumns = []; /** * Any pivot table restrictions for where clauses. * * @var array */ protected $pivotWheres = []; /** * Any pivot table restrictions for whereIn clauses. * * @var array */ protected $pivotWhereIns = []; /** * Any pivot table restrictions for whereNull clauses. * * @var array */ protected $pivotWhereNulls = []; /** * The default values for the pivot columns. * * @var array */ protected $pivotValues = []; /** * Indicates if timestamps are available on the pivot table. * * @var bool */ public $withTimestamps = false; /** * The custom pivot table column for the created_at timestamp. * * @var string */ protected $pivotCreatedAt; /** * The custom pivot table column for the updated_at timestamp. * * @var string */ protected $pivotUpdatedAt; /** * The class name of the custom pivot model to use for the relationship. * * @var string */ protected $using; /** * The name of the accessor to use for the "pivot" relationship. * * @var string */ protected $accessor = 'pivot'; /** * The count of self joins. * * @var int */ protected static $selfJoinCount = 0; /** * Create a new belongs to many relationship instance. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Model $parent * @param string $table * @param string $foreignPivotKey * @param string $relatedPivotKey * @param string $parentKey * @param string $relatedKey * @param string|null $relationName * @return void */ public function __construct(Builder $query, Model $parent, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $relationName = null) { $this->parentKey = $parentKey; $this->relatedKey = $relatedKey; $this->relationName = $relationName; $this->relatedPivotKey = $relatedPivotKey; $this->foreignPivotKey = $foreignPivotKey; $this->table = $this->resolveTableName($table); parent::__construct($query, $parent); } /** * Attempt to resolve the intermediate table name from the given string. * * @param string $table * @return string */ protected function resolveTableName($table) { if (! Str::contains($table, '\\') || ! class_exists($table)) { return $table; } $model = new $table; if (! $model instanceof Model) { return $table; } if ($model instanceof Pivot) { $this->using($table); } return $model->getTable(); } /** * Set the base constraints on the relation query. * * @return void */ public function addConstraints() { $this->performJoin(); if (static::$constraints) { $this->addWhereConstraints(); } } /** * Set the join clause for the relation query. * * @param \Illuminate\Database\Eloquent\Builder|null $query * @return $this */ protected function performJoin($query = null) { $query = $query ?: $this->query; // We need to join to the intermediate table on the related model's primary // key column with the intermediate table's foreign key for the related // model instance. Then we can set the "where" for the parent models. $baseTable = $this->related->getTable(); $key = $baseTable.'.'.$this->relatedKey; $query->join($this->table, $key, '=', $this->getQualifiedRelatedPivotKeyName()); return $this; } /** * Set the where clause for the relation query. * * @return $this */ protected function addWhereConstraints() { $this->query->where( $this->getQualifiedForeignPivotKeyName(), '=', $this->parent->{$this->parentKey} ); return $this; } /** * Set the constraints for an eager load of the relation. * * @param array $models * @return void */ public function addEagerConstraints(array $models) { $whereIn = $this->whereInMethod($this->parent, $this->parentKey); $this->query->{$whereIn}( $this->getQualifiedForeignPivotKeyName(), $this->getKeys($models, $this->parentKey) ); } /** * Initialize the relation on a set of models. * * @param array $models * @param string $relation * @return array */ public function initRelation(array $models, $relation) { foreach ($models as $model) { $model->setRelation($relation, $this->related->newCollection()); } return $models; } /** * Match the eagerly loaded results to their parents. * * @param array $models * @param \Illuminate\Database\Eloquent\Collection $results * @param string $relation * @return array */ public function match(array $models, Collection $results, $relation) { $dictionary = $this->buildDictionary($results); // Once we have an array dictionary of child objects we can easily match the // children back to their parent using the dictionary and the keys on the // the parent models. Then we will return the hydrated models back out. foreach ($models as $model) { if (isset($dictionary[$key = $model->{$this->parentKey}])) { $model->setRelation( $relation, $this->related->newCollection($dictionary[$key]) ); } } return $models; } /** * Build model dictionary keyed by the relation's foreign key. * * @param \Illuminate\Database\Eloquent\Collection $results * @return array */ protected function buildDictionary(Collection $results) { // First we will build a dictionary of child models keyed by the foreign key // of the relation so that we will easily and quickly match them to their // parents without having a possibly slow inner loops for every models. $dictionary = []; foreach ($results as $result) { $dictionary[$result->{$this->accessor}->{$this->foreignPivotKey}][] = $result; } return $dictionary; } /** * Get the class being used for pivot models. * * @return string */ public function getPivotClass() { return $this->using ?? Pivot::class; } /** * Specify the custom pivot model to use for the relationship. * * @param string $class * @return $this */ public function using($class) { $this->using = $class; return $this; } /** * Specify the custom pivot accessor to use for the relationship. * * @param string $accessor * @return $this */ public function as($accessor) { $this->accessor = $accessor; return $this; } /** * Set a where clause for a pivot table column. * * @param string $column * @param mixed $operator * @param mixed $value * @param string $boolean * @return $this */ public function wherePivot($column, $operator = null, $value = null, $boolean = 'and') { $this->pivotWheres[] = func_get_args(); return $this->where($this->table.'.'.$column, $operator, $value, $boolean); } /** * Set a "where between" clause for a pivot table column. * * @param string $column * @param array $values * @param string $boolean * @param bool $not * @return $this */ public function wherePivotBetween($column, array $values, $boolean = 'and', $not = false) { return $this->whereBetween($this->table.'.'.$column, $values, $boolean, $not); } /** * Set a "or where between" clause for a pivot table column. * * @param string $column * @param array $values * @return $this */ public function orWherePivotBetween($column, array $values) { return $this->wherePivotBetween($column, $values, 'or'); } /** * Set a "where pivot not between" clause for a pivot table column. * * @param string $column * @param array $values * @param string $boolean * @return $this */ public function wherePivotNotBetween($column, array $values, $boolean = 'and') { return $this->wherePivotBetween($column, $values, $boolean, true); } /** * Set a "or where not between" clause for a pivot table column. * * @param string $column * @param array $values * @return $this */ public function orWherePivotNotBetween($column, array $values) { return $this->wherePivotBetween($column, $values, 'or', true); } /** * Set a "where in" clause for a pivot table column. * * @param string $column * @param mixed $values * @param string $boolean * @param bool $not * @return $this */ public function wherePivotIn($column, $values, $boolean = 'and', $not = false) { $this->pivotWhereIns[] = func_get_args(); return $this->whereIn($this->table.'.'.$column, $values, $boolean, $not); } /** * Set an "or where" clause for a pivot table column. * * @param string $column * @param mixed $operator * @param mixed $value * @return $this */ public function orWherePivot($column, $operator = null, $value = null) { return $this->wherePivot($column, $operator, $value, 'or'); } /** * Set a where clause for a pivot table column. * * In addition, new pivot records will receive this value. * * @param string|array $column * @param mixed $value * @return $this * * @throws \InvalidArgumentException */ public function withPivotValue($column, $value = null) { if (is_array($column)) { foreach ($column as $name => $value) { $this->withPivotValue($name, $value); } return $this; } if (is_null($value)) { throw new InvalidArgumentException('The provided value may not be null.'); } $this->pivotValues[] = compact('column', 'value'); return $this->wherePivot($column, '=', $value); } /** * Set an "or where in" clause for a pivot table column. * * @param string $column * @param mixed $values * @return $this */ public function orWherePivotIn($column, $values) { return $this->wherePivotIn($column, $values, 'or'); } /** * Set a "where not in" clause for a pivot table column. * * @param string $column * @param mixed $values * @param string $boolean * @return $this */ public function wherePivotNotIn($column, $values, $boolean = 'and') { return $this->wherePivotIn($column, $values, $boolean, true); } /** * Set an "or where not in" clause for a pivot table column. * * @param string $column * @param mixed $values * @return $this */ public function orWherePivotNotIn($column, $values) { return $this->wherePivotNotIn($column, $values, 'or'); } /** * Set a "where null" clause for a pivot table column. * * @param string $column * @param string $boolean * @param bool $not * @return $this */ public function wherePivotNull($column, $boolean = 'and', $not = false) { $this->pivotWhereNulls[] = func_get_args(); return $this->whereNull($this->table.'.'.$column, $boolean, $not); } /** * Set a "where not null" clause for a pivot table column. * * @param string $column * @param string $boolean * @return $this */ public function wherePivotNotNull($column, $boolean = 'and') { return $this->wherePivotNull($column, $boolean, true); } /** * Set a "or where null" clause for a pivot table column. * * @param string $column * @param bool $not * @return $this */ public function orWherePivotNull($column, $not = false) { return $this->wherePivotNull($column, 'or', $not); } /** * Set a "or where not null" clause for a pivot table column. * * @param string $column * @return $this */ public function orWherePivotNotNull($column) { return $this->orWherePivotNull($column, true); } /** * Find a related model by its primary key or return new instance of the related model. * * @param mixed $id * @param array $columns * @return \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model */ public function findOrNew($id, $columns = ['*']) { if (is_null($instance = $this->find($id, $columns))) { $instance = $this->related->newInstance(); } return $instance; } /** * Get the first related model record matching the attributes or instantiate it. * * @param array $attributes * @return \Illuminate\Database\Eloquent\Model */ public function firstOrNew(array $attributes) { if (is_null($instance = $this->related->where($attributes)->first())) { $instance = $this->related->newInstance($attributes); } return $instance; } /** * Get the first related record matching the attributes or create it. * * @param array $attributes * @param array $joining * @param bool $touch * @return \Illuminate\Database\Eloquent\Model */ public function firstOrCreate(array $attributes, array $joining = [], $touch = true) { if (is_null($instance = $this->related->where($attributes)->first())) { $instance = $this->create($attributes, $joining, $touch); } return $instance; } /** * Create or update a related record matching the attributes, and fill it with values. * * @param array $attributes * @param array $values * @param array $joining * @param bool $touch * @return \Illuminate\Database\Eloquent\Model */ public function updateOrCreate(array $attributes, array $values = [], array $joining = [], $touch = true) { if (is_null($instance = $this->related->where($attributes)->first())) { return $this->create($values, $joining, $touch); } $instance->fill($values); $instance->save(['touch' => false]); return $instance; } /** * Find a related model by its primary key. * * @param mixed $id * @param array $columns * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|null */ public function find($id, $columns = ['*']) { if (! $id instanceof Model && (is_array($id) || $id instanceof Arrayable)) { return $this->findMany($id, $columns); } return $this->where( $this->getRelated()->getQualifiedKeyName(), '=', $this->parseId($id) )->first($columns); } /** * Find multiple related models by their primary keys. * * @param \Illuminate\Contracts\Support\Arrayable|array $ids * @param array $columns * @return \Illuminate\Database\Eloquent\Collection */ public function findMany($ids, $columns = ['*']) { $ids = $ids instanceof Arrayable ? $ids->toArray() : $ids; if (empty($ids)) { return $this->getRelated()->newCollection(); } return $this->whereIn( $this->getRelated()->getQualifiedKeyName(), $this->parseIds($ids) )->get($columns); } /** * Find a related model by its primary key or throw an exception. * * @param mixed $id * @param array $columns * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection * * @throws \Illuminate\Database\Eloquent\ModelNotFoundException */ public function findOrFail($id, $columns = ['*']) { $result = $this->find($id, $columns); $id = $id instanceof Arrayable ? $id->toArray() : $id; if (is_array($id)) { if (count($result) === count(array_unique($id))) { return $result; } } elseif (! is_null($result)) { return $result; } throw (new ModelNotFoundException)->setModel(get_class($this->related), $id); } /** * Add a basic where clause to the query, and return the first result. * * @param \Closure|string|array $column * @param mixed $operator * @param mixed $value * @param string $boolean * @return \Illuminate\Database\Eloquent\Model|static */ public function firstWhere($column, $operator = null, $value = null, $boolean = 'and') { return $this->where($column, $operator, $value, $boolean)->first(); } /** * Execute the query and get the first result. * * @param array $columns * @return mixed */ public function first($columns = ['*']) { $results = $this->take(1)->get($columns); return count($results) > 0 ? $results->first() : null; } /** * Execute the query and get the first result or throw an exception. * * @param array $columns * @return \Illuminate\Database\Eloquent\Model|static * * @throws \Illuminate\Database\Eloquent\ModelNotFoundException */ public function firstOrFail($columns = ['*']) { if (! is_null($model = $this->first($columns))) { return $model; } throw (new ModelNotFoundException)->setModel(get_class($this->related)); } /** * Get the results of the relationship. * * @return mixed */ public function getResults() { return ! is_null($this->parent->{$this->parentKey}) ? $this->get() : $this->related->newCollection(); } /** * Execute the query as a "select" statement. * * @param array $columns * @return \Illuminate\Database\Eloquent\Collection */ public function get($columns = ['*']) { // First we'll add the proper select columns onto the query so it is run with // the proper columns. Then, we will get the results and hydrate out pivot // models with the result of those columns as a separate model relation. $builder = $this->query->applyScopes(); $columns = $builder->getQuery()->columns ? [] : $columns; $models = $builder->addSelect( $this->shouldSelect($columns) )->getModels(); $this->hydratePivotRelation($models); // If we actually found models we will also eager load any relationships that // have been specified as needing to be eager loaded. This will solve the // n + 1 query problem for the developer and also increase performance. if (count($models) > 0) { $models = $builder->eagerLoadRelations($models); } return $this->related->newCollection($models); } /** * Get the select columns for the relation query. * * @param array $columns * @return array */ protected function shouldSelect(array $columns = ['*']) { if ($columns == ['*']) { $columns = [$this->related->getTable().'.*']; } return array_merge($columns, $this->aliasedPivotColumns()); } /** * Get the pivot columns for the relation. * * "pivot_" is prefixed ot each column for easy removal later. * * @return array */ protected function aliasedPivotColumns() { $defaults = [$this->foreignPivotKey, $this->relatedPivotKey]; return collect(array_merge($defaults, $this->pivotColumns))->map(function ($column) { return $this->table.'.'.$column.' as pivot_'.$column; })->unique()->all(); } /** * Get a paginator for the "select" statement. * * @param int|null $perPage * @param array $columns * @param string $pageName * @param int|null $page * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) { $this->query->addSelect($this->shouldSelect($columns)); return tap($this->query->paginate($perPage, $columns, $pageName, $page), function ($paginator) { $this->hydratePivotRelation($paginator->items()); }); } /** * Paginate the given query into a simple paginator. * * @param int|null $perPage * @param array $columns * @param string $pageName * @param int|null $page * @return \Illuminate\Contracts\Pagination\Paginator */ public function simplePaginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) { $this->query->addSelect($this->shouldSelect($columns)); return tap($this->query->simplePaginate($perPage, $columns, $pageName, $page), function ($paginator) { $this->hydratePivotRelation($paginator->items()); }); } /** * Chunk the results of the query. * * @param int $count * @param callable $callback * @return bool */ public function chunk($count, callable $callback) { $this->query->addSelect($this->shouldSelect()); return $this->query->chunk($count, function ($results, $page) use ($callback) { $this->hydratePivotRelation($results->all()); return $callback($results, $page); }); } /** * Chunk the results of a query by comparing numeric IDs. * * @param int $count * @param callable $callback * @param string|null $column * @param string|null $alias * @return bool */ public function chunkById($count, callable $callback, $column = null, $alias = null) { $this->query->addSelect($this->shouldSelect()); $column = $column ?? $this->getRelated()->qualifyColumn( $this->getRelatedKeyName() ); $alias = $alias ?? $this->getRelatedKeyName(); return $this->query->chunkById($count, function ($results) use ($callback) { $this->hydratePivotRelation($results->all()); return $callback($results); }, $column, $alias); } /** * Execute a callback over each item while chunking. * * @param callable $callback * @param int $count * @return bool */ public function each(callable $callback, $count = 1000) { return $this->chunk($count, function ($results) use ($callback) { foreach ($results as $key => $value) { if ($callback($value, $key) === false) { return false; } } }); } /** * Get a lazy collection for the given query. * * @return \Illuminate\Support\LazyCollection */ public function cursor() { $this->query->addSelect($this->shouldSelect()); return $this->query->cursor()->map(function ($model) { $this->hydratePivotRelation([$model]); return $model; }); } /** * Hydrate the pivot table relationship on the models. * * @param array $models * @return void */ protected function hydratePivotRelation(array $models) { // To hydrate the pivot relationship, we will just gather the pivot attributes // and create a new Pivot model, which is basically a dynamic model that we // will set the attributes, table, and connections on it so it will work. foreach ($models as $model) { $model->setRelation($this->accessor, $this->newExistingPivot( $this->migratePivotAttributes($model) )); } } /** * Get the pivot attributes from a model. * * @param \Illuminate\Database\Eloquent\Model $model * @return array */ protected function migratePivotAttributes(Model $model) { $values = []; foreach ($model->getAttributes() as $key => $value) { // To get the pivots attributes we will just take any of the attributes which // begin with "pivot_" and add those to this arrays, as well as unsetting // them from the parent's models since they exist in a different table. if (strpos($key, 'pivot_') === 0) { $values[substr($key, 6)] = $value; unset($model->$key); } } return $values; } /** * If we're touching the parent model, touch. * * @return void */ public function touchIfTouching() { if ($this->touchingParent()) { $this->getParent()->touch(); } if ($this->getParent()->touches($this->relationName)) { $this->touch(); } } /** * Determine if we should touch the parent on sync. * * @return bool */ protected function touchingParent() { return $this->getRelated()->touches($this->guessInverseRelation()); } /** * Attempt to guess the name of the inverse of the relation. * * @return string */ protected function guessInverseRelation() { return Str::camel(Str::pluralStudly(class_basename($this->getParent()))); } /** * Touch all of the related models for the relationship. * * E.g.: Touch all roles associated with this user. * * @return void */ public function touch() { $key = $this->getRelated()->getKeyName(); $columns = [ $this->related->getUpdatedAtColumn() => $this->related->freshTimestampString(), ]; // If we actually have IDs for the relation, we will run the query to update all // the related model's timestamps, to make sure these all reflect the changes // to the parent models. This will help us keep any caching synced up here. if (count($ids = $this->allRelatedIds()) > 0) { $this->getRelated()->newQueryWithoutRelationships()->whereIn($key, $ids)->update($columns); } } /** * Get all of the IDs for the related models. * * @return \Illuminate\Support\Collection */ public function allRelatedIds() { return $this->newPivotQuery()->pluck($this->relatedPivotKey); } /** * Save a new model and attach it to the parent model. * * @param \Illuminate\Database\Eloquent\Model $model * @param array $pivotAttributes * @param bool $touch * @return \Illuminate\Database\Eloquent\Model */ public function save(Model $model, array $pivotAttributes = [], $touch = true) { $model->save(['touch' => false]); $this->attach($model, $pivotAttributes, $touch); return $model; } /** * Save an array of new models and attach them to the parent model. * * @param \Illuminate\Support\Collection|array $models * @param array $pivotAttributes * @return array */ public function saveMany($models, array $pivotAttributes = []) { foreach ($models as $key => $model) { $this->save($model, (array) ($pivotAttributes[$key] ?? []), false); } $this->touchIfTouching(); return $models; } /** * Create a new instance of the related model. * * @param array $attributes * @param array $joining * @param bool $touch * @return \Illuminate\Database\Eloquent\Model */ public function create(array $attributes = [], array $joining = [], $touch = true) { $instance = $this->related->newInstance($attributes); // Once we save the related model, we need to attach it to the base model via // through intermediate table so we'll use the existing "attach" method to // accomplish this which will insert the record and any more attributes. $instance->save(['touch' => false]); $this->attach($instance, $joining, $touch); return $instance; } /** * Create an array of new instances of the related models. * * @param iterable $records * @param array $joinings * @return array */ public function createMany(iterable $records, array $joinings = []) { $instances = []; foreach ($records as $key => $record) { $instances[] = $this->create($record, (array) ($joinings[$key] ?? []), false); } $this->touchIfTouching(); return $instances; } /** * Add the constraints for a relationship query. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Builder $parentQuery * @param array|mixed $columns * @return \Illuminate\Database\Eloquent\Builder */ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) { if ($parentQuery->getQuery()->from == $query->getQuery()->from) { return $this->getRelationExistenceQueryForSelfJoin($query, $parentQuery, $columns); } $this->performJoin($query); return parent::getRelationExistenceQuery($query, $parentQuery, $columns); } /** * Add the constraints for a relationship query on the same table. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Builder $parentQuery * @param array|mixed $columns * @return \Illuminate\Database\Eloquent\Builder */ public function getRelationExistenceQueryForSelfJoin(Builder $query, Builder $parentQuery, $columns = ['*']) { $query->select($columns); $query->from($this->related->getTable().' as '.$hash = $this->getRelationCountHash()); $this->related->setTable($hash); $this->performJoin($query); return parent::getRelationExistenceQuery($query, $parentQuery, $columns); } /** * Get the key for comparing against the parent key in "has" query. * * @return string */ public function getExistenceCompareKey() { return $this->getQualifiedForeignPivotKeyName(); } /** * Get a relationship join table hash. * * @return string */ public function getRelationCountHash() { return 'laravel_reserved_'.static::$selfJoinCount++; } /** * Specify that the pivot table has creation and update timestamps. * * @param mixed $createdAt * @param mixed $updatedAt * @return $this */ public function withTimestamps($createdAt = null, $updatedAt = null) { $this->withTimestamps = true; $this->pivotCreatedAt = $createdAt; $this->pivotUpdatedAt = $updatedAt; return $this->withPivot($this->createdAt(), $this->updatedAt()); } /** * Get the name of the "created at" column. * * @return string */ public function createdAt() { return $this->pivotCreatedAt ?: $this->parent->getCreatedAtColumn(); } /** * Get the name of the "updated at" column. * * @return string */ public function updatedAt() { return $this->pivotUpdatedAt ?: $this->parent->getUpdatedAtColumn(); } /** * Get the foreign key for the relation. * * @return string */ public function getForeignPivotKeyName() { return $this->foreignPivotKey; } /** * Get the fully qualified foreign key for the relation. * * @return string */ public function getQualifiedForeignPivotKeyName() { return $this->table.'.'.$this->foreignPivotKey; } /** * Get the "related key" for the relation. * * @return string */ public function getRelatedPivotKeyName() { return $this->relatedPivotKey; } /** * Get the fully qualified "related key" for the relation. * * @return string */ public function getQualifiedRelatedPivotKeyName() { return $this->table.'.'.$this->relatedPivotKey; } /** * Get the parent key for the relationship. * * @return string */ public function getParentKeyName() { return $this->parentKey; } /** * Get the fully qualified parent key name for the relation. * * @return string */ public function getQualifiedParentKeyName() { return $this->parent->qualifyColumn($this->parentKey); } /** * Get the related key for the relationship. * * @return string */ public function getRelatedKeyName() { return $this->relatedKey; } /** * Get the intermediate table for the relationship. * * @return string */ public function getTable() { return $this->table; } /** * Get the relationship name for the relationship. * * @return string */ public function getRelationName() { return $this->relationName; } /** * Get the name of the pivot accessor for this relationship. * * @return string */ public function getPivotAccessor() { return $this->accessor; } /** * Get the pivot columns for this relationship. * * @return array */ public function getPivotColumns() { return $this->pivotColumns; } }
{ "pile_set_name": "Github" }
<?php /** * CodeIgniter * * An open source application development framework for PHP 5.2.4 or newer * * NOTICE OF LICENSE * * Licensed under the Open Software License version 3.0 * * This source file is subject to the Open Software License (OSL 3.0) that is * bundled with this package in the files license.txt / license.rst. It is * also available through the world wide web at this URL: * http://opensource.org/licenses/OSL-3.0 * If you did not receive a copy of the license and are unable to obtain it * through the world wide web, please send an email to * [email protected] so we can send you a copy immediately. * * @package CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) * @link http://codeigniter.com * @since Version 1.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); if ( ! function_exists('xml_parser_create')) { show_error('Your PHP installation does not support XML'); } // ------------------------------------------------------------------------ /** * XML-RPC request handler class * * @package CodeIgniter * @subpackage Libraries * @category XML-RPC * @author EllisLab Dev Team * @link http://codeigniter.com/user_guide/libraries/xmlrpc.html */ class CI_Xmlrpc { /** * Debug flag * * @var bool */ public $debug = FALSE; /** * I4 data type * * @var string */ public $xmlrpcI4 = 'i4'; /** * Integer data type * * @var string */ public $xmlrpcInt = 'int'; /** * Boolean data type * * @var string */ public $xmlrpcBoolean = 'boolean'; /** * Double data type * * @var string */ public $xmlrpcDouble = 'double'; /** * String data type * * @var string */ public $xmlrpcString = 'string'; /** * DateTime format * * @var string */ public $xmlrpcDateTime = 'dateTime.iso8601'; /** * Base64 data type * * @var string */ public $xmlrpcBase64 = 'base64'; /** * Array data type * * @var string */ public $xmlrpcArray = 'array'; /** * Struct data type * * @var string */ public $xmlrpcStruct = 'struct'; /** * Data types list * * @var array */ public $xmlrpcTypes = array(); /** * Valid parents list * * @var array */ public $valid_parents = array(); /** * Response error numbers list * * @var array */ public $xmlrpcerr = array(); /** * Response error messages list * * @var string[] */ public $xmlrpcstr = array(); /** * Encoding charset * * @var string */ public $xmlrpc_defencoding = 'UTF-8'; /** * XML-RPC client name * * @var string */ public $xmlrpcName = 'XML-RPC for CodeIgniter'; /** * XML-RPC version * * @var string */ public $xmlrpcVersion = '1.1'; /** * Start of user errors * * @var int */ public $xmlrpcerruser = 800; /** * Start of XML parse errors * * @var int */ public $xmlrpcerrxml = 100; /** * Backslash replacement value * * @var string */ public $xmlrpc_backslash = ''; /** * XML-RPC Client object * * @var object */ public $client; /** * XML-RPC Method name * * @var string */ public $method; /** * XML-RPC Data * * @var array */ public $data; /** * XML-RPC Message * * @var string */ public $message = ''; /** * Request error message * * @var string */ public $error = ''; /** * XML-RPC result object * * @var object */ public $result; /** * XML-RPC Reponse * * @var array */ public $response = array(); // Response from remote server /** * XSS Filter flag * * @var bool */ public $xss_clean = TRUE; // -------------------------------------------------------------------- /** * Constructor * * Initializes property default values * * @param array $config * @return void */ public function __construct($config = array()) { $this->xmlrpc_backslash = chr(92).chr(92); // Types for info sent back and forth $this->xmlrpcTypes = array( $this->xmlrpcI4 => '1', $this->xmlrpcInt => '1', $this->xmlrpcBoolean => '1', $this->xmlrpcString => '1', $this->xmlrpcDouble => '1', $this->xmlrpcDateTime => '1', $this->xmlrpcBase64 => '1', $this->xmlrpcArray => '2', $this->xmlrpcStruct => '3' ); // Array of Valid Parents for Various XML-RPC elements $this->valid_parents = array('BOOLEAN' => array('VALUE'), 'I4' => array('VALUE'), 'INT' => array('VALUE'), 'STRING' => array('VALUE'), 'DOUBLE' => array('VALUE'), 'DATETIME.ISO8601' => array('VALUE'), 'BASE64' => array('VALUE'), 'ARRAY' => array('VALUE'), 'STRUCT' => array('VALUE'), 'PARAM' => array('PARAMS'), 'METHODNAME' => array('METHODCALL'), 'PARAMS' => array('METHODCALL', 'METHODRESPONSE'), 'MEMBER' => array('STRUCT'), 'NAME' => array('MEMBER'), 'DATA' => array('ARRAY'), 'FAULT' => array('METHODRESPONSE'), 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT') ); // XML-RPC Responses $this->xmlrpcerr['unknown_method'] = '1'; $this->xmlrpcstr['unknown_method'] = 'This is not a known method for this XML-RPC Server'; $this->xmlrpcerr['invalid_return'] = '2'; $this->xmlrpcstr['invalid_return'] = 'The XML data received was either invalid or not in the correct form for XML-RPC. Turn on debugging to examine the XML data further.'; $this->xmlrpcerr['incorrect_params'] = '3'; $this->xmlrpcstr['incorrect_params'] = 'Incorrect parameters were passed to method'; $this->xmlrpcerr['introspect_unknown'] = '4'; $this->xmlrpcstr['introspect_unknown'] = 'Cannot inspect signature for request: method unknown'; $this->xmlrpcerr['http_error'] = '5'; $this->xmlrpcstr['http_error'] = "Did not receive a '200 OK' response from remote server."; $this->xmlrpcerr['no_data'] = '6'; $this->xmlrpcstr['no_data'] = 'No data received from server.'; $this->initialize($config); log_message('debug', 'XML-RPC Class Initialized'); } // -------------------------------------------------------------------- /** * Initialize * * @param array $config * @return void */ public function initialize($config = array()) { if (count($config) > 0) { foreach ($config as $key => $val) { if (isset($this->$key)) { $this->$key = $val; } } } } // -------------------------------------------------------------------- /** * Parse server URL * * @param string $url * @param int $port * @param string $proxy * @param int $proxy_port * @return void */ public function server($url, $port = 80, $proxy = FALSE, $proxy_port = 8080) { if (strpos($url, 'http') !== 0) { $url = 'http://'.$url; } $parts = parse_url($url); if (isset($parts['user'], $parts['pass'])) { $parts['host'] = $parts['user'].':'.$parts['pass'].'@'.$parts['host']; } $path = isset($parts['path']) ? $parts['path'] : '/'; if ( ! empty($parts['query'])) { $path .= '?'.$parts['query']; } $this->client = new XML_RPC_Client($path, $parts['host'], $port, $proxy, $proxy_port); } // -------------------------------------------------------------------- /** * Set Timeout * * @param int $seconds * @return void */ public function timeout($seconds = 5) { if ($this->client !== NULL && is_int($seconds)) { $this->client->timeout = $seconds; } } // -------------------------------------------------------------------- /** * Set Methods * * @param string $function Method name * @return void */ public function method($function) { $this->method = $function; } // -------------------------------------------------------------------- /** * Take Array of Data and Create Objects * * @param array $incoming * @return void */ public function request($incoming) { if ( ! is_array($incoming)) { // Send Error return; } $this->data = array(); foreach ($incoming as $key => $value) { $this->data[$key] = $this->values_parsing($value); } } // -------------------------------------------------------------------- /** * Set Debug * * @param bool $flag * @return void */ public function set_debug($flag = TRUE) { $this->debug = ($flag === TRUE); } // -------------------------------------------------------------------- /** * Values Parsing * * @param mixed $value * @return object */ public function values_parsing($value) { if (is_array($value) && array_key_exists(0, $value)) { if ( ! isset($value[1], $this->xmlrpcTypes[$value[1]])) { $temp = new XML_RPC_Values($value[0], (is_array($value[0]) ? 'array' : 'string')); } else { if (is_array($value[0]) && ($value[1] === 'struct' OR $value[1] === 'array')) { while (list($k) = each($value[0])) { $value[0][$k] = $this->values_parsing($value[0][$k]); } } $temp = new XML_RPC_Values($value[0], $value[1]); } } else { $temp = new XML_RPC_Values($value, 'string'); } return $temp; } // -------------------------------------------------------------------- /** * Sends XML-RPC Request * * @return bool */ public function send_request() { $this->message = new XML_RPC_Message($this->method, $this->data); $this->message->debug = $this->debug; if ( ! $this->result = $this->client->send($this->message) OR ! is_object($this->result->val)) { $this->error = $this->result->errstr; return FALSE; } $this->response = $this->result->decode(); return TRUE; } // -------------------------------------------------------------------- /** * Returns Error * * @return string */ public function display_error() { return $this->error; } // -------------------------------------------------------------------- /** * Returns Remote Server Response * * @return string */ public function display_response() { return $this->response; } // -------------------------------------------------------------------- /** * Sends an Error Message for Server Request * * @param int $number * @param string $message * @return object */ public function send_error_message($number, $message) { return new XML_RPC_Response(0, $number, $message); } // -------------------------------------------------------------------- /** * Send Response for Server Request * * @param array $response * @return object */ public function send_response($response) { // $response should be array of values, which will be parsed // based on their data and type into a valid group of XML-RPC values return new XML_RPC_Response($this->values_parsing($response)); } } // END XML_RPC Class /** * XML-RPC Client class * * @category XML-RPC * @author EllisLab Dev Team * @link http://codeigniter.com/user_guide/libraries/xmlrpc.html */ class XML_RPC_Client extends CI_Xmlrpc { /** * Path * * @var string */ public $path = ''; /** * Server hostname * * @var string */ public $server = ''; /** * Server port * * @var int */ public $port = 80; /** * * Server username * * @var string */ public $username; /** * Server password * * @var string */ public $password; /** * Proxy hostname * * @var string */ public $proxy = FALSE; /** * Proxy port * * @var int */ public $proxy_port = 8080; /** * Error number * * @var string */ public $errno = ''; /** * Error message * * @var string */ public $errstring = ''; /** * Timeout in seconds * * @var int */ public $timeout = 5; /** * No Multicall flag * * @var bool */ public $no_multicall = FALSE; // -------------------------------------------------------------------- /** * Constructor * * @param string $path * @param object $server * @param int $port * @param string $proxy * @param int $proxy_port * @return void */ public function __construct($path, $server, $port = 80, $proxy = FALSE, $proxy_port = 8080) { parent::__construct(); $url = parse_url('http://'.$server); if (isset($url['user'], $url['pass'])) { $this->username = $url['user']; $this->password = $url['pass']; } $this->port = $port; $this->server = $url['host']; $this->path = $path; $this->proxy = $proxy; $this->proxy_port = $proxy_port; } // -------------------------------------------------------------------- /** * Send message * * @param mixed $msg * @return object */ public function send($msg) { if (is_array($msg)) { // Multi-call disabled return new XML_RPC_Response(0, $this->xmlrpcerr['multicall_recursion'], $this->xmlrpcstr['multicall_recursion']); } return $this->sendPayload($msg); } // -------------------------------------------------------------------- /** * Send payload * * @param object $msg * @return object */ public function sendPayload($msg) { if ($this->proxy === FALSE) { $server = $this->server; $port = $this->port; } else { $server = $this->proxy; $port = $this->proxy_port; } $fp = @fsockopen($server, $port, $this->errno, $this->errstring, $this->timeout); if ( ! is_resource($fp)) { error_log($this->xmlrpcstr['http_error']); return new XML_RPC_Response(0, $this->xmlrpcerr['http_error'], $this->xmlrpcstr['http_error']); } if (empty($msg->payload)) { // $msg = XML_RPC_Messages $msg->createPayload(); } $r = "\r\n"; $op = 'POST '.$this->path.' HTTP/1.0'.$r .'Host: '.$this->server.$r .'Content-Type: text/xml'.$r .(isset($this->username, $this->password) ? 'Authorization: Basic '.base64_encode($this->username.':'.$this->password).$r : '') .'User-Agent: '.$this->xmlrpcName.$r .'Content-Length: '.strlen($msg->payload).$r.$r .$msg->payload; for ($written = 0, $length = strlen($op); $written < $length; $written += $result) { if (($result = fwrite($fp, substr($op, $written))) === FALSE) { break; } } if ($result === FALSE) { error_log($this->xmlrpcstr['http_error']); return new XML_RPC_Response(0, $this->xmlrpcerr['http_error'], $this->xmlrpcstr['http_error']); } $resp = $msg->parseResponse($fp); fclose($fp); return $resp; } } // END XML_RPC_Client Class /** * XML-RPC Response class * * @category XML-RPC * @author EllisLab Dev Team * @link http://codeigniter.com/user_guide/libraries/xmlrpc.html */ class XML_RPC_Response { /** * Value * * @var mixed */ public $val = 0; /** * Error number * * @var int */ public $errno = 0; /** * Error message * * @var string */ public $errstr = ''; /** * Headers list * * @var array */ public $headers = array(); /** * XSS Filter flag * * @var bool */ public $xss_clean = TRUE; // -------------------------------------------------------------------- /** * Constructor * * @param mixed $val * @param int $code * @param string $fstr * @return void */ public function __construct($val, $code = 0, $fstr = '') { if ($code !== 0) { // error $this->errno = $code; $this->errstr = htmlspecialchars($fstr, (is_php('5.4') ? ENT_XML1 | ENT_NOQUOTES : ENT_NOQUOTES), 'UTF-8'); } elseif ( ! is_object($val)) { // programmer error, not an object error_log("Invalid type '".gettype($val)."' (value: ".$val.') passed to XML_RPC_Response. Defaulting to empty value.'); $this->val = new XML_RPC_Values(); } else { $this->val = $val; } } // -------------------------------------------------------------------- /** * Fault code * * @return int */ public function faultCode() { return $this->errno; } // -------------------------------------------------------------------- /** * Fault string * * @return string */ public function faultString() { return $this->errstr; } // -------------------------------------------------------------------- /** * Value * * @return mixed */ public function value() { return $this->val; } // -------------------------------------------------------------------- /** * Prepare response * * @return string xml */ public function prepare_response() { return "<methodResponse>\n" .($this->errno ? '<fault> <value> <struct> <member> <name>faultCode</name> <value><int>'.$this->errno.'</int></value> </member> <member> <name>faultString</name> <value><string>'.$this->errstr.'</string></value> </member> </struct> </value> </fault>' : "<params>\n<param>\n".$this->val->serialize_class()."</param>\n</params>") ."\n</methodResponse>"; } // -------------------------------------------------------------------- /** * Decode * * @param mixed $array * @return array */ public function decode($array = NULL) { $CI =& get_instance(); if (is_array($array)) { while (list($key) = each($array)) { if (is_array($array[$key])) { $array[$key] = $this->decode($array[$key]); } elseif ($this->xss_clean) { $array[$key] = $CI->security->xss_clean($array[$key]); } } return $array; } $result = $this->xmlrpc_decoder($this->val); if (is_array($result)) { $result = $this->decode($result); } elseif ($this->xss_clean) { $result = $CI->security->xss_clean($result); } return $result; } // -------------------------------------------------------------------- /** * XML-RPC Object to PHP Types * * @param object * @return array */ public function xmlrpc_decoder($xmlrpc_val) { $kind = $xmlrpc_val->kindOf(); if ($kind === 'scalar') { return $xmlrpc_val->scalarval(); } elseif ($kind === 'array') { reset($xmlrpc_val->me); $b = current($xmlrpc_val->me); $arr = array(); for ($i = 0, $size = count($b); $i < $size; $i++) { $arr[] = $this->xmlrpc_decoder($xmlrpc_val->me['array'][$i]); } return $arr; } elseif ($kind === 'struct') { reset($xmlrpc_val->me['struct']); $arr = array(); while (list($key,$value) = each($xmlrpc_val->me['struct'])) { $arr[$key] = $this->xmlrpc_decoder($value); } return $arr; } } // -------------------------------------------------------------------- /** * ISO-8601 time to server or UTC time * * @param string * @param bool * @return int unix timestamp */ public function iso8601_decode($time, $utc = FALSE) { // Return a time in the localtime, or UTC $t = 0; if (preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})/', $time, $regs)) { $fnc = ($utc === TRUE) ? 'gmmktime' : 'mktime'; $t = $fnc($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]); } return $t; } } // END XML_RPC_Response Class /** * XML-RPC Message class * * @category XML-RPC * @author EllisLab Dev Team * @link http://codeigniter.com/user_guide/libraries/xmlrpc.html */ class XML_RPC_Message extends CI_Xmlrpc { /** * Payload * * @var string */ public $payload; /** * Method name * * @var string */ public $method_name; /** * Parameter list * * @var array */ public $params = array(); /** * XH? * * @var array */ public $xh = array(); // -------------------------------------------------------------------- /** * Constructor * * @param string $method * @param array $pars * @return void */ public function __construct($method, $pars = FALSE) { parent::__construct(); $this->method_name = $method; if (is_array($pars) && count($pars) > 0) { for ($i = 0, $c = count($pars); $i < $c; $i++) { // $pars[$i] = XML_RPC_Values $this->params[] = $pars[$i]; } } } // -------------------------------------------------------------------- /** * Create Payload to Send * * @return void */ public function createPayload() { $this->payload = '<?xml version="1.0"?'.">\r\n<methodCall>\r\n" .'<methodName>'.$this->method_name."</methodName>\r\n" ."<params>\r\n"; for ($i = 0, $c = count($this->params); $i < $c; $i++) { // $p = XML_RPC_Values $p = $this->params[$i]; $this->payload .= "<param>\r\n".$p->serialize_class()."</param>\r\n"; } $this->payload .= "</params>\r\n</methodCall>\r\n"; } // -------------------------------------------------------------------- /** * Parse External XML-RPC Server's Response * * @param resource * @return object */ public function parseResponse($fp) { $data = ''; while ($datum = fread($fp, 4096)) { $data .= $datum; } // Display HTTP content for debugging if ($this->debug === TRUE) { echo "<pre>---DATA---\n".htmlspecialchars($data)."\n---END DATA---\n\n</pre>"; } // Check for data if ($data === '') { error_log($this->xmlrpcstr['no_data']); return new XML_RPC_Response(0, $this->xmlrpcerr['no_data'], $this->xmlrpcstr['no_data']); } // Check for HTTP 200 Response if (strpos($data, 'HTTP') === 0 && ! preg_match('/^HTTP\/[0-9\.]+ 200 /', $data)) { $errstr = substr($data, 0, strpos($data, "\n")-1); return new XML_RPC_Response(0, $this->xmlrpcerr['http_error'], $this->xmlrpcstr['http_error'].' ('.$errstr.')'); } //------------------------------------- // Create and Set Up XML Parser //------------------------------------- $parser = xml_parser_create($this->xmlrpc_defencoding); $pname = (string) $parser; $this->xh[$pname] = array( 'isf' => 0, 'ac' => '', 'headers' => array(), 'stack' => array(), 'valuestack' => array(), 'isf_reason' => 0 ); xml_set_object($parser, $this); xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, TRUE); xml_set_element_handler($parser, 'open_tag', 'closing_tag'); xml_set_character_data_handler($parser, 'character_data'); //xml_set_default_handler($parser, 'default_handler'); // Get headers $lines = explode("\r\n", $data); while (($line = array_shift($lines))) { if (strlen($line) < 1) { break; } $this->xh[$pname]['headers'][] = $line; } $data = implode("\r\n", $lines); // Parse XML data if ( ! xml_parse($parser, $data, count($data))) { $errstr = sprintf('XML error: %s at line %d', xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser)); $r = new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'], $this->xmlrpcstr['invalid_return']); xml_parser_free($parser); return $r; } xml_parser_free($parser); // Got ourselves some badness, it seems if ($this->xh[$pname]['isf'] > 1) { if ($this->debug === TRUE) { echo "---Invalid Return---\n".$this->xh[$pname]['isf_reason']."---Invalid Return---\n\n"; } return new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'], $this->xmlrpcstr['invalid_return'].' '.$this->xh[$pname]['isf_reason']); } elseif ( ! is_object($this->xh[$pname]['value'])) { return new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'], $this->xmlrpcstr['invalid_return'].' '.$this->xh[$pname]['isf_reason']); } // Display XML content for debugging if ($this->debug === TRUE) { echo '<pre>'; if (count($this->xh[$pname]['headers'] > 0)) { echo "---HEADERS---\n"; foreach ($this->xh[$pname]['headers'] as $header) { echo $header."\n"; } echo "---END HEADERS---\n\n"; } echo "---DATA---\n".htmlspecialchars($data)."\n---END DATA---\n\n---PARSED---\n"; var_dump($this->xh[$pname]['value']); echo "\n---END PARSED---</pre>"; } // Send response $v = $this->xh[$pname]['value']; if ($this->xh[$pname]['isf']) { $errno_v = $v->me['struct']['faultCode']; $errstr_v = $v->me['struct']['faultString']; $errno = $errno_v->scalarval(); if ($errno === 0) { // FAULT returned, errno needs to reflect that $errno = -1; } $r = new XML_RPC_Response($v, $errno, $errstr_v->scalarval()); } else { $r = new XML_RPC_Response($v); } $r->headers = $this->xh[$pname]['headers']; return $r; } // -------------------------------------------------------------------- // ------------------------------------ // Begin Return Message Parsing section // ------------------------------------ // quick explanation of components: // ac - used to accumulate values // isf - used to indicate a fault // lv - used to indicate "looking for a value": implements // the logic to allow values with no types to be strings // params - used to store parameters in method calls // method - used to store method name // stack - array with parent tree of the xml element, // used to validate the nesting of elements // -------------------------------------------------------------------- /** * Start Element Handler * * @param string * @param string * @return void */ public function open_tag($the_parser, $name) { $the_parser = (string) $the_parser; // If invalid nesting, then return if ($this->xh[$the_parser]['isf'] > 1) return; // Evaluate and check for correct nesting of XML elements if (count($this->xh[$the_parser]['stack']) === 0) { if ($name !== 'METHODRESPONSE' && $name !== 'METHODCALL') { $this->xh[$the_parser]['isf'] = 2; $this->xh[$the_parser]['isf_reason'] = 'Top level XML-RPC element is missing'; return; } } // not top level element: see if parent is OK elseif ( ! in_array($this->xh[$the_parser]['stack'][0], $this->valid_parents[$name], TRUE)) { $this->xh[$the_parser]['isf'] = 2; $this->xh[$the_parser]['isf_reason'] = 'XML-RPC element '.$name.' cannot be child of '.$this->xh[$the_parser]['stack'][0]; return; } switch ($name) { case 'STRUCT': case 'ARRAY': // Creates array for child elements $cur_val = array('value' => array(), 'type' => $name); array_unshift($this->xh[$the_parser]['valuestack'], $cur_val); break; case 'METHODNAME': case 'NAME': $this->xh[$the_parser]['ac'] = ''; break; case 'FAULT': $this->xh[$the_parser]['isf'] = 1; break; case 'PARAM': $this->xh[$the_parser]['value'] = NULL; break; case 'VALUE': $this->xh[$the_parser]['vt'] = 'value'; $this->xh[$the_parser]['ac'] = ''; $this->xh[$the_parser]['lv'] = 1; break; case 'I4': case 'INT': case 'STRING': case 'BOOLEAN': case 'DOUBLE': case 'DATETIME.ISO8601': case 'BASE64': if ($this->xh[$the_parser]['vt'] !== 'value') { //two data elements inside a value: an error occurred! $this->xh[$the_parser]['isf'] = 2; $this->xh[$the_parser]['isf_reason'] = 'There is a '.$name.' element following a ' .$this->xh[$the_parser]['vt'].' element inside a single value'; return; } $this->xh[$the_parser]['ac'] = ''; break; case 'MEMBER': // Set name of <member> to nothing to prevent errors later if no <name> is found $this->xh[$the_parser]['valuestack'][0]['name'] = ''; // Set NULL value to check to see if value passed for this param/member $this->xh[$the_parser]['value'] = NULL; break; case 'DATA': case 'METHODCALL': case 'METHODRESPONSE': case 'PARAMS': // valid elements that add little to processing break; default: /// An Invalid Element is Found, so we have trouble $this->xh[$the_parser]['isf'] = 2; $this->xh[$the_parser]['isf_reason'] = 'Invalid XML-RPC element found: '.$name; break; } // Add current element name to stack, to allow validation of nesting array_unshift($this->xh[$the_parser]['stack'], $name); $name === 'VALUE' OR $this->xh[$the_parser]['lv'] = 0; } // -------------------------------------------------------------------- /** * End Element Handler * * @param string * @param string * @return void */ public function closing_tag($the_parser, $name) { $the_parser = (string) $the_parser; if ($this->xh[$the_parser]['isf'] > 1) return; // Remove current element from stack and set variable // NOTE: If the XML validates, then we do not have to worry about // the opening and closing of elements. Nesting is checked on the opening // tag so we be safe there as well. $curr_elem = array_shift($this->xh[$the_parser]['stack']); switch ($name) { case 'STRUCT': case 'ARRAY': $cur_val = array_shift($this->xh[$the_parser]['valuestack']); $this->xh[$the_parser]['value'] = isset($cur_val['values']) ? $cur_val['values'] : array(); $this->xh[$the_parser]['vt'] = strtolower($name); break; case 'NAME': $this->xh[$the_parser]['valuestack'][0]['name'] = $this->xh[$the_parser]['ac']; break; case 'BOOLEAN': case 'I4': case 'INT': case 'STRING': case 'DOUBLE': case 'DATETIME.ISO8601': case 'BASE64': $this->xh[$the_parser]['vt'] = strtolower($name); if ($name === 'STRING') { $this->xh[$the_parser]['value'] = $this->xh[$the_parser]['ac']; } elseif ($name === 'DATETIME.ISO8601') { $this->xh[$the_parser]['vt'] = $this->xmlrpcDateTime; $this->xh[$the_parser]['value'] = $this->xh[$the_parser]['ac']; } elseif ($name === 'BASE64') { $this->xh[$the_parser]['value'] = base64_decode($this->xh[$the_parser]['ac']); } elseif ($name === 'BOOLEAN') { // Translated BOOLEAN values to TRUE AND FALSE $this->xh[$the_parser]['value'] = (bool) $this->xh[$the_parser]['ac']; } elseif ($name=='DOUBLE') { // we have a DOUBLE // we must check that only 0123456789-.<space> are characters here $this->xh[$the_parser]['value'] = preg_match('/^[+-]?[eE0-9\t \.]+$/', $this->xh[$the_parser]['ac']) ? (float) $this->xh[$the_parser]['ac'] : 'ERROR_NON_NUMERIC_FOUND'; } else { // we have an I4/INT // we must check that only 0123456789-<space> are characters here $this->xh[$the_parser]['value'] = preg_match('/^[+-]?[0-9\t ]+$/', $this->xh[$the_parser]['ac']) ? (int) $this->xh[$the_parser]['ac'] : 'ERROR_NON_NUMERIC_FOUND'; } $this->xh[$the_parser]['ac'] = ''; $this->xh[$the_parser]['lv'] = 3; // indicate we've found a value break; case 'VALUE': // This if() detects if no scalar was inside <VALUE></VALUE> if ($this->xh[$the_parser]['vt'] == 'value') { $this->xh[$the_parser]['value'] = $this->xh[$the_parser]['ac']; $this->xh[$the_parser]['vt'] = $this->xmlrpcString; } // build the XML-RPC value out of the data received, and substitute it $temp = new XML_RPC_Values($this->xh[$the_parser]['value'], $this->xh[$the_parser]['vt']); if (count($this->xh[$the_parser]['valuestack']) && $this->xh[$the_parser]['valuestack'][0]['type'] === 'ARRAY') { // Array $this->xh[$the_parser]['valuestack'][0]['values'][] = $temp; } else { // Struct $this->xh[$the_parser]['value'] = $temp; } break; case 'MEMBER': $this->xh[$the_parser]['ac'] = ''; // If value add to array in the stack for the last element built if ($this->xh[$the_parser]['value']) { $this->xh[$the_parser]['valuestack'][0]['values'][$this->xh[$the_parser]['valuestack'][0]['name']] = $this->xh[$the_parser]['value']; } break; case 'DATA': $this->xh[$the_parser]['ac'] = ''; break; case 'PARAM': if ($this->xh[$the_parser]['value']) { $this->xh[$the_parser]['params'][] = $this->xh[$the_parser]['value']; } break; case 'METHODNAME': $this->xh[$the_parser]['method'] = ltrim($this->xh[$the_parser]['ac']); break; case 'PARAMS': case 'FAULT': case 'METHODCALL': case 'METHORESPONSE': // We're all good kids with nuthin' to do break; default: // End of an Invalid Element. Taken care of during the opening tag though break; } } // -------------------------------------------------------------------- /** * Parse character data * * @param string * @param string * @return void */ public function character_data($the_parser, $data) { $the_parser = (string) $the_parser; if ($this->xh[$the_parser]['isf'] > 1) return; // XML Fault found already // If a value has not been found if ($this->xh[$the_parser]['lv'] !== 3) { if ($this->xh[$the_parser]['lv'] === 1) { $this->xh[$the_parser]['lv'] = 2; // Found a value } if ( ! isset($this->xh[$the_parser]['ac'])) { $this->xh[$the_parser]['ac'] = ''; } $this->xh[$the_parser]['ac'] .= $data; } } // -------------------------------------------------------------------- /** * Add parameter * * @param mixed * @return void */ public function addParam($par) { $this->params[] = $par; } // -------------------------------------------------------------------- /** * Output parameters * * @param array $array * @return array */ public function output_parameters(array $array = array()) { $CI =& get_instance(); if ( ! empty($array)) { while (list($key) = each($array)) { if (is_array($array[$key])) { $array[$key] = $this->output_parameters($array[$key]); } elseif ($key !== 'bits' && $this->xss_clean) { // 'bits' is for the MetaWeblog API image bits // @todo - this needs to be made more general purpose $array[$key] = $CI->security->xss_clean($array[$key]); } } return $array; } $parameters = array(); for ($i = 0, $c = count($this->params); $i < $c; $i++) { $a_param = $this->decode_message($this->params[$i]); if (is_array($a_param)) { $parameters[] = $this->output_parameters($a_param); } else { $parameters[] = ($this->xss_clean) ? $CI->security->xss_clean($a_param) : $a_param; } } return $parameters; } // -------------------------------------------------------------------- /** * Decode message * * @param object * @return mixed */ public function decode_message($param) { $kind = $param->kindOf(); if ($kind === 'scalar') { return $param->scalarval(); } elseif ($kind === 'array') { reset($param->me); $b = current($param->me); $arr = array(); for ($i = 0, $c = count($b); $i < $c; $i++) { $arr[] = $this->decode_message($param->me['array'][$i]); } return $arr; } elseif ($kind === 'struct') { reset($param->me['struct']); $arr = array(); while (list($key,$value) = each($param->me['struct'])) { $arr[$key] = $this->decode_message($value); } return $arr; } } } // END XML_RPC_Message Class /** * XML-RPC Values class * * @category XML-RPC * @author EllisLab Dev Team * @link http://codeigniter.com/user_guide/libraries/xmlrpc.html */ class XML_RPC_Values extends CI_Xmlrpc { /** * Value data * * @var array */ public $me = array(); /** * Value type * * @var int */ public $mytype = 0; // -------------------------------------------------------------------- /** * Constructor * * @param mixed $val * @param string $type * @return void */ public function __construct($val = -1, $type = '') { parent::__construct(); if ($val !== -1 OR $type !== '') { $type = $type === '' ? 'string' : $type; if ($this->xmlrpcTypes[$type] == 1) { $this->addScalar($val, $type); } elseif ($this->xmlrpcTypes[$type] == 2) { $this->addArray($val); } elseif ($this->xmlrpcTypes[$type] == 3) { $this->addStruct($val); } } } // -------------------------------------------------------------------- /** * Add scalar value * * @param scalar * @param string * @return int */ public function addScalar($val, $type = 'string') { $typeof = $this->xmlrpcTypes[$type]; if ($this->mytype === 1) { echo '<strong>XML_RPC_Values</strong>: scalar can have only one value<br />'; return 0; } if ($typeof != 1) { echo '<strong>XML_RPC_Values</strong>: not a scalar type (${typeof})<br />'; return 0; } if ($type === $this->xmlrpcBoolean) { $val = (int) (strcasecmp($val, 'true') === 0 OR $val === 1 OR ($val === TRUE && strcasecmp($val, 'false'))); } if ($this->mytype === 2) { // adding to an array here $ar = $this->me['array']; $ar[] = new XML_RPC_Values($val, $type); $this->me['array'] = $ar; } else { // a scalar, so set the value and remember we're scalar $this->me[$type] = $val; $this->mytype = $typeof; } return 1; } // -------------------------------------------------------------------- /** * Add array value * * @param array * @return int */ public function addArray($vals) { if ($this->mytype !== 0) { echo '<strong>XML_RPC_Values</strong>: already initialized as a ['.$this->kindOf().']<br />'; return 0; } $this->mytype = $this->xmlrpcTypes['array']; $this->me['array'] = $vals; return 1; } // -------------------------------------------------------------------- /** * Add struct value * * @param object * @return int */ public function addStruct($vals) { if ($this->mytype !== 0) { echo '<strong>XML_RPC_Values</strong>: already initialized as a ['.$this->kindOf().']<br />'; return 0; } $this->mytype = $this->xmlrpcTypes['struct']; $this->me['struct'] = $vals; return 1; } // -------------------------------------------------------------------- /** * Get value type * * @return string */ public function kindOf() { switch ($this->mytype) { case 3: return 'struct'; case 2: return 'array'; case 1: return 'scalar'; default: return 'undef'; } } // -------------------------------------------------------------------- /** * Serialize data * * @param string * @param mixed */ public function serializedata($typ, $val) { $rs = ''; switch ($this->xmlrpcTypes[$typ]) { case 3: // struct $rs .= "<struct>\n"; reset($val); while (list($key2, $val2) = each($val)) { $rs .= "<member>\n<name>{$key2}</name>\n".$this->serializeval($val2)."</member>\n"; } $rs .= '</struct>'; break; case 2: // array $rs .= "<array>\n<data>\n"; for ($i = 0, $c = count($val); $i < $c; $i++) { $rs .= $this->serializeval($val[$i]); } $rs .= "</data>\n</array>\n"; break; case 1: // others switch ($typ) { case $this->xmlrpcBase64: $rs .= '<'.$typ.'>'.base64_encode( (string) $val).'</'.$typ.">\n"; break; case $this->xmlrpcBoolean: $rs .= '<'.$typ.'>'.( (bool) $val ? '1' : '0').'</'.$typ.">\n"; break; case $this->xmlrpcString: $rs .= '<'.$typ.'>'.htmlspecialchars( (string) $val).'</'.$typ.">\n"; break; default: $rs .= '<'.$typ.'>'.$val.'</'.$typ.">\n"; break; } default: break; } return $rs; } // -------------------------------------------------------------------- /** * Serialize class * * @return string */ public function serialize_class() { return $this->serializeval($this); } // -------------------------------------------------------------------- /** * Serialize value * * @param object * @return string */ public function serializeval($o) { $ar = $o->me; reset($ar); list($typ, $val) = each($ar); return "<value>\n".$this->serializedata($typ, $val)."</value>\n"; } // -------------------------------------------------------------------- /** * Scalar value * * @return mixed */ public function scalarval() { reset($this->me); return current($this->me); } // -------------------------------------------------------------------- /** * Encode time in ISO-8601 form. * Useful for sending time in XML-RPC * * @param int unix timestamp * @param bool * @return string */ public function iso8601_encode($time, $utc = FALSE) { return ($utc) ? strftime('%Y%m%dT%H:%i:%s', $time) : gmstrftime('%Y%m%dT%H:%i:%s', $time); } } // END XML_RPC_Values Class /* End of file Xmlrpc.php */ /* Location: ./system/libraries/Xmlrpc.php */
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <meta charset='utf-8' /> <link href='../fullcalendar.css' rel='stylesheet' /> <link href='../fullcalendar.print.css' rel='stylesheet' media='print' /> <script src='../lib/moment.min.js'></script> <script src='../lib/jquery.min.js'></script> <script src='../fullcalendar.min.js'></script> <script> $(document).ready(function() { var currentTimezone = false; // load the list of available timezones $.getJSON('php/get-timezones.php', function(timezones) { $.each(timezones, function(i, timezone) { if (timezone != 'UTC') { // UTC is already in the list $('#timezone-selector').append($("<option/>").text(timezone).attr('value', timezone)); } }); }); // when the timezone selector changes, rerender the calendar $('#timezone-selector').on('change', function() { currentTimezone = this.value || false; $('#calendar').fullCalendar('destroy'); renderCalendar(); }); function renderCalendar() { $('#calendar').fullCalendar( { header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, defaultDate: '2015-02-12', timezone: currentTimezone, editable: true, eventLimit: true, // allow "more" link when too many events events: { url: 'php/get-events.php', error: function() { $('#script-warning').show(); } }, loading: function(bool) { $('#loading').toggle(bool); }, eventRender: function(event, el) { // render the timezone offset below the event title if (event.start.hasZone()) { el.find('.fc-title').after($('<div class="tzo"/>').text(event.start.format('Z'))); } } }); } renderCalendar(); }); </script> <style> body { margin: 0; padding: 0; font-family: "Lucida Grande", Helvetica, Arial, Verdana, sans-serif; font-size: 14px; } #top { background: #eee; border-bottom: 1px solid #ddd; padding: 0 10px; line-height: 40px; font-size: 12px; } .left { float: left } .right { float: right } .clear { clear: both } #script-warning, #loading { display: none } #script-warning { font-weight: bold; color: red } #calendar { max-width: 900px; margin: 40px auto; padding: 0 10px; } .tzo { color: #000; } </style> </head> <body> <div id='top'> <div class='left'> Timezone: <select id='timezone-selector'> <option value='' selected>none</option> <option value='local'>local</option> <option value='UTC'>UTC</option> </select> </div> <div class='right'> <span id='loading'>loading...</span> <span id='script-warning'><code>php/get-events.php</code> must be running.</span> </div> <div class='clear'></div> </div> <div id='calendar'></div> </body> </html>
{ "pile_set_name": "Github" }
/*! * commander * Copyright(c) 2011 TJ Holowaychuk <[email protected]> * MIT Licensed */ /** * Module dependencies. */ var EventEmitter = require('events').EventEmitter , spawn = require('child_process').spawn , keypress = require('keypress') , fs = require('fs') , exists = fs.existsSync , path = require('path') , tty = require('tty') , dirname = path.dirname , basename = path.basename; /** * Expose the root command. */ exports = module.exports = new Command; /** * Expose `Command`. */ exports.Command = Command; /** * Expose `Option`. */ exports.Option = Option; /** * Initialize a new `Option` with the given `flags` and `description`. * * @param {String} flags * @param {String} description * @api public */ function Option(flags, description) { this.flags = flags; this.required = ~flags.indexOf('<'); this.optional = ~flags.indexOf('['); this.bool = !~flags.indexOf('-no-'); flags = flags.split(/[ ,|]+/); if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift(); this.long = flags.shift(); this.description = description || ''; } /** * Return option name. * * @return {String} * @api private */ Option.prototype.name = function(){ return this.long .replace('--', '') .replace('no-', ''); }; /** * Check if `arg` matches the short or long flag. * * @param {String} arg * @return {Boolean} * @api private */ Option.prototype.is = function(arg){ return arg == this.short || arg == this.long; }; /** * Initialize a new `Command`. * * @param {String} name * @api public */ function Command(name) { this.commands = []; this.options = []; this._execs = []; this._args = []; this._name = name; } /** * Inherit from `EventEmitter.prototype`. */ Command.prototype.__proto__ = EventEmitter.prototype; /** * Add command `name`. * * The `.action()` callback is invoked when the * command `name` is specified via __ARGV__, * and the remaining arguments are applied to the * function for access. * * When the `name` is "*" an un-matched command * will be passed as the first arg, followed by * the rest of __ARGV__ remaining. * * Examples: * * program * .version('0.0.1') * .option('-C, --chdir <path>', 'change the working directory') * .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf') * .option('-T, --no-tests', 'ignore test hook') * * program * .command('setup') * .description('run remote setup commands') * .action(function(){ * console.log('setup'); * }); * * program * .command('exec <cmd>') * .description('run the given remote command') * .action(function(cmd){ * console.log('exec "%s"', cmd); * }); * * program * .command('*') * .description('deploy the given env') * .action(function(env){ * console.log('deploying "%s"', env); * }); * * program.parse(process.argv); * * @param {String} name * @param {String} [desc] * @return {Command} the new command * @api public */ Command.prototype.command = function(name, desc){ var args = name.split(/ +/); var cmd = new Command(args.shift()); if (desc) cmd.description(desc); if (desc) this.executables = true; if (desc) this._execs[cmd._name] = true; this.commands.push(cmd); cmd.parseExpectedArgs(args); cmd.parent = this; if (desc) return this; return cmd; }; /** * Add an implicit `help [cmd]` subcommand * which invokes `--help` for the given command. * * @api private */ Command.prototype.addImplicitHelpCommand = function() { this.command('help [cmd]', 'display help for [cmd]'); }; /** * Parse expected `args`. * * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. * * @param {Array} args * @return {Command} for chaining * @api public */ Command.prototype.parseExpectedArgs = function(args){ if (!args.length) return; var self = this; args.forEach(function(arg){ switch (arg[0]) { case '<': self._args.push({ required: true, name: arg.slice(1, -1) }); break; case '[': self._args.push({ required: false, name: arg.slice(1, -1) }); break; } }); return this; }; /** * Register callback `fn` for the command. * * Examples: * * program * .command('help') * .description('display verbose help') * .action(function(){ * // output help here * }); * * @param {Function} fn * @return {Command} for chaining * @api public */ Command.prototype.action = function(fn){ var self = this; this.parent.on(this._name, function(args, unknown){ // Parse any so-far unknown options unknown = unknown || []; var parsed = self.parseOptions(unknown); // Output help if necessary outputHelpIfNecessary(self, parsed.unknown); // If there are still any unknown options, then we simply // die, unless someone asked for help, in which case we give it // to them, and then we die. if (parsed.unknown.length > 0) { self.unknownOption(parsed.unknown[0]); } // Leftover arguments need to be pushed back. Fixes issue #56 if (parsed.args.length) args = parsed.args.concat(args); self._args.forEach(function(arg, i){ if (arg.required && null == args[i]) { self.missingArgument(arg.name); } }); // Always append ourselves to the end of the arguments, // to make sure we match the number of arguments the user // expects if (self._args.length) { args[self._args.length] = self; } else { args.push(self); } fn.apply(this, args); }); return this; }; /** * Define option with `flags`, `description` and optional * coercion `fn`. * * The `flags` string should contain both the short and long flags, * separated by comma, a pipe or space. The following are all valid * all will output this way when `--help` is used. * * "-p, --pepper" * "-p|--pepper" * "-p --pepper" * * Examples: * * // simple boolean defaulting to false * program.option('-p, --pepper', 'add pepper'); * * --pepper * program.pepper * // => Boolean * * // simple boolean defaulting to false * program.option('-C, --no-cheese', 'remove cheese'); * * program.cheese * // => true * * --no-cheese * program.cheese * // => true * * // required argument * program.option('-C, --chdir <path>', 'change the working directory'); * * --chdir /tmp * program.chdir * // => "/tmp" * * // optional argument * program.option('-c, --cheese [type]', 'add cheese [marble]'); * * @param {String} flags * @param {String} description * @param {Function|Mixed} fn or default * @param {Mixed} defaultValue * @return {Command} for chaining * @api public */ Command.prototype.option = function(flags, description, fn, defaultValue){ var self = this , option = new Option(flags, description) , oname = option.name() , name = camelcase(oname); // default as 3rd arg if ('function' != typeof fn) defaultValue = fn, fn = null; // preassign default value only for --no-*, [optional], or <required> if (false == option.bool || option.optional || option.required) { // when --no-* we make sure default is true if (false == option.bool) defaultValue = true; // preassign only if we have a default if (undefined !== defaultValue) self[name] = defaultValue; } // register the option this.options.push(option); // when it's passed assign the value // and conditionally invoke the callback this.on(oname, function(val){ // coercion if (null != val && fn) val = fn(val); // unassigned or bool if ('boolean' == typeof self[name] || 'undefined' == typeof self[name]) { // if no value, bool true, and we have a default, then use it! if (null == val) { self[name] = option.bool ? defaultValue || true : false; } else { self[name] = val; } } else if (null !== val) { // reassign self[name] = val; } }); return this; }; /** * Parse `argv`, settings options and invoking commands when defined. * * @param {Array} argv * @return {Command} for chaining * @api public */ Command.prototype.parse = function(argv){ // implicit help if (this.executables) this.addImplicitHelpCommand(); // store raw args this.rawArgs = argv; // guess name this._name = this._name || basename(argv[1]); // process argv var parsed = this.parseOptions(this.normalize(argv.slice(2))); var args = this.args = parsed.args; var result = this.parseArgs(this.args, parsed.unknown); // executable sub-commands var name = result.args[0]; if (this._execs[name]) return this.executeSubCommand(argv, args, parsed.unknown); return result; }; /** * Execute a sub-command executable. * * @param {Array} argv * @param {Array} args * @param {Array} unknown * @api private */ Command.prototype.executeSubCommand = function(argv, args, unknown) { args = args.concat(unknown); if (!args.length) this.help(); if ('help' == args[0] && 1 == args.length) this.help(); // <cmd> --help if ('help' == args[0]) { args[0] = args[1]; args[1] = '--help'; } // executable var dir = dirname(argv[1]); var bin = basename(argv[1]) + '-' + args[0]; // check for ./<bin> first var local = path.join(dir, bin); // run it args = args.slice(1); var proc = spawn(local, args, { stdio: 'inherit', customFds: [0, 1, 2] }); proc.on('error', function(err){ if (err.code == "ENOENT") { console.error('\n %s(1) does not exist, try --help\n', bin); } else if (err.code == "EACCES") { console.error('\n %s(1) not executable. try chmod or run with root\n', bin); } }); this.runningCommand = proc; }; /** * Normalize `args`, splitting joined short flags. For example * the arg "-abc" is equivalent to "-a -b -c". * This also normalizes equal sign and splits "--abc=def" into "--abc def". * * @param {Array} args * @return {Array} * @api private */ Command.prototype.normalize = function(args){ var ret = [] , arg , index; for (var i = 0, len = args.length; i < len; ++i) { arg = args[i]; if (arg.length > 1 && '-' == arg[0] && '-' != arg[1]) { arg.slice(1).split('').forEach(function(c){ ret.push('-' + c); }); } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) { ret.push(arg.slice(0, index), arg.slice(index + 1)); } else { ret.push(arg); } } return ret; }; /** * Parse command `args`. * * When listener(s) are available those * callbacks are invoked, otherwise the "*" * event is emitted and those actions are invoked. * * @param {Array} args * @return {Command} for chaining * @api private */ Command.prototype.parseArgs = function(args, unknown){ var cmds = this.commands , len = cmds.length , name; if (args.length) { name = args[0]; if (this.listeners(name).length) { this.emit(args.shift(), args, unknown); } else { this.emit('*', args); } } else { outputHelpIfNecessary(this, unknown); // If there were no args and we have unknown options, // then they are extraneous and we need to error. if (unknown.length > 0) { this.unknownOption(unknown[0]); } } return this; }; /** * Return an option matching `arg` if any. * * @param {String} arg * @return {Option} * @api private */ Command.prototype.optionFor = function(arg){ for (var i = 0, len = this.options.length; i < len; ++i) { if (this.options[i].is(arg)) { return this.options[i]; } } }; /** * Parse options from `argv` returning `argv` * void of these options. * * @param {Array} argv * @return {Array} * @api public */ Command.prototype.parseOptions = function(argv){ var args = [] , len = argv.length , literal , option , arg; var unknownOptions = []; // parse options for (var i = 0; i < len; ++i) { arg = argv[i]; // literal args after -- if ('--' == arg) { literal = true; continue; } if (literal) { args.push(arg); continue; } // find matching Option option = this.optionFor(arg); // option is defined if (option) { // requires arg if (option.required) { arg = argv[++i]; if (null == arg) return this.optionMissingArgument(option); if ('-' == arg[0] && '-' != arg) return this.optionMissingArgument(option, arg); this.emit(option.name(), arg); // optional arg } else if (option.optional) { arg = argv[i+1]; if (null == arg || ('-' == arg[0] && '-' != arg)) { arg = null; } else { ++i; } this.emit(option.name(), arg); // bool } else { this.emit(option.name()); } continue; } // looks like an option if (arg.length > 1 && '-' == arg[0]) { unknownOptions.push(arg); // If the next argument looks like it might be // an argument for this option, we pass it on. // If it isn't, then it'll simply be ignored if (argv[i+1] && '-' != argv[i+1][0]) { unknownOptions.push(argv[++i]); } continue; } // arg args.push(arg); } return { args: args, unknown: unknownOptions }; }; /** * Argument `name` is missing. * * @param {String} name * @api private */ Command.prototype.missingArgument = function(name){ console.error(); console.error(" error: missing required argument `%s'", name); console.error(); process.exit(1); }; /** * `Option` is missing an argument, but received `flag` or nothing. * * @param {String} option * @param {String} flag * @api private */ Command.prototype.optionMissingArgument = function(option, flag){ console.error(); if (flag) { console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag); } else { console.error(" error: option `%s' argument missing", option.flags); } console.error(); process.exit(1); }; /** * Unknown option `flag`. * * @param {String} flag * @api private */ Command.prototype.unknownOption = function(flag){ console.error(); console.error(" error: unknown option `%s'", flag); console.error(); process.exit(1); }; /** * Set the program version to `str`. * * This method auto-registers the "-V, --version" flag * which will print the version number when passed. * * @param {String} str * @param {String} flags * @return {Command} for chaining * @api public */ Command.prototype.version = function(str, flags){ if (0 == arguments.length) return this._version; this._version = str; flags = flags || '-V, --version'; this.option(flags, 'output the version number'); this.on('version', function(){ console.log(str); process.exit(0); }); return this; }; /** * Set the description `str`. * * @param {String} str * @return {String|Command} * @api public */ Command.prototype.description = function(str){ if (0 == arguments.length) return this._description; this._description = str; return this; }; /** * Set / get the command usage `str`. * * @param {String} str * @return {String|Command} * @api public */ Command.prototype.usage = function(str){ var args = this._args.map(function(arg){ return arg.required ? '<' + arg.name + '>' : '[' + arg.name + ']'; }); var usage = '[options' + (this.commands.length ? '] [command' : '') + ']' + (this._args.length ? ' ' + args : ''); if (0 == arguments.length) return this._usage || usage; this._usage = str; return this; }; /** * Return the largest option length. * * @return {Number} * @api private */ Command.prototype.largestOptionLength = function(){ return this.options.reduce(function(max, option){ return Math.max(max, option.flags.length); }, 0); }; /** * Return help for options. * * @return {String} * @api private */ Command.prototype.optionHelp = function(){ var width = this.largestOptionLength(); // Prepend the help information return [pad('-h, --help', width) + ' ' + 'output usage information'] .concat(this.options.map(function(option){ return pad(option.flags, width) + ' ' + option.description; })) .join('\n'); }; /** * Return command help documentation. * * @return {String} * @api private */ Command.prototype.commandHelp = function(){ if (!this.commands.length) return ''; return [ '' , ' Commands:' , '' , this.commands.map(function(cmd){ var args = cmd._args.map(function(arg){ return arg.required ? '<' + arg.name + '>' : '[' + arg.name + ']'; }).join(' '); return pad(cmd._name + (cmd.options.length ? ' [options]' : '') + ' ' + args, 22) + (cmd.description() ? ' ' + cmd.description() : ''); }).join('\n').replace(/^/gm, ' ') , '' ].join('\n'); }; /** * Return program help documentation. * * @return {String} * @api private */ Command.prototype.helpInformation = function(){ return [ '' , ' Usage: ' + this._name + ' ' + this.usage() , '' + this.commandHelp() , ' Options:' , '' , '' + this.optionHelp().replace(/^/gm, ' ') , '' , '' ].join('\n'); }; /** * Prompt for a `Number`. * * @param {String} str * @param {Function} fn * @api private */ Command.prototype.promptForNumber = function(str, fn){ var self = this; this.promptSingleLine(str, function parseNumber(val){ val = Number(val); if (isNaN(val)) return self.promptSingleLine(str + '(must be a number) ', parseNumber); fn(val); }); }; /** * Prompt for a `Date`. * * @param {String} str * @param {Function} fn * @api private */ Command.prototype.promptForDate = function(str, fn){ var self = this; this.promptSingleLine(str, function parseDate(val){ val = new Date(val); if (isNaN(val.getTime())) return self.promptSingleLine(str + '(must be a date) ', parseDate); fn(val); }); }; /** * Prompt for a `Regular Expression`. * * @param {String} str * @param {Object} pattern regular expression object to test * @param {Function} fn * @api private */ Command.prototype.promptForRegexp = function(str, pattern, fn){ var self = this; this.promptSingleLine(str, function parseRegexp(val){ if(!pattern.test(val)) return self.promptSingleLine(str + '(regular expression mismatch) ', parseRegexp); fn(val); }); }; /** * Single-line prompt. * * @param {String} str * @param {Function} fn * @api private */ Command.prototype.promptSingleLine = function(str, fn){ // determine if the 2nd argument is a regular expression if (arguments[1].global !== undefined && arguments[1].multiline !== undefined) { return this.promptForRegexp(str, arguments[1], arguments[2]); } else if ('function' == typeof arguments[2]) { return this['promptFor' + (fn.name || fn)](str, arguments[2]); } process.stdout.write(str); process.stdin.setEncoding('utf8'); process.stdin.once('data', function(val){ fn(val.trim()); }).resume(); }; /** * Multi-line prompt. * * @param {String} str * @param {Function} fn * @api private */ Command.prototype.promptMultiLine = function(str, fn){ var buf = []; console.log(str); process.stdin.setEncoding('utf8'); process.stdin.on('data', function(val){ if ('\n' == val || '\r\n' == val) { process.stdin.removeAllListeners('data'); fn(buf.join('\n')); } else { buf.push(val.trimRight()); } }).resume(); }; /** * Prompt `str` and callback `fn(val)` * * Commander supports single-line and multi-line prompts. * To issue a single-line prompt simply add white-space * to the end of `str`, something like "name: ", whereas * for a multi-line prompt omit this "description:". * * * Examples: * * program.prompt('Username: ', function(name){ * console.log('hi %s', name); * }); * * program.prompt('Description:', function(desc){ * console.log('description was "%s"', desc.trim()); * }); * * @param {String|Object} str * @param {Function} fn * @api public */ Command.prototype.prompt = function(str, fn){ var self = this; if ('string' == typeof str) { if (/ $/.test(str)) return this.promptSingleLine.apply(this, arguments); this.promptMultiLine(str, fn); } else { var keys = Object.keys(str) , obj = {}; function next() { var key = keys.shift() , label = str[key]; if (!key) return fn(obj); self.prompt(label, function(val){ obj[key] = val; next(); }); } next(); } }; /** * Prompt for password with `str`, `mask` char and callback `fn(val)`. * * The mask string defaults to '', aka no output is * written while typing, you may want to use "*" etc. * * Examples: * * program.password('Password: ', function(pass){ * console.log('got "%s"', pass); * process.stdin.destroy(); * }); * * program.password('Password: ', '*', function(pass){ * console.log('got "%s"', pass); * process.stdin.destroy(); * }); * * @param {String} str * @param {String} mask * @param {Function} fn * @api public */ Command.prototype.password = function(str, mask, fn){ var self = this , buf = ''; // default mask if ('function' == typeof mask) { fn = mask; mask = ''; } keypress(process.stdin); function setRawMode(mode) { if (process.stdin.setRawMode) { process.stdin.setRawMode(mode); } else { tty.setRawMode(mode); } }; setRawMode(true); process.stdout.write(str); // keypress process.stdin.on('keypress', function(c, key){ if (key && 'enter' == key.name) { console.log(); process.stdin.pause(); process.stdin.removeAllListeners('keypress'); setRawMode(false); if (!buf.trim().length) return self.password(str, mask, fn); fn(buf); return; } if (key && key.ctrl && 'c' == key.name) { console.log('%s', buf); process.exit(); } process.stdout.write(mask); buf += c; }).resume(); }; /** * Confirmation prompt with `str` and callback `fn(bool)` * * Examples: * * program.confirm('continue? ', function(ok){ * console.log(' got %j', ok); * process.stdin.destroy(); * }); * * @param {String} str * @param {Function} fn * @api public */ Command.prototype.confirm = function(str, fn, verbose){ var self = this; this.prompt(str, function(ok){ if (!ok.trim()) { if (!verbose) str += '(yes or no) '; return self.confirm(str, fn, true); } fn(parseBool(ok)); }); }; /** * Choice prompt with `list` of items and callback `fn(index, item)` * * Examples: * * var list = ['tobi', 'loki', 'jane', 'manny', 'luna']; * * console.log('Choose the coolest pet:'); * program.choose(list, function(i){ * console.log('you chose %d "%s"', i, list[i]); * process.stdin.destroy(); * }); * * @param {Array} list * @param {Number|Function} index or fn * @param {Function} fn * @api public */ Command.prototype.choose = function(list, index, fn){ var self = this , hasDefault = 'number' == typeof index; if (!hasDefault) { fn = index; index = null; } list.forEach(function(item, i){ if (hasDefault && i == index) { console.log('* %d) %s', i + 1, item); } else { console.log(' %d) %s', i + 1, item); } }); function again() { self.prompt(' : ', function(val){ val = parseInt(val, 10) - 1; if (hasDefault && isNaN(val)) val = index; if (null == list[val]) { again(); } else { fn(val, list[val]); } }); } again(); }; /** * Output help information for this command * * @api public */ Command.prototype.outputHelp = function(){ process.stdout.write(this.helpInformation()); this.emit('--help'); }; /** * Output help information and exit. * * @api public */ Command.prototype.help = function(){ this.outputHelp(); process.exit(); }; /** * Camel-case the given `flag` * * @param {String} flag * @return {String} * @api private */ function camelcase(flag) { return flag.split('-').reduce(function(str, word){ return str + word[0].toUpperCase() + word.slice(1); }); } /** * Parse a boolean `str`. * * @param {String} str * @return {Boolean} * @api private */ function parseBool(str) { return /^y|yes|ok|true$/i.test(str); } /** * Pad `str` to `width`. * * @param {String} str * @param {Number} width * @return {String} * @api private */ function pad(str, width) { var len = Math.max(0, width - str.length); return str + Array(len + 1).join(' '); } /** * Output help information if necessary * * @param {Command} command to output help for * @param {Array} array of options to search for -h or --help * @api private */ function outputHelpIfNecessary(cmd, options) { options = options || []; for (var i = 0; i < options.length; i++) { if (options[i] == '--help' || options[i] == '-h') { cmd.outputHelp(); process.exit(0); } } }
{ "pile_set_name": "Github" }
H 11 // 0.000000 0x0 // 0.000000 0x0 // 0.000000 0x0 // 0.000000 0x0 // -0.007748 0x9fef // -0.005384 0x9d83 // 0.018774 0x24ce // -0.004330 0x9c6f // -0.023351 0xa5fa // -0.015517 0xa3f2 // -0.029153 0xa777
{ "pile_set_name": "Github" }
var str1 = "abc"; var str2 = "abc"; var str3 = "abd"; writeln(str1, " == ", str2, " => ", (str1 == str2)); writeln(str1, " == ", str3, " => ", (str1 == str3)); writeln(str1, " != ", str2, " => ", (str1 != str2)); writeln(str1, " != ", str3, " => ", (str1 != str3)); writeln(str1, " <= ", str2, " => ", (str1 <= str2)); writeln(str1, " <= ", str3, " => ", (str1 <= str3)); writeln(str1, " < ", str2, " => ", (str1 < str2)); writeln(str1, " < ", str3, " => ", (str1 < str3)); writeln(str1, " >= ", str2, " => ", (str1 >= str2)); writeln(str1, " >= ", str3, " => ", (str1 >= str3)); writeln(str1, " > ", str2, " => ", (str1 > str2)); writeln(str1, " > ", str3, " => ", (str1 > str3));
{ "pile_set_name": "Github" }
/* *********************************************************************************************************************** * * Copyright (c) 2018-2020 Advanced Micro Devices, Inc. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * **********************************************************************************************************************/ #pragma once #include "core/fence.h" #include "core/os/amdgpu/amdgpuDevice.h" #include "core/os/amdgpu/amdgpuQueue.h" #include <climits> namespace Pal { namespace Amdgpu { class Device; class Platform; class SubmissionContext; // ===================================================================================================================== // Represents a command buffer SyncobjFence the client can use for coarse-level synchronization between GPU and CPU. // // SyncObjFences is implemented on Sync Object. Instead using timestamp to reference the underlying dma-fence, // Sync Object contains the pointer to the fence. Beyond the ordinary fence wait operation, Fence import/export // are supported with sync object. class SyncobjFence : public Fence { public: SyncobjFence(const Device& device); ~SyncobjFence(); virtual Result Init( const FenceCreateInfo& createInfo) override; virtual Result OpenHandle( const FenceOpenInfo& openInfo) override; virtual OsExternalHandle ExportExternalHandle( const FenceExportInfo& exportInfo) const override; virtual Result WaitForFences( const Pal::Device& device, uint32 fenceCount, const Pal::Fence*const* ppFenceList, bool waitAll, uint64 timeout) const override; virtual void AssociateWithContext(Pal::SubmissionContext* pContext) override; virtual Result Reset() override; virtual Result GetStatus() const override; amdgpu_syncobj_handle SyncObjHandle() const { return m_fenceSyncObject; } private: bool IsSyncobjSignaled( amdgpu_syncobj_handle syncObj) const; amdgpu_syncobj_handle m_fenceSyncObject; const Device& m_device; PAL_DISALLOW_COPY_AND_ASSIGN(SyncobjFence); }; } // Amdgpu } // Pal
{ "pile_set_name": "Github" }
syntax = "proto3"; package external; // Type that belongs to a non-envoy package. // // Part of a test suite that verifies normalization of // fully-qualified type names. message PackageLevelType { }
{ "pile_set_name": "Github" }
--- - name: Install gitlab server hosts: all become: yes vars: # host entries won't work in docker # see https://stackoverflow.com/questions/28327458/how-to-add-my-containers-hostname-to-etc-hosts add_host_entries: true roles: - common - gitlab
{ "pile_set_name": "Github" }
/** * Original code: automated SDL platform test written by Edgar Simo "bobbens" * Extended and updated by aschiffler at ferzkopp dot net */ #include <stdio.h> #include <SDL/SDL.h> #include "../../include/SDL_test.h" /* Test cases */ static const TestCaseReference test1 = (TestCaseReference){ "platform_testTypes", "Tests predefined types", TEST_ENABLED, 0, 0 }; static const TestCaseReference test2 = (TestCaseReference){ "platform_testEndianessAndSwap", "Tests endianess and swap functions", TEST_ENABLED, 0, 0 }; static const TestCaseReference test3 = (TestCaseReference){ "platform_testGetFunctions", "Tests various SDL_GetXYZ functions", TEST_ENABLED, 0, 0 }; static const TestCaseReference test4 = (TestCaseReference){ "platform_testHasFunctions", "Tests various SDL_HasXYZ functions", TEST_ENABLED, 0, 0 }; static const TestCaseReference test5 = (TestCaseReference){ "platform_testGetVersion", "Tests SDL_GetVersion function", TEST_ENABLED, 0, 0 }; static const TestCaseReference test6 = (TestCaseReference){ "platform_testSDLVersion", "Tests SDL_VERSION macro", TEST_ENABLED, 0, 0 }; static const TestCaseReference test7 = (TestCaseReference){ "platform_testDefaultInit", "Tests default SDL_Init", TEST_ENABLED, 0, 0 }; static const TestCaseReference test8 = (TestCaseReference){ "platform_testGetSetClearError", "Tests SDL_Get/Set/ClearError", TEST_ENABLED, 0, 0 }; static const TestCaseReference test9 = (TestCaseReference){ "platform_testSetErrorEmptyInput", "Tests SDL_SetError with empty input", TEST_ENABLED, 0, 0 }; static const TestCaseReference test10 = (TestCaseReference){ "platform_testSetErrorInvalidInput", "Tests SDL_SetError with invalid input", TEST_ENABLED, 0, 0 }; static const TestCaseReference test11 = (TestCaseReference){ "platform_testGetPowerInfo", "Tests SDL_GetPowerInfo function", TEST_ENABLED, 0, 0 }; /* Test suite */ extern const TestCaseReference *testSuite[] = { &test1, &test2, &test3, &test4, &test5, &test6, &test7, &test8, &test9, &test10, &test11, NULL }; TestCaseReference **QueryTestSuite() { return (TestCaseReference **)testSuite; } /** * @brief Compare sizes of types. * * @note Watcom C flags these as Warning 201: "Unreachable code" if you just * compare them directly, so we push it through a function to keep the * compiler quiet. --ryan. */ static int _compareSizeOfType( size_t sizeoftype, size_t hardcodetype ) { return sizeoftype != hardcodetype; } /** * @brief Tests type sizes. */ int platform_testTypes(void *arg) { int ret; ret = _compareSizeOfType( sizeof(Uint8), 1 ); AssertTrue( ret == 0, "sizeof(Uint8) = %lu, expected 1", sizeof(Uint8) ); ret = _compareSizeOfType( sizeof(Uint16), 2 ); AssertTrue( ret == 0, "sizeof(Uint16) = %lu, expected 2", sizeof(Uint16) ); ret = _compareSizeOfType( sizeof(Uint32), 4 ); AssertTrue( ret == 0, "sizeof(Uint32) = %lu, expected 4", sizeof(Uint32) ); ret = _compareSizeOfType( sizeof(Uint64), 8 ); AssertTrue( ret == 0, "sizeof(Uint64) = %lu, expected 8", sizeof(Uint64) ); } /** * @brief Tests platform endianness and SDL_SwapXY functions. */ int platform_testEndianessAndSwap(void *arg) { int real_byteorder; Uint16 value = 0x1234; Uint16 value16 = 0xCDAB; Uint16 swapped16 = 0xABCD; Uint32 value32 = 0xEFBEADDE; Uint32 swapped32 = 0xDEADBEEF; Uint64 value64, swapped64; value64 = 0xEFBEADDE; value64 <<= 32; value64 |= 0xCDAB3412; swapped64 = 0x1234ABCD; swapped64 <<= 32; swapped64 |= 0xDEADBEEF; if ((*((char *) &value) >> 4) == 0x1) { real_byteorder = SDL_BIG_ENDIAN; } else { real_byteorder = SDL_LIL_ENDIAN; } /* Test endianness. */ AssertTrue( real_byteorder == SDL_BYTEORDER, "Machine detected as %s endian, appears to be %s endian.", (SDL_BYTEORDER == SDL_LIL_ENDIAN) ? "little" : "big", (real_byteorder == SDL_LIL_ENDIAN) ? "little" : "big" ); /* Test 16 swap. */ AssertTrue( SDL_Swap16(value16) == swapped16, "SDL_Swap16(): 16 bit swapped: 0x%X => 0x%X", value16, SDL_Swap16(value16) ); /* Test 32 swap. */ AssertTrue( SDL_Swap32(value32) == swapped32, "SDL_Swap32(): 32 bit swapped: 0x%X => 0x%X", value32, SDL_Swap32(value32) ); /* Test 64 swap. */ AssertTrue( SDL_Swap64(value64) == swapped64, #ifdef _MSC_VER "SDL_Swap64(): 64 bit swapped: 0x%I64X => 0x%I64X", #else "SDL_Swap64(): 64 bit swapped: 0x%llX => 0x%llX", #endif value64, SDL_Swap64(value64) ); } /*! * \brief Tests SDL_GetXYZ() functions * \sa * http://wiki.libsdl.org/moin.cgi/SDL_GetPlatform * http://wiki.libsdl.org/moin.cgi/SDL_GetCPUCount * http://wiki.libsdl.org/moin.cgi/SDL_GetCPUCacheLineSize * http://wiki.libsdl.org/moin.cgi/SDL_GetRevision * http://wiki.libsdl.org/moin.cgi/SDL_GetRevisionNumber */ int platform_testGetFunctions (void *arg) { char *platform; char *revision; int ret; int len; platform = (char *)SDL_GetPlatform(); AssertPass("SDL_GetPlatform()"); AssertTrue(platform != NULL, "SDL_GetPlatform() != NULL"); if (platform != NULL) { len = strlen(platform); AssertTrue(len > 0, "SDL_GetPlatform(): expected non-empty platform, was platform: '%s', len: %i", platform, len); } ret = SDL_GetCPUCount(); AssertPass("SDL_GetCPUCount()"); AssertTrue(ret > 0, "SDL_GetCPUCount(): expected count > 0, was: %i", ret); ret = SDL_GetCPUCacheLineSize(); AssertPass("SDL_GetCPUCacheLineSize()"); AssertTrue(ret >= 0, "SDL_GetCPUCacheLineSize(): expected size >= 0, was: %i", ret); revision = (char *)SDL_GetRevision(); AssertPass("SDL_GetRevision()"); AssertTrue(revision != NULL, "SDL_GetRevision() != NULL"); ret = SDL_GetRevisionNumber(); AssertPass("SDL_GetRevisionNumber()"); } /*! * \brief Tests SDL_HasXYZ() functions * \sa * http://wiki.libsdl.org/moin.cgi/SDL_Has3DNow * http://wiki.libsdl.org/moin.cgi/SDL_HasAltiVec * http://wiki.libsdl.org/moin.cgi/SDL_HasMMX * http://wiki.libsdl.org/moin.cgi/SDL_HasRDTSC * http://wiki.libsdl.org/moin.cgi/SDL_HasSSE * http://wiki.libsdl.org/moin.cgi/SDL_HasSSE2 * http://wiki.libsdl.org/moin.cgi/SDL_HasSSE3 * http://wiki.libsdl.org/moin.cgi/SDL_HasSSE41 * http://wiki.libsdl.org/moin.cgi/SDL_HasSSE42 */ int platform_testHasFunctions (void *arg) { int ret; // TODO: independently determine and compare values as well ret = SDL_HasRDTSC(); AssertPass("SDL_HasRDTSC()"); ret = SDL_HasAltiVec(); AssertPass("SDL_HasAltiVec()"); ret = SDL_HasMMX(); AssertPass("SDL_HasMMX()"); ret = SDL_Has3DNow(); AssertPass("SDL_Has3DNow()"); ret = SDL_HasSSE(); AssertPass("SDL_HasSSE()"); ret = SDL_HasSSE2(); AssertPass("SDL_HasSSE2()"); ret = SDL_HasSSE3(); AssertPass("SDL_HasSSE3()"); ret = SDL_HasSSE41(); AssertPass("SDL_HasSSE41()"); ret = SDL_HasSSE42(); AssertPass("SDL_HasSSE42()"); } /*! * \brief Tests SDL_GetVersion * \sa * http://wiki.libsdl.org/moin.cgi/SDL_GetVersion */ int platform_testGetVersion(void *arg) { SDL_version linked; SDL_GetVersion(&linked); AssertTrue( linked.major >= SDL_MAJOR_VERSION, "SDL_GetVersion(): returned major %i (>= %i)", linked.major, SDL_MAJOR_VERSION); AssertTrue( linked.minor >= SDL_MINOR_VERSION, "SDL_GetVersion(): returned minor %i (>= %i)", linked.minor, SDL_MINOR_VERSION); } /*! * \brief Tests SDL_VERSION macro */ int platform_testSDLVersion(void *arg) { SDL_version compiled; SDL_VERSION(&compiled); AssertTrue( compiled.major >= SDL_MAJOR_VERSION, "SDL_VERSION() returned major %i (>= %i)", compiled.major, SDL_MAJOR_VERSION); AssertTrue( compiled.minor >= SDL_MINOR_VERSION, "SDL_VERSION() returned minor %i (>= %i)", compiled.minor, SDL_MINOR_VERSION); } /*! * \brief Tests default SDL_Init */ int platform_testDefaultInit(void *arg) { int ret; int subsystem; ret = SDL_Init(0); AssertTrue( ret == 0, "SDL_Init(0): returned %i, expected 0, error: %s", ret, SDL_GetError()); subsystem = SDL_WasInit(0); AssertTrue( subsystem == 0, "SDL_WasInit(0): returned %i, expected 0", ret); SDL_Quit(); } /*! * \brief Tests SDL_Get/Set/ClearError * \sa * http://wiki.libsdl.org/moin.cgi/SDL_GetError * http://wiki.libsdl.org/moin.cgi/SDL_SetError * http://wiki.libsdl.org/moin.cgi/SDL_ClearError */ int platform_testGetSetClearError(void *arg) { const char *testError = "Testing"; char *lastError; int len; SDL_ClearError(); AssertPass("SDL_ClearError()"); lastError = (char *)SDL_GetError(); AssertPass("SDL_GetError()"); AssertTrue(lastError != NULL, "SDL_GetError() != NULL"); if (lastError != NULL) { len = strlen(lastError); AssertTrue(len == 0, "SDL_GetError(): no message expected, len: %i", len); } SDL_SetError("%s", testError); AssertPass("SDL_SetError()"); lastError = (char *)SDL_GetError(); AssertTrue(lastError != NULL, "SDL_GetError() != NULL"); if (lastError != NULL) { len = strlen(lastError); AssertTrue(len == strlen(testError), "SDL_GetError(): expected message len %i, was len: %i", strlen(testError), len); AssertTrue(strcmp(lastError, testError) == 0, "SDL_GetError(): expected message %s, was message: %s", testError, lastError); } // Clean up SDL_ClearError(); } /*! * \brief Tests SDL_SetError with empty input * \sa * http://wiki.libsdl.org/moin.cgi/SDL_SetError */ int platform_testSetErrorEmptyInput(void *arg) { const char *testError = ""; char *lastError; int len; SDL_SetError("%s", testError); AssertPass("SDL_SetError()"); lastError = (char *)SDL_GetError(); AssertTrue(lastError != NULL, "SDL_GetError() != NULL"); if (lastError != NULL) { len = strlen(lastError); AssertTrue(len == strlen(testError), "SDL_GetError(): expected message len %i, was len: %i", strlen(testError), len); AssertTrue(strcmp(lastError, testError) == 0, "SDL_GetError(): expected message '%s', was message: '%s'", testError, lastError); } // Clean up SDL_ClearError(); } /*! * \brief Tests SDL_SetError with invalid input * \sa * http://wiki.libsdl.org/moin.cgi/SDL_SetError */ int platform_testSetErrorInvalidInput(void *arg) { const char *testError = NULL; const char *probeError = "Testing"; char *lastError; int len; // Reset SDL_ClearError(); // Check for no-op SDL_SetError(testError); AssertPass("SDL_SetError()"); lastError = (char *)SDL_GetError(); AssertTrue(lastError != NULL, "SDL_GetError() != NULL"); if (lastError != NULL) { len = strlen(lastError); AssertTrue(len == 0, "SDL_GetError(): expected message len 0, was len: %i", 0, len); AssertTrue(strcmp(lastError, "") == 0, "SDL_GetError(): expected message '', was message: '%s'", lastError); } // Set SDL_SetError(probeError); // Check for no-op SDL_SetError(testError); AssertPass("SDL_SetError()"); lastError = (char *)SDL_GetError(); AssertTrue(lastError != NULL, "SDL_GetError() != NULL"); if (lastError != NULL) { len = strlen(lastError); AssertTrue(len == strlen(probeError), "SDL_GetError(): expected message len %i, was len: %i", strlen(probeError), len); AssertTrue(strcmp(lastError, probeError) == 0, "SDL_GetError(): expected message '%s', was message: '%s'", probeError, lastError); } // Clean up SDL_ClearError(); } /*! * \brief Tests SDL_GetPowerInfo * \sa * http://wiki.libsdl.org/moin.cgi/SDL_GetPowerInfo */ int platform_testGetPowerInfo(void *arg) { SDL_PowerState state; SDL_PowerState stateAgain; int secs; int secsAgain; int pct; int pctAgain; state = SDL_GetPowerInfo(&secs, &pct); AssertPass("SDL_GetPowerInfo()"); AssertTrue( state==SDL_POWERSTATE_UNKNOWN || state==SDL_POWERSTATE_ON_BATTERY || state==SDL_POWERSTATE_NO_BATTERY || state==SDL_POWERSTATE_CHARGING || state==SDL_POWERSTATE_CHARGED, "SDL_GetPowerInfo(): state %i is one of the expected values", (int)state); if (state==SDL_POWERSTATE_ON_BATTERY) { AssertTrue( secs >= 0, "SDL_GetPowerInfo(): on battery, secs >= 0, was: %i", secs); AssertTrue( (pct >= 0) && (pct <= 100), "SDL_GetPowerInfo(): on battery, pct=[0,100], was: %i", pct); } if (state==SDL_POWERSTATE_UNKNOWN || state==SDL_POWERSTATE_NO_BATTERY) { AssertTrue( secs == -1, "SDL_GetPowerInfo(): no battery, secs == -1, was: %i", secs); AssertTrue( pct == -1, "SDL_GetPowerInfo(): no battery, pct == -1, was: %i", pct); } // Partial return value variations stateAgain = SDL_GetPowerInfo(&secsAgain, NULL); AssertTrue( state==stateAgain, "State %i returned when only 'secs' requested", stateAgain); AssertTrue( secs==secsAgain, "Value %i matches when only 'secs' requested", secsAgain); stateAgain = SDL_GetPowerInfo(NULL, &pctAgain); AssertTrue( state==stateAgain, "State %i returned when only 'pct' requested", stateAgain); AssertTrue( pct==pctAgain, "Value %i matches when only 'pct' requested", pctAgain); stateAgain = SDL_GetPowerInfo(NULL, NULL); AssertTrue( state==stateAgain, "State %i returned when no value requested", stateAgain); }
{ "pile_set_name": "Github" }
backend app { .host = "127.0.0.1"; .port = "8081"; .connect_timeout = 60s; .first_byte_timeout = 60s; .between_bytes_timeout = 60s; .max_connections = 800; } acl purge { "127.0.0.1"; }
{ "pile_set_name": "Github" }
import { PersonalizeClientResolvedConfig, ServiceInputTypes, ServiceOutputTypes } from "../PersonalizeClient"; import { DescribeEventTrackerRequest, DescribeEventTrackerResponse } from "../models/models_0"; import { deserializeAws_json1_1DescribeEventTrackerCommand, serializeAws_json1_1DescribeEventTrackerCommand, } from "../protocols/Aws_json1_1"; import { getSerdePlugin } from "@aws-sdk/middleware-serde"; import { HttpRequest as __HttpRequest, HttpResponse as __HttpResponse } from "@aws-sdk/protocol-http"; import { Command as $Command } from "@aws-sdk/smithy-client"; import { FinalizeHandlerArguments, Handler, HandlerExecutionContext, MiddlewareStack, HttpHandlerOptions as __HttpHandlerOptions, MetadataBearer as __MetadataBearer, SerdeContext as __SerdeContext, } from "@aws-sdk/types"; export type DescribeEventTrackerCommandInput = DescribeEventTrackerRequest; export type DescribeEventTrackerCommandOutput = DescribeEventTrackerResponse & __MetadataBearer; export class DescribeEventTrackerCommand extends $Command< DescribeEventTrackerCommandInput, DescribeEventTrackerCommandOutput, PersonalizeClientResolvedConfig > { // Start section: command_properties // End section: command_properties constructor(readonly input: DescribeEventTrackerCommandInput) { // Start section: command_constructor super(); // End section: command_constructor } resolveMiddleware( clientStack: MiddlewareStack<ServiceInputTypes, ServiceOutputTypes>, configuration: PersonalizeClientResolvedConfig, options?: __HttpHandlerOptions ): Handler<DescribeEventTrackerCommandInput, DescribeEventTrackerCommandOutput> { this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize)); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const handlerExecutionContext: HandlerExecutionContext = { logger, inputFilterSensitiveLog: DescribeEventTrackerRequest.filterSensitiveLog, outputFilterSensitiveLog: DescribeEventTrackerResponse.filterSensitiveLog, }; const { requestHandler } = configuration; return stack.resolve( (request: FinalizeHandlerArguments<any>) => requestHandler.handle(request.request as __HttpRequest, options || {}), handlerExecutionContext ); } private serialize(input: DescribeEventTrackerCommandInput, context: __SerdeContext): Promise<__HttpRequest> { return serializeAws_json1_1DescribeEventTrackerCommand(input, context); } private deserialize(output: __HttpResponse, context: __SerdeContext): Promise<DescribeEventTrackerCommandOutput> { return deserializeAws_json1_1DescribeEventTrackerCommand(output, context); } // Start section: command_body_extra // End section: command_body_extra }
{ "pile_set_name": "Github" }
import "hash" rule n3ed_1b2fa905c6210b12 { meta: copyright="Copyright (c) 2014-2017 Support Intelligence Inc, All Rights Reserved." engine="saphire/1.2.2 divinorum/0.99 icewater/0.3.01" viz_url="http://icewater.io/en/cluster/query?h64=n3ed.1b2fa905c6210b12" cluster="n3ed.1b2fa905c6210b12" cluster_size="16 samples" filetype = "pe" tlp = "amber" version = "icewater foxtail" author = "Rick Wesson (@wessorh) [email protected]" date = "20171009" license = "RIL v1.0 see https://raw.githubusercontent.com/SupportIntelligence/Icewater/master/LICENSE" family="ramnit nimnul bmnup" md5_hashes="['c892113d4a14339c6928985be0e75374', 'd3dfccee1745066ec5317219729b9b9f', '6a1ecf016388b2abe6f5fd7e06aab543']" condition: filesize > 262144 and filesize < 1048576 and hash.md5(296995,1059) == "529f9aec791a33f80d7be972c607e7b7" }
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models from os.path import abspath, dirname class Migration(SchemaMigration): def forwards(self, orm): sql_migration_file = "{}/migration_0074_up.sql".format( abspath(dirname(__file__))) db.execute(open(sql_migration_file).read()) def backwards(self, orm): pass models = { u'physical.cloud': { 'Meta': {'object_name': 'Cloud'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.databaseinfra': { 'Meta': {'object_name': 'DatabaseInfra'}, 'capacity': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'database_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'disk_offering': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['physical.DiskOffering']"}), 'endpoint': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'endpoint_dns': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'engine': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Engine']"}), 'environment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Environment']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_vm_created': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'name_prefix': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'name_stamp': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '406', 'blank': 'True'}), 'per_database_size_mbytes': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'plan': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Plan']"}), 'ssl_configured': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}) }, u'physical.databaseinfraparameter': { 'Meta': {'unique_together': "((u'databaseinfra', u'parameter'),)", 'object_name': 'DatabaseInfraParameter'}, 'applied_on_database': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_value': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'databaseinfra': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.DatabaseInfra']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'parameter': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Parameter']"}), 'reset_default_value': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, u'physical.diskoffering': { 'Meta': {'object_name': 'DiskOffering'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'size_kb': ('django.db.models.fields.PositiveIntegerField', [], {}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.engine': { 'Meta': {'ordering': "(u'engine_type__name', u'version')", 'unique_together': "((u'version', u'engine_type'),)", 'object_name': 'Engine'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'engine_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'engines'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.EngineType']"}), 'engine_upgrade_option': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'backwards_engine'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Engine']"}), 'has_users': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'read_node_description': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100', 'null': 'True', 'blank': 'True'}), 'template_name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user_data_script': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'version': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'write_node_description': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100', 'null': 'True', 'blank': 'True'}) }, u'physical.enginetype': { 'Meta': {'ordering': "(u'name',)", 'object_name': 'EngineType'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_in_memory': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.environment': { 'Meta': {'object_name': 'Environment'}, 'cloud': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'environment_cloud'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Cloud']"}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'migrate_environment': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'migrate_to'", 'null': 'True', 'to': u"orm['physical.Environment']"}), 'min_of_zones': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.environmentgroup': { 'Meta': {'object_name': 'EnvironmentGroup'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'environments': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'groups'", 'symmetrical': 'False', 'to': u"orm['physical.Environment']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.host': { 'Meta': {'object_name': 'Host'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'future_host': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Host']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'hostname': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'identifier': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255'}), 'monitor_url': ('django.db.models.fields.URLField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}), 'offering': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Offering']", 'null': 'True'}), 'os_description': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '406', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}) }, u'physical.instance': { 'Meta': {'unique_together': "((u'address', u'port'),)", 'object_name': 'Instance'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'databaseinfra': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'instances'", 'to': u"orm['physical.DatabaseInfra']"}), 'dns': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'future_instance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Instance']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'hostname': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'instances'", 'to': u"orm['physical.Host']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance_type': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'port': ('django.db.models.fields.IntegerField', [], {}), 'read_only': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'shard': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}), 'total_size_in_bytes': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'used_size_in_bytes': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}) }, u'physical.offering': { 'Meta': {'object_name': 'Offering'}, 'cpus': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'environments': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'offerings'", 'symmetrical': 'False', 'to': u"orm['physical.Environment']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'memory_size_mb': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.parameter': { 'Meta': {'ordering': "(u'engine_type__name', u'name')", 'unique_together': "((u'name', u'engine_type'),)", 'object_name': 'Parameter'}, 'allowed_values': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '200', 'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'custom_method': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'dynamic': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'engine_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'enginetype'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.EngineType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'parameter_type': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.plan': { 'Meta': {'object_name': 'Plan'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'disk_offering': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'plans'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['physical.DiskOffering']"}), 'engine': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'plans'", 'to': u"orm['physical.Engine']"}), 'engine_equivalent_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'backwards_plan'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'environments': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'plans'", 'symmetrical': 'False', 'to': u"orm['physical.Environment']"}), 'has_persistence': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_ha': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'max_db_size': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'migrate_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'migrate_to'", 'null': 'True', 'to': u"orm['physical.Plan']"}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'provider': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'replication_topology': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'replication_topology'", 'null': 'True', 'to': u"orm['physical.ReplicationTopology']"}), 'stronger_offering': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'main_offerings'", 'null': 'True', 'to': u"orm['physical.Offering']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'weaker_offering': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'weaker_offerings'", 'null': 'True', 'to': u"orm['physical.Offering']"}) }, u'physical.planattribute': { 'Meta': {'object_name': 'PlanAttribute'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'plan': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'plan_attributes'", 'to': u"orm['physical.Plan']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, u'physical.replicationtopology': { 'Meta': {'object_name': 'ReplicationTopology'}, 'can_change_parameters': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_clone_db': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_reinstall_vm': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_resize_vm': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_setup_ssl': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'can_switch_master': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_upgrade_db': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'class_path': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'details': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'engine': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'replication_topologies'", 'symmetrical': 'False', 'to': u"orm['physical.Engine']"}), 'has_horizontal_scalability': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'parameter': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'replication_topologies'", 'blank': 'True', 'to': u"orm['physical.Parameter']"}), 'script': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'replication_topologies'", 'null': 'True', 'to': u"orm['physical.Script']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.script': { 'Meta': {'object_name': 'Script'}, 'configuration': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'initialization': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'metric_collector': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'start_database': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'start_replication': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.topologyparametercustomvalue': { 'Meta': {'unique_together': "((u'topology', u'parameter'),)", 'object_name': 'TopologyParameterCustomValue'}, 'attr_name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'parameter': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'topology_custom_values'", 'to': u"orm['physical.Parameter']"}), 'topology': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'param_custom_values'", 'to': u"orm['physical.ReplicationTopology']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.vip': { 'Meta': {'object_name': 'Vip'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'identifier': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'infra': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'vips'", 'to': u"orm['physical.DatabaseInfra']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.volume': { 'Meta': {'object_name': 'Volume'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'host': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'volumes'", 'to': u"orm['physical.Host']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'identifier': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'total_size_kb': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'used_size_kb': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}) } } complete_apps = ['physical']
{ "pile_set_name": "Github" }
package net.zoneland.x.bpm.mobile.v1.zoneXBPM.core.component.enums; /** * Created by FancyLou on 2016/10/27. */ public enum ContactFragmentListItemType { header(0),//头部 department(1),//我的部门 company(2),//我的公司 group(3),//我的群组 usually(4);//我的常用联系人 private final int type; ContactFragmentListItemType(int type) { this.type = type; } public int getType() { return type; } }
{ "pile_set_name": "Github" }
@extends('backend.app') @section('modules') <div class="container-fluid"> <div class="row"> <div class="col-md-2"> @include('backend.setting._menu') </div> @yield('content') </div> </div> @endsection
{ "pile_set_name": "Github" }
using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using GitDiffMargin.Git; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Text; namespace GitDiffMargin.Core { public class DiffUpdateBackgroundParser : BackgroundParser { private readonly FileSystemWatcher _watcher; private readonly IGitCommands _commands; private readonly ITextDocument _textDocument; private readonly ITextBuffer _documentBuffer; private readonly string _originalPath; internal DiffUpdateBackgroundParser(ITextBuffer textBuffer, ITextBuffer documentBuffer, string originalPath, TaskScheduler taskScheduler, ITextDocumentFactoryService textDocumentFactoryService, IGitCommands commands) : base(textBuffer, taskScheduler, textDocumentFactoryService) { _documentBuffer = documentBuffer; _commands = commands; ReparseDelay = TimeSpan.FromMilliseconds(500); if (TextDocumentFactoryService.TryGetTextDocument(_documentBuffer, out _textDocument)) { _originalPath = originalPath; if (_commands.IsGitRepository(_textDocument.FilePath, _originalPath)) { _textDocument.FileActionOccurred += OnFileActionOccurred; var repositoryDirectory = _commands.GetGitRepository(_textDocument.FilePath, _originalPath); if (repositoryDirectory != null) { _watcher = new FileSystemWatcher(repositoryDirectory); _watcher.Changed += HandleFileSystemChanged; _watcher.Created += HandleFileSystemChanged; _watcher.Deleted += HandleFileSystemChanged; _watcher.Renamed += HandleFileSystemChanged; _watcher.EnableRaisingEvents = true; } } } } private void HandleFileSystemChanged(object sender, FileSystemEventArgs e) { Action action = () => { try { ProcessFileSystemChange(e); } catch (Exception ex) { if (ErrorHandler.IsCriticalException(ex)) throw; } }; Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); } private void ProcessFileSystemChange(FileSystemEventArgs e) { if (e.ChangeType == WatcherChangeTypes.Changed && Directory.Exists(e.FullPath)) return; if (string.Equals(Path.GetExtension(e.Name), ".lock", StringComparison.OrdinalIgnoreCase)) return; MarkDirty(true); } private void OnFileActionOccurred(object sender, TextDocumentFileActionEventArgs e) { if ((e.FileActionType & FileActionTypes.ContentSavedToDisk) != 0) { MarkDirty(true); } } public override string Name { get { return "Git Diff Analyzer"; } } protected override void ReParseImpl() { try { var stopwatch = Stopwatch.StartNew(); var snapshot = TextBuffer.CurrentSnapshot; ITextDocument textDocument; if (!TextDocumentFactoryService.TryGetTextDocument(_documentBuffer, out textDocument)) return; var diff = _commands.GetGitDiffFor(textDocument, _originalPath, snapshot); var result = new DiffParseResultEventArgs(snapshot, stopwatch.Elapsed, diff.ToList()); OnParseComplete(result); } catch (InvalidOperationException) { MarkDirty(true); throw; } } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { if (_textDocument != null) { _textDocument.FileActionOccurred -= OnFileActionOccurred; } if (_watcher != null) { _watcher.Dispose(); } } } } }
{ "pile_set_name": "Github" }
<?php namespace App\Http\Controllers\Backend; use App\Http\Controllers\Controller; use App\Http\Requests\Backend\Notification\MarkNotificationRequest; use App\Models\Notification\Notification; use App\Repositories\Backend\Notification\NotificationRepository; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class NotificationController extends Controller { /** * @var \App\Repositories\Backend\Notification\NotificationRepository */ protected $notification; public function __construct(NotificationRepository $notification) { $this->notification = $notification; } /* * Ajax data fetch function */ public function ajaxNotifications() { /* * get user id */ $userId = Auth::user()->id; /* * where conditions to get count */ $where = ['user_id' => $userId, 'is_read' => 0]; /* * get unread count */ $getUnreadNotificationCount = $this->notification->getNotification($where, 'count'); /* * where condition to list top notifications */ $listWhere = ['user_id' => $userId, 'is_read' => 0]; /* * get top 5 notifications */ $getNotifications = $this->notification->getNotification($listWhere, 'get', $limit = 5); /* * preparing pass array which contain view and count both */ $passArray['view'] = view('backend.includes.notification') ->with('notifications', $getNotifications) ->with('unreadNotificationCount', $getUnreadNotificationCount) ->render(); $passArray['count'] = $getUnreadNotificationCount; /* * pass jsonencode array */ echo json_encode($passArray); exit; } /* * clearCurrentNotifications */ public function clearCurrentNotifications() { $userId = Auth::user()->id; echo $this->notification->clearNotifications(5); exit; } /** * @return mixed */ public function index(Request $request) { $notifications = Notification::where('user_id', access()->user()->id)->get(); return view('backend.notification.index', compact('notifications')); } /** * @param type $id * @param type $status * @param MarkNotificationRequest $request * * @return type */ public function mark($id, $status, MarkNotificationRequest $request) { $this->notification->mark($id, $status); return response()->json(['status' => 'OK']); } }
{ "pile_set_name": "Github" }
# mapstructure [![Godoc](https://godoc.org/github.com/mitchellh/mapstructure?status.svg)](https://godoc.org/github.com/mitchellh/mapstructure) mapstructure is a Go library for decoding generic map values to structures and vice versa, while providing helpful error handling. This library is most useful when decoding values from some data stream (JSON, Gob, etc.) where you don't _quite_ know the structure of the underlying data until you read a part of it. You can therefore read a `map[string]interface{}` and use this library to decode it into the proper underlying native Go structure. ## Installation Standard `go get`: ``` $ go get github.com/mitchellh/mapstructure ``` ## Usage & Example For usage and examples see the [Godoc](http://godoc.org/github.com/mitchellh/mapstructure). The `Decode` function has examples associated with it there. ## But Why?! Go offers fantastic standard libraries for decoding formats such as JSON. The standard method is to have a struct pre-created, and populate that struct from the bytes of the encoded format. This is great, but the problem is if you have configuration or an encoding that changes slightly depending on specific fields. For example, consider this JSON: ```json { "type": "person", "name": "Mitchell" } ``` Perhaps we can't populate a specific structure without first reading the "type" field from the JSON. We could always do two passes over the decoding of the JSON (reading the "type" first, and the rest later). However, it is much simpler to just decode this into a `map[string]interface{}` structure, read the "type" key, then use something like this library to decode it into the proper structure.
{ "pile_set_name": "Github" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // THIS IS AUTOGENERATED FILE CREATED BY // https://github.com/dotnet/buildtools/blob/6736870b84e06b75e7df32bb84d442db1b2afa10/src/Microsoft.DotNet.Build.Tasks/PackageFiles/encoding.targets // namespace System.Text { internal static partial class EncodingTable { // // s_encodingNames is the concatenation of all supported IANA names for each codepage. // This is done rather than using a large readonly array of strings to avoid // generating a large amount of code in the static constructor. // Using indices from s_encodingNamesIndices, we binary search this string when mapping // an encoding name to a codepage. Note that these names are all lowercase and are // sorted alphabetically. // private const string s_encodingNames = "ansi_x3.4-1968" + // 20127 "ansi_x3.4-1986" + // 20127 "ascii" + // 20127 "cp367" + // 20127 "cp819" + // 28591 "csascii" + // 20127 "csisolatin1" + // 28591 "csunicode11utf7" + // 65000 "ibm367" + // 20127 "ibm819" + // 28591 "iso-10646-ucs-2" + // 1200 "iso-8859-1" + // 28591 "iso-ir-100" + // 28591 "iso-ir-6" + // 20127 "iso646-us" + // 20127 "iso8859-1" + // 28591 "iso_646.irv:1991" + // 20127 "iso_8859-1" + // 28591 "iso_8859-1:1987" + // 28591 "l1" + // 28591 "latin1" + // 28591 "ucs-2" + // 1200 "unicode" + // 1200 "unicode-1-1-utf-7" + // 65000 "unicode-1-1-utf-8" + // 65001 "unicode-2-0-utf-7" + // 65000 "unicode-2-0-utf-8" + // 65001 "unicodefffe" + // 1201 "us" + // 20127 "us-ascii" + // 20127 "utf-16" + // 1200 "utf-16be" + // 1201 "utf-16le" + // 1200 "utf-32" + // 12000 "utf-32be" + // 12001 "utf-32le" + // 12000 "utf-7" + // 65000 "utf-8" + // 65001 "x-unicode-1-1-utf-7" + // 65000 "x-unicode-1-1-utf-8" + // 65001 "x-unicode-2-0-utf-7" + // 65000 "x-unicode-2-0-utf-8"; // 65001 // // s_encodingNameIndices contains the start index of every encoding name in the string // s_encodingNames. We infer the length of each string by looking at the start index // of the next string. // private static readonly int[] s_encodingNameIndices = new int[] { 0, // ansi_x3.4-1968 (20127) 14, // ansi_x3.4-1986 (20127) 28, // ascii (20127) 33, // cp367 (20127) 38, // cp819 (28591) 43, // csascii (20127) 50, // csisolatin1 (28591) 61, // csunicode11utf7 (65000) 76, // ibm367 (20127) 82, // ibm819 (28591) 88, // iso-10646-ucs-2 (1200) 103, // iso-8859-1 (28591) 113, // iso-ir-100 (28591) 123, // iso-ir-6 (20127) 131, // iso646-us (20127) 140, // iso8859-1 (28591) 149, // iso_646.irv:1991 (20127) 165, // iso_8859-1 (28591) 175, // iso_8859-1:1987 (28591) 190, // l1 (28591) 192, // latin1 (28591) 198, // ucs-2 (1200) 203, // unicode (1200) 210, // unicode-1-1-utf-7 (65000) 227, // unicode-1-1-utf-8 (65001) 244, // unicode-2-0-utf-7 (65000) 261, // unicode-2-0-utf-8 (65001) 278, // unicodefffe (1201) 289, // us (20127) 291, // us-ascii (20127) 299, // utf-16 (1200) 305, // utf-16be (1201) 313, // utf-16le (1200) 321, // utf-32 (12000) 327, // utf-32be (12001) 335, // utf-32le (12000) 343, // utf-7 (65000) 348, // utf-8 (65001) 353, // x-unicode-1-1-utf-7 (65000) 372, // x-unicode-1-1-utf-8 (65001) 391, // x-unicode-2-0-utf-7 (65000) 410, // x-unicode-2-0-utf-8 (65001) 429 }; // // s_codePagesByName contains the list of supported codepages which match the encoding // names listed in s_encodingNames. The way mapping works is we binary search // s_encodingNames using s_encodingNamesIndices until we find a match for a given name. // The index of the entry in s_encodingNamesIndices will be the index of codepage in // s_codePagesByName. // private static readonly ushort[] s_codePagesByName = new ushort[] { 20127, // ansi_x3.4-1968 20127, // ansi_x3.4-1986 20127, // ascii 20127, // cp367 28591, // cp819 20127, // csascii 28591, // csisolatin1 65000, // csunicode11utf7 20127, // ibm367 28591, // ibm819 1200, // iso-10646-ucs-2 28591, // iso-8859-1 28591, // iso-ir-100 20127, // iso-ir-6 20127, // iso646-us 28591, // iso8859-1 20127, // iso_646.irv:1991 28591, // iso_8859-1 28591, // iso_8859-1:1987 28591, // l1 28591, // latin1 1200, // ucs-2 1200, // unicode 65000, // unicode-1-1-utf-7 65001, // unicode-1-1-utf-8 65000, // unicode-2-0-utf-7 65001, // unicode-2-0-utf-8 1201, // unicodefffe 20127, // us 20127, // us-ascii 1200, // utf-16 1201, // utf-16be 1200, // utf-16le 12000, // utf-32 12001, // utf-32be 12000, // utf-32le 65000, // utf-7 65001, // utf-8 65000, // x-unicode-1-1-utf-7 65001, // x-unicode-1-1-utf-8 65000, // x-unicode-2-0-utf-7 65001 // x-unicode-2-0-utf-8 }; // // When retrieving the value for System.Text.Encoding.WebName or // System.Text.Encoding.EncodingName given System.Text.Encoding.CodePage, // we perform a linear search on s_mappedCodePages to find the index of the // given codepage. This is used to index WebNameIndices to get the start // index of the web name in the string WebNames, and to index // s_englishNameIndices to get the start of the English name in // s_englishNames. In addition, this arrays indices correspond to the indices // into s_uiFamilyCodePages and s_flags. // private static readonly ushort[] s_mappedCodePages = new ushort[] { 1200, // utf-16 1201, // utf-16be 12000, // utf-32 12001, // utf-32be 20127, // us-ascii 28591, // iso-8859-1 65000, // utf-7 65001 // utf-8 }; // // s_uiFamilyCodePages is indexed by the corresponding index in s_mappedCodePages. // private static readonly int[] s_uiFamilyCodePages = new int[] { 1200, 1200, 1200, 1200, 1252, 1252, 1200, 1200 }; // // s_webNames is a concatenation of the default encoding names // for each code page. It is used in retrieving the value for // System.Text.Encoding.WebName given System.Text.Encoding.CodePage. // This is done rather than using a large readonly array of strings to avoid // generating a large amount of code in the static constructor. // private const string s_webNames = "utf-16" + // 1200 "utf-16BE" + // 1201 "utf-32" + // 12000 "utf-32BE" + // 12001 "us-ascii" + // 20127 "iso-8859-1" + // 28591 "utf-7" + // 65000 "utf-8"; // 65001 // // s_webNameIndices contains the start index of each code page's default // web name in the string s_webNames. It is indexed by an index into // s_mappedCodePages. // private static readonly int[] s_webNameIndices = new int[] { 0, // utf-16 (1200) 6, // utf-16be (1201) 14, // utf-32 (12000) 20, // utf-32be (12001) 28, // us-ascii (20127) 36, // iso-8859-1 (28591) 46, // utf-7 (65000) 51, // utf-8 (65001) 56 }; // // s_englishNames is the concatenation of the English names for each codepage. // It is used in retrieving the value for System.Text.Encoding.EncodingName // given System.Text.Encoding.CodePage. // This is done rather than using a large readonly array of strings to avoid // generating a large amount of code in the static constructor. // private const string s_englishNames = "Unicode" + // 1200 "Unicode (Big-Endian)" + // 1201 "Unicode (UTF-32)" + // 12000 "Unicode (UTF-32 Big-Endian)" + // 12001 "US-ASCII" + // 20127 "Western European (ISO)" + // 28591 "Unicode (UTF-7)" + // 65000 "Unicode (UTF-8)"; // 65001 // // s_englishNameIndices contains the start index of each code page's English // name in the string s_englishNames. It is indexed by an index into // s_mappedCodePages. // private static readonly int[] s_englishNameIndices = new int[] { 0, // Unicode (1200) 7, // Unicode (Big-Endian) (1201) 27, // Unicode (UTF-32) (12000) 43, // Unicode (UTF-32 Big-Endian) (12001) 70, // US-ASCII (20127) 78, // Western European (ISO) (28591) 100, // Unicode (UTF-7) (65000) 115, // Unicode (UTF-8) (65001) 130 }; // redeclaring these constants here for readability below private const uint MIMECONTF_MAILNEWS = Encoding.MIMECONTF_MAILNEWS; private const uint MIMECONTF_BROWSER = Encoding.MIMECONTF_BROWSER; private const uint MIMECONTF_SAVABLE_MAILNEWS = Encoding.MIMECONTF_SAVABLE_MAILNEWS; private const uint MIMECONTF_SAVABLE_BROWSER = Encoding.MIMECONTF_SAVABLE_BROWSER; // s_flags is indexed by the corresponding index in s_mappedCodePages. private static readonly uint[] s_flags = new uint[] { MIMECONTF_SAVABLE_BROWSER, 0, 0, 0, MIMECONTF_MAILNEWS | MIMECONTF_SAVABLE_MAILNEWS, MIMECONTF_MAILNEWS | MIMECONTF_BROWSER | MIMECONTF_SAVABLE_MAILNEWS | MIMECONTF_SAVABLE_BROWSER, MIMECONTF_MAILNEWS | MIMECONTF_SAVABLE_MAILNEWS, MIMECONTF_MAILNEWS | MIMECONTF_BROWSER | MIMECONTF_SAVABLE_MAILNEWS | MIMECONTF_SAVABLE_BROWSER }; } }
{ "pile_set_name": "Github" }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. //! Contains record-based API for reading Parquet files. mod api; pub mod reader; mod record_writer; mod triplet; pub use self::{ api::{List, ListAccessor, Map, MapAccessor, Row, RowAccessor}, record_writer::RecordWriter, };
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- import json from app.const import * from app.base.db import get_db, SQL from app.base.logger import log from app.base.utils import tp_timestamp_sec from . import syslog def save_config(handler, msg, name, value): db = get_db() str_val = json.dumps(value, separators=(',', ':')) sql = 'SELECT name FROM `{dbtp}config` WHERE name="{name}";'.format(dbtp=db.table_prefix, name=name) db_ret = db.query(sql) if db_ret is not None and len(db_ret) > 0: sql = 'UPDATE `{dbtp}config` SET value={dbph} WHERE name="{name}";'.format(dbtp=db.table_prefix, dbph=db.place_holder, name=name) db_ret = db.exec(sql, (str_val,)) else: sql = 'INSERT INTO `{dbtp}config` (name, value) VALUES ({dbph}, {dbph});'.format(dbtp=db.table_prefix, dbph=db.place_holder) db_ret = db.exec(sql, (name, str_val)) if not db_ret: return TPE_DATABASE operator = handler.get_current_user() syslog.sys_log(operator, handler.request.remote_ip, TPE_OK, msg) return TPE_OK def add_role(handler, role_name, privilege): db = get_db() _time_now = tp_timestamp_sec() operator = handler.get_current_user() # 1. 判断是否已经存在了 sql = 'SELECT id FROM {}role WHERE name="{name}";'.format(db.table_prefix, name=role_name) db_ret = db.query(sql) if db_ret is not None and len(db_ret) > 0: return TPE_EXISTS, 0 sql = 'INSERT INTO `{}role` (name, privilege, creator_id, create_time) VALUES ' \ '("{name}", {privilege}, {creator_id}, {create_time});' \ ''.format(db.table_prefix, name=role_name, privilege=privilege, creator_id=operator['id'], create_time=_time_now) db_ret = db.exec(sql) if not db_ret: return TPE_DATABASE, 0 _id = db.last_insert_id() syslog.sys_log(operator, handler.request.remote_ip, TPE_OK, "创建角色:{}".format(role_name)) return TPE_OK, _id def update_role(handler, role_id, role_name, privilege): """ 更新一个远程账号 """ db = get_db() # 1. 判断是否存在 sql = 'SELECT id FROM {}role WHERE id={rid};'.format(db.table_prefix, rid=role_id) db_ret = db.query(sql) if db_ret is None or len(db_ret) == 0: return TPE_NOT_EXISTS sql = 'UPDATE `{}role` SET name="{name}", privilege={p} WHERE id={rid};' \ ''.format(db.table_prefix, name=role_name, p=privilege, rid=role_id) db_ret = db.exec(sql) if not db_ret: return TPE_DATABASE return TPE_OK def remove_role(handler, role_id): db = get_db() s = SQL(db) # 1. 判断是否存在 s.select_from('role', ['name'], alt_name='r') s.where('r.id={rid}'.format(rid=role_id)) err = s.query() if err != TPE_OK: return err if len(s.recorder) == 0: return TPE_NOT_EXISTS role_name = s.recorder[0].name sql_list = list() sql = 'DELETE FROM `{tp}role` WHERE `id`={ph};'.format(tp=db.table_prefix, ph=db.place_holder) sql_list.append({'s': sql, 'v': (role_id, )}) # 更新此角色相关的用户信息 sql = 'UPDATE `{tp}user` SET `role_id`=0 WHERE `role_id`={ph};'.format(tp=db.table_prefix, ph=db.place_holder) sql_list.append({'s': sql, 'v': (role_id, )}) if not db.transaction(sql_list): return TPE_DATABASE syslog.sys_log(handler.get_current_user(), handler.request.remote_ip, TPE_OK, "删除角色:{}".format(role_name)) return TPE_OK
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_10) on Sun Jun 02 21:40:21 BST 2013 --> <title>Uses of Class propel.core.validation.propertyMetadata.PathPropertyMetadata</title> <meta name="date" content="2013-06-02"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class propel.core.validation.propertyMetadata.PathPropertyMetadata"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../propel/core/validation/propertyMetadata/PathPropertyMetadata.html" title="class in propel.core.validation.propertyMetadata">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?propel/core/validation/propertyMetadata/class-use/PathPropertyMetadata.html" target="_top">Frames</a></li> <li><a href="PathPropertyMetadata.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class propel.core.validation.propertyMetadata.PathPropertyMetadata" class="title">Uses of Class<br>propel.core.validation.propertyMetadata.PathPropertyMetadata</h2> </div> <div class="classUseContainer">No usage of propel.core.validation.propertyMetadata.PathPropertyMetadata</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../propel/core/validation/propertyMetadata/PathPropertyMetadata.html" title="class in propel.core.validation.propertyMetadata">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?propel/core/validation/propertyMetadata/class-use/PathPropertyMetadata.html" target="_top">Frames</a></li> <li><a href="PathPropertyMetadata.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "pile_set_name": "Github" }
#! /bin/sh # Copyright (C) 2013 - LGPL - Steve Schnepp <[email protected]> # # [backuppc] # user backuppc # env.pcdir /var/lib/BackupPC/pc # env.full_warning 10 # warn if FULL backup older than N days # env.full_critical 20 # critical if FULL backup older than N days # env.incr_warning 1 # warn if INCR backup older than N days # env.incr_critical 3 # critical if INCR backup older than N days # #%# family=backuppc #%# capabilities=autoconf PCDIR=${pcdir:-"/var/lib/BackupPC/pc"} HOSTS=$(cd ${PCDIR} 2>/dev/null && ls -1) . $MUNIN_LIBDIR/plugins/plugin.sh if [ "$1" = "autoconf" ]; then if [ -n "$HOSTS" ]; then echo "yes" else echo "no" fi exit 0 fi if [ "$1" = "config" ]; then echo "multigraph backuppc_sizes" echo "graph_title BackupPC - Last Backup Size" echo "graph_args --base 1024 -l 0" echo "graph_vlabel Bytes" echo "graph_category backup" for h in ${HOSTS} do echo "$(clean_fieldname ${h})_full.label $(clean_fieldname ${h}) Full" echo "$(clean_fieldname ${h})_incr.label $(clean_fieldname ${h}) Incr" done echo "multigraph backuppc_ages" echo "graph_title BackupPC - Last Backup Age" echo "graph_args -l 0" echo "graph_vlabel days" echo "graph_category backup" for h in ${HOSTS} do echo "$(clean_fieldname ${h})_incr.label $(clean_fieldname ${h})" if [ -n "$incr_warning" ]; then echo "$(clean_fieldname ${h})_incr.warning $incr_warning" fi if [ -n "$incr_critical" ]; then echo "$(clean_fieldname ${h})_incr.critical $incr_critical" fi done echo "multigraph backuppc_ages_full" echo "graph_title BackupPC - Last Full Backup Age" echo "graph_args -l 0" echo "graph_vlabel days" echo "graph_category backup" for h in ${HOSTS} do echo "$(clean_fieldname ${h})_full.label $(clean_fieldname ${h})" if [ -n "$full_warning" ]; then echo "$(clean_fieldname ${h})_full.warning $full_warning" fi if [ -n "$full_critical" ]; then echo "$(clean_fieldname ${h})_full.critical $full_critical" fi done exit 0 fi echo "multigraph backuppc_sizes" for h in $HOSTS do SIZE=$(awk '/full/ { size = $6 } END { print size; }' ${PCDIR}/${h}/backups) echo "$(clean_fieldname ${h})_full.value $SIZE" SIZE=$(awk '/incr/ { size = $6 } END { print size; }' ${PCDIR}/${h}/backups) echo "$(clean_fieldname ${h})_incr.value $SIZE" done echo "multigraph backuppc_ages" for h in $HOSTS do SIZE=$(awk '{ age = systime() - $3 } END { print age / 3600 / 24; }' ${PCDIR}/${h}/backups) echo "$(clean_fieldname ${h})_incr.value $SIZE" done echo "multigraph backuppc_ages_full" for h in $HOSTS do SIZE=$(awk '/full/ { age = systime() - $3 } END { print age / 3600 / 24; }' ${PCDIR}/${h}/backups) echo "$(clean_fieldname ${h})_full.value $SIZE" done <<'__END__' Extract for the BackupPC doc, http://backuppc.sourceforge.net/faq/BackupPC.html backups A tab-delimited ascii table listing information about each successful backup, one per row. The columns are: num The backup number, an integer that starts at 0 and increments for each successive backup. The corresponding backup is stored in the directory num (eg: if this field is 5, then the backup is stored in __TOPDIR__/pc/$host/5). type Set to "full" or "incr" for full or incremental backup. startTime Start time of the backup in unix seconds. endTime Stop time of the backup in unix seconds. nFiles Number of files backed up (as reported by smbclient, tar, rsync or ftp). size Total file size backed up (as reported by smbclient, tar, rsync or ftp). nFilesExist Number of files that were already in the pool (as determined by BackupPC_dump and BackupPC_link). sizeExist Total size of files that were already in the pool (as determined by BackupPC_dump and BackupPC_link). nFilesNew Number of files that were not in the pool (as determined by BackupPC_link). sizeNew Total size of files that were not in the pool (as determined by BackupPC_link). xferErrs Number of errors or warnings from smbclient, tar, rsync or ftp. xferBadFile Number of errors from smbclient that were bad file errors (zero otherwise). xferBadShare Number of errors from smbclient that were bad share errors (zero otherwise). tarErrs Number of errors from BackupPC_tarExtract. compress The compression level used on this backup. Zero or empty means no compression. sizeExistComp Total compressed size of files that were already in the pool (as determined by BackupPC_dump and BackupPC_link). sizeNewComp Total compressed size of files that were not in the pool (as determined by BackupPC_link). noFill Set if this backup has not been filled in with the most recent previous filled or full backup. See $Conf{IncrFill}. fillFromNum If this backup was filled (ie: noFill is 0) then this is the number of the backup that it was filled from mangle Set if this backup has mangled file names and attributes. Always true for backups in v1.4.0 and above. False for all backups prior to v1.4.0. __END__
{ "pile_set_name": "Github" }
/* ** $Id: lauxlib.c,v 1.158 2006/01/16 12:42:21 roberto Exp $ ** Auxiliary functions for building Lua libraries ** See Copyright Notice in lua.h */ #include <ctype.h> #include <errno.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* This file uses only the official API of Lua. ** Any function declared here could be written as an application function. */ #define lauxlib_c #define LUA_LIB #include "lua.h" #include "lauxlib.h" #define FREELIST_REF 0 /* free list of references */ /* convert a stack index to positive */ #define abs_index(L, i) ((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : \ lua_gettop(L) + (i) + 1) /* ** {====================================================== ** Error-report functions ** ======================================================= */ LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) { lua_Debug ar; if (!lua_getstack(L, 0, &ar)) /* no stack frame? */ return luaL_error(L, "bad argument #%d (%s)", narg, extramsg); lua_getinfo(L, "n", &ar); if (strcmp(ar.namewhat, "method") == 0) { narg--; /* do not count `self' */ if (narg == 0) /* error is in the self argument itself? */ return luaL_error(L, "calling " LUA_QS " on bad self (%s)", ar.name, extramsg); } if (ar.name == NULL) ar.name = "?"; return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)", narg, ar.name, extramsg); } LUALIB_API int luaL_typerror (lua_State *L, int narg, const char *tname) { const char *msg = lua_pushfstring(L, "%s expected, got %s", tname, luaL_typename(L, narg)); return luaL_argerror(L, narg, msg); } static void tag_error (lua_State *L, int narg, int tag) { luaL_typerror(L, narg, lua_typename(L, tag)); } LUALIB_API void luaL_where (lua_State *L, int level) { lua_Debug ar; if (lua_getstack(L, level, &ar)) { /* check function at level */ lua_getinfo(L, "Sl", &ar); /* get info about it */ if (ar.currentline > 0) { /* is there info? */ lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline); return; } } lua_pushliteral(L, ""); /* else, no information available... */ } LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) { va_list argp; va_start(argp, fmt); luaL_where(L, 1); lua_pushvfstring(L, fmt, argp); va_end(argp); lua_concat(L, 2); return lua_error(L); } /* }====================================================== */ LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def, const char *const lst[]) { const char *name = (def) ? luaL_optstring(L, narg, def) : luaL_checkstring(L, narg); int i; for (i=0; lst[i]; i++) if (strcmp(lst[i], name) == 0) return i; return luaL_argerror(L, narg, lua_pushfstring(L, "invalid option " LUA_QS, name)); } LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) { lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get registry.name */ if (!lua_isnil(L, -1)) /* name already in use? */ return 0; /* leave previous value on top, but return 0 */ lua_pop(L, 1); lua_newtable(L); /* create metatable */ lua_pushvalue(L, -1); lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */ return 1; } LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) { void *p = lua_touserdata(L, ud); lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */ if (p == NULL || !lua_getmetatable(L, ud) || !lua_rawequal(L, -1, -2)) luaL_typerror(L, ud, tname); lua_pop(L, 2); /* remove both metatables */ return p; } LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *mes) { if (!lua_checkstack(L, space)) luaL_error(L, "stack overflow (%s)", mes); } LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) { if (lua_type(L, narg) != t) tag_error(L, narg, t); } LUALIB_API void luaL_checkany (lua_State *L, int narg) { if (lua_type(L, narg) == LUA_TNONE) luaL_argerror(L, narg, "value expected"); } LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) { const char *s = lua_tolstring(L, narg, len); if (!s) tag_error(L, narg, LUA_TSTRING); return s; } LUALIB_API const char *luaL_optlstring (lua_State *L, int narg, const char *def, size_t *len) { if (lua_isnoneornil(L, narg)) { if (len) *len = (def ? strlen(def) : 0); return def; } else return luaL_checklstring(L, narg, len); } LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) { lua_Number d = lua_tonumber(L, narg); if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */ tag_error(L, narg, LUA_TNUMBER); return d; } LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) { return luaL_opt(L, luaL_checknumber, narg, def); } LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) { lua_Integer d = lua_tointeger(L, narg); if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */ tag_error(L, narg, LUA_TNUMBER); return d; } LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg, lua_Integer def) { return luaL_opt(L, luaL_checkinteger, narg, def); } LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) { if (!lua_getmetatable(L, obj)) /* no metatable? */ return 0; lua_pushstring(L, event); lua_rawget(L, -2); if (lua_isnil(L, -1)) { lua_pop(L, 2); /* remove metatable and metafield */ return 0; } else { lua_remove(L, -2); /* remove only metatable */ return 1; } } LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) { obj = abs_index(L, obj); if (!luaL_getmetafield(L, obj, event)) /* no metafield? */ return 0; lua_pushvalue(L, obj); lua_call(L, 1, 1); return 1; } LUALIB_API void (luaL_register) (lua_State *L, const char *libname, const luaL_Reg *l) { luaI_openlib(L, libname, l, 0); } static int libsize (const luaL_Reg *l) { int size = 0; for (; l->name; l++) size++; return size; } LUALIB_API void luaI_openlib (lua_State *L, const char *libname, const luaL_Reg *l, int nup) { if (libname) { int size = libsize(l); /* check whether lib already exists */ luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", size); lua_getfield(L, -1, libname); /* get _LOADED[libname] */ if (!lua_istable(L, -1)) { /* not found? */ lua_pop(L, 1); /* remove previous result */ /* try global variable (and create one if it does not exist) */ if (luaL_findtable(L, LUA_GLOBALSINDEX, libname, size) != NULL) luaL_error(L, "name conflict for module " LUA_QS, libname); lua_pushvalue(L, -1); lua_setfield(L, -3, libname); /* _LOADED[libname] = new table */ } lua_remove(L, -2); /* remove _LOADED table */ lua_insert(L, -(nup+1)); /* move library table to below upvalues */ } for (; l->name; l++) { int i; for (i=0; i<nup; i++) /* copy upvalues to the top */ lua_pushvalue(L, -nup); lua_pushcclosure(L, l->func, nup); lua_setfield(L, -(nup+2), l->name); } lua_pop(L, nup); /* remove upvalues */ } /* ** {====================================================== ** getn-setn: size for arrays ** ======================================================= */ #if defined(LUA_COMPAT_GETN) static int checkint (lua_State *L, int topop) { int n = (lua_type(L, -1) == LUA_TNUMBER) ? lua_tointeger(L, -1) : -1; lua_pop(L, topop); return n; } static void getsizes (lua_State *L) { lua_getfield(L, LUA_REGISTRYINDEX, "LUA_SIZES"); if (lua_isnil(L, -1)) { /* no `size' table? */ lua_pop(L, 1); /* remove nil */ lua_newtable(L); /* create it */ lua_pushvalue(L, -1); /* `size' will be its own metatable */ lua_setmetatable(L, -2); lua_pushliteral(L, "kv"); lua_setfield(L, -2, "__mode"); /* metatable(N).__mode = "kv" */ lua_pushvalue(L, -1); lua_setfield(L, LUA_REGISTRYINDEX, "LUA_SIZES"); /* store in register */ } } LUALIB_API void luaL_setn (lua_State *L, int t, int n) { t = abs_index(L, t); lua_pushliteral(L, "n"); lua_rawget(L, t); if (checkint(L, 1) >= 0) { /* is there a numeric field `n'? */ lua_pushliteral(L, "n"); /* use it */ lua_pushinteger(L, n); lua_rawset(L, t); } else { /* use `sizes' */ getsizes(L); lua_pushvalue(L, t); lua_pushinteger(L, n); lua_rawset(L, -3); /* sizes[t] = n */ lua_pop(L, 1); /* remove `sizes' */ } } LUALIB_API int luaL_getn (lua_State *L, int t) { int n; t = abs_index(L, t); lua_pushliteral(L, "n"); /* try t.n */ lua_rawget(L, t); if ((n = checkint(L, 1)) >= 0) return n; getsizes(L); /* else try sizes[t] */ lua_pushvalue(L, t); lua_rawget(L, -2); if ((n = checkint(L, 2)) >= 0) return n; return (int)lua_objlen(L, t); } #endif /* }====================================================== */ LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p, const char *r) { const char *wild; size_t l = strlen(p); luaL_Buffer b; luaL_buffinit(L, &b); while ((wild = strstr(s, p)) != NULL) { luaL_addlstring(&b, s, wild - s); /* push prefix */ luaL_addstring(&b, r); /* push replacement in place of pattern */ s = wild + l; /* continue after `p' */ } luaL_addstring(&b, s); /* push last suffix */ luaL_pushresult(&b); return lua_tostring(L, -1); } LUALIB_API const char *luaL_findtable (lua_State *L, int idx, const char *fname, int szhint) { const char *e; lua_pushvalue(L, idx); do { e = strchr(fname, '.'); if (e == NULL) e = fname + strlen(fname); lua_pushlstring(L, fname, e - fname); lua_rawget(L, -2); if (lua_isnil(L, -1)) { /* no such field? */ lua_pop(L, 1); /* remove this nil */ lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */ lua_pushlstring(L, fname, e - fname); lua_pushvalue(L, -2); lua_settable(L, -4); /* set new table into field */ } else if (!lua_istable(L, -1)) { /* field has a non-table value? */ lua_pop(L, 2); /* remove table and value */ return fname; /* return problematic part of the name */ } lua_remove(L, -2); /* remove previous table */ fname = e + 1; } while (*e == '.'); return NULL; } /* ** {====================================================== ** Generic Buffer manipulation ** ======================================================= */ #define bufflen(B) ((B)->p - (B)->buffer) #define bufffree(B) ((size_t)(LUAL_BUFFERSIZE - bufflen(B))) #define LIMIT (LUA_MINSTACK/2) static int emptybuffer (luaL_Buffer *B) { size_t l = bufflen(B); if (l == 0) return 0; /* put nothing on stack */ else { lua_pushlstring(B->L, B->buffer, l); B->p = B->buffer; B->lvl++; return 1; } } static void adjuststack (luaL_Buffer *B) { if (B->lvl > 1) { lua_State *L = B->L; int toget = 1; /* number of levels to concat */ size_t toplen = lua_strlen(L, -1); do { size_t l = lua_strlen(L, -(toget+1)); if (B->lvl - toget + 1 >= LIMIT || toplen > l) { toplen += l; toget++; } else break; } while (toget < B->lvl); lua_concat(L, toget); B->lvl = B->lvl - toget + 1; } } LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B) { if (emptybuffer(B)) adjuststack(B); return B->buffer; } LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) { while (l--) luaL_addchar(B, *s++); } LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) { luaL_addlstring(B, s, strlen(s)); } LUALIB_API void luaL_pushresult (luaL_Buffer *B) { emptybuffer(B); lua_concat(B->L, B->lvl); B->lvl = 1; } LUALIB_API void luaL_addvalue (luaL_Buffer *B) { lua_State *L = B->L; size_t vl; const char *s = lua_tolstring(L, -1, &vl); if (vl <= bufffree(B)) { /* fit into buffer? */ memcpy(B->p, s, vl); /* put it there */ B->p += vl; lua_pop(L, 1); /* remove from stack */ } else { if (emptybuffer(B)) lua_insert(L, -2); /* put buffer before new value */ B->lvl++; /* add new value into B stack */ adjuststack(B); } } LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) { B->L = L; B->p = B->buffer; B->lvl = 0; } /* }====================================================== */ LUALIB_API int luaL_ref (lua_State *L, int t) { int ref; t = abs_index(L, t); if (lua_isnil(L, -1)) { lua_pop(L, 1); /* remove from stack */ return LUA_REFNIL; /* `nil' has a unique fixed reference */ } lua_rawgeti(L, t, FREELIST_REF); /* get first free element */ ref = (int)lua_tointeger(L, -1); /* ref = t[FREELIST_REF] */ lua_pop(L, 1); /* remove it from stack */ if (ref != 0) { /* any free element? */ lua_rawgeti(L, t, ref); /* remove it from list */ lua_rawseti(L, t, FREELIST_REF); /* (t[FREELIST_REF] = t[ref]) */ } else { /* no free elements */ ref = (int)lua_objlen(L, t); ref++; /* create new reference */ } lua_rawseti(L, t, ref); return ref; } LUALIB_API void luaL_unref (lua_State *L, int t, int ref) { if (ref >= 0) { t = abs_index(L, t); lua_rawgeti(L, t, FREELIST_REF); lua_rawseti(L, t, ref); /* t[ref] = t[FREELIST_REF] */ lua_pushinteger(L, ref); lua_rawseti(L, t, FREELIST_REF); /* t[FREELIST_REF] = ref */ } } /* ** {====================================================== ** Load functions ** ======================================================= */ typedef struct LoadF { int extraline; FILE *f; char buff[LUAL_BUFFERSIZE]; } LoadF; static const char *getF (lua_State *L, void *ud, size_t *size) { LoadF *lf = (LoadF *)ud; (void)L; if (lf->extraline) { lf->extraline = 0; *size = 1; return "\n"; } if (feof(lf->f)) return NULL; *size = fread(lf->buff, 1, LUAL_BUFFERSIZE, lf->f); return (*size > 0) ? lf->buff : NULL; } static int errfile (lua_State *L, const char *what, int fnameindex) { const char *serr = strerror(errno); const char *filename = lua_tostring(L, fnameindex) + 1; lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr); lua_remove(L, fnameindex); return LUA_ERRFILE; } LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) { LoadF lf; int status, readstatus; int c; int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */ lf.extraline = 0; if (filename == NULL) { lua_pushliteral(L, "=stdin"); lf.f = stdin; } else { lua_pushfstring(L, "@%s", filename); lf.f = fopen(filename, "r"); if (lf.f == NULL) return errfile(L, "open", fnameindex); } c = getc(lf.f); if (c == '#') { /* Unix exec. file? */ lf.extraline = 1; while ((c = getc(lf.f)) != EOF && c != '\n') ; /* skip first line */ if (c == '\n') c = getc(lf.f); } if (c == LUA_SIGNATURE[0] && lf.f != stdin) { /* binary file? */ fclose(lf.f); lf.f = fopen(filename, "rb"); /* reopen in binary mode */ if (lf.f == NULL) return errfile(L, "reopen", fnameindex); /* skip eventual `#!...' */ while ((c = getc(lf.f)) != EOF && c != LUA_SIGNATURE[0]) ; lf.extraline = 0; } ungetc(c, lf.f); status = lua_load(L, getF, &lf, lua_tostring(L, -1)); readstatus = ferror(lf.f); if (lf.f != stdin) fclose(lf.f); /* close file (even in case of errors) */ if (readstatus) { lua_settop(L, fnameindex); /* ignore results from `lua_load' */ return errfile(L, "read", fnameindex); } lua_remove(L, fnameindex); return status; } typedef struct LoadS { const char *s; size_t size; } LoadS; static const char *getS (lua_State *L, void *ud, size_t *size) { LoadS *ls = (LoadS *)ud; (void)L; if (ls->size == 0) return NULL; *size = ls->size; ls->size = 0; return ls->s; } LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t size, const char *name) { LoadS ls; ls.s = buff; ls.size = size; return lua_load(L, getS, &ls, name); } LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s) { return luaL_loadbuffer(L, s, strlen(s), s); } /* }====================================================== */ static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { (void)ud; (void)osize; if (nsize == 0) { free(ptr); return NULL; } else return realloc(ptr, nsize); } static int panic (lua_State *L) { (void)L; /* to avoid warnings */ fprintf(stderr, "PANIC: unprotected error in call to Lua API (%s)\n", lua_tostring(L, -1)); return 0; } LUALIB_API lua_State *luaL_newstate (void) { lua_State *L = lua_newstate(l_alloc, NULL); if (L) lua_atpanic(L, &panic); return L; }
{ "pile_set_name": "Github" }
 <Page x:Class="ExpenseIt.ExpenseReportPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="350" d:DesignWidth="500" Title="ExpenseIt - View Expense Report"> <Grid> <!--Templates to display expense report data--> <Grid.Resources> <!-- Reason item template --> <DataTemplate x:Key="typeItemTemplate"> <Label Content="{Binding XPath=@ExpenseType}"/> </DataTemplate> <!-- Amount item template --> <DataTemplate x:Key="amountItemTemplate"> <Label Content="{Binding XPath=@ExpenseAmount}"/> </DataTemplate> </Grid.Resources> <Grid.Background> <ImageBrush ImageSource="watermark.png" /> </Grid.Background> <Grid.ColumnDefinitions> <ColumnDefinition Width="230" /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition /> </Grid.RowDefinitions> <Label Grid.Column="1" Style="{StaticResource HeaderTextStyle}"> Expense Report For: </Label> <Grid Margin="10" Grid.Column="1" Grid.Row="1"> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition /> </Grid.RowDefinitions> <!-- Name --> <StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0" Orientation="Horizontal"> <Label Style="{StaticResource LabelStyle}">Name:</Label> <Label Style="{StaticResource LabelStyle}" Content="{Binding XPath=@Name}"></Label> </StackPanel> <!-- Department --> <StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="1" Orientation="Horizontal"> <Label Style="{StaticResource LabelStyle}">Department:</Label> <Label Style="{StaticResource LabelStyle}" Content="{Binding XPath=@Department}"></Label> </StackPanel> <Grid Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="2" VerticalAlignment="Top" HorizontalAlignment="Left"> <!-- Expense type and Amount table --> <DataGrid AutomationProperties.Name="Expense Report" ItemsSource="{Binding XPath=Expense}" ColumnHeaderStyle="{StaticResource ColumnHeaderStyle}" AutoGenerateColumns="False" RowHeaderWidth="0" > <DataGrid.Columns> <DataGridTextColumn Header="ExpenseType" Binding="{Binding XPath=@ExpenseType}" /> <DataGridTextColumn Header="Amount" Binding="{Binding XPath=@ExpenseAmount}" /> </DataGrid.Columns> </DataGrid> </Grid> </Grid> </Grid> </Page>
{ "pile_set_name": "Github" }
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var component_1 = require('../common/component'); var utils_1 = require('./utils'); function simpleTick(fn) { return setTimeout(fn, 30); } component_1.VantComponent({ props: { useSlot: Boolean, millisecond: Boolean, time: { type: Number, observer: 'reset', }, format: { type: String, value: 'HH:mm:ss', }, autoStart: { type: Boolean, value: true, }, }, data: { timeData: utils_1.parseTimeData(0), formattedTime: '0', }, destroyed: function () { clearTimeout(this.tid); this.tid = null; }, methods: { // 开始 start: function () { if (this.counting) { return; } this.counting = true; this.endTime = Date.now() + this.remain; this.tick(); }, // 暂停 pause: function () { this.counting = false; clearTimeout(this.tid); }, // 重置 reset: function () { this.pause(); this.remain = this.data.time; this.setRemain(this.remain); if (this.data.autoStart) { this.start(); } }, tick: function () { if (this.data.millisecond) { this.microTick(); } else { this.macroTick(); } }, microTick: function () { var _this = this; this.tid = simpleTick(function () { _this.setRemain(_this.getRemain()); if (_this.remain !== 0) { _this.microTick(); } }); }, macroTick: function () { var _this = this; this.tid = simpleTick(function () { var remain = _this.getRemain(); if (!utils_1.isSameSecond(remain, _this.remain) || remain === 0) { _this.setRemain(remain); } if (_this.remain !== 0) { _this.macroTick(); } }); }, getRemain: function () { return Math.max(this.endTime - Date.now(), 0); }, setRemain: function (remain) { this.remain = remain; var timeData = utils_1.parseTimeData(remain); if (this.data.useSlot) { this.$emit('change', timeData); } this.setData({ formattedTime: utils_1.parseFormat(this.data.format, timeData), }); if (remain === 0) { this.pause(); this.$emit('finish'); } }, }, });
{ "pile_set_name": "Github" }
context('test stats') test_that('fortify.stl works for AirPassengers', { fortified <- ggplot2::fortify(stats::stl(AirPassengers, s.window = 'periodic')) expect_true(is.data.frame(fortified)) expected_names <- c('Index', 'Data', 'seasonal', 'trend', 'remainder') expect_equal(names(fortified), expected_names) expect_equal(as.vector(AirPassengers), as.vector(fortified[['Data']])) expect_equal(fortified$Index[1], as.Date('1949-01-01')) expect_equal(fortified$Index[nrow(fortified)], as.Date('1960-12-01')) fortified <- ggplot2::fortify(stats::decompose(AirPassengers)) expect_true(is.data.frame(fortified)) expected_names <- c('Index', 'Data', 'seasonal', 'trend', 'remainder') expect_equal(names(fortified), expected_names) expect_equal(as.vector(AirPassengers), as.vector(fortified[['Data']])) expect_equal(fortified$Index[1], as.Date('1949-01-01')) expect_equal(fortified$Index[nrow(fortified)], as.Date('1960-12-01')) }) test_that('fortify.Arima works for AirPassengers', { skip_if_not_installed("forecast") skip_if_not_installed("fGarch") fortified <- ggplot2::fortify(ar(AirPassengers)) expect_true(is.data.frame(fortified)) expected_names <- c('Index', 'Data', 'Fitted', 'Residuals') expect_equal(names(fortified), expected_names) expect_equal(as.vector(AirPassengers), as.vector(fortified[['Data']])) expect_equal(fortified$Index[1], as.Date('1949-01-01')) expect_equal(fortified$Index[nrow(fortified)], as.Date('1960-12-01')) x <- AirPassengers m <- stats::ar(x) # create model with temporary variable x <- NULL fortified2 <- ggplot2::fortify(m, data = AirPassengers) expect_equal(fortified, fortified2) ggplot2::autoplot(m, data = AirPassengers) fortified <- ggplot2::fortify(stats::arima(AirPassengers)) expect_true(is.data.frame(fortified)) expected_names <- c('Index', 'Data', 'Fitted', 'Residuals') expect_equal(names(fortified), expected_names) expect_equal(as.vector(AirPassengers), as.vector(fortified[['Data']])) expect_equal(fortified$Index[1], as.Date('1949-01-01')) expect_equal(fortified$Index[nrow(fortified)], as.Date('1960-12-01')) ggplot2::autoplot(stats::arima(AirPassengers)) x <- AirPassengers m <- stats::arima(x) # create model with temporary variable x <- NULL fortified2 <- ggplot2::fortify(m, data = AirPassengers) expect_equal(fortified, fortified2) ggplot2::autoplot(m, data = AirPassengers) fortified <- ggplot2::fortify(stats::HoltWinters(AirPassengers)) expect_true(is.data.frame(fortified)) expected_names <- c('Index', 'Data', 'xhat', 'level', 'trend', 'season', 'Residuals') expect_equal(names(fortified), expected_names) expect_equal(as.vector(AirPassengers), as.vector(fortified[['Data']])) expect_equal(fortified$Index[1], as.Date('1949-01-01')) expect_equal(fortified$Index[nrow(fortified)], as.Date('1960-12-01')) library(fGarch) d.fGarch <- fGarch::garchFit(formula = ~arma(1, 1) + garch(1, 1), data = UKgas, trace = FALSE) fortified <- ggplot2::fortify(d.fGarch) expected_names <- c('Index', 'Data', 'Fitted', 'Residuals') expect_equal(names(fortified), expected_names) }) test_that('fortify.prcomp works for iris', { df <- iris[c(1, 2, 3, 4)] pcs <- c('PC1', 'PC2', 'PC3', 'PC4') expected_names <- c(names(df), pcs) fortified <- ggplot2::fortify(stats::prcomp(df, center = TRUE, scale = TRUE)) expect_true(is.data.frame(fortified)) expect_equal(names(fortified), expected_names) expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), df) expect_equal(rownames(fortified), rownames(df)) fortified <- ggplot2::fortify(stats::prcomp(df, center = FALSE, scale = TRUE)) expect_true(is.data.frame(fortified)) expect_equal(names(fortified), expected_names) expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), df) expect_equal(rownames(fortified), rownames(df)) fortified <- ggplot2::fortify(stats::prcomp(df, center = TRUE, scale = FALSE)) expect_true(is.data.frame(fortified)) expect_equal(names(fortified), expected_names) expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), df) expect_equal(rownames(fortified), rownames(df)) fortified <- ggplot2::fortify(stats::prcomp(df, center = FALSE, scale = FALSE)) expect_true(is.data.frame(fortified)) expect_equal(names(fortified), expected_names) expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), df) expect_equal(rownames(fortified), rownames(df)) # attach original expected_names <- c(names(df), 'Species', pcs) fortified <- ggplot2::fortify(stats::prcomp(df), data = iris) expect_true(is.data.frame(fortified)) expect_equal(names(fortified), expected_names) expect_equal(data.frame(fortified[c(1, 2, 3, 4, 5)]), iris) expect_equal(rownames(fortified), rownames(df)) tmp <- stats::prcomp(df) class(tmp) <- 'unsupportedClass' expect_error(ggplot2::fortify(tmp, data = iris)) }) test_that('fortify.princomp works for iris', { df <- iris[c(1, 2, 3, 4)] pcs <- c('Comp.1', 'Comp.2', 'Comp.3', 'Comp.4') expected_names <- c(names(df), pcs) fortified <- ggplot2::fortify(stats::princomp(df)) expect_true(is.data.frame(fortified)) expect_equal(names(fortified), expected_names) expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), df) expect_equal(rownames(fortified), rownames(df)) # attach original expected_names <- c(names(df), 'Species', pcs) fortified <- ggplot2::fortify(stats::princomp(df), data = iris) expect_true(is.data.frame(fortified)) expect_equal(names(fortified), expected_names) expect_equal(data.frame(fortified[c(1, 2, 3, 4, 5)]), iris) expect_equal(rownames(fortified), rownames(df)) p <- ggplot2::autoplot(stats::princomp(df), data = iris, colour = 'Species') expect_true(is(p, 'ggplot')) p <- ggplot2::autoplot(stats::princomp(df), data = iris, loadings.label = TRUE) expect_true(is(p, 'ggplot')) p <- ggplot2::autoplot(stats::princomp(df), data = iris, frame.type = 'convex') expect_true(is(p, 'ggplot')) expect_error(ggplot2::autoplot(stats::princomp(df), frame.type = 'invalid')) }) test_that('fortify.factanal works for state.x77', { d.factanal <- stats::factanal(state.x77, factors = 3, scores = 'regression') pcs <- c('Factor1', 'Factor2', 'Factor3') fortified <- ggplot2::fortify(d.factanal) expect_true(is.data.frame(fortified)) expect_equal(names(fortified), pcs) expect_equal(rownames(fortified), rownames(state.x77)) # attach original fortified <- ggplot2::fortify(d.factanal, data = state.x77) expect_true(is.data.frame(fortified)) expect_equal(names(fortified), c(colnames(state.x77), pcs)) expect_equal(rownames(fortified), rownames(state.x77)) }) test_that('fortify.prcomp works for USArrests', { pcs <- c('PC1', 'PC2', 'PC3', 'PC4') expected_names <- c(names(USArrests), pcs) fortified <- ggplot2::fortify(stats::prcomp(USArrests, center = TRUE, scale = TRUE)) expect_true(is.data.frame(fortified)) expect_equal(names(fortified), expected_names) expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), USArrests) expect_equal(rownames(fortified), rownames(USArrests)) fortified <- ggplot2::fortify(stats::prcomp(USArrests, center = FALSE, scale = TRUE)) expect_true(is.data.frame(fortified)) expect_equal(names(fortified), expected_names) expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), USArrests) expect_equal(rownames(fortified), rownames(USArrests)) fortified <- ggplot2::fortify(stats::prcomp(USArrests, center = TRUE, scale = FALSE)) expect_true(is.data.frame(fortified)) expect_equal(names(fortified), expected_names) expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), USArrests) expect_equal(rownames(fortified), rownames(USArrests)) fortified <- ggplot2::fortify(stats::prcomp(USArrests, center = FALSE, scale = FALSE)) expect_true(is.data.frame(fortified)) expect_equal(names(fortified), expected_names) expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), USArrests) expect_equal(rownames(fortified), rownames(USArrests)) # attach original fortified <- ggplot2::fortify(stats::prcomp(USArrests), data = USArrests) expect_true(is.data.frame(fortified)) expect_equal(names(fortified), expected_names) expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), USArrests) expect_equal(rownames(fortified), rownames(USArrests)) }) test_that('fortify.princomp works for USArrests', { pcs <- c('Comp.1', 'Comp.2', 'Comp.3', 'Comp.4') expected_names <- c(names(USArrests), pcs) fortified <- ggplot2::fortify(stats::princomp(USArrests)) expect_true(is.data.frame(fortified)) expect_equal(names(fortified), expected_names) expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), USArrests) expect_equal(rownames(fortified), rownames(USArrests)) # attach original fortified <- ggplot2::fortify(stats::princomp(USArrests), data = USArrests) expect_true(is.data.frame(fortified)) expect_equal(names(fortified), expected_names) expect_equal(data.frame(fortified[c(1, 2, 3, 4)]), USArrests) expect_equal(rownames(fortified), rownames(USArrests)) }) test_that('autoplot.prcomp works for iris with scale (default)', { # fails on CRAN i386 because components are inversed. skip_on_cran() obj <- stats::prcomp(iris[-5]) exp_x <- c(-0.10658039, -0.10777226, -0.11471510, -0.10901118, -0.10835099, -0.09056763) exp_y <- c(-0.05293913, 0.02933742, 0.02402493, 0.05275710, -0.05415858, -0.12287329) p <- ggplot2::autoplot(obj) expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 1) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) ld <- head(ggplot2:::layer_data(p, 1)) expect_equal(ld$x, exp_x, tolerance = 1e-4) expect_equal(ld$y, exp_y, tolerance = 1e-4) expect_equal(ld$colour, rep('black', 6)) p <- ggplot2::autoplot(obj, data = iris, colour = 'Species') expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 1) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) ld <- head(ggplot2:::layer_data(p, 1)) expect_equal(ld$x, exp_x, tolerance = 1e-4) expect_equal(ld$y, exp_y, tolerance = 1e-4) expect_equal(ld$colour, rep("#F8766D", 6)) p <- ggplot2::autoplot(obj, data = iris, loadings = TRUE, loadings.label = FALSE) expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 2) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) expect_true('GeomSegment' %in% class(p$layers[[2]]$geom)) ld <- head(ggplot2:::layer_data(p, 1)) expect_equal(ld$x, exp_x, tolerance = 1e-4) expect_equal(ld$y, exp_y, tolerance = 1e-4) expect_equal(ld$colour, rep("black", 6)) ld <- ggplot2:::layer_data(p, 2) expect_equal(ld$x, rep(0, 4), tolerance = 1e-4) expect_equal(ld$xend, c(0.05086374, -0.01189621, 0.12057301, 0.05042779), tolerance = 1e-4) expect_equal(ld$y, rep(0, 4), tolerance = 1e-4) expect_equal(ld$colour, rep("#FF0000", 4)) p <- ggplot2::autoplot(obj, data = iris, loadings.label = TRUE) expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 3) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) expect_true('GeomSegment' %in% class(p$layers[[2]]$geom)) expect_true('GeomText' %in% class(p$layers[[3]]$geom)) ld <- head(ggplot2:::layer_data(p, 1)) expect_equal(ld$x, exp_x, tolerance = 1e-4) expect_equal(ld$y, exp_y, tolerance = 1e-4) expect_equal(ld$colour, rep("black", 6)) ld <- ggplot2:::layer_data(p, 2) expect_equal(ld$x, rep(0, 4), tolerance = 1e-4) expect_equal(ld$xend, c(0.05086374, -0.01189621, 0.12057301, 0.05042779), tolerance = 1e-4) expect_equal(ld$y, rep(0, 4)) expect_equal(ld$colour, rep("#FF0000", 4)) ld <- ggplot2:::layer_data(p, 3) expect_equal(ld$x, c(0.05086374, -0.01189621, 0.12057301, 0.05042779), tolerance = 1e-4) expect_equal(ld$y, c(-0.09241228, -0.10276734, 0.02440152, 0.01062366), tolerance = 1e-4) expect_equal(ld$colour, rep("#FF0000", 4)) expect_equal(ld$label, c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")) p <- ggplot2::autoplot(obj, data = iris, frame.type = 'convex') expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 2) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) expect_true('GeomPolygon' %in% class(p$layers[[2]]$geom)) ld <- head(ggplot2:::layer_data(p, 1)) expect_equal(ld$x, exp_x, tolerance = 1e-4) expect_equal(ld$y, exp_y, tolerance = 1e-4) expect_equal(ld$colour, rep("black", 6)) ld <- head(ggplot2:::layer_data(p, 2)) expect_equal(ld$x, c(0.15071626, 0.13846286, 0.12828254, -0.09474406, -0.10501689, -0.12769748), tolerance = 1e-4) expect_equal(ld$y, c(-0.04265051, -0.19487526, -0.22776373, -0.22177981, -0.19537669, -0.02212193), tolerance = 1e-4) expect_equal(ld$fill, rep("grey20", 6)) expect_equal(ld$alpha, rep(0.2, 6)) p <- ggplot2::autoplot(obj, data = iris, frame.type = 'convex', shape = FALSE) expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 2) # label will be turned on expect_true('GeomText' %in% class(p$layers[[1]]$geom)) expect_true('GeomPolygon' %in% class(p$layers[[2]]$geom)) ld <- head(ggplot2:::layer_data(p, 1)) expect_equal(ld$x, exp_x, tolerance = 1e-4) expect_equal(ld$y, exp_y, tolerance = 1e-4) expect_equal(ld$colour, rep("#000000", 6)) expect_equal(ld$label, c('1', '2', '3', '4', '5', '6')) ld <- head(ggplot2:::layer_data(p, 2)) expect_equal(ld$x, c(0.15071626, 0.13846286, 0.12828254, -0.09474406, -0.10501689, -0.12769748), tolerance = 1e-4) expect_equal(ld$y, c(-0.04265051, -0.19487526, -0.22776373, -0.22177981, -0.19537669, -0.02212193), tolerance = 1e-4) expect_equal(ld$fill, rep("grey20", 6)) expect_equal(ld$alpha, rep(0.2, 6)) }) test_that('autoplot.prcomp works for iris without scale', { # fails on CRAN i386 because components are inversed. skip_on_cran() obj <- stats::prcomp(iris[-5]) exp_x <- c(-2.684126, -2.714142, -2.888991, -2.745343, -2.728717, -2.280860) exp_y <- c(-0.3193972, 0.1770012, 0.1449494, 0.3182990, -0.3267545, -0.7413304) p <- ggplot2::autoplot(obj, scale = 0.) expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 1) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) ld <- head(ggplot2:::layer_data(p, 1)) expect_equal(ld$x, exp_x, tolerance = 1e-4) expect_equal(ld$y, exp_y, tolerance = 1e-4) expect_equal(ld$colour, rep('black', 6)) p <- ggplot2::autoplot(obj, scale = 0., data = iris, colour = 'Species') expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 1) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) ld <- head(ggplot2:::layer_data(p, 1)) expect_equal(ld$x, exp_x, tolerance = 1e-4) expect_equal(ld$y, exp_y, tolerance = 1e-4) expect_equal(ld$colour, rep("#F8766D", 6)) p <- ggplot2::autoplot(obj, scale = 0, data = iris, loadings = TRUE, loadings.label = FALSE) expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 2) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) expect_true('GeomSegment' %in% class(p$layers[[2]]$geom)) ld <- head(ggplot2:::layer_data(p, 1)) expect_equal(ld$x, exp_x, tolerance = 1e-4) expect_equal(ld$y, exp_y, tolerance = 1e-4) expect_equal(ld$colour, rep("black", 6)) ld <- ggplot2:::layer_data(p, 2) expect_equal(ld$x, rep(0, 4), tolerance = 1e-4) expect_equal(ld$xend, c(0.5441042, -0.1272572, 1.2898045, 0.5394407), tolerance = 1e-4) expect_equal(ld$y, rep(0, 4), tolerance = 1e-4) expect_equal(ld$colour, rep("#FF0000", 4)) p <- ggplot2::autoplot(obj, scale = 0., data = iris, loadings.label = TRUE) expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 3) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) expect_true('GeomSegment' %in% class(p$layers[[2]]$geom)) expect_true('GeomText' %in% class(p$layers[[3]]$geom)) ld <- head(ggplot2:::layer_data(p, 1)) expect_equal(ld$x, exp_x, tolerance = 1e-4) expect_equal(ld$y, exp_y, tolerance = 1e-4) expect_equal(ld$colour, rep("black", 6)) ld <- ggplot2:::layer_data(p, 2) expect_equal(ld$x, rep(0, 4), tolerance = 1e-4) expect_equal(ld$xend, c(0.5441042, -0.1272572, 1.2898045, 0.5394407), tolerance = 1e-4) expect_equal(ld$y, rep(0, 4)) expect_equal(ld$colour, rep("#FF0000", 4)) ld <- ggplot2:::layer_data(p, 3) expect_equal(ld$x, c(0.5441042, -0.1272572, 1.2898045, 0.5394407), tolerance = 1e-4) expect_equal(ld$y, c(-0.9885610, -1.0993321, 0.2610301, 0.1136443), tolerance = 1e-4) expect_equal(ld$colour, rep("#FF0000", 4)) expect_equal(ld$label, c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")) p <- ggplot2::autoplot(obj, scale = 0., data = iris, frame.type = 'convex') expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 2) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) expect_true('GeomPolygon' %in% class(p$layers[[2]]$geom)) ld <- head(ggplot2:::layer_data(p, 1)) expect_equal(ld$x, exp_x, tolerance = 1e-4) expect_equal(ld$y, exp_y, tolerance = 1e-4) expect_equal(ld$colour, rep("black", 6)) ld <- head(ggplot2:::layer_data(p, 2)) expect_equal(ld$x, c(3.795645, 3.487055, 3.230674, -2.386039, -2.644750, -3.215939), tolerance = 1e-4) expect_equal(ld$y, c(-0.2573230, -1.1757393, -1.3741651, -1.3380623, -1.1787646, -0.1334681), tolerance = 1e-4) expect_equal(ld$fill, rep("grey20", 6)) expect_equal(ld$alpha, rep(0.2, 6)) p <- ggplot2::autoplot(obj, scale = 0., data = iris, frame.type = 'convex', shape = FALSE) expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 2) # label will be turned on expect_true('GeomText' %in% class(p$layers[[1]]$geom)) expect_true('GeomPolygon' %in% class(p$layers[[2]]$geom)) ld <- head(ggplot2:::layer_data(p, 1)) expect_equal(ld$x, exp_x, tolerance = 1e-4) expect_equal(ld$y, exp_y, tolerance = 1e-4) expect_equal(ld$colour, rep("#000000", 6)) expect_equal(ld$label, c('1', '2', '3', '4', '5', '6')) ld <- head(ggplot2:::layer_data(p, 2)) expect_equal(ld$x, c(3.795645, 3.487055, 3.230674, -2.386039, -2.644750, -3.215939), tolerance = 1e-4) expect_equal(ld$y, c(-0.2573230, -1.1757393, -1.3741651, -1.3380623, -1.1787646, -0.1334681), tolerance = 1e-4) expect_equal(ld$fill, rep("grey20", 6)) expect_equal(ld$alpha, rep(0.2, 6)) }) test_that('autoplot.prcomp works for USArrests', { # fails on CRAN SPARC because components are inversed. skip_on_cran() obj <- stats::prcomp(USArrests) # scale exp_x <- c(0.10944879, 0.15678261, 0.20954726, 0.03097574, 0.18143395, 0.05907333) exp_y <- c(-0.11391408, -0.17894035, 0.08786745, -0.16621327, 0.22408730, 0.13651754) p <- ggplot2::autoplot(obj, label = TRUE) expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 2) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) expect_true('GeomText' %in% class(p$layers[[2]]$geom)) ld <- head(ggplot2:::layer_data(p, 1)) expect_equal(ld$x, exp_x, tolerance = 1e-4) expect_equal(ld$y, exp_y, tolerance = 1e-4) expect_equal(ld$colour, rep("black", 6)) ld <- head(ggplot2:::layer_data(p, 2)) expect_equal(ld$x, exp_x, tolerance = 1e-4) expect_equal(ld$y, exp_y, tolerance = 1e-4) expect_equal(ld$label, c("Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado")) expect_equal(ld$colour, rep("#000000", 6)) # not scale exp_x <- c(64.80216, 92.82745, 124.06822, 18.34004, 107.42295, 34.97599) exp_y <- c(-11.448007, -17.982943, 8.830403, -16.703911, 22.520070, 13.719584) p <- ggplot2::autoplot(obj, scale = 0., label = TRUE) expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 2) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) expect_true('GeomText' %in% class(p$layers[[2]]$geom)) ld <- head(ggplot2:::layer_data(p, 1)) expect_equal(ld$x, exp_x, tolerance = 1e-4) expect_equal(ld$y, exp_y, tolerance = 1e-4) expect_equal(ld$colour, rep("black", 6)) ld <- head(ggplot2:::layer_data(p, 2)) expect_equal(ld$x, exp_x, tolerance = 1e-4) expect_equal(ld$y, exp_y, tolerance = 1e-4) expect_equal(ld$label, c("Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado")) expect_equal(ld$colour, rep("#000000", 6)) }) test_that('autoplot.princomp works for iris', { obj <- stats::princomp(iris[-5]) p <- ggplot2::autoplot(obj, data = iris, colour = 'Species') expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 1) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) p <- ggplot2::autoplot(obj, data = iris, loadings = TRUE, loadings.label = FALSE) expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 2) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) expect_true('GeomSegment' %in% class(p$layers[[2]]$geom)) p <- ggplot2::autoplot(obj, data = iris, loadings.label = TRUE) expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 3) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) expect_true('GeomSegment' %in% class(p$layers[[2]]$geom)) expect_true('GeomText' %in% class(p$layers[[3]]$geom)) p <- ggplot2::autoplot(obj, data = iris, frame.type = 'convex') expect_true(is(p, 'ggplot')) expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 2) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) expect_true('GeomPolygon' %in% class(p$layers[[2]]$geom)) }) test_that('autoplot.prcomp plots the desired components', { # fails on CRAN SPARC because components are inversed. skip_on_cran() obj <- stats::prcomp(iris[-5]) exp_x <- c(-0.0529391329513015, 0.0293374206773287, 0.0240249314006331, 0.0527570984441502, -0.0541585777198945, -0.1228732921883) exp_y <- c(0.00815003672083961, 0.0614473273321588, -0.00522617400592586, -0.00921410146450414, -0.0262996114135432, -0.0492472720451544 ) p <- ggplot2::autoplot(obj, x = 2, y = 3) expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 1) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) ld <- head(ggplot2:::layer_data(p, 1)) expect_equal(ld$x, exp_x, tolerance = 1e-4) expect_equal(ld$y, exp_y, tolerance = 1e-4) expect_equal(ld$colour, rep('black', 6)) expect_equal(p$labels$x, "PC2 (5.31%)") expect_equal(p$labels$y, "PC3 (1.71%)") }) test_that('autoplot.princomp plots the desired components', { # fails on CRAN and Travis because components are inversed. skip_on_travis() skip_on_cran() obj <- stats::princomp(iris[-5]) exp_x <- c(-0.0531164839772263, 0.0294357037689672, 0.0241054171584106, 0.052933839637522, -0.0543400139993682, -0.123284929161055) exp_y <- c(-0.00817734010291634, -0.0616531816016784, 0.00524368217559065, 0.00924496956257505, 0.0263877175612184, 0.0494122549931978) p <- ggplot2::autoplot(obj, x = 2, y = 3) expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 1) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) ld <- head(ggplot2:::layer_data(p, 1)) # expect_equal(ld$x, exp_x, tolerance = 1e-4) # expect_equal(ld$y, exp_y, tolerance = 1e-4) expect_equal(ld$colour, rep('black', 6)) expect_equal(p$labels$x, "Comp.2 (5.31%)") expect_equal(p$labels$y, "Comp.3 (1.71%)") }) test_that('autoplot.factanal works for state.x77', { obj <- stats::factanal(state.x77, factors = 3, scores = 'regression') p <- ggplot2::autoplot(obj) expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 1) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) p <- ggplot2::autoplot(obj, label = TRUE) expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 2) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) expect_true('GeomText' %in% class(p$layers[[2]]$geom)) }) test_that('autoplot.factanal plots the desired components', { obj <- stats::factanal(state.x77, factors = 3, scores = 'regression') p <- ggplot2::autoplot(obj, x = 2, y = 3) expect_true(is(p, 'ggplot')) expect_equal(length(p$layers), 1) expect_true('GeomPoint' %in% class(p$layers[[1]]$geom)) expect_equal(p$labels$x, "Factor2 (20.15%)") expect_equal(p$labels$y, "Factor3 (18.24%)") }) test_that('fortify.dist works for eurodist', { fortified <- ggplot2::fortify(eurodist) expect_true(is.data.frame(fortified)) expect_equal(dim(fortified), c(21, 21)) }) test_that('fortify.lfda works for iris', { skip_on_cran() library(lfda) k <- iris[, -5] y <- iris[, 5] r <- 3 model <- lfda(k, y, r, metric = "plain") fortified <- ggplot2::fortify(model) expect_true(is.data.frame(fortified)) model <- klfda(kmatrixGauss(k), y, r, metric = "plain") fortified <- ggplot2::fortify(model) expect_true(is.data.frame(fortified)) model <- self(k, y, beta=0.1, r, metric = "plain") fortified <- ggplot2::fortify(model) expect_true(is.data.frame(fortified)) }) test_that('autoplot.lfda works for iris', { skip_on_cran() k <- iris[, -5] y <- iris[, 5] r <- 4 model <- lfda::lfda(k, y, r, metric = "plain") p <- autoplot(model, data=iris, frame = TRUE, frame.colour='Species') expect_true(is(p, 'ggplot')) }) test_that('autoplot.acf works', { p <- autoplot(stats::acf(AirPassengers, plot = FALSE)) expect_true(is(p, 'ggplot')) p <- autoplot(stats::acf(AirPassengers, plot = FALSE), conf.int.type = 'ma') expect_true(is(p, 'ggplot')) p <- autoplot(stats::pacf(AirPassengers, plot = FALSE)) expect_true(is(p, 'ggplot')) p <- autoplot(stats::ccf(AirPassengers, AirPassengers, plot = FALSE)) expect_true(is(p, 'ggplot')) }) test_that('autoplot.stepfun works', { p <- autoplot(stepfun(c(1, 2, 3), c(4, 5, 6, 7))) expect_true(is(p, 'ggplot')) fortified <- fortify(stepfun(c(1, 2, 3), c(4, 5, 6, 7))) expected <- data.frame(x = c(0, 1, 1, 2, 2, 3, 3, 4), y = c(4, 4, 5, 5, 6, 6, 7, 7)) expect_equal(fortified, expected) fortified <- fortify(stepfun(c(1), c(4, 5))) expected <- data.frame(x = c(0.9375, 1.0000, 1.0000, 1.0625), y = c(4, 4, 5, 5)) expect_equal(fortified, expected) fortified <- fortify(stepfun(c(1, 3, 4, 8), c(4, 5, 2, 3, 5))) expected <- data.frame(x = c(-1, 1, 1, 3, 3, 4, 4, 8, 8, 10), y = c(4, 4, 5, 5, 2, 2, 3, 3, 5, 5)) expect_equal(fortified, expected) fortified <- fortify(stepfun(c(1, 2, 3, 4, 5, 6, 7, 8, 10), c(4, 5, 6, 7, 8, 9, 10, 11, 12, 9))) expected <- data.frame(x = c(0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 10, 10, 11), y = c(4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 9, 9)) expect_equal(fortified, expected) }) test_that('autoplot.spec works', { result <- stats::spec.ar(AirPassengers) p <- autoplot(result) expect_true(is(p, 'ggplot')) expect_equal(sum(fortify(result)[1]), 1500, tolerance = 0.01) expect_equal(sum(fortify(result)[2]), 684799.7, tolerance = 0.01) })
{ "pile_set_name": "Github" }
--- name: Bug Report about: Report a bug or regression in functionality --- <!-- ❤️ ngrx? Please consider supporting our collective: 👉 [donate](https://opencollective.com/ngrx/donate) --> <!-- Please search GitHub for a similar issue or PR before submitting a new issue--> ## Minimal reproduction of the bug/regression with instructions: <!-- Use the following StackBlitz example to create a reproduction: https://stackblitz.com/edit/ngrx-seed --> <!-- If the bug/regression does not include a reproduction via StackBlitz or GitHub repo, your issue may be closed without resolution. --> ## Expected behavior: <!-- Describe what the expected behavior would be. --> ## Versions of NgRx, Angular, Node, affected browser(s) and operating system(s): ## Other information: ## I would be willing to submit a PR to fix this issue [ ] Yes (Assistance is provided if you need help submitting a pull request) [ ] No
{ "pile_set_name": "Github" }
--TEST-- Regular Expression type: regex with slash --DESCRIPTION-- Generated by scripts/convert-bson-corpus-tests.php DO NOT EDIT THIS FILE --FILE-- <?php require_once __DIR__ . '/../utils/tools.php'; $canonicalBson = hex2bin('110000000B610061622F636400696D0000'); $canonicalExtJson = '{"a" : {"$regularExpression" : { "pattern": "ab/cd", "options" : "im"}}}'; // Canonical BSON -> Native -> Canonical BSON echo bin2hex(fromPHP(toPHP($canonicalBson))), "\n"; // Canonical BSON -> Canonical extJSON echo json_canonicalize(toCanonicalExtendedJSON($canonicalBson)), "\n"; // Canonical extJSON -> Canonical BSON echo bin2hex(fromJSON($canonicalExtJson)), "\n"; ?> ===DONE=== <?php exit(0); ?> --EXPECT-- 110000000b610061622f636400696d0000 {"a":{"$regularExpression":{"pattern":"ab\/cd","options":"im"}}} 110000000b610061622f636400696d0000 ===DONE===
{ "pile_set_name": "Github" }
// This file is provided under The MIT License as part of Steamworks.NET. // Copyright (c) 2013-2019 Riley Labrecque // Please see the included LICENSE.txt for additional information. // This file is automatically generated. // Changes to this file will be reverted when you update Steamworks.NET #if UNITY_ANDROID || UNITY_IOS || UNITY_TIZEN || UNITY_TVOS || UNITY_WEBGL || UNITY_WSA || UNITY_PS4 || UNITY_WII || UNITY_XBOXONE || UNITY_SWITCH #define DISABLESTEAMWORKS #endif #if !DISABLESTEAMWORKS using System.Runtime.InteropServices; using IntPtr = System.IntPtr; #endif // !DISABLESTEAMWORKS // This file is no longer needed. Valve has removed the functionality. // We continue to generate this file to provide a small amount of backwards compatability.
{ "pile_set_name": "Github" }
package ledis import ( "encoding/binary" "errors" "sync" "time" "github.com/ledisdb/ledisdb/store" ) var ( errExpMetaKey = errors.New("invalid expire meta key") errExpTimeKey = errors.New("invalid expire time key") ) type onExpired func(*batch, []byte) int64 type ttlChecker struct { sync.Mutex db *DB txs []*batch cbs []onExpired //next check time nc int64 } var errExpType = errors.New("invalid expire type") func (db *DB) expEncodeTimeKey(dataType byte, key []byte, when int64) []byte { buf := make([]byte, len(key)+10+len(db.indexVarBuf)) pos := copy(buf, db.indexVarBuf) buf[pos] = ExpTimeType pos++ binary.BigEndian.PutUint64(buf[pos:], uint64(when)) pos += 8 buf[pos] = dataType pos++ copy(buf[pos:], key) return buf } func (db *DB) expEncodeMetaKey(dataType byte, key []byte) []byte { buf := make([]byte, len(key)+2+len(db.indexVarBuf)) pos := copy(buf, db.indexVarBuf) buf[pos] = ExpMetaType pos++ buf[pos] = dataType pos++ copy(buf[pos:], key) return buf } func (db *DB) expDecodeMetaKey(mk []byte) (byte, []byte, error) { pos, err := db.checkKeyIndex(mk) if err != nil { return 0, nil, err } if pos+2 > len(mk) || mk[pos] != ExpMetaType { return 0, nil, errExpMetaKey } return mk[pos+1], mk[pos+2:], nil } func (db *DB) expDecodeTimeKey(tk []byte) (byte, []byte, int64, error) { pos, err := db.checkKeyIndex(tk) if err != nil { return 0, nil, 0, err } if pos+10 > len(tk) || tk[pos] != ExpTimeType { return 0, nil, 0, errExpTimeKey } return tk[pos+9], tk[pos+10:], int64(binary.BigEndian.Uint64(tk[pos+1:])), nil } func (db *DB) expire(t *batch, dataType byte, key []byte, duration int64) { db.expireAt(t, dataType, key, time.Now().Unix()+duration) } func (db *DB) expireAt(t *batch, dataType byte, key []byte, when int64) { mk := db.expEncodeMetaKey(dataType, key) tk := db.expEncodeTimeKey(dataType, key, when) t.Put(tk, mk) t.Put(mk, PutInt64(when)) db.ttlChecker.setNextCheckTime(when, false) } func (db *DB) ttl(dataType byte, key []byte) (t int64, err error) { mk := db.expEncodeMetaKey(dataType, key) if t, err = Int64(db.bucket.Get(mk)); err != nil || t == 0 { t = -1 } else { t -= time.Now().Unix() if t <= 0 { t = -1 } // if t == -1 : to remove ???? } return t, err } func (db *DB) rmExpire(t *batch, dataType byte, key []byte) (int64, error) { mk := db.expEncodeMetaKey(dataType, key) v, err := db.bucket.Get(mk) if err != nil { return 0, err } else if v == nil { return 0, nil } when, err2 := Int64(v, nil) if err2 != nil { return 0, err2 } tk := db.expEncodeTimeKey(dataType, key, when) t.Delete(mk) t.Delete(tk) return 1, nil } func (c *ttlChecker) register(dataType byte, t *batch, f onExpired) { c.txs[dataType] = t c.cbs[dataType] = f } func (c *ttlChecker) setNextCheckTime(when int64, force bool) { c.Lock() if force { c.nc = when } else if c.nc > when { c.nc = when } c.Unlock() } func (c *ttlChecker) check() { now := time.Now().Unix() c.Lock() nc := c.nc c.Unlock() if now < nc { return } nc = now + 3600 db := c.db dbGet := db.bucket.Get minKey := db.expEncodeTimeKey(NoneType, nil, 0) maxKey := db.expEncodeTimeKey(maxDataType, nil, nc) it := db.bucket.RangeLimitIterator(minKey, maxKey, store.RangeROpen, 0, -1) for ; it.Valid(); it.Next() { tk := it.RawKey() mk := it.RawValue() dt, k, nt, err := db.expDecodeTimeKey(tk) if err != nil { continue } if nt > now { //the next ttl check time is nt! nc = nt break } t := c.txs[dt] cb := c.cbs[dt] if tk == nil || cb == nil { continue } t.Lock() if exp, err := Int64(dbGet(mk)); err == nil { // check expire again if exp <= now { cb(t, k) t.Delete(tk) t.Delete(mk) t.Commit() } } t.Unlock() } it.Close() c.setNextCheckTime(nc, true) return }
{ "pile_set_name": "Github" }
object ExampleTrainerStyle3: TExampleTrainerStyle3 Left = 992 Top = 687 BorderIcons = [] BorderStyle = bsNone Caption = 'ExampleTrainerStyle3' ClientHeight = 280 ClientWidth = 280 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False Position = poScreenCenter OnShow = FormShow PixelsPerInch = 96 TextHeight = 13 object Image1: TImage Left = 0 Top = 0 Width = 280 Height = 280 end object Image6: TImage Left = 272 Top = 248 Width = 9 Height = 25 OnMouseMove = Image6MouseMove end object Image5: TImage Left = 248 Top = 272 Width = 33 Height = 9 OnMouseMove = Image5MouseMove end object Image3: TImage Left = 0 Top = 0 Width = 281 Height = 249 OnMouseMove = Image3MouseMove end object Image4: TImage Left = 0 Top = 248 Width = 249 Height = 33 OnMouseMove = Image4MouseMove end object Label1: TLabel Left = 8 Top = 216 Width = 35 Height = 13 Caption = 'Label1t' Transparent = True OnMouseMove = Image3MouseMove end object Image2: TImage Left = 248 Top = 248 Width = 25 Height = 25 Cursor = crHandPoint Hint = 'This marks the location where the user has to click to exit the ' + 'trainer' ParentShowHint = False ShowHint = True Stretch = True Transparent = True OnClick = Image2Click end object CheckListBox1: TCheckListBox Left = 40 Top = 16 Width = 201 Height = 193 ItemHeight = 13 TabOrder = 0 end end
{ "pile_set_name": "Github" }
<!DOCTYPE html> <!--[if IE]><![endif]--> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Class UniqueItemsKeyword </title> <meta name="viewport" content="width=device-width"> <meta name="title" content="Class UniqueItemsKeyword "> <meta name="generator" content="docfx 2.43.2.0"> <link rel="shortcut icon" href="../favicon.ico"> <link rel="stylesheet" href="../styles/docfx.vendor.css"> <link rel="stylesheet" href="../styles/docfx.css"> <link rel="stylesheet" href="../styles/main.css"> <meta property="docfx:navrel" content="../toc.html"> <meta property="docfx:tocrel" content="toc.html"> </head> <body data-spy="scroll" data-target="#affix" data-offset="120"> <div id="wrapper"> <header> <nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../index.html"> <img id="logo" class="svg site-icon" src="../siteicon.png" alt=""> </a> </div> <div class="collapse navbar-collapse" id="navbar"> <form class="navbar-form navbar-right" role="search" id="search"> <div class="form-group"> <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off"> </div> </form> </div> </div> </nav> <div class="subnav navbar navbar-default"> <div class="container hide-when-search" id="breadcrumb"> <ul class="breadcrumb"> <li></li> </ul> </div> </div> </header> <div role="main" class="container body-content hide-when-search"> <div class="sidenav hide-when-search"> <a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a> <div class="sidetoggle collapse" id="sidetoggle"> <div id="sidetoc"></div> </div> </div> <div class="article row grid-right"> <div class="col-md-10"> <article class="content wrap" id="_content" data-uid="Manatee.Json.Schema.UniqueItemsKeyword"> <h1 id="Manatee_Json_Schema_UniqueItemsKeyword" data-uid="Manatee.Json.Schema.UniqueItemsKeyword" class="text-break">Class UniqueItemsKeyword </h1> <div class="markdown level0 summary"><p>Defines the <code>uniqueItems</code> JSON Schema keyword.</p> </div> <div class="markdown level0 conceptual"></div> <div class="inheritance"> <h5>Inheritance</h5> <div class="level0"><span class="xref">System.Object</span></div> <div class="level1"><span class="xref">UniqueItemsKeyword</span></div> </div> <div classs="implements"> <h5>Implements</h5> <div><a class="xref" href="Manatee.Json.Schema.IJsonSchemaKeyword.html">IJsonSchemaKeyword</a></div> <div><a class="xref" href="Manatee.Json.Serialization.IJsonSerializable.html">IJsonSerializable</a></div> <div><span class="xref">System.IEquatable</span>&lt;<a class="xref" href="Manatee.Json.Schema.IJsonSchemaKeyword.html">IJsonSchemaKeyword</a>&gt;</div> <div><span class="xref">System.IEquatable</span>&lt;<a class="xref" href="Manatee.Json.Schema.UniqueItemsKeyword.html">UniqueItemsKeyword</a>&gt;</div> </div> <div class="inheritedMembers"> <h5>Inherited Members</h5> <div> <span class="xref">System.Object.Equals(System.Object)</span> </div> <div> <span class="xref">System.Object.Equals(System.Object, System.Object)</span> </div> <div> <span class="xref">System.Object.GetType()</span> </div> <div> <span class="xref">System.Object.MemberwiseClone()</span> </div> <div> <span class="xref">System.Object.ReferenceEquals(System.Object, System.Object)</span> </div> <div> <span class="xref">System.Object.ToString()</span> </div> </div> <h6><strong>Namespace</strong>: <a class="xref" href="Manatee.Json.Schema.html">Manatee.Json.Schema</a></h6> <h6><strong>Assembly</strong>: Manatee.Json.dll</h6> <h5 id="Manatee_Json_Schema_UniqueItemsKeyword_syntax">Syntax</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public class UniqueItemsKeyword : IJsonSchemaKeyword, IJsonSerializable, IEquatable&lt;IJsonSchemaKeyword&gt;, IEquatable&lt;UniqueItemsKeyword&gt;</code></pre> </div> <h3 id="constructors">Constructors </h3> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/gregsdennis/Manatee.Json/new/master/apiSpec/new?filename=Manatee_Json_Schema_UniqueItemsKeyword__ctor.md&amp;value=---%0Auid%3A%20Manatee.Json.Schema.UniqueItemsKeyword.%23ctor%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/gregsdennis/Manatee.Json/blob/master/Manatee.Json/Schema/Keywords/UniqueItemsKeyword.cs/#L50">View Source</a> </span> <a id="Manatee_Json_Schema_UniqueItemsKeyword__ctor_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.#ctor*"></a> <h4 id="Manatee_Json_Schema_UniqueItemsKeyword__ctor" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.#ctor">UniqueItemsKeyword()</h4> <div class="markdown level1 summary"><p>Used for deserialization.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public UniqueItemsKeyword()</code></pre> </div> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/gregsdennis/Manatee.Json/new/master/apiSpec/new?filename=Manatee_Json_Schema_UniqueItemsKeyword__ctor_System_Boolean_.md&amp;value=---%0Auid%3A%20Manatee.Json.Schema.UniqueItemsKeyword.%23ctor(System.Boolean)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/gregsdennis/Manatee.Json/blob/master/Manatee.Json/Schema/Keywords/UniqueItemsKeyword.cs/#L56">View Source</a> </span> <a id="Manatee_Json_Schema_UniqueItemsKeyword__ctor_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.#ctor*"></a> <h4 id="Manatee_Json_Schema_UniqueItemsKeyword__ctor_System_Boolean_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.#ctor(System.Boolean)">UniqueItemsKeyword(Boolean)</h4> <div class="markdown level1 summary"><p>Creates an instance of the <a class="xref" href="Manatee.Json.Schema.UniqueItemsKeyword.html">UniqueItemsKeyword</a>.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public UniqueItemsKeyword(bool value = true)</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">System.Boolean</span></td> <td><span class="parametername">value</span></td> <td></td> </tr> </tbody> </table> <h3 id="properties">Properties </h3> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/gregsdennis/Manatee.Json/new/master/apiSpec/new?filename=Manatee_Json_Schema_UniqueItemsKeyword_ErrorTemplate.md&amp;value=---%0Auid%3A%20Manatee.Json.Schema.UniqueItemsKeyword.ErrorTemplate%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/gregsdennis/Manatee.Json/blob/master/Manatee.Json/Schema/Keywords/UniqueItemsKeyword.cs/#L23">View Source</a> </span> <a id="Manatee_Json_Schema_UniqueItemsKeyword_ErrorTemplate_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.ErrorTemplate*"></a> <h4 id="Manatee_Json_Schema_UniqueItemsKeyword_ErrorTemplate" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.ErrorTemplate">ErrorTemplate</h4> <div class="markdown level1 summary"><p>Gets or sets the error message template.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public static string ErrorTemplate { get; set; }</code></pre> </div> <h5 class="propertyValue">Property Value</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">System.String</span></td> <td></td> </tr> </tbody> </table> <h5 id="Manatee_Json_Schema_UniqueItemsKeyword_ErrorTemplate_remarks">Remarks</h5> <div class="markdown level1 remarks"><p>Does not supports any tokens.</p> </div> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/gregsdennis/Manatee.Json/new/master/apiSpec/new?filename=Manatee_Json_Schema_UniqueItemsKeyword_Name.md&amp;value=---%0Auid%3A%20Manatee.Json.Schema.UniqueItemsKeyword.Name%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/gregsdennis/Manatee.Json/blob/master/Manatee.Json/Schema/Keywords/UniqueItemsKeyword.cs/#L28">View Source</a> </span> <a id="Manatee_Json_Schema_UniqueItemsKeyword_Name_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.Name*"></a> <h4 id="Manatee_Json_Schema_UniqueItemsKeyword_Name" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.Name">Name</h4> <div class="markdown level1 summary"><p>Gets the name of the keyword.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public string Name { get; }</code></pre> </div> <h5 class="propertyValue">Property Value</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">System.String</span></td> <td></td> </tr> </tbody> </table> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/gregsdennis/Manatee.Json/new/master/apiSpec/new?filename=Manatee_Json_Schema_UniqueItemsKeyword_SupportedVersions.md&amp;value=---%0Auid%3A%20Manatee.Json.Schema.UniqueItemsKeyword.SupportedVersions%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/gregsdennis/Manatee.Json/blob/master/Manatee.Json/Schema/Keywords/UniqueItemsKeyword.cs/#L32">View Source</a> </span> <a id="Manatee_Json_Schema_UniqueItemsKeyword_SupportedVersions_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.SupportedVersions*"></a> <h4 id="Manatee_Json_Schema_UniqueItemsKeyword_SupportedVersions" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.SupportedVersions">SupportedVersions</h4> <div class="markdown level1 summary"><p>Gets the versions (drafts) of JSON Schema which support this keyword.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public JsonSchemaVersion SupportedVersions { get; }</code></pre> </div> <h5 class="propertyValue">Property Value</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><a class="xref" href="Manatee.Json.Schema.JsonSchemaVersion.html">JsonSchemaVersion</a></td> <td></td> </tr> </tbody> </table> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/gregsdennis/Manatee.Json/new/master/apiSpec/new?filename=Manatee_Json_Schema_UniqueItemsKeyword_ValidationSequence.md&amp;value=---%0Auid%3A%20Manatee.Json.Schema.UniqueItemsKeyword.ValidationSequence%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/gregsdennis/Manatee.Json/blob/master/Manatee.Json/Schema/Keywords/UniqueItemsKeyword.cs/#L36">View Source</a> </span> <a id="Manatee_Json_Schema_UniqueItemsKeyword_ValidationSequence_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.ValidationSequence*"></a> <h4 id="Manatee_Json_Schema_UniqueItemsKeyword_ValidationSequence" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.ValidationSequence">ValidationSequence</h4> <div class="markdown level1 summary"><p>Gets the a value indicating the sequence in which this keyword will be evaluated.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public int ValidationSequence { get; }</code></pre> </div> <h5 class="propertyValue">Property Value</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">System.Int32</span></td> <td></td> </tr> </tbody> </table> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/gregsdennis/Manatee.Json/new/master/apiSpec/new?filename=Manatee_Json_Schema_UniqueItemsKeyword_Value.md&amp;value=---%0Auid%3A%20Manatee.Json.Schema.UniqueItemsKeyword.Value%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/gregsdennis/Manatee.Json/blob/master/Manatee.Json/Schema/Keywords/UniqueItemsKeyword.cs/#L45">View Source</a> </span> <a id="Manatee_Json_Schema_UniqueItemsKeyword_Value_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.Value*"></a> <h4 id="Manatee_Json_Schema_UniqueItemsKeyword_Value" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.Value">Value</h4> <div class="markdown level1 summary"><p>The boolean value for this keyword.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public bool Value { get; }</code></pre> </div> <h5 class="propertyValue">Property Value</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">System.Boolean</span></td> <td></td> </tr> </tbody> </table> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/gregsdennis/Manatee.Json/new/master/apiSpec/new?filename=Manatee_Json_Schema_UniqueItemsKeyword_Vocabulary.md&amp;value=---%0Auid%3A%20Manatee.Json.Schema.UniqueItemsKeyword.Vocabulary%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/gregsdennis/Manatee.Json/blob/master/Manatee.Json/Schema/Keywords/UniqueItemsKeyword.cs/#L40">View Source</a> </span> <a id="Manatee_Json_Schema_UniqueItemsKeyword_Vocabulary_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.Vocabulary*"></a> <h4 id="Manatee_Json_Schema_UniqueItemsKeyword_Vocabulary" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.Vocabulary">Vocabulary</h4> <div class="markdown level1 summary"><p>Gets the vocabulary that defines this keyword.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public SchemaVocabulary Vocabulary { get; }</code></pre> </div> <h5 class="propertyValue">Property Value</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><a class="xref" href="Manatee.Json.Schema.SchemaVocabulary.html">SchemaVocabulary</a></td> <td></td> </tr> </tbody> </table> <h3 id="methods">Methods </h3> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/gregsdennis/Manatee.Json/new/master/apiSpec/new?filename=Manatee_Json_Schema_UniqueItemsKeyword_Equals_System_Nullable_Manatee_Json_Schema_IJsonSchemaKeyword__.md&amp;value=---%0Auid%3A%20Manatee.Json.Schema.UniqueItemsKeyword.Equals(System.Nullable%7BManatee.Json.Schema.IJsonSchemaKeyword%7D)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/gregsdennis/Manatee.Json/blob/master/Manatee.Json/Schema/Keywords/UniqueItemsKeyword.cs/#L141">View Source</a> </span> <a id="Manatee_Json_Schema_UniqueItemsKeyword_Equals_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.Equals*"></a> <h4 id="Manatee_Json_Schema_UniqueItemsKeyword_Equals_System_Nullable_Manatee_Json_Schema_IJsonSchemaKeyword__" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.Equals(System.Nullable{Manatee.Json.Schema.IJsonSchemaKeyword})">Equals(Nullable&lt;IJsonSchemaKeyword&gt;)</h4> <div class="markdown level1 summary"><p>Indicates whether the current object is equal to another object of the same type.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public bool Equals(IJsonSchemaKeyword? other)</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">System.Nullable</span>&lt;<a class="xref" href="Manatee.Json.Schema.IJsonSchemaKeyword.html">IJsonSchemaKeyword</a>&gt;</td> <td><span class="parametername">other</span></td> <td><p>An object to compare with this object.</p> </td> </tr> </tbody> </table> <h5 class="returns">Returns</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">System.Boolean</span></td> <td><p>true if the current object is equal to the <code data-dev-comment-type="paramref" class="paramref">other</code> parameter; otherwise, false.</p> </td> </tr> </tbody> </table> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/gregsdennis/Manatee.Json/new/master/apiSpec/new?filename=Manatee_Json_Schema_UniqueItemsKeyword_Equals_System_Nullable_Manatee_Json_Schema_UniqueItemsKeyword__.md&amp;value=---%0Auid%3A%20Manatee.Json.Schema.UniqueItemsKeyword.Equals(System.Nullable%7BManatee.Json.Schema.UniqueItemsKeyword%7D)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/gregsdennis/Manatee.Json/blob/master/Manatee.Json/Schema/Keywords/UniqueItemsKeyword.cs/#L132">View Source</a> </span> <a id="Manatee_Json_Schema_UniqueItemsKeyword_Equals_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.Equals*"></a> <h4 id="Manatee_Json_Schema_UniqueItemsKeyword_Equals_System_Nullable_Manatee_Json_Schema_UniqueItemsKeyword__" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.Equals(System.Nullable{Manatee.Json.Schema.UniqueItemsKeyword})">Equals(Nullable&lt;UniqueItemsKeyword&gt;)</h4> <div class="markdown level1 summary"><p>Indicates whether the current object is equal to another object of the same type.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public bool Equals(UniqueItemsKeyword? other)</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">System.Nullable</span>&lt;<a class="xref" href="Manatee.Json.Schema.UniqueItemsKeyword.html">UniqueItemsKeyword</a>&gt;</td> <td><span class="parametername">other</span></td> <td><p>An object to compare with this object.</p> </td> </tr> </tbody> </table> <h5 class="returns">Returns</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">System.Boolean</span></td> <td><p>true if the current object is equal to the <code data-dev-comment-type="paramref" class="paramref">other</code> parameter; otherwise, false.</p> </td> </tr> </tbody> </table> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/gregsdennis/Manatee.Json/new/master/apiSpec/new?filename=Manatee_Json_Schema_UniqueItemsKeyword_Equals_System_Nullable_System_Object__.md&amp;value=---%0Auid%3A%20Manatee.Json.Schema.UniqueItemsKeyword.Equals(System.Nullable%7BSystem.Object%7D)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/gregsdennis/Manatee.Json/blob/master/Manatee.Json/Schema/Keywords/UniqueItemsKeyword.cs/#L148">View Source</a> </span> <a id="Manatee_Json_Schema_UniqueItemsKeyword_Equals_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.Equals*"></a> <h4 id="Manatee_Json_Schema_UniqueItemsKeyword_Equals_System_Nullable_System_Object__" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.Equals(System.Nullable{System.Object})">Equals(Nullable&lt;Object&gt;)</h4> <div class="markdown level1 summary"><p>Determines whether the specified object is equal to the current object.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public override bool Equals(object? obj)</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">System.Nullable</span>&lt;<span class="xref">System.Object</span>&gt;</td> <td><span class="parametername">obj</span></td> <td><p>The object to compare with the current object.</p> </td> </tr> </tbody> </table> <h5 class="returns">Returns</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">System.Boolean</span></td> <td><p>true if the specified object is equal to the current object; otherwise, false.</p> </td> </tr> </tbody> </table> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/gregsdennis/Manatee.Json/new/master/apiSpec/new?filename=Manatee_Json_Schema_UniqueItemsKeyword_FromJson_Manatee_Json_JsonValue_Manatee_Json_Serialization_JsonSerializer_.md&amp;value=---%0Auid%3A%20Manatee.Json.Schema.UniqueItemsKeyword.FromJson(Manatee.Json.JsonValue%2CManatee.Json.Serialization.JsonSerializer)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/gregsdennis/Manatee.Json/blob/master/Manatee.Json/Schema/Keywords/UniqueItemsKeyword.cs/#L115">View Source</a> </span> <a id="Manatee_Json_Schema_UniqueItemsKeyword_FromJson_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.FromJson*"></a> <h4 id="Manatee_Json_Schema_UniqueItemsKeyword_FromJson_Manatee_Json_JsonValue_Manatee_Json_Serialization_JsonSerializer_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.FromJson(Manatee.Json.JsonValue,Manatee.Json.Serialization.JsonSerializer)">FromJson(JsonValue, JsonSerializer)</h4> <div class="markdown level1 summary"><p>Builds an object from a <a class="xref" href="Manatee.Json.JsonValue.html">JsonValue</a>.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public void FromJson(JsonValue json, JsonSerializer serializer)</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><a class="xref" href="Manatee.Json.JsonValue.html">JsonValue</a></td> <td><span class="parametername">json</span></td> <td><p>The <a class="xref" href="Manatee.Json.JsonValue.html">JsonValue</a> representation of the object.</p> </td> </tr> <tr> <td><a class="xref" href="Manatee.Json.Serialization.JsonSerializer.html">JsonSerializer</a></td> <td><span class="parametername">serializer</span></td> <td><p>The <a class="xref" href="Manatee.Json.Serialization.JsonSerializer.html">JsonSerializer</a> instance to use for additional serialization of values.</p> </td> </tr> </tbody> </table> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/gregsdennis/Manatee.Json/new/master/apiSpec/new?filename=Manatee_Json_Schema_UniqueItemsKeyword_GetHashCode.md&amp;value=---%0Auid%3A%20Manatee.Json.Schema.UniqueItemsKeyword.GetHashCode%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/gregsdennis/Manatee.Json/blob/master/Manatee.Json/Schema/Keywords/UniqueItemsKeyword.cs/#L154">View Source</a> </span> <a id="Manatee_Json_Schema_UniqueItemsKeyword_GetHashCode_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.GetHashCode*"></a> <h4 id="Manatee_Json_Schema_UniqueItemsKeyword_GetHashCode" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.GetHashCode">GetHashCode()</h4> <div class="markdown level1 summary"><p>Serves as the default hash function.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public override int GetHashCode()</code></pre> </div> <h5 class="returns">Returns</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">System.Int32</span></td> <td><p>A hash code for the current object.</p> </td> </tr> </tbody> </table> <h5 class="overrides">Overrides</h5> <div><span class="xref">System.Object.GetHashCode()</span></div> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/gregsdennis/Manatee.Json/new/master/apiSpec/new?filename=Manatee_Json_Schema_UniqueItemsKeyword_RegisterSubschemas_Manatee_Json_Schema_SchemaValidationContext_.md&amp;value=---%0Auid%3A%20Manatee.Json.Schema.UniqueItemsKeyword.RegisterSubschemas(Manatee.Json.Schema.SchemaValidationContext)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/gregsdennis/Manatee.Json/blob/master/Manatee.Json/Schema/Keywords/UniqueItemsKeyword.cs/#L97">View Source</a> </span> <a id="Manatee_Json_Schema_UniqueItemsKeyword_RegisterSubschemas_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.RegisterSubschemas*"></a> <h4 id="Manatee_Json_Schema_UniqueItemsKeyword_RegisterSubschemas_Manatee_Json_Schema_SchemaValidationContext_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.RegisterSubschemas(Manatee.Json.Schema.SchemaValidationContext)">RegisterSubschemas(SchemaValidationContext)</h4> <div class="markdown level1 summary"><p>Used register any subschemas during validation. Enables look-forward compatibility with <code>$ref</code> keywords.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public void RegisterSubschemas(SchemaValidationContext context)</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><a class="xref" href="Manatee.Json.Schema.SchemaValidationContext.html">SchemaValidationContext</a></td> <td><span class="parametername">context</span></td> <td><p>The context object.</p> </td> </tr> </tbody> </table> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/gregsdennis/Manatee.Json/new/master/apiSpec/new?filename=Manatee_Json_Schema_UniqueItemsKeyword_ResolveSubschema_Manatee_Json_Pointer_JsonPointer_System_Uri_Manatee_Json_Schema_JsonSchemaVersion_.md&amp;value=---%0Auid%3A%20Manatee.Json.Schema.UniqueItemsKeyword.ResolveSubschema(Manatee.Json.Pointer.JsonPointer%2CSystem.Uri%2CManatee.Json.Schema.JsonSchemaVersion)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/gregsdennis/Manatee.Json/blob/master/Manatee.Json/Schema/Keywords/UniqueItemsKeyword.cs/#L105">View Source</a> </span> <a id="Manatee_Json_Schema_UniqueItemsKeyword_ResolveSubschema_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.ResolveSubschema*"></a> <h4 id="Manatee_Json_Schema_UniqueItemsKeyword_ResolveSubschema_Manatee_Json_Pointer_JsonPointer_System_Uri_Manatee_Json_Schema_JsonSchemaVersion_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.ResolveSubschema(Manatee.Json.Pointer.JsonPointer,System.Uri,Manatee.Json.Schema.JsonSchemaVersion)">ResolveSubschema(JsonPointer, Uri, JsonSchemaVersion)</h4> <div class="markdown level1 summary"><p>Resolves any subschemas during resolution of a <code>$ref</code> during validation.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public JsonSchema? ResolveSubschema(JsonPointer pointer, Uri baseUri, JsonSchemaVersion supportedVersions)</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><a class="xref" href="Manatee.Json.Pointer.JsonPointer.html">JsonPointer</a></td> <td><span class="parametername">pointer</span></td> <td><p>A <a class="xref" href="Manatee.Json.Pointer.JsonPointer.html">JsonPointer</a> to the target schema.</p> </td> </tr> <tr> <td><span class="xref">System.Uri</span></td> <td><span class="parametername">baseUri</span></td> <td><p>The current base URI.</p> </td> </tr> <tr> <td><a class="xref" href="Manatee.Json.Schema.JsonSchemaVersion.html">JsonSchemaVersion</a></td> <td><span class="parametername">supportedVersions</span></td> <td><p>Indicates the root schema's supported versions.</p> </td> </tr> </tbody> </table> <h5 class="returns">Returns</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">System.Nullable</span>&lt;<a class="xref" href="Manatee.Json.Schema.JsonSchema.html">JsonSchema</a>&gt;</td> <td><p>The referenced schema, if it exists; otherwise null.</p> </td> </tr> </tbody> </table> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/gregsdennis/Manatee.Json/new/master/apiSpec/new?filename=Manatee_Json_Schema_UniqueItemsKeyword_ToJson_Manatee_Json_Serialization_JsonSerializer_.md&amp;value=---%0Auid%3A%20Manatee.Json.Schema.UniqueItemsKeyword.ToJson(Manatee.Json.Serialization.JsonSerializer)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/gregsdennis/Manatee.Json/blob/master/Manatee.Json/Schema/Keywords/UniqueItemsKeyword.cs/#L125">View Source</a> </span> <a id="Manatee_Json_Schema_UniqueItemsKeyword_ToJson_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.ToJson*"></a> <h4 id="Manatee_Json_Schema_UniqueItemsKeyword_ToJson_Manatee_Json_Serialization_JsonSerializer_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.ToJson(Manatee.Json.Serialization.JsonSerializer)">ToJson(JsonSerializer)</h4> <div class="markdown level1 summary"><p>Converts an object to a <a class="xref" href="Manatee.Json.JsonValue.html">JsonValue</a>.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public JsonValue ToJson(JsonSerializer serializer)</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><a class="xref" href="Manatee.Json.Serialization.JsonSerializer.html">JsonSerializer</a></td> <td><span class="parametername">serializer</span></td> <td><p>The <a class="xref" href="Manatee.Json.Serialization.JsonSerializer.html">JsonSerializer</a> instance to use for additional serialization of values.</p> </td> </tr> </tbody> </table> <h5 class="returns">Returns</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><a class="xref" href="Manatee.Json.JsonValue.html">JsonValue</a></td> <td><p>The <a class="xref" href="Manatee.Json.JsonValue.html">JsonValue</a> representation of the object.</p> </td> </tr> </tbody> </table> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/gregsdennis/Manatee.Json/new/master/apiSpec/new?filename=Manatee_Json_Schema_UniqueItemsKeyword_Validate_Manatee_Json_Schema_SchemaValidationContext_.md&amp;value=---%0Auid%3A%20Manatee.Json.Schema.UniqueItemsKeyword.Validate(Manatee.Json.Schema.SchemaValidationContext)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/gregsdennis/Manatee.Json/blob/master/Manatee.Json/Schema/Keywords/UniqueItemsKeyword.cs/#L66">View Source</a> </span> <a id="Manatee_Json_Schema_UniqueItemsKeyword_Validate_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.Validate*"></a> <h4 id="Manatee_Json_Schema_UniqueItemsKeyword_Validate_Manatee_Json_Schema_SchemaValidationContext_" data-uid="Manatee.Json.Schema.UniqueItemsKeyword.Validate(Manatee.Json.Schema.SchemaValidationContext)">Validate(SchemaValidationContext)</h4> <div class="markdown level1 summary"><p>Provides the validation logic for this keyword.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public SchemaValidationResults Validate(SchemaValidationContext context)</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><a class="xref" href="Manatee.Json.Schema.SchemaValidationContext.html">SchemaValidationContext</a></td> <td><span class="parametername">context</span></td> <td><p>The context object.</p> </td> </tr> </tbody> </table> <h5 class="returns">Returns</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><a class="xref" href="Manatee.Json.Schema.SchemaValidationResults.html">SchemaValidationResults</a></td> <td><p>Results object containing a final result and any errors that may have been found.</p> </td> </tr> </tbody> </table> <h3 id="implements">Implements</h3> <div> <a class="xref" href="Manatee.Json.Schema.IJsonSchemaKeyword.html">IJsonSchemaKeyword</a> </div> <div> <a class="xref" href="Manatee.Json.Serialization.IJsonSerializable.html">IJsonSerializable</a> </div> <div> <span class="xref">System.IEquatable&lt;T&gt;</span> </div> <div> <span class="xref">System.IEquatable&lt;T&gt;</span> </div> </article> </div> <div class="hidden-sm col-md-2" role="complementary"> <div class="sideaffix"> <div class="contribution"> <ul class="nav"> <li> <a href="https://github.com/gregsdennis/Manatee.Json/new/master/apiSpec/new?filename=Manatee_Json_Schema_UniqueItemsKeyword.md&amp;value=---%0Auid%3A%20Manatee.Json.Schema.UniqueItemsKeyword%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A" class="contribution-link">Improve this Doc</a> </li> <li> <a href="https://github.com/gregsdennis/Manatee.Json/blob/master/Manatee.Json/Schema/Keywords/UniqueItemsKeyword.cs/#L14" class="contribution-link">View Source</a> </li> </ul> </div> <nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix"> <!-- <p><a class="back-to-top" href="#top">Back to top</a><p> --> </nav> </div> </div> </div> </div> <footer> <div class="grad-bottom"></div> <div class="footer"> <div class="container"> <span class="pull-right"> <a href="#top">Back to top</a> </span> <span>Generated by <strong>DocFX</strong></span> </div> </div> </footer> </div> <script type="text/javascript" src="../styles/docfx.vendor.js"></script> <script type="text/javascript" src="../styles/docfx.js"></script> <script type="text/javascript" src="../styles/main.js"></script> </body> </html>
{ "pile_set_name": "Github" }
a2e36336e35f9466c883ade059c6485e *tests/data/fate/vsynth3-mpeg1b.mpeg1video 38251 tests/data/fate/vsynth3-mpeg1b.mpeg1video c44023d27be27deb7f3793321655ca75 *tests/data/fate/vsynth3-mpeg1b.out.rawvideo stddev: 7.00 PSNR: 31.22 MAXDIFF: 56 bytes: 86700/ 86700
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <debug-info version="2"> <concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068580123140:jetbrains.mps.baseLanguage.structure.ConstructorDeclaration" /> <concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068580123155:jetbrains.mps.baseLanguage.structure.ExpressionStatement" /> <concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068390468200:jetbrains.mps.baseLanguage.structure.FieldDeclaration" /> <concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068580123159:jetbrains.mps.baseLanguage.structure.IfStatement" /> <concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068580123165:jetbrains.mps.baseLanguage.structure.InstanceMethodDeclaration" /> <concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068581242864:jetbrains.mps.baseLanguage.structure.LocalVariableDeclarationStatement" /> <concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068581242878:jetbrains.mps.baseLanguage.structure.ReturnStatement" /> <concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1070462154015:jetbrains.mps.baseLanguage.structure.StaticFieldDeclaration" /> <concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1070475587102:jetbrains.mps.baseLanguage.structure.SuperConstructorInvocation" /> <concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/5351203823916750322:jetbrains.mps.baseLanguage.structure.TryUniversalStatement" /> <root> <file name="EditorAspectDescriptorImpl.java"> <unit at="15,0,31,0" name="jetbrains.mps.samples.generator_demo.demoLang7.editor.EditorAspectDescriptorImpl" /> </file> </root> <root nodeRef="r:f08b1eba-d157-4242-b1d4-18f615d583e8(jetbrains.mps.samples.generator_demo.demoLang7.editor)/3618324829955893159"> <file name="XMLDocument_Editor.java"> <node id="3618324829955893159" at="11,79,12,77" concept="6" /> <node id="3618324829955893159" at="11,0,14,0" concept="4" trace="createEditorCell#(Ljetbrains/mps/openapi/editor/EditorContext;Lorg/jetbrains/mps/openapi/model/SNode;)Ljetbrains/mps/openapi/editor/cells/EditorCell;" /> <scope id="3618324829955893159" at="11,79,12,77" /> <scope id="3618324829955893159" at="11,0,14,0"> <var name="editorContext" id="3618324829955893159" /> <var name="node" id="3618324829955893159" /> </scope> <unit id="3618324829955893159" at="10,0,15,0" name="jetbrains.mps.samples.generator_demo.demoLang7.editor.XMLDocument_Editor" /> </file> <file name="XMLDocument_EditorBuilder_a.java"> <node id="3618324829955893159" at="33,91,34,19" concept="8" /> <node id="3618324829955893159" at="34,19,35,18" concept="1" /> <node id="3618324829955893159" at="40,26,41,18" concept="6" /> <node id="3618324829955893159" at="44,39,45,32" concept="6" /> <node id="3618324829955893159" at="48,43,49,120" concept="5" /> <node id="3618324829955893159" at="49,120,50,47" concept="1" /> <node id="3618324829955893159" at="50,47,51,28" concept="1" /> <node id="3618324829955893159" at="51,28,52,31" concept="1" /> <node id="3618324829955894225" at="52,31,53,49" concept="1" /> <node id="3618324829955894231" at="53,49,54,51" concept="1" /> <node id="3618324829955893159" at="54,51,55,22" concept="6" /> <node id="3618324829955894225" at="57,41,58,105" concept="5" /> <node id="3618324829955894225" at="58,105,59,46" concept="1" /> <node id="3618324829955894225" at="59,46,60,34" concept="1" /> <node id="3618324829955894225" at="60,34,61,22" concept="6" /> <node id="3618324829955893159" at="63,43,64,120" concept="5" /> <node id="3618324829955893159" at="64,120,65,48" concept="1" /> <node id="3618324829955893159" at="65,48,66,34" concept="5" /> <node id="3618324829955894233" at="66,34,67,49" concept="1" /> <node id="3618324829955893159" at="67,49,68,40" concept="1" /> <node id="3618324829955894243" at="68,40,69,52" concept="1" /> <node id="3618324829955893159" at="69,52,70,22" concept="6" /> <node id="3618324829955893159" at="72,44,73,99" concept="5" /> <node id="3618324829955893159" at="73,99,74,93" concept="5" /> <node id="3618324829955893159" at="74,93,75,48" concept="1" /> <node id="3618324829955893159" at="75,48,76,51" concept="1" /> <node id="3618324829955893159" at="76,51,77,22" concept="6" /> <node id="3618324829955893159" at="83,81,84,28" concept="8" /> <node id="3618324829955893159" at="84,28,85,25" concept="1" /> <node id="3618324829955893159" at="89,28,90,20" concept="6" /> <node id="3618324829955893159" at="92,40,93,32" concept="6" /> <node id="3618324829955893159" at="95,48,96,33" concept="6" /> <node id="3618324829955893159" at="99,57,100,83" concept="5" /> <node id="3618324829955893159" at="100,83,101,65" concept="1" /> <node id="3618324829955893159" at="101,65,102,25" concept="6" /> <node id="3618324829955893159" at="104,41,105,41" concept="1" /> <node id="3618324829955893159" at="105,41,106,141" concept="1" /> <node id="3618324829955893159" at="107,11,108,36" concept="5" /> <node id="3618324829955893159" at="108,36,109,44" concept="1" /> <node id="3618324829955893159" at="109,44,110,57" concept="1" /> <node id="3618324829955893159" at="110,57,111,34" concept="1" /> <node id="3618324829955893159" at="111,34,112,25" concept="6" /> <node id="3618324829955893159" at="113,17,114,42" concept="1" /> <node id="3618324829955893159" at="118,0,119,0" concept="7" trace="OBJ" /> <node id="3618324829955893159" at="122,122,123,92" concept="1" /> <node id="3618324829955893159" at="123,92,124,146" concept="1" /> <node id="3618324829955893159" at="128,34,129,90" concept="1" /> <node id="3618324829955893159" at="129,90,130,142" concept="1" /> <node id="3618324829955893159" at="134,34,135,69" concept="1" /> <node id="3618324829955893159" at="135,69,136,146" concept="1" /> <node id="3618324829955893159" at="140,34,141,91" concept="1" /> <node id="3618324829955893159" at="148,0,149,0" concept="7" trace="element$sWtF" /> <node id="3618324829955893159" at="152,0,153,0" concept="7" trace="Element$hR" /> <node id="3618324829955893159" at="30,0,32,0" concept="2" trace="myNode" /> <node id="3618324829955893159" at="80,0,82,0" concept="2" trace="myNode" /> <node id="3618324829955893159" at="44,0,47,0" concept="4" trace="createCell#()Ljetbrains/mps/openapi/editor/cells/EditorCell;" /> <node id="3618324829955893159" at="92,0,95,0" concept="4" trace="getSLink#()Lorg/jetbrains/mps/openapi/language/SContainmentLink;" /> <node id="3618324829955893159" at="95,0,98,0" concept="4" trace="getChildSConcept#()Lorg/jetbrains/mps/openapi/language/SAbstractConcept;" /> <node id="3618324829955893159" at="139,96,142,9" concept="3" /> <node id="3618324829955893159" at="33,0,37,0" concept="0" trace="XMLDocument_EditorBuilder_a#(Ljetbrains/mps/openapi/editor/EditorContext;Lorg/jetbrains/mps/openapi/model/SNode;)V" /> <node id="3618324829955893159" at="83,0,87,0" concept="0" trace="elementListHandler_rkc9p_a1a#(Lorg/jetbrains/mps/openapi/model/SNode;Ljetbrains/mps/openapi/editor/EditorContext;)V" /> <node id="3618324829955893159" at="88,0,92,0" concept="4" trace="getNode#()Lorg/jetbrains/mps/openapi/model/SNode;" /> <node id="3618324829955893159" at="121,97,125,9" concept="3" /> <node id="3618324829955893159" at="127,95,131,9" concept="3" /> <node id="3618324829955893159" at="133,74,137,9" concept="3" /> <node id="3618324829955893159" at="38,0,43,0" concept="4" trace="getNode#()Lorg/jetbrains/mps/openapi/model/SNode;" /> <node id="3618324829955893159" at="99,0,104,0" concept="4" trace="createNodeCell#(Lorg/jetbrains/mps/openapi/model/SNode;)Ljetbrains/mps/openapi/editor/cells/EditorCell;" /> <node id="3618324829955893159" at="138,7,143,7" concept="3" /> <node id="3618324829955894225" at="57,0,63,0" concept="4" trace="createConstant_0#()Ljetbrains/mps/openapi/editor/cells/EditorCell;" /> <node id="3618324829955893159" at="120,107,126,7" concept="3" /> <node id="3618324829955893159" at="126,7,132,7" concept="3" /> <node id="3618324829955893159" at="132,7,138,7" concept="3" /> <node id="3618324829955893159" at="72,0,79,0" concept="4" trace="createRefNodeList_0#()Ljetbrains/mps/openapi/editor/cells/EditorCell;" /> <node id="3618324829955893159" at="48,0,57,0" concept="4" trace="createCollection_0#()Ljetbrains/mps/openapi/editor/cells/EditorCell;" /> <node id="3618324829955893159" at="63,0,72,0" concept="4" trace="createCollection_1#()Ljetbrains/mps/openapi/editor/cells/EditorCell;" /> <node id="3618324829955893159" at="106,141,115,7" concept="9" /> <node id="3618324829955893159" at="104,0,117,0" concept="4" trace="createEmptyCell#()Ljetbrains/mps/openapi/editor/cells/EditorCell;" /> <node id="3618324829955893159" at="120,0,145,0" concept="4" trace="installElementCellActions#(Lorg/jetbrains/mps/openapi/model/SNode;Ljetbrains/mps/openapi/editor/cells/EditorCell;Z)V" /> <scope id="3618324829955893159" at="40,26,41,18" /> <scope id="3618324829955893159" at="44,39,45,32" /> <scope id="3618324829955893159" at="89,28,90,20" /> <scope id="3618324829955893159" at="92,40,93,32" /> <scope id="3618324829955893159" at="95,48,96,33" /> <scope id="3618324829955893159" at="113,17,114,42" /> <scope id="3618324829955893159" at="140,34,141,91" /> <scope id="3618324829955893159" at="33,91,35,18" /> <scope id="3618324829955893159" at="83,81,85,25" /> <scope id="3618324829955893159" at="122,122,124,146" /> <scope id="3618324829955893159" at="128,34,130,142" /> <scope id="3618324829955893159" at="134,34,136,146" /> <scope id="3618324829955893159" at="44,0,47,0" /> <scope id="3618324829955893159" at="92,0,95,0" /> <scope id="3618324829955893159" at="95,0,98,0" /> <scope id="3618324829955893159" at="99,57,102,25"> <var name="elementCell" id="3618324829955893159" /> </scope> <scope id="3618324829955893159" at="139,96,142,9" /> <scope id="3618324829955893159" at="33,0,37,0"> <var name="context" id="3618324829955893159" /> <var name="node" id="3618324829955893159" /> </scope> <scope id="3618324829955894225" at="57,41,61,22"> <var name="editorCell" id="3618324829955894225" /> </scope> <scope id="3618324829955893159" at="83,0,87,0"> <var name="context" id="3618324829955893159" /> <var name="ownerNode" id="3618324829955893159" /> </scope> <scope id="3618324829955893159" at="88,0,92,0" /> <scope id="3618324829955893159" at="121,97,125,9" /> <scope id="3618324829955893159" at="127,95,131,9" /> <scope id="3618324829955893159" at="133,74,137,9" /> <scope id="3618324829955893159" at="38,0,43,0" /> <scope id="3618324829955893159" at="72,44,77,22"> <var name="editorCell" id="3618324829955893159" /> <var name="handler" id="3618324829955893159" /> </scope> <scope id="3618324829955893159" at="99,0,104,0"> <var name="elementNode" id="3618324829955893159" /> </scope> <scope id="3618324829955893159" at="107,11,112,25"> <var name="emptyCell" id="3618324829955893159" /> </scope> <scope id="3618324829955894225" at="57,0,63,0" /> <scope id="3618324829955893159" at="48,43,55,22"> <var name="editorCell" id="3618324829955893159" /> </scope> <scope id="3618324829955893159" at="63,43,70,22"> <var name="editorCell" id="3618324829955893159" /> <var name="style" id="3618324829955893159" /> </scope> <scope id="3618324829955893159" at="72,0,79,0" /> <scope id="3618324829955893159" at="48,0,57,0" /> <scope id="3618324829955893159" at="63,0,72,0" /> <scope id="3618324829955893159" at="104,41,115,7" /> <scope id="3618324829955893159" at="104,0,117,0" /> <scope id="3618324829955893159" at="120,107,143,7" /> <scope id="3618324829955893159" at="120,0,145,0"> <var name="elementCell" id="3618324829955893159" /> <var name="elementNode" id="3618324829955893159" /> <var name="isEmptyCell" id="3618324829955893159" /> </scope> <unit id="3618324829955893159" at="147,0,150,0" name="jetbrains.mps.samples.generator_demo.demoLang7.editor.XMLDocument_EditorBuilder_a$LINKS" /> <unit id="3618324829955893159" at="151,0,154,0" name="jetbrains.mps.samples.generator_demo.demoLang7.editor.XMLDocument_EditorBuilder_a$CONCEPTS" /> <unit id="3618324829955893159" at="79,0,146,0" name="jetbrains.mps.samples.generator_demo.demoLang7.editor.XMLDocument_EditorBuilder_a$elementListHandler_rkc9p_a1a" /> <unit id="3618324829955893159" at="29,0,155,0" name="jetbrains.mps.samples.generator_demo.demoLang7.editor.XMLDocument_EditorBuilder_a" /> </file> </root> </debug-info>
{ "pile_set_name": "Github" }
/* jQuery Colorbox language configuration language: German (de) translated by: wallenium */ jQuery.extend(jQuery.colorbox.settings, { current: "Bild {current} von {total}", previous: "Zurück", next: "Vor", close: "Schließen", xhrError: "Dieser Inhalt konnte nicht geladen werden.", imgError: "Dieses Bild konnte nicht geladen werden.", slideshowStart: "Slideshow starten", slideshowStop: "Slideshow anhalten" });
{ "pile_set_name": "Github" }
# lru cache A cache object that deletes the least-recently-used items. ## Usage: ```javascript var LRU = require("lru-cache") , options = { max: 500 , length: function (n) { return n * 2 } , dispose: function (key, n) { n.close() } , maxAge: 1000 * 60 * 60 } , cache = LRU(options) , otherCache = LRU(50) // sets just the max size cache.set("key", "value") cache.get("key") // "value" cache.reset() // empty the cache ``` If you put more stuff in it, then items will fall out. If you try to put an oversized thing in it, then it'll fall out right away. ## Keys should always be Strings or Numbers Note: this module will print warnings to `console.error` if you use a key that is not a String or Number. Because items are stored in an object, which coerces keys to a string, it won't go well for you if you try to use a key that is not a unique string, it'll cause surprise collisions. For example: ```JavaScript // Bad Example! Dont' do this! var cache = LRU() var a = {} var b = {} cache.set(a, 'this is a') cache.set(b, 'this is b') console.log(cache.get(a)) // prints: 'this is b' ``` ## Options * `max` The maximum size of the cache, checked by applying the length function to all values in the cache. Not setting this is kind of silly, since that's the whole purpose of this lib, but it defaults to `Infinity`. * `maxAge` Maximum age in ms. Items are not pro-actively pruned out as they age, but if you try to get an item that is too old, it'll drop it and return undefined instead of giving it to you. * `length` Function that is used to calculate the length of stored items. If you're storing strings or buffers, then you probably want to do something like `function(n){return n.length}`. The default is `function(n){return 1}`, which is fine if you want to store `max` like-sized things. * `dispose` Function that is called on items when they are dropped from the cache. This can be handy if you want to close file descriptors or do other cleanup tasks when items are no longer accessible. Called with `key, value`. It's called *before* actually removing the item from the internal cache, so if you want to immediately put it back in, you'll have to do that in a `nextTick` or `setTimeout` callback or it won't do anything. * `stale` By default, if you set a `maxAge`, it'll only actually pull stale items out of the cache when you `get(key)`. (That is, it's not pre-emptively doing a `setTimeout` or anything.) If you set `stale:true`, it'll return the stale value before deleting it. If you don't set this, then it'll return `undefined` when you try to get a stale entry, as if it had already been deleted. ## API * `set(key, value, maxAge)` * `get(key) => value` Both of these will update the "recently used"-ness of the key. They do what you think. `max` is optional and overrides the cache `max` option if provided. * `peek(key)` Returns the key value (or `undefined` if not found) without updating the "recently used"-ness of the key. (If you find yourself using this a lot, you *might* be using the wrong sort of data structure, but there are some use cases where it's handy.) * `del(key)` Deletes a key out of the cache. * `reset()` Clear the cache entirely, throwing away all values. * `has(key)` Check if a key is in the cache, without updating the recent-ness or deleting it for being stale. * `forEach(function(value,key,cache), [thisp])` Just like `Array.prototype.forEach`. Iterates over all the keys in the cache, in order of recent-ness. (Ie, more recently used items are iterated over first.) * `keys()` Return an array of the keys in the cache. * `values()` Return an array of the values in the cache. * `length()` Return total length of objects in cache taking into account `length` options function. * `itemCount` Return total quantity of objects currently in cache. Note, that `stale` (see options) items are returned as part of this item count. * `dump()` Return an array of the cache entries ready for serialization and usage with 'destinationCache.load(arr)`. * `load(cacheEntriesArray)` Loads another cache entries array, obtained with `sourceCache.dump()`, into the cache. The destination cache is reset before loading new entries
{ "pile_set_name": "Github" }
// +build windows package dns import "net" // SessionUDP holds the remote address type SessionUDP struct { raddr *net.UDPAddr } // RemoteAddr returns the remote network address. func (s *SessionUDP) RemoteAddr() net.Addr { return s.raddr } // ReadFromSessionUDP acts just like net.UDPConn.ReadFrom(), but returns a session object instead of a // net.UDPAddr. // TODO(fastest963): Once go1.10 is released, use ReadMsgUDP. func ReadFromSessionUDP(conn *net.UDPConn, b []byte) (int, *SessionUDP, error) { n, raddr, err := conn.ReadFrom(b) if err != nil { return n, nil, err } session := &SessionUDP{raddr.(*net.UDPAddr)} return n, session, err } // WriteToSessionUDP acts just like net.UDPConn.WriteTo(), but uses a *SessionUDP instead of a net.Addr. // TODO(fastest963): Once go1.10 is released, use WriteMsgUDP. func WriteToSessionUDP(conn *net.UDPConn, b []byte, session *SessionUDP) (int, error) { n, err := conn.WriteTo(b, session.raddr) return n, err } // TODO(fastest963): Once go1.10 is released and we can use *MsgUDP methods // use the standard method in udp.go for these. func setUDPSocketOptions(*net.UDPConn) error { return nil } func parseDstFromOOB([]byte, net.IP) net.IP { return nil }
{ "pile_set_name": "Github" }
/* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2014 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { var util = require('./util'); /** * Determine whether mappingB is after mappingA with respect to generated * position. */ function generatedPositionAfter(mappingA, mappingB) { // Optimized for most common case var lineA = mappingA.generatedLine; var lineB = mappingB.generatedLine; var columnA = mappingA.generatedColumn; var columnB = mappingB.generatedColumn; return lineB > lineA || lineB == lineA && columnB >= columnA || util.compareByGeneratedPositions(mappingA, mappingB) <= 0; } /** * A data structure to provide a sorted view of accumulated mappings in a * performance conscious manner. It trades a neglibable overhead in general * case for a large speedup in case of mappings being added in order. */ function MappingList() { this._array = []; this._sorted = true; // Serves as infimum this._last = {generatedLine: -1, generatedColumn: 0}; } /** * Iterate through internal items. This method takes the same arguments that * `Array.prototype.forEach` takes. * * NOTE: The order of the mappings is NOT guaranteed. */ MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) { this._array.forEach(aCallback, aThisArg); }; /** * Add the given source mapping. * * @param Object aMapping */ MappingList.prototype.add = function MappingList_add(aMapping) { var mapping; if (generatedPositionAfter(this._last, aMapping)) { this._last = aMapping; this._array.push(aMapping); } else { this._sorted = false; this._array.push(aMapping); } }; /** * Returns the flat, sorted array of mappings. The mappings are sorted by * generated position. * * WARNING: This method returns internal data without copying, for * performance. The return value must NOT be mutated, and should be treated as * an immutable borrow. If you want to take ownership, you must make your own * copy. */ MappingList.prototype.toArray = function MappingList_toArray() { if (!this._sorted) { this._array.sort(util.compareByGeneratedPositions); this._sorted = true; } return this._array; }; exports.MappingList = MappingList; });
{ "pile_set_name": "Github" }
/* * Copyright Andrey Semashev 2007 - 2015. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ /*! * \file keywords/order.hpp * \author Andrey Semashev * \date 23.08.2009 * * The header contains the \c order keyword declaration. */ #ifndef BOOST_LOG_KEYWORDS_ORDER_HPP_INCLUDED_ #define BOOST_LOG_KEYWORDS_ORDER_HPP_INCLUDED_ #include <boost/parameter/keyword.hpp> #include <boost/log/detail/config.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif namespace boost { BOOST_LOG_OPEN_NAMESPACE namespace keywords { //! The keyword allows to pass the ordering predicate to sink frontends BOOST_PARAMETER_KEYWORD(tag, order) } // namespace keywords BOOST_LOG_CLOSE_NAMESPACE // namespace log } // namespace boost #endif // BOOST_LOG_KEYWORDS_ORDER_HPP_INCLUDED_
{ "pile_set_name": "Github" }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("gas", function(_config, parserConfig) { 'use strict'; // If an architecture is specified, its initialization function may // populate this array with custom parsing functions which will be // tried in the event that the standard functions do not find a match. var custom = []; // The symbol used to start a line comment changes based on the target // architecture. // If no architecture is pased in "parserConfig" then only multiline // comments will have syntax support. var lineCommentStartSymbol = ""; // These directives are architecture independent. // Machine specific directives should go in their respective // architecture initialization function. // Reference: // http://sourceware.org/binutils/docs/as/Pseudo-Ops.html#Pseudo-Ops var directives = { ".abort" : "builtin", ".align" : "builtin", ".altmacro" : "builtin", ".ascii" : "builtin", ".asciz" : "builtin", ".balign" : "builtin", ".balignw" : "builtin", ".balignl" : "builtin", ".bundle_align_mode" : "builtin", ".bundle_lock" : "builtin", ".bundle_unlock" : "builtin", ".byte" : "builtin", ".cfi_startproc" : "builtin", ".comm" : "builtin", ".data" : "builtin", ".def" : "builtin", ".desc" : "builtin", ".dim" : "builtin", ".double" : "builtin", ".eject" : "builtin", ".else" : "builtin", ".elseif" : "builtin", ".end" : "builtin", ".endef" : "builtin", ".endfunc" : "builtin", ".endif" : "builtin", ".equ" : "builtin", ".equiv" : "builtin", ".eqv" : "builtin", ".err" : "builtin", ".error" : "builtin", ".exitm" : "builtin", ".extern" : "builtin", ".fail" : "builtin", ".file" : "builtin", ".fill" : "builtin", ".float" : "builtin", ".func" : "builtin", ".global" : "builtin", ".gnu_attribute" : "builtin", ".hidden" : "builtin", ".hword" : "builtin", ".ident" : "builtin", ".if" : "builtin", ".incbin" : "builtin", ".include" : "builtin", ".int" : "builtin", ".internal" : "builtin", ".irp" : "builtin", ".irpc" : "builtin", ".lcomm" : "builtin", ".lflags" : "builtin", ".line" : "builtin", ".linkonce" : "builtin", ".list" : "builtin", ".ln" : "builtin", ".loc" : "builtin", ".loc_mark_labels" : "builtin", ".local" : "builtin", ".long" : "builtin", ".macro" : "builtin", ".mri" : "builtin", ".noaltmacro" : "builtin", ".nolist" : "builtin", ".octa" : "builtin", ".offset" : "builtin", ".org" : "builtin", ".p2align" : "builtin", ".popsection" : "builtin", ".previous" : "builtin", ".print" : "builtin", ".protected" : "builtin", ".psize" : "builtin", ".purgem" : "builtin", ".pushsection" : "builtin", ".quad" : "builtin", ".reloc" : "builtin", ".rept" : "builtin", ".sbttl" : "builtin", ".scl" : "builtin", ".section" : "builtin", ".set" : "builtin", ".short" : "builtin", ".single" : "builtin", ".size" : "builtin", ".skip" : "builtin", ".sleb128" : "builtin", ".space" : "builtin", ".stab" : "builtin", ".string" : "builtin", ".struct" : "builtin", ".subsection" : "builtin", ".symver" : "builtin", ".tag" : "builtin", ".text" : "builtin", ".title" : "builtin", ".type" : "builtin", ".uleb128" : "builtin", ".val" : "builtin", ".version" : "builtin", ".vtable_entry" : "builtin", ".vtable_inherit" : "builtin", ".warning" : "builtin", ".weak" : "builtin", ".weakref" : "builtin", ".word" : "builtin" }; var registers = {}; function x86(_parserConfig) { lineCommentStartSymbol = "#"; registers.ax = "variable"; registers.eax = "variable-2"; registers.rax = "variable-3"; registers.bx = "variable"; registers.ebx = "variable-2"; registers.rbx = "variable-3"; registers.cx = "variable"; registers.ecx = "variable-2"; registers.rcx = "variable-3"; registers.dx = "variable"; registers.edx = "variable-2"; registers.rdx = "variable-3"; registers.si = "variable"; registers.esi = "variable-2"; registers.rsi = "variable-3"; registers.di = "variable"; registers.edi = "variable-2"; registers.rdi = "variable-3"; registers.sp = "variable"; registers.esp = "variable-2"; registers.rsp = "variable-3"; registers.bp = "variable"; registers.ebp = "variable-2"; registers.rbp = "variable-3"; registers.ip = "variable"; registers.eip = "variable-2"; registers.rip = "variable-3"; registers.cs = "keyword"; registers.ds = "keyword"; registers.ss = "keyword"; registers.es = "keyword"; registers.fs = "keyword"; registers.gs = "keyword"; } function armv6(_parserConfig) { // Reference: // http://infocenter.arm.com/help/topic/com.arm.doc.qrc0001l/QRC0001_UAL.pdf // http://infocenter.arm.com/help/topic/com.arm.doc.ddi0301h/DDI0301H_arm1176jzfs_r0p7_trm.pdf lineCommentStartSymbol = "@"; directives.syntax = "builtin"; registers.r0 = "variable"; registers.r1 = "variable"; registers.r2 = "variable"; registers.r3 = "variable"; registers.r4 = "variable"; registers.r5 = "variable"; registers.r6 = "variable"; registers.r7 = "variable"; registers.r8 = "variable"; registers.r9 = "variable"; registers.r10 = "variable"; registers.r11 = "variable"; registers.r12 = "variable"; registers.sp = "variable-2"; registers.lr = "variable-2"; registers.pc = "variable-2"; registers.r13 = registers.sp; registers.r14 = registers.lr; registers.r15 = registers.pc; custom.push(function(ch, stream) { if (ch === '#') { stream.eatWhile(/\w/); return "number"; } }); } var arch = (parserConfig.architecture || "x86").toLowerCase(); if (arch === "x86") { x86(parserConfig); } else if (arch === "arm" || arch === "armv6") { armv6(parserConfig); } function nextUntilUnescaped(stream, end) { var escaped = false, next; while ((next = stream.next()) != null) { if (next === end && !escaped) { return false; } escaped = !escaped && next === "\\"; } return escaped; } function clikeComment(stream, state) { var maybeEnd = false, ch; while ((ch = stream.next()) != null) { if (ch === "/" && maybeEnd) { state.tokenize = null; break; } maybeEnd = (ch === "*"); } return "comment"; } return { startState: function() { return { tokenize: null }; }, token: function(stream, state) { if (state.tokenize) { return state.tokenize(stream, state); } if (stream.eatSpace()) { return null; } var style, cur, ch = stream.next(); if (ch === "/") { if (stream.eat("*")) { state.tokenize = clikeComment; return clikeComment(stream, state); } } if (ch === lineCommentStartSymbol) { stream.skipToEnd(); return "comment"; } if (ch === '"') { nextUntilUnescaped(stream, '"'); return "string"; } if (ch === '.') { stream.eatWhile(/\w/); cur = stream.current().toLowerCase(); style = directives[cur]; return style || null; } if (ch === '=') { stream.eatWhile(/\w/); return "tag"; } if (ch === '{') { return "braket"; } if (ch === '}') { return "braket"; } if (/\d/.test(ch)) { if (ch === "0" && stream.eat("x")) { stream.eatWhile(/[0-9a-fA-F]/); return "number"; } stream.eatWhile(/\d/); return "number"; } if (/\w/.test(ch)) { stream.eatWhile(/\w/); if (stream.eat(":")) { return 'tag'; } cur = stream.current().toLowerCase(); style = registers[cur]; return style || null; } for (var i = 0; i < custom.length; i++) { style = custom[i](ch, stream, state); if (style) { return style; } } }, lineComment: lineCommentStartSymbol, blockCommentStart: "/*", blockCommentEnd: "*/" }; }); });
{ "pile_set_name": "Github" }
/* * This file is part of the OregonCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "CinematicMgr.h" #include "Creature.h" #include "Player.h" #include "TemporarySummon.h" CinematicMgr::CinematicMgr(Player* playerref) { player = playerref; m_cinematicDiff = 0; m_lastCinematicCheck = 0; m_activeCinematicCameraId = 0; m_cinematicLength = 0; m_cinematicCamera = nullptr; m_remoteSightPosition = { 0.0f, 0.0f, 0.0f}; m_CinematicObject = nullptr; } CinematicMgr::~CinematicMgr() { if (m_cinematicCamera && m_activeCinematicCameraId) EndCinematic(); } void CinematicMgr::BeginCinematic() { // Sanity check for active camera set if (m_activeCinematicCameraId == 0) return; auto itr = sFlyByCameraStore.find(m_activeCinematicCameraId); if (itr != sFlyByCameraStore.end()) { // Initialize diff, and set camera m_cinematicDiff = 0; m_cinematicCamera = &itr->second; auto camitr = m_cinematicCamera->begin(); if (camitr != m_cinematicCamera->end()) { Position pos { camitr->locations.x, camitr->locations.y, camitr->locations.z, camitr->locations.w }; if (!pos.IsPositionValid()) return; player->GetMap()->LoadGrid(camitr->locations.x, camitr->locations.y); m_CinematicObject = player->SummonCreature(VISUAL_WAYPOINT, pos.m_positionX, pos.m_positionY, pos.m_positionZ, 0.0f, TEMPSUMMON_TIMED_DESPAWN, 5 * MINUTE * IN_MILLISECONDS); if (m_CinematicObject) { m_CinematicObject->setActive(true); player->SetViewpoint(m_CinematicObject, true); } // Get cinematic length FlyByCameraCollection::const_reverse_iterator camrevitr = m_cinematicCamera->rbegin(); if (camrevitr != m_cinematicCamera->rend()) m_cinematicLength = camrevitr->timeStamp; else m_cinematicLength = 0; } } } void CinematicMgr::EndCinematic() { if (m_activeCinematicCameraId == 0) return; m_cinematicDiff = 0; m_cinematicCamera = nullptr; m_activeCinematicCameraId = 0; if (m_CinematicObject) { if (WorldObject* vpObject = player->GetViewpoint()) if (vpObject == m_CinematicObject) player->SetViewpoint(m_CinematicObject, false); m_CinematicObject->AddObjectToRemoveList(); } } void CinematicMgr::UpdateCinematicLocation(uint32 /*diff*/) { if (m_activeCinematicCameraId == 0 || !m_cinematicCamera || m_cinematicCamera->size() == 0) return; Position lastPosition; uint32 lastTimestamp = 0; Position nextPosition; uint32 nextTimestamp = 0; // Obtain direction of travel for (FlyByCamera cam : *m_cinematicCamera) { if (cam.timeStamp > m_cinematicDiff) { nextPosition = { cam.locations.x, cam.locations.y, cam.locations.z, cam.locations.w }; nextTimestamp = cam.timeStamp; break; } lastPosition = { cam.locations.x, cam.locations.y, cam.locations.z, cam.locations.w }; lastTimestamp = cam.timeStamp; } float angle = lastPosition.GetAngle(&nextPosition); angle -= lastPosition.GetOrientation(); if (angle < 0) angle += 2 * float(M_PI); // Look for position around 2 second ahead of us. int32 workDiff = m_cinematicDiff; // Modify result based on camera direction (Humans for example, have the camera point behind) workDiff += static_cast<int32>(float(CINEMATIC_LOOKAHEAD) * cos(angle)); // Get an iterator to the last entry in the cameras, to make sure we don't go beyond the end FlyByCameraCollection::const_reverse_iterator endItr = m_cinematicCamera->rbegin(); if (endItr != m_cinematicCamera->rend() && workDiff > static_cast<int32>(endItr->timeStamp)) workDiff = endItr->timeStamp; // Never try to go back in time before the start of cinematic! if (workDiff < 0) workDiff = m_cinematicDiff; // Obtain the previous and next waypoint based on timestamp for (FlyByCamera cam : *m_cinematicCamera) { if (static_cast<int32>(cam.timeStamp) >= workDiff) { nextPosition = { cam.locations.x, cam.locations.y, cam.locations.z, cam.locations.w }; nextTimestamp = cam.timeStamp; break; } lastPosition = { cam.locations.x, cam.locations.y, cam.locations.z, cam.locations.w }; lastTimestamp = cam.timeStamp; } // Never try to go beyond the end of the cinematic if (workDiff > static_cast<int32>(nextTimestamp)) workDiff = static_cast<int32>(nextTimestamp); // Interpolate the position for this moment in time (or the adjusted moment in time) uint32 timeDiff = nextTimestamp - lastTimestamp; uint32 interDiff = workDiff - lastTimestamp; float xDiff = nextPosition.m_positionX - lastPosition.m_positionX; float yDiff = nextPosition.m_positionY - lastPosition.m_positionY; float zDiff = nextPosition.m_positionZ - lastPosition.m_positionZ; Position interPosition = { lastPosition.m_positionX + (xDiff * (float(interDiff) / float(timeDiff))), lastPosition.m_positionY + (yDiff * (float(interDiff) / float(timeDiff))), lastPosition.m_positionZ + (zDiff * (float(interDiff) / float(timeDiff))) }; // Advance (at speed) to this position. The remote sight object is used // to send update information to player in cinematic if (m_CinematicObject && interPosition.IsPositionValid()) m_CinematicObject->MonsterMoveWithSpeed(interPosition.m_positionX, interPosition.m_positionY, interPosition.m_positionZ, 500.0f, false, true); // If we never received an end packet 10 seconds after the final timestamp then force an end if (m_cinematicDiff > m_cinematicLength + 10 * IN_MILLISECONDS) EndCinematic(); }
{ "pile_set_name": "Github" }
import React from "react"; import PropTypes from "prop-types"; import Utility from "global/components/utility"; import { UID } from "react-uid"; export default class SelectFilter extends React.PureComponent { static propTypes = { options: PropTypes.array, label: PropTypes.string }; get labelName() { return this.props.label; } get idPrefix() { return "filter"; } render() { return ( <div className={"notes-filter__select-container"}> <UID name={id => `${this.idPrefix}-${id}`}> {id => ( <> <label htmlFor={id} className="screen-reader-text"> {this.labelName} </label> <select id={id} value={this.props.value} onChange={this.props.onChange} className={"notes-filter__select"} > <option value={""}>{this.labelName}</option> {this.props.options.map(option => { return ( <option value={option.value} key={option.value}> {option.label} </option> ); })} </select> <Utility.IconComposer icon="disclosureDown16" size={22} iconClass="notes-filter__icon" /> </> )} </UID> </div> ); } }
{ "pile_set_name": "Github" }
# -*- mode: snippet -*- # key: word # contributor: Translated from TextMate Snippet # name: word-spacing: normal # -- word-spacing: normal;$0
{ "pile_set_name": "Github" }
using UnityEngine; using System.IO; using System.Text; namespace admob { [System.Serializable] public class AdProperties { public bool isForChildDirectedTreatment=false; public bool isUnderAgeOfConsent=false; public bool isAppMuted=false; public bool isTesting=false; public bool nonPersonalizedAdsOnly=false; public int appVolume=100; public string maxAdContentRating;//value can been null or one of G, PG, T, MA, public string[] keywords; public string toString() { string result=JsonUtility.ToJson(this); return result; } } }
{ "pile_set_name": "Github" }
/** * \file drm_scatter.c * IOCTLs to manage scatter/gather memory * * \author Gareth Hughes <[email protected]> */ /* * Created: Mon Dec 18 23:20:54 2000 by [email protected] * * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) 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 * PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include <linux/vmalloc.h> #include <linux/slab.h> #include <drm/drmP.h> #include "drm_legacy.h" #define DEBUG_SCATTER 0 static inline void *drm_vmalloc_dma(unsigned long size) { #if defined(__powerpc__) && defined(CONFIG_NOT_COHERENT_CACHE) return __vmalloc(size, GFP_KERNEL, pgprot_noncached_wc(PAGE_KERNEL)); #else return vmalloc_32(size); #endif } static void drm_sg_cleanup(struct drm_sg_mem * entry) { struct page *page; int i; for (i = 0; i < entry->pages; i++) { page = entry->pagelist[i]; if (page) ClearPageReserved(page); } vfree(entry->virtual); kfree(entry->busaddr); kfree(entry->pagelist); kfree(entry); } void drm_legacy_sg_cleanup(struct drm_device *dev) { if (drm_core_check_feature(dev, DRIVER_SG) && dev->sg && drm_core_check_feature(dev, DRIVER_LEGACY)) { drm_sg_cleanup(dev->sg); dev->sg = NULL; } } #ifdef _LP64 # define ScatterHandle(x) (unsigned int)((x >> 32) + (x & ((1L << 32) - 1))) #else # define ScatterHandle(x) (unsigned int)(x) #endif int drm_legacy_sg_alloc(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_scatter_gather *request = data; struct drm_sg_mem *entry; unsigned long pages, i, j; DRM_DEBUG("\n"); if (!drm_core_check_feature(dev, DRIVER_LEGACY)) return -EINVAL; if (!drm_core_check_feature(dev, DRIVER_SG)) return -EINVAL; if (dev->sg) return -EINVAL; entry = kzalloc(sizeof(*entry), GFP_KERNEL); if (!entry) return -ENOMEM; pages = (request->size + PAGE_SIZE - 1) / PAGE_SIZE; DRM_DEBUG("size=%ld pages=%ld\n", request->size, pages); entry->pages = pages; entry->pagelist = kcalloc(pages, sizeof(*entry->pagelist), GFP_KERNEL); if (!entry->pagelist) { kfree(entry); return -ENOMEM; } entry->busaddr = kcalloc(pages, sizeof(*entry->busaddr), GFP_KERNEL); if (!entry->busaddr) { kfree(entry->pagelist); kfree(entry); return -ENOMEM; } entry->virtual = drm_vmalloc_dma(pages << PAGE_SHIFT); if (!entry->virtual) { kfree(entry->busaddr); kfree(entry->pagelist); kfree(entry); return -ENOMEM; } /* This also forces the mapping of COW pages, so our page list * will be valid. Please don't remove it... */ memset(entry->virtual, 0, pages << PAGE_SHIFT); entry->handle = ScatterHandle((unsigned long)entry->virtual); DRM_DEBUG("handle = %08lx\n", entry->handle); DRM_DEBUG("virtual = %p\n", entry->virtual); for (i = (unsigned long)entry->virtual, j = 0; j < pages; i += PAGE_SIZE, j++) { entry->pagelist[j] = vmalloc_to_page((void *)i); if (!entry->pagelist[j]) goto failed; SetPageReserved(entry->pagelist[j]); } request->handle = entry->handle; dev->sg = entry; #if DEBUG_SCATTER /* Verify that each page points to its virtual address, and vice * versa. */ { int error = 0; for (i = 0; i < pages; i++) { unsigned long *tmp; tmp = page_address(entry->pagelist[i]); for (j = 0; j < PAGE_SIZE / sizeof(unsigned long); j++, tmp++) { *tmp = 0xcafebabe; } tmp = (unsigned long *)((u8 *) entry->virtual + (PAGE_SIZE * i)); for (j = 0; j < PAGE_SIZE / sizeof(unsigned long); j++, tmp++) { if (*tmp != 0xcafebabe && error == 0) { error = 1; DRM_ERROR("Scatter allocation error, " "pagelist does not match " "virtual mapping\n"); } } tmp = page_address(entry->pagelist[i]); for (j = 0; j < PAGE_SIZE / sizeof(unsigned long); j++, tmp++) { *tmp = 0; } } if (error == 0) DRM_ERROR("Scatter allocation matches pagelist\n"); } #endif return 0; failed: drm_sg_cleanup(entry); return -ENOMEM; } int drm_legacy_sg_free(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_scatter_gather *request = data; struct drm_sg_mem *entry; if (!drm_core_check_feature(dev, DRIVER_LEGACY)) return -EINVAL; if (!drm_core_check_feature(dev, DRIVER_SG)) return -EINVAL; entry = dev->sg; dev->sg = NULL; if (!entry || entry->handle != request->handle) return -EINVAL; DRM_DEBUG("virtual = %p\n", entry->virtual); drm_sg_cleanup(entry); return 0; }
{ "pile_set_name": "Github" }
/* Copyright (C) 2013-2019 Expedia Inc. 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. */ package com.hotels.styx.api; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.stream.Stream; import static com.hotels.styx.api.HttpHeader.header; import static com.hotels.styx.api.HttpHeaderNames.CONTENT_LENGTH; import static com.hotels.styx.api.HttpHeaderNames.HOST; import static com.hotels.styx.api.HttpMethod.GET; import static com.hotels.styx.api.HttpMethod.POST; import static com.hotels.styx.api.HttpVersion.HTTP_1_0; import static com.hotels.styx.api.HttpVersion.HTTP_1_1; import static com.hotels.styx.api.LiveHttpRequest.get; import static com.hotels.styx.api.LiveHttpRequest.patch; import static com.hotels.styx.api.LiveHttpRequest.post; import static com.hotels.styx.api.LiveHttpRequest.put; import static com.hotels.styx.api.RequestCookie.requestCookie; import static com.hotels.styx.api.Url.Builder.url; import static com.hotels.styx.support.matchers.IsOptional.isAbsent; import static com.hotels.styx.support.matchers.IsOptional.isValue; import static com.hotels.styx.support.matchers.MapMatcher.isMap; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.emptyIterable; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; public class LiveHttpRequestTest { @Test public void decodesToFullHttpRequest() throws Exception { LiveHttpRequest streamingRequest = post("/foo/bar", body("foo", "bar")) .version(HTTP_1_0) .header("HeaderName", "HeaderValue") .cookies(requestCookie("CookieName", "CookieValue")) .build(); HttpRequest full = Mono.from(streamingRequest.aggregate(0x1000)).block(); assertThat(full.method(), is(POST)); assertThat(full.url(), is(url("/foo/bar").build())); assertThat(full.version(), is(HTTP_1_0)); assertThat(full.headers(), containsInAnyOrder( header("HeaderName", "HeaderValue"), header("Cookie", "CookieName=CookieValue"))); assertThat(full.cookies(), contains(requestCookie("CookieName", "CookieValue"))); assertThat(full.body(), is(bytes("foobar"))); } @Test public void toFullRequestReleasesOriginalReferenceCountedBuffers() throws ExecutionException, InterruptedException { Buffer content = new Buffer("original", UTF_8); LiveHttpRequest original = LiveHttpRequest.get("/foo") .body(new ByteStream(Flux.just(content))) .build(); HttpRequest fullRequest = Mono.from(original.aggregate(100)).block(); assertThat(content.delegate().refCnt(), is(0)); assertThat(fullRequest.bodyAs(UTF_8), is("original")); } @ParameterizedTest @MethodSource("emptyBodyRequests") public void encodesToStreamingHttpRequestWithEmptyBody(LiveHttpRequest streamingRequest) throws Exception { HttpRequest full = Mono.from(streamingRequest.aggregate(0x1000)).block(); assertThat(full.body(), is(new byte[0])); } // We want to ensure that these are all considered equivalent private static Stream<Arguments> emptyBodyRequests() { return Stream.of( Arguments.of(get("/foo/bar").build()), Arguments.of(post("/foo/bar", new ByteStream(Flux.empty())).build()) ); } @Test public void createsARequestWithDefaultValues() { LiveHttpRequest request = get("/index").build(); assertThat(request.version(), is(HTTP_1_1)); assertThat(request.url().toString(), is("/index")); assertThat(request.path(), is("/index")); assertThat(request.id(), is(notNullValue())); assertThat(request.cookies(), is(emptyIterable())); assertThat(request.headers(), is(emptyIterable())); assertThat(request.headers("any"), is(emptyIterable())); assertThat(bytesToString(request.body()), is("")); assertThat(request.cookie("any"), isAbsent()); assertThat(request.header("any"), isAbsent()); assertThat(request.keepAlive(), is(true)); assertThat(request.method(), is(GET)); assertThat(request.queryParam("any"), isAbsent()); assertThat(request.queryParams("any"), is(emptyIterable())); } @Test public void canUseBuilderToSetRequestProperties() { LiveHttpRequest request = patch("https://hotels.com") .version(HTTP_1_0) .id("id") .header("headerName", "a") .cookies(requestCookie("cfoo", "bar")) .build(); assertThat(request.toString(), is("{version=HTTP/1.0, method=PATCH, uri=https://hotels.com, id=id}")); assertThat(request.headers().toString(), is("[headerName=a, Cookie=cfoo=bar, Host=hotels.com]")); } @Test public void canModifyPreviouslyCreatedRequest() { LiveHttpRequest request = get("/foo") .header("remove", "remove") .build(); LiveHttpRequest newRequest = request.newBuilder() .uri("/home") .header("remove", "notanymore") .build(); assertThat(newRequest.url().path(), is("/home")); assertThat(newRequest.headers(), hasItem(header("remove", "notanymore"))); } @Test public void decodesQueryParams() { LiveHttpRequest request = get("http://example.com/?foo=bar") .build(); assertThat(request.queryParam("foo"), isValue("bar")); } @Test public void decodesQueryParamsContainingEncodedEquals() { LiveHttpRequest request = get("http://example.com/?foo=a%2Bb%3Dc") .build(); assertThat(request.queryParam("foo"), isValue("a+b=c")); } @Test public void createsRequestBuilderFromRequest() { LiveHttpRequest originalRequest = get("/home") .cookies(requestCookie("fred", "blogs")) .header("some", "header") .build(); LiveHttpRequest clonedRequest = originalRequest.newBuilder().build(); assertThat(clonedRequest.method(), is(originalRequest.method())); assertThat(clonedRequest.url(), is(originalRequest.url())); assertThat(clonedRequest.headers().toString(), is(originalRequest.headers().toString())); assertThat(clonedRequest.body(), is(originalRequest.body())); } @Test public void extractsSingleQueryParameter() { LiveHttpRequest req = get("http://host.com:8080/path?fish=cod&fruit=orange") .build(); assertThat(req.queryParam("fish"), isValue("cod")); } @Test public void extractsMultipleQueryParameterValues() { LiveHttpRequest req = get("http://host.com:8080/path?fish=cod&fruit=orange&fish=smørflyndre").build(); assertThat(req.queryParams("fish"), contains("cod", "smørflyndre")); } @Test public void extractsMultipleQueryParams() { LiveHttpRequest req = get("http://example.com?foo=bar&foo=hello&abc=def") .build(); assertThat(req.queryParamNames(), containsInAnyOrder("foo", "abc")); assertThat(req.queryParams(), isMap(ImmutableMap.of( "foo", asList("bar", "hello"), "abc", singletonList("def") ))); } @Test public void alwaysReturnsEmptyListWhenThereIsNoQueryString() { LiveHttpRequest req = get("http://host.com:8080/path").build(); assertThat(req.queryParams("fish"), is(emptyIterable())); assertThat(req.queryParam("fish"), isAbsent()); } @Test public void returnsEmptyListWhenThereIsNoSuchParameter() { LiveHttpRequest req = get("http://host.com:8080/path?poisson=cabillaud").build(); assertThat(req.queryParams("fish"), is(emptyIterable())); assertThat(req.queryParam("fish"), isAbsent()); } @Test public void canExtractCookies() { LiveHttpRequest request = get("/") .cookies( requestCookie("cookie1", "foo"), requestCookie("cookie3", "baz"), requestCookie("cookie2", "bar")) .build(); assertThat(request.cookie("cookie1"), isValue(requestCookie("cookie1", "foo"))); assertThat(request.cookie("cookie2"), isValue(requestCookie("cookie2", "bar"))); assertThat(request.cookie("cookie3"), isValue(requestCookie("cookie3", "baz"))); } @Test public void cannotExtractNonExistentCookie() { LiveHttpRequest request = get("/") .cookies( requestCookie("cookie1", "foo"), requestCookie("cookie3", "baz"), requestCookie("cookie2", "bar")) .build(); assertThat(request.cookie("cookie4"), isAbsent()); } @Test public void extractsAllCookies() { LiveHttpRequest request = get("/") .cookies( requestCookie("cookie1", "foo"), requestCookie("cookie3", "baz"), requestCookie("cookie2", "bar")) .build(); assertThat(request.cookies(), containsInAnyOrder( requestCookie("cookie1", "foo"), requestCookie("cookie2", "bar"), requestCookie("cookie3", "baz"))); } @Test public void extractsEmptyIterableIfCookieHeaderNotSet() { LiveHttpRequest request = get("/").build(); assertThat(request.cookies(), is(emptyIterable())); } @Test public void canRemoveAHeader() { Object hdValue = "b"; LiveHttpRequest request = get("/") .header("a", hdValue) .addHeader("c", hdValue) .build(); LiveHttpRequest shouldRemoveHeader = request.newBuilder() .removeHeader("c") .build(); assertThat(shouldRemoveHeader.headers(), contains(header("a", "b"))); } @Test public void shouldSetsContentLengthForNonStreamingBodyMessage() { assertThat(put("/home").body(new ByteStream(Flux.just(new Buffer("Hello", UTF_8)))).build().header(CONTENT_LENGTH), isAbsent()); } @Test public void shouldDetectKeepAlive() { assertThat(get("/index").build().keepAlive(), is(true)); assertThat(get("/index").version(HTTP_1_0).enableKeepAlive().build().keepAlive(), is(true)); assertThat(get("/index").version(HTTP_1_0).build().keepAlive(), is(false)); } @Test public void builderSetsRequestContent() throws Exception { LiveHttpRequest request = post("/foo/bar", body("Foo bar")).build(); assertThat(bytesToString(request.body()), is("Foo bar")); } @Test public void rejectsNullCookie() { assertThrows(NullPointerException.class, () -> get("/").cookies((RequestCookie) null)); } @Test public void rejectsNullCookieName() { assertThrows(IllegalArgumentException.class, () -> get("/").cookies(requestCookie(null, "value")).build()); } @Test public void rejectsNullCookieValue() { assertThrows(NullPointerException.class, () -> get("/").cookies(requestCookie("name", null)).build()); } @Test public void rejectsMultipleContentLengthInSingleHeader() { assertThrows(IllegalArgumentException.class, () -> get("/foo") .addHeader(CONTENT_LENGTH, "15, 16") .build()); } @Test public void rejectsMultipleContentLengthHeaders() { assertThrows(IllegalArgumentException.class, () -> get("/foo") .addHeader(CONTENT_LENGTH, "15") .addHeader(CONTENT_LENGTH, "16") .build()); } @Test public void rejectsInvalidContentLength() { assertThrows(IllegalArgumentException.class, () -> get("/foo") .addHeader(CONTENT_LENGTH, "foo") .build()); } @Test public void createARequestWithStreamingUrl() { LiveHttpRequest request = get("http://www.hotels.com").build(); assertThat(request.url(), is(url("http://www.hotels.com").build())); } @Test public void setsHostHeaderFromAuthorityIfSet() { LiveHttpRequest request = get("http://www.hotels.com").build(); assertThat(request.header(HOST), isValue("www.hotels.com")); } @Test public void createsANewRequestWithSameVersionAsBefore() { LiveHttpRequest v10Request = get("/foo/bar").version(HTTP_1_0).build(); LiveHttpRequest newRequest = v10Request.newBuilder().uri("/blah/blah").build(); assertThat(newRequest.version(), is(HTTP_1_0)); } @Test public void addsCookies() { LiveHttpRequest request = LiveHttpRequest.get("/") .addCookies(requestCookie("x", "x1"), requestCookie("y", "y1")) .build(); assertThat(request.cookies(), containsInAnyOrder(requestCookie("x", "x1"), requestCookie("y", "y1"))); } @Test public void addsCookiesToExistingCookies() { LiveHttpRequest request = LiveHttpRequest.get("/") .addCookies(requestCookie("z", "z1")) .addCookies(requestCookie("x", "x1"), requestCookie("y", "y1")) .build(); assertThat(request.cookies(), containsInAnyOrder(requestCookie("x", "x1"), requestCookie("y", "y1"), requestCookie("z", "z1"))); } @Test public void newCookiesWithDuplicateNamesOverridePreviousOnes() { LiveHttpRequest r1 = LiveHttpRequest.get("/") .cookies(requestCookie("y", "y1")) .build(); LiveHttpRequest r2 = r1.newBuilder().addCookies( requestCookie("y", "y2")) .build(); assertThat(r2.cookies(), contains(requestCookie("y", "y2"))); } @Test public void removesCookies() { LiveHttpRequest r1 = LiveHttpRequest.get("/") .addCookies(requestCookie("x", "x1"), requestCookie("y", "y1")) .build(); LiveHttpRequest r2 = r1.newBuilder() .removeCookies("x") .removeCookies("foo") // ensure that trying to remove a non-existent cookie does not cause Exception .build(); assertThat(r2.cookies(), contains(requestCookie("y", "y1"))); } @Test public void removesCookiesInSameBuilder() { LiveHttpRequest r1 = LiveHttpRequest.get("/") .addCookies(requestCookie("x", "x1")) .removeCookies("x") .build(); assertThat(r1.cookie("x"), isAbsent()); } @Test public void transformsUri() { LiveHttpRequest request = LiveHttpRequest.get("/x").build() .newBuilder() .uri("/y") .build(); assertEquals(request.url().path(), "/y"); } @Test public void transformsId() { LiveHttpRequest request = LiveHttpRequest.get("/").id("abc").build() .newBuilder() .id("xyz") .build(); assertEquals(request.id(), "xyz"); } @Test public void transformsHeader() { LiveHttpRequest request = LiveHttpRequest.get("/").header("X-Styx-ID", "test").build() .newBuilder() .header("X-Styx-ID", "bar") .build(); assertEquals(request.header("X-Styx-ID"), Optional.of("bar")); } @Test public void transformsHeaders() { LiveHttpRequest request = LiveHttpRequest.get("/").headers( new HttpHeaders.Builder() .add("x", "y") .build()) .build() .newBuilder() .headers( new HttpHeaders.Builder() .add("a", "b") .build()) .build(); assertThat(request.header("x"), is(Optional.empty())); assertThat(request.header("a"), is(Optional.of("b"))); } @Test public void transformerAddsHeader() { LiveHttpRequest request = LiveHttpRequest.get("/").build() .newBuilder() .addHeader("x", "y") .build(); assertEquals(request.header("x"), Optional.of("y")); } @Test public void transformerRemovesHeader() { LiveHttpRequest request = LiveHttpRequest.get("/").addHeader("x", "y").build() .newBuilder() .removeHeader("x") .build(); assertEquals(request.header("x"), Optional.empty()); } @Test public void transformsUrl() { LiveHttpRequest request = LiveHttpRequest.get("/").build() .newBuilder() .url(url("/z").build()) .build(); assertEquals(request.url().path(), "/z"); } @Test public void transformsCookies() { LiveHttpRequest request = LiveHttpRequest.get("/").addCookies(requestCookie("cookie", "xyz010")).build() .newBuilder() .cookies(requestCookie("cookie", "xyz202")) .build(); assertEquals(request.cookie("cookie"), Optional.of(requestCookie("cookie", "xyz202"))); } @Test public void transformsCookiesViaList() { LiveHttpRequest request = LiveHttpRequest.get("/").addCookies(requestCookie("cookie", "xyz010")).build() .newBuilder() .cookies(ImmutableList.of(requestCookie("cookie", "xyz202"))) .build(); assertEquals(request.cookie("cookie"), Optional.of(requestCookie("cookie", "xyz202"))); } @Test public void transformsByAddingCookies() { LiveHttpRequest request = LiveHttpRequest.get("/").build() .newBuilder() .addCookies(requestCookie("cookie", "xyz202")) .build(); assertEquals(request.cookie("cookie"), Optional.of(requestCookie("cookie", "xyz202"))); } @Test public void transformsByAddingCookiesList() { LiveHttpRequest request = LiveHttpRequest.get("/").build() .newBuilder() .addCookies(ImmutableList.of(requestCookie("cookie", "xyz202"))) .build(); assertEquals(request.cookie("cookie"), Optional.of(requestCookie("cookie", "xyz202"))); } @Test public void transformsByRemovingCookies() { LiveHttpRequest request = LiveHttpRequest.get("/").addCookies(requestCookie("cookie", "xyz202")).build() .newBuilder() .removeCookies("cookie") .build(); assertEquals(request.cookie("cookie"), Optional.empty()); } @Test public void transformsByRemovingCookieList() { LiveHttpRequest request = LiveHttpRequest.get("/").addCookies(requestCookie("cookie", "xyz202")).build() .newBuilder() .removeCookies(ImmutableList.of("cookie")) .build(); assertEquals(request.cookie("cookie"), Optional.empty()); } @Test public void ensuresContentLengthIsPositive() { Exception e = assertThrows(IllegalArgumentException.class, () -> LiveHttpRequest.post("/y") .header("Content-Length", -3) .build()); assertEquals("Invalid Content-Length found. -3", e.getMessage()); } private static ByteStream body(String... contents) { return new ByteStream( Flux.fromIterable( Stream.of(contents) .map(content -> new Buffer(content, UTF_8)) .collect(toList()))); } private static String bytesToString(ByteStream body) { try { return new String(body.aggregate(100000).get().content(), UTF_8); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } private static byte[] bytes(String content) { return content.getBytes(UTF_8); } }
{ "pile_set_name": "Github" }
/** * Copyright 2007-2016, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.gateway.service.amqp; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import org.kaazing.gateway.service.Service; import org.kaazing.gateway.service.ServiceFactory; import org.kaazing.test.util.MethodExecutionTrace; public class CreateAmqpProxyServiceTest { @Rule public TestRule testExecutionTrace = new MethodExecutionTrace(); @Test public void createTestService() { ServiceFactory factory = ServiceFactory.newServiceFactory(); Service amqpProxyService = factory.newService("amqp.proxy"); Assert.assertNotNull("Failed to create amqp.proxy service", amqpProxyService); } }
{ "pile_set_name": "Github" }
// Copyright (c) 2014-2018 Ceemple Software Ltd. All rights Reserved. // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_IR_CACHINGPASSMANAGER_H #define LLVM_IR_CACHINGPASSMANAGER_H #include "clang/CodeGen/BackendUtil.h" #include <memory> namespace clang { class CompilerInstance; class DependencyMap; } namespace llvm { class raw_pwrite_stream; class CachingPassManager { public: explicit CachingPassManager(clang::CompilerInstance *CI, clang::DependencyMap *DM); ~CachingPassManager(); void emitObj(clang::BackendAction Action, raw_pwrite_stream *AsmOutStream); private: class Implementation; std::unique_ptr<Implementation> Impl; CachingPassManager(CachingPassManager &) = delete; CachingPassManager &operator=(CachingPassManager &) = delete; }; } // End llvm namespace #endif
{ "pile_set_name": "Github" }
DELETE FROM achievement_criteria_data WHERE criteria_id = 3693; INSERT INTO achievement_criteria_data VALUES (3693, 11, 0, 0, 'achievement_bg_control_all_nodes');
{ "pile_set_name": "Github" }
define("ace/snippets/sql",["require","exports","module"], function(require, exports, module) { "use strict"; exports.snippetText = "snippet tbl\n\ create table ${1:table} (\n\ ${2:columns}\n\ );\n\ snippet col\n\ ${1:name} ${2:type} ${3:default ''} ${4:not null}\n\ snippet ccol\n\ ${1:name} varchar2(${2:size}) ${3:default ''} ${4:not null}\n\ snippet ncol\n\ ${1:name} number ${3:default 0} ${4:not null}\n\ snippet dcol\n\ ${1:name} date ${3:default sysdate} ${4:not null}\n\ snippet ind\n\ create index ${3:$1_$2} on ${1:table}(${2:column});\n\ snippet uind\n\ create unique index ${1:name} on ${2:table}(${3:column});\n\ snippet tblcom\n\ comment on table ${1:table} is '${2:comment}';\n\ snippet colcom\n\ comment on column ${1:table}.${2:column} is '${3:comment}';\n\ snippet addcol\n\ alter table ${1:table} add (${2:column} ${3:type});\n\ snippet seq\n\ create sequence ${1:name} start with ${2:1} increment by ${3:1} minvalue ${4:1};\n\ snippet s*\n\ select * from ${1:table}\n\ "; exports.scope = "sql"; });
{ "pile_set_name": "Github" }
require("tests/testsuite") GlobalSettings.lookandfeel.denseparagraphs = false DocumentSet = CreateDocumentSet() AssertEquals(DocumentSet.styles.P.above, 1) GlobalSettings.lookandfeel.denseparagraphs = true DocumentSet = CreateDocumentSet() AssertEquals(DocumentSet.styles.P.above, 0)
{ "pile_set_name": "Github" }
#ifndef CVD_LA_H #define CVD_LA_H #include <iostream> #include <cvd/internal/is_pod.h> namespace CVD { ////////////////////////////// // CVD::La // Template class to represent luminance and alpha components // /// A colour consisting of luminance and alpha components /// @param T The datatype of each component /// @ingroup gImage template <typename T> class La { public: /// Default constructor. Does nothing. La() {} /// Constructs a colour as specified /// @param l The luminance component /// @param a The alpha component La(T l, T a) : luminance(l), alpha(a) {} T luminance; ///< The luminance component T alpha; ///< The alpha component /// Assignment operator /// @param c The colour to copy from La<T>& operator=(const La<T>& c) {luminance = c.luminance; alpha = c.alpha; return *this;} /// Assignment operator between two different storage types, using the standard casts as necessary /// @param c The colour to copy from template <typename T2> La<T>& operator=(const La<T2>& c){ luminance = static_cast<T>(c.luminance); alpha = static_cast<T>(c.alpha); return *this; } /// Logical equals operator. Returns true if each component is the same. /// @param c La to compare with bool operator==(const La<T>& c) const {return luminance == c.luminance && alpha == c.alpha;} /// Logical not-equals operator. Returns true unless each component is the same. /// @param c La to compare with bool operator!=(const La<T>& c) const {return luminance != c.luminance || alpha != c.alpha;} }; /// Write the colour to a stream in the format "(luminance,alpha)" /// @param os The stream /// @param x The colour object /// @relates La template <typename T> std::ostream& operator <<(std::ostream& os, const La<T>& x) { return os << "(" << x.luminance << "," << x.alpha << ")"; } /// Write the colour to a stream in the format "(luminance,alpha)" /// @param os The stream /// @param x The colour object /// @relates La inline std::ostream& operator <<(std::ostream& os, const La<unsigned char>& x) { return os << "(" << static_cast<unsigned int>(x.luminance) << "," << static_cast<unsigned int>(x.alpha) << ")"; } #ifndef DOXYGEN_IGNORE_INTERNAL namespace Internal { template<class C> struct is_POD<La<C> > { enum { is_pod = is_POD<C>::is_pod }; }; } #endif } // end namespace #endif
{ "pile_set_name": "Github" }
import ma = require('azure-pipelines-task-lib/mock-answer'); import tmrm = require('azure-pipelines-task-lib/mock-run'); import path = require('path'); let taskPath = path.join(__dirname, '..', 'deployiiswebapp.js'); let tr: tmrm.TaskMockRunner = new tmrm.TaskMockRunner(taskPath); tr.setInput('WebSiteName', 'mytestwebsite'); tr.setInput('Package', 'Invalid_webAppPkg'); process.env["SYSTEM_DEFAULTWORKINGDIRECTORY"] = "DefaultWorkingDirectory"; // provide answers for task mock let a: ma.TaskLibAnswers = <ma.TaskLibAnswers>{ "glob": { "Invalid_webAppPkg" : [], } } tr.setAnswers(a); tr.run();
{ "pile_set_name": "Github" }
{ "errors":[ { "loc":{"source":null,"start":{"line":2,"column":0},"end":{"line":2,"column":0}}, "message":"Unexpected end of input" } ], "type":"Program", "loc":{"source":null,"start":{"line":2,"column":0},"end":{"line":2,"column":0}}, "range":[5,5], "body":[], "comments":[] }
{ "pile_set_name": "Github" }
# Copyright 2012 Mozilla Foundation # # 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. # Main toolbar buttons (tooltips and alt text for images) previous.title=Eine Seite zurück previous_label=Zurück next.title=Eine Seite vor next_label=Vor # LOCALIZATION NOTE (page_label, page_of): # These strings are concatenated to form the "Page: X of Y" string. # Do not translate "{{pageCount}}", it will be substituted with a number # representing the total number of pages. page_label=Seite: page_of=von {{pageCount}} zoom_out.title=Verkleinern zoom_out_label=Verkleinern zoom_in.title=Vergrößern zoom_in_label=Vergrößern zoom.title=Zoom print.title=Drucken print_label=Drucken presentation_mode.title=In Präsentationsmodus wechseln presentation_mode_label=Präsentationsmodus open_file.title=Datei öffnen open_file_label=Öffnen download.title=Dokument speichern download_label=Speichern bookmark.title=Aktuelle Ansicht (zum Kopieren oder Öffnen in einem neuen Fenster) bookmark_label=Aktuelle Ansicht # Secondary toolbar and context menu tools.title=Werkzeuge tools_label=Werkzeuge first_page.title=Erste Seite anzeigen first_page.label=Erste Seite anzeigen first_page_label=Erste Seite anzeigen last_page.title=Letzte Seite anzeigen last_page.label=Letzte Seite anzeigen last_page_label=Letzte Seite anzeigen page_rotate_cw.title=Im Uhrzeigersinn drehen page_rotate_cw.label=Im Uhrzeigersinn drehen page_rotate_cw_label=Im Uhrzeigersinn drehen page_rotate_ccw.title=Gegen Uhrzeigersinn drehen page_rotate_ccw.label=Gegen Uhrzeigersinn drehen page_rotate_ccw_label=Gegen Uhrzeigersinn drehen hand_tool_enable.title=Hand-Werkzeug aktivieren hand_tool_enable_label=Hand-Werkzeug aktivieren hand_tool_disable.title=Hand-Werkzeug deaktivieren hand_tool_disable_label=Hand-Werkzeug deaktivieren # Document properties dialog box document_properties.title=Dokumenteigenschaften document_properties_label=Dokumenteigenschaften… document_properties_file_name=Dateiname: document_properties_file_size=Dateigröße: document_properties_kb={{size_kb}} KB ({{size_b}} Bytes) document_properties_mb={{size_mb}} MB ({{size_b}} Bytes) document_properties_title=Titel: document_properties_author=Autor: document_properties_subject=Thema: document_properties_keywords=Stichwörter: document_properties_creation_date=Erstelldatum: document_properties_modification_date=Bearbeitungsdatum: document_properties_date_string={{date}} {{time}} document_properties_creator=Anwendung: document_properties_producer=PDF erstellt mit: document_properties_version=PDF-Version: document_properties_page_count=Seitenzahl: document_properties_close=Schließen # Tooltips and alt text for side panel toolbar buttons # (the _label strings are alt text for the buttons, the .title strings are # tooltips) toggle_sidebar.title=Sidebar umschalten toggle_sidebar_label=Sidebar umschalten outline.title=Dokumentstruktur anzeigen outline_label=Dokumentstruktur attachments.title=Anhänge anzeigen attachments_label=Anhänge thumbs.title=Miniaturansichten anzeigen thumbs_label=Miniaturansichten findbar.title=Dokument durchsuchen findbar_label=Suchen # Thumbnails panel item (tooltip and alt text for images) # LOCALIZATION NOTE (thumb_page_title): "{{page}}" will be replaced by the page # number. thumb_page_title=Seite {{page}} # LOCALIZATION NOTE (thumb_page_canvas): "{{page}}" will be replaced by the page # number. thumb_page_canvas=Miniaturansicht von Seite {{page}} # Find panel button title and messages find_label=Suchen: find_previous.title=Vorheriges Vorkommen des Suchbegriffs finden find_previous_label=Zurück find_next.title=Nächstes Vorkommen des Suchbegriffs finden find_next_label=Weiter find_highlight=Alle hervorheben find_match_case_label=Groß-/Kleinschreibung beachten find_reached_top=Anfang des Dokuments erreicht, fahre am Ende fort find_reached_bottom=Ende des Dokuments erreicht, fahre am Anfang fort find_not_found=Suchbegriff nicht gefunden # Error panel labels error_more_info=Mehr Informationen error_less_info=Weniger Informationen error_close=Schließen # LOCALIZATION NOTE (error_version_info): "{{version}}" and "{{build}}" will be # replaced by the PDF.JS version and build ID. error_version_info=PDF.js Version {{version}} (build: {{build}}) # LOCALIZATION NOTE (error_message): "{{message}}" will be replaced by an # english string describing the error. error_message=Nachricht: {{message}} # LOCALIZATION NOTE (error_stack): "{{stack}}" will be replaced with a stack # trace. error_stack=Aufrufliste: {{stack}} # LOCALIZATION NOTE (error_file): "{{file}}" will be replaced with a filename error_file=Datei: {{file}} # LOCALIZATION NOTE (error_line): "{{line}}" will be replaced with a line number error_line=Zeile: {{line}} rendering_error=Beim Darstellen der Seite trat ein Fehler auf. # Predefined zoom values page_scale_width=Seitenbreite page_scale_fit=Seitengröße page_scale_auto=Automatischer Zoom page_scale_actual=Originalgröße # LOCALIZATION NOTE (page_scale_percent): "{{scale}}" will be replaced by a # numerical scale value. page_scale_percent={{scale}}% # Loading indicator messages loading_error_indicator=Fehler loading_error=Beim Laden der PDF-Datei trat ein Fehler auf. invalid_file_error=Ungültige oder beschädigte PDF-Datei missing_file_error=Fehlende PDF-Datei unexpected_response_error=Unerwartete Antwort des Servers # LOCALIZATION NOTE (text_annotation_type.alt): This is used as a tooltip. # "{{type}}" will be replaced with an annotation type from a list defined in # the PDF spec (32000-1:2008 Table 169 – Annotation types). # Some common types are e.g.: "Check", "Text", "Comment", "Note" text_annotation_type.alt=[Anlage: {{type}}] password_label=Geben Sie zum Öffnen der PDF-Datei deren Passwort ein. password_invalid=Falsches Passwort. Bitte versuchen Sie es erneut. password_ok=OK password_cancel=Abbrechen printing_not_supported=Warnung: Die Drucken-Funktion wird durch diesen Browser nicht vollständig unterstützt. printing_not_ready=Warnung: Die PDF-Datei ist nicht vollständig geladen, dies ist für das Drucken aber empfohlen. web_fonts_disabled=Web-Schriftarten sind deaktiviert: Eingebettete PDF-Schriftarten konnten nicht geladen werden. document_colors_not_allowed=PDF-Dokumenten ist es nicht erlaubt, ihre eigenen Farben zu verwenden: 'Seiten das Verwenden von eigenen Farben erlauben' ist im Browser deaktiviert.
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <HTML> <HEAD> <TITLE>Introduction to FreeS/WAN</TITLE> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=iso-8859-1"> <STYLE TYPE="text/css"><!-- BODY { font-family: serif } H1 { font-family: sans-serif } H2 { font-family: sans-serif } H3 { font-family: sans-serif } H4 { font-family: sans-serif } H5 { font-family: sans-serif } H6 { font-family: sans-serif } SUB { font-size: smaller } SUP { font-size: smaller } PRE { font-family: monospace } --></STYLE> </HEAD> <BODY> <A HREF="toc.html">Contents</A> <A HREF="interop.html">Previous</A> <A HREF="testing.html">Next</A> <HR> <H1><A name="performance">Performance of FreeS/WAN</A></H1> The performance of FreeS/WAN is adequate for most applications. <P>In normal operation, the main concern is the overhead for encryption, decryption and authentication of the actual IPsec (<A href="glossary.html#ESP"> ESP</A> and/or<A href="glossary.html#AH"> AH</A>) data packets. Tunnel setup and rekeying occur so much less frequently than packet processing that, in general, their overheads are not worth worrying about.</P> <P>At startup, however, tunnel setup overheads may be significant. If you reboot a gateway and it needs to establish many tunnels, expect some delay. This and other issues for large gateways are discussed<A href="#biggate"> below</A>.</P> <H2><A name="pub.bench">Published material</A></H2> <P>The University of Wales at Aberystwyth has done quite detailed speed tests and put<A href="http://tsc.llwybr.org.uk/public/reports/SWANTIME/"> their results</A> on the web.</P> <P>Davide Cerri's<A href="http://www.linux.it/~davide/doc/"> thesis (in Italian)</A> includes performance results for FreeS/WAN and for<A href="glossary.html#TLS"> TLS</A>. He posted an<A href="http://lists.freeswan.org/pipermail/users/2001-December/006303.html"> English summary</A> on the mailing list.</P> <P>Steve Bellovin used one of AT&amp;T Research's FreeS/WAN gateways as his data source for an analysis of the cache sizes required for key swapping in IPsec. Available as<A href="http://www.research.att.com/~smb/talks/key-agility.email.txt"> text</A> or<A href="http://www.research.att.com/~smb/talks/key-agility.pdf"> PDF slides</A> for a talk on the topic.</P> <P>See also the NAI work mentioned in the next section.</P> <H2><A name="perf.estimate">Estimating CPU overheads</A></H2> <P>We can come up with a formula that roughly relates CPU speed to the rate of IPsec processing possible. It is far from exact, but should be usable as a first approximation.</P> <P>An analysis of authentication overheads for high-speed networks, including some tests using FreeS/WAN, is on the<A href="http://www.pgp.com/research/nailabs/cryptographic/adaptive-cryptographic.asp"> NAI Labs site</A>. In particular, see figure 3 in this<A href="http://download.nai.com/products/media/pgp/pdf/acsa_final_report.pdf"> PDF document</A>. Their estimates of overheads, measured in Pentium II cycles per byte processed are:</P> <TABLE align="center" border="1"><TBODY></TBODY> <TR><TH></TH><TH>IPsec</TH><TH>authentication</TH><TH>encryption</TH><TH> cycles/byte</TH></TR> <TR><TD>Linux IP stack alone</TD><TD>no</TD><TD>no</TD><TD>no</TD><TD align="right"> 5</TD></TR> <TR><TD>IPsec without crypto</TD><TD>yes</TD><TD>no</TD><TD>no</TD><TD align="right"> 11</TD></TR> <TR><TD>IPsec, authentication only</TD><TD>yes</TD><TD>SHA-1</TD><TD>no</TD><TD align="right">24</TD></TR> <TR><TD>IPsec with encryption</TD><TD>yes</TD><TD>yes</TD><TD>yes</TD><TD align="right">not tested</TD></TR> </TABLE> <P>Overheads for IPsec with encryption were not tested in the NAI work, but Antoon Bosselaers'<A href="http://www.esat.kuleuven.ac.be/~bosselae/fast.html"> web page</A> gives cost for his optimised Triple DES implementation as 928 Pentium cycles per block, or 116 per byte. Adding that to the 24 above, we get 140 cycles per byte for IPsec with encryption.</P> <P>At 140 cycles per byte, a 140 MHz machine can handle a megabyte -- 8 megabits -- per second. Speeds for other machines will be proportional to this. To saturate a link with capacity C megabits per second, you need a machine running at<VAR> C * 140/8 = C * 17.5</VAR> MHz.</P> <P>However, that estimate is not precise. It ignores the differences between:</P> <UL> <LI>NAI's test packets and real traffic</LI> <LI>NAI's Pentium II cycles, Bosselaers' Pentium cycles, and your machine's cycles</LI> <LI>different 3DES implementations</LI> <LI>SHA-1 and MD5</LI> </UL> <P>and does not account for some overheads you will almost certainly have:</P> <UL> <LI>communication on the client-side interface</LI> <LI>switching between multiple tunnels -- re-keying, cache reloading and so on</LI> </UL> <P>so we suggest using<VAR> C * 25</VAR> to get an estimate with a bit of a built-in safety factor.</P> <P>This covers only IP and IPsec processing. If you have other loads on your gateway -- for example if it is also working as a firewall -- then you will need to add your own safety factor atop that.</P> <P>This estimate matches empirical data reasonably well. For example, Metheringham's tests, described<A href="#klips.bench"> below</A>, show a 733 topping out between 32 and 36 Mbit/second, pushing data as fast as it can down a 100 Mbit link. Our formula suggests you need at least an 800 to handle a fully loaded 32 Mbit link. The two results are consistent.</P> <P>Some examples using this estimation method:</P> <TABLE align="center" border="1"><TBODY></TBODY> <TR><TH colspan="2">Interface</TH><TH colspan="3">Machine speed in MHz</TH> </TR> <TR><TH>Type</TH><TH>Mbit per <BR> second</TH><TH>Estimate <BR> Mbit*25</TH><TH>Minimum IPSEC gateway</TH><TH>Minimum with other load <P>(e.g. firewall)</P> </TH></TR> <TR><TD>DSL</TD><TD align="right">1</TD><TD align="right">25 MHz</TD><TD rowspan="2"> whatever you have</TD><TD rowspan="2">133, or better if you have it</TD></TR> <TR><TD>cable modem</TD><TD align="right">3</TD><TD align="right">75 MHz</TD> </TR> <TR><TD><STRONG>any link, light load</STRONG></TD><TD align="right"><STRONG> 5</STRONG></TD><TD align="right">125 MHz</TD><TD>133</TD><TD>200+,<STRONG> almost any surplus machine</STRONG></TD></TR> <TR><TD>Ethernet</TD><TD align="right">10</TD><TD align="right">250 MHz</TD><TD> surplus 266 or 300</TD><TD>500+</TD></TR> <TR><TD><STRONG>fast link, moderate load</STRONG></TD><TD align="right"><STRONG> 20</STRONG></TD><TD align="right">500 MHz</TD><TD>500</TD><TD>800+,<STRONG> any current off-the-shelf PC</STRONG></TD></TR> <TR><TD>T3 or E3</TD><TD align="right">45</TD><TD align="right">1125 MHz</TD><TD> 1200</TD><TD>1500+</TD></TR> <TR><TD>fast Ethernet</TD><TD align="right">100</TD><TD align="right"> 2500 MHz</TD><TD align="center" colspan="2" rowspan="2">// not feasible with 3DES in software on current machines //</TD></TR> <TR><TD>OC3</TD><TD align="right">155</TD><TD align="right">3875 MHz</TD> </TR> </TABLE> <P>Such an estimate is far from exact, but should be usable as minimum requirement for planning. The key observations are:</P> <UL> <LI>older<STRONG> surplus machines</STRONG> are fine for IPsec gateways at loads up to<STRONG> 5 megabits per second</STRONG> or so</LI> <LI>a<STRONG> mid-range new machine</STRONG> can handle IPsec at rates up to<STRONG> 20 megabits per second</STRONG> or more</LI> </UL> <H3><A name="perf.more">Higher performance alternatives</A></H3> <P><A href="glossary.html#AES">AES</A> is a new US government block cipher standard, designed to replace the obsolete<A href="glossary.html#DES"> DES</A>. If FreeS/WAN using<A href="glossary.html#3DES"> 3DES</A> is not fast enough for your application, the AES<A href="web.html#patch"> patch</A> may help.</P> <P>To date (March 2002) we have had only one<A href="http://lists.freeswan.org/pipermail/users/2002-February/007771.html"> mailing list report</A> of measurements with the patch applied. It indicates that, at least for the tested load on that user's network,<STRONG> AES roughly doubles IPsec throughput</STRONG>. If further testing confirms this, it may prove possible to saturate an OC3 link in software on a high-end box.</P> <P>Also, some work is being done toward support of<A href="compat.html#hardware"> hardware IPsec acceleration</A> which might extend the range of requirements FreeS/WAN could meet.</P> <H3><A NAME="11_2_2">Other considerations</A></H3> <P>CPU speed may be the main issue for IPsec performance, but of course it isn't the only one.</P> <P>You need good ethernet cards or other network interface hardware to get the best performance. See this<A href="http://www.ethermanage.com/ethernet/ethernet.html"> ethernet information</A> page and this<A href="http://www.scyld.com/diag"> Linux network driver</A> page.</P> <P>The current FreeS/WAN kernel code is largely single-threaded. It is SMP safe, and will run just fine on a multiprocessor machine (<A href="compat.html#multiprocessor"> discussion</A>), but the load within the kernel is not shared effectively. This means that, for example to saturate a T3 -- which needs about a 1200 MHz machine -- you cannot expect something like a dual 800 to do the job.</P> <P>On the other hand, SMP machines do tend to share loads well so -- provided one CPU is fast enough for the IPsec work -- a multiprocessor machine may be ideal for a gateway with a mixed load.</P> <H2><A name="biggate">Many tunnels from a single gateway</A></H2> <P>FreeS/WAN allows a single gateway machine to build tunnels to many others. There may, however, be some problems for large numbers as indicated in this message from the mailing list:</P> <PRE>Subject: Re: Maximum number of ipsec tunnels? Date: Tue, 18 Apr 2000 From: &quot;John S. Denker&quot; &lt;[email protected]&gt; Christopher Ferris wrote: &gt;&gt; What are the maximum number ipsec tunnels FreeS/WAN can handle?? Henry Spencer wrote: &gt;There is no particular limit. Some of the setup procedures currently &gt;scale poorly to large numbers of connections, but there are (clumsy) &gt;workarounds for that now, and proper fixes are coming. 1) &quot;Large&quot; numbers means anything over 50 or so. I routinely run boxes with about 200 tunnels. Once you get more than 50 or so, you need to worry about several scalability issues: a) You need to put a &quot;-&quot; sign in syslogd.conf, and rotate the logs daily not weekly. b) Processor load per tunnel is small unless the tunnel is not up, in which case a new half-key gets generated every 90 seconds, which can add up if you've got a lot of down tunnels. c) There's other bits of lore you need when running a large number of tunnels. For instance, systematically keeping the .conf file free of conflicts requires tools that aren't shipped with the standard freeswan package. d) The pluto startup behavior is quadratic. With 200 tunnels, this eats up several minutes at every restart. I'm told fixes are coming soon. 2) Other than item (1b), the CPU load depends mainly on the size of the pipe attached, not on the number of tunnels. </PRE> <P>It is worth noting that item (1b) applies only to repeated attempts to re-key a data connection (IPsec SA, Phase 2) over an established keying connection (ISAKMP SA, Phase 1). There are two ways to reduce this overhead using settings in<A href="manpage.d/ipsec.conf.5.html"> ipsec.conf(5)</A>:</P> <UL> <LI>set<VAR> keyingtries</VAR> to some small value to limit repetitions</LI> <LI>set<VAR> keylife</VAR> to a short time so that a failing data connection will be cleaned up when the keying connection is reset.</LI> </UL> <P>The overheads for establishing keying connections (ISAKMP SAs, Phase 1) are lower because for these Pluto does not perform expensive operations before receiving a reply from the peer.</P> <P>A gateway that does a lot of rekeying -- many tunnels and/or low settings for tunnel lifetimes -- will also need a lot of<A href="glossary.html#random"> random numbers</A> from the random(4) driver.</P> <H2><A name="low-end">Low-end systems</A></H2> <P><EM>Even a 486 can handle a T1 line</EM>, according to this mailing list message:</P> <PRE>Subject: Re: linux-ipsec: IPSec Masquerade Date: Fri, 15 Jan 1999 11:13:22 -0500 From: Michael Richardson . . . A 486/66 has been clocked by Phil Karn to do 10Mb/s encryption.. that uses all the CPU, so half that to get some CPU, and you have 5Mb/s. 1/3 that for 3DES and you get 1.6Mb/s....</PRE> <P>and a piece of mail from project technical lead Henry Spencer:</P> <PRE>Oh yes, and a new timing point for Sandy's docs... A P60 -- yes, a 60MHz Pentium, talk about antiques -- running a host-to-host tunnel to another machine shows an FTP throughput (that is, end-to-end results with a real protocol) of slightly over 5Mbit/s either way. (The other machine is much faster, the network is 100Mbps, and the ether cards are good ones... so the P60 is pretty definitely the bottleneck.)</PRE> <P>From the above, and from general user experience as reported on the list, it seems clear that a cheap surplus machine -- a reasonable 486, a minimal Pentium box, a Sparc 5, ... -- can easily handle a home office or a small company connection using any of:</P> <UL> <LI>ADSL service</LI> <LI>cable modem</LI> <LI>T1</LI> <LI>E1</LI> </UL> <P>If available, we suggest using a Pentium 133 or better. This should ensure that, even under maximum load, IPsec will use less than half the CPU cycles. You then have enough left for other things you may want on your gateway -- firewalling, web caching, DNS and such.</P> <H2><A name="klips.bench">Measuring KLIPS</A></H2> <P>Here is some additional data from the mailing list.</P> <PRE>Subject: FreeSWAN (specically KLIPS) performance measurements Date: Thu, 01 Feb 2001 From: Nigel Metheringham &lt;[email protected]&gt; I've spent a happy morning attempting performance tests against KLIPS (this is due to me not being able to work out the CPU usage of KLIPS so resorting to the crude measurements of maximum throughput to give a baseline to work out loading of a box). Measurements were done using a set of 4 boxes arranged in a line, each connected to the next by 100Mbit duplex ethernet. The inner 2 had an ipsec tunnel between them (shared secret, but I was doing measurements when the tunnel was up and running - keying should not be an issue here). The outer pair of boxes were traffic generators or traffic sink. The crypt boxes are Compaq DL380s - Uniprocessor PIII/733 with 256K cache. They have 128M main memory. Nothing significant was running on the boxes other than freeswan. The kernel was a 2.2.19pre7 patched with freeswan and ext3. Without an ipsec tunnel in the chain (ie the 2 inner boxes just being 100BaseT routers), throughput (measured with ttcp) was between 10644 and 11320 KB/sec With an ipsec tunnel in place, throughput was between 3268 and 3402 KB/sec These measurements are for data pushed across a TCP link, so the traffic on the wire between the 2 ipsec boxes would have been higher than this.... vmstat (run during some other tests, so not affecting those figures) on the encrypting box shows approx 50% system &amp; 50% idle CPU - which I don't believe at all. Interactive feel of the box was significantly sluggish. I also tried running the kernel profiler (see man readprofile) during test runs. A box doing primarily decrypt work showed basically nothing happening - I assume interrupts were off. A box doing encrypt work showed the following:- Ticks Function Load ~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~ 956 total 0.0010 532 des_encrypt2 0.1330 110 MD5Transform 0.0443 97 kmalloc 0.1880 39 des_encrypt3 0.1336 23 speedo_interrupt 0.0298 14 skb_copy_expand 0.0250 13 ipsec_tunnel_start_xmit 0.0009 13 Decode 0.1625 11 handle_IRQ_event 0.1019 11 .des_ncbc_encrypt_end 0.0229 10 speedo_start_xmit 0.0188 9 satoa 0.0225 8 kfree 0.0118 8 ip_fragment 0.0121 7 ultoa 0.0365 5 speedo_rx 0.0071 5 .des_encrypt2_end 5.0000 4 _stext 0.0140 4 ip_fw_check 0.0035 2 rj_match 0.0034 2 ipfw_output_check 0.0200 2 inet_addr_type 0.0156 2 eth_copy_and_sum 0.0139 2 dev_get 0.0294 2 addrtoa 0.0143 1 speedo_tx_buffer_gc 0.0024 1 speedo_refill_rx_buf 0.0022 1 restore_all 0.0667 1 number 0.0020 1 net_bh 0.0021 1 neigh_connected_output 0.0076 1 MD5Final 0.0083 1 kmem_cache_free 0.0016 1 kmem_cache_alloc 0.0022 1 __kfree_skb 0.0060 1 ipsec_rcv 0.0001 1 ip_rcv 0.0014 1 ip_options_fragment 0.0071 1 ip_local_deliver 0.0023 1 ipfw_forward_check 0.0139 1 ip_forward 0.0011 1 eth_header 0.0040 1 .des_encrypt3_end 0.0833 1 des_decrypt3 0.0034 1 csum_partial_copy_generic 0.0045 1 call_out_firewall 0.0125 Hope this data is helpful to someone... however the lack of visibility into the decrypt side makes things less clear</PRE> <H2><A name="speed.compress">Speed with compression</A></H2> <P>Another user reported some results for connections with and without IP compression:</P> <PRE>Subject: [Users] Speed with compression Date: Fri, 29 Jun 2001 From: John McMonagle &lt;[email protected]&gt; Did a couple tests with compression using the new 1.91 freeswan. Running between 2 sites with cable modems. Both using approximately 130 mhz pentium. Transferred files with ncftp. Compressed file was a 6mb compressed installation file. Non compressed was 18mb /var/lib/rpm/packages.rpm Compressed vpn regular vpn Compress file 42.59 kBs 42.08 kBs regular file 110.84 kBs 41.66 kBs Load was about 0 either way. Ping times were very similar a bit above 9 ms. Compression looks attractive to me.</PRE> Later in the same thread, project technical lead Henry Spencer added: <PRE>&gt; is there a reason not to switch compression on? I have large gateway boxes &gt; connecting 3 connections, one of them with a measly DS1 link... Run some timing tests with and without, with data and loads representative of what you expect in production. That's the definitive way to decide. If compression is a net loss, then obviously, leave it turned off. If it doesn't make much difference, leave it off for simplicity and hence robustness. If there's a substantial gain, by all means turn it on. If both ends support compression and can successfully negotiate a compressed connection (trivially true if both are FreeS/WAN 1.91), then the crucial question is CPU cycles. Compression has some overhead, so one question is whether *your* data compresses well enough to save you more CPU cycles (by reducing the volume of data going through CPU-intensive encryption/decryption) than it costs you. Last time I ran such tests on data that was reasonably compressible but not deliberately contrived to be so, this generally was not true -- compression cost extra CPU cycles -- so compression was worthwhile only if the link, not the CPU, was the bottleneck. However, that was before the slow-compression bug was fixed. I haven't had a chance to re-run those tests yet, but it sounds like I'd probably see a different result. </PRE> The bug he refers to was a problem with the compression libraries that had us using C code, rather than assembler, for compression. It was fixed before 1.91. <H2><A name="methods">Methods of measuring</A></H2> <P>If you want to measure the loads FreeS/WAN puts on a system, note that tools such as top or measurements such as load average are more-or-less useless for this. They are not designed to measure something that does most of its work inside the kernel.</P> <P>Here is a message from FreeS/WAN kernel programmer Richard Guy Briggs on this:</P> <PRE>&gt; I have a batch of boxes doing Freeswan stuff. &gt; I want to measure the CPU loading of the Freeswan tunnels, but am &gt; having trouble seeing how I get some figures out... &gt; &gt; - Keying etc is in userspace so will show up on the per-process &gt; and load average etc (ie pluto's load) Correct. &gt; - KLIPS is in the kernel space, and does not show up in load average &gt; I think also that the KLIPS per-packet processing stuff is running &gt; as part of an interrupt handler so it does not show up in the &gt; /proc/stat system_cpu or even idle_cpu figures It is not running in interrupt handler. It is in the bottom half. This is somewhere between user context (careful, this is not userspace!) and hardware interrupt context. &gt; Is this correct, and is there any means of instrumenting how much the &gt; cpu is being loaded - I don't like the idea of a system running out of &gt; steam whilst still showing 100% idle CPU :-) vmstat seems to do a fairly good job, but use a running tally to get a good idea. A one-off call to vmstat gives different numbers than a running stat. To do this, put an interval on your vmstat command line.</PRE> and another suggestion from the same thread: <PRE>Subject: Re: Measuring the CPU usage of Freeswan Date: Mon, 29 Jan 2001 From: Patrick Michael Kane &lt;[email protected]&gt; The only truly accurate way to accurately track FreeSWAN CPU usage is to use a CPU soaker. You run it on an unloaded system as a benchmark, then start up FreeSWAN and take the difference to determine how much FreeSWAN is eating. I believe someone has done this in the past, so you may find something in the FreeSWAN archives. If not, someone recently posted a URL to a CPU soaker benchmark tool on linux-kernel.</PRE> <HR> <A HREF="toc.html">Contents</A> <A HREF="interop.html">Previous</A> <A HREF="testing.html">Next</A> </BODY> </HTML>
{ "pile_set_name": "Github" }
/* Substitute for and wrapper around <langinfo.h>. Copyright (C) 2009-2016 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. */ /* * POSIX <langinfo.h> for platforms that lack it or have an incomplete one. * <http://www.opengroup.org/onlinepubs/9699919799/basedefs/langinfo.h.html> */ #ifndef _@GUARD_PREFIX@_LANGINFO_H #if __GNUC__ >= 3 @PRAGMA_SYSTEM_HEADER@ #endif @PRAGMA_COLUMNS@ /* The include_next requires a split double-inclusion guard. */ #if @HAVE_LANGINFO_H@ # @INCLUDE_NEXT@ @NEXT_LANGINFO_H@ #endif #ifndef _@GUARD_PREFIX@_LANGINFO_H #define _@GUARD_PREFIX@_LANGINFO_H #if !@HAVE_LANGINFO_H@ /* A platform that lacks <langinfo.h>. */ /* Assume that it also lacks <nl_types.h> and the nl_item type. */ # if !GNULIB_defined_nl_item typedef int nl_item; # define GNULIB_defined_nl_item 1 # endif /* nl_langinfo items of the LC_CTYPE category */ # define CODESET 10000 /* nl_langinfo items of the LC_NUMERIC category */ # define RADIXCHAR 10001 # define DECIMAL_POINT RADIXCHAR # define THOUSEP 10002 # define THOUSANDS_SEP THOUSEP # define GROUPING 10114 /* nl_langinfo items of the LC_TIME category */ # define D_T_FMT 10003 # define D_FMT 10004 # define T_FMT 10005 # define T_FMT_AMPM 10006 # define AM_STR 10007 # define PM_STR 10008 # define DAY_1 10009 # define DAY_2 (DAY_1 + 1) # define DAY_3 (DAY_1 + 2) # define DAY_4 (DAY_1 + 3) # define DAY_5 (DAY_1 + 4) # define DAY_6 (DAY_1 + 5) # define DAY_7 (DAY_1 + 6) # define ABDAY_1 10016 # define ABDAY_2 (ABDAY_1 + 1) # define ABDAY_3 (ABDAY_1 + 2) # define ABDAY_4 (ABDAY_1 + 3) # define ABDAY_5 (ABDAY_1 + 4) # define ABDAY_6 (ABDAY_1 + 5) # define ABDAY_7 (ABDAY_1 + 6) # define MON_1 10023 # define MON_2 (MON_1 + 1) # define MON_3 (MON_1 + 2) # define MON_4 (MON_1 + 3) # define MON_5 (MON_1 + 4) # define MON_6 (MON_1 + 5) # define MON_7 (MON_1 + 6) # define MON_8 (MON_1 + 7) # define MON_9 (MON_1 + 8) # define MON_10 (MON_1 + 9) # define MON_11 (MON_1 + 10) # define MON_12 (MON_1 + 11) # define ABMON_1 10035 # define ABMON_2 (ABMON_1 + 1) # define ABMON_3 (ABMON_1 + 2) # define ABMON_4 (ABMON_1 + 3) # define ABMON_5 (ABMON_1 + 4) # define ABMON_6 (ABMON_1 + 5) # define ABMON_7 (ABMON_1 + 6) # define ABMON_8 (ABMON_1 + 7) # define ABMON_9 (ABMON_1 + 8) # define ABMON_10 (ABMON_1 + 9) # define ABMON_11 (ABMON_1 + 10) # define ABMON_12 (ABMON_1 + 11) # define ERA 10047 # define ERA_D_FMT 10048 # define ERA_D_T_FMT 10049 # define ERA_T_FMT 10050 # define ALT_DIGITS 10051 /* nl_langinfo items of the LC_MONETARY category */ # define CRNCYSTR 10052 # define CURRENCY_SYMBOL CRNCYSTR # define INT_CURR_SYMBOL 10100 # define MON_DECIMAL_POINT 10101 # define MON_THOUSANDS_SEP 10102 # define MON_GROUPING 10103 # define POSITIVE_SIGN 10104 # define NEGATIVE_SIGN 10105 # define FRAC_DIGITS 10106 # define INT_FRAC_DIGITS 10107 # define P_CS_PRECEDES 10108 # define N_CS_PRECEDES 10109 # define P_SEP_BY_SPACE 10110 # define N_SEP_BY_SPACE 10111 # define P_SIGN_POSN 10112 # define N_SIGN_POSN 10113 /* nl_langinfo items of the LC_MESSAGES category */ # define YESEXPR 10053 # define NOEXPR 10054 #else /* A platform that has <langinfo.h>. */ # if !@HAVE_LANGINFO_CODESET@ # define CODESET 10000 # define GNULIB_defined_CODESET 1 # endif # if !@HAVE_LANGINFO_T_FMT_AMPM@ # define T_FMT_AMPM 10006 # define GNULIB_defined_T_FMT_AMPM 1 # endif # if !@HAVE_LANGINFO_ERA@ # define ERA 10047 # define ERA_D_FMT 10048 # define ERA_D_T_FMT 10049 # define ERA_T_FMT 10050 # define ALT_DIGITS 10051 # define GNULIB_defined_ERA 1 # endif # if !@HAVE_LANGINFO_YESEXPR@ # define YESEXPR 10053 # define NOEXPR 10054 # define GNULIB_defined_YESEXPR 1 # endif #endif /* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */ /* The definition of _GL_WARN_ON_USE is copied here. */ /* Declare overridden functions. */ /* Return a piece of locale dependent information. Note: The difference between nl_langinfo (CODESET) and locale_charset () is that the latter normalizes the encoding names to GNU conventions. */ #if @GNULIB_NL_LANGINFO@ # if @REPLACE_NL_LANGINFO@ # if !(defined __cplusplus && defined GNULIB_NAMESPACE) # undef nl_langinfo # define nl_langinfo rpl_nl_langinfo # endif _GL_FUNCDECL_RPL (nl_langinfo, char *, (nl_item item)); _GL_CXXALIAS_RPL (nl_langinfo, char *, (nl_item item)); # else # if !@HAVE_NL_LANGINFO@ _GL_FUNCDECL_SYS (nl_langinfo, char *, (nl_item item)); # endif _GL_CXXALIAS_SYS (nl_langinfo, char *, (nl_item item)); # endif _GL_CXXALIASWARN (nl_langinfo); #elif defined GNULIB_POSIXCHECK # undef nl_langinfo # if HAVE_RAW_DECL_NL_LANGINFO _GL_WARN_ON_USE (nl_langinfo, "nl_langinfo is not portable - " "use gnulib module nl_langinfo for portability"); # endif #endif #endif /* _@GUARD_PREFIX@_LANGINFO_H */ #endif /* _@GUARD_PREFIX@_LANGINFO_H */
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.6"/> <title>LiquidFun: Dynamics Directory Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">LiquidFun </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.6 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark">&#160;</span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark">&#160;</span>Enumerator</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(8)"><span class="SelectionMark">&#160;</span>Macros</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(9)"><span class="SelectionMark">&#160;</span>Pages</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_4adbe910e807faea824f4d71cf48195e.html">Dynamics</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">Dynamics Directory Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="subdirs"></a> Directories</h2></td></tr> <tr class="memitem:dir_39037f20ed96345475e9b075eb4f4bd4"><td class="memItemLeft" align="right" valign="top">directory &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="dir_39037f20ed96345475e9b075eb4f4bd4.html">Contacts</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:dir_7e1edc0ba8e5612421d823d0da568df6"><td class="memItemLeft" align="right" valign="top">directory &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="dir_7e1edc0ba8e5612421d823d0da568df6.html">Joints</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="files"></a> Files</h2></td></tr> <tr class="memitem:b2_body_8cpp"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>b2Body.cpp</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:b2_body_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>b2Body.h</b> <a href="b2_body_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:b2_contact_manager_8cpp"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>b2ContactManager.cpp</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:b2_contact_manager_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>b2ContactManager.h</b> <a href="b2_contact_manager_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:b2_fixture_8cpp"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>b2Fixture.cpp</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:b2_fixture_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>b2Fixture.h</b> <a href="b2_fixture_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:b2_island_8cpp"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>b2Island.cpp</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:b2_island_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>b2Island.h</b> <a href="b2_island_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:b2_time_step_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>b2TimeStep.h</b> <a href="b2_time_step_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:b2_world_8cpp"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>b2World.cpp</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:b2_world_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>b2World.h</b> <a href="b2_world_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:b2_world_callbacks_8cpp"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>b2WorldCallbacks.cpp</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:b2_world_callbacks_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>b2WorldCallbacks.h</b> <a href="b2_world_callbacks_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> <!-- Google Analytics --> <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-46159502-1', 'auto'); ga('create', 'UA-49880327-7', 'auto', {'name': 'liquidFunTracker'}); ga('send', 'pageview'); ga('liquidFunTracker.send', 'pageview'); </script> </body> </html>
{ "pile_set_name": "Github" }
/* ----------------------------------------------------------------------- ffi.c - Copyright (c) 2013 Tensilica, Inc. XTENSA Foreign Function Interface Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ``Software''), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #include <ffi.h> #include <ffi_common.h> /* |----------------------------------------| | | on entry to ffi_call ----> |----------------------------------------| | caller stack frame for registers a0-a3 | |----------------------------------------| | | | additional arguments | entry of the function ---> |----------------------------------------| | copy of function arguments a2-a7 | | - - - - - - - - - - - - - | | | The area below the entry line becomes the new stack frame for the function. */ #define FFI_TYPE_STRUCT_REGS FFI_TYPE_LAST extern void ffi_call_SYSV(void *rvalue, unsigned rsize, unsigned flags, void(*fn)(void), unsigned nbytes, extended_cif*); extern void ffi_closure_SYSV(void) FFI_HIDDEN; ffi_status ffi_prep_cif_machdep(ffi_cif *cif) { switch(cif->rtype->type) { case FFI_TYPE_SINT8: case FFI_TYPE_UINT8: case FFI_TYPE_SINT16: case FFI_TYPE_UINT16: cif->flags = cif->rtype->type; break; case FFI_TYPE_VOID: case FFI_TYPE_FLOAT: cif->flags = FFI_TYPE_UINT32; break; case FFI_TYPE_DOUBLE: case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: cif->flags = FFI_TYPE_UINT64; // cif->rtype->type; break; case FFI_TYPE_STRUCT: cif->flags = FFI_TYPE_STRUCT; //_REGS; /* Up to 16 bytes are returned in registers */ if (cif->rtype->size > 4 * 4) { /* returned structure is referenced by a register; use 8 bytes (including 4 bytes for potential additional alignment) */ cif->flags = FFI_TYPE_STRUCT; cif->bytes += 8; } break; default: cif->flags = FFI_TYPE_UINT32; break; } /* Round the stack up to a full 4 register frame, just in case (we use this size in movsp). This way, it's also a multiple of 8 bytes for 64-bit arguments. */ cif->bytes = ALIGN(cif->bytes, 16); return FFI_OK; } void ffi_prep_args(extended_cif *ecif, unsigned char* stack) { unsigned int i; unsigned long *addr; ffi_type **ptr; union { void **v; char **c; signed char **sc; unsigned char **uc; signed short **ss; unsigned short **us; unsigned int **i; long long **ll; float **f; double **d; } p_argv; /* Verify that everything is aligned up properly */ FFI_ASSERT (((unsigned long) stack & 0x7) == 0); p_argv.v = ecif->avalue; addr = (unsigned long*)stack; /* structures with a size greater than 16 bytes are passed in memory */ if (ecif->cif->rtype->type == FFI_TYPE_STRUCT && ecif->cif->rtype->size > 16) { *addr++ = (unsigned long)ecif->rvalue; } for (i = ecif->cif->nargs, ptr = ecif->cif->arg_types; i > 0; i--, ptr++, p_argv.v++) { switch ((*ptr)->type) { case FFI_TYPE_SINT8: *addr++ = **p_argv.sc; break; case FFI_TYPE_UINT8: *addr++ = **p_argv.uc; break; case FFI_TYPE_SINT16: *addr++ = **p_argv.ss; break; case FFI_TYPE_UINT16: *addr++ = **p_argv.us; break; case FFI_TYPE_FLOAT: case FFI_TYPE_INT: case FFI_TYPE_UINT32: case FFI_TYPE_SINT32: case FFI_TYPE_POINTER: *addr++ = **p_argv.i; break; case FFI_TYPE_DOUBLE: case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: if (((unsigned long)addr & 4) != 0) addr++; *(unsigned long long*)addr = **p_argv.ll; addr += sizeof(unsigned long long) / sizeof (addr); break; case FFI_TYPE_STRUCT: { unsigned long offs; unsigned long size; if (((unsigned long)addr & 4) != 0 && (*ptr)->alignment > 4) addr++; offs = (unsigned long) addr - (unsigned long) stack; size = (*ptr)->size; /* Entire structure must fit the argument registers or referenced */ if (offs < FFI_REGISTER_NARGS * 4 && offs + size > FFI_REGISTER_NARGS * 4) addr = (unsigned long*) (stack + FFI_REGISTER_NARGS * 4); memcpy((char*) addr, *p_argv.c, size); addr += (size + 3) / 4; break; } default: FFI_ASSERT(0); } } } void ffi_call(ffi_cif* cif, void(*fn)(void), void *rvalue, void **avalue) { extended_cif ecif; unsigned long rsize = cif->rtype->size; int flags = cif->flags; void *alloc = NULL; ecif.cif = cif; ecif.avalue = avalue; /* Note that for structures that are returned in registers (size <= 16 bytes) we allocate a temporary buffer and use memcpy to copy it to the final destination. The reason is that the target address might be misaligned or the length not a multiple of 4 bytes. Handling all those cases would be very complex. */ if (flags == FFI_TYPE_STRUCT && (rsize <= 16 || rvalue == NULL)) { alloc = alloca(ALIGN(rsize, 4)); ecif.rvalue = alloc; } else { ecif.rvalue = rvalue; } if (cif->abi != FFI_SYSV) FFI_ASSERT(0); ffi_call_SYSV (ecif.rvalue, rsize, cif->flags, fn, cif->bytes, &ecif); if (alloc != NULL && rvalue != NULL) memcpy(rvalue, alloc, rsize); } extern void ffi_trampoline(); extern void ffi_cacheflush(void* start, void* end); ffi_status ffi_prep_closure_loc (ffi_closure* closure, ffi_cif* cif, void (*fun)(ffi_cif*, void*, void**, void*), void *user_data, void *codeloc) { /* copye trampoline to stack and patch 'ffi_closure_SYSV' pointer */ memcpy(closure->tramp, ffi_trampoline, FFI_TRAMPOLINE_SIZE); *(unsigned int*)(&closure->tramp[8]) = (unsigned int)ffi_closure_SYSV; // Do we have this function? // __builtin___clear_cache(closer->tramp, closer->tramp + FFI_TRAMPOLINE_SIZE) ffi_cacheflush(closure->tramp, closure->tramp + FFI_TRAMPOLINE_SIZE); closure->cif = cif; closure->fun = fun; closure->user_data = user_data; return FFI_OK; } long FFI_HIDDEN ffi_closure_SYSV_inner(ffi_closure *closure, void **values, void *rvalue) { ffi_cif *cif; ffi_type **arg_types; void **avalue; int i, areg; cif = closure->cif; if (cif->abi != FFI_SYSV) return FFI_BAD_ABI; areg = 0; int rtype = cif->rtype->type; if (rtype == FFI_TYPE_STRUCT && cif->rtype->size > 4 * 4) { rvalue = *values; areg++; } cif = closure->cif; arg_types = cif->arg_types; avalue = alloca(cif->nargs * sizeof(void *)); for (i = 0; i < cif->nargs; i++) { if (arg_types[i]->alignment == 8 && (areg & 1) != 0) areg++; // skip the entry 16,a1 framework, add 16 bytes (4 registers) if (areg == FFI_REGISTER_NARGS) areg += 4; if (arg_types[i]->type == FFI_TYPE_STRUCT) { int numregs = ((arg_types[i]->size + 3) & ~3) / 4; if (areg < FFI_REGISTER_NARGS && areg + numregs > FFI_REGISTER_NARGS) areg = FFI_REGISTER_NARGS + 4; } avalue[i] = &values[areg]; areg += (arg_types[i]->size + 3) / 4; } (closure->fun)(cif, rvalue, avalue, closure->user_data); return rtype; }
{ "pile_set_name": "Github" }
/* http://jmblog.github.com/color-themes-for-google-code-highlightjs */ /* Tomorrow Comment */ .hljs-comment, .hljs-quote { color: #8e908c; } /* Tomorrow Red */ .hljs-variable, .hljs-template-variable, .hljs-tag, .hljs-name, .hljs-selector-id, .hljs-selector-class, .hljs-regexp, .hljs-deletion { color: #c82829; } /* Tomorrow Orange */ .hljs-number, .hljs-built_in, .hljs-builtin-name, .hljs-literal, .hljs-type, .hljs-params, .hljs-meta, .hljs-link { color: #f5871f; } /* Tomorrow Yellow */ .hljs-attribute { color: #eab700; } /* Tomorrow Green */ .hljs-string, .hljs-symbol, .hljs-bullet, .hljs-addition { color: #718c00; } /* Tomorrow Blue */ .hljs-title, .hljs-section { color: #4271ae; } /* Tomorrow Purple */ .hljs-keyword, .hljs-selector-tag { color: #8959a8; } .hljs { display: block; overflow-x: auto; background: white; color: #4d4d4c; padding: 0.5em; } .hljs-emphasis { font-style: italic; } .hljs-strong { font-weight: bold; }
{ "pile_set_name": "Github" }
-- things that are libc only, not syscalls -- this file will not be included if not running with libc eg for rump local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local function init(S) local c = S.c local types = S.types local t, s, pt = types.t, types.s, types.pt local ffi = require "ffi" local h = require "syscall.helpers" local zeropointer = pt.void(0) local function retbool(ret) if ret == -1 then return nil, t.error() end return true end -- if getcwd not defined, fall back to libc implementation (currently osx, freebsd) -- freebsd implementation fairly complex if not S.getcwd then ffi.cdef [[ char *getcwd(char *buf, size_t size); ]] function S.getcwd(buf, size) size = size or c.PATH_MAX buf = buf or t.buffer(size) local ret = ffi.C.getcwd(buf, size) if ret == zeropointer then return nil, t.error() end return ffi.string(buf) end end -- in NetBSD, OSX exit defined in libc, no _exit syscall available if not S.exit then function S.exit(status) return retbool(ffi.C.exit(c.EXIT[status or 0])) end end if not S._exit then S._exit = S.exit -- provide syscall exit if possible end ffi.cdef [[ int __cxa_atexit(void (*func) (void *), void * arg, void * dso_handle); ]] local function inlibc(k) return ffi.C[k] end if pcall(inlibc, "exit") and pcall(inlibc, "__cxa_atexit") then function S.exit(status) return retbool(ffi.C.exit(c.EXIT[status or 0])) end -- use libc exit instead function S.atexit(f) return retbool(ffi.C.__cxa_atexit(f, nil, nil)) end end --[[ -- need more types defined int uname(struct utsname *buf); time_t time(time_t *t); ]] --[[ int gethostname(char *name, size_t namelen); int sethostname(const char *name, size_t len); int getdomainname(char *name, size_t namelen); int setdomainname(const char *name, size_t len); --]] -- environment ffi.cdef [[ // environment extern char **environ; int setenv(const char *name, const char *value, int overwrite); int unsetenv(const char *name); int clearenv(void); char *getenv(const char *name); ]] function S.environ() -- return whole environment as table local environ = ffi.C.environ if not environ then return nil end local r = {} local i = 0 while environ[i] ~= zeropointer do local e = ffi.string(environ[i]) local eq = e:find('=') if eq then r[e:sub(1, eq - 1)] = e:sub(eq + 1) end i = i + 1 end return r end function S.getenv(name) return S.environ()[name] end function S.unsetenv(name) return retbool(ffi.C.unsetenv(name)) end function S.setenv(name, value, overwrite) overwrite = h.booltoc(overwrite) -- allows nil as false/0 return retbool(ffi.C.setenv(name, value, overwrite)) end function S.clearenv() return retbool(ffi.C.clearenv()) end S.errno = ffi.errno return S end return {init = init}
{ "pile_set_name": "Github" }
/* Copyright 2019 ZeroEx Intl. 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. */ pragma solidity ^0.5.9; library LibWethUtilsRichErrors { // bytes4(keccak256("UnregisteredAssetProxyError()")) bytes4 internal constant UNREGISTERED_ASSET_PROXY_ERROR_SELECTOR = 0xf3b96b8d; // bytes4(keccak256("InsufficientEthForFeeError(uint256,uint256)")) bytes4 internal constant INSUFFICIENT_ETH_FOR_FEE_ERROR_SELECTOR = 0xecf40fd9; // bytes4(keccak256("DefaultFunctionWethContractOnlyError(address)")) bytes4 internal constant DEFAULT_FUNCTION_WETH_CONTRACT_ONLY_ERROR_SELECTOR = 0x08b18698; // bytes4(keccak256("EthFeeLengthMismatchError(uint256,uint256)")) bytes4 internal constant ETH_FEE_LENGTH_MISMATCH_ERROR_SELECTOR = 0x3ecb6ceb; // solhint-disable func-name-mixedcase function UnregisteredAssetProxyError() internal pure returns (bytes memory) { return abi.encodeWithSelector(UNREGISTERED_ASSET_PROXY_ERROR_SELECTOR); } function InsufficientEthForFeeError( uint256 ethFeeRequired, uint256 ethAvailable ) internal pure returns (bytes memory) { return abi.encodeWithSelector( INSUFFICIENT_ETH_FOR_FEE_ERROR_SELECTOR, ethFeeRequired, ethAvailable ); } function DefaultFunctionWethContractOnlyError( address senderAddress ) internal pure returns (bytes memory) { return abi.encodeWithSelector( DEFAULT_FUNCTION_WETH_CONTRACT_ONLY_ERROR_SELECTOR, senderAddress ); } function EthFeeLengthMismatchError( uint256 ethFeesLength, uint256 feeRecipientsLength ) internal pure returns (bytes memory) { return abi.encodeWithSelector( ETH_FEE_LENGTH_MISMATCH_ERROR_SELECTOR, ethFeesLength, feeRecipientsLength ); } }
{ "pile_set_name": "Github" }
-- Copyright (C) 2017 yushi studio <[email protected]> github.com/ywb94 -- Copyright (C) 2018 lean <[email protected]> github.com/coolsnowwolf -- Licensed to the public under the GNU General Public License v3. local m, s, sec, o, kcp_enable local vssr = 'vssr' local gfwmode = 0 if nixio.fs.access('/etc/dnsmasq.ssr/gfw_list.conf') then gfwmode = 1 end local uci = luci.model.uci.cursor() m = Map(vssr) m:section(SimpleSection).template = 'vssr/status_top' local server_table = {} local tw_table = {} local tvb_table = {} uci:foreach( vssr, 'servers', function(s) if s.alias then server_table[s['.name']] = '[%s]:%s' % {string.upper(s.type), s.alias} elseif s.server and s.server_port then server_table[s['.name']] = '[%s]:%s:%s' % { string.upper(s.type), s.server, s.server_port } end if s.flag == 'tw' then if s.alias then tw_table[s['.name']] = '[%s]:%s' % {string.upper(s.type), s.alias} elseif s.server and s.server_port then tw_table[s['.name']] = '[%s]:%s:%s' % { string.upper(s.type), s.server, s.server_port } end end if s.flag == 'hk' then if s.alias then tvb_table[s['.name']] = '[%s]:%s' % {string.upper(s.type), s.alias} elseif s.server and s.server_port then tvb_table[s['.name']] = '[%s]:%s:%s' % { string.upper(s.type), s.server, s.server_port } end end end ) local key_table = {} for key, _ in pairs(server_table) do table.insert(key_table, key) end local key_table_tw = {} for key, _ in pairs(tw_table) do table.insert(key_table_tw, key) end local key_table_tvb = {} for key, _ in pairs(tvb_table) do table.insert(key_table_tvb, key) end table.sort(key_table) table.sort(key_table_tw) table.sort(key_table_tvb) local route_name = { 'youtube_server', 'tw_video_server', 'netflix_server', 'disney_server', 'prime_server', 'tvb_server', 'custom_server' } local route_label = { 'Youtube Proxy', 'TaiWan Video Proxy', 'Netflix Proxy', 'Diseny+ Proxy', 'Prime Video Proxy', 'TVB Video Proxy', 'Custom Proxy' } -- [[ Global Setting ]]-- s = m:section(TypedSection, 'global', translate('Basic Settings [SS|SSR|V2ray|Trojan]')) s.anonymous = true o = s:option(ListValue, 'global_server', translate('Main Server')) o:value('nil', translate('Disable')) for _, key in pairs(key_table) do o:value(key, server_table[key]) end o.default = 'nil' o.rmempty = false o = s:option(ListValue, 'udp_relay_server', translate('Game Mode UDP Server')) o:value('', translate('Disable')) o:value('same', translate('Same as Main Server')) for _, key in pairs(key_table) do o:value(key, server_table[key]) end o = s:option(Flag, 'v2ray_flow', translate('Open v2ray route')) o.rmempty = false o.description = translate('When open v2ray routed,Apply may take more time.') for i, v in pairs(route_name) do o = s:option(ListValue, v, translate(route_label[i])) o:value('nil', translate('Same as Main Server')) if (v == 'tw_video_server') then for _, key in pairs(key_table_tw) do o:value(key, tw_table[key]) end elseif (v == 'tvb_server') then for _, key in pairs(key_table_tvb) do o:value(key, tvb_table[key]) end else for _, key in pairs(key_table) do o:value(key, server_table[key]) end end o:depends('v2ray_flow', '1') o.default = 'nil' end o = s:option(ListValue, 'threads', translate('Multi Threads Option')) o:value('0', translate('Auto Threads')) o:value('1', translate('1 Thread')) o:value('2', translate('2 Threads')) o:value('4', translate('4 Threads')) o:value('8', translate('8 Threads')) o.default = '0' o.rmempty = false o = s:option(ListValue, 'run_mode', translate('Running Mode')) o:value('gfw', translate('GFW List Mode')) o:value('router', translate('IP Route Mode')) o:value('all', translate('Global Mode')) o:value('oversea', translate('Oversea Mode')) o.default = 'router' o = s:option(ListValue, 'dports', translate('Proxy Ports')) o:value('1', translate('All Ports')) o:value('2', translate('Only Common Ports')) o.default = 1 o = s:option(ListValue, 'pdnsd_enable', translate('Resolve Dns Mode')) o:value('1', translate('Use Pdnsd tcp query and cache')) o:value('0', translate('Use Local DNS Service listen port 5335')) o.default = 1 o = s:option(Value, 'tunnel_forward', translate('Anti-pollution DNS Server')) o:value('8.8.4.4:53', translate('Google Public DNS (8.8.4.4)')) o:value('8.8.8.8:53', translate('Google Public DNS (8.8.8.8)')) o:value('208.67.222.222:53', translate('OpenDNS (208.67.222.222)')) o:value('208.67.220.220:53', translate('OpenDNS (208.67.220.220)')) o:value('209.244.0.3:53', translate('Level 3 Public DNS (209.244.0.3)')) o:value('209.244.0.4:53', translate('Level 3 Public DNS (209.244.0.4)')) o:value('4.2.2.1:53', translate('Level 3 Public DNS (4.2.2.1)')) o:value('4.2.2.2:53', translate('Level 3 Public DNS (4.2.2.2)')) o:value('4.2.2.3:53', translate('Level 3 Public DNS (4.2.2.3)')) o:value('4.2.2.4:53', translate('Level 3 Public DNS (4.2.2.4)')) o:value('1.1.1.1:53', translate('Cloudflare DNS (1.1.1.1)')) o:value('114.114.114.114:53', translate('Oversea Mode DNS-1 (114.114.114.114)')) o:value('114.114.115.115:53', translate('Oversea Mode DNS-2 (114.114.115.115)')) o:depends('pdnsd_enable', '1') m:section(SimpleSection).template = 'vssr/status_bottom' return m
{ "pile_set_name": "Github" }
'label':'bus' 'bounding box':(1341,215,2047,651) 'label':'bus' 'bounding box':(1341,215,2047,651) 'label':'bus' 'bounding box':(1341,215,2047,651) 'label':'bicycle' 'bounding box':(756,524,768,534) 'label':'car' 'bounding box':(1003,505,1070,534) 'label':'car' 'bounding box':(635,501,696,537) 'label':'car' 'bounding box':(637,511,688,539) 'label':'car' 'bounding box':(1102,503,1127,544) 'label':'car' 'bounding box':(1110,504,1127,545) 'label':'car' 'bounding box':(826,502,856,535) 'label':'car' 'bounding box':(760,516,787,532) 'label':'person' 'bounding box':(1240,486,1263,548) 'label':'bicycle' 'bounding box':(1198,507,1221,547) 'label':'motorcycle' 'bounding box':(1177,510,1193,543) 'label':'car' 'bounding box':(1113,503,1177,546) 'label':'person' 'bounding box':(1094,502,1106,513) 'label':'bicycle' 'bounding box':(1089,514,1104,538) 'label':'person' 'bounding box':(948,509,955,527) 'label':'car' 'bounding box':(951,507,995,539) 'label':'rider' 'bounding box':(756,513,763,527) 'label':'bus' 'bounding box':(1341,215,2047,651) 'label':'car' 'bounding box':(1013,501,1040,535) 'label':'car' 'bounding box':(1027,497,1069,536) 'label':'car' 'bounding box':(1037,509,1066,537) 'label':'car' 'bounding box':(1050,507,1094,538)
{ "pile_set_name": "Github" }
using Umbraco.Core.Composing; namespace Umbraco.Core.Mapping { public class MapDefinitionCollectionBuilder : SetCollectionBuilderBase<MapDefinitionCollectionBuilder, MapDefinitionCollection, IMapDefinition> { protected override MapDefinitionCollectionBuilder This => this; protected override Lifetime CollectionLifetime => Lifetime.Transient; } }
{ "pile_set_name": "Github" }
# Polynomial Regression Surrogate This example is meant to demonstrate how a polynomial regression based surrogate model is trained and used on a parametric problem. Additionally, the results are compared to those obtained using a Polynomial Chaos (PC) surrogate. The possible differences in applicability are highlighted as well. For more on the regression method used here, see [PolynomialRegressionTrainer.md] while details of Polynomial Chaos are available under [PolynomialChaos.md]. ## Problem Statement The full-order model in this example is essentially the same as the one described in [surrogate_training.md]. It is a one-dimensional heat conduction model: !equation -k\frac{d^2T}{dx^2} = q \,, \quad x\in[0, L] !equation \begin{aligned} \left.\frac{dT}{dx}\right|_{x=0} &= 0 \\ T(x=L) &= T_{\infty} \end{aligned} where $T$ is the temperature, $k$ is the thermal conductivity, $L$ is the length of the domain, $q$ is a heat source and $T_\infty$ is the value of the Dirichlet boundary condition. To make the comparison between different surrogate models easier, only the maximum temperature is selected to be the Quantity of Interest (QoI): !equation id=problem \begin{aligned}\\ T_{\max} &= \max_{x\in[0,L]}T(x). \end{aligned} The problem is parametric in a sense that the solution depends on four input parameters: $T=T(x,k,q,L,T_\infty)$. Two problem settings are considered in this example. In the first scenario, all of the parameters are assumed to have [Uniform](Uniform.md) distributions ($\mathcal{U}(a,b)$), while the second considers parameters with [Normal](Normal.md) distributions ($\mathcal{N}(\mu,\sigma)$). To be more specific the distributions for the two cases are: !table | Parameter | Symbol | Uniform | Normal | | :- | - | - | - | | Conductivity | $k$ | $\sim\mathcal{U}(1, 10)$ | $\sim\mathcal{N}(5, 2)$ | | Volumetric Heat Source | $q$ | $\sim\mathcal{U}(9000, 11000)$ | $\sim\mathcal{N}(10000, 500)$ | | Domain Size | $L$ | $\sim\mathcal{U}(0.01, 0.05)$ | $\sim\mathcal{N}(0.03, 0.01)$ | | Right Boundary Temperature | $T_{\infty}$ | $\sim\mathcal{U}(290, 310)$ | $\sim\mathcal{N}(300, 10)$ | The parameters of the uniform distribution are the minimum and maximum bounds, while the parameters of the normal distribution are the mean and standard deviation. It must be mentioned that the maximum temperature can be determined analytically and turns out to be: !equation \begin{aligned} T_{\max}(k,q,L,T_{\infty}) &= \frac{qL^2}{2k} + T_{\infty}. \end{aligned} Using this expression and the previously described probability density functions, the mean ($\mu$) and standard deviation ($\sigma$) of the QoI can be computed for reference: !table id=ref_results caption=The reference results for the mean and standard deviation of the maximum temperature. | Moment | Uniform | Normal | | :- | - | - | | $\mu_{T_{max}}$ | 301.3219 | 301.2547 | | $\sigma_{T_{max}}$ | 5.9585 | 10.0011 | ## Solving the problem without uncertain parameters The first step towards creating a surrogate model is the generation of a full-order model which can solve [problem] with fixed parameter combinations. The complete input file for this case is presented in [sub_app]. !listing surrogates/polynomial_regression/sub.i id=sub_app caption=Complete input file for the heat equation problem in this study. ## Training surrogate models Both surrogate models are constructed using some knowledge about the full-order problem. This means that the [full-order problem](surrogates/polynomial_regression/sub.i) is solved multiple times with different parameter samples and the value of the QoI is stored from each computation. This step is managed by a master input file which creates parameter samples, transfers them to the sub-application and collects the results from the completed computations. For more information about setting up master input files see [examples/surrogate_training.md] and [examples/parameter_study.md]. The two complete training input files used for the two cases with the two different parameter distributions are available under [uniform](surrogates/polynomial_regression/uniform_train.i) and [normal](surrogates/polynomial_regression/normal_train.i). The training phase starts with the definition of the distributions in the `Distributions` block. The uniform distributions can be defined as: !listing surrogates/polynomial_regression/uniform_train.i block=Distributions For the case with normal distributions the block changes to: !listing surrogates/polynomial_regression/normal_train.i block=Distributions As a next step, several parameter instances are prepared by sampling the underlying distributions. The sampling objects can be defined in the `Samplers` block. The generation of these parameter samples is different for the two surrogate models. Meanwhile the polynomial chaos uses the samples at specific quadrature points in the parameters space (generated by a [QuadratureSampler.md]), the polynomial regression model is trained using samples from a [LatinHypercubeSampler.md]. It is visible that the number of sample (`num_rows`) is set in the [LatinHypercubeSampler.md] to match the number of samples in the tensor-product quadrature set of [QuadratureSampler.md]. !listing surrogates/polynomial_regression/normal_train.i block=Samplers The objects in blocks `Controls`, `MultiApps`, `Transfers` and `VectorPostprocessors` are responsible for managing the communication between master and sub-applications, execution of the sub-applications and the collection of the results. For a more detailed description of these blocks see [examples/parameter_study.md] and [surrogate_training.md]. !listing surrogates/polynomial_regression/normal_train.i block=MultiApps Controls Transfers VectorPostprocessors The next step is to set up two `Trainer` objects to generate the surrogate models from the available data. This can be done in the `Trainers` block. It is visible that both examples use the data from `Sampler` and `VectorPostprocessor` objects. A polynomial chaos surrogate of order 8 and a polynomial regression surrogate with a polynomial of degree at most 4 is used in this study. The [PolynomialChaosTrainer.md] also needs knowledge about the underlying parameter distributions to be able to select matching polynomials. !listing surrogates/polynomial_regression/uniform_train.i block=Trainers As a last step in the training process, the important parameters of the trained surrogates are saved into `.rd` files. These files can be used to construct the surrogate models again without the need to carry out the training process from the beginning. !listing surrogates/polynomial_regression/normal_train.i block=Outputs ## Evaluation of surrogate models To evaluate surrogate models, a new master input file has to be created for [uniform](surrogates/polynomial_regression/uniform_surr.i) and [normal](surrogates/polynomial_regression/normal_surr.i) parameter distributions. The input files contain testing distributions for the parameters defined in the `Distributions` block. In this study, the training distributions are used for the testing of the surrogates as well. Both surrogate models are tested using the same parameter samples. These samples are selected using [LatinHypercubeSampler.md] defined in the `Samplers` block. Since the surrogate models are orders of magnitude faster than the full-order model, $100,000$ samples are selected for testing (compared to $6,560$ used for training). !listing surrogates/polynomial_regression/normal_surr.i block=Samplers As a next step, two object are created in the `Surrogates` block for the two surrogate modeling techniques. Both of them are constructed using the information available within the corresponding `.rd` files. !listing surrogates/polynomial_regression/normal_surr.i block=Surrogates These surrogate models can be evaluated at the points defined in the testing sample batch. This is done using objects in the `VectorPostprocessors` block. !listing surrogates/polynomial_regression/normal_surr.i block=VectorPostprocessors ## Results and Analysis In this section the results from the different surrogate models are provided. They are compared to the reference results summarized in [ref_results]. A short analysis of the results is provided as well to showcase potential issues the user might encounter when using polynomial regression. ### Uniform parameter distributions First, the case with parameters having uniform distributions are investigated. The statistical moments obtained by the execution of the [surrogate model](surrogates/polynomial_regression/uniform_surr.i) are summarized in [stats_uniform]. !table id=stats_uniform caption=Comparison of the statistical moments from different surrogate models assuming uniform parameter distributions. | Moment | Reference | Poly. Chaos | Poly. Reg. (deg. 4) | Poly. Reg. (deg. 8)| | :- | - | - | - | - | | $\mu_{T_{max}}$ | 301.3219 | 301.3218 | 301.3351 | 301.3332 | | $\sigma_{T_{max}}$ | 5.9585 | 5.9585 | 5.9548 | 5.9537 | It can be observed that the polynomial chaos surrogate gives results closer to the reference values. It is also visible that by increasing the polynomial order for the regression, the accuracy in the standard deviation slightly decreases. This behavior is often referred to as [overfitting](https://en.wikipedia.org/wiki/Overfitting) which decreases the accuracy with the increasing model parameters. The histogram of the results is presented in [uniform_hist]. It is important to mention that the results for the polynomial regression surrogate were obtained using `max_degree=4`. It is apparent that the two methods give similar solutions. !media stochastic_tools/surrogates/poly_reg/poly_reg_example_uniform_hist.svg id=uniform_hist caption=Histogram of the maximum temperature coming from the Monte Carlo run using the surrogate models and assuming uniform parameter distributions. ### Normal parameter distributions Next, the case with normally distributed parameters is analyzed. The statistical moments of the results from testing the [surrogate model](surrogates/polynomial_regression/uniform_surr.i) are summarized in [stats_normal]. !table id=stats_normal caption=Comparison of the statistical moments from different surrogate models assuming normal distributions. | Moment | Reference | Poly. Chaos | Poly. Reg. (deg. 4) | Poly. Reg. (deg. 8)| | :- | - | - | - | - | | $\mu_{T_{max}}$ | 301.2547 | 301.3162 | 301.6289 | 301.7549 | | $\sigma_{T_{max}}$ | 10.0011 | 10.1125 | 11.2611 | 59.6608 | It is visible that polynomial chaos surrogate gives the closest results to the reference values. The overfitting phenomenon can also be observed, since the increase in the polynomial degree for the regression leads to a decrease in accuracy for both the mean and the standard deviation. The histogram of the results is presented in [normal_hist]. It is important to mention that the results for the polynomial regression surrogate were obtained using `max_degree=4`. It is apparent that the two methods give similar solutions, however the tails of the Histogram from the polynomial regression are longer. !media poly_reg_example_normal_hist.svg id=normal_hist caption=Histogram of the maximum temperature coming from the Monte Carlo run using the surrogate models and assuming normal parameter distributions. An explanation for this can be that the normal parameter distributions result in more outliers in terms of QoIs. The least squares regression is sensitive to these outliers because even if there are a few of them, their contribution to the squared error can be considerable. This is not an issue for the polynomial chaos surrogate, since it includes additional weighting functions in the integrals. To further demonstrate this, `num_bins=20` is set in the [LatinHypercubeSampler.md] to create the training set for the polynomial regression surrogate. This allows more samples on the tails of the bell curves, thus the number of outliers potentially increases. The histogram of the testing results compared to that of the polynomial chaos surrogate is presented in [normal_hist_outlier]. It is visible that the tails of the histogram further increased and the mean got distorted as well. !media poly_reg_example_normal_hist_outlier.svg id=normal_hist_outlier caption=Histogram of the maximum temperature presenting the effect of increasing the outliers in the training of the polynomial regression surrogate. To conclude, it is apparent that there are potential issues associated with the polynomial regression such as overfitting and the bias introduced by the outliers. For this reason, the utilization of polynomial regression surrogates may require several optimization steps to set the best maximum degree and filter potential outliers. Alternatively, the utilization of a regularizer can be considered as well.
{ "pile_set_name": "Github" }
// mkerrors.sh -m64 // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,openbsd // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -m64 _const.go package unix import "syscall" const ( AF_APPLETALK = 0x10 AF_BLUETOOTH = 0x20 AF_CCITT = 0xa AF_CHAOS = 0x5 AF_CNT = 0x15 AF_COIP = 0x14 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_E164 = 0x1a AF_ECMA = 0x8 AF_ENCAP = 0x1c AF_HYLINK = 0xf AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x18 AF_IPX = 0x17 AF_ISDN = 0x1a AF_ISO = 0x7 AF_KEY = 0x1e AF_LAT = 0xe AF_LINK = 0x12 AF_LOCAL = 0x1 AF_MAX = 0x24 AF_MPLS = 0x21 AF_NATM = 0x1b AF_NS = 0x6 AF_OSI = 0x7 AF_PUP = 0x4 AF_ROUTE = 0x11 AF_SIP = 0x1d AF_SNA = 0xb AF_UNIX = 0x1 AF_UNSPEC = 0x0 ALTWERASE = 0x200 ARPHRD_ETHER = 0x1 ARPHRD_FRELAY = 0xf ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 B0 = 0x0 B110 = 0x6e B115200 = 0x1c200 B1200 = 0x4b0 B134 = 0x86 B14400 = 0x3840 B150 = 0x96 B1800 = 0x708 B19200 = 0x4b00 B200 = 0xc8 B230400 = 0x38400 B2400 = 0x960 B28800 = 0x7080 B300 = 0x12c B38400 = 0x9600 B4800 = 0x12c0 B50 = 0x32 B57600 = 0xe100 B600 = 0x258 B7200 = 0x1c20 B75 = 0x4b B76800 = 0x12c00 B9600 = 0x2580 BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDIRFILT = 0x4004427c BIOCGDLT = 0x4004426a BIOCGDLTLIST = 0xc010427b BIOCGETIF = 0x4020426b BIOCGFILDROP = 0x40044278 BIOCGHDRCMPLT = 0x40044274 BIOCGRSIG = 0x40044273 BIOCGRTIMEOUT = 0x4010426e BIOCGSTATS = 0x4008426f BIOCIMMEDIATE = 0x80044270 BIOCLOCK = 0x20004276 BIOCPROMISC = 0x20004269 BIOCSBLEN = 0xc0044266 BIOCSDIRFILT = 0x8004427d BIOCSDLT = 0x8004427a BIOCSETF = 0x80104267 BIOCSETIF = 0x8020426c BIOCSETWF = 0x80104277 BIOCSFILDROP = 0x80044279 BIOCSHDRCMPLT = 0x80044275 BIOCSRSIG = 0x80044272 BIOCSRTIMEOUT = 0x8010426d BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x4 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIRECTION_IN = 0x1 BPF_DIRECTION_OUT = 0x2 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x200000 BPF_MAXINSNS = 0x200 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 CFLUSH = 0xf CLOCAL = 0x8000 CLOCK_BOOTTIME = 0x6 CLOCK_MONOTONIC = 0x3 CLOCK_PROCESS_CPUTIME_ID = 0x2 CLOCK_REALTIME = 0x0 CLOCK_THREAD_CPUTIME_ID = 0x4 CLOCK_UPTIME = 0x5 CREAD = 0x800 CRTSCTS = 0x10000 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0xff CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a CTL_HW = 0x6 CTL_KERN = 0x1 CTL_MAXNAME = 0xc CTL_NET = 0x4 DIOCOSFPFLUSH = 0x2000444e DLT_ARCNET = 0x7 DLT_ATM_RFC1483 = 0xb DLT_AX25 = 0x3 DLT_CHAOS = 0x5 DLT_C_HDLC = 0x68 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_ENC = 0xd DLT_FDDI = 0xa DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_LOOP = 0xc DLT_MPLS = 0xdb DLT_NULL = 0x0 DLT_OPENFLOW = 0x10b DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0x10 DLT_PPP_ETHER = 0x33 DLT_PPP_SERIAL = 0x32 DLT_PRONET = 0x4 DLT_RAW = 0xe DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xf DLT_USBPCAP = 0xf9 DLT_USER0 = 0x93 DLT_USER1 = 0x94 DLT_USER10 = 0x9d DLT_USER11 = 0x9e DLT_USER12 = 0x9f DLT_USER13 = 0xa0 DLT_USER14 = 0xa1 DLT_USER15 = 0xa2 DLT_USER2 = 0x95 DLT_USER3 = 0x96 DLT_USER4 = 0x97 DLT_USER5 = 0x98 DLT_USER6 = 0x99 DLT_USER7 = 0x9a DLT_USER8 = 0x9b DLT_USER9 = 0x9c DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EMT_TAGOVF = 0x1 EMUL_ENABLED = 0x1 EMUL_NATIVE = 0x2 ENDRUNDISC = 0x9 ETHERMIN = 0x2e ETHERMTU = 0x5dc ETHERTYPE_8023 = 0x4 ETHERTYPE_AARP = 0x80f3 ETHERTYPE_ACCTON = 0x8390 ETHERTYPE_AEONIC = 0x8036 ETHERTYPE_ALPHA = 0x814a ETHERTYPE_AMBER = 0x6008 ETHERTYPE_AMOEBA = 0x8145 ETHERTYPE_AOE = 0x88a2 ETHERTYPE_APOLLO = 0x80f7 ETHERTYPE_APOLLODOMAIN = 0x8019 ETHERTYPE_APPLETALK = 0x809b ETHERTYPE_APPLITEK = 0x80c7 ETHERTYPE_ARGONAUT = 0x803a ETHERTYPE_ARP = 0x806 ETHERTYPE_AT = 0x809b ETHERTYPE_ATALK = 0x809b ETHERTYPE_ATOMIC = 0x86df ETHERTYPE_ATT = 0x8069 ETHERTYPE_ATTSTANFORD = 0x8008 ETHERTYPE_AUTOPHON = 0x806a ETHERTYPE_AXIS = 0x8856 ETHERTYPE_BCLOOP = 0x9003 ETHERTYPE_BOFL = 0x8102 ETHERTYPE_CABLETRON = 0x7034 ETHERTYPE_CHAOS = 0x804 ETHERTYPE_COMDESIGN = 0x806c ETHERTYPE_COMPUGRAPHIC = 0x806d ETHERTYPE_COUNTERPOINT = 0x8062 ETHERTYPE_CRONUS = 0x8004 ETHERTYPE_CRONUSVLN = 0x8003 ETHERTYPE_DCA = 0x1234 ETHERTYPE_DDE = 0x807b ETHERTYPE_DEBNI = 0xaaaa ETHERTYPE_DECAM = 0x8048 ETHERTYPE_DECCUST = 0x6006 ETHERTYPE_DECDIAG = 0x6005 ETHERTYPE_DECDNS = 0x803c ETHERTYPE_DECDTS = 0x803e ETHERTYPE_DECEXPER = 0x6000 ETHERTYPE_DECLAST = 0x8041 ETHERTYPE_DECLTM = 0x803f ETHERTYPE_DECMUMPS = 0x6009 ETHERTYPE_DECNETBIOS = 0x8040 ETHERTYPE_DELTACON = 0x86de ETHERTYPE_DIDDLE = 0x4321 ETHERTYPE_DLOG1 = 0x660 ETHERTYPE_DLOG2 = 0x661 ETHERTYPE_DN = 0x6003 ETHERTYPE_DOGFIGHT = 0x1989 ETHERTYPE_DSMD = 0x8039 ETHERTYPE_ECMA = 0x803 ETHERTYPE_ENCRYPT = 0x803d ETHERTYPE_ES = 0x805d ETHERTYPE_EXCELAN = 0x8010 ETHERTYPE_EXPERDATA = 0x8049 ETHERTYPE_FLIP = 0x8146 ETHERTYPE_FLOWCONTROL = 0x8808 ETHERTYPE_FRARP = 0x808 ETHERTYPE_GENDYN = 0x8068 ETHERTYPE_HAYES = 0x8130 ETHERTYPE_HIPPI_FP = 0x8180 ETHERTYPE_HITACHI = 0x8820 ETHERTYPE_HP = 0x8005 ETHERTYPE_IEEEPUP = 0xa00 ETHERTYPE_IEEEPUPAT = 0xa01 ETHERTYPE_IMLBL = 0x4c42 ETHERTYPE_IMLBLDIAG = 0x424c ETHERTYPE_IP = 0x800 ETHERTYPE_IPAS = 0x876c ETHERTYPE_IPV6 = 0x86dd ETHERTYPE_IPX = 0x8137 ETHERTYPE_IPXNEW = 0x8037 ETHERTYPE_KALPANA = 0x8582 ETHERTYPE_LANBRIDGE = 0x8038 ETHERTYPE_LANPROBE = 0x8888 ETHERTYPE_LAT = 0x6004 ETHERTYPE_LBACK = 0x9000 ETHERTYPE_LITTLE = 0x8060 ETHERTYPE_LLDP = 0x88cc ETHERTYPE_LOGICRAFT = 0x8148 ETHERTYPE_LOOPBACK = 0x9000 ETHERTYPE_MATRA = 0x807a ETHERTYPE_MAX = 0xffff ETHERTYPE_MERIT = 0x807c ETHERTYPE_MICP = 0x873a ETHERTYPE_MOPDL = 0x6001 ETHERTYPE_MOPRC = 0x6002 ETHERTYPE_MOTOROLA = 0x818d ETHERTYPE_MPLS = 0x8847 ETHERTYPE_MPLS_MCAST = 0x8848 ETHERTYPE_MUMPS = 0x813f ETHERTYPE_NBPCC = 0x3c04 ETHERTYPE_NBPCLAIM = 0x3c09 ETHERTYPE_NBPCLREQ = 0x3c05 ETHERTYPE_NBPCLRSP = 0x3c06 ETHERTYPE_NBPCREQ = 0x3c02 ETHERTYPE_NBPCRSP = 0x3c03 ETHERTYPE_NBPDG = 0x3c07 ETHERTYPE_NBPDGB = 0x3c08 ETHERTYPE_NBPDLTE = 0x3c0a ETHERTYPE_NBPRAR = 0x3c0c ETHERTYPE_NBPRAS = 0x3c0b ETHERTYPE_NBPRST = 0x3c0d ETHERTYPE_NBPSCD = 0x3c01 ETHERTYPE_NBPVCD = 0x3c00 ETHERTYPE_NBS = 0x802 ETHERTYPE_NCD = 0x8149 ETHERTYPE_NESTAR = 0x8006 ETHERTYPE_NETBEUI = 0x8191 ETHERTYPE_NOVELL = 0x8138 ETHERTYPE_NS = 0x600 ETHERTYPE_NSAT = 0x601 ETHERTYPE_NSCOMPAT = 0x807 ETHERTYPE_NTRAILER = 0x10 ETHERTYPE_OS9 = 0x7007 ETHERTYPE_OS9NET = 0x7009 ETHERTYPE_PACER = 0x80c6 ETHERTYPE_PAE = 0x888e ETHERTYPE_PCS = 0x4242 ETHERTYPE_PLANNING = 0x8044 ETHERTYPE_PPP = 0x880b ETHERTYPE_PPPOE = 0x8864 ETHERTYPE_PPPOEDISC = 0x8863 ETHERTYPE_PRIMENTS = 0x7031 ETHERTYPE_PUP = 0x200 ETHERTYPE_PUPAT = 0x200 ETHERTYPE_QINQ = 0x88a8 ETHERTYPE_RACAL = 0x7030 ETHERTYPE_RATIONAL = 0x8150 ETHERTYPE_RAWFR = 0x6559 ETHERTYPE_RCL = 0x1995 ETHERTYPE_RDP = 0x8739 ETHERTYPE_RETIX = 0x80f2 ETHERTYPE_REVARP = 0x8035 ETHERTYPE_SCA = 0x6007 ETHERTYPE_SECTRA = 0x86db ETHERTYPE_SECUREDATA = 0x876d ETHERTYPE_SGITW = 0x817e ETHERTYPE_SG_BOUNCE = 0x8016 ETHERTYPE_SG_DIAG = 0x8013 ETHERTYPE_SG_NETGAMES = 0x8014 ETHERTYPE_SG_RESV = 0x8015 ETHERTYPE_SIMNET = 0x5208 ETHERTYPE_SLOW = 0x8809 ETHERTYPE_SNA = 0x80d5 ETHERTYPE_SNMP = 0x814c ETHERTYPE_SONIX = 0xfaf5 ETHERTYPE_SPIDER = 0x809f ETHERTYPE_SPRITE = 0x500 ETHERTYPE_STP = 0x8181 ETHERTYPE_TALARIS = 0x812b ETHERTYPE_TALARISMC = 0x852b ETHERTYPE_TCPCOMP = 0x876b ETHERTYPE_TCPSM = 0x9002 ETHERTYPE_TEC = 0x814f ETHERTYPE_TIGAN = 0x802f ETHERTYPE_TRAIL = 0x1000 ETHERTYPE_TRANSETHER = 0x6558 ETHERTYPE_TYMSHARE = 0x802e ETHERTYPE_UBBST = 0x7005 ETHERTYPE_UBDEBUG = 0x900 ETHERTYPE_UBDIAGLOOP = 0x7002 ETHERTYPE_UBDL = 0x7000 ETHERTYPE_UBNIU = 0x7001 ETHERTYPE_UBNMC = 0x7003 ETHERTYPE_VALID = 0x1600 ETHERTYPE_VARIAN = 0x80dd ETHERTYPE_VAXELN = 0x803b ETHERTYPE_VEECO = 0x8067 ETHERTYPE_VEXP = 0x805b ETHERTYPE_VGLAB = 0x8131 ETHERTYPE_VINES = 0xbad ETHERTYPE_VINESECHO = 0xbaf ETHERTYPE_VINESLOOP = 0xbae ETHERTYPE_VITAL = 0xff00 ETHERTYPE_VLAN = 0x8100 ETHERTYPE_VLTLMAN = 0x8080 ETHERTYPE_VPROD = 0x805c ETHERTYPE_VURESERVED = 0x8147 ETHERTYPE_WATERLOO = 0x8130 ETHERTYPE_WELLFLEET = 0x8103 ETHERTYPE_X25 = 0x805 ETHERTYPE_X75 = 0x801 ETHERTYPE_XNSSM = 0x9001 ETHERTYPE_XTP = 0x817d ETHER_ADDR_LEN = 0x6 ETHER_ALIGN = 0x2 ETHER_CRC_LEN = 0x4 ETHER_CRC_POLY_BE = 0x4c11db6 ETHER_CRC_POLY_LE = 0xedb88320 ETHER_HDR_LEN = 0xe ETHER_MAX_DIX_LEN = 0x600 ETHER_MAX_HARDMTU_LEN = 0xff9b ETHER_MAX_LEN = 0x5ee ETHER_MIN_LEN = 0x40 ETHER_TYPE_LEN = 0x2 ETHER_VLAN_ENCAP_LEN = 0x4 EVFILT_AIO = -0x3 EVFILT_DEVICE = -0x8 EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0x8 EVFILT_TIMER = -0x7 EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 EVL_ENCAPLEN = 0x4 EVL_PRIO_BITS = 0xd EVL_PRIO_MAX = 0x7 EVL_VLID_MASK = 0xfff EVL_VLID_MAX = 0xffe EVL_VLID_MIN = 0x1 EVL_VLID_NULL = 0x0 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 EV_DISABLE = 0x8 EV_DISPATCH = 0x80 EV_ENABLE = 0x4 EV_EOF = 0x8000 EV_ERROR = 0x4000 EV_FLAG1 = 0x2000 EV_ONESHOT = 0x10 EV_RECEIPT = 0x40 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FLUSHO = 0x800000 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0xa F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0x7 F_GETOWN = 0x5 F_ISATTY = 0xb F_OK = 0x0 F_RDLCK = 0x1 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0x8 F_SETLKW = 0x9 F_SETOWN = 0x6 F_UNLCK = 0x2 F_WRLCK = 0x3 HUPCL = 0x4000 HW_MACHINE = 0x1 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 IFF_ALLMULTI = 0x200 IFF_BROADCAST = 0x2 IFF_CANTCHANGE = 0x8e52 IFF_DEBUG = 0x4 IFF_LINK0 = 0x1000 IFF_LINK1 = 0x2000 IFF_LINK2 = 0x4000 IFF_LOOPBACK = 0x8 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SIMPLEX = 0x800 IFF_STATICARP = 0x20 IFF_UP = 0x1 IFNAMSIZ = 0x10 IFT_1822 = 0x2 IFT_A12MPPSWITCH = 0x82 IFT_AAL2 = 0xbb IFT_AAL5 = 0x31 IFT_ADSL = 0x5e IFT_AFLANE8023 = 0x3b IFT_AFLANE8025 = 0x3c IFT_ARAP = 0x58 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ASYNC = 0x54 IFT_ATM = 0x25 IFT_ATMDXI = 0x69 IFT_ATMFUNI = 0x6a IFT_ATMIMA = 0x6b IFT_ATMLOGICAL = 0x50 IFT_ATMRADIO = 0xbd IFT_ATMSUBINTERFACE = 0x86 IFT_ATMVCIENDPT = 0xc2 IFT_ATMVIRTUAL = 0x95 IFT_BGPPOLICYACCOUNTING = 0xa2 IFT_BLUETOOTH = 0xf8 IFT_BRIDGE = 0xd1 IFT_BSC = 0x53 IFT_CARP = 0xf7 IFT_CCTEMUL = 0x3d IFT_CEPT = 0x13 IFT_CES = 0x85 IFT_CHANNEL = 0x46 IFT_CNR = 0x55 IFT_COFFEE = 0x84 IFT_COMPOSITELINK = 0x9b IFT_DCN = 0x8d IFT_DIGITALPOWERLINE = 0x8a IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba IFT_DLSW = 0x4a IFT_DOCSCABLEDOWNSTREAM = 0x80 IFT_DOCSCABLEMACLAYER = 0x7f IFT_DOCSCABLEUPSTREAM = 0x81 IFT_DOCSCABLEUPSTREAMCHANNEL = 0xcd IFT_DS0 = 0x51 IFT_DS0BUNDLE = 0x52 IFT_DS1FDL = 0xaa IFT_DS3 = 0x1e IFT_DTM = 0x8c IFT_DUMMY = 0xf1 IFT_DVBASILN = 0xac IFT_DVBASIOUT = 0xad IFT_DVBRCCDOWNSTREAM = 0x93 IFT_DVBRCCMACLAYER = 0x92 IFT_DVBRCCUPSTREAM = 0x94 IFT_ECONET = 0xce IFT_ENC = 0xf4 IFT_EON = 0x19 IFT_EPLRS = 0x57 IFT_ESCON = 0x49 IFT_ETHER = 0x6 IFT_FAITH = 0xf3 IFT_FAST = 0x7d IFT_FASTETHER = 0x3e IFT_FASTETHERFX = 0x45 IFT_FDDI = 0xf IFT_FIBRECHANNEL = 0x38 IFT_FRAMERELAYINTERCONNECT = 0x3a IFT_FRAMERELAYMPI = 0x5c IFT_FRDLCIENDPT = 0xc1 IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_FRF16MFRBUNDLE = 0xa3 IFT_FRFORWARD = 0x9e IFT_G703AT2MB = 0x43 IFT_G703AT64K = 0x42 IFT_GIF = 0xf0 IFT_GIGABITETHERNET = 0x75 IFT_GR303IDT = 0xb2 IFT_GR303RDT = 0xb1 IFT_H323GATEKEEPER = 0xa4 IFT_H323PROXY = 0xa5 IFT_HDH1822 = 0x3 IFT_HDLC = 0x76 IFT_HDSL2 = 0xa8 IFT_HIPERLAN2 = 0xb7 IFT_HIPPI = 0x2f IFT_HIPPIINTERFACE = 0x39 IFT_HOSTPAD = 0x5a IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IBM370PARCHAN = 0x48 IFT_IDSL = 0x9a IFT_IEEE1394 = 0x90 IFT_IEEE80211 = 0x47 IFT_IEEE80212 = 0x37 IFT_IEEE8023ADLAG = 0xa1 IFT_IFGSN = 0x91 IFT_IMT = 0xbe IFT_INFINIBAND = 0xc7 IFT_INTERLEAVE = 0x7c IFT_IP = 0x7e IFT_IPFORWARD = 0x8e IFT_IPOVERATM = 0x72 IFT_IPOVERCDLC = 0x6d IFT_IPOVERCLAW = 0x6e IFT_IPSWITCH = 0x4e IFT_ISDN = 0x3f IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISDNS = 0x4b IFT_ISDNU = 0x4c IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88025CRFPINT = 0x62 IFT_ISO88025DTR = 0x56 IFT_ISO88025FIBER = 0x73 IFT_ISO88026 = 0xa IFT_ISUP = 0xb3 IFT_L2VLAN = 0x87 IFT_L3IPVLAN = 0x88 IFT_L3IPXVLAN = 0x89 IFT_LAPB = 0x10 IFT_LAPD = 0x4d IFT_LAPF = 0x77 IFT_LINEGROUP = 0xd2 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MBIM = 0xfa IFT_MEDIAMAILOVERIP = 0x8b IFT_MFSIGLINK = 0xa7 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_MPC = 0x71 IFT_MPLS = 0xa6 IFT_MPLSTUNNEL = 0x96 IFT_MSDSL = 0x8f IFT_MVL = 0xbf IFT_MYRINET = 0x63 IFT_NFAS = 0xaf IFT_NSIP = 0x1b IFT_OPTICALCHANNEL = 0xc3 IFT_OPTICALTRANSPORT = 0xc4 IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PFLOG = 0xf5 IFT_PFLOW = 0xf9 IFT_PFSYNC = 0xf6 IFT_PLC = 0xae IFT_PON155 = 0xcf IFT_PON622 = 0xd0 IFT_POS = 0xab IFT_PPP = 0x17 IFT_PPPMULTILINKBUNDLE = 0x6c IFT_PROPATM = 0xc5 IFT_PROPBWAP2MP = 0xb8 IFT_PROPCNLS = 0x59 IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 IFT_PROPMUX = 0x36 IFT_PROPVIRTUAL = 0x35 IFT_PROPWIRELESSP2P = 0x9d IFT_PTPSERIAL = 0x16 IFT_PVC = 0xf2 IFT_Q2931 = 0xc9 IFT_QLLC = 0x44 IFT_RADIOMAC = 0xbc IFT_RADSL = 0x5f IFT_REACHDSL = 0xc0 IFT_RFC1483 = 0x9f IFT_RS232 = 0x21 IFT_RSRB = 0x4f IFT_SDLC = 0x11 IFT_SDSL = 0x60 IFT_SHDSL = 0xa9 IFT_SIP = 0x1f IFT_SIPSIG = 0xcc IFT_SIPTG = 0xcb IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETOVERHEADCHANNEL = 0xb9 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_SRP = 0x97 IFT_SS7SIGLINK = 0x9c IFT_STACKTOSTACK = 0x6f IFT_STARLAN = 0xb IFT_T1 = 0x12 IFT_TDLC = 0x74 IFT_TELINK = 0xc8 IFT_TERMPAD = 0x5b IFT_TR008 = 0xb0 IFT_TRANSPHDLC = 0x7b IFT_TUNNEL = 0x83 IFT_ULTRA = 0x1d IFT_USB = 0xa0 IFT_V11 = 0x40 IFT_V35 = 0x2d IFT_V36 = 0x41 IFT_V37 = 0x78 IFT_VDSL = 0x61 IFT_VIRTUALIPADDRESS = 0x70 IFT_VIRTUALTG = 0xca IFT_VOICEDID = 0xd5 IFT_VOICEEM = 0x64 IFT_VOICEEMFGD = 0xd3 IFT_VOICEENCAP = 0x67 IFT_VOICEFGDEANA = 0xd4 IFT_VOICEFXO = 0x65 IFT_VOICEFXS = 0x66 IFT_VOICEOVERATM = 0x98 IFT_VOICEOVERCABLE = 0xc6 IFT_VOICEOVERFRAMERELAY = 0x99 IFT_VOICEOVERIP = 0x68 IFT_X213 = 0x5d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25HUNTGROUP = 0x7a IFT_X25MLP = 0x79 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_LOOPBACKNET = 0x7f IN_RFC3021_HOST = 0x1 IN_RFC3021_NET = 0xfffffffe IN_RFC3021_NSHIFT = 0x1f IPPROTO_AH = 0x33 IPPROTO_CARP = 0x70 IPPROTO_DIVERT = 0x102 IPPROTO_DONE = 0x101 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_ETHERIP = 0x61 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPCOMP = 0x6c IPPROTO_IPIP = 0x4 IPPROTO_IPV4 = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MAX = 0x100 IPPROTO_MAXID = 0x103 IPPROTO_MOBILE = 0x37 IPPROTO_MPLS = 0x89 IPPROTO_NONE = 0x3b IPPROTO_PFSYNC = 0xf0 IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPV6_AUTH_LEVEL = 0x35 IPV6_AUTOFLOWLABEL = 0x3b IPV6_CHECKSUM = 0x1a IPV6_DEFAULT_MULTICAST_HOPS = 0x1 IPV6_DEFAULT_MULTICAST_LOOP = 0x1 IPV6_DEFHLIM = 0x40 IPV6_DONTFRAG = 0x3e IPV6_DSTOPTS = 0x32 IPV6_ESP_NETWORK_LEVEL = 0x37 IPV6_ESP_TRANS_LEVEL = 0x36 IPV6_FAITH = 0x1d IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FRAGTTL = 0x78 IPV6_HLIMDEC = 0x1 IPV6_HOPLIMIT = 0x2f IPV6_HOPOPTS = 0x31 IPV6_IPCOMP_LEVEL = 0x3c IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd IPV6_MAXHLIM = 0xff IPV6_MAXPACKET = 0xffff IPV6_MINHOPCOUNT = 0x41 IPV6_MMTU = 0x500 IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_NEXTHOP = 0x30 IPV6_OPTIONS = 0x1 IPV6_PATHMTU = 0x2c IPV6_PIPEX = 0x3f IPV6_PKTINFO = 0x2e IPV6_PORTRANGE = 0xe IPV6_PORTRANGE_DEFAULT = 0x0 IPV6_PORTRANGE_HIGH = 0x1 IPV6_PORTRANGE_LOW = 0x2 IPV6_RECVDSTOPTS = 0x28 IPV6_RECVDSTPORT = 0x40 IPV6_RECVHOPLIMIT = 0x25 IPV6_RECVHOPOPTS = 0x27 IPV6_RECVPATHMTU = 0x2b IPV6_RECVPKTINFO = 0x24 IPV6_RECVRTHDR = 0x26 IPV6_RECVTCLASS = 0x39 IPV6_RTABLE = 0x1021 IPV6_RTHDR = 0x33 IPV6_RTHDRDSTOPTS = 0x23 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SOCKOPT_RESERVED1 = 0x3 IPV6_TCLASS = 0x3d IPV6_UNICAST_HOPS = 0x4 IPV6_USE_MIN_MTU = 0x2a IPV6_V6ONLY = 0x1b IPV6_VERSION = 0x60 IPV6_VERSION_MASK = 0xf0 IP_ADD_MEMBERSHIP = 0xc IP_AUTH_LEVEL = 0x14 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0xd IP_ESP_NETWORK_LEVEL = 0x16 IP_ESP_TRANS_LEVEL = 0x15 IP_HDRINCL = 0x2 IP_IPCOMP_LEVEL = 0x1d IP_IPDEFTTL = 0x25 IP_IPSECFLOWINFO = 0x24 IP_IPSEC_LOCAL_AUTH = 0x1b IP_IPSEC_LOCAL_CRED = 0x19 IP_IPSEC_LOCAL_ID = 0x17 IP_IPSEC_REMOTE_AUTH = 0x1c IP_IPSEC_REMOTE_CRED = 0x1a IP_IPSEC_REMOTE_ID = 0x18 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0xfff IP_MF = 0x2000 IP_MINTTL = 0x20 IP_MIN_MEMBERSHIPS = 0xf IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 IP_MULTICAST_LOOP = 0xb IP_MULTICAST_TTL = 0xa IP_OFFMASK = 0x1fff IP_OPTIONS = 0x1 IP_PIPEX = 0x22 IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 IP_PORTRANGE_LOW = 0x2 IP_RECVDSTADDR = 0x7 IP_RECVDSTPORT = 0x21 IP_RECVIF = 0x1e IP_RECVOPTS = 0x5 IP_RECVRETOPTS = 0x6 IP_RECVRTABLE = 0x23 IP_RECVTTL = 0x1f IP_RETOPTS = 0x8 IP_RF = 0x8000 IP_RTABLE = 0x1021 IP_SENDSRCADDR = 0x7 IP_TOS = 0x3 IP_TTL = 0x4 ISIG = 0x80 ISTRIP = 0x20 IUCLC = 0x1000 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 KERN_HOSTNAME = 0xa KERN_OSRELEASE = 0x2 KERN_OSTYPE = 0x1 KERN_VERSION = 0x4 LCNT_OVERLOAD_FLUSH = 0x6 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DONTNEED = 0x4 MADV_FREE = 0x6 MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_SPACEAVAIL = 0x5 MADV_WILLNEED = 0x3 MAP_ANON = 0x1000 MAP_ANONYMOUS = 0x1000 MAP_CONCEAL = 0x8000 MAP_COPY = 0x2 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_FLAGMASK = 0xfff7 MAP_HASSEMAPHORE = 0x0 MAP_INHERIT = 0x0 MAP_INHERIT_COPY = 0x1 MAP_INHERIT_NONE = 0x2 MAP_INHERIT_SHARE = 0x0 MAP_INHERIT_ZERO = 0x3 MAP_NOEXTEND = 0x0 MAP_NORESERVE = 0x0 MAP_PRIVATE = 0x2 MAP_RENAME = 0x0 MAP_SHARED = 0x1 MAP_STACK = 0x4000 MAP_TRYFIXED = 0x0 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MNT_ASYNC = 0x40 MNT_DEFEXPORTED = 0x200 MNT_DELEXPORT = 0x20000 MNT_DOOMED = 0x8000000 MNT_EXPORTANON = 0x400 MNT_EXPORTED = 0x100 MNT_EXRDONLY = 0x80 MNT_FORCE = 0x80000 MNT_LAZY = 0x3 MNT_LOCAL = 0x1000 MNT_NOATIME = 0x8000 MNT_NODEV = 0x10 MNT_NOEXEC = 0x4 MNT_NOPERM = 0x20 MNT_NOSUID = 0x8 MNT_NOWAIT = 0x2 MNT_QUOTA = 0x2000 MNT_RDONLY = 0x1 MNT_RELOAD = 0x40000 MNT_ROOTFS = 0x4000 MNT_SOFTDEP = 0x4000000 MNT_STALLED = 0x100000 MNT_SYNCHRONOUS = 0x2 MNT_UPDATE = 0x10000 MNT_VISFLAGMASK = 0x400ffff MNT_WAIT = 0x1 MNT_WANTRDWR = 0x2000000 MNT_WXALLOWED = 0x800 MSG_BCAST = 0x100 MSG_CMSG_CLOEXEC = 0x800 MSG_CTRUNC = 0x20 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_EOR = 0x8 MSG_MCAST = 0x200 MSG_NOSIGNAL = 0x400 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_TRUNC = 0x10 MSG_WAITALL = 0x40 MS_ASYNC = 0x1 MS_INVALIDATE = 0x4 MS_SYNC = 0x2 NAME_MAX = 0xff NET_RT_DUMP = 0x1 NET_RT_FLAGS = 0x2 NET_RT_IFLIST = 0x3 NET_RT_IFNAMES = 0x6 NET_RT_MAXID = 0x7 NET_RT_STATS = 0x4 NET_RT_TABLE = 0x5 NFDBITS = 0x20 NOFLSH = 0x80000000 NOKERNINFO = 0x2000000 NOTE_ATTRIB = 0x8 NOTE_CHANGE = 0x1 NOTE_CHILD = 0x4 NOTE_DELETE = 0x1 NOTE_EOF = 0x2 NOTE_EXEC = 0x20000000 NOTE_EXIT = 0x80000000 NOTE_EXTEND = 0x4 NOTE_FORK = 0x40000000 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_PCTRLMASK = 0xf0000000 NOTE_PDATAMASK = 0xfffff NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_TRUNCATE = 0x80 NOTE_WRITE = 0x2 OCRNL = 0x10 OLCUC = 0x20 ONLCR = 0x2 ONLRET = 0x80 ONOCR = 0x40 ONOEOT = 0x8 OPOST = 0x1 OXTABS = 0x4 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x40 O_CLOEXEC = 0x10000 O_CREAT = 0x200 O_DIRECTORY = 0x20000 O_DSYNC = 0x80 O_EXCL = 0x800 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 O_NOCTTY = 0x8000 O_NOFOLLOW = 0x100 O_NONBLOCK = 0x4 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x80 O_SHLOCK = 0x10 O_SYNC = 0x80 O_TRUNC = 0x400 O_WRONLY = 0x1 PARENB = 0x1000 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PF_FLUSH = 0x1 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_MEMLOCK = 0x6 RLIMIT_NOFILE = 0x8 RLIMIT_NPROC = 0x7 RLIMIT_RSS = 0x5 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 RTAX_BFD = 0xb RTAX_BRD = 0x7 RTAX_DNS = 0xc RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_LABEL = 0xa RTAX_MAX = 0xf RTAX_NETMASK = 0x2 RTAX_SEARCH = 0xe RTAX_SRC = 0x8 RTAX_SRCMASK = 0x9 RTAX_STATIC = 0xd RTA_AUTHOR = 0x40 RTA_BFD = 0x800 RTA_BRD = 0x80 RTA_DNS = 0x1000 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_LABEL = 0x400 RTA_NETMASK = 0x4 RTA_SEARCH = 0x4000 RTA_SRC = 0x100 RTA_SRCMASK = 0x200 RTA_STATIC = 0x2000 RTF_ANNOUNCE = 0x4000 RTF_BFD = 0x1000000 RTF_BLACKHOLE = 0x1000 RTF_BROADCAST = 0x400000 RTF_CACHED = 0x20000 RTF_CLONED = 0x10000 RTF_CLONING = 0x100 RTF_CONNECTED = 0x800000 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_FMASK = 0x110fc08 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_LLINFO = 0x400 RTF_LOCAL = 0x200000 RTF_MODIFIED = 0x20 RTF_MPATH = 0x40000 RTF_MPLS = 0x100000 RTF_MULTICAST = 0x200 RTF_PERMANENT_ARP = 0x2000 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_PROTO3 = 0x2000 RTF_REJECT = 0x8 RTF_STATIC = 0x800 RTF_UP = 0x1 RTF_USETRAILERS = 0x8000 RTM_ADD = 0x1 RTM_BFD = 0x12 RTM_CHANGE = 0x3 RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_DESYNC = 0x10 RTM_GET = 0x4 RTM_IFANNOUNCE = 0xf RTM_IFINFO = 0xe RTM_INVALIDATE = 0x11 RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MAXSIZE = 0x800 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_PROPOSAL = 0x13 RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_RTTUNIT = 0xf4240 RTM_VERSION = 0x5 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RT_TABLEID_BITS = 0x8 RT_TABLEID_MASK = 0xff RT_TABLEID_MAX = 0xff RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x4 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDMULTI = 0x80206931 SIOCAIFADDR = 0x8040691a SIOCAIFGROUP = 0x80286987 SIOCATMARK = 0x40047307 SIOCBRDGADD = 0x8060693c SIOCBRDGADDL = 0x80606949 SIOCBRDGADDS = 0x80606941 SIOCBRDGARL = 0x808c694d SIOCBRDGDADDR = 0x81286947 SIOCBRDGDEL = 0x8060693d SIOCBRDGDELS = 0x80606942 SIOCBRDGFLUSH = 0x80606948 SIOCBRDGFRL = 0x808c694e SIOCBRDGGCACHE = 0xc0186941 SIOCBRDGGFD = 0xc0186952 SIOCBRDGGHT = 0xc0186951 SIOCBRDGGIFFLGS = 0xc060693e SIOCBRDGGMA = 0xc0186953 SIOCBRDGGPARAM = 0xc0406958 SIOCBRDGGPRI = 0xc0186950 SIOCBRDGGRL = 0xc030694f SIOCBRDGGTO = 0xc0186946 SIOCBRDGIFS = 0xc0606942 SIOCBRDGRTS = 0xc0206943 SIOCBRDGSADDR = 0xc1286944 SIOCBRDGSCACHE = 0x80186940 SIOCBRDGSFD = 0x80186952 SIOCBRDGSHT = 0x80186951 SIOCBRDGSIFCOST = 0x80606955 SIOCBRDGSIFFLGS = 0x8060693f SIOCBRDGSIFPRIO = 0x80606954 SIOCBRDGSIFPROT = 0x8060694a SIOCBRDGSMA = 0x80186953 SIOCBRDGSPRI = 0x80186950 SIOCBRDGSPROTO = 0x8018695a SIOCBRDGSTO = 0x80186945 SIOCBRDGSTXHC = 0x80186959 SIOCDELMULTI = 0x80206932 SIOCDIFADDR = 0x80206919 SIOCDIFGROUP = 0x80286989 SIOCDIFPARENT = 0x802069b4 SIOCDIFPHYADDR = 0x80206949 SIOCDVNETID = 0x802069af SIOCGETKALIVE = 0xc01869a4 SIOCGETLABEL = 0x8020699a SIOCGETMPWCFG = 0xc02069ae SIOCGETPFLOW = 0xc02069fe SIOCGETPFSYNC = 0xc02069f8 SIOCGETSGCNT = 0xc0207534 SIOCGETVIFCNT = 0xc0287533 SIOCGETVLAN = 0xc0206990 SIOCGIFADDR = 0xc0206921 SIOCGIFBRDADDR = 0xc0206923 SIOCGIFCONF = 0xc0106924 SIOCGIFDATA = 0xc020691b SIOCGIFDESCR = 0xc0206981 SIOCGIFDSTADDR = 0xc0206922 SIOCGIFFLAGS = 0xc0206911 SIOCGIFGATTR = 0xc028698b SIOCGIFGENERIC = 0xc020693a SIOCGIFGMEMB = 0xc028698a SIOCGIFGROUP = 0xc0286988 SIOCGIFHARDMTU = 0xc02069a5 SIOCGIFLLPRIO = 0xc02069b6 SIOCGIFMEDIA = 0xc0406938 SIOCGIFMETRIC = 0xc0206917 SIOCGIFMTU = 0xc020697e SIOCGIFNETMASK = 0xc0206925 SIOCGIFPAIR = 0xc02069b1 SIOCGIFPARENT = 0xc02069b3 SIOCGIFPRIORITY = 0xc020699c SIOCGIFRDOMAIN = 0xc02069a0 SIOCGIFRTLABEL = 0xc0206983 SIOCGIFRXR = 0x802069aa SIOCGIFXFLAGS = 0xc020699e SIOCGLIFPHYADDR = 0xc218694b SIOCGLIFPHYDF = 0xc02069c2 SIOCGLIFPHYRTABLE = 0xc02069a2 SIOCGLIFPHYTTL = 0xc02069a9 SIOCGPGRP = 0x40047309 SIOCGSPPPPARAMS = 0xc0206994 SIOCGUMBINFO = 0xc02069be SIOCGUMBPARAM = 0xc02069c0 SIOCGVH = 0xc02069f6 SIOCGVNETFLOWID = 0xc02069c4 SIOCGVNETID = 0xc02069a7 SIOCIFAFATTACH = 0x801169ab SIOCIFAFDETACH = 0x801169ac SIOCIFCREATE = 0x8020697a SIOCIFDESTROY = 0x80206979 SIOCIFGCLONERS = 0xc0106978 SIOCSETKALIVE = 0x801869a3 SIOCSETLABEL = 0x80206999 SIOCSETMPWCFG = 0x802069ad SIOCSETPFLOW = 0x802069fd SIOCSETPFSYNC = 0x802069f7 SIOCSETVLAN = 0x8020698f SIOCSIFADDR = 0x8020690c SIOCSIFBRDADDR = 0x80206913 SIOCSIFDESCR = 0x80206980 SIOCSIFDSTADDR = 0x8020690e SIOCSIFFLAGS = 0x80206910 SIOCSIFGATTR = 0x8028698c SIOCSIFGENERIC = 0x80206939 SIOCSIFLLADDR = 0x8020691f SIOCSIFLLPRIO = 0x802069b5 SIOCSIFMEDIA = 0xc0206937 SIOCSIFMETRIC = 0x80206918 SIOCSIFMTU = 0x8020697f SIOCSIFNETMASK = 0x80206916 SIOCSIFPAIR = 0x802069b0 SIOCSIFPARENT = 0x802069b2 SIOCSIFPRIORITY = 0x8020699b SIOCSIFRDOMAIN = 0x8020699f SIOCSIFRTLABEL = 0x80206982 SIOCSIFXFLAGS = 0x8020699d SIOCSLIFPHYADDR = 0x8218694a SIOCSLIFPHYDF = 0x802069c1 SIOCSLIFPHYRTABLE = 0x802069a1 SIOCSLIFPHYTTL = 0x802069a8 SIOCSPGRP = 0x80047308 SIOCSSPPPPARAMS = 0x80206993 SIOCSUMBPARAM = 0x802069bf SIOCSVH = 0xc02069f5 SIOCSVNETFLOWID = 0x802069c3 SIOCSVNETID = 0x802069a6 SIOCSWGDPID = 0xc018695b SIOCSWGMAXFLOW = 0xc0186960 SIOCSWGMAXGROUP = 0xc018695d SIOCSWSDPID = 0x8018695c SIOCSWSPORTNO = 0xc060695f SOCK_CLOEXEC = 0x8000 SOCK_DGRAM = 0x2 SOCK_DNS = 0x1000 SOCK_NONBLOCK = 0x4000 SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_BINDANY = 0x1000 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 SO_LINGER = 0x80 SO_NETPROC = 0x1020 SO_OOBINLINE = 0x100 SO_PEERCRED = 0x1022 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_RTABLE = 0x1021 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_SPLICE = 0x1023 SO_TIMESTAMP = 0x800 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 SO_ZEROIZE = 0x2000 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISTXT = 0x200 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TCIFLUSH = 0x1 TCIOFF = 0x3 TCIOFLUSH = 0x3 TCION = 0x4 TCOFLUSH = 0x2 TCOOFF = 0x1 TCOON = 0x2 TCP_MAXBURST = 0x4 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_SACK = 0x3 TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0x4 TCP_MSS = 0x200 TCP_NODELAY = 0x1 TCP_NOPUSH = 0x10 TCP_SACK_ENABLE = 0x8 TCSAFLUSH = 0x2 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCHKVERAUTH = 0x2000741e TIOCCLRVERAUTH = 0x2000741d TIOCCONS = 0x80047462 TIOCDRAIN = 0x2000745e TIOCEXCL = 0x2000740d TIOCEXT = 0x80047460 TIOCFLAG_CLOCAL = 0x2 TIOCFLAG_CRTSCTS = 0x4 TIOCFLAG_MDMBUF = 0x8 TIOCFLAG_PPS = 0x10 TIOCFLAG_SOFTCAR = 0x1 TIOCFLUSH = 0x80047410 TIOCGETA = 0x402c7413 TIOCGETD = 0x4004741a TIOCGFLAGS = 0x4004745d TIOCGPGRP = 0x40047477 TIOCGSID = 0x40047463 TIOCGTSTAMP = 0x4010745b TIOCGWINSZ = 0x40087468 TIOCMBIC = 0x8004746b TIOCMBIS = 0x8004746c TIOCMGET = 0x4004746a TIOCMODG = 0x4004746a TIOCMODS = 0x8004746d TIOCMSET = 0x8004746d TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x20007471 TIOCNXCL = 0x2000740e TIOCOUTQ = 0x40047473 TIOCPKT = 0x80047470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCREMOTE = 0x80047469 TIOCSBRK = 0x2000747b TIOCSCTTY = 0x20007461 TIOCSDTR = 0x20007479 TIOCSETA = 0x802c7414 TIOCSETAF = 0x802c7416 TIOCSETAW = 0x802c7415 TIOCSETD = 0x8004741b TIOCSETVERAUTH = 0x8004741c TIOCSFLAGS = 0x8004745c TIOCSIG = 0x8004745f TIOCSPGRP = 0x80047476 TIOCSTART = 0x2000746e TIOCSTAT = 0x20007465 TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSTSTAMP = 0x8008745a TIOCSWINSZ = 0x80087467 TIOCUCNTL = 0x80047466 TIOCUCNTL_CBRK = 0x7a TIOCUCNTL_SBRK = 0x7b TOSTOP = 0x400000 UTIME_NOW = -0x2 UTIME_OMIT = -0x1 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 VEOL = 0x1 VEOL2 = 0x2 VERASE = 0x3 VINTR = 0x8 VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 VM_ANONMIN = 0x7 VM_LOADAVG = 0x2 VM_MAXID = 0xc VM_MAXSLP = 0xa VM_METER = 0x1 VM_NKMEMPAGES = 0x6 VM_PSSTRINGS = 0x3 VM_SWAPENCRYPT = 0x5 VM_USPACE = 0xb VM_UVMEXP = 0x4 VM_VNODEMIN = 0x9 VM_VTEXTMIN = 0x8 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc VSTATUS = 0x12 VSTOP = 0xd VSUSP = 0xa VTIME = 0x11 VWERASE = 0x4 WALTSIG = 0x4 WCONTINUED = 0x8 WCOREFLAG = 0x80 WNOHANG = 0x1 WUNTRACED = 0x2 XCASE = 0x1000000 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x30) EADDRNOTAVAIL = syscall.Errno(0x31) EAFNOSUPPORT = syscall.Errno(0x2f) EAGAIN = syscall.Errno(0x23) EALREADY = syscall.Errno(0x25) EAUTH = syscall.Errno(0x50) EBADF = syscall.Errno(0x9) EBADMSG = syscall.Errno(0x5c) EBADRPC = syscall.Errno(0x48) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x58) ECHILD = syscall.Errno(0xa) ECONNABORTED = syscall.Errno(0x35) ECONNREFUSED = syscall.Errno(0x3d) ECONNRESET = syscall.Errno(0x36) EDEADLK = syscall.Errno(0xb) EDESTADDRREQ = syscall.Errno(0x27) EDOM = syscall.Errno(0x21) EDQUOT = syscall.Errno(0x45) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EFTYPE = syscall.Errno(0x4f) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EIDRM = syscall.Errno(0x59) EILSEQ = syscall.Errno(0x54) EINPROGRESS = syscall.Errno(0x24) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EIPSEC = syscall.Errno(0x52) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) ELAST = syscall.Errno(0x5f) ELOOP = syscall.Errno(0x3e) EMEDIUMTYPE = syscall.Errno(0x56) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x28) ENAMETOOLONG = syscall.Errno(0x3f) ENEEDAUTH = syscall.Errno(0x51) ENETDOWN = syscall.Errno(0x32) ENETRESET = syscall.Errno(0x34) ENETUNREACH = syscall.Errno(0x33) ENFILE = syscall.Errno(0x17) ENOATTR = syscall.Errno(0x53) ENOBUFS = syscall.Errno(0x37) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x4d) ENOMEDIUM = syscall.Errno(0x55) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x5a) ENOPROTOOPT = syscall.Errno(0x2a) ENOSPC = syscall.Errno(0x1c) ENOSYS = syscall.Errno(0x4e) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) ENOTRECOVERABLE = syscall.Errno(0x5d) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x5b) ENOTTY = syscall.Errno(0x19) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x2d) EOVERFLOW = syscall.Errno(0x57) EOWNERDEAD = syscall.Errno(0x5e) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) EPROCLIM = syscall.Errno(0x43) EPROCUNAVAIL = syscall.Errno(0x4c) EPROGMISMATCH = syscall.Errno(0x4b) EPROGUNAVAIL = syscall.Errno(0x4a) EPROTO = syscall.Errno(0x5f) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) ERANGE = syscall.Errno(0x22) EREMOTE = syscall.Errno(0x47) EROFS = syscall.Errno(0x1e) ERPCMISMATCH = syscall.Errno(0x49) ESHUTDOWN = syscall.Errno(0x3a) ESOCKTNOSUPPORT = syscall.Errno(0x2c) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESTALE = syscall.Errno(0x46) ETIMEDOUT = syscall.Errno(0x3c) ETOOMANYREFS = syscall.Errno(0x3b) ETXTBSY = syscall.Errno(0x1a) EUSERS = syscall.Errno(0x44) EWOULDBLOCK = syscall.Errno(0x23) EXDEV = syscall.Errno(0x12) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x14) SIGCONT = syscall.Signal(0x13) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x1d) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x17) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPROF = syscall.Signal(0x1b) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x11) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTHR = syscall.Signal(0x20) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x12) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x10) SIGUSR1 = syscall.Signal(0x1e) SIGUSR2 = syscall.Signal(0x1f) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errorList = [...]struct { num syscall.Errno name string desc string }{ {1, "EPERM", "operation not permitted"}, {2, "ENOENT", "no such file or directory"}, {3, "ESRCH", "no such process"}, {4, "EINTR", "interrupted system call"}, {5, "EIO", "input/output error"}, {6, "ENXIO", "device not configured"}, {7, "E2BIG", "argument list too long"}, {8, "ENOEXEC", "exec format error"}, {9, "EBADF", "bad file descriptor"}, {10, "ECHILD", "no child processes"}, {11, "EDEADLK", "resource deadlock avoided"}, {12, "ENOMEM", "cannot allocate memory"}, {13, "EACCES", "permission denied"}, {14, "EFAULT", "bad address"}, {15, "ENOTBLK", "block device required"}, {16, "EBUSY", "device busy"}, {17, "EEXIST", "file exists"}, {18, "EXDEV", "cross-device link"}, {19, "ENODEV", "operation not supported by device"}, {20, "ENOTDIR", "not a directory"}, {21, "EISDIR", "is a directory"}, {22, "EINVAL", "invalid argument"}, {23, "ENFILE", "too many open files in system"}, {24, "EMFILE", "too many open files"}, {25, "ENOTTY", "inappropriate ioctl for device"}, {26, "ETXTBSY", "text file busy"}, {27, "EFBIG", "file too large"}, {28, "ENOSPC", "no space left on device"}, {29, "ESPIPE", "illegal seek"}, {30, "EROFS", "read-only file system"}, {31, "EMLINK", "too many links"}, {32, "EPIPE", "broken pipe"}, {33, "EDOM", "numerical argument out of domain"}, {34, "ERANGE", "result too large"}, {35, "EAGAIN", "resource temporarily unavailable"}, {36, "EINPROGRESS", "operation now in progress"}, {37, "EALREADY", "operation already in progress"}, {38, "ENOTSOCK", "socket operation on non-socket"}, {39, "EDESTADDRREQ", "destination address required"}, {40, "EMSGSIZE", "message too long"}, {41, "EPROTOTYPE", "protocol wrong type for socket"}, {42, "ENOPROTOOPT", "protocol not available"}, {43, "EPROTONOSUPPORT", "protocol not supported"}, {44, "ESOCKTNOSUPPORT", "socket type not supported"}, {45, "EOPNOTSUPP", "operation not supported"}, {46, "EPFNOSUPPORT", "protocol family not supported"}, {47, "EAFNOSUPPORT", "address family not supported by protocol family"}, {48, "EADDRINUSE", "address already in use"}, {49, "EADDRNOTAVAIL", "can't assign requested address"}, {50, "ENETDOWN", "network is down"}, {51, "ENETUNREACH", "network is unreachable"}, {52, "ENETRESET", "network dropped connection on reset"}, {53, "ECONNABORTED", "software caused connection abort"}, {54, "ECONNRESET", "connection reset by peer"}, {55, "ENOBUFS", "no buffer space available"}, {56, "EISCONN", "socket is already connected"}, {57, "ENOTCONN", "socket is not connected"}, {58, "ESHUTDOWN", "can't send after socket shutdown"}, {59, "ETOOMANYREFS", "too many references: can't splice"}, {60, "ETIMEDOUT", "operation timed out"}, {61, "ECONNREFUSED", "connection refused"}, {62, "ELOOP", "too many levels of symbolic links"}, {63, "ENAMETOOLONG", "file name too long"}, {64, "EHOSTDOWN", "host is down"}, {65, "EHOSTUNREACH", "no route to host"}, {66, "ENOTEMPTY", "directory not empty"}, {67, "EPROCLIM", "too many processes"}, {68, "EUSERS", "too many users"}, {69, "EDQUOT", "disk quota exceeded"}, {70, "ESTALE", "stale NFS file handle"}, {71, "EREMOTE", "too many levels of remote in path"}, {72, "EBADRPC", "RPC struct is bad"}, {73, "ERPCMISMATCH", "RPC version wrong"}, {74, "EPROGUNAVAIL", "RPC program not available"}, {75, "EPROGMISMATCH", "program version wrong"}, {76, "EPROCUNAVAIL", "bad procedure for program"}, {77, "ENOLCK", "no locks available"}, {78, "ENOSYS", "function not implemented"}, {79, "EFTYPE", "inappropriate file type or format"}, {80, "EAUTH", "authentication error"}, {81, "ENEEDAUTH", "need authenticator"}, {82, "EIPSEC", "IPsec processing failure"}, {83, "ENOATTR", "attribute not found"}, {84, "EILSEQ", "illegal byte sequence"}, {85, "ENOMEDIUM", "no medium found"}, {86, "EMEDIUMTYPE", "wrong medium type"}, {87, "EOVERFLOW", "value too large to be stored in data type"}, {88, "ECANCELED", "operation canceled"}, {89, "EIDRM", "identifier removed"}, {90, "ENOMSG", "no message of desired type"}, {91, "ENOTSUP", "not supported"}, {92, "EBADMSG", "bad message"}, {93, "ENOTRECOVERABLE", "state not recoverable"}, {94, "EOWNERDEAD", "previous owner died"}, {95, "ELAST", "protocol error"}, } // Signal table var signalList = [...]struct { num syscall.Signal name string desc string }{ {1, "SIGHUP", "hangup"}, {2, "SIGINT", "interrupt"}, {3, "SIGQUIT", "quit"}, {4, "SIGILL", "illegal instruction"}, {5, "SIGTRAP", "trace/BPT trap"}, {6, "SIGABRT", "abort trap"}, {7, "SIGEMT", "EMT trap"}, {8, "SIGFPE", "floating point exception"}, {9, "SIGKILL", "killed"}, {10, "SIGBUS", "bus error"}, {11, "SIGSEGV", "segmentation fault"}, {12, "SIGSYS", "bad system call"}, {13, "SIGPIPE", "broken pipe"}, {14, "SIGALRM", "alarm clock"}, {15, "SIGTERM", "terminated"}, {16, "SIGURG", "urgent I/O condition"}, {17, "SIGSTOP", "suspended (signal)"}, {18, "SIGTSTP", "suspended"}, {19, "SIGCONT", "continued"}, {20, "SIGCHLD", "child exited"}, {21, "SIGTTIN", "stopped (tty input)"}, {22, "SIGTTOU", "stopped (tty output)"}, {23, "SIGIO", "I/O possible"}, {24, "SIGXCPU", "cputime limit exceeded"}, {25, "SIGXFSZ", "filesize limit exceeded"}, {26, "SIGVTALRM", "virtual timer expired"}, {27, "SIGPROF", "profiling timer expired"}, {28, "SIGWINCH", "window size changes"}, {29, "SIGINFO", "information request"}, {30, "SIGUSR1", "user defined signal 1"}, {31, "SIGUSR2", "user defined signal 2"}, {32, "SIGTHR", "thread AST"}, }
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.Linq; namespace LiteDB { /// <summary> /// Manages all transactions and grantees concurrency and recovery /// </summary> internal class TransactionService { private IDiskService _disk; private AesEncryption _crypto; private LockService _locker; private PageService _pager; private CacheService _cache; private Logger _log; private int _cacheSize; internal TransactionService(IDiskService disk, AesEncryption crypto, PageService pager, LockService locker, CacheService cache, int cacheSize, Logger log) { _disk = disk; _crypto = crypto; _cache = cache; _locker = locker; _pager = pager; _cacheSize = cacheSize; _log = log; } /// <summary> /// Checkpoint is a safe point to clear cache pages without loose pages references. /// Is called after each document insert/update/deleted/indexed/fetch from query /// Clear only clean pages - do not clear dirty pages (transaction) /// Return true if cache was clear /// </summary> public bool CheckPoint() { if (_cache.CleanUsed > _cacheSize) { _log.Write(Logger.CACHE, "cache size reached {0} pages, will clear now", _cache.CleanUsed); _cache.ClearPages(); return true; } return false; } /// <summary> /// Save all dirty pages to disk /// </summary> public void PersistDirtyPages() { // get header page var header = _pager.GetPage<HeaderPage>(0); // increase file changeID (back to 0 when overflow) header.ChangeID = header.ChangeID == ushort.MaxValue ? (ushort)0 : (ushort)(header.ChangeID + (ushort)1); // mark header as dirty _pager.SetDirty(header); _log.Write(Logger.DISK, "begin disk operations - changeID: {0}", header.ChangeID); // write journal file in desc order to header be last page in disk if (_disk.IsJournalEnabled) { _disk.WriteJournal(_cache.GetDirtyPages() .OrderByDescending(x => x.PageID) .Select(x => x.DiskData) .Where(x => x.Length > 0) .ToList(), header.LastPageID); // mark header as recovery before start writing (in journal, must keep recovery = false) header.Recovery = true; // flush to disk to ensure journal is committed to disk before proceeding _disk.Flush(); } else { // if no journal extend, resize file here to fast writes _disk.SetLength(BasePage.GetSizeOfPages(header.LastPageID + 1)); } // write header page first. if header.Recovery == true, this ensures it's written to disk *before* we start changing pages var headerPage = _cache.GetPage(0); var headerBuffer = headerPage.WritePage(); _disk.WritePage(0, headerBuffer); _disk.Flush(); // get all dirty page stating from Header page (SortedList) // header page (id=0) always must be first page to write on disk because it's will mark disk as "in recovery" foreach (var page in _cache.GetDirtyPages()) { // we've already written the header, so skip it if (page.PageID == 0) { continue; } // page.WritePage() updated DiskData with new rendered buffer var buffer = _crypto == null || page.PageID == 0 ? page.WritePage() : _crypto.Encrypt(page.WritePage()); _disk.WritePage(page.PageID, buffer); } if (_disk.IsJournalEnabled) { // ensure changed pages are persisted to disk *before* we change header.Recovery to false _disk.Flush(); // re-write header page but now with recovery=false header.Recovery = false; _log.Write(Logger.DISK, "re-write header page now with recovery = false"); _disk.WritePage(0, header.WritePage()); } // mark all dirty pages as clean pages (all are persisted in disk and are valid pages) _cache.MarkDirtyAsClean(); // flush all data direct to disk _disk.Flush(); // discard journal file _disk.ClearJournal(header.LastPageID); } /// <summary> /// Get journal pages and override all into datafile /// </summary> public void Recovery() { _log.Write(Logger.RECOVERY, "initializing recovery mode"); using (_locker.Write()) { // double check in header need recovery (could be already recover from another thread) var header = BasePage.ReadPage(_disk.ReadPage(0)) as HeaderPage; if (header.Recovery == false) return; // read all journal pages foreach (var buffer in _disk.ReadJournal(header.LastPageID)) { // read pageID (first 4 bytes) var pageID = BitConverter.ToUInt32(buffer, 0); _log.Write(Logger.RECOVERY, "recover page #{0:0000}", pageID); // write in stream (encrypt if datafile is encrypted) _disk.WritePage(pageID, _crypto == null || pageID == 0 ? buffer : _crypto.Encrypt(buffer)); } // shrink datafile _disk.ClearJournal(header.LastPageID); } } } }
{ "pile_set_name": "Github" }
/* * Copyright © 2014 Intel Corporation * * 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #ifndef BRW_META_UTIL_H #define BRW_META_UTIL_H #include <stdbool.h> #include "main/mtypes.h" #include "intel_mipmap_tree.h" #ifdef __cplusplus extern "C" { #endif bool brw_meta_mirror_clip_and_scissor(const struct gl_context *ctx, const struct gl_framebuffer *read_fb, const struct gl_framebuffer *draw_fb, GLfloat *srcX0, GLfloat *srcY0, GLfloat *srcX1, GLfloat *srcY1, GLfloat *dstX0, GLfloat *dstY0, GLfloat *dstX1, GLfloat *dstY1, bool *mirror_x, bool *mirror_y); union isl_color_value brw_meta_convert_fast_clear_color(const struct brw_context *brw, const struct intel_mipmap_tree *mt, const union gl_color_union *color); bool brw_is_color_fast_clear_compatible(struct brw_context *brw, const struct intel_mipmap_tree *mt, const union gl_color_union *color); #ifdef __cplusplus } #endif #endif /* BRW_META_UTIL_H */
{ "pile_set_name": "Github" }
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!159 &1 EditorSettings: m_ObjectHideFlags: 0 serializedVersion: 3 m_ExternalVersionControlSupport: Visible Meta Files m_SerializationMode: 2 m_WebSecurityEmulationEnabled: 0 m_WebSecurityEmulationHostUrl: http://www.mydomain.com/mygame.unity3d m_DefaultBehaviorMode: 0 m_SpritePackerMode: 2 m_SpritePackerPaddingPower: 1 m_ProjectGenerationIncludedExtensions: txt;xml;fnt;cd m_ProjectGenerationRootNamespace:
{ "pile_set_name": "Github" }
// license:BSD-3-Clause // copyright-holders:Fabio Priuli /********************************************************************** SNK Neo Geo Mahjong controller emulation **********************************************************************/ #ifndef MAME_BUS_NEOGEO_CTRL_MAHJONG_H #define MAME_BUS_NEOGEO_CTRL_MAHJONG_H #pragma once #include "ctrl.h" //************************************************************************** // TYPE DEFINITIONS //************************************************************************** // ======================> neogeo_mjctrl_ac_device class neogeo_mjctrl_ac_device : public device_t, public device_neogeo_control_port_interface { public: // construction/destruction neogeo_mjctrl_ac_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock); protected: neogeo_mjctrl_ac_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock); // device-level overrides virtual ioport_constructor device_input_ports() const override; virtual uint8_t read_start_sel() override; virtual void device_start() override; // device_neogeo_control_port_interface overrides virtual uint8_t read_ctrl() override; virtual void write_ctrlsel(uint8_t data) override; uint8_t m_ctrl_sel; required_ioport m_ss; private: required_ioport_array<3> m_mjpanel; }; // ======================> neogeo_mjctrl_device class neogeo_mjctrl_device : public neogeo_mjctrl_ac_device { public: // construction/destruction neogeo_mjctrl_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock); protected: // optional information overrides virtual ioport_constructor device_input_ports() const override; // device_neogeo_control_port_interface overrides virtual uint8_t read_start_sel() override; }; // device type definition DECLARE_DEVICE_TYPE(NEOGEO_MJCTRL_AC, neogeo_mjctrl_ac_device) DECLARE_DEVICE_TYPE(NEOGEO_MJCTRL, neogeo_mjctrl_device) #endif // MAME_BUS_NEOGEO_CTRL_MAHJONG_H
{ "pile_set_name": "Github" }
package org.springframework.data.mongodb.core.mapreduce; public class ContentAndVersion { private String id; private String document_id; private String content; private String author; private Long version; private Long value; public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getDocumentId() { return document_id; } public Long getValue() { return value; } public void setValue(Long value) { this.value = value; } public void setDocumentId(String documentId) { this.document_id = documentId; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } @Override public String toString() { return "ContentAndVersion [id=" + id + ", document_id=" + document_id + ", content=" + content + ", author=" + author + ", version=" + version + ", value=" + value + "]"; } }
{ "pile_set_name": "Github" }