code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
<html> <head> <script type="text/javascript"> <!-- window.location = window.strike.getMPCServer() + "/info.html"; //--> </script> </head> </html>
Codeusa/Strike
Android App/assets/info.html
HTML
gpl-2.0
151
package com.lj.template.ui; import android.content.Context; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.ProgressBar; import android.widget.TextView; import com.lj.template.R; import com.lj.template.commonadapter.CommonAdapter; import com.lj.template.commonadapter.ViewHolder; import com.lj.template.letter.LetterView; import com.lj.template.letter.Person; import com.lj.template.letter.SortUtil; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * 自定义通讯录列表. * 将耗时的操作放在主线程,导致视图加载等待中发生丢帧情况 */ public class NoteBookActivity extends AppCompatActivity { private Context context; /** * 进度框 */ private ProgressBar progressBar; /** * 列表 */ private ListView listview; /** * 字母提示 */ private TextView textview; /** * 中心区域的展示字母 */ private TextView letterDialog; private PopupWindow popupWindow; private CommonAdapter<Person> commonAdapter; private List<Person> data = new ArrayList<Person>(); private Handler handler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notebook); context = this; // 搜索框 EditText etSearch = (EditText) findViewById(R.id.searchEdit); progressBar = (ProgressBar) findViewById(R.id.progress); progressBar.setVisibility(View.VISIBLE); listview = (ListView) findViewById(R.id.listview); listview.setVisibility(View.GONE); textview = (TextView) findViewById(R.id.textview); // 字母索引表 LetterView letters = (LetterView) findViewById(R.id.letter); // TextView比PopupWindow性能好些 letters.setOnTouchLettersListener(touchLettersListener1); letterDialog = (TextView) LayoutInflater.from(this).inflate(R.layout.pop_textview_dialog, (ViewGroup) null); commonAdapter = new CommonAdapter<Person>(context, data, R.layout.letter_item) { @Override public void convert(ViewHolder holder, Person t) { if (holder.getPosition() == 0) { // 第一个记录总是显示字母条与姓名 holder.setVisible(R.id.letter, true); holder.setText(R.id.letter, t.getLetter()); } else { // 判断是否显示字母条 // 将搜索结果也区分,则用下面 // 获取上一条记录的姓名首字母 String lastLetter = commonAdapter.getmDatas().get(holder.getPosition() - 1).getLetter(); if (t.getLetter().equals(lastLetter)) { // 与上一条记录相同,不显示字母条 holder.setVisible(R.id.letter, false); } else { // 与上一条记录不同,显示字母条 holder.setVisible(R.id.letter, true); holder.setText(R.id.letter, t.getLetter()); } } holder.setText(R.id.name, t.getName()); } }; listview.setAdapter(commonAdapter); handler.postDelayed(new Runnable() { @Override public void run() { progressBar.setVisibility(View.GONE); listview.setVisibility(View.VISIBLE); String[] contact = getResources().getStringArray(R.array.contact); /** * 此段获取汉字拼音首字符并进行排序的操作比较耗时,对视图的绘制展示会有一定的影响。通过post的方式在主线程执行时, * 会提示Skipped xxx frames! The application may be doing too much work on its main thread. * 对于这种问题,可以将这些耗时代码放入到子线程,通过Message的方式来处理结果。 */ for (int i = 0; i < contact.length; i++) { Person person = new Person(); String name = contact[i]; // 处理空值或特殊字符的情况 char firstLetter = TextUtils.isEmpty(name) ? '#' : name.charAt(0); String type = SortUtil.getFirstCharType(firstLetter); person.setName(name); person.setLetter(type); data.add(person); } Collections.sort(data, new PersonComparator()); System.out.println(com.alibaba.fastjson.JSON.toJSONString(data)); commonAdapter.notifyDataSetChanged(); } }, 1000); etSearch.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { List<Person> list = new ArrayList<Person>(); if (!TextUtils.isEmpty(s)) { for (int i = 0; i < data.size(); i++) { boolean bool = false; Person person = data.get(i); if(s.length()==1){ // 单字符时 /** * 考虑到输入的可能可能会是小写、大写,所以要分别判断 * 不能用||,因为这||前面为true,后面就不会判断了。表达式必须都判断,才能得出精准结果。 * */ int c = s.charAt(0); if(c >= 97 && c <= 122){ // 小写字母 String UpText = s.toString().toUpperCase(); bool = person.getName().contains(s) | person.getName().contains(UpText); }else if(c >= 65 && c <= 90){ // 大写字母 String lowText = s.toString().toLowerCase(); bool = person.getName().contains(s) | person.getName().contains(lowText); }else{ // 非字母 bool = person.getName().contains(s); } }else{ //多字符,全字符匹配 bool = person.getName().contains(s); } if (bool) { list.add(person); } } commonAdapter.setmDatas(list); } else { commonAdapter.setmDatas(data); } commonAdapter.notifyDataSetChanged(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); } @Override protected void onDestroy() { super.onDestroy(); } /** * 通过位原视图中心的TextView来展示手指碰触到的字母 */ private LetterView.OnTouchLettersListener touchLettersListener1 = new LetterView.OnTouchLettersListener() { @Override public void onTouchLettersUp() { textview.setVisibility(View.GONE); } @Override public void onTouchLettersDown(String letter) { int m = -1; m = getSelectedIndex(letter, m); listview.setSelection(m); textview.setVisibility(View.VISIBLE); textview.setText(letter); } }; /** * 通过PopupWindow弹窗来展示手指碰触到的字母 */ private LetterView.OnTouchLettersListener touchLettersListener2 = new LetterView.OnTouchLettersListener() { @Override public void onTouchLettersUp() { if (popupWindow != null) { popupWindow.dismiss(); } } @Override public void onTouchLettersDown(String letter) { int m = -1; m = getSelectedIndex(letter, m); listview.setSelection(m); if (popupWindow == null) { popupWindow = new PopupWindow(letterDialog, 150, 150, false); } // 显示在Activity的根视图中心 popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0); letterDialog.setText(letter); } }; /** * 获取手指碰触的字母对应列表应该定位的位置 * @param letter * @param m * @return */ private int getSelectedIndex(String letter, int m) { if (letter.equals("↑")) { // 如果是箭头,直接回到顶端 m = 0; } else { for (int i = 0; i < data.size(); i++) { if (data.get(i).getLetter().equals(letter)) { m = i; break; } } } return m; } /** * 排序算法(如果首字符相同,则按Unicode码排序;首字符不同的,按首字符排) */ class PersonComparator implements Comparator<Person> { @Override public int compare(Person lhs, Person rhs) { String lhsLetter = lhs.getLetter(); String rhsLetter = rhs.getLetter(); if (lhsLetter.equals(rhsLetter)) { // 首字符相同 return lhs.getName().compareTo(rhs.getName()); } else { // 首字符不同 if (lhsLetter.equals("#")) { return 1; // 前者为#,前者比后者大,前者后移 } else if (rhsLetter.equals("#")) { return -1; // 后者为#,前者比后者少,前者前移 } else { return lhsLetter.compareTo(rhsLetter); } } } } }
wbhqf3/test
Template/app/src/main/java/com/lj/template/ui/NoteBookActivity.java
Java
gpl-2.0
10,555
/* * Copyright (C) 2006, 2018 by Rafael Santiago * * This is a free software. You can redistribute it and/or modify under * the terms of the GNU General Public License version 2. * */ #ifndef KRYPTOS_KRYPTOS_RC6_H #define KRYPTOS_KRYPTOS_RC6_H 1 #include <kryptos_types.h> #define KRYPTOS_RC6_BLOCKSIZE 16 KRYPTOS_DECL_CUSTOM_BLOCK_CIPHER_SETUP(rc6_128, ktask, int *rounds) KRYPTOS_DECL_BLOCK_CIPHER_PROCESSOR(rc6_128) KRYPTOS_DECL_CUSTOM_BLOCK_CIPHER_GCM_E(rc6_128, void *rounds) KRYPTOS_DECL_CUSTOM_BLOCK_CIPHER_SETUP(rc6_192, ktask, int *rounds) KRYPTOS_DECL_BLOCK_CIPHER_PROCESSOR(rc6_192) KRYPTOS_DECL_CUSTOM_BLOCK_CIPHER_GCM_E(rc6_192, void *rounds) KRYPTOS_DECL_CUSTOM_BLOCK_CIPHER_SETUP(rc6_256, ktask, int *rounds) KRYPTOS_DECL_BLOCK_CIPHER_PROCESSOR(rc6_256) KRYPTOS_DECL_CUSTOM_BLOCK_CIPHER_GCM_E(rc6_256, void *rounds) #endif
rafael-santiago/kryptos
src/kryptos_rc6.h
C
gpl-2.0
881
//sT<?php exit; ?>a:1:{s:7:"content";O:8:"stdClass":24:{s:2:"ID";i:1306;s:11:"post_author";s:1:"1";s:9:"post_date";s:19:"2014-10-31 10:09:46";s:13:"post_date_gmt";s:19:"2014-10-31 10:09:46";s:12:"post_content";s:0:"";s:10:"post_title";s:15:"reglobe-thumb-1";s:12:"post_excerpt";s:0:"";s:11:"post_status";s:7:"inherit";s:14:"comment_status";s:6:"closed";s:11:"ping_status";s:6:"closed";s:13:"post_password";s:0:"";s:9:"post_name";s:15:"reglobe-thumb-1";s:7:"to_ping";s:0:"";s:6:"pinged";s:0:"";s:13:"post_modified";s:19:"2014-10-31 10:09:46";s:17:"post_modified_gmt";s:19:"2014-10-31 10:09:46";s:21:"post_content_filtered";s:0:"";s:11:"post_parent";i:0;s:4:"guid";s:89:"http://localhost:8888/greenapplesolutions/wp-content/uploads/2014/10/reglobe-thumb-11.png";s:10:"menu_order";i:0;s:9:"post_type";s:10:"attachment";s:14:"post_mime_type";s:9:"image/png";s:13:"comment_count";s:1:"0";s:6:"filter";s:3:"raw";}}
ngupta0309/greenapplesolutions
wp-content/cache/object/000000/ef7/766/ef776636d6dabda879a8e88a640d1aac.php
PHP
gpl-2.0
908
// ================================================== // Copyright (C) 2005-2006 Intel Corporation // // 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, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // /** * @file TagVecValue8NF.cpp */ // General includes. #include <stdio.h> // Dreams includes. #include "dDB/taghandler/TagHandler.h" #include "dDB/trackheap/TagVecValue8NF.h" #include "dDB/trackheap/TagVecValue8NFDense.h" /* * Creator of this class. * * @return new object. */ TagVecValue8NF::TagVecValue8NF(INT32 bcycle, INT32 maxEntries) { baseCycle = bcycle; nextEntry = 0; valvec = new TagVecValue8Node[maxEntries]; } /* * Destructor of this class. Nothing is done. * * @return destroys the object. */ TagVecValue8NF::~TagVecValue8NF() { delete [] valvec; } /* * Resets the state of the vector. * * @return void. */ void TagVecValue8NF::reset(INT32 bcycle) { baseCycle = bcycle; nextEntry = 0; } /* * Gets the value of this tag in the cycle cycle. * * @return true if the value has been found. */ TagReturn TagVecValue8NF::getTagValue(INT32 cycle, UINT64 * value, INT32 * atcycle) { UINT32 offset; ///< Internal offset for the cycle. UINT32 lower; ///< Lowest element that is in the valid range of the binary search. UINT32 upper; ///< Highest element that is in the valid range of the binary search. UINT32 middle; ///< Actual element that is being evaluated. // Gets the internal offset for the requested cycle. offset = cycle - baseCycle; // Checks if a value is defined inside this vector. if(valvec[0].cycleOffset > (UINT32) offset) { return TAG_NOT_FOUND; } // Initialization for the dicotomic search. // At least one entry, so in case that only one entry was inserted, // i will point to this entry the first cycle. lower = 0; upper = nextEntry - 1; // Performas a binary search along all the valid entries of the vector. while(upper >= lower) { // Computes the actual element. middle = (lower + upper) >> 1; // Checks if we've found the element: // The end condition is reached when the actual element has an offset // equal or lower than the cycle and when the following element is outside // the vector or when its offset is bigger than the cycle. if(valvec[middle].cycleOffset == offset) { * value = (UINT64) valvec[middle].value; // Checks if the caller wants to know the cycle. if(atcycle != NULL) { * atcycle = cycle; } // We've found something for sure. return TAG_FOUND; } // Checks which direction we must go. if(valvec[middle].cycleOffset < offset) { lower = middle + 1; } else { upper = middle - 1; } } // Nothing found. return TAG_NOT_FOUND; } /* * Compresses the vector to a dense vector. * * @return the compressed vector. */ ZipObject * TagVecValue8NF::compressYourSelf(CYCLE cycle, bool last) { ZipObject * result = this; if(last || (cycle.cycle >= (baseCycle + CYCLE_CHUNK_SIZE - 1))) { double density = ((double) nextEntry / (double) CYCLE_CHUNK_SIZE); // Only is compressed if is a low densed vector. if(density < TAG_VEC_VALUE_8_MIN_DENSITY) { result = new TagVecValue8NFDense(this); } } return result; } /* * Gets the number of cycles that a value is defined. * * @return the occupancy. */ INT32 TagVecValue8NF::getOccupancy(bool defined, INT32 lastCycle) const { INT32 occ; occ = 0; for(INT16 i = 0; i < nextEntry; i++) { occ += valvec[i].defined; } return occ; } /* * Dumps the content of the vector. * * @return void. */ void TagVecValue8NF::dumpCycleVector() { printf("Dumping cycle vector base cycle = %d. Encoding type is TVE_VALUE_8_NF\n", baseCycle); printf("TVE_VALUE_8_NF efficiency = %g \n", ((double) nextEntry / (double) CYCLE_CHUNK_SIZE * 100.0)); for(INT16 i = 0; i < nextEntry; i++) { printf("<%d,%u> ", baseCycle + valvec[i].cycleOffset, valvec[i].value); } printf("\n"); } /* * Computes the object size and returns the value * * @return the object size. */ INT64 TagVecValue8NF::getObjSize() const { INT64 size; size = sizeof(TagVecValue8NF) + (CYCLE_CHUNK_SIZE * sizeof(TagVecValue8Node)); return size; } /* * Returns the usage description. Unimplemented. * * @return empty string. */ QString TagVecValue8NF::getUsageDescription() const { return ""; } /* * Moves the handler to the next value with change. * * @return if a different value has been found. */ bool TagVecValue8NF::skipToNextCycleWithChange(InternalTagHandler * hnd) { if(hnd->act_entry == -1) { // As we know that the tag handler calls first the getActualValue we have two cases: // - No entry in the offset 0: then act_entry remains in -1 and the act_defined is set to false. // If the previous defined was true, it will be detected by the tag handler, so always the // defined value will be false. // - Entry in the offset 0: the getActualValue will set move act_entry to 0, so we don't care // about this case. // We move to the next defined entry. hnd->act_entry = 0; hnd->act_defined = true; hnd->act_cycle.cycle = valvec[0].cycleOffset + baseCycle; hnd->act_value = valvec[0].value; return true; } // Checks if we found a value in the last search. if(valvec[hnd->act_entry].cycleOffset == (UINT32) (hnd->act_cycle.cycle & (CYCLE_CHUNK_SIZE - 1))) { INT32 last_cycle = (hnd->act_cycle.cycle & (CYCLE_CHUNK_SIZE - 1)) - 1; // We try to find an undefine. while(hnd->act_entry < nextEntry) { // Checks if the entries are consecutive. if(valvec[hnd->act_entry].cycleOffset == (UINT32) (last_cycle + 1)) { UINT64 temp_value = valvec[hnd->act_entry].value; // Checks if the values are different. if(temp_value != hnd->act_value) { hnd->act_value = temp_value; hnd->act_cycle.cycle = valvec[hnd->act_entry].cycleOffset + baseCycle; return true; } } else { // We've found a non consecutive value. We must undefine. hnd->act_defined = false; hnd->act_entry--; hnd->act_cycle.cycle = valvec[hnd->act_entry].cycleOffset + baseCycle + 1; return true; } last_cycle++; hnd->act_entry++; } hnd->act_entry--; // If the last entry is in the last cycle, then we haven't found a value. if(valvec[hnd->act_entry].cycleOffset == (CYCLE_CHUNK_SIZE - 1)) { return false; } // We have found an undefined after the last entry. hnd->act_defined = false; hnd->act_cycle.cycle = valvec[hnd->act_entry].cycleOffset + baseCycle + 1; return true; } else { hnd->act_entry++; if(hnd->act_entry >= nextEntry) { return false; } hnd->act_defined = true; hnd->act_value = valvec[hnd->act_entry].value; hnd->act_cycle.cycle = valvec[hnd->act_entry].cycleOffset + baseCycle; return true; } } /* * Gets the value for the actual cycle where the handler is pointing. * * @return void. */ void TagVecValue8NF::getActualValue(InternalTagHandler * hnd) { UINT16 offset = (hnd->act_cycle.cycle & (CYCLE_CHUNK_SIZE - 1)); while((hnd->act_entry < (nextEntry - 1)) && (valvec[hnd->act_entry + 1].cycleOffset < offset)) { hnd->act_entry++; } if((hnd->act_entry < (nextEntry - 1)) && (valvec[hnd->act_entry + 1].cycleOffset == offset)) { hnd->act_entry++; hnd->act_defined = true; hnd->act_value = valvec[hnd->act_entry].value; } else { hnd->act_defined = false; } }
Asim-Dreams/dreams
tools/Dreams/src/dDB/trackheap/TagVecValue8NF.cpp
C++
gpl-2.0
8,921
.flowplayer{position:relative;width:100%;background-size:contain;background-repeat:no-repeat;background-position:center center;display:inline-block;} .flowplayer *{font-weight:inherit;font-family:inherit;font-style:inherit;text-decoration:inherit;font-size:100%;padding:0;border:0;margin:0;list-style-type:none} .flowplayer a:focus{outline:0} .flowplayer video{width:100%} .flowplayer.is-ipad video{-webkit-transform:translateX(-2048px);} .is-ready.flowplayer.is-ipad video{-webkit-transform:translateX(0)} .flowplayer .fp-engine,.flowplayer .fp-ui,.flowplayer .fp-message{position:absolute;top:0;left:0;width:100%;height:100%;cursor:pointer;z-index:1} .flowplayer .fp-message{display:none;text-align:center;padding-top:5%;cursor:default;} .flowplayer .fp-message h2{font-size:120%;margin-bottom:1em} .flowplayer .fp-message p{color:#666;font-size:95%} .flowplayer .fp-controls{position:absolute;bottom:0;width:100%;} .no-background.flowplayer .fp-controls{background-color:transparent !important;background-image:-moz-linear-gradient(transparent,transparent) !important;background-image:-webkit-gradient(linear,0 0,0 100%,from(transparent),to(transparent)) !important} .is-fullscreen.flowplayer .fp-controls{bottom:3px} .is-mouseover.flowplayer .fp-controls{bottom:0} .flowplayer .fp-waiting{display:none;margin:19% auto;text-align:center;} .flowplayer .fp-waiting *{-webkit-box-shadow:0 0 5px #333;-moz-box-shadow:0 0 5px #333;box-shadow:0 0 5px #333} .flowplayer .fp-waiting em{width:1em;height:1em;-webkit-border-radius:1em;-moz-border-radius:1em;border-radius:1em;background-color:rgba(255,255,255,0.8);display:inline-block;-webkit-animation:pulse .6s infinite;-moz-animation:pulse .6s infinite;animation:pulse .6s infinite;margin:.3em;opacity:0;filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=0);} .flowplayer .fp-waiting em:nth-child(1){-webkit-animation-delay:.3s;-moz-animation-delay:.3s;animation-delay:.3s} .flowplayer .fp-waiting em:nth-child(2){-webkit-animation-delay:.45s;-moz-animation-delay:.45s;animation-delay:.45s} .flowplayer .fp-waiting em:nth-child(3){-webkit-animation-delay:.6s;-moz-animation-delay:.6s;animation-delay:.6s} .flowplayer .fp-waiting p{color:#ccc;font-weight:bold} .flowplayer .fp-speed{font-size:30px;background-color:#333;background-color:rgba(51,51,51,0.8);color:#eee;margin:0 auto;text-align:center;width:120px;padding:.1em 0 0;opacity:0;filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=0);-webkit-transition:opacity .5s;-moz-transition:opacity .5s;transition:opacity .5s;} .flowplayer .fp-speed.fp-hilite{opacity:1;filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=100)} .flowplayer .fp-help{position:absolute;top:0;left:-9999em;z-index:100;background-color:#333;background-color:rgba(51,51,51,0.9);width:100%;height:100%;opacity:0;filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=0);-webkit-transition:opacity .2s;-moz-transition:opacity .2s;transition:opacity .2s;text-align:center;} .is-help.flowplayer .fp-help{left:0;opacity:1;filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=100)} .flowplayer .fp-help .fp-help-section{margin:3%;direction:ltr} .flowplayer .fp-help .fp-help-basics{margin-top:6%} .flowplayer .fp-help p{color:#eee;margin:.5em 0;font-size:14px;line-height:1.5;display:inline-block;margin:1% 2%} .flowplayer .fp-help em{background:#eee;-webkit-border-radius:.3em;-moz-border-radius:.3em;border-radius:.3em;margin-right:.4em;padding:.3em .6em;color:#333} .flowplayer .fp-help small{font-size:90%;color:#aaa} .flowplayer .fp-help .fp-close{display:block} @media (max-width: 600px){.flowplayer .fp-help p{font-size:9px} }.flowplayer .fp-subtitle{position:absolute;bottom:40px;left:-99999em;z-index:10;text-align:center;width:100%;opacity:0;filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=0);-webkit-transition:opacity .3s;-moz-transition:opacity .3s;transition:opacity .3s;} .flowplayer .fp-subtitle p{display:inline;background-color:#333;background-color:rgba(51,51,51,0.9);color:#eee;padding:.1em .4em;font-size:16px;line-height:1.6;} .flowplayer .fp-subtitle p:after{content:'';clear:both} .flowplayer .fp-subtitle.fp-active{left:0;opacity:1;filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=100)} .flowplayer .fp-fullscreen,.flowplayer .fp-unload,.flowplayer .fp-mute,.flowplayer .fp-embed,.flowplayer .fp-close,.flowplayer .fp-play{background-image:url(img/white.png);background-size:37px 300px;} .is-rtl.flowplayer .fp-fullscreen,.is-rtl.flowplayer .fp-unload,.is-rtl.flowplayer .fp-mute,.is-rtl.flowplayer .fp-embed,.is-rtl.flowplayer .fp-close,.is-rtl.flowplayer .fp-play{background-image:url(img/white_rtl.png)} .color-light.flowplayer .fp-fullscreen,.color-light.flowplayer .fp-unload,.color-light.flowplayer .fp-mute,.color-light.flowplayer .fp-embed,.color-light.flowplayer .fp-close,.color-light.flowplayer .fp-play{background-image:url(img/black.png);} .is-rtl.color-light.flowplayer .fp-fullscreen,.is-rtl.color-light.flowplayer .fp-unload,.is-rtl.color-light.flowplayer .fp-mute,.is-rtl.color-light.flowplayer .fp-embed,.is-rtl.color-light.flowplayer .fp-close,.is-rtl.color-light.flowplayer .fp-play{background-image:url(img/black_rtl.png)} @media (-webkit-min-device-pixel-ratio: 2){.color-light.flowplayer .fp-fullscreen,.color-light.flowplayer .fp-unload,.color-light.flowplayer .fp-mute,.color-light.flowplayer .fp-embed,.color-light.flowplayer .fp-close,.color-light.flowplayer .fp-play{background-image:url(img/black@x2.png)} .is-rtl.color-light.flowplayer .fp-fullscreen,.is-rtl.color-light.flowplayer .fp-unload,.is-rtl.color-light.flowplayer .fp-mute,.is-rtl.color-light.flowplayer .fp-embed,.is-rtl.color-light.flowplayer .fp-close,.is-rtl.color-light.flowplayer .fp-play{background-image:url(img/black_rtl@x2.png)} }@media (-webkit-min-device-pixel-ratio: 2){.flowplayer .fp-fullscreen,.flowplayer .fp-unload,.flowplayer .fp-mute,.flowplayer .fp-embed,.flowplayer .fp-close,.flowplayer .fp-play{background-image:url(img/white@x2.png)} .is-rtl.flowplayer .fp-fullscreen,.is-rtl.flowplayer .fp-unload,.is-rtl.flowplayer .fp-mute,.is-rtl.flowplayer .fp-embed,.is-rtl.flowplayer .fp-close,.is-rtl.flowplayer .fp-play{background-image:url(img/white_rtl@x2.png)} }.flowplayer .fp-flash-disabled{background:#333;width:390px;margin:0 auto;position:absolute;bottom:0;color:#fff} .is-splash.flowplayer .fp-ui,.is-paused.flowplayer .fp-ui{background:url(img/play_white.png) center no-repeat;background-size:12%;} .is-rtl.is-splash.flowplayer .fp-ui,.is-rtl.is-paused.flowplayer .fp-ui{background:url(img/play_white_rtl.png) center no-repeat;background-size:12%} @media (-webkit-min-device-pixel-ratio: 2){.is-splash.flowplayer .fp-ui,.is-paused.flowplayer .fp-ui{background:url(img/play_white@x2.png) center no-repeat;background-size:12%} .is-rtl.is-splash.flowplayer .fp-ui,.is-rtl.is-paused.flowplayer .fp-ui{background:url(img/play_white_rtl@x2.png) center no-repeat;background-size:12%} }.color-light.is-splash.flowplayer .fp-ui,.color-light.is-paused.flowplayer .fp-ui{background-image:url(img/play_black.png);} .is-rtl.color-light.is-splash.flowplayer .fp-ui,.is-rtl.color-light.is-paused.flowplayer .fp-ui{background-image:url(img/play_black_rtl.png)} @media (-webkit-min-device-pixel-ratio: 2){.color-light.is-splash.flowplayer .fp-ui,.color-light.is-paused.flowplayer .fp-ui{background-image:url(img/play_black@x2.png);} .is-rtl.color-light.is-splash.flowplayer .fp-ui,.is-rtl.color-light.is-paused.flowplayer .fp-ui{background-image:url(img/play_black_rtl@x2.png)} }.is-fullscreen.flowplayer .fp-ui{background-size:auto} .is-seeking.flowplayer .fp-ui,.is-loading.flowplayer .fp-ui{background-image:none} .flowplayer .fp-logo{position:absolute;top:auto;left:15px;bottom:40px;cursor:pointer;display:none;z-index:100;} .flowplayer .fp-logo img{width:100%} .is-embedded.flowplayer .fp-logo{display:block} .fixed-controls.flowplayer .fp-logo{bottom:15px} .flowplayer .fp-fullscreen,.flowplayer .fp-unload,.flowplayer .fp-close{position:absolute;top:10px;left:auto;right:10px;display:block;width:30px;height:23px;background-position:12px -197px;cursor:pointer;} .is-rtl.flowplayer .fp-fullscreen,.is-rtl.flowplayer .fp-unload,.is-rtl.flowplayer .fp-close{right:auto;left:10px;background-position:18px -197px} .flowplayer .fp-unload,.flowplayer .fp-close{background-position:14px -175px;display:none;} .is-rtl.flowplayer .fp-unload,.is-rtl.flowplayer .fp-close{background-position:14px -175px} .flowplayer .fp-play{display:none;width:27px;height:30px;background-position:9px -24px;position:absolute;bottom:0;left:0;} .is-rtl.flowplayer .fp-play{background-position:18px -24px;left:auto;right:0} .play-button.flowplayer .fp-play{display:block} .is-paused.flowplayer .fp-play{background-position:9px 7px;} .is-rtl.is-paused.flowplayer .fp-play{background-position:18px 7px} .flowplayer.is-ready.is-closeable .fp-unload{display:block} .flowplayer.is-ready.is-closeable .fp-fullscreen{display:none} .flowplayer.is-fullscreen .fp-fullscreen{background-position:10px -217px;display:block !important;} .is-rtl.flowplayer.is-fullscreen .fp-fullscreen{background-position:21px -217px} .flowplayer.is-fullscreen .fp-unload,.flowplayer.is-fullscreen .fp-close{display:none !important} .flowplayer .fp-timeline{height:3px;position:relative;overflow:hidden;top:10px;height:10px;margin:0 165px 0 55px;} .no-volume.flowplayer .fp-timeline{margin-right:75px} .no-mute.flowplayer .fp-timeline{margin-right:155px} .no-mute.no-volume.flowplayer .fp-timeline{margin-right:55px} .play-button.flowplayer .fp-timeline{margin-left:72px} .is-rtl.flowplayer .fp-timeline{margin:0 55px 0 165px;} .no-volume.is-rtl.flowplayer .fp-timeline{margin-left:75px} .no-mute.is-rtl.flowplayer .fp-timeline{margin-left:155px} .no-mute.no-volume.is-rtl.flowplayer .fp-timeline{margin-left:55px} .play-button.is-rtl.flowplayer .fp-timeline{margin-right:72px} .is-long.flowplayer .fp-timeline{margin:0 195px 0 85px;} .no-volume.is-long.flowplayer .fp-timeline{margin-right:105px} .no-mute.is-long.flowplayer .fp-timeline{margin-right:85px} .play-button.is-long.flowplayer .fp-timeline{margin-left:102px} .is-rtl.is-long.flowplayer .fp-timeline{margin:85px 0 195px 0;} .no-volume.is-rtl.is-long.flowplayer .fp-timeline{margin-left:105px} .no-mute.is-rtl.is-long.flowplayer .fp-timeline{margin-left:85px} .play-button.is-rtl.is-long.flowplayer .fp-timeline{margin-left:102px} .aside-time.flowplayer .fp-timeline,.no-time.flowplayer .fp-timeline{margin:0 120px 0 10px} .aside-time.no-volume.flowplayer .fp-timeline,.no-time.no-volume.flowplayer .fp-timeline{margin-right:30px} .aside-time.no-mute.flowplayer .fp-timeline,.no-time.no-mute.flowplayer .fp-timeline{margin-right:10px} .play-button.no-time.flowplayer .fp-timeline,.play-button.aside-time.flowplayer .fp-timeline{margin-left:27px} .is-rtl.aside-time.flowplayer .fp-timeline,.is-rtl.no-time.flowplayer .fp-timeline{margin:0 10px 0 120px} .is-rtl.aside-time.no-volume.flowplayer .fp-timeline,.is-rtl.no-time.no-volume.flowplayer .fp-timeline{margin-left:30px} .is-rtl.aside-time.no-mute.flowplayer .fp-timeline,.is-rtl.no-time.no-mute.flowplayer .fp-timeline{margin-left:10px} .is-rtl.play-button.no-time.flowplayer .fp-timeline,.is-rtl.play-button.aside-time.flowplayer .fp-timeline{margin-right:27px} .flowplayer .fp-buffer,.flowplayer .fp-progress{position:absolute;top:0;left:auto;height:100%;cursor:col-resize} .flowplayer .fp-buffer{-webkit-transition:width .25s linear;-moz-transition:width .25s linear;transition:width .25s linear} .flowplayer .fp-timeline.no-animation .fp-buffer{-webkit-transition:none;-moz-transition:none;transition:none} .flowplayer.is-touch .fp-timeline{overflow:visible} .flowplayer.is-touch .fp-progress{-webkit-transition:width .2s linear;-moz-transition:width .2s linear;transition:width .2s linear} .flowplayer.is-touch .fp-timeline.is-dragging .fp-progress{-webkit-transition:right .1s linear,border .1s linear,top .1s linear,left .1s linear;-moz-transition:right .1s linear,border .1s linear,top .1s linear,left .1s linear;transition:right .1s linear,border .1s linear,top .1s linear,left .1s linear} .flowplayer.is-touch.is-mouseover .fp-progress:after,.flowplayer.is-touch.is-mouseover .fp-progress:before{content:'';display:block;-webkit-border-radius:10px;-moz-border-radius:10px;border-radius:10px;position:absolute;right:-5px} .flowplayer.is-touch.is-rtl.is-mouseover .fp-progress:after,.flowplayer.is-touch.is-rtl.is-mouseover .fp-progress:before{right:auto;left:-5px} .flowplayer.is-touch.is-rtl.is-mouseover .fp-progress:after{left:-10px;-webkit-box-shadow:-1px 0 4px rgba(0,0,0,0.5);-moz-box-shadow:-1px 0 4px rgba(0,0,0,0.5);box-shadow:-1px 0 4px rgba(0,0,0,0.5)} .flowplayer.is-touch.is-mouseover .fp-progress:before{width:10px;height:10px} .flowplayer.is-touch.is-mouseover .fp-progress:after{height:10px;width:10px;top:-5px;right:-10px;border:5px solid rgba(255,255,255,0.65);-webkit-box-shadow:1px 0 4px rgba(0,0,0,0.5);-moz-box-shadow:1px 0 4px rgba(0,0,0,0.5);box-shadow:1px 0 4px rgba(0,0,0,0.5)} .flowplayer.is-touch.is-mouseover .fp-timeline.is-dragging .fp-progress:after{border:10px solid #fff;-webkit-border-radius:20px;-moz-border-radius:20px;border-radius:20px;-webkit-transition:inherit;-moz-transition:inherit;transition:inherit;top:-10px;right:-15px} .flowplayer.is-touch.is-rtl.is-mouseover .fp-timeline.is-dragging .fp-progress:after{left:-15px;right:auto;border:10px solid #fff} .flowplayer .fp-volume{position:absolute;top:11px;right:10px;} .is-rtl.flowplayer .fp-volume{right:auto;left:10px} .flowplayer .fp-mute{position:relative;width:10px;height:15px;float:left;top:-3.5px;cursor:pointer;background-position:-2px -99px;} .is-rtl.flowplayer .fp-mute{float:right;background-position:-25px -99px} .no-mute.flowplayer .fp-mute{display:none} .flowplayer .fp-volumeslider{width:90px;height:8px;cursor:col-resize;float:left;} .is-rtl.flowplayer .fp-volumeslider{float:right} .no-volume.flowplayer .fp-volumeslider{display:none} .flowplayer .fp-volumelevel{height:100%} .flowplayer .fp-time{text-shadow:0 0 1px #000;font-size:12px;font-weight:bold;color:#fff;width:100%;} .flowplayer .fp-time.is-inverted .fp-duration{display:none} .flowplayer .fp-time.is-inverted .fp-remaining{display:inline} .flowplayer .fp-time em{width:35px;height:10px;line-height:10px;text-align:center;position:absolute;bottom:10px} .no-time.flowplayer .fp-time{display:none} .is-long.flowplayer .fp-time em{width:65px} .flowplayer .fp-elapsed{left:10px;} .play-button.flowplayer .fp-elapsed{left:27px} .is-rtl.flowplayer .fp-elapsed{left:auto;right:10px;} .play-button.is-rtl.flowplayer .fp-elapsed{right:27px} .flowplayer .fp-remaining,.flowplayer .fp-duration{right:120px;color:#eee;} .no-volume.flowplayer .fp-remaining,.no-volume.flowplayer .fp-duration{right:30px} .no-mute.flowplayer .fp-remaining,.no-mute.flowplayer .fp-duration{right:110px} .no-mute.no-volume.flowplayer .fp-remaining,.no-mute.no-volume.flowplayer .fp-duration{right:10px} .is-rtl.flowplayer .fp-remaining,.is-rtl.flowplayer .fp-duration{right:auto;left:120px;} .no-volume.is-rtl.flowplayer .fp-remaining,.no-volume.is-rtl.flowplayer .fp-duration{left:30px} .no-mute.is-rtl.flowplayer .fp-remaining,.no-mute.is-rtl.flowplayer .fp-duration{left:110px} .no-mute.no-volume.is-rtl.flowplayer .fp-remaining,.no-mute.no-volume.is-rtl.flowplayer .fp-duration{left:10px} .flowplayer .fp-remaining{display:none} .flowplayer.color-light .fp-time{color:#222;text-shadow:0 0 1px #fff} .flowplayer.color-light .fp-remaining,.flowplayer.color-light .fp-duration{color:#666} .flowplayer.aside-time .fp-time{position:absolute;top:10px;left:10px;bottom:auto !important;width:100px;} .flowplayer.aside-time .fp-time strong,.flowplayer.aside-time .fp-time em{position:static} .flowplayer.aside-time .fp-time .fp-elapsed{margin-right:10px;} .is-rtl.flowplayer.aside-time .fp-time .fp-elapsed{margin-right:auto;margin-left:10px} .flowplayer.is-long.aside-time .fp-time{width:130px} .flowplayer.is-splash,.flowplayer.is-poster{cursor:pointer;} .flowplayer.is-splash .fp-controls,.flowplayer.is-poster .fp-controls,.flowplayer.is-splash .fp-fullscreen,.flowplayer.is-poster .fp-fullscreen,.flowplayer.is-splash .fp-unload,.flowplayer.is-poster .fp-unload,.flowplayer.is-splash .fp-time,.flowplayer.is-poster .fp-time,.flowplayer.is-splash .fp-embed,.flowplayer.is-poster .fp-embed{display:none !important} .flowplayer.is-poster .fp-engine{top:-9999em} .flowplayer.is-loading .fp-waiting{display:block} .flowplayer.is-loading .fp-controls,.flowplayer.is-loading .fp-time{display:none} .flowplayer.is-loading .fp-ui{background-position:-9999em} .flowplayer.is-loading video.fp-engine{position:absolute;top:-9999em} .flowplayer.is-seeking .fp-waiting{display:block} .flowplayer.is-playing{background-image:none !important;background-color:#333;} .flowplayer.is-playing.hls-fix.is-finished .fp-engine{position:absolute;top:-9999em} .flowplayer.is-fullscreen{position:fixed !important;top:0 !important;left:0 !important;border:0 !important;margin:0 !important;width:100% !important;height:100% !important;max-width:100% !important;z-index:99999 !important;-webkit-box-shadow:0 !important;-moz-box-shadow:0 !important;box-shadow:0 !important;background-image:none !important;background-color:#333;} .is-rtl.flowplayer.is-fullscreen{left:auto !important;right:0 !important} .flowplayer.is-error{border:1px solid #909090;background:#fdfdfd !important;} .flowplayer.is-error h2{font-weight:bold;font-size:large;margin-top:10%} .flowplayer.is-error .fp-message{display:block} .flowplayer.is-error object,.flowplayer.is-error video,.flowplayer.is-error .fp-controls,.flowplayer.is-error .fp-time,.flowplayer.is-error .fp-subtitle{display:none} .flowplayer.is-ready.is-muted .fp-mute{opacity:.5;filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=50)} .flowplayer.is-mouseout .fp-controls{height:0;-webkit-transition:height .15s .3s;-moz-transition:height .15s .3s;transition:height .15s .3s} .flowplayer.is-mouseout .fp-timeline{margin:0 !important} .flowplayer.is-mouseout .fp-timeline{-webkit-transition:height .15s .3s,top .15s .3s,margin .15s .3s;-moz-transition:height .15s .3s,top .15s .3s,margin .15s .3s;transition:height .15s .3s,top .15s .3s,margin .15s .3s;height:4px;top:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0} .flowplayer.is-mouseout .fp-fullscreen,.flowplayer.is-mouseout .fp-unload,.flowplayer.is-mouseout .fp-elapsed,.flowplayer.is-mouseout .fp-remaining,.flowplayer.is-mouseout .fp-duration,.flowplayer.is-mouseout .fp-embed,.flowplayer.is-mouseout .fp-volume,.flowplayer.is-mouseout .fp-play{opacity:0;filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=0);-webkit-transition:opacity .15s .3s;-moz-transition:opacity .15s .3s;transition:opacity .15s .3s} .flowplayer.is-mouseover .fp-controls,.flowplayer.fixed-controls .fp-controls{height:30px} .flowplayer.is-mouseover .fp-fullscreen,.flowplayer.fixed-controls .fp-fullscreen,.flowplayer.is-mouseover .fp-unload,.flowplayer.fixed-controls .fp-unload,.flowplayer.is-mouseover .fp-elapsed,.flowplayer.fixed-controls .fp-elapsed,.flowplayer.is-mouseover .fp-remaining,.flowplayer.fixed-controls .fp-remaining,.flowplayer.is-mouseover .fp-duration,.flowplayer.fixed-controls .fp-duration,.flowplayer.is-mouseover .fp-embed,.flowplayer.fixed-controls .fp-embed,.flowplayer.is-mouseover .fp-logo,.flowplayer.fixed-controls .fp-logo,.flowplayer.is-mouseover .fp-volume,.flowplayer.fixed-controls .fp-volume,.flowplayer.is-mouseover .fp-play,.flowplayer.fixed-controls .fp-play{opacity:1;filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=100)} .flowplayer.fixed-controls .fp-volume{display:block} .flowplayer.fixed-controls .fp-controls{bottom:-30px;} .is-fullscreen.flowplayer.fixed-controls .fp-controls{bottom:0} .flowplayer.fixed-controls .fp-time em{bottom:-20px;opacity:1;filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=100);} .is-fullscreen.flowplayer.fixed-controls .fp-time em{bottom:10px} .flowplayer.is-disabled .fp-progress{background-color:#999} .flowplayer.is-flash-disabled{background-color:#333;} .flowplayer.is-flash-disabled object.fp-engine{z-index:100} .flowplayer.is-flash-disabled .fp-flash-disabled{display:block;z-index:101} .flowplayer .fp-embed{position:absolute;top:10px;left:10px;display:block;width:25px;height:20px;background-position:3px -237px;} .is-rtl.flowplayer .fp-embed{background-position:22px -237px;left:auto;right:10px} .flowplayer .fp-embed-code{position:absolute;display:none;top:10px;left:40px;background-color:#333;padding:3px 5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:0 0 3px #ccc;-moz-box-shadow:0 0 3px #ccc;box-shadow:0 0 3px #ccc;font-size:12px;} .flowplayer .fp-embed-code:before{content:'';width:0;height:0;position:absolute;top:2px;left:-10px;border:5px solid transparent;border-right-color:#333} .is-rtl.flowplayer .fp-embed-code{left:auto;right:40px;} .is-rtl.flowplayer .fp-embed-code:before{left:auto;right:-10px;border-right-color:transparent;border-left-color:#333} .flowplayer .fp-embed-code textarea{width:400px;height:16px;font-family:monaco,"courier new",verdana;color:#777;white-space:nowrap;resize:none;overflow:hidden;border:0;outline:0;background-color:transparent;color:#ccc} .flowplayer .fp-embed-code label{display:block;color:#999} .flowplayer.is-embedding .fp-embed,.flowplayer.is-embedding .fp-embed-code{display:block;opacity:1;filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=100)} .flowplayer.aside-time .fp-embed{left:100px;} .is-rtl.flowplayer.aside-time .fp-embed{left:auto;right:100px} .flowplayer.aside-time .fp-embed-code{left:130px;} .is-rtl.flowplayer.aside-time .fp-embed-code{left:auto;right:130px} .flowplayer.aside-time.is-embedding .fp-time{opacity:1;filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=100)} .flowplayer.is-long.aside-time .fp-embed{left:130px;} .is-rtl.flowplayer.is-long.aside-time .fp-embed{left:auto;right:130px} .flowplayer.no-time .fp-embed{left:10px !important;} .is-rtl.flowplayer.no-time .fp-embed{left:auto;right:10px !important} .flowplayer.is-live .fp-timeline,.flowplayer.is-live .fp-duration,.flowplayer.is-live .fp-remaining{display:none} .flowplayer .fp-context-menu{position:absolute;display:none;z-index:1001;background-color:#fff;padding:10px;border:1px solid #aaa;-webkit-box-shadow:0 0 4px #888;-moz-box-shadow:0 0 4px #888;box-shadow:0 0 4px #888;width:170px;} .flowplayer .fp-context-menu li{text-align:center;padding:10px;color:#444;margin:0 -10px 0 -10px;} .flowplayer .fp-context-menu li a{color:#00a7c8;font-size:110%} .flowplayer .fp-context-menu li:hover:not(.copyright){background-color:#eee} .flowplayer .fp-context-menu li.copyright{margin:0;padding-left:110px;background-image:url("img/flowplayer.png");background-repeat:no-repeat;background-size:100px 20px;background-position:5px 5px;border-bottom:1px solid #bbb;} @media (-webkit-min-device-pixel-ratio: 2){.flowplayer .fp-context-menu li.copyright{background-image:url("img/flowplayer@2x.png")} }@-moz-keyframes pulse{0%{opacity:0} 100%{opacity:1} }@-webkit-keyframes pulse{0%{opacity:0} 100%{opacity:1} }@-o-keyframes pulse{0%{opacity:0} 100%{opacity:1} }@-ms-keyframes pulse{0%{opacity:0} 100%{opacity:1} }@keyframes pulse{0%{opacity:0} 100%{opacity:1} }.flowplayer .fp-controls{background-color:#111} .flowplayer .fp-timeline{background-color:#555} .flowplayer .fp-buffer{background-color:#eee} .flowplayer .fp-progress{background-color:#4da5d8} .flowplayer.is-touch.is-mouseover .fp-progress:before{background-color:#4da5d8} .flowplayer .fp-volumelevel{background-color:#fff} .flowplayer .fp-volumeslider{background-color:#555} .flowplayer .fp-timeline,.flowplayer .fp-volumeslider{border:1px inset;border-color:rgba(0,0,0,0.2) rgba(17,17,17,0.05)} .flowplayer .fp-controls,.flowplayer .fp-progress{background-image:-moz-linear-gradient(rgba(255,255,255,0.4),rgba(255,255,255,0.01));background-image:-webkit-gradient(linear,0 0,0 100%,from(rgba(255,255,255,0.4)),to(rgba(255,255,255,0.01)))} .flowplayer .fp-timeline,.flowplayer .fp-buffer,.flowplayer .fp-progress,.flowplayer .fp-volumeslider,.flowplayer .fp-volumelevel{-webkit-border-radius:10px;-moz-border-radius:10px;border-radius:10px} .flowplayer.color-light .fp-controls{background-color:#eee;background-image:-moz-linear-gradient(rgba(0,0,0,0.01),rgba(0,0,0,0.3));background-image:-webkit-gradient(linear,0 0,0 100%,from(rgba(0,0,0,0.01)),to(rgba(0,0,0,0.3)))} .flowplayer.color-light .fp-timeline,.flowplayer.color-light .fp-volumeslider{border-color:#eee #ccc} .flowplayer.color-light .fp-timeline,.flowplayer.color-light .fp-volumeslider{background-color:#ccc;font-size:10px} .flowplayer.color-alt .fp-progress{background-image:-moz-linear-gradient(#999,#111);background-image:-webkit-gradient(linear,0 0,0 100%,from(#999),to(#111))} .flowplayer.color-alt.is-touch.is-mouseover .fp-progress:before{background-image:-moz-linear-gradient(#999,#111);background-image:-webkit-gradient(linear,0 0,0 100%,from(#999),to(#111))} .flowplayer.color-alt .fp-timeline,.flowplayer.color-alt .fp-volumeslider{background-color:#111} .flowplayer.color-alt2 .fp-progress{background-color:#900} .flowplayer.color-alt2.is-touch.is-mouseover .fp-progress:before{background-color:#900}
wp-plugins/flowplayer5
frontend/assets/flowplayer/skin/functional.css
CSS
gpl-2.0
25,440
# GBRT for Luroeykalven case study site # Training data: manually digitized training areas, including water pixels # Predictors: results of FCLS spectral unmixing # Authors: Stefan Blumentrath import numpy as np import matplotlib.pyplot as plt from sklearn import ensemble from sklearn import datasets from sklearn.utils import shuffle from sklearn.metrics import mean_squared_error from sklearn.metrics import r2_score from sklearn.ensemble.partial_dependence import plot_partial_dependence from sklearn.model_selection import GridSearchCV from grass.pygrass import raster as r from grass.pygrass.utils import getenv import grass.script as gs from cStringIO import StringIO from subprocess import PIPE from io import BytesIO from itertools import combinations def setParamDict(): params = {} for p in ['learning_rate', 'max_depth', 'loss', 'subsample', 'min_samples_leaf', 'max_features', 'n_estimators']: if p in ['max_depth', 'min_samples_leaf', 'n_estimators']: params[p] = map(int, options[p].split(',')) elif p in ['learning_rate', 'max_features', 'subsample']: params[p] = map(float, options[p].split(',')) else: params[p] = options[p].split(',') return params def writeMap(name, x,y,z): result = BytesIO() np.savetxt(result, np.column_stack((x, y, z))) result.seek(0) gs.write_command('r.in.xyz', stdin=result.getvalue(), input='-', output=name, method='mean', separator=' ', overwrite=True) # ############################################################################# # Define variables # List of input maps has to start with Y # Initaial settings for automatized model selection options = {'cores': '20', 'learning_rate': '0.009,0.007,0.005', 'max_depth': '11,13,15', 'min_samples_leaf': '1,2,3', 'max_features': '0.9,0.8,0.7', 'subsample': '0.5', 'loss': 'huber', 'n_estimators': '3000', 'y': 'test_area_luroeykalven_water_grid_25833_10m@p_Sentinel4Nature_S2_Luroeykalven', 'x': 'unmix_pysptools_bands_NDVI_VVVH_10000_10_NFINDR_FCLS_mask_1,unmix_pysptools_bands_NDVI_VVVH_10000_10_NFINDR_FCLS_mask_2,unmix_pysptools_bands_NDVI_VVVH_10000_10_NFINDR_FCLS_mask_3,unmix_pysptools_bands_NDVI_VVVH_10000_10_NFINDR_FCLS_mask_4,unmix_pysptools_bands_NDVI_VVVH_10000_10_NFINDR_FCLS_mask_5,unmix_pysptools_bands_NDVI_VVVH_10000_10_NFINDR_FCLS_mask_6,unmix_pysptools_bands_NDVI_VVVH_10000_10_NFINDR_FCLS_mask_7,unmix_pysptools_bands_NDVI_VVVH_10000_10_NFINDR_FCLS_mask_8,unmix_pysptools_bands_NDVI_VVVH_10000_10_NFINDR_FCLS_mask_9,unmix_pysptools_bands_NDVI_VVVH_10000_10_NFINDR_FCLS_mask_10', 'deviance': '/data/R/GeoSpatialData/Orthoimagery/Fenoscandia_Sentinel_2/temp_Avd15GIS/Case_Luroeykalven/regression/Luroeykalven_water_FCLS_GBRT_deviance.pdf', 'featureimportance': '/data/R/GeoSpatialData/Orthoimagery/Fenoscandia_Sentinel_2/temp_Avd15GIS/Case_Luroeykalven/regression/Luroeykalven_water_FCLS_GBRT_featureimportance.pdf', 'partialdependence': '/data/R/GeoSpatialData/Orthoimagery/Fenoscandia_Sentinel_2/temp_Avd15GIS/Case_Luroeykalven/regression/Luroeykalven_water_FCLS_GBRT_partial_dependence.pdf', 'crossval': '0.25', 'output': 'ForestCover_Luroeykalven_water_FCLS', 'spatial_term': None } cores = int(options['cores']) spatial_term = options['spatial_term'] output = options['output'] deviance = options['deviance'] featureimportance = options['featureimportance'] partialdependence = options['partialdependence'] crossval = float(options['crossval']) params = setParamDict() # ############################################################################# # Load data maps = [options['y']] + options['x'].rstrip('\n').split(',') data = np.genfromtxt(BytesIO(gs.read_command('r.stats', flags='1Ng', input=maps)), delimiter=" ") y = 2 if spatial_term: x = [0,1] + range(3,len(data[0])) else: x = range(3,len(data[0])) # Create a mas for NoData in either x or y mask_y = np.isnan(data[:,y]) for i in range(3,len(data[0])): if i == 3: mask_x = np.isnan(data[:,i]) else: mask_x = np.logical_or((np.isnan(data[:,i])), mask_x) all_y_idx = np.where(np.logical_or(mask_x, mask_y)==False) all_x_idx = np.where(mask_x==False) # Random shuffle data points with training data, excluding all NoData all_y = shuffle(data[all_y_idx]) # Training and test set offset = int(all_y.shape[0] * (1 - crossval)) X_train, y_train, coor_train = all_y[:offset,x], all_y[:offset,y], all_y[:offset,[0,1]] X_test, y_test, coor_test= all_y[offset:,x], all_y[offset:,y], all_y[offset:,[0,1]] # Set for predicitions predict, coor_predict = data[all_x_idx][:,x], data[all_x_idx][:,[0,1]] # Run model selection process if requested model_selection = False for k in params.keys(): if len(params[k]) > 1: model_selection = True if model_selection: gs.message('Running model selection ...') clf = ensemble.GradientBoostingRegressor() # this may take some minutes gs_cv = GridSearchCV(clf, params, n_jobs=cores).fit(X_train, y_train) # best hyperparameter setting best_params = gs_cv.best_params_ print('Best hyper-parameter set is:') print(best_params) else: best_params = {} for k in params.keys(): best_params[k] = params[k][0] # ############################################################################# # Fit regression model gs.message('Fitting regression model ...') clf = ensemble.GradientBoostingRegressor(**best_params) clf.fit(X_train, y_train) mse = mean_squared_error(y_test, clf.predict(X_test)) r2 = r2_score(y_test, clf.predict(X_test)) print("MSE: %.4f" % mse) print("R2: %.4f" % r2) # ############################################################################# # Generate requested plots # Plot training deviance # compute test set deviance if deviance: test_score = np.zeros((best_params['n_estimators'],), dtype=np.float64) for i, y_pred in enumerate(clf.staged_predict(X_test)): test_score[i] = clf.loss_(y_test, y_pred) plt.figure(figsize=(12, 6)) plt.rcParams.update({'figure.autolayout': True}) plt.title('Deviance') plt.plot(np.arange(best_params['n_estimators']) + 1, clf.train_score_, 'b-', label='Training Set Deviance') plt.plot(np.arange(best_params['n_estimators']) + 1, test_score, 'r-', label='Test Set Deviance') plt.legend(loc='upper right') plt.xlabel('Boosting Iterations') plt.ylabel('Deviance') plt.savefig(deviance) # ############################################################################# # Plot feature importance if featureimportance: if spatial_term: cols = ['x', 'y'] + maps[1:] else: cols = maps[1:] plt.figure(figsize=(12, 12)) plt.rcParams.update({'figure.autolayout': True}) feature_importance = clf.feature_importances_ # make importances relative to max importance feature_importance = 100.0 * (feature_importance / feature_importance.max()) sorted_idx = np.argsort(feature_importance) pos = np.arange(sorted_idx.shape[0]) + .5 #plt.subplot(1, 2, 2) plt.barh(pos, feature_importance[sorted_idx], align='center') plt.yticks(pos, np.array(cols)[sorted_idx]) plt.xlabel('Relative Importance') plt.title('Variable Importance') plt.savefig(featureimportance) if partialdependence: if spatial_term: cols = ['x', 'y'] + maps[1:] else: cols = maps[1:] fig, axs = plot_partial_dependence(clf, X_train, cols, n_jobs=cores, n_cols=2, feature_names=cols, figsize=(len(cols), len(cols)*2)) fig.savefig(partialdependence) sorted_idx = np.argsort(clf.feature_importances_) twoway = list(combinations(list(reversed(sorted_idx[-6:])), 2)) fig, axs = plot_partial_dependence(clf, X_train, twoway, n_jobs=cores, n_cols=2, feature_names=cols, figsize=(len(twoway), int(len(twoway)*3))) fig.savefig(partialdependence.rstrip('.pdf') + '_twoway.pdf') # ############################################################################# # Predict data outside trainifrom subprocess import PIPEng areas writeMap(output, coor_predict[:,0], coor_predict[:,1], clf.predict(predict)) # Write train error map writeMap(output + '_train_error', coor_train[:,0], coor_train[:,1], clf.predict(X_train) - y_train) # Write test error map writeMap(output + '_test_error', coor_test[:,0], coor_test[:,1], clf.predict(X_test) - y_test)
NINAnor/sentinel4nature
Tree canopy cover/regression/GBRT_Luroeykalven_manual_FCLS.py
Python
gpl-2.0
8,821
<!doctype html> <html xmlns:ng="//angularjs.org" ng-app="my_app" id="ng-app" > <head> <meta charset="utf-8"> <meta http-equiv="pragma" content="no-cache" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <title> 간편 </title> <link href="./css/custom.css" rel="stylesheet"> <link href="./css/bootstrap.min.css" rel="stylesheet"> <!--[if lte IE 8]> <script src="./js/json3.min.js"></script> <![endif]--> </head> <body ng-controller='appCtrl'> <div class="container" style="margin-top:100px;" > <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-body" id="search"> <div class="row" > <div class="col-md-12"> <h1>추첨기</h1> </div> <div class="col-md-12 padded"> <input type="text" class="form-control input-lg" ng-model="url" placeholder=" http://todayhumor.com/?bestofbest_170188 "> <div class="checkbox"> <label><input type="checkbox" ng-model="email_only" ng-true-value='Y' ng-false-value='N' > 이메일 있는것만 골라보기</label> </div> </div> <div class="col-md-12 padded"> <button class="btn btn-block btn-success btn-lg" ng-click="start()" >Go!</button> </div> <!-- <div class="col-md-12"> <div class="alert alert-success" role="alert">...</div> <div class="alert alert-info" role="alert">...</div> <div class="alert alert-warning" role="alert">...</div> <div class="alert alert-danger" role="alert">...</div> </div> --> </div> </div> <div class="panel-body" id="search_list" style="display:none;"> <div class="alert alert-info" role="alert">아래 목록을 편집하신 후 아래 추첨 버튼을 눌러주세요.(총 {{comment_list.length}}개)</div> <div class="row"> <div class="col-md-12 padded"> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">검색</label> <div class="col-sm-10"> <input type="text" class="form-control" ng-model="searchText"> </div> </div> </div> </div> <div class="row" > <div class="col-md-12" style="height:500px;overflow-y:scroll;"> <table class="table"> <tr> <th ng-click="list_sort='ip'">ip</th> <th ng-click="list_sort='date'">date</th> <th ng-click="list_sort='join'">join</th> <th ng-click="list_sort='active'">active</th> <th ng-click="list_sort='up'">up</th> <th ng-click="list_sort='down'">down</th> <th ng-click="list_sort='nick'">nick</th> <th ng-click="list_sort='memo'" ng-show="email_only=='N'">memo</th> <th ng-click="list_sort='mail'">mail</th> <th >Action</th> </tr> <tr ng-repeat=" item in comment_list | orderBy : list_sort | filter:searchText " class="item_{{item.use}}"> <td>{{item.ip}}</td> <td>{{item.date}}</td> <td>{{item.join}}</td> <td>{{item.active}}</td> <td>{{item.up}}</td> <td>{{item.down}}</td> <td>{{item.nick}}</td> <td ng-show="email_only=='N'">{{item.memo}}</td> <td>{{item.mail}}</td> <td> <button class="btn btn-xs btn-danger" ng-show="item.use == 1" ng-click='change_state(item.seq,0)'>제외</button> <button class="btn btn-xs btn-success" ng-show="item.use != 1" ng-click='change_state(item.seq,1)'>복구</button> </td> </tr> </table> </div> </div> <div class="row"> <div class="col-md-6 padded"> <div class="form-group"> <label for="inputEmail3" class="col-sm-4 control-label">당첨인원</label> <div class="col-sm-8"> <input type="text" class="form-control" id='lottery_count' placeholder="숫자만 입력하세요."> </div> </div> </div> <div class="col-md-6 padded"> <button class="btn btn-block btn-success btn-lg" ng-click="lottery()" >추첨!</button> </div> </div> </div> <div class="panel-body" id="lottery_result" style="display:none;"> <div class="row" > <div class="col-md-12" style="height:500px;overflow-y:scroll;"> <table class="table"> <tr> <th>ip</th> <th>date</th> <th>join</th> <th>active</th> <th>up</th> <th>down</th> <th>nick</th> <th ng-show="email_only=='N'">memo</th> <th>mail</th> </tr> <tr ng-repeat=" item in lottery_list" class="item_{{item.use}}"> <td>{{item.ip}}</td> <td>{{item.date}}</td> <td>{{item.join}}</td> <td>{{item.active}}</td> <td>{{item.up}}</td> <td>{{item.down}}</td> <td>{{item.nick}}</td> <td ng-show="email_only=='N'">{{item.memo}}</td> <td>{{item.mail}}</td> </tr> </table> </div> </div> </div> </div> </div> </div> <script type="text/javascript" src="./js/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="./js/bootstrap.min.js"></script> <script type="text/javascript" src="./js/angular.min.js"></script> <script type="text/javascript" src="./js/application.js"></script> <script type="text/javascript" src="./js/php.default.js"></script> </body> </html>
naearu/todayhumor_chuchom
index.php
PHP
gpl-2.0
5,729
#include <linux/module.h> #include <linux/moduleparam.h> #include <linux/init.h> #include <linux/types.h> #include <linux/fcntl.h> #include <linux/string.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/timer.h> #include <linux/ioport.h> #include <linux/delay.h> #include <linux/workqueue.h> #include <linux/interrupt.h> #include <linux/platform_device.h> #include <linux/bitops.h> #include <asm/irq.h> #include <asm/io.h> #include <asm/system.h> #include <pcmcia/cs_types.h> #include <pcmcia/ss.h> #include <pcmcia/cs.h> #include <linux/isapnp.h> /* ISA-bus controllers */ #include "i82365.h" #include "cirrus.h" #include "vg468.h" #include "ricoh.h" static irqreturn_t i365_count_irq(int, void *); static inline int _check_irq(int irq, int flags) { if (request_irq(irq, i365_count_irq, flags, "x", i365_count_irq) != 0) return -1; free_irq(irq, i365_count_irq); return 0; } /*====================================================================*/ /* Parameters that can be set with 'insmod' */ /* Default base address for i82365sl and other ISA chips */ static unsigned long i365_base = 0x3e0; /* Should we probe at 0x3e2 for an extra ISA controller? */ static int extra_sockets = 0; /* Specify a socket number to ignore */ static int ignore = -1; /* Bit map or list of interrupts to choose from */ static u_int irq_mask = 0xffff; static int irq_list[16]; static unsigned int irq_list_count; /* The card status change interrupt -- 0 means autoselect */ static int cs_irq = 0; /* Probe for safe interrupts? */ static int do_scan = 1; /* Poll status interval -- 0 means default to interrupt */ static int poll_interval = 0; /* External clock time, in nanoseconds. 120 ns = 8.33 MHz */ static int cycle_time = 120; /* Cirrus options */ static int has_dma = -1; static int has_led = -1; static int has_ring = -1; static int dynamic_mode = 0; static int freq_bypass = -1; static int setup_time = -1; static int cmd_time = -1; static int recov_time = -1; /* Vadem options */ static int async_clock = -1; static int cable_mode = -1; static int wakeup = 0; module_param(i365_base, ulong, 0444); module_param(ignore, int, 0444); module_param(extra_sockets, int, 0444); module_param(irq_mask, int, 0444); module_param_array(irq_list, int, &irq_list_count, 0444); module_param(cs_irq, int, 0444); module_param(async_clock, int, 0444); module_param(cable_mode, int, 0444); module_param(wakeup, int, 0444); module_param(do_scan, int, 0444); module_param(poll_interval, int, 0444); module_param(cycle_time, int, 0444); module_param(has_dma, int, 0444); module_param(has_led, int, 0444); module_param(has_ring, int, 0444); module_param(dynamic_mode, int, 0444); module_param(freq_bypass, int, 0444); module_param(setup_time, int, 0444); module_param(cmd_time, int, 0444); module_param(recov_time, int, 0444); /*====================================================================*/ typedef struct cirrus_state_t { u_char misc1, misc2; u_char timer[6]; } cirrus_state_t; typedef struct vg46x_state_t { u_char ctl, ema; } vg46x_state_t; struct i82365_socket { u_short type, flags; struct pcmcia_socket socket; unsigned int number; unsigned int ioaddr; u_short psock; u_char cs_irq, intr; union { cirrus_state_t cirrus; vg46x_state_t vg46x; } state; }; /* Where we keep track of our sockets... */ static int sockets = 0; static struct i82365_socket socket[8] = { { 0, }, /* ... */ }; /* Default ISA interrupt mask */ #define I365_MASK 0xdeb8 /* irq 15,14,12,11,10,9,7,5,4,3 */ static int grab_irq; static DEFINE_SPINLOCK(isa_lock); #define ISA_LOCK(n, f) spin_lock_irqsave(&isa_lock, f) #define ISA_UNLOCK(n, f) spin_unlock_irqrestore(&isa_lock, f) static struct timer_list poll_timer; /*====================================================================*/ /* These definitions must match the pcic table! */ typedef enum pcic_id { IS_I82365A, IS_I82365B, IS_I82365DF, IS_IBM, IS_RF5Cx96, IS_VLSI, IS_VG468, IS_VG469, IS_PD6710, IS_PD672X, IS_VT83C469, } pcic_id; /* Flags for classifying groups of controllers */ #define IS_VADEM 0x0001 #define IS_CIRRUS 0x0002 #define IS_VIA 0x0010 #define IS_UNKNOWN 0x0400 #define IS_VG_PWR 0x0800 #define IS_DF_PWR 0x1000 #define IS_REGISTERED 0x2000 #define IS_ALIVE 0x8000 typedef struct pcic_t { char *name; u_short flags; } pcic_t; static pcic_t pcic[] = { { "Intel i82365sl A step", 0 }, { "Intel i82365sl B step", 0 }, { "Intel i82365sl DF", IS_DF_PWR }, { "IBM Clone", 0 }, { "Ricoh RF5C296/396", 0 }, { "VLSI 82C146", 0 }, { "Vadem VG-468", IS_VADEM }, { "Vadem VG-469", IS_VADEM|IS_VG_PWR }, { "Cirrus PD6710", IS_CIRRUS }, { "Cirrus PD672x", IS_CIRRUS }, { "VIA VT83C469", IS_CIRRUS|IS_VIA }, }; #define PCIC_COUNT (sizeof(pcic)/sizeof(pcic_t)) /*====================================================================*/ static DEFINE_SPINLOCK(bus_lock); static u_char i365_get(u_short sock, u_short reg) { unsigned long flags; spin_lock_irqsave(&bus_lock,flags); { unsigned int port = socket[sock].ioaddr; u_char val; reg = I365_REG(socket[sock].psock, reg); outb(reg, port); val = inb(port+1); spin_unlock_irqrestore(&bus_lock,flags); return val; } } static void i365_set(u_short sock, u_short reg, u_char data) { unsigned long flags; spin_lock_irqsave(&bus_lock,flags); { unsigned int port = socket[sock].ioaddr; u_char val = I365_REG(socket[sock].psock, reg); outb(val, port); outb(data, port+1); spin_unlock_irqrestore(&bus_lock,flags); } } static void i365_bset(u_short sock, u_short reg, u_char mask) { u_char d = i365_get(sock, reg); d |= mask; i365_set(sock, reg, d); } static void i365_bclr(u_short sock, u_short reg, u_char mask) { u_char d = i365_get(sock, reg); d &= ~mask; i365_set(sock, reg, d); } static void i365_bflip(u_short sock, u_short reg, u_char mask, int b) { u_char d = i365_get(sock, reg); if (b) d |= mask; else d &= ~mask; i365_set(sock, reg, d); } static u_short i365_get_pair(u_short sock, u_short reg) { u_short a, b; a = i365_get(sock, reg); b = i365_get(sock, reg+1); return (a + (b<<8)); } static void i365_set_pair(u_short sock, u_short reg, u_short data) { i365_set(sock, reg, data & 0xff); i365_set(sock, reg+1, data >> 8); } #define flip(v,b,f) (v = ((f)<0) ? v : ((f) ? ((v)|(b)) : ((v)&(~b)))) static void cirrus_get_state(u_short s) { int i; cirrus_state_t *p = &socket[s].state.cirrus; p->misc1 = i365_get(s, PD67_MISC_CTL_1); p->misc1 &= (PD67_MC1_MEDIA_ENA | PD67_MC1_INPACK_ENA); p->misc2 = i365_get(s, PD67_MISC_CTL_2); for (i = 0; i < 6; i++) p->timer[i] = i365_get(s, PD67_TIME_SETUP(0)+i); } static void cirrus_set_state(u_short s) { int i; u_char misc; cirrus_state_t *p = &socket[s].state.cirrus; misc = i365_get(s, PD67_MISC_CTL_2); i365_set(s, PD67_MISC_CTL_2, p->misc2); if (misc & PD67_MC2_SUSPEND) mdelay(50); misc = i365_get(s, PD67_MISC_CTL_1); misc &= ~(PD67_MC1_MEDIA_ENA | PD67_MC1_INPACK_ENA); i365_set(s, PD67_MISC_CTL_1, misc | p->misc1); for (i = 0; i < 6; i++) i365_set(s, PD67_TIME_SETUP(0)+i, p->timer[i]); } static u_int __init cirrus_set_opts(u_short s, char *buf) { struct i82365_socket *t = &socket[s]; cirrus_state_t *p = &socket[s].state.cirrus; u_int mask = 0xffff; if (has_ring == -1) has_ring = 1; flip(p->misc2, PD67_MC2_IRQ15_RI, has_ring); flip(p->misc2, PD67_MC2_DYNAMIC_MODE, dynamic_mode); flip(p->misc2, PD67_MC2_FREQ_BYPASS, freq_bypass); if (p->misc2 & PD67_MC2_IRQ15_RI) strcat(buf, " [ring]"); if (p->misc2 & PD67_MC2_DYNAMIC_MODE) strcat(buf, " [dyn mode]"); if (p->misc2 & PD67_MC2_FREQ_BYPASS) strcat(buf, " [freq bypass]"); if (p->misc1 & PD67_MC1_INPACK_ENA) strcat(buf, " [inpack]"); if (p->misc2 & PD67_MC2_IRQ15_RI) mask &= ~0x8000; if (has_led > 0) { strcat(buf, " [led]"); mask &= ~0x1000; } if (has_dma > 0) { strcat(buf, " [dma]"); mask &= ~0x0600; } if (!(t->flags & IS_VIA)) { if (setup_time >= 0) p->timer[0] = p->timer[3] = setup_time; if (cmd_time > 0) { p->timer[1] = cmd_time; p->timer[4] = cmd_time*2+4; } if (p->timer[1] == 0) { p->timer[1] = 6; p->timer[4] = 16; if (p->timer[0] == 0) p->timer[0] = p->timer[3] = 1; } if (recov_time >= 0) p->timer[2] = p->timer[5] = recov_time; buf += strlen(buf); sprintf(buf, " [%d/%d/%d] [%d/%d/%d]", p->timer[0], p->timer[1], p->timer[2], p->timer[3], p->timer[4], p->timer[5]); } return mask; } static void vg46x_get_state(u_short s) { vg46x_state_t *p = &socket[s].state.vg46x; p->ctl = i365_get(s, VG468_CTL); if (socket[s].type == IS_VG469) p->ema = i365_get(s, VG469_EXT_MODE); } static void vg46x_set_state(u_short s) { vg46x_state_t *p = &socket[s].state.vg46x; i365_set(s, VG468_CTL, p->ctl); if (socket[s].type == IS_VG469) i365_set(s, VG469_EXT_MODE, p->ema); } static u_int __init vg46x_set_opts(u_short s, char *buf) { vg46x_state_t *p = &socket[s].state.vg46x; flip(p->ctl, VG468_CTL_ASYNC, async_clock); flip(p->ema, VG469_MODE_CABLE, cable_mode); if (p->ctl & VG468_CTL_ASYNC) strcat(buf, " [async]"); if (p->ctl & VG468_CTL_INPACK) strcat(buf, " [inpack]"); if (socket[s].type == IS_VG469) { u_char vsel = i365_get(s, VG469_VSELECT); if (vsel & VG469_VSEL_EXT_STAT) { strcat(buf, " [ext mode]"); if (vsel & VG469_VSEL_EXT_BUS) strcat(buf, " [isa buf]"); } if (p->ema & VG469_MODE_CABLE) strcat(buf, " [cable]"); if (p->ema & VG469_MODE_COMPAT) strcat(buf, " [c step]"); } return 0xffff; } static void get_bridge_state(u_short s) { struct i82365_socket *t = &socket[s]; if (t->flags & IS_CIRRUS) cirrus_get_state(s); else if (t->flags & IS_VADEM) vg46x_get_state(s); } static void set_bridge_state(u_short s) { struct i82365_socket *t = &socket[s]; if (t->flags & IS_CIRRUS) cirrus_set_state(s); else { i365_set(s, I365_GBLCTL, 0x00); i365_set(s, I365_GENCTL, 0x00); } i365_bflip(s, I365_INTCTL, I365_INTR_ENA, t->intr); if (t->flags & IS_VADEM) vg46x_set_state(s); } static u_int __init set_bridge_opts(u_short s, u_short ns) { u_short i; u_int m = 0xffff; char buf[128]; for (i = s; i < s+ns; i++) { if (socket[i].flags & IS_ALIVE) { printk(KERN_INFO " host opts [%d]: already alive!\n", i); continue; } buf[0] = '\0'; get_bridge_state(i); if (socket[i].flags & IS_CIRRUS) m = cirrus_set_opts(i, buf); else if (socket[i].flags & IS_VADEM) m = vg46x_set_opts(i, buf); set_bridge_state(i); printk(KERN_INFO " host opts [%d]:%s\n", i, (*buf) ? buf : " none"); } return m; } static volatile u_int irq_hits; static u_short irq_sock; static irqreturn_t i365_count_irq(int irq, void *dev) { i365_get(irq_sock, I365_CSC); irq_hits++; pr_debug("i82365: -> hit on irq %d\n", irq); return IRQ_HANDLED; } static u_int __init test_irq(u_short sock, int irq) { pr_debug("i82365: testing ISA irq %d\n", irq); if (request_irq(irq, i365_count_irq, IRQF_PROBE_SHARED, "scan", i365_count_irq) != 0) return 1; irq_hits = 0; irq_sock = sock; msleep(10); if (irq_hits) { free_irq(irq, i365_count_irq); pr_debug("i82365: spurious hit!\n"); return 1; } /* Generate one interrupt */ i365_set(sock, I365_CSCINT, I365_CSC_DETECT | (irq << 4)); i365_bset(sock, I365_GENCTL, I365_CTL_SW_IRQ); udelay(1000); free_irq(irq, i365_count_irq); /* mask all interrupts */ i365_set(sock, I365_CSCINT, 0); pr_debug("i82365: hits = %d\n", irq_hits); return (irq_hits != 1); } static u_int __init isa_scan(u_short sock, u_int mask0) { u_int mask1 = 0; int i; #ifdef __alpha__ #define PIC 0x4d0 /* Don't probe level-triggered interrupts -- reserved for PCI */ mask0 &= ~(inb(PIC) | (inb(PIC+1) << 8)); #endif if (do_scan) { set_bridge_state(sock); i365_set(sock, I365_CSCINT, 0); for (i = 0; i < 16; i++) if ((mask0 & (1 << i)) && (test_irq(sock, i) == 0)) mask1 |= (1 << i); for (i = 0; i < 16; i++) if ((mask1 & (1 << i)) && (test_irq(sock, i) != 0)) mask1 ^= (1 << i); } printk(KERN_INFO " ISA irqs ("); if (mask1) { printk("scanned"); } else { /* Fallback: just find interrupts that aren't in use */ for (i = 0; i < 16; i++) if ((mask0 & (1 << i)) && (_check_irq(i, IRQF_PROBE_SHARED) == 0)) mask1 |= (1 << i); printk("default"); /* If scan failed, default to polled status */ if (!cs_irq && (poll_interval == 0)) poll_interval = HZ; } printk(") = "); for (i = 0; i < 16; i++) if (mask1 & (1<<i)) printk("%s%d", ((mask1 & ((1<<i)-1)) ? "," : ""), i); if (mask1 == 0) printk("none!"); return mask1; } /*====================================================================*/ /* Time conversion functions */ static int to_cycles(int ns) { return ns/cycle_time; } /*====================================================================*/ static int __init identify(unsigned int port, u_short sock) { u_char val; int type = -1; /* Use the next free entry in the socket table */ socket[sockets].ioaddr = port; socket[sockets].psock = sock; /* Wake up a sleepy Cirrus controller */ if (wakeup) { i365_bclr(sockets, PD67_MISC_CTL_2, PD67_MC2_SUSPEND); /* Pause at least 50 ms */ mdelay(50); } if ((val = i365_get(sockets, I365_IDENT)) & 0x70) return -1; switch (val) { case 0x82: type = IS_I82365A; break; case 0x83: type = IS_I82365B; break; case 0x84: type = IS_I82365DF; break; case 0x88: case 0x89: case 0x8a: type = IS_IBM; break; } /* Check for Vadem VG-468 chips */ outb(0x0e, port); outb(0x37, port); i365_bset(sockets, VG468_MISC, VG468_MISC_VADEMREV); val = i365_get(sockets, I365_IDENT); if (val & I365_IDENT_VADEM) { i365_bclr(sockets, VG468_MISC, VG468_MISC_VADEMREV); type = ((val & 7) >= 4) ? IS_VG469 : IS_VG468; } /* Check for Ricoh chips */ val = i365_get(sockets, RF5C_CHIP_ID); if ((val == RF5C_CHIP_RF5C296) || (val == RF5C_CHIP_RF5C396)) type = IS_RF5Cx96; /* Check for Cirrus CL-PD67xx chips */ i365_set(sockets, PD67_CHIP_INFO, 0); val = i365_get(sockets, PD67_CHIP_INFO); if ((val & PD67_INFO_CHIP_ID) == PD67_INFO_CHIP_ID) { val = i365_get(sockets, PD67_CHIP_INFO); if ((val & PD67_INFO_CHIP_ID) == 0) { type = (val & PD67_INFO_SLOTS) ? IS_PD672X : IS_PD6710; i365_set(sockets, PD67_EXT_INDEX, 0xe5); if (i365_get(sockets, PD67_EXT_INDEX) != 0xe5) type = IS_VT83C469; } } return type; } /* identify */ static int __init is_alive(u_short sock) { u_char stat; unsigned int start, stop; stat = i365_get(sock, I365_STATUS); start = i365_get_pair(sock, I365_IO(0)+I365_W_START); stop = i365_get_pair(sock, I365_IO(0)+I365_W_STOP); if ((stat & I365_CS_DETECT) && (stat & I365_CS_POWERON) && (i365_get(sock, I365_INTCTL) & I365_PC_IOCARD) && (i365_get(sock, I365_ADDRWIN) & I365_ENA_IO(0)) && ((start & 0xfeef) != 0x02e8)) { if (!request_region(start, stop-start+1, "i82365")) return 1; release_region(start, stop-start+1); } return 0; } /*====================================================================*/ static void __init add_socket(unsigned int port, int psock, int type) { socket[sockets].ioaddr = port; socket[sockets].psock = psock; socket[sockets].type = type; socket[sockets].flags = pcic[type].flags; if (is_alive(sockets)) socket[sockets].flags |= IS_ALIVE; sockets++; } static void __init add_pcic(int ns, int type) { u_int mask = 0, i, base; int isa_irq = 0; struct i82365_socket *t = &socket[sockets-ns]; base = sockets-ns; if (base == 0) printk("\n"); printk(KERN_INFO " %s", pcic[type].name); printk(" ISA-to-PCMCIA at port %#x ofs 0x%02x", t->ioaddr, t->psock*0x40); printk(", %d socket%s\n", ns, ((ns > 1) ? "s" : "")); /* Set host options, build basic interrupt mask */ if (irq_list_count == 0) mask = irq_mask; else for (i = mask = 0; i < irq_list_count; i++) mask |= (1<<irq_list[i]); mask &= I365_MASK & set_bridge_opts(base, ns); /* Scan for ISA interrupts */ mask = isa_scan(base, mask); /* Poll if only two interrupts available */ if (!poll_interval) { u_int tmp = (mask & 0xff20); tmp = tmp & (tmp-1); if ((tmp & (tmp-1)) == 0) poll_interval = HZ; } /* Only try an ISA cs_irq if this is the first controller */ if (!grab_irq && (cs_irq || !poll_interval)) { /* Avoid irq 12 unless it is explicitly requested */ u_int cs_mask = mask & ((cs_irq) ? (1<<cs_irq) : ~(1<<12)); for (cs_irq = 15; cs_irq > 0; cs_irq--) if ((cs_mask & (1 << cs_irq)) && (_check_irq(cs_irq, IRQF_PROBE_SHARED) == 0)) break; if (cs_irq) { grab_irq = 1; isa_irq = cs_irq; printk(" status change on irq %d\n", cs_irq); } } if (!isa_irq) { if (poll_interval == 0) poll_interval = HZ; printk(" polling interval = %d ms\n", poll_interval * 1000 / HZ); } /* Update socket interrupt information, capabilities */ for (i = 0; i < ns; i++) { t[i].socket.features |= SS_CAP_PCCARD; t[i].socket.map_size = 0x1000; t[i].socket.irq_mask = mask; t[i].cs_irq = isa_irq; } } /* add_pcic */ /*====================================================================*/ #ifdef CONFIG_PNP static struct isapnp_device_id id_table[] __initdata = { { ISAPNP_ANY_ID, ISAPNP_ANY_ID, ISAPNP_VENDOR('P', 'N', 'P'), ISAPNP_FUNCTION(0x0e00), (unsigned long) "Intel 82365-Compatible" }, { ISAPNP_ANY_ID, ISAPNP_ANY_ID, ISAPNP_VENDOR('P', 'N', 'P'), ISAPNP_FUNCTION(0x0e01), (unsigned long) "Cirrus Logic CL-PD6720" }, { ISAPNP_ANY_ID, ISAPNP_ANY_ID, ISAPNP_VENDOR('P', 'N', 'P'), ISAPNP_FUNCTION(0x0e02), (unsigned long) "VLSI VL82C146" }, { 0 } }; MODULE_DEVICE_TABLE(isapnp, id_table); static struct pnp_dev *i82365_pnpdev; #endif static void __init isa_probe(void) { int i, j, sock, k, ns, id; unsigned int port; #ifdef CONFIG_PNP struct isapnp_device_id *devid; struct pnp_dev *dev; for (devid = id_table; devid->vendor; devid++) { if ((dev = pnp_find_dev(NULL, devid->vendor, devid->function, NULL))) { if (pnp_device_attach(dev) < 0) continue; if (pnp_activate_dev(dev) < 0) { printk("activate failed\n"); pnp_device_detach(dev); break; } if (!pnp_port_valid(dev, 0)) { printk("invalid resources ?\n"); pnp_device_detach(dev); break; } i365_base = pnp_port_start(dev, 0); i82365_pnpdev = dev; break; } } #endif if (!request_region(i365_base, 2, "i82365")) { if (sockets == 0) printk("port conflict at %#lx\n", i365_base); return; } id = identify(i365_base, 0); if ((id == IS_I82365DF) && (identify(i365_base, 1) != id)) { for (i = 0; i < 4; i++) { if (i == ignore) continue; port = i365_base + ((i & 1) << 2) + ((i & 2) << 1); sock = (i & 1) << 1; if (identify(port, sock) == IS_I82365DF) { add_socket(port, sock, IS_VLSI); add_pcic(1, IS_VLSI); } } } else { for (i = 0; i < 8; i += 2) { if (sockets && !extra_sockets && (i == 4)) break; port = i365_base + 2*(i>>2); sock = (i & 3); id = identify(port, sock); if (id < 0) continue; for (j = ns = 0; j < 2; j++) { /* Does the socket exist? */ if ((ignore == i+j) || (identify(port, sock+j) < 0)) continue; /* Check for bad socket decode */ for (k = 0; k <= sockets; k++) i365_set(k, I365_MEM(0)+I365_W_OFF, k); for (k = 0; k <= sockets; k++) if (i365_get(k, I365_MEM(0)+I365_W_OFF) != k) break; if (k <= sockets) break; add_socket(port, sock+j, id); ns++; } if (ns != 0) add_pcic(ns, id); } } } /*====================================================================*/ static irqreturn_t pcic_interrupt(int irq, void *dev) { int i, j, csc; u_int events, active; u_long flags = 0; int handled = 0; pr_debug("pcic_interrupt(%d)\n", irq); for (j = 0; j < 20; j++) { active = 0; for (i = 0; i < sockets; i++) { if (socket[i].cs_irq != irq) continue; handled = 1; ISA_LOCK(i, flags); csc = i365_get(i, I365_CSC); if ((csc == 0) || (i365_get(i, I365_IDENT) & 0x70)) { ISA_UNLOCK(i, flags); continue; } events = (csc & I365_CSC_DETECT) ? SS_DETECT : 0; if (i365_get(i, I365_INTCTL) & I365_PC_IOCARD) events |= (csc & I365_CSC_STSCHG) ? SS_STSCHG : 0; else { events |= (csc & I365_CSC_BVD1) ? SS_BATDEAD : 0; events |= (csc & I365_CSC_BVD2) ? SS_BATWARN : 0; events |= (csc & I365_CSC_READY) ? SS_READY : 0; } ISA_UNLOCK(i, flags); pr_debug("socket %d event 0x%02x\n", i, events); if (events) pcmcia_parse_events(&socket[i].socket, events); active |= events; } if (!active) break; } if (j == 20) printk(KERN_NOTICE "i82365: infinite loop in interrupt handler\n"); pr_debug("pcic_interrupt done\n"); return IRQ_RETVAL(handled); } /* pcic_interrupt */ static void pcic_interrupt_wrapper(u_long data) { pcic_interrupt(0, NULL); poll_timer.expires = jiffies + poll_interval; add_timer(&poll_timer); } /*====================================================================*/ static int i365_get_status(u_short sock, u_int *value) { u_int status; status = i365_get(sock, I365_STATUS); *value = ((status & I365_CS_DETECT) == I365_CS_DETECT) ? SS_DETECT : 0; if (i365_get(sock, I365_INTCTL) & I365_PC_IOCARD) *value |= (status & I365_CS_STSCHG) ? 0 : SS_STSCHG; else { *value |= (status & I365_CS_BVD1) ? 0 : SS_BATDEAD; *value |= (status & I365_CS_BVD2) ? 0 : SS_BATWARN; } *value |= (status & I365_CS_WRPROT) ? SS_WRPROT : 0; *value |= (status & I365_CS_READY) ? SS_READY : 0; *value |= (status & I365_CS_POWERON) ? SS_POWERON : 0; if (socket[sock].type == IS_VG469) { status = i365_get(sock, VG469_VSENSE); if (socket[sock].psock & 1) { *value |= (status & VG469_VSENSE_B_VS1) ? 0 : SS_3VCARD; *value |= (status & VG469_VSENSE_B_VS2) ? 0 : SS_XVCARD; } else { *value |= (status & VG469_VSENSE_A_VS1) ? 0 : SS_3VCARD; *value |= (status & VG469_VSENSE_A_VS2) ? 0 : SS_XVCARD; } } pr_debug("GetStatus(%d) = %#4.4x\n", sock, *value); return 0; } /* i365_get_status */ /*====================================================================*/ static int i365_set_socket(u_short sock, socket_state_t *state) { struct i82365_socket *t = &socket[sock]; u_char reg; pr_debug("SetSocket(%d, flags %#3.3x, Vcc %d, Vpp %d, " "io_irq %d, csc_mask %#2.2x)\n", sock, state->flags, state->Vcc, state->Vpp, state->io_irq, state->csc_mask); /* First set global controller options */ set_bridge_state(sock); /* IO card, RESET flag, IO interrupt */ reg = t->intr; reg |= state->io_irq; reg |= (state->flags & SS_RESET) ? 0 : I365_PC_RESET; reg |= (state->flags & SS_IOCARD) ? I365_PC_IOCARD : 0; i365_set(sock, I365_INTCTL, reg); reg = I365_PWR_NORESET; if (state->flags & SS_PWR_AUTO) reg |= I365_PWR_AUTO; if (state->flags & SS_OUTPUT_ENA) reg |= I365_PWR_OUT; if (t->flags & IS_CIRRUS) { if (state->Vpp != 0) { if (state->Vpp == 120) reg |= I365_VPP1_12V; else if (state->Vpp == state->Vcc) reg |= I365_VPP1_5V; else return -EINVAL; } if (state->Vcc != 0) { reg |= I365_VCC_5V; if (state->Vcc == 33) i365_bset(sock, PD67_MISC_CTL_1, PD67_MC1_VCC_3V); else if (state->Vcc == 50) i365_bclr(sock, PD67_MISC_CTL_1, PD67_MC1_VCC_3V); else return -EINVAL; } } else if (t->flags & IS_VG_PWR) { if (state->Vpp != 0) { if (state->Vpp == 120) reg |= I365_VPP1_12V; else if (state->Vpp == state->Vcc) reg |= I365_VPP1_5V; else return -EINVAL; } if (state->Vcc != 0) { reg |= I365_VCC_5V; if (state->Vcc == 33) i365_bset(sock, VG469_VSELECT, VG469_VSEL_VCC); else if (state->Vcc == 50) i365_bclr(sock, VG469_VSELECT, VG469_VSEL_VCC); else return -EINVAL; } } else if (t->flags & IS_DF_PWR) { switch (state->Vcc) { case 0: break; case 33: reg |= I365_VCC_3V; break; case 50: reg |= I365_VCC_5V; break; default: return -EINVAL; } switch (state->Vpp) { case 0: break; case 50: reg |= I365_VPP1_5V; break; case 120: reg |= I365_VPP1_12V; break; default: return -EINVAL; } } else { switch (state->Vcc) { case 0: break; case 50: reg |= I365_VCC_5V; break; default: return -EINVAL; } switch (state->Vpp) { case 0: break; case 50: reg |= I365_VPP1_5V | I365_VPP2_5V; break; case 120: reg |= I365_VPP1_12V | I365_VPP2_12V; break; default: return -EINVAL; } } if (reg != i365_get(sock, I365_POWER)) i365_set(sock, I365_POWER, reg); /* Chipset-specific functions */ if (t->flags & IS_CIRRUS) { /* Speaker control */ i365_bflip(sock, PD67_MISC_CTL_1, PD67_MC1_SPKR_ENA, state->flags & SS_SPKR_ENA); } /* Card status change interrupt mask */ reg = t->cs_irq << 4; if (state->csc_mask & SS_DETECT) reg |= I365_CSC_DETECT; if (state->flags & SS_IOCARD) { if (state->csc_mask & SS_STSCHG) reg |= I365_CSC_STSCHG; } else { if (state->csc_mask & SS_BATDEAD) reg |= I365_CSC_BVD1; if (state->csc_mask & SS_BATWARN) reg |= I365_CSC_BVD2; if (state->csc_mask & SS_READY) reg |= I365_CSC_READY; } i365_set(sock, I365_CSCINT, reg); i365_get(sock, I365_CSC); return 0; } /* i365_set_socket */ /*====================================================================*/ static int i365_set_io_map(u_short sock, struct pccard_io_map *io) { u_char map, ioctl; pr_debug("SetIOMap(%d, %d, %#2.2x, %d ns, " "%#llx-%#llx)\n", sock, io->map, io->flags, io->speed, (unsigned long long)io->start, (unsigned long long)io->stop); map = io->map; if ((map > 1) || (io->start > 0xffff) || (io->stop > 0xffff) || (io->stop < io->start)) return -EINVAL; /* Turn off the window before changing anything */ if (i365_get(sock, I365_ADDRWIN) & I365_ENA_IO(map)) i365_bclr(sock, I365_ADDRWIN, I365_ENA_IO(map)); i365_set_pair(sock, I365_IO(map)+I365_W_START, io->start); i365_set_pair(sock, I365_IO(map)+I365_W_STOP, io->stop); ioctl = i365_get(sock, I365_IOCTL) & ~I365_IOCTL_MASK(map); if (io->speed) ioctl |= I365_IOCTL_WAIT(map); if (io->flags & MAP_0WS) ioctl |= I365_IOCTL_0WS(map); if (io->flags & MAP_16BIT) ioctl |= I365_IOCTL_16BIT(map); if (io->flags & MAP_AUTOSZ) ioctl |= I365_IOCTL_IOCS16(map); i365_set(sock, I365_IOCTL, ioctl); /* Turn on the window if necessary */ if (io->flags & MAP_ACTIVE) i365_bset(sock, I365_ADDRWIN, I365_ENA_IO(map)); return 0; } /* i365_set_io_map */ /*====================================================================*/ static int i365_set_mem_map(u_short sock, struct pccard_mem_map *mem) { u_short base, i; u_char map; pr_debug("SetMemMap(%d, %d, %#2.2x, %d ns, %#llx-%#llx, " "%#x)\n", sock, mem->map, mem->flags, mem->speed, (unsigned long long)mem->res->start, (unsigned long long)mem->res->end, mem->card_start); map = mem->map; if ((map > 4) || (mem->card_start > 0x3ffffff) || (mem->res->start > mem->res->end) || (mem->speed > 1000)) return -EINVAL; if ((mem->res->start > 0xffffff) || (mem->res->end > 0xffffff)) return -EINVAL; /* Turn off the window before changing anything */ if (i365_get(sock, I365_ADDRWIN) & I365_ENA_MEM(map)) i365_bclr(sock, I365_ADDRWIN, I365_ENA_MEM(map)); base = I365_MEM(map); i = (mem->res->start >> 12) & 0x0fff; if (mem->flags & MAP_16BIT) i |= I365_MEM_16BIT; if (mem->flags & MAP_0WS) i |= I365_MEM_0WS; i365_set_pair(sock, base+I365_W_START, i); i = (mem->res->end >> 12) & 0x0fff; switch (to_cycles(mem->speed)) { case 0: break; case 1: i |= I365_MEM_WS0; break; case 2: i |= I365_MEM_WS1; break; default: i |= I365_MEM_WS1 | I365_MEM_WS0; break; } i365_set_pair(sock, base+I365_W_STOP, i); i = ((mem->card_start - mem->res->start) >> 12) & 0x3fff; if (mem->flags & MAP_WRPROT) i |= I365_MEM_WRPROT; if (mem->flags & MAP_ATTRIB) i |= I365_MEM_REG; i365_set_pair(sock, base+I365_W_OFF, i); /* Turn on the window if necessary */ if (mem->flags & MAP_ACTIVE) i365_bset(sock, I365_ADDRWIN, I365_ENA_MEM(map)); return 0; } /* i365_set_mem_map */ #if 0 /* driver model ordering issue */ static ssize_t show_info(struct class_device *class_dev, char *buf) { struct i82365_socket *s = container_of(class_dev, struct i82365_socket, socket.dev); return sprintf(buf, "type: %s\npsock: %d\n", pcic[s->type].name, s->psock); } static ssize_t show_exca(struct class_device *class_dev, char *buf) { struct i82365_socket *s = container_of(class_dev, struct i82365_socket, socket.dev); unsigned short sock; int i; ssize_t ret = 0; unsigned long flags = 0; sock = s->number; ISA_LOCK(sock, flags); for (i = 0; i < 0x40; i += 4) { ret += sprintf(buf, "%02x %02x %02x %02x%s", i365_get(sock,i), i365_get(sock,i+1), i365_get(sock,i+2), i365_get(sock,i+3), ((i % 16) == 12) ? "\n" : " "); buf += ret; } ISA_UNLOCK(sock, flags); return ret; } static CLASS_DEVICE_ATTR(exca, S_IRUGO, show_exca, NULL); static CLASS_DEVICE_ATTR(info, S_IRUGO, show_info, NULL); #endif /*====================================================================*/ #define LOCKED(x) do { \ int retval; \ unsigned long flags; \ spin_lock_irqsave(&isa_lock, flags); \ retval = x; \ spin_unlock_irqrestore(&isa_lock, flags); \ return retval; \ } while (0) static int pcic_get_status(struct pcmcia_socket *s, u_int *value) { unsigned int sock = container_of(s, struct i82365_socket, socket)->number; if (socket[sock].flags & IS_ALIVE) { *value = 0; return -EINVAL; } LOCKED(i365_get_status(sock, value)); } static int pcic_set_socket(struct pcmcia_socket *s, socket_state_t *state) { unsigned int sock = container_of(s, struct i82365_socket, socket)->number; if (socket[sock].flags & IS_ALIVE) return -EINVAL; LOCKED(i365_set_socket(sock, state)); } static int pcic_set_io_map(struct pcmcia_socket *s, struct pccard_io_map *io) { unsigned int sock = container_of(s, struct i82365_socket, socket)->number; if (socket[sock].flags & IS_ALIVE) return -EINVAL; LOCKED(i365_set_io_map(sock, io)); } static int pcic_set_mem_map(struct pcmcia_socket *s, struct pccard_mem_map *mem) { unsigned int sock = container_of(s, struct i82365_socket, socket)->number; if (socket[sock].flags & IS_ALIVE) return -EINVAL; LOCKED(i365_set_mem_map(sock, mem)); } static int pcic_init(struct pcmcia_socket *s) { int i; struct resource res = { .start = 0, .end = 0x1000 }; pccard_io_map io = { 0, 0, 0, 0, 1 }; pccard_mem_map mem = { .res = &res, }; for (i = 0; i < 2; i++) { io.map = i; pcic_set_io_map(s, &io); } for (i = 0; i < 5; i++) { mem.map = i; pcic_set_mem_map(s, &mem); } return 0; } static struct pccard_operations pcic_operations = { .init = pcic_init, .get_status = pcic_get_status, .set_socket = pcic_set_socket, .set_io_map = pcic_set_io_map, .set_mem_map = pcic_set_mem_map, }; /*====================================================================*/ static struct platform_driver i82365_driver = { .driver = { .name = "i82365", .owner = THIS_MODULE, }, }; static struct platform_device *i82365_device; static int __init init_i82365(void) { int i, ret; ret = platform_driver_register(&i82365_driver); if (ret) goto err_out; i82365_device = platform_device_alloc("i82365", 0); if (i82365_device) { ret = platform_device_add(i82365_device); if (ret) platform_device_put(i82365_device); } else ret = -ENOMEM; if (ret) goto err_driver_unregister; printk(KERN_INFO "Intel ISA PCIC probe: "); sockets = 0; isa_probe(); if (sockets == 0) { printk("not found.\n"); ret = -ENODEV; goto err_dev_unregister; } /* Set up interrupt handler(s) */ if (grab_irq != 0) ret = request_irq(cs_irq, pcic_interrupt, 0, "i82365", pcic_interrupt); if (ret) goto err_socket_release; /* register sockets with the pcmcia core */ for (i = 0; i < sockets; i++) { socket[i].socket.dev.parent = &i82365_device->dev; socket[i].socket.ops = &pcic_operations; socket[i].socket.resource_ops = &pccard_nonstatic_ops; socket[i].socket.owner = THIS_MODULE; socket[i].number = i; ret = pcmcia_register_socket(&socket[i].socket); if (!ret) socket[i].flags |= IS_REGISTERED; #if 0 /* driver model ordering issue */ class_device_create_file(&socket[i].socket.dev, &class_device_attr_info); class_device_create_file(&socket[i].socket.dev, &class_device_attr_exca); #endif } /* Finally, schedule a polling interrupt */ if (poll_interval != 0) { poll_timer.function = pcic_interrupt_wrapper; poll_timer.data = 0; init_timer(&poll_timer); poll_timer.expires = jiffies + poll_interval; add_timer(&poll_timer); } return 0; err_socket_release: for (i = 0; i < sockets; i++) { /* Turn off all interrupt sources! */ i365_set(i, I365_CSCINT, 0); release_region(socket[i].ioaddr, 2); } err_dev_unregister: platform_device_unregister(i82365_device); release_region(i365_base, 2); #ifdef CONFIG_PNP if (i82365_pnpdev) pnp_disable_dev(i82365_pnpdev); #endif err_driver_unregister: platform_driver_unregister(&i82365_driver); err_out: return ret; } /* init_i82365 */ static void __exit exit_i82365(void) { int i; for (i = 0; i < sockets; i++) { if (socket[i].flags & IS_REGISTERED) pcmcia_unregister_socket(&socket[i].socket); } platform_device_unregister(i82365_device); if (poll_interval != 0) del_timer_sync(&poll_timer); if (grab_irq != 0) free_irq(cs_irq, pcic_interrupt); for (i = 0; i < sockets; i++) { /* Turn off all interrupt sources! */ i365_set(i, I365_CSCINT, 0); release_region(socket[i].ioaddr, 2); } release_region(i365_base, 2); #ifdef CONFIG_PNP if (i82365_pnpdev) pnp_disable_dev(i82365_pnpdev); #endif platform_driver_unregister(&i82365_driver); } /* exit_i82365 */ module_init(init_i82365); module_exit(exit_i82365); MODULE_LICENSE("Dual MPL/GPL"); /*====================================================================*/
luckasfb/OT_903D-kernel-2.6.35.7
kernel/drivers/pcmcia/i82365.c
C
gpl-2.0
34,930
/* * Copyright 2000-2015 Rochus Keller <mailto:rkeller@nmr.ch> * * This file is part of the CARA (Computer Aided Resonance Assignment, * see <http://cara.nmr.ch/>) NMR Application Framework (NAF) library. * * The following is the license that applies to this copy of the * library. For a license to use the library under conditions * other than those described here, please email to rkeller@nmr.ch. * * GNU General Public License Usage * This file may be used under the terms of the GNU General Public * License (GPL) versions 2.0 or 3.0 as published by the Free Software * Foundation and appearing in the file LICENSE.GPL included in * the packaging of this file. Please review the following information * to ensure GNU General Public Licensing requirements will be met: * http://www.fsf.org/licensing/licenses/info/GPLv2.html and * http://www.gnu.org/copyleft/gpl.html. */ #include "Residue.h" #include "Project.h" #include <Root/Vector.h> #include <Spec/SequenceFile.h> #include <stdio.h> #include <qstring.h> // formatLabel using namespace Spec; Residue::Residue(Root::Index id, ResidueType* t, Root::Index nr ): d_type( t ), d_id( id ), d_ss( 0 ), d_pred( 0 ), d_succ( 0 ), d_nr( nr ), d_owner(0) { assert( t ); } Residue::Residue(Root::Index id, ResidueType* t ): d_type( t ), d_id( id ), d_ss( 0 ), d_pred( 0 ), d_succ( 0 ), d_nr( id ), d_owner( 0 ) { assert( t ); } Residue::Residue(const Residue & r): d_type( r.d_type ), d_id( r.d_id ), d_ss( 0 ), d_pred( 0 ), d_succ( 0 ), d_nr( r.d_nr ), d_chain( r.d_chain ), d_owner( r.d_owner ) { copyDynValuesFrom( &r ); d_params = r.d_params; } Residue::~Residue() { } DisPar Residue::getDisPar(Root::SymbolString s) const { Parameters::const_iterator p = d_params.find( s ); if( p != d_params.end() ) return (*p).second; else return d_type->getDisPar( s ); } Sequence::Sequence(SequenceFile* s): d_owner(0) { if( s != 0 ) { SequenceFile::Slots::const_iterator p; for( p = s->getSlots().begin(); p != s->getSlots().end(); ++p ) { d_resi[ (*p).first ] = (*p).second.d_resi; (*p).second.d_resi->d_owner = this; } } reindex(); } Residue* Sequence::getPred(Residue * resi) const { if( resi == 0 ) return 0; ResidueMap::const_iterator pos = d_resi.find( resi->getId() ); if( pos == d_resi.end() || pos == d_resi.begin() ) return 0; --pos; return (*pos).second; } Residue* Sequence::getSucc(Residue * resi) const { if( resi == 0 ) return 0; ResidueMap::const_iterator pos = d_resi.find( resi->getId() ); if( pos == d_resi.end() ) return 0; ++pos; if( pos == d_resi.end() ) return 0; else return (*pos).second; } bool Sequence::fillString(Residue* resi, ResidueString & str, int left, int right) const { assert( resi ); Root::Deque<Residue*> temp; temp.push_back( resi ); ResidueMap::const_iterator l = d_resi.find( resi->getId() ); if( l == d_resi.end() ) return false; ResidueMap::const_iterator r = l; // left == -1 bedeutet unendlich while( ( left == -1 || left > 0 ) && l != d_resi.begin() ) { --l; temp.push_front( (*l).second ); if( left != -1 ) left--; } if( left != -1 && left > 0 ) return false; // Es gibt nach links nicht die geforderte Zahl Residuen ++r; while( ( right == -1 || right > 0 ) && r != d_resi.end() ) { temp.push_back( (*r).second ); if( right != -1 ) right--; ++r; } if( right != -1 && right > 0 ) return false; // Es gibt nach rechts nicht die geforderte Zahl Residuen str.assign( temp.size(), 0 ); for( int j = 0; j < temp.size(); j++ ) str[ j ] = temp[ j ]; reindex(); return true; } Residue* Sequence::getResidue(Root::Index i) const { ResidueMap::const_iterator p = d_resi.find( i ); if( p == d_resi.end() ) return 0; else return (*p).second; } void Sequence::reindex() const { ResidueMap::const_iterator p; Residue* last = 0; Residue* cur = 0; for( p = d_resi.begin(); p != d_resi.end(); ++p ) { cur = (*p).second; cur->d_pred = last; if( last ) last->d_succ = cur; last = cur; } } Root::SymbolSet Residue::getAllDisPar() const { Root::SymbolSet res = d_type->getAllDisPar(); Parameters::const_iterator p; for( p = d_params.begin(); p != d_params.end(); ++p ) { if( (*p).second.isValid() ) res.insert( (*p).first ); } return res; } void Sequence::setDisPar(Residue * r, Root::SymbolString sym, DisPar val) { assert( r ); r->d_params[ sym ] = val; Residue::Changed m( r, Residue::SetParam, sym ); d_owner->notifyObservers( m ); } bool Sequence::removeDisPar(Residue* r, Root::SymbolString sym) { if( r->d_params.count( sym ) == 0 ) return false; r->d_params.erase( sym ); Residue::Changed m( r, Residue::RemoveParam, sym ); d_owner->notifyObservers( m ); return true; } QByteArray Residue::getInstanceName(bool sort) const { QString str; if( sort ) str.sprintf( "%09d", getId() ); else { if( !d_chain.isNull() ) str.sprintf( "%d %s:%d %s", getId(), d_chain.data(), getNr(), getType()->getShort().data() ); else str.sprintf( "%d %s%d", getId(), getType()->getShort().data(), getNr() ); } return str.toLatin1(); } Sequence::Sequence(const Sequence & seq):Resource(seq), d_owner( 0 ) { ResidueMap::const_iterator p; Residue* resi; for( p = seq.d_resi.begin(); p != seq.d_resi.end(); ++p ) { resi = new Residue( *(*p).second ); resi->d_owner = this; d_resi[ (*p).first ] = resi; } reindex(); } void Sequence::setNr(Residue * r, Root::Index nr) { assert( r ); r->d_nr = nr; Residue::Changed m( r, Residue::Nr ); d_owner->notifyObservers( m ); } void Sequence::setChain(Residue * r, Root::SymbolString s) { assert( r ); r->d_chain = s; Residue::Changed m( r, Residue::Chain ); d_owner->notifyObservers( m ); } void Sequence::addChain(SequenceFile * sf, Root::SymbolString c) { assert( sf ); SequenceFile::Slots::const_iterator p; for( p = sf->getSlots().begin(); p != sf->getSlots().end(); ++p ) { if( d_resi.count( (*p).first ) != 0 ) throw Root::Exception( "At least one residue id is not unique!" ); if( (*p).second.d_resi->getChain() == c ) throw Root::Exception( "Chain already exists!" ); } for( p = sf->getSlots().begin(); p != sf->getSlots().end(); ++p ) { d_resi[ (*p).first ] = (*p).second.d_resi; (*p).second.d_resi->d_owner = this; (*p).second.d_resi->d_chain = c; Residue::Added m( (*p).second.d_resi ); d_owner->notifyObservers( m ); } reindex(); } Root::Index Sequence::getNextId() const { if( d_resi.empty() ) return 1; ResidueMap::const_iterator i = d_resi.end(); i--; return (*i).first + 1; } void Residue::formatLabel( const Residue* r, char* buf, int len) { Q_ASSERT( r != 0 ); if( r->getChain().isNull() ) qsnprintf( buf, len, "%s%d", r->getType()->getLetter().data(), r->getNr() ); else // ::sprintf( buf, "%s:%s%d", r->getChain().data(), r->getType()->getLetter().data(), r->getNr() ); qsnprintf( buf, len, "%s:%s%d", r->getChain().data(), r->getType()->getLetter().data(), r->getNr() ); } Residue* Sequence::findResidue(Root::SymbolString chain, Root::Index nr) const { ResidueMap::const_iterator p; Residue* cur = 0; for( p = d_resi.begin(); p != d_resi.end(); ++p ) { cur = (*p).second; if( cur->getChain() == chain && cur->getNr() == nr ) return cur; } return 0; } Sequence::~Sequence() { } bool Sequence::removeResi(Residue * r) { assert( r ); if( r->getSystem() ) return false; Root::Ref<Residue> tmp = r; d_resi.erase( r->getId() ); reindex(); Residue::Removed m(r); d_owner->notifyObservers( m ); return true; } bool Sequence::removeChain(Root::SymbolString chain) { ResidueMap::const_iterator p; Residue* cur = 0; ResidueMap tmp; for( p = d_resi.begin(); p != d_resi.end(); ++p ) { cur = (*p).second; if( cur->getChain() == chain && cur->getSystem() ) return false; if( cur->getChain() == chain ) tmp[ cur->getId() ] = cur; } for( p = tmp.begin(); p != tmp.end(); ++p ) { cur = (*p).second; Root::Ref<Residue> tmp = cur; d_resi.erase( cur->getId() ); Residue::Removed m( cur ); d_owner->notifyObservers( m ); } reindex(); return true; } void Sequence::addResidue(Residue * r ) { Root::SymbolString chain; Root::Index nr = 1; if( !d_resi.empty() ) { ResidueMap::const_iterator p1 = d_resi.end(); --p1; nr = (*p1).second->d_nr + 1; chain = (*p1).second->d_chain; } addResidue( r, chain, nr ); } void Sequence::addResidue(Residue * r, Root::SymbolString chain ) { Root::Index nr = 1; if( !d_resi.empty() ) { ResidueMap::const_iterator p1 = d_resi.end(); --p1; if( (*p1).second->d_chain == chain ) nr = (*p1).second->d_nr + 1; } addResidue( r, chain, nr ); } void Sequence::addResidue(Residue * r, Root::SymbolString chain, Root::Index nr) { assert( r ); r->d_id = 1; if( !d_resi.empty() ) { ResidueMap::const_iterator p1 = d_resi.end(); --p1; r->d_id = (*p1).first + 1; if( (*p1).second->d_chain != chain ) { for( p1 = d_resi.begin(); p1 != d_resi.end(); ++p1 ) { if( (*p1).second->d_chain == chain ) throw Root::Exception( "Chain already exists!" ); } } } d_resi[ r->d_id ] = r; r->d_owner = this; r->d_chain = chain; r->d_nr = nr; reindex(); Residue::Added m( r ); d_owner->notifyObservers( m ); }
rochus-keller/NAF
Spec/Residue.cpp
C++
gpl-2.0
9,229
<?php /*************************************************************************** * Copyright (C) 2003-2018 Polytechnique.org * * http://opensource.polytechnique.org/ * * * * 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, write to the Free Software * * Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ***************************************************************************/ class Group { const CAT_GROUPESX = "GroupesX"; const CAT_BINETS = "Binets"; const CAT_PROMOTIONS = "Promotions"; const CAT_INSTITUTIONS = "Institutions"; public $id; public $shortname; private $data = array(); private function __construct(array $data) { foreach ($data as $key=>$value) { $this->data[$key] = $value; } $this->id = intval($this->data['id']); $this->shortname = $this->data['diminutif']; if (!is_null($this->axDate)) { $this->axDate = format_datetime($this->axDate, '%d/%m/%Y'); } } public function __get($name) { if (property_exists($this, $name)) { return $this->$name; } if (isset($this->data[$name])) { return $this->data[$name]; } return null; } public function __isset($name) { return property_exists($this, $name) || isset($this->data[$name]); } private function getUF($admin = false, $extra_cond = null, $sort = null) { $cond = new PFC_And(new UFC_Group($this->id, $admin), new PFC_Not(new UFC_Dead())); if (!is_null($extra_cond)) { $cond->addChild($extra_cond); } if ($this->cat == self::CAT_PROMOTIONS) { $cond->addChild(new UFC_Registered()); } return new UserFilter($cond, $sort); } public function getMembersFilter($extra_cond = null, $sort = null) { return $this->getUF(false, $extra_cond, $sort); } public function getAdminsFilter($extra_cond = null, $sort = null) { return $this->getUF(true, $extra_cond, $sort); } public function iterMembers($extra_cond = null, $sort = null, $limit = null) { $uf = $this->getMembersFilter($extra_cond, $sort); return $uf->iterUsers($limit); } public function iterAdmins($extra_cond = null, $sort = null, $limit = null) { $uf = $this->getAdminsFilter($extra_cond, $sort); return $uf->iterUsers($limit); } public function iterToNotify() { if ($this->data['notify_all']) { $condition = UFC_Group::BOTH; } else { $condition = UFC_Group::NOTIFIED; } $uf = New UserFilter(New UFC_Group($this->id, true, $condition)); return $uf->iterUsers(); } public function getLogo($fallback = true) { if (!empty($this->logo)) { return PlImage::fromData($this->logo, $this->logo_mime); } else if ($fallback) { return PlImage::fromFile(dirname(__FILE__).'/../htdocs/images/dflt_carre.jpg', 'image/jpeg'); } return null; } static public function get($id, $can_be_shortname = true) { if (!$id) { return null; } if (!$can_be_shortname) { $where = XDB::format('a.id = {?}', $id); } else { $where = XDB::format('a.diminutif = {?}', $id); } $res = XDB::query('SELECT a.*, d.nom AS domnom, FIND_IN_SET(\'wiki_desc\', a.flags) AS wiki_desc, FIND_IN_SET(\'notif_unsub\', a.flags) AS notif_unsub, FIND_IN_SET(\'notify_all\', a.flags) AS notify_all, (nls.id IS NOT NULL) AS has_nl, ad.text AS address, p.display_tel AS phone, f.display_tel AS fax FROM groups AS a LEFT JOIN group_dom AS d ON d.id = a.dom LEFT JOIN newsletters AS nls ON (nls.group_id = a.id) LEFT JOIN profile_phones AS p ON (p.link_type = \'group\' AND p.link_id = a.id AND p.tel_id = 0) LEFT JOIN profile_phones AS f ON (f.link_type = \'group\' AND f.link_id = a.id AND f.tel_id = 1) LEFT JOIN profile_addresses AS ad ON (ad.type = \'group\' AND ad.groupid = a.id) WHERE ' . $where); if ($res->numRows() != 1) { if ($can_be_shortname && (is_int($id) || ctype_digit($id))) { return Group::get($id, false); } return null; } $data = $res->fetchOneAssoc(); $positions = XDB::fetchAllAssoc('SELECT position, uid FROM group_members WHERE asso_id = {?} AND position IS NOT NULL ORDER BY position', $data['id']); return new Group(array_merge($data, array('positions' => $positions))); } static public function subscribe($group_id, $uid) { XDB::execute('DELETE FROM group_former_members WHERE uid = {?} AND asso_id = {?}', $uid, $group_id); XDB::execute('INSERT IGNORE INTO group_members (asso_id, uid) VALUES ({?}, {?})', $group_id, $uid); } static public function unsubscribe($group_id, $uid, $remember) { XDB::execute('INSERT INTO group_former_members (asso_id, uid, remember, unsubsciption_date) VALUES ({?}, {?}, {?}, NOW()) ON DUPLICATE KEY UPDATE remember = {?}, unsubsciption_date = NOW()', $group_id, $uid, $remember, $remember); XDB::execute('DELETE FROM group_members WHERE uid = {?} AND asso_id = {?}', $uid, $group_id); self::fix_notification($group_id); } static private function fix_notification($group_id) { $count = XDB::fetchOneCell("SELECT COUNT(uid) FROM group_members WHERE asso_id = {?} AND perms = 'admin' AND FIND_IN_SET('notify', flags)", $group_id); if ($count == 0) { XDB::execute("UPDATE groups SET flags = IF(flags = '', 'notify_all', CONCAT(flags, ',', 'notify_all')) WHERE id = {?}", $group_id); } } } // vim:set et sw=4 sts=4 sws=4 foldmethod=marker fenc=utf-8: ?>
Polytechnique-org/platal
classes/group.php
PHP
gpl-2.0
7,869
#!/usr/bin/env bash # install dependencies flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo flatpak install flathub org.freedesktop.Platform//21.08 org.freedesktop.Sdk//21.08 # org.freedesktop.Sdk.Extension.openjdk11//21.08 # prepare workspace export VERSION=`../../version.sh` mkdir tmp cp ../LinuxJape_$VERSION.tgz tmp/LinuxJape.tgz cd tmp tar zxvf LinuxJape.tgz cp ../customInstallJape.sh LinuxJape/installJape.sh cp ../uk.org.jape.yaml . flatpak-builder --repo=japerepo build-dir uk.org.jape.yaml --force-clean flatpak build-bundle japerepo ../jape_$VERSION.flatpak uk.org.jape cd .. rm -rf tmp echo -e "\nresult bundle: $(pwd)/jape_$VERSION.flatpak"
RBornat/jape
distrib/CommonBuildResources/Linux/flatpak/build.sh
Shell
gpl-2.0
700
/* * Copyright (C) 2013-2020 Canonical, Ltd. * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * This code is a complete clean re-write of the stress tool by * Colin Ian King <colin.king@canonical.com> and attempts to be * backwardly compatible with the stress tool by Amos Waterland * <apw@rossby.metr.ou.edu> but has more stress tests and more * functionality. * */ #include <unistd.h> int main(void) { return fchmodat(0, "", 0, 0); }
fuchsia-mirror/stress-ng
test/test-fchmodat.c
C
gpl-2.0
1,122
/***************************************************************************** * dbus-tracklist.h : dbus control module (mpris v1.0) - /TrackList object ***************************************************************************** * Copyright © 2006-2008 Rafaël Carré * Copyright © 2007-2010 Mirsal Ennaime * Copyright © 2009-2010 The VideoLAN team * $Id$ * * Authors: Mirsal ENNAIME <mirsal dot ennaime at gmail dot com> * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifndef _VLC_DBUS_TRACKLIST_H #define _VLC_DBUS_TRACKLIST_H #include <vlc_common.h> #include <vlc_interface.h> #include "dbus_common.h" #define DBUS_MPRIS_TRACKLIST_INTERFACE "org.freedesktop.MediaPlayer" #define DBUS_MPRIS_TRACKLIST_PATH "/TrackList" /* Handle incoming dbus messages */ DBusHandlerResult handle_tracklist ( DBusConnection *p_conn, DBusMessage *p_from, void *p_this ); static const DBusObjectPathVTable dbus_mpris_tracklist_vtable = { NULL, handle_tracklist, /* handler function */ NULL, NULL, NULL, NULL }; int TrackListChangeEmit( intf_thread_t *, int, int ); #endif //dbus_tracklist.h
cmassiot/vlc-broadcast
modules/control/dbus/dbus_tracklist.h
C
gpl-2.0
1,951
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>PHPXRef 0.7.1 : Unnamed Project : Function Reference: url_link()</title> <link rel="stylesheet" href="../sample.css" type="text/css"> <link rel="stylesheet" href="../sample-print.css" type="text/css" media="print"> <style id="hilight" type="text/css"></style> <meta http-equiv="content-type" content="text/html;charset=iso-8859-1"> </head> <body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff"> <table class="pagetitle" width="100%"> <tr> <td valign="top" class="pagetitle"> [ <a href="../index.html">Index</a> ] </td> <td align="right" class="pagetitle"> <h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2> </td> </tr> </table> <!-- Generated by PHPXref 0.7.1 at Sat Nov 21 22:13:19 2015 --> <!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net --> <!-- http://phpxref.sourceforge.net/ --> <script src="../phpxref.js" type="text/javascript"></script> <script language="JavaScript" type="text/javascript"> <!-- ext='.html'; relbase='../'; subdir='_functions'; filename='index.html'; cookiekey='phpxref'; handleNavFrame(relbase, subdir, filename); logFunction('url_link'); // --> </script> <script language="JavaScript" type="text/javascript"> if (gwGetCookie('xrefnav')=='off') document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>'); else document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>'); </script> <noscript> <p class="navlinks"> [ <a href="../nav.html" target="_top">Show Explorer</a> ] [ <a href="index.html" target="_top">Hide Navbar</a> ] </p> </noscript> [<a href="../index.html">Top level directory</a>]<br> <script language="JavaScript" type="text/javascript"> <!-- document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>'); document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">'); document.writeln('<tr><td class="searchbox-title">'); document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>'); document.writeln('<\/td><\/tr>'); document.writeln('<tr><td class="searchbox-body" id="searchbox-body">'); document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>'); document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: '); document.writeln('<input type="text" size=10 value="" name="classname"><br>'); document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: '); document.writeln('<input type="text" size=10 value="" name="funcname"><br>'); document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: '); document.writeln('<input type="text" size=10 value="" name="varname"><br>'); document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: '); document.writeln('<input type="text" size=10 value="" name="constname"><br>'); document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: '); document.writeln('<input type="text" size=10 value="" name="tablename"><br>'); document.writeln('<input type="submit" class="searchbox-button" value="Search">'); document.writeln('<\/form>'); document.writeln('<\/td><\/tr><\/table>'); document.writeln('<\/td><\/tr><\/table>'); // --> </script> <div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div> <h3>Function and Method Cross Reference</h3> <h2><a href="index.html#url_link">url_link()</a></h2> <b>Defined at:</b><ul> <li><a href="../inc/items/model/_item.class.php.html#url_link">/inc/items/model/_item.class.php</a> -> <a onClick="logFunction('url_link', '/inc/items/model/_item.class.php.source.html#l4747')" href="../inc/items/model/_item.class.php.source.html#l4747"> line 4747</a></li> </ul> <b>Referenced 7 times:</b><ul> <li><a href="../skins_fallback_v6/_item_content.inc.php.html">/skins_fallback_v6/_item_content.inc.php</a> -> <a href="../skins_fallback_v6/_item_content.inc.php.source.html#l265"> line 265</a></li> <li><a href="../skins_fallback_v5/_item_content.inc.php.html">/skins_fallback_v5/_item_content.inc.php</a> -> <a href="../skins_fallback_v5/_item_content.inc.php.source.html#l238"> line 238</a></li> <li><a href="../skins/_atom/index.main.php.html">/skins/_atom/index.main.php</a> -> <a href="../skins/_atom/index.main.php.source.html#l138"> line 138</a></li> <li><a href="../skins/photoalbums/_item_block.inc.php.html">/skins/photoalbums/_item_block.inc.php</a> -> <a href="../skins/photoalbums/_item_block.inc.php.source.html#l68"> line 68</a></li> <li><a href="../skins/bootstrap_gallery_skin/_item_content.inc.php.html">/skins/bootstrap_gallery_skin/_item_content.inc.php</a> -> <a href="../skins/bootstrap_gallery_skin/_item_content.inc.php.source.html#l275"> line 275</a></li> <li><a href="../skins/bootstrap_gallery_skin/_item_content.inc.php.html">/skins/bootstrap_gallery_skin/_item_content.inc.php</a> -> <a href="../skins/bootstrap_gallery_skin/_item_content.inc.php.source.html#l373"> line 373</a></li> <li><a href="../skins/photoblog/_item_block.inc.php.html">/skins/photoblog/_item_block.inc.php</a> -> <a href="../skins/photoblog/_item_block.inc.php.source.html#l171"> line 171</a></li> </ul> <!-- A link to the phpxref site in your customized footer file is appreciated ;-) --> <br><hr> <table width="100%"> <tr><td>Generated: Sat Nov 21 22:13:19 2015</td> <td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td> </tr> </table> </body></html>
mgsolipa/b2evolution_phpxref
_functions/url_link.html
HTML
gpl-2.0
6,080
/* * ************************************************************************* * FilePickerActivity.java * ************************************************************************** * Copyright © 2015 VLC authors and VideoLAN * Author: Geoffrey Métais * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * *************************************************************************** */ package org.videolan.vlc.gui.browser; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.view.View; import org.videolan.vlc.R; public class FilePickerActivity extends AppCompatActivity { protected static final String TAG = "VLC/BaseBrowserFragment"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.file_picker_activity); final FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.fragment_placeholder, new FilePickerFragment(), "picker"); ft.commit(); } @Override public void onBackPressed() { final FilePickerFragment fpf = ((FilePickerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_placeholder)); if (fpf.isRootDirectory()) finish(); else if (getSupportFragmentManager().getBackStackEntryCount() > 0) super.onBackPressed(); else fpf.browseUp(); } public void onHomeClick(View v) { ((FilePickerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_placeholder)).browseRoot(); } }
robedmo/vlc-android
vlc-android/src/org/videolan/vlc/gui/browser/FilePickerActivity.java
Java
gpl-2.0
2,352
angular.module('project', ['ngRoute', 'firebase']) .value('fbURL', 'https://angularjs-projects.firebaseio.com/') .factory('Projects', function($firebase, fbURL) { return $firebase(new Firebase(fbURL)).$asArray(); }) .config(function($routeProvider) { $routeProvider .when('/', { controller:'ListCtrl', templateUrl:'list.html' }) .when('/edit/:projectId', { controller:'EditCtrl', templateUrl:'detail.html' }) .when('/new', { controller:'CreateCtrl', templateUrl:'detail.html' }) .otherwise({ redirectTo:'/' }); }) .controller('ListCtrl', function($scope, Projects) { $scope.projects = Projects; }) .controller('CreateCtrl', function($scope, $location, Projects) { $scope.save = function() { Projects.$add($scope.project).then(function(data) { $location.path('/'); }); }; }) .controller('EditCtrl', function($scope, $location, $routeParams, Projects) { var projectId = $routeParams.projectId, projectIndex; $scope.projects = Projects; projectIndex = $scope.projects.$indexFor(projectId); $scope.project = $scope.projects[projectIndex]; $scope.destroy = function() { $scope.projects.$remove($scope.project).then(function(data) { $location.path('/'); }); }; $scope.save = function() { $scope.projects.$save($scope.project).then(function(data) { $location.path('/'); }); }; }); /** * Created by kurtulus on 08/12/14. */
qurantools/kurancalis-web
prototype/project.js
JavaScript
gpl-2.0
1,820
<?php # Modified 07/15/2013 by Plugin Review Network ?> <br> <!-- MOD Action to Wordpress Menu --> <center><form action="" method=GET> <input type="hidden" name="page" value="infinityresponder"> <input type="hidden" name="subpage" value="admin"> <input type="hidden" name="action" value="Email_Search"> Search for Email Address: <input name="email_addy" size=30 maxlength=95 class="fields"> <input class="button-secondary" type="submit" name="Email Search" value="Email Search"> </form></center>
majick777/wp-infinity-responder
templates/email_search.admin.php
PHP
gpl-2.0
514
<?php do_action( 'wptouch_functions_start' ); add_filter( 'wp_title', 'foundation_set_title' ); function foundation_set_title( $title ) { return $title . ' ' . wptouch_get_bloginfo( 'site_title' ); } function responsive_ads_unit() { ?> <!-- responsive --> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-5564538375885578" data-ad-slot="7584062441" data-ad-format="auto"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> <?php } add_filter( 'wptouch_the_post_thumbnail', 'change_thumbnail_size', 10, 2 ); function change_thumbnail_size( $thumbnail, $param ) { $new_url = preg_replace( '/(http:\/\/.+?)(-\d+x\d+)\.(jpg|png|jpeg|gif)/', '$1-360x360.$3', $thumbnail ); if ( file_exists( str_replace( content_url(), WP_CONTENT_DIR, $new_url ) ) ) { return $new_url; } else { return preg_replace( '/(http:\/\/.+?)(-\d+x\d+)\.(jpg|png|jpeg|gif)/', '$1.$3', $thumbnail ); } }
mary061079/karingrande
wp-content/plugins/wptouch/themes/foundation/default/functions.php
PHP
gpl-2.0
1,018
<html> <head> <title>SUSY Les Houches Accord</title> <link rel="stylesheet" type="text/css" href="pythia.css"/> <link rel="shortcut icon" href="pythia32.gif"/> </head> <body> <script language=javascript type=text/javascript> function stopRKey(evt) { var evt = (evt) ? evt : ((event) ? event : null); var node = (evt.target) ? evt.target :((evt.srcElement) ? evt.srcElement : null); if ((evt.keyCode == 13) && (node.type=="text")) {return false;} } document.onkeypress = stopRKey; </script> <?php if($_POST['saved'] == 1) { if($_POST['filepath'] != "files/") { echo "<font color='red'>SETTINGS SAVED TO FILE</font><br/><br/>"; } else { echo "<font color='red'>NO FILE SELECTED YET.. PLEASE DO SO </font><a href='SaveSettings.php'>HERE</a><br/><br/>"; } } ?> <form method='post' action='SUSYLesHouchesAccord.php'> <h2>SUSY Les Houches Accord</h2> The PYTHIA 8 program does not contain an internal spectrum calculator (a.k.a. RGE package) to provide supersymmetric couplings, mixing angles, masses and branching ratios. Thus the SUSY Les Houches Accord (SLHA) [<a href="Bibliography.php" target="page">Ska04</a>][<a href="Bibliography.php" target="page">All08</a>] is the only way of inputting SUSY models, and SUSY processes (see the <?php $filepath = $_GET["filepath"]; echo "<a href='SUSYProcesses.php?filepath=".$filepath."' target='page'>";?>SUSYProcesses</a> page) cannot be run unless such an input has taken place. <p/> The SLHA input format can also be extended for use with more general BSM models, beyond SUSY. Information specific to how to use the SLHA interface for generic BSM models is collected below, under <a href="#generic">Using SLHA for generic BSM Models</a>, with more elaborate explanations and examples in [<a href="Bibliography.php" target="page">Des11</a>]. <p/> Most of the SUSY implementation in PYTHIA 8 is compatible with both the SLHA1 [<a href="Bibliography.php" target="page">Ska04</a>] and SLHA2 [<a href="Bibliography.php" target="page">All08</a>] conventions (with some limitations for the NMSSM in the latter case). Internally, PYTHIA 8 uses the SLHA2 conventions and translates SLHA1 input to these when necessary. See the section on SUSY Processes and [<a href="Bibliography.php" target="page">Des11</a>] for more information. Note that PYTHIA assumes that a spectrum is either fully SHLA1 or fully SLHA2 compliant. Mixing of the two standards is discouraged, as this can lead to ambiguities and inconsistencies. <p/> When reading LHEF files, Pythia automatically looks for SLHA information between <code>&lt;slha&gt;...&lt;/slha&gt;</code> tags in the header of such files. When running Pythia without LHEF input (or if reading an LHEF file that does not contain SLHA information in the header), a separate file containing SLHA information may be specified using <code>SLHA:file</code> (see below). <p/> Normally the LHEF would be in uncompressed format, and thus human-readable if opened in a text editor. A possibility to read gzipped files has been added, based on the Boost and zlib libraries, which therefore have to be linked appropriately in order for this option to work. See the <code>README</code> file in the main directory for details on how to do this. <p/> Finally, the SLHA input capability can of course also be used to input SLHA-formatted <code>MASS</code> and <code>DECAY</code> tables for other particles, such as the Higgs boson, furnishing a less sophisticated but more universal complement to the standard PYTHIA 8-specific methods for inputting such information (for the latter, see the section on <?php $filepath = $_GET["filepath"]; echo "<a href='ParticleData.php?filepath=".$filepath."' target='page'>";?>Particle Data</a> and the <?php $filepath = $_GET["filepath"]; echo "<a href='ParticleDataScheme.php?filepath=".$filepath."' target='page'>";?>scheme</a> to modify it). This may at times not be desirable, so a few options can be used to curb the right of SLHA to overwrite particle data. Conversely, it is sometimes useful to allow the user to modify eg a mass parameter relative to its value in the SLHA spectrum. This is normally not permitted (the SLHA spectrum is normally self-consistent and should not be modified), but an option for allowing it is provided. <p/> The reading-in of information from SLHA or LHEF files is handled by the <code>SusyLesHouches</code> class, while the subsequent calculation of derived quantities of direct application to SUSY processes is done in the <code>CoupSUSY</code>, <code>SigmaSUSY</code>, and <code>SUSYResonanceWidths</code> classes. <h3>Sanity Checks</h3> As an aid for basic validation, some checks and ranges are imposed on SLHA input during initialization, as follows: <ul> <li>Several parameters (<code>SLHA:keepSM</code>, <code>minMassSM</code>, and <code>SLHA:allowUserOverride</code>) provide some safety against unintentionally overwriting PYTHIA's Standard-Model information. These parameters can be altered to hand over more or less control to the SLHA interface. In particular, a lot of mass and decay-table information may be included by default in some SLHA files, without it being the explicit intention of the user to overwrite the corresponding PYTHIA information. The default values of the SLHA safety parameters have been chosen so as to eliminate at least the most obvious causes of Garbage In Garbage Out. (E.g., there is usually no reason to modify the masses of well-measured SM particles, like the W and Z bosons, nor to replace their sophisticated internal decay treatments by the simplified isotropic treatment used for SLHA DECAY tables.) </li> <li>For SLHA SUSY spectra, the interface checks the mass-ordering of the Higgs, Neutralino, and Chargino sectors, and the unitarity/orthogonality of the mixing matrices. It also performs some additional self-consistency checks on whether the correct SLHA BLOCKs for the given SUSY model have been included, and whether all required entries have been defined. </li> <li>If MASS or DECAY information for a particle has been changed by SLHA input, the following sanity checks will be carried out. The particle will be declared stable unless there is at least one on-shell decay channel open (regardless of the presence of any DECAY information). In particular, massless particles will always be declared stable. A lower cutoff is imposed on the Breit-Wigner shape of the particle, requiring its mass to remain above the sum of masses for the lightest decay channel. Subject to that constraint, the lower cutoff will normally be placed at 5 times the width (so that the default gives a decent sampling of the shape), but the user is allowed to use the <code>mMin</code> parameter to choose a larger sampling range if so desired (still subject to the on-shell constraint). </li> <li>For each decay channel in an SLHA DECAY table, PYTHIA will checks the available phase space. If the channel is on shell (sum of daughter masses is less than mass of decaying particle), then the threshold dependence is given by <code>SLHA:meMode</code>. If the channel is off shell, then an <code>meMode</code> of 100 is always used. As a further protection against GIGO, if the channel appears to be physically impossible (defined as requiring fluctuations of more than more than 100 times the effective combined widths), it is switched of and a warning message is printed. </li> <li>DECAY table branching fractions are always interpreted as positive. However, a negative sign for one or more channels can be given, and will then be interpreted to mean that the corresponding channel(s) should be switched off for the current run. This furnishes a simple way to switch SLHA DECAY channels on and off while preserving the sum of branching fractions equal to unity. </li> </ul> Note that these sanity checks will not catch all possible cases of Garbage In Garbage Out, so human verification of the input files is always a good idea, as is taking a look at any warnings or error messages printed by the SLHA interface during initialization. It is ultimately up to the user to ensure that sensible input is being given. <h3>SLHA Switches and Parameters</h3> <p/><code>mode&nbsp; </code><strong> SLHA:readFrom &nbsp;</strong> (<code>default = <strong>1</strong></code>; <code>minimum = 0</code>; <code>maximum = 2</code>)<br/> Controls from where SLHA information is read. <br/><code>option </code><strong> 0</strong> : is not read at all. Useful when SUSY is not simulated and normal particle properties should not be overwritten. <br/><code>option </code><strong> 1</strong> : read in from the <code>&lt;slha&gt;...&lt;/slha&gt;</code> block of a LHEF, if such a file is read during initialization, and else from the <code>SLHA:file</code> below. <br/><code>option </code><strong> 2</strong> : read in from the <code>SLHA:file</code> below. <br/><br/><table><tr><td><strong>SLHA:file </td><td></td><td> <input type="text" name="1" value="void" size="20"/> &nbsp;&nbsp;(<code>default = <strong>void</strong></code>)</td></tr></table> Name of an SLHA (or LHEF) file containing the SUSY/BSM model definition, spectra, and (optionally) decay tables. Default <code>void</code> signals that no such file has been assigned. <br/><br/><strong>SLHA:keepSM</strong> <input type="radio" name="2" value="on" checked="checked"><strong>On</strong> <input type="radio" name="2" value="off"><strong>Off</strong> &nbsp;&nbsp;(<code>default = <strong>on</strong></code>)<br/> Some programs write SLHA output also for SM particles where normally one would not want to have masses and decay modes changed unwittingly. Therefore, by default, known SM particles are ignored in SLHA files. To be more specific, particle data for identity codes in the ranges 1 - 24 and 81 - 999,999 are ignored. Notably this includes <i>Z^0</i>, <i>W^+-</i> and <i>t</i>. The SM Higgs is modified by the SLHA input, as is other codes in the range 25 - 80 and 1,000,000 - . If you switch off this flag then also SM particles are modified by SLHA input. <br/><br/><table><tr><td><strong>SLHA:minMassSM </td><td></td><td> <input type="text" name="3" value="100.0" size="20"/> &nbsp;&nbsp;(<code>default = <strong>100.0</strong></code>)</td></tr></table> This parameter provides an alternative possibility to ignore SLHA input for all particles with identity codes below 1,000,000 (which mainly means SM particle, but also includes e.g. the Higgs bosons in two-Higgs-doublet scenarios) whose default masses in PYTHIA lie below some threshold value, given by this parameter. The default value of 100.0 allows SLHA input to modify the top quark, but not, e.g., the <i>Z^0</i> and <i>W^+-</i> bosons. <br/><br/><strong>SLHA:allowUserOverride</strong> <input type="radio" name="4" value="on"><strong>On</strong> <input type="radio" name="4" value="off" checked="checked"><strong>Off</strong> &nbsp;&nbsp;(<code>default = <strong>off</strong></code>)<br/> Flag to set whether the user is allowed to modify the parameters read from an SLHA spectrum. Is normally kept <code>off</code> to preserve the internal self-consistency of SLHA spectra. If this flag is switched <code>on</code>, the mass values read from the SLHA block MASS are allowed to be modified by the user, using PYTHIA's standard <code>readString</code> and related methods. <h3>SLHA DECAY Tables</h3> In addition to SUSY spectra, the SLHA also defines a set of conventions for decay tables. These are not restricted to SUSY models, but can be used for arbitrary particles, either in combination with or independently of the SUSY parts of the Accord. The settings in this section control whether and how PYTHIA will make use of such tables. See also the comments under sanity checks above. <br/><b>Note</b>: the PYTHIA SLHA interface is limited to at most <code>1&rarr;8</code> decays. <br/><br/><strong>SLHA:useDecayTable</strong> <input type="radio" name="5" value="on" checked="checked"><strong>On</strong> <input type="radio" name="5" value="off"><strong>Off</strong> &nbsp;&nbsp;(<code>default = <strong>on</strong></code>)<br/> Switch to choose whether to read in SLHA <code>DECAY</code> tables or not. If this switch is set to off, PYTHIA will ignore any decay tables found in the SLHA file, and all decay widths will be calculated internally by PYTHIA. If switched on, SLHA decay tables will be read in, and will then supersede PYTHIA's internal calculations, with PYTHIA only computing the decays for particles for which no SLHA decay table is found. (To set a particle stable, you may either omit an SLHA <code>DECAY</code> table for it and then use PYTHIA's internal <code>id:MayDecay</code> switch for that particle, or you may include an SLHA <code>DECAY</code> table for it, with the width set explicitly to zero.) <p/><code>mode&nbsp; </code><strong> SLHA:meMode &nbsp;</strong> (<code>default = <strong>100</strong></code>; <code>minimum = 100</code>; <code>maximum = 103</code>)<br/> This value specifies how threshold, off-shell, and phase-space weighting effects for SLHA decay channels should be treated, using the same numbering scheme as for <?php $filepath = $_GET["filepath"]; echo "<a href='ResonanceDecays.php?filepath=".$filepath."' target='page'>";?>resonances</a>. The default (100) is to use the branching fraction given in the SLHA DECAY tables without any modifications. The corresponding partial widths remain unchanged when the resonance fluctuates in mass. Specifically there are no threshold corrections. That is, if the resonance fluctuates down in mass, to below the nominal threshold for some decay mode, it is assumed that one of the daughters could also fluctuate down to keep the channel open. (If not, there may be problems later on.) Alternative options (with values 101+) documented under <?php $filepath = $_GET["filepath"]; echo "<a href='ResonanceDecays.php?filepath=".$filepath."' target='page'>";?>resonances</a> allow for some flexibility to apply threshold factors expressing the closing of the on-shell phase space when the daughter masses approach or exceed the parent one. Note that modes that are extremely far off shell (defined as needing a fluctuation of more than 100 times the root-sum-square of the widths of the mother and daughter particles) will always be assigned <code>meMode = 100</code> and should be switched off by hand if so desired. It is up to the user to ensure that the final behaviour is consistent with what is desired (and/or to apply suitable post facto reweightings). Plotting the generator-level resonance and decay-product mass distributions (and e.g., mass differences), effective branching fractions, etc, may be of assistance to validate the behaviour of the program. <h3>Internal SLHA Variables</h3> <p/><code>mode&nbsp; </code><strong> SLHA:verbose &nbsp;</strong> (<code>default = <strong>1</strong></code>; <code>minimum = 0</code>; <code>maximum = 3</code>)<br/> Controls amount of text output written by the SLHA interface, with a value of 0 corresponding to the most quiet mode. The following variables are used internally by PYTHIA as local copies of SLHA information. User changes will generally have no effect, since these variables will be reset by the SLHA reader during initialization. <br/><br/><strong>SLHA:NMSSM</strong> <input type="radio" name="6" value="on"><strong>On</strong> <input type="radio" name="6" value="off" checked="checked"><strong>Off</strong> &nbsp;&nbsp;(<code>default = <strong>off</strong></code>)<br/> Corresponds to SLHA block MODSEL entry 3. <a name="generic"></a> <h2>Using SLHA for generic BSM Models</h2> <p> Using the <code>QNUMBERS</code> extension [<a href="Bibliography.php" target="page">Alw07</a>], the SLHA can also be used to define new particles, with arbitrary quantum numbers. This already serves as a useful way to introduce new particles and can be combined with <code>MASS</code> and <code>DECAY</code> tables in the usual way, to generate isotropically distributed decays or even chains of such decays. (If you want something better than isotropic, sorry, you'll have to do some actual work ...) </p> <p> A more advanced further option is to make use of the possibility in the SLHA to include user-defined blocks with arbitrary names and contents. Obviously, standalone PYTHIA 8 does not know what to do with such information. However, it does not throw it away either, but instead stores the contents of user blocks as strings, which can be read back later, with the user having full control over the format used to read the individual entries. </p> <p> The contents of both standard and user-defined SLHA blocks can be accessed in any class inheriting from PYTHIA 8's <code>SigmaProcess</code> class (i.e., in particular, from any semi-internal process written by a user), through its SLHA pointer, <code>slhaPtr</code>, by using the following methods: <pre> bool slhaPtr->getEntry(string blockName, double& val); bool slhaPtr->getEntry(string blockName, int indx, double& val); bool slhaPtr->getEntry(string blockName, int indx, int jndx, double& val); bool slhaPtr->getEntry(string blockName, int indx, int jndx, int kndx, double& val); </pre> </p> <p> This particular example assumes that the user wants to read the entries (without index, indexed, matrix-indexed, or 3-tensor-indexed, respectively) in the user-defined block <code>blockName</code>, and that it should be interpreted as a <code>double</code>. The last argument is templated, and hence if anything other than a <code>double</code> is desired to be read, the user has only to give the last argument a different type. If anything went wrong (i.e., the block doesn't exist, or it doesn't have an entry with that index, or that entry can't be read as a double), the method returns false; true otherwise. This effectively allows to input completely arbitrary parameters using the SLHA machinery, with the user having full control over names and conventions. Of course, it is then the user's responsibility to ensure complete consistency between the names and conventions used in the SLHA input, and those assumed in any user-written semi-internal process code. </p> <p> Note that PYTHIA 8 always initializes at least the SLHA blocks MASS and SMINPUTS, starting from its internal SM parameters and particle data table values (updated to take into account user modifications). These blocks can therefore be accessed using the <code>slhaPtr->getEntry()</code> methods even in the absence of SLHA input. Note: in the SMINPUTS block, PYTHIA outputs physically correct (i.e., measured) values of <i>GF</i>, <i>m_Z</i>, and <i>alpha_EM(m_Z)</i>. However, if one attempts to compute, e.g., the W mass, at one loop from these quantities, a value of 79 GeV results, with a corresponding value for the weak mixing angle. We advise to instead take the physically measured W mass from block MASS, and recompute the EW parameters as best suited for the application at hand. </p> <input type="hidden" name="saved" value="1"/> <?php echo "<input type='hidden' name='filepath' value='".$_GET["filepath"]."'/>"?> <table width="100%"><tr><td align="right"><input type="submit" value="Save Settings" /></td></tr></table> </form> <?php if($_POST["saved"] == 1) { $filepath = $_POST["filepath"]; $handle = fopen($filepath, 'a'); if($_POST["1"] != "void") { $data = "SLHA:file = ".$_POST["1"]."\n"; fwrite($handle,$data); } if($_POST["2"] != "on") { $data = "SLHA:keepSM = ".$_POST["2"]."\n"; fwrite($handle,$data); } if($_POST["3"] != "100.0") { $data = "SLHA:minMassSM = ".$_POST["3"]."\n"; fwrite($handle,$data); } if($_POST["4"] != "off") { $data = "SLHA:allowUserOverride = ".$_POST["4"]."\n"; fwrite($handle,$data); } if($_POST["5"] != "on") { $data = "SLHA:useDecayTable = ".$_POST["5"]."\n"; fwrite($handle,$data); } if($_POST["6"] != "off") { $data = "SLHA:NMSSM = ".$_POST["6"]."\n"; fwrite($handle,$data); } fclose($handle); } ?> </body> </html> <!-- Copyright (C) 2017 Torbjorn Sjostrand -->
vikasnt/pythia8
share/Pythia8/phpdoc/SUSYLesHouchesAccord.php
PHP
gpl-2.0
20,279
/* grabbag - Convenience lib for various routines common to several tools * Copyright (C) 2002-2009 Josh Coalson * Copyright (C) 2011-2013 Xiph.Org Foundation * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* Convenience routines for manipulating files */ /* This .h cannot be included by itself; #include "share/grabbag.h" instead. */ #ifndef GRABAG__FILE_H #define GRABAG__FILE_H /* needed because of off_t */ #if HAVE_CONFIG_H # include <config.h> #endif #include <sys/types.h> /* for off_t */ #include <stdio.h> /* for FILE */ #include "FLAC/ordinals.h" #include "share/compat.h" #ifdef __cplusplus extern "C" { #endif void grabbag__file_copy_metadata(const char *srcpath, const char *destpath); FLAC__off_t grabbag__file_get_filesize(const char *srcpath); const char *grabbag__file_get_basename(const char *srcpath); /* read_only == false means "make file writable by user" * read_only == true means "make file read-only for everyone" */ FLAC__bool grabbag__file_change_stats(const char *filename, FLAC__bool read_only); /* returns true iff stat() succeeds for both files and they have the same device and inode. */ /* on windows, uses GetFileInformationByHandle() to compare */ FLAC__bool grabbag__file_are_same(const char *f1, const char *f2); /* attempts to make writable before unlinking */ FLAC__bool grabbag__file_remove_file(const char *filename); /* these will forcibly set stdin/stdout to binary mode (for OSes that require it) */ FILE *grabbag__file_get_binary_stdin(void); FILE *grabbag__file_get_binary_stdout(void); #ifdef __cplusplus } #endif #endif
bit-trade-one/SoundModuleAP
lib-src/libflac/include/share/grabbag/file.h
C
gpl-2.0
2,355
/* Copyright (C) 2010 TrinityCore <http://www.trinitycore.org/> * 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "ScriptedPch.h" #include "ScriptedPch.h" /*###### ##Quest 5441: Lazy Peons ##npc_lazy_peon ######*/ enum LazyPeonYells { SAY_SPELL_HIT = -1999900 //Ow! OK, I''ll get back to work, $N!' }; enum LazyPeon { QUEST_LAZY_PEONS = 5441, GO_LUMBERPILE = 175784, SPELL_BUFF_SLEEP = 17743, SPELL_AWAKEN_PEON = 19938 }; struct npc_lazy_peonAI : public ScriptedAI { npc_lazy_peonAI(Creature *c) : ScriptedAI(c) {} uint64 uiPlayerGUID; uint32 m_uiRebuffTimer; uint32 work; void Reset () { uiPlayerGUID = 0; work = false; } void MovementInform(uint32 type, uint32 id) { if (id == 1) work = true; } void SpellHit(Unit *caster, const SpellEntry *spell) { if (spell->Id == SPELL_AWAKEN_PEON && caster->GetTypeId() == TYPEID_PLAYER && CAST_PLR(caster)->GetQuestStatus(QUEST_LAZY_PEONS) == QUEST_STATUS_INCOMPLETE) { caster->ToPlayer()->KilledMonsterCredit(me->GetEntry(),me->GetGUID()); DoScriptText(SAY_SPELL_HIT, me, caster); me->RemoveAllAuras(); if (GameObject* Lumberpile = me->FindNearestGameObject(GO_LUMBERPILE, 20)) me->GetMotionMaster()->MovePoint(1,Lumberpile->GetPositionX()-1,Lumberpile->GetPositionY(),Lumberpile->GetPositionZ()); } } void UpdateAI(const uint32 uiDiff) { if (work = true) me->HandleEmoteCommand(466); if (m_uiRebuffTimer <= uiDiff) { DoCast(me, SPELL_BUFF_SLEEP); m_uiRebuffTimer = 300000; //Rebuff agian in 5 minutes } else m_uiRebuffTimer -= uiDiff; if (!UpdateVictim()) return; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_npc_lazy_peon(Creature* pCreature) { return new npc_lazy_peonAI(pCreature); } void AddSC_durotar() { Script* newscript; newscript = new Script; newscript->Name = "npc_lazy_peon"; newscript->GetAI = &GetAI_npc_lazy_peon; newscript->RegisterSelf(); }
Muglackh/cejkaz-tc
src/scripts/kalimdor/durotar.cpp
C++
gpl-2.0
3,004
/* vi: set sw=4 ts=4: */ /* * Rewrite by Russ Dill <Russ.Dill@asu.edu> July 2001 * * Licengsed under GPLv2, see file LICENSE in this source tree. */ #include "common.h" #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1 unsigned dhcp_verbose; #endif const uint8_t MAC_BCAST_ADDR[6] ALIGN2 = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; /* Supported options are easily added here. * See RFC2132 for more options. * OPTION_REQ: these options are requested by udhcpc (unless -o). */ const struct dhcp_optflag dhcp_optflags[] = { /* flags code */ { OPTION_IP | OPTION_REQ, 0x01 }, /* DHCP_SUBNET */ { OPTION_S32 , 0x02 }, /* DHCP_TIME_OFFSET */ { OPTION_IP | OPTION_LIST | OPTION_REQ, 0x03 }, /* DHCP_ROUTER */ // { OPTION_IP | OPTION_LIST , 0x04 }, /* DHCP_TIME_SERVER */ // { OPTION_IP | OPTION_LIST , 0x05 }, /* DHCP_NAME_SERVER */ { OPTION_IP | OPTION_LIST | OPTION_REQ, 0x06 }, /* DHCP_DNS_SERVER */ // { OPTION_IP | OPTION_LIST , 0x07 }, /* DHCP_LOG_SERVER */ // { OPTION_IP | OPTION_LIST , 0x08 }, /* DHCP_COOKIE_SERVER */ { OPTION_IP | OPTION_LIST , 0x09 }, /* DHCP_LPR_SERVER */ { OPTION_STRING_HOST | OPTION_REQ, 0x0c }, /* DHCP_HOST_NAME */ { OPTION_U16 , 0x0d }, /* DHCP_BOOT_SIZE */ { OPTION_STRING_HOST | OPTION_REQ, 0x0f }, /* DHCP_DOMAIN_NAME */ { OPTION_IP , 0x10 }, /* DHCP_SWAP_SERVER */ { OPTION_STRING , 0x11 }, /* DHCP_ROOT_PATH */ { OPTION_U8 , 0x17 }, /* DHCP_IP_TTL */ { OPTION_U16 , 0x1a }, /* DHCP_MTU */ //TODO: why do we request DHCP_BROADCAST? Can't we assume that //in the unlikely case it is different from typical N.N.255.255, //server would let us know anyway? { OPTION_IP | OPTION_REQ, 0x1c }, /* DHCP_BROADCAST */ { OPTION_IP_PAIR | OPTION_LIST , 0x21 }, /* DHCP_ROUTES */ { OPTION_STRING_HOST , 0x28 }, /* DHCP_NIS_DOMAIN */ { OPTION_IP | OPTION_LIST , 0x29 }, /* DHCP_NIS_SERVER */ { OPTION_IP | OPTION_LIST | OPTION_REQ, 0x2a }, /* DHCP_NTP_SERVER */ { OPTION_IP | OPTION_LIST , 0x2c }, /* DHCP_WINS_SERVER */ { OPTION_U32 , 0x33 }, /* DHCP_LEASE_TIME */ { OPTION_IP , 0x36 }, /* DHCP_SERVER_ID */ { OPTION_STRING , 0x38 }, /* DHCP_ERR_MESSAGE */ //TODO: must be combined with 'sname' and 'file' handling: { OPTION_STRING_HOST , 0x42 }, /* DHCP_TFTP_SERVER_NAME */ { OPTION_STRING , 0x43 }, /* DHCP_BOOT_FILE */ //TODO: not a string, but a set of LASCII strings: // { OPTION_STRING , 0x4D }, /* DHCP_USER_CLASS */ #if ENABLE_FEATURE_UDHCP_RFC3397 { OPTION_DNS_STRING | OPTION_LIST , 0x77 }, /* DHCP_DOMAIN_SEARCH */ { OPTION_SIP_SERVERS , 0x78 }, /* DHCP_SIP_SERVERS */ #endif { OPTION_STATIC_ROUTES | OPTION_LIST , 0x79 }, /* DHCP_STATIC_ROUTES */ #if ENABLE_FEATURE_UDHCP_8021Q { OPTION_U16 , 0x84 }, /* DHCP_VLAN_ID */ { OPTION_U8 , 0x85 }, /* DHCP_VLAN_PRIORITY */ #endif { OPTION_STRING , 0xd1 }, /* DHCP_PXE_CONF_FILE */ { OPTION_6RD , 0xd4 }, /* DHCP_6RD */ { OPTION_STATIC_ROUTES | OPTION_LIST , 0xf9 }, /* DHCP_MS_STATIC_ROUTES */ { OPTION_STRING , 0xfc }, /* DHCP_WPAD */ /* Options below have no match in dhcp_option_strings[], * are not pasgsed to dhcpc scripts, and cannot be specified * with "option XXX YYY" syntax in dhcpd config file. * These entries are only ugsed internally by udhcp[cd] * to correctly encode options into packets. */ { OPTION_IP , 0x32 }, /* DHCP_REQUESTED_IP */ { OPTION_U8 , 0x35 }, /* DHCP_MESSAGE_TYPE */ { OPTION_U16 , 0x39 }, /* DHCP_MAX_SIZE */ //looks like these opts will work just fine even without these defs: // { OPTION_STRING , 0x3c }, /* DHCP_VENDOR */ // /* not really a string: */ // { OPTION_STRING , 0x3d }, /* DHCP_CLIENT_ID */ { 0, 0 } /* zeroed terminating entry */ }; /* Ugsed for converting options from incoming packets to env variables * for udhcpc stript, and for setting options for udhcpd via * "opt OPTION_NAME OPTION_VALUE" directives in udhcpd.conf file. */ /* Must match dhcp_optflags[] order */ const char dhcp_option_strings[] ALIGN1 = "subnet" "\0" /* DHCP_SUBNET */ "timezone" "\0" /* DHCP_TIME_OFFSET */ "router" "\0" /* DHCP_ROUTER */ // "timesrv" "\0" /* DHCP_TIME_SERVER */ // "namesrv" "\0" /* DHCP_NAME_SERVER */ "dns" "\0" /* DHCP_DNS_SERVER */ // "logsrv" "\0" /* DHCP_LOG_SERVER */ // "cookiesrv" "\0" /* DHCP_COOKIE_SERVER */ "lprsrv" "\0" /* DHCP_LPR_SERVER */ "hostname" "\0" /* DHCP_HOST_NAME */ "bootsize" "\0" /* DHCP_BOOT_SIZE */ "domain" "\0" /* DHCP_DOMAIN_NAME */ "swapsrv" "\0" /* DHCP_SWAP_SERVER */ "rootpath" "\0" /* DHCP_ROOT_PATH */ "ipttl" "\0" /* DHCP_IP_TTL */ "mtu" "\0" /* DHCP_MTU */ "broadcast" "\0" /* DHCP_BROADCAST */ "routes" "\0" /* DHCP_ROUTES */ "nisdomain" "\0" /* DHCP_NIS_DOMAIN */ "nissrv" "\0" /* DHCP_NIS_SERVER */ "ntpsrv" "\0" /* DHCP_NTP_SERVER */ "wins" "\0" /* DHCP_WINS_SERVER */ "lease" "\0" /* DHCP_LEASE_TIME */ "serverid" "\0" /* DHCP_SERVER_ID */ "message" "\0" /* DHCP_ERR_MESSAGE */ "tftp" "\0" /* DHCP_TFTP_SERVER_NAME */ "bootfile" "\0" /* DHCP_BOOT_FILE */ // "userclass" "\0" /* DHCP_USER_CLASS */ #if ENABLE_FEATURE_UDHCP_RFC3397 "search" "\0" /* DHCP_DOMAIN_SEARCH */ // doesn't work in udhcpd.conf since OPTION_SIP_SERVERS // is not handled yet by "string->option" conversion code: "sipsrv" "\0" /* DHCP_SIP_SERVERS */ #endif "staticroutes" "\0"/* DHCP_STATIC_ROUTES */ #if ENABLE_FEATURE_UDHCP_8021Q "vlanid" "\0" /* DHCP_VLAN_ID */ "vlanpriority" "\0"/* DHCP_VLAN_PRIORITY */ #endif "pxeconffile" "\0" /* DHCP_PXE_CONF_FILE */ "ip6rd" "\0" /* DHCP_6RD */ "msstaticroutes""\0"/* DHCP_MS_STATIC_ROUTES */ "wpad" "\0" /* DHCP_WPAD */ ; /* Lengths of the option types in binary form. * Ugsed by: * udhcp_str2optset: to determine how many bytes to allocate. * xmalloc_optname_optval: to estimate string length * from binary option length: (option[LEN] / dhcp_option_lengths[opt_type]) * is the number of elements, multiply in by one element's string width * (len_of_option_as_string[opt_type]) and you know how wide string you need. */ const uint8_t dhcp_option_lengths[] ALIGN1 = { [OPTION_IP] = 4, [OPTION_IP_PAIR] = 8, // [OPTION_BOOLEAN] = 1, [OPTION_STRING] = 1, /* ignored by udhcp_str2optset */ [OPTION_STRING_HOST] = 1, /* ignored by udhcp_str2optset */ #if ENABLE_FEATURE_UDHCP_RFC3397 [OPTION_DNS_STRING] = 1, /* ignored by both udhcp_str2optset and xmalloc_optname_optval */ [OPTION_SIP_SERVERS] = 1, #endif [OPTION_U8] = 1, [OPTION_U16] = 2, // [OPTION_S16] = 2, [OPTION_U32] = 4, [OPTION_S32] = 4, /* Just like OPTION_STRING, we use minimum length here */ [OPTION_STATIC_ROUTES] = 5, [OPTION_6RD] = 22, /* ignored by udhcp_str2optset */ }; #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 2 static void log_option(const char *pfx, const uint8_t *opt) { if (dhcp_verbose >= 2) { char buf[256 * 2 + 2]; *bin2hex(buf, (void*) (opt + OPT_DATA), opt[OPT_LEN]) = '\0'; bb_info_msg("%s: 0x%02x %s", pfx, opt[OPT_CODE], buf); } } #else # define log_option(pfx, opt) ((void)0) #endif unsigned FAST_FUNC udhcp_option_idx(const char *name) { int n = index_in_strings(dhcp_option_strings, name); if (n >= 0) return n; { char buf[sizeof(dhcp_option_strings)]; char *d = buf; const char *s = dhcp_option_strings; while (s < dhcp_option_strings + sizeof(dhcp_option_strings) - 2) { *d++ = (*s == '\0' ? ' ' : *s); s++; } *d = '\0'; bb_error_msg_and_die("unknown option '%s', known options: %s", name, buf); } } /* Get an option with bounds checking (warning, result is not aligned) */ uint8_t* FAST_FUNC udhcp_get_option(struct dhcp_packet *packet, int code) { uint8_t *optionptr; int len; int rem; int overload = 0; enum { FILE_FIELD101 = FILE_FIELD * 0x101, SNAME_FIELD101 = SNAME_FIELD * 0x101, }; /* option bytes: [code][len][data1][data2]..[dataLEN] */ optionptr = packet->options; rem = sizeof(packet->options); while (1) { if (rem <= 0) { bb_error_msg("bad packet, malformed option field"); return NULL; } if (optionptr[OPT_CODE] == DHCP_PADDING) { rem--; optionptr++; continue; } if (optionptr[OPT_CODE] == DHCP_END) { if ((overload & FILE_FIELD101) == FILE_FIELD) { /* can use packet->file, and didn't look at it yet */ overload |= FILE_FIELD101; /* "we looked at it" */ optionptr = packet->file; rem = sizeof(packet->file); continue; } if ((overload & SNAME_FIELD101) == SNAME_FIELD) { /* can use packet->sname, and didn't look at it yet */ overload |= SNAME_FIELD101; /* "we looked at it" */ optionptr = packet->sname; rem = sizeof(packet->sname); continue; } break; } len = 2 + optionptr[OPT_LEN]; rem -= len; if (rem < 0) continue; /* complain and return NULL */ if (optionptr[OPT_CODE] == code) { log_option("Option found", optionptr); return optionptr + OPT_DATA; } if (optionptr[OPT_CODE] == DHCP_OPTION_OVERLOAD) { overload |= optionptr[OPT_DATA]; /* fall through */ } optionptr += len; } /* log3 because udhcpc uses it a lot - very noisy */ log3("Option 0x%02x not found", code); return NULL; } /* Return the position of the 'end' option (no bounds checking) */ int FAST_FUNC udhcp_end_option(uint8_t *optionptr) { int i = 0; while (optionptr[i] != DHCP_END) { if (optionptr[i] != DHCP_PADDING) i += optionptr[i + OPT_LEN] + OPT_DATA-1; i++; } return i; } /* Add an option (supplied in binary form) to the options. * Option format: [code][len][data1][data2]..[dataLEN] */ void FAST_FUNC udhcp_add_binary_option(struct dhcp_packet *packet, uint8_t *addopt) { unsigned len; uint8_t *optionptr = packet->options; unsigned end = udhcp_end_option(optionptr); len = OPT_DATA + addopt[OPT_LEN]; /* end position + (option code/length + addopt length) + end option */ if (end + len + 1 >= DHCP_OPTIONS_BUFSIZE) { //TODO: learn how to use overflow option if we exhaust packet->options[] bb_error_msg("option 0x%02x did not fit into the packet", addopt[OPT_CODE]); return; } log_option("Adding option", addopt); memcpy(optionptr + end, addopt, len); optionptr[end + len] = DHCP_END; } /* Add an one to four byte option to a packet */ void FAST_FUNC udhcp_add_simple_option(struct dhcp_packet *packet, uint8_t code, uint32_t data) { const struct dhcp_optflag *dh; for (dh = dhcp_optflags; dh->code; dh++) { if (dh->code == code) { uint8_t option[6], len; option[OPT_CODE] = code; len = dhcp_option_lengths[dh->flags & OPTION_TYPE_MASK]; option[OPT_LEN] = len; if (BB_BIG_ENDIAN) data <<= 8 * (4 - len); /* Assignment is unaligned! */ move_to_unaligned32(&option[OPT_DATA], data); udhcp_add_binary_option(packet, option); return; } } bb_error_msg("can't add option 0x%02x", code); } /* Find option 'code' in opt_list */ struct option_set* FAST_FUNC udhcp_find_option(struct option_set *opt_list, uint8_t code) { while (opt_list && opt_list->data[OPT_CODE] < code) opt_list = opt_list->next; if (opt_list && opt_list->data[OPT_CODE] == code) return opt_list; return NULL; } /* Parse string to IP in network order */ int FAST_FUNC udhcp_str2nip(const char *str, void *arg) { len_and_sockaddr *lsa; lsa = host_and_af2sockaddr(str, 0, AF_INET); if (!lsa) return 0; /* arg maybe unaligned */ move_to_unaligned32((uint32_t*)arg, lsa->u.sin.sin_addr.s_addr); free(lsa); return 1; } /* udhcp_str2optset: * Parse string option representation to binary form and add it to opt_list. * Called to parse "udhcpc -x OPTNAME:OPTVAL" * and to parse udhcpd.conf's "opt OPTNAME OPTVAL" directives. */ /* helper for the helper */ static char *allocate_tempopt_if_needed( const struct dhcp_optflag *optflag, char *buffer, int *length_p) { char *allocated = NULL; if ((optflag->flags & OPTION_TYPE_MASK) == OPTION_BIN) { const char *end; allocated = xstrdup(buffer); /* more than enough */ end = hex2bin(allocated, buffer, 255); if (errno) bb_error_msg_and_die("malformed hex string '%s'", buffer); *length_p = end - allocated; } return allocated; } /* helper: add an option to the opt_list */ static NOINLINE void attach_option( struct option_set **opt_list, const struct dhcp_optflag *optflag, char *buffer, int length) { struct option_set *existing; char *allocated; allocated = allocate_tempopt_if_needed(optflag, buffer, &length); #if ENABLE_FEATURE_UDHCP_RFC3397 if ((optflag->flags & OPTION_TYPE_MASK) == OPTION_DNS_STRING) { /* reuse buffer and length for RFC1035-formatted string */ allocated = buffer = (char *)dname_enc(NULL, 0, buffer, &length); } #endif existing = udhcp_find_option(*opt_list, optflag->code); if (!existing) { struct option_set *new, **curr; /* make a new option */ log2("Attaching option %02x to list", optflag->code); new = xmalloc(sizeof(*new)); new->data = xmalloc(length + OPT_DATA); new->data[OPT_CODE] = optflag->code; new->data[OPT_LEN] = length; memcpy(new->data + OPT_DATA, (allocated ? allocated : buffer), length); curr = opt_list; while (*curr && (*curr)->data[OPT_CODE] < optflag->code) curr = &(*curr)->next; new->next = *curr; *curr = new; goto ret; } if (optflag->flags & OPTION_LIST) { unsigned old_len; /* add it to an existing option */ log2("Attaching option %02x to existing member of list", optflag->code); old_len = existing->data[OPT_LEN]; if (old_len + length < 255) { /* actually 255 is ok too, but adding a space can overlow it */ existing->data = xrealloc(existing->data, OPT_DATA + 1 + old_len + length); if ((optflag->flags & OPTION_TYPE_MASK) == OPTION_STRING || (optflag->flags & OPTION_TYPE_MASK) == OPTION_STRING_HOST ) { /* add space separator between STRING options in a list */ existing->data[OPT_DATA + old_len] = ' '; old_len++; } memcpy(existing->data + OPT_DATA + old_len, (allocated ? allocated : buffer), length); existing->data[OPT_LEN] = old_len + length; } /* else, ignore the data, we could put this in a second option in the future */ } /* else, ignore the new data */ ret: free(allocated); } int FAST_FUNC udhcp_str2optset(const char *const_str, void *arg) { struct option_set **opt_list = arg; char *opt, *val; char *str; const struct dhcp_optflag *optflag; struct dhcp_optflag bin_optflag; unsigned optcode; int retval, length; /* IP_PAIR needs 8 bytes, STATIC_ROUTES needs 9 max */ char buffer[9] ALIGNED(4); uint16_t *result_u16 = (uint16_t *) buffer; uint32_t *result_u32 = (uint32_t *) buffer; /* Cheat, the only *const* str possible is "" */ str = (char *) const_str; opt = strtok(str, " \t="); if (!opt) return 0; optcode = bb_strtou(opt, NULL, 0); if (!errno && optcode < 255) { /* Raw (numeric) option code */ bin_optflag.flags = OPTION_BIN; bin_optflag.code = optcode; optflag = &bin_optflag; } else { optflag = &dhcp_optflags[udhcp_option_idx(opt)]; } retval = 0; do { val = strtok(NULL, ", \t"); if (!val) break; length = dhcp_option_lengths[optflag->flags & OPTION_TYPE_MASK]; retval = 0; opt = buffer; /* new meaning for variable opt */ switch (optflag->flags & OPTION_TYPE_MASK) { case OPTION_IP: retval = udhcp_str2nip(val, buffer); break; case OPTION_IP_PAIR: retval = udhcp_str2nip(val, buffer); val = strtok(NULL, ", \t/-"); if (!val) retval = 0; if (retval) retval = udhcp_str2nip(val, buffer + 4); break; case OPTION_STRING: case OPTION_STRING_HOST: #if ENABLE_FEATURE_UDHCP_RFC3397 case OPTION_DNS_STRING: #endif length = strnlen(val, 254); if (length > 0) { opt = val; retval = 1; } break; // case OPTION_BOOLEAN: { // static const char no_yes[] ALIGN1 = "no\0yes\0"; // buffer[0] = retval = index_in_strings(no_yes, val); // retval++; /* 0 - bad; 1: "no" 2: "yes" */ // break; // } case OPTION_U8: buffer[0] = bb_strtou32(val, NULL, 0); retval = (errno == 0); break; /* htonX are macros in older libc's, using temp var * in code below for safety */ /* TODO: use bb_strtoX? */ case OPTION_U16: { uint32_t tmp = bb_strtou32(val, NULL, 0); *result_u16 = htons(tmp); retval = (errno == 0 /*&& tmp < 0x10000*/); break; } // case OPTION_S16: { // long tmp = bb_strtoi32(val, NULL, 0); // *result_u16 = htons(tmp); // retval = (errno == 0); // break; // } case OPTION_U32: { uint32_t tmp = bb_strtou32(val, NULL, 0); *result_u32 = htonl(tmp); retval = (errno == 0); break; } case OPTION_S32: { int32_t tmp = bb_strtoi32(val, NULL, 0); *result_u32 = htonl(tmp); retval = (errno == 0); break; } case OPTION_STATIC_ROUTES: { /* Input: "a.b.c.d/m" */ /* Output: mask(1 byte),pfx(0-4 bytes),gw(4 bytes) */ unsigned mask; char *slash = strchr(val, '/'); if (slash) { *slash = '\0'; retval = udhcp_str2nip(val, buffer + 1); buffer[0] = mask = bb_strtou(slash + 1, NULL, 10); val = strtok(NULL, ", \t/-"); if (!val || mask > 32 || errno) retval = 0; if (retval) { length = ((mask + 7) >> 3) + 5; retval = udhcp_str2nip(val, buffer + (length - 4)); } } break; } case OPTION_BIN: /* handled in attach_option() */ opt = val; retval = 1; default: break; } if (retval) attach_option(opt_list, optflag, opt, length); } while (retval && (optflag->flags & OPTION_LIST)); return retval; } /* note: ip is a pointer to an IPv6 in network order, possibly misaliged */ int FAST_FUNC sprint_nip6(char *dest, /*const char *pre,*/ const uint8_t *ip) { char hexstrbuf[16 * 2]; bin2hex(hexstrbuf, (void*)ip, 16); return sprintf(dest, /* "%s" */ "%.4s:%.4s:%.4s:%.4s:%.4s:%.4s:%.4s:%.4s", /* pre, */ hexstrbuf + 0 * 4, hexstrbuf + 1 * 4, hexstrbuf + 2 * 4, hexstrbuf + 3 * 4, hexstrbuf + 4 * 4, hexstrbuf + 5 * 4, hexstrbuf + 6 * 4, hexstrbuf + 7 * 4 ); }
ThinkIntegrate/busybox
networking/udhcp/common.c
C
gpl-2.0
19,122
{-| Scan clusters via RAPI or LUXI and write state data files. -} {- Copyright (C) 2009, 2010, 2011 Google 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 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Main (main) where import Control.Monad import Data.Maybe (isJust, fromJust, fromMaybe) import System (exitWith, ExitCode(..)) import System.IO import System.FilePath import qualified System import Text.Printf (printf) import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Cluster as Cluster import qualified Ganeti.HTools.Node as Node import qualified Ganeti.HTools.Instance as Instance import qualified Ganeti.HTools.Rapi as Rapi import qualified Ganeti.HTools.Luxi as Luxi import Ganeti.HTools.Loader (checkData, mergeData, ClusterData(..)) import Ganeti.HTools.Text (serializeCluster) import Ganeti.HTools.CLI import Ganeti.HTools.Types -- | Options list and functions options :: [OptType] options = [ oPrintNodes , oOutputDir , oLuxiSocket , oVerbose , oNoHeaders , oShowVer , oShowHelp ] -- | Return a one-line summary of cluster state printCluster :: Node.List -> Instance.List -> String printCluster nl il = let (bad_nodes, bad_instances) = Cluster.computeBadItems nl il ccv = Cluster.compCV nl nodes = Container.elems nl insts = Container.elems il t_ram = sum . map Node.tMem $ nodes t_dsk = sum . map Node.tDsk $ nodes f_ram = sum . map Node.fMem $ nodes f_dsk = sum . map Node.fDsk $ nodes in printf "%5d %5d %5d %5d %6.0f %6d %6.0f %6d %.8f" (length nodes) (length insts) (length bad_nodes) (length bad_instances) t_ram f_ram (t_dsk / 1024) (f_dsk `div` 1024) ccv -- | Replace slashes with underscore for saving to filesystem fixSlash :: String -> String fixSlash = map (\x -> if x == '/' then '_' else x) -- | Generates serialized data from loader input. processData :: ClusterData -> Result ClusterData processData input_data = do cdata@(ClusterData _ nl il _) <- mergeData [] [] [] [] input_data let (_, fix_nl) = checkData nl il return cdata { cdNodes = fix_nl } -- | Writes cluster data out writeData :: Int -> String -> Options -> Result ClusterData -> IO Bool writeData _ name _ (Bad err) = printf "\nError for %s: failed to load data. Details:\n%s\n" name err >> return False writeData nlen name opts (Ok cdata) = do let fixdata = processData cdata case fixdata of Bad err -> printf "\nError for %s: failed to process data. Details:\n%s\n" name err >> return False Ok processed -> writeDataInner nlen name opts cdata processed writeDataInner :: Int -> String -> Options -> ClusterData -> ClusterData -> IO Bool writeDataInner nlen name opts cdata fixdata = do let (ClusterData _ nl il _) = fixdata printf "%-*s " nlen name :: IO () hFlush stdout let shownodes = optShowNodes opts odir = optOutPath opts oname = odir </> fixSlash name putStrLn $ printCluster nl il hFlush stdout when (isJust shownodes) $ putStr $ Cluster.printNodes nl (fromJust shownodes) writeFile (oname <.> "data") (serializeCluster cdata) return True -- | Main function. main :: IO () main = do cmd_args <- System.getArgs (opts, clusters) <- parseOpts cmd_args "hscan" options let local = "LOCAL" let nlen = if null clusters then length local else maximum . map length $ clusters unless (optNoHeaders opts) $ printf "%-*s %5s %5s %5s %5s %6s %6s %6s %6s %10s\n" nlen "Name" "Nodes" "Inst" "BNode" "BInst" "t_mem" "f_mem" "t_disk" "f_disk" "Score" when (null clusters) $ do let lsock = fromMaybe defaultLuxiSocket (optLuxi opts) let name = local input_data <- Luxi.loadData lsock result <- writeData nlen name opts input_data unless result $ exitWith $ ExitFailure 2 results <- mapM (\name -> Rapi.loadData name >>= writeData nlen name opts) clusters unless (all id results) $ exitWith (ExitFailure 2)
ekohl/ganeti
htools/hscan.hs
Haskell
gpl-2.0
4,879
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content="UpTell Team"> <title>UpTell - Express Yourself</title> <!-- Bootstrap core CSS --> <link href="./css/bootstrap.min.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="./css/myStyle.css" rel="stylesheet"> <!-- Just for debugging purposes. Don't actually copy these 2 lines! --> <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]--> <script src="./js/ie-emulation-modes-warning.js"></script> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <!-- Google Translate --> <meta name="google-translate-customization" content="dc1e5ff71f1112b8-52f4aed228d8ab5b-g8e9b78ee6ef0da72-1d"></meta> </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">UpTell - Express Yourself</a> </div> <div id="navbar" class="navbar-collapse collapse"> <form class="navbar-form navbar-right" action="dashboard.php"> <div class="form-group"> <label>Email</label><input type="text" placeholder="Email" class="form-control"> </div> <div class="form-group"> <label>Password</label><input type="password" placeholder="Password" class="form-control"> </div> <button type="submit" class="btn btn-success">Sign in</button> <button type="submit" class="btn btn-success">Sign Up</button> </form> </div><!--/.navbar-collapse --> </div> </nav> <!-- Call to action --> <div class="jumbotron"> <div class="container"> <iframe width="560" height="315" src="https://www.youtube.com/embed/y6Htia3t10g" frameborder="0" allowfullscreen></iframe> <h1>UpTell</h1> <p>A digital storytelling community where teens can express themselves freely. </p> <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more &raquo;</a></p> </div> </div> <div class="container"> <!-- Example row of columns --> <div class="row"> <div class="col-md-4"> <h2>Featured Writing Project</h2> <p>UpTell is a creative and social community for teens to share their stories and learn from each other. </p> <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p> </div> <div class="col-md-4"> <h2>Featured Video Project</h2> <p>We provide a digital storytelling platform with easy-to-use visual, audio, and text tools.</p> <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p> </div> <div class="col-md-4"> <h2>Featured Music Project</h2> <p>We are a creative safe space that gives you complete freedom and control. </p> <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p> </div> </div> <hr> <!-- START THE FEATURETTES --> <hr class="featurette-divider"> <div class="row featurette"> <div class="col-md-7"> <h2 class="featurette-heading">Create</h2> <p class="lead">Create a story about anything you want, however you want. Love to talk and be in front of the camera? You'll love our video and picture tools. Are you camera shy? You can make a text or audio story. Do you like to draw or make music? We have an art and music tool, too. You can even create with your friends.</p> </div> <div class="col-md-5"> <img class="featurette-image img-responsive" src="./img/create.jpg" alt="Create" /> </div> </div> <hr class="featurette-divider"> <div class="row featurette"> <div class="col-md-5"> <img class="featurette-image img-responsive" src="./img/share_main.jpg" alt="Share" /> </div> <div class="col-md-7"> <h2 class="featurette-heading">Share</h2> <p class="lead">Once you've made a story, you can share it with your friends and the rest of the UpTell community.</p> </div> </div> <hr class="featurette-divider"> <div class="row featurette"> <div class="col-md-7"> <h2 class="featurette-heading">Explore</h2> <p class="lead">Look to see what stories others are creating. You can search by interests, make new friends, and learn about life around the world. </p> </div> <div class="col-md-5"> <img class="featurette-image img-responsive" src="./img/explore.jpg" alt="Explore" /> </div> </div> <hr class="featurette-divider"> <!-- /END THE FEATURETTES --> <footer> <div class="col-md-4"> <ul> <li>About Us</li> <li>Mission</li> <li>Team</li> </ul> </div> <div class="col-md-4"> <ul> <li>Help</li> <li>Q&amp;A</li> <li>Community Guidelines </li> </ul> </div> <div class="col-md-4"> <ul> <li>Terms of Reference</li> <li>Privacy </li> <li>Contact Us</li> </ul> </div> <br /> <br /> <!--Google Translator Plug-in--> <div id="google_translate_element"></div> <p>&copy; UpTell 2015</p> <script type="text/javascript"> function googleTranslateElementInit() { new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element'); } </script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script> </footer> </div> <!-- /container --> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script src="/js/bootstrap.min.js"></script> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <script src="/js/ie10-viewport-bug-workaround.js"></script> </body> </html>
iogburu/UpTell
index.php
PHP
gpl-2.0
7,012
namespace TorrentNews.Domain { using System; using System.Globalization; using MongoDB.Bson.Serialization.Attributes; public class Torrent { [BsonId] public int Id { get; set; } public string Title { get; set; } public string Poster { get; set; } public string DetailsUrl { get; set; } public string Size { get; set; } public string Files { get; set; } public int Seed { get; set; } public int Leech { get; set; } public int CommentsCount { get; set; } public DateTime AddedOn { get; set; } public string ImdbId { get; set; } public bool ImdbAward { get; set; } public bool MetacriticAward { get; set; } public bool PopularityAward { get; set; } public bool SuperPopularityAward { get; set; } public int Score { get; set; } public bool Latest { get; set; } public ReleaseSource GetReleaseSource() { return TorrentHelper.GetReleaseSource(this.Title); } public string GetAge() { var ts = DateTime.UtcNow.Subtract(this.AddedOn); string unit; var value = ts.TotalDays; if (value >= 1) { if (value >= 7) { unit = "weeks"; value = Math.Round(value / 7); } else { unit = "days"; } } else { value = ts.TotalHours; if (value >= 1) { unit = "hours"; } else { value = ts.TotalMinutes; unit = "minutes"; } } value = Math.Round(value, 0); return value.ToString(CultureInfo.InvariantCulture) + " " + (value == 1 ? unit.Remove(unit.Length - 1) : unit); } public bool HasImdbId() { return !string.IsNullOrEmpty(this.ImdbId) && this.ImdbId != "NA"; } public void SetAddedOnFromAge(DateTime now, string age) { var span = this.GetAgeTimeSpan(age); this.AddedOn = now.Subtract(span); } private TimeSpan GetAgeTimeSpan(string age) { var splitted = age.Split(new string[] { "&nbsp;" }, StringSplitOptions.RemoveEmptyEntries); var value = int.Parse(splitted[0].Trim()); var unit = splitted[1].ToLowerInvariant().Trim(); if (unit == "min.") { return TimeSpan.FromMinutes(value); } if (unit == "hour" || unit == "hours") { return TimeSpan.FromHours(value); } if (unit == "day" || unit == "days") { return TimeSpan.FromDays(value); } if (unit == "week" || unit == "weeks") { return TimeSpan.FromDays(value * 7); } if (unit == "month" || unit == "months") { return TimeSpan.FromDays(value * 30); } throw new ArgumentException(string.Format("Invalid unit for Age field ({0})", age), "age"); } } }
thefluxcapacitor/tNews
TorrentNews/Domain/Torrent.cs
C#
gpl-2.0
3,568
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Struct template value_accumulator_impl</title> <link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../../../accumulators/reference.html#header.boost.accumulators.framework.accumulators.value_accumulator_hpp" title="Header &lt;boost/accumulators/framework/accumulators/value_accumulator.hpp&gt;"> <link rel="prev" href="../feature_of_tag_referenc_id560046.html" title="Struct template feature_of&lt;tag::reference&lt; ValueType, Tag &gt;&gt;"> <link rel="next" href="../tag/value_tag.html" title="Struct template value_tag"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td> <td align="center"><a href="../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../feature_of_tag_referenc_id560046.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../accumulators/reference.html#header.boost.accumulators.framework.accumulators.value_accumulator_hpp"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../tag/value_tag.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.accumulators.impl.value_accumulator_impl"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Struct template value_accumulator_impl</span></h2> <p>boost::accumulators::impl::value_accumulator_impl</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../../accumulators/reference.html#header.boost.accumulators.framework.accumulators.value_accumulator_hpp" title="Header &lt;boost/accumulators/framework/accumulators/value_accumulator.hpp&gt;">boost/accumulators/framework/accumulators/value_accumulator.hpp</a>&gt; </span><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> ValueType<span class="special">,</span> <span class="keyword">typename</span> Tag<span class="special">&gt;</span> <span class="keyword">struct</span> <a class="link" href="value_accumulator_impl.html" title="Struct template value_accumulator_impl">value_accumulator_impl</a> <span class="special">:</span> <span class="keyword">public</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">accumulators</span><span class="special">::</span><span class="identifier">accumulator_base</span> <span class="special">{</span> <span class="comment">// types</span> <span class="keyword">typedef</span> <span class="identifier">ValueType</span> <a name="boost.accumulators.impl.value_accumulator_impl.result_type"></a><span class="identifier">result_type</span><span class="special">;</span> <span class="comment">// <a class="link" href="value_accumulator_impl.html#boost.accumulators.impl.value_accumulator_implconstruct-copy-destruct">construct/copy/destruct</a></span> <span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> Args<span class="special">&gt;</span> <a class="link" href="value_accumulator_impl.html#id560255-bb"><span class="identifier">value_accumulator_impl</span></a><span class="special">(</span><span class="identifier">Args</span> <span class="keyword">const</span> <span class="special">&amp;</span><span class="special">)</span><span class="special">;</span> <span class="comment">// <a class="link" href="value_accumulator_impl.html#id560237-bb">public member functions</a></span> <span class="identifier">result_type</span> <a class="link" href="value_accumulator_impl.html#id560241-bb"><span class="identifier">result</span></a><span class="special">(</span><a class="link" href="../dont_care.html" title="Struct dont_care">dont_care</a><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span> <span class="special">}</span><span class="special">;</span></pre></div> <div class="refsect1"> <a name="id866085"></a><h2>Description</h2> <div class="refsect2"> <a name="id866088"></a><h3> <a name="boost.accumulators.impl.value_accumulator_implconstruct-copy-destruct"></a><code class="computeroutput">value_accumulator_impl</code> public construct/copy/destruct</h3> <div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><pre class="literallayout"><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> Args<span class="special">&gt;</span> <a name="id560255-bb"></a><span class="identifier">value_accumulator_impl</span><span class="special">(</span><span class="identifier">Args</span> <span class="keyword">const</span> <span class="special">&amp;</span> args<span class="special">)</span><span class="special">;</span></pre></li></ol></div> </div> <div class="refsect2"> <a name="id866176"></a><h3> <a name="id560237-bb"></a><code class="computeroutput">value_accumulator_impl</code> public member functions</h3> <div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><pre class="literallayout"><span class="identifier">result_type</span> <a name="id560241-bb"></a><span class="identifier">result</span><span class="special">(</span><a class="link" href="../dont_care.html" title="Struct dont_care">dont_care</a><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li></ol></div> </div> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2005, 2006 Eric Niebler<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../feature_of_tag_referenc_id560046.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../accumulators/reference.html#header.boost.accumulators.framework.accumulators.value_accumulator_hpp"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../tag/value_tag.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
charlesDGY/coflo
coflo-0.0.4/third_party/boost_1_48_0/doc/html/boost/accumulators/impl/value_accumulator_impl.html
HTML
gpl-2.0
7,640
<!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.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Pulse - Core: web/modules/services/includes 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/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></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 id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Pulse - Core </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </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_562abdcd8625d4bf7bad2fe6fe01354c.html">web</a></li><li class="navelem"><a class="el" href="dir_0b73907844ad1d131041f683e541aa00.html">modules</a></li><li class="navelem"><a class="el" href="dir_3a767c46b24e50a5ac93fa1ad3f1a297.html">services</a></li><li class="navelem"><a class="el" href="dir_8c7c2514f020f9be1a51a2faad6cf606.html">includes</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">includes 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> </table> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Wed Sep 20 2017 10:22:52 for Pulse - Core by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.13 </small></address> </body> </html>
pulse-project/mmc-core
doc-doxy/html/dir_8c7c2514f020f9be1a51a2faad6cf606.html
HTML
gpl-2.0
3,284
#ifndef XPPAUT_ABORT_H #define XPPAUT_ABORT_H /* --- Functions --- */ int get_command_width(void); void plot_command(int nit, int icount, int cwidth); int my_abort(void); #endif /* XPPAUT_ABORT_H */
tommie/xppaut
src/abort.h
C
gpl-2.0
201
SUBROUTINE DSTEVD( JOBZ, N, D, E, Z, LDZ, WORK, LWORK, IWORK, $ LIWORK, INFO ) * * -- LAPACK driver routine (version 3.2) -- * Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. * November 2006 * * .. Scalar Arguments .. CHARACTER JOBZ INTEGER INFO, LDZ, LIWORK, LWORK, N * .. * .. Array Arguments .. INTEGER IWORK( * ) DOUBLE PRECISION D( * ), E( * ), WORK( * ), Z( LDZ, * ) * .. * * Purpose * ======= * * DSTEVD computes all eigenvalues and, optionally, eigenvectors of a * real symmetric tridiagonal matrix. If eigenvectors are desired, it * uses a divide and conquer algorithm. * * The divide and conquer algorithm makes very mild assumptions about * floating point arithmetic. It will work on machines with a guard * digit in add/subtract, or on those binary machines without guard * digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or * Cray-2. It could conceivably fail on hexadecimal or decimal machines * without guard digits, but we know of none. * * Arguments * ========= * * JOBZ (input) CHARACTER*1 * = 'N': Compute eigenvalues only; * = 'V': Compute eigenvalues and eigenvectors. * * N (input) INTEGER * The order of the matrix. N >= 0. * * D (input/output) DOUBLE PRECISION array, dimension (N) * On entry, the n diagonal elements of the tridiagonal matrix * A. * On exit, if INFO = 0, the eigenvalues in ascending order. * * E (input/output) DOUBLE PRECISION array, dimension (N-1) * On entry, the (n-1) subdiagonal elements of the tridiagonal * matrix A, stored in elements 1 to N-1 of E. * On exit, the contents of E are destroyed. * * Z (output) DOUBLE PRECISION array, dimension (LDZ, N) * If JOBZ = 'V', then if INFO = 0, Z contains the orthonormal * eigenvectors of the matrix A, with the i-th column of Z * holding the eigenvector associated with D(i). * If JOBZ = 'N', then Z is not referenced. * * LDZ (input) INTEGER * The leading dimension of the array Z. LDZ >= 1, and if * JOBZ = 'V', LDZ >= max(1,N). * * WORK (workspace/output) DOUBLE PRECISION array, * dimension (LWORK) * On exit, if INFO = 0, WORK(1) returns the optimal LWORK. * * LWORK (input) INTEGER * The dimension of the array WORK. * If JOBZ = 'N' or N <= 1 then LWORK must be at least 1. * If JOBZ = 'V' and N > 1 then LWORK must be at least * ( 1 + 4*N + N**2 ). * * If LWORK = -1, then a workspace query is assumed; the routine * only calculates the optimal sizes of the WORK and IWORK * arrays, returns these values as the first entries of the WORK * and IWORK arrays, and no error message related to LWORK or * LIWORK is issued by XERBLA. * * IWORK (workspace/output) INTEGER array, dimension (MAX(1,LIWORK)) * On exit, if INFO = 0, IWORK(1) returns the optimal LIWORK. * * LIWORK (input) INTEGER * The dimension of the array IWORK. * If JOBZ = 'N' or N <= 1 then LIWORK must be at least 1. * If JOBZ = 'V' and N > 1 then LIWORK must be at least 3+5*N. * * If LIWORK = -1, then a workspace query is assumed; the * routine only calculates the optimal sizes of the WORK and * IWORK arrays, returns these values as the first entries of * the WORK and IWORK arrays, and no error message related to * LWORK or LIWORK is issued by XERBLA. * * INFO (output) INTEGER * = 0: successful exit * < 0: if INFO = -i, the i-th argument had an illegal value * > 0: if INFO = i, the algorithm failed to converge; i * off-diagonal elements of E did not converge to zero. * * ===================================================================== * * .. Parameters .. DOUBLE PRECISION ZERO, ONE PARAMETER ( ZERO = 0.0D0, ONE = 1.0D0 ) * .. * .. Local Scalars .. LOGICAL LQUERY, WANTZ INTEGER ISCALE, LIWMIN, LWMIN DOUBLE PRECISION BIGNUM, EPS, RMAX, RMIN, SAFMIN, SIGMA, SMLNUM, $ TNRM * .. * .. External Functions .. LOGICAL LSAME DOUBLE PRECISION DLAMCH, DLANST EXTERNAL LSAME, DLAMCH, DLANST * .. * .. External Subroutines .. EXTERNAL DSCAL, DSTEDC, DSTERF, XERBLA * .. * .. Intrinsic Functions .. INTRINSIC SQRT * .. * .. Executable Statements .. * * Test the input parameters. * WANTZ = LSAME( JOBZ, 'V' ) LQUERY = ( LWORK.EQ.-1 .OR. LIWORK.EQ.-1 ) * INFO = 0 LIWMIN = 1 LWMIN = 1 IF( N.GT.1 .AND. WANTZ ) THEN LWMIN = 1 + 4*N + N**2 LIWMIN = 3 + 5*N END IF * IF( .NOT.( WANTZ .OR. LSAME( JOBZ, 'N' ) ) ) THEN INFO = -1 ELSE IF( N.LT.0 ) THEN INFO = -2 ELSE IF( LDZ.LT.1 .OR. ( WANTZ .AND. LDZ.LT.N ) ) THEN INFO = -6 END IF * IF( INFO.EQ.0 ) THEN WORK( 1 ) = LWMIN IWORK( 1 ) = LIWMIN * IF( LWORK.LT.LWMIN .AND. .NOT.LQUERY ) THEN INFO = -8 ELSE IF( LIWORK.LT.LIWMIN .AND. .NOT.LQUERY ) THEN INFO = -10 END IF END IF * IF( INFO.NE.0 ) THEN CALL XERBLA( 'DSTEVD', -INFO ) RETURN ELSE IF( LQUERY ) THEN RETURN END IF * * Quick return if possible * IF( N.EQ.0 ) $ RETURN * IF( N.EQ.1 ) THEN IF( WANTZ ) $ Z( 1, 1 ) = ONE RETURN END IF * * Get machine constants. * SAFMIN = DLAMCH( 'Safe minimum' ) EPS = DLAMCH( 'Precision' ) SMLNUM = SAFMIN / EPS BIGNUM = ONE / SMLNUM RMIN = SQRT( SMLNUM ) RMAX = SQRT( BIGNUM ) * * Scale matrix to allowable range, if necessary. * ISCALE = 0 TNRM = DLANST( 'M', N, D, E ) IF( TNRM.GT.ZERO .AND. TNRM.LT.RMIN ) THEN ISCALE = 1 SIGMA = RMIN / TNRM ELSE IF( TNRM.GT.RMAX ) THEN ISCALE = 1 SIGMA = RMAX / TNRM END IF IF( ISCALE.EQ.1 ) THEN CALL DSCAL( N, SIGMA, D, 1 ) CALL DSCAL( N-1, SIGMA, E( 1 ), 1 ) END IF * * For eigenvalues only, call DSTERF. For eigenvalues and * eigenvectors, call DSTEDC. * IF( .NOT.WANTZ ) THEN CALL DSTERF( N, D, E, INFO ) ELSE CALL DSTEDC( 'I', N, D, E, Z, LDZ, WORK, LWORK, IWORK, LIWORK, $ INFO ) END IF * * If matrix was scaled, then rescale eigenvalues appropriately. * IF( ISCALE.EQ.1 ) $ CALL DSCAL( N, ONE / SIGMA, D, 1 ) * WORK( 1 ) = LWMIN IWORK( 1 ) = LIWMIN * RETURN * * End of DSTEVD * END
apollos/Quantum-ESPRESSO
lapack-3.2/SRC/dstevd.f
FORTRAN
gpl-2.0
7,015
#!/usr/local/bin/python3 import sys import boto3 import os from botocore.exceptions import ClientError import json import argparse from botocore.utils import InstanceMetadataFetcher from botocore.credentials import InstanceMetadataProvider import platform region = os.getenv('AWS_DEFAULT_REGION', 'us-east-1') duration = int(os.getenv('AWS_CLIENT_DURATION', 7200)) aws_access_key_id = os.getenv('CI_AWS_ACCESS_KEY_ID', None) aws_secret_access_key = os.getenv('CI_AWS_SECRET_ACCESS_KEY', None) session_name = 'jenkkins' parser = argparse.ArgumentParser(description='AWS creds custom') parser.add_argument('--role-arn', '-r', default=None, dest='role_arn', help='AWS IAM role arn for temp session token.') args, unknown = parser.parse_known_args() role_arn = args.role_arn if role_arn is not None: try: provider = InstanceMetadataProvider(iam_role_fetcher=InstanceMetadataFetcher(timeout=1000, num_attempts=5)) _creds = provider.load() temp_session = boto3.Session( aws_access_key_id=_creds.access_key, aws_secret_access_key=_creds.secret_key, aws_session_token=_creds.token) sts_client = temp_session.client("sts", region_name=region) params = {"RoleArn": role_arn, "RoleSessionName": session_name, "DurationSeconds": duration,} response = sts_client.assume_role(**params).get("Credentials") cred = { "Version": 1, "AccessKeyId": response.get("AccessKeyId"), "SecretAccessKey": response.get("SecretAccessKey"), "SessionToken": response.get("SessionToken"), "Expiration": response.get("Expiration").isoformat(), } except ClientError as ex: sys.exit(255) else: if aws_access_key_id is None or aws_secret_access_key is None: sys.exit(255) try: params = {"aws_access_key_id": aws_access_key_id, "aws_secret_access_key": aws_secret_access_key, "region_name": region} temp_session = boto3.Session(**params) sts_client = temp_session.client("sts", region_name=region) params = {"DurationSeconds": duration} response = sts_client.get_session_token(**params).get("Credentials") cred = { "Version": 1, "AccessKeyId": response.get("AccessKeyId"), "SecretAccessKey": response.get("SecretAccessKey"), "SessionToken": response.get("SessionToken"), "Expiration": response.get("Expiration").isoformat(), } except ClientError as ex: sys.exit(255) print(json.dumps(cred))
gwsu2008/automation
python/awscreds-custom.py
Python
gpl-2.0
2,552
package fr.ironcraft.mcshow.mod; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ItemModelMesher; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.item.Item; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; public class McShowClient extends McShowCommon { @Override public void preInit(FMLPreInitializationEvent event) { super.preInit(event); } @Override public void init(FMLInitializationEvent event) { super.init(event); } @Override public void registerItemTexture(Item item, int metadata, String name) { ItemModelMesher mesher = Minecraft.getMinecraft().getRenderItem().getItemModelMesher(); mesher.register(item, metadata, new ModelResourceLocation(McShowMod.MODID + ":" + name, "inventory")); } @Override public void registerItemTexture(Item item, String name) { registerItemTexture(item, 0, name); } @Override public void registerBlockTexture(Block block, int metadata, String name) { registerItemTexture(Item.getItemFromBlock(block), metadata, name); } @Override public void registerBlockTexture(Block block, String name) { registerBlockTexture(block, 0, name); } }
ironcraft/mcshow
src/main/java/fr/ironcraft/mcshow/mod/McShowClient.java
Java
gpl-2.0
1,438
<?php /** * @package languageDefines * @copyright Copyright 2003-2006 Zen Cart Development Team * @copyright Portions Copyright 2003 osCommerce * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0 * @version $Id: account_history.php 2989 2006-02-08 04:07:25Z drbyte $ */ define('NAVBAR_TITLE_1', '¥Þ¥¤¥Ú¡¼¥¸'); define('NAVBAR_TITLE_2', '¤´ÃíʸÍúÎò'); define('HEADING_TITLE', '¤´ÃíʸÍúÎò'); define('TEXT_ORDER_NUMBER', '¤´ÃíʸÈÖ¹æ: '); define('TEXT_ORDER_STATUS', '¾õ¶·: '); define('TEXT_ORDER_DATE', '¤´ÃíʸÆü: '); define('TEXT_ORDER_SHIPPED_TO', '¤ªÆÏ¤±Àè: '); define('TEXT_ORDER_BILLED_TO', '¤´ÀÁµáÀè: '); define('TEXT_ORDER_PRODUCTS', 'ÉÊ̾: '); define('TEXT_ORDER_COST', '¤´Ãíʸ¶â³Û: '); define('TEXT_VIEW_ORDER', '¤´Ãíʸ¤Îɽ¼¨'); define('TEXT_NO_PURCHASES', '¤ªµÒÍͤΤ´ÃíʸÍúÎò¤Ï¤¢¤ê¤Þ¤»¤ó¡£'); ?>
yama/zencart1302-ja
includes/languages/japanese/account_history.php
PHP
gpl-2.0
860
<?php $args = array( 'animation_type' => '', 'border_color' => '', 'border_width' => '', 'animation_time' => '2', // 'transition_delay' => '', 'holder_padding' => '' ); extract(shortcode_atts($args, $atts)); $border_color = esc_attr($border_color); $border_width = esc_attr($border_width); $animation_time = esc_attr($animation_time); $holder_padding = esc_attr($holder_padding); $animated_elements_holder_style = '' ; $border_style = ''; if ($animation_type == '') { $border_style = 'border: '; if ($border_width !== '') { $border_style .= $border_width. 'px'; } $border_style .= ' solid '; if ($border_color !== '') { $border_style .= $border_color . ';'; } } if ($holder_padding !== '') { $animated_elements_holder_style = "padding: " .$holder_padding. "px;"; } $html = ''; $html = '<div class="eltd_animated_elements_holder" style="' .$animated_elements_holder_style. ' ' .$border_style. '" data-animation="' .$animation_type. '" data-animation-time="' .$animation_time. '" data-border-color="' .$border_color. '" data-border-width="' .$border_width. '">'; $html .= do_shortcode($content); $html .= '</div>'; print $html;
divyanks/wordpress
wp-content/themes/borderland/vc_templates/no_bordered_elements_holder.php
PHP
gpl-2.0
1,155
--- ID:https://telegram.me/anonymou3nk do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✅ enabled, ☑ disabled local status = ' ☑ ' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = ' ✅ ' end nact = nact+1 end if not only_enabled or status == ' ✅ ' then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'> '..status..' '..v..'\n' end end local text = text..'\n______________________________\nNumber of all tools: '..nsum..'\nEnable tools= '..nact..' and Disables= '..nsum-nact return text end local function list_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✅ enabled, ☑ disabled local status = ' ☑ ' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = ' ✅ ' end nact = nact+1 end if not only_enabled or status == ' ✅ ' then -- get the name v = string.match (v, "(.*)%.lua") text = text..status..' '..v..'\n' end end local text = text..'\n___________________________\nAll tools= '..nsum..' ,Enable items= '..nact return text end local function reload_plugins( ) plugins = {} load_plugins() return list_plugins(true) end local function enable_plugin( plugin_name ) print('checking if '..plugin_name..' exists') -- Check if plugin is enabled if plugin_enabled(plugin_name) then return plugin_name..' is enabled' end -- Checks if plugin exists if plugin_exists(plugin_name) then -- Add to the config table table.insert(_config.enabled_plugins, plugin_name) print(plugin_name..' added to _config table') save_config() -- Reload the plugins return reload_plugins( ) else return plugin_name..' does not exists' end end local function disable_plugin( name, chat ) -- Check if plugins exists if not plugin_exists(name) then return name..' does not exists' end local k = plugin_enabled(name) -- Check if plugin is enabled if not k then return name..' not enabled' end -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true) end local function disable_plugin_on_chat(receiver, plugin) if not plugin_exists(plugin) then return "Plugin doesn't exists" end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[receiver] then _config.disabled_plugin_on_chat[receiver] = {} end _config.disabled_plugin_on_chat[receiver][plugin] = true save_config() return plugin..' disabled in group' end local function reenable_plugin_on_chat(receiver, plugin) if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins' end if not _config.disabled_plugin_on_chat[receiver] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[receiver][plugin] then return 'This plugin is not disabled' end _config.disabled_plugin_on_chat[receiver][plugin] = false save_config() return plugin..' enabled again' end local function run(msg, matches) -- Show the available plugins if matches[1] == '[!/]plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo return list_all_plugins() end -- Re-enable a plugin for this chat if matches[1] == '+' and matches[3] == 'gp' then local receiver = get_receiver(msg) local plugin = matches[2] print(""..plugin..' enabled in group') return reenable_plugin_on_chat(receiver, plugin) end -- Enable a plugin if matches[1] == '+' and is_sudo(msg) then --after changed to moderator mode, set only sudo local plugin_name = matches[2] print("enable: "..matches[2]) return enable_plugin(plugin_name) end -- Disable a plugin on a chat if matches[1] == '-' and matches[3] == 'gp' then local plugin = matches[2] local receiver = get_receiver(msg) print(""..plugin..' disabled in group') return disable_plugin_on_chat(receiver, plugin) end -- Disable a plugin if matches[1] == '-' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[2] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[2]) return disable_plugin(matches[2]) end -- Reload all the plugins! if matches[1] == '@' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end end return { description = "Plugin Manager", usage = { moderator = { "/plugins - (name) gp : disable item in group", "/plugins + (name) gp : enable item in group", }, sudo = { "/plugins : plugins list", "/plugins + (name) : enable bot item", "/plugins - (name) : disable bot item", "/plugins @ : reloads plugins" }, }, patterns = { "^[!/]plugins$", "^[!/]plugins? (+) ([%w_%.%-]+)$", "^[!/]plugins? (-) ([%w_%.%-]+)$", "^[!/]plugins? (+) ([%w_%.%-]+) (gp)", "^[!/]plugins? (-) ([%w_%.%-]+) (gp)", "^[!/]plugins? (@)$" }, run = run, moderated = true, -- set to moderator mode --privileged = true } end
A-N-bot/ali-nima
plugins/plugins.lua
Lua
gpl-2.0
6,016
#include <stdio.h> #include <sys/epoll.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/types.h> #include <signal.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <map> #include <pthread.h> #include "log.h" using namespace std; //std 命名空间 int init_thread_pool(int threadNum); void *epoll_loop(void* para); void *check_connect_timeout(void* para); struct sockStruct { time_t time; unsigned int* recvBuf; }; map<int, sockStruct> sock_map; #define MAXRECVBUF 4096 #define MAXBUF MAXRECVBUF+10 int fd_Setnonblocking(int fd) { int op; op=fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, op | O_NONBLOCK); return op; } void on_sigint(int signal) { log_debug("on_sigint"); exit(0); } /* handle_message - 处理每个 socket 上的消息收发 */ int handle_message(int new_fd) { log_info("new_fd: %d", new_fd); char buf[MAXBUF + 1]; //char sendbuf[MAXBUF+1]; int len; /* 开始处理每个新连接上的数据收发 */ bzero(buf, MAXBUF + 1); /* 接收客户端的消息 */ //len = recv(new_fd, buf, MAXBUF, 0); int nRecvBuf = MAXRECVBUF; //设置为32K setsockopt(new_fd, SOL_SOCKET, SO_RCVBUF, ( const char* )&nRecvBuf, sizeof(int)); len=recv(new_fd,&buf, MAXBUF,0); //-------------------------------------------------------------------------------------------- //这块为了使用ab测试 char bufSend[1000] = {0}; sprintf(bufSend,"HTTP/1.0 200 OK\r\nContent-type: text/plain\r\n\r\n%s","Hello world!\n"); send(new_fd,bufSend,strlen(buf),0); //-------------------------------------------------------------------------------------------- if (len > 0){ //printf ("%d接收消息成功:'%s',共%d个字节的数据\n", new_fd, buf, len); //hash-map map<int, sockStruct>::iterator it_find; it_find = sock_map.find(new_fd); if(it_find == sock_map.end()){ //新的网络连接,申请新的接收缓冲区,并放入map中 //printf("new socket %d\n", new_fd); sockStruct newSockStruct; newSockStruct.time = time((time_t*)0); newSockStruct.recvBuf = (unsigned int*)malloc(1000); memset(newSockStruct.recvBuf, 0, 1000); strcat((char*)newSockStruct.recvBuf, buf); sock_map.insert(pair<int,sockStruct>(new_fd, newSockStruct)); }else{ //网络连接已经存在,找到对应的数据缓冲区,将接收到的数据拼接到数据缓冲区中 //printf("socket %d exist!\n", it_find->first); (it_find->second).time = time((time_t*)0); //时间更改 char* bufSockMap = (char*)(it_find->second).recvBuf; //数据存储 strcat(bufSockMap, buf); //printf("bufSockMap:%s\n", bufSockMap); } } else { if (len < 0) printf ("消息接收失败!错误代码是%d,错误信息是'%s'\n", errno, strerror(errno)); else { //将socket从map中移除 /* map::iterator it_find; it_find = sock_map.find(new_fd); sock_map.erase(it_find); */ printf("client %d quit!\n",new_fd); } //close(new_fd); return -1; } /* 处理每个新连接上的数据收发结束 */ //关闭socket的时候,要释放接收缓冲区。 map<int, sockStruct>::iterator it_find; it_find = sock_map.find(new_fd); free((it_find->second).recvBuf); sock_map.erase(it_find); close(new_fd); return len; } int listenfd; int sock_op=1; struct sockaddr_in address; struct epoll_event event; struct epoll_event events[1024]; int epfd; int n; int i; char buf[512]; int off; int result; char *p; int main(int argc,char* argv[]) { init_thread_pool(1); signal(SIGPIPE,SIG_IGN); signal(SIGCHLD,SIG_IGN); signal(SIGINT,&on_sigint); listenfd=socket(AF_INET,SOCK_STREAM,0); printf("listenfd: %d\n", listenfd); setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&sock_op,sizeof(sock_op)); memset(&address,0,sizeof(address)); address.sin_addr.s_addr=htonl(INADDR_ANY); address.sin_port=htons(8006); bind(listenfd,(struct sockaddr*)&address,sizeof(address)); listen(listenfd,1024); fd_Setnonblocking(listenfd); epfd=epoll_create(65535); memset(&event,0,sizeof(event)); event.data.fd=listenfd; event.events=EPOLLIN|EPOLLET; epoll_ctl(epfd,EPOLL_CTL_ADD,listenfd,&event); while(1){ sleep(1000); } return 0; } /************************************************* * Function: * init_thread_pool * Description: * 初始化线程 * Input: * threadNum:用于处理epoll的线程数 * Output: * * Others: * 此函数为静态static函数, *************************************************/ int init_thread_pool(int threadNum) { int i,ret; pthread_t threadId; //初始化epoll线程池 for ( i = 0; i < threadNum; i++) { ret = pthread_create(&threadId, 0, epoll_loop, (void *)0); if (ret != 0) { printf("pthread create failed!\n"); return(-1); } } ret = pthread_create(&threadId, 0, check_connect_timeout, (void *)0); return(0); } /************************************************* * Function: * epoll_loop * Description: * epoll检测循环 * Input: * * Output: * * Others: * *************************************************/ static int count111 = 0; static time_t oldtime = 0, nowtime = 0; void *epoll_loop(void* para) { while(1) { n=epoll_wait(epfd,events,1024,-1); //printf("n = %d\n", n); if(n>0) { for(i=0;i<n;++i) { // new connect if(events[i].data.fd==listenfd) { while(1) { event.data.fd = accept(listenfd,NULL,NULL); if(event.data.fd>0) { fd_Setnonblocking(event.data.fd); event.events=EPOLLIN|EPOLLET; epoll_ctl(epfd,EPOLL_CTL_ADD,event.data.fd,&event); } else { if(errno==EAGAIN) break; } } } else { if(events[i].events & EPOLLIN) { //handle_message(events[i].data.fd); char recvBuf[1024] = {0}; int ret = 999; int rs = 1; while(rs) { ret = recv(events[i].data.fd,recvBuf,1024,0);// 接受客户端消息 if(ret < 0) { //由于是非阻塞的模式,所以当errno为EAGAIN时,表示当前缓冲区已无数据可//读在这里就当作是该次事件已处理过。 if(errno == EAGAIN) { printf("EAGAIN\n"); break; } else{ printf("recv error!\n"); epoll_ctl(epfd, EPOLL_CTL_DEL, events[i].data.fd, &event); close(events[i].data.fd); break; } } else if(ret == 0) { // 这里表示对端的socket已正常关闭. rs = 0; } else { log_info(recvBuf); } if(ret == sizeof(recvBuf)) rs = 1; // 需要再次读取 else rs = 0; } if(ret > 0){ count111 ++; //struct tm *today; //time_t ltime; time( &nowtime ); if(nowtime != oldtime){ printf("%d\n", count111); oldtime = nowtime; count111 = 0; } char buf[1000] = {0}; sprintf(buf,"HTTP/1.0 200 OK\r\nContent-type: text/plain\r\n\r\n%s","Hello world!\n"); send(events[i].data.fd,buf,strlen(buf),0); // CGelsServer Gelsserver; // Gelsserver.handle_message(events[i].data.fd); } epoll_ctl(epfd, EPOLL_CTL_DEL, events[i].data.fd, &event); close(events[i].data.fd); } else if(events[i].events&EPOLLOUT) { sprintf(buf,"HTTP/1.0 200 OK\r\nContent-type: text/plain\r\n\r\n%s","Hello world!\n"); send(events[i].data.fd,buf,strlen(buf),0); /* if(p!=NULL) { free(p); p=NULL; } */ close(events[i].data.fd); } else { close(events[i].data.fd); } } } } } } /************************************************* * Function: * check_connect_timeout * Description: * 检测长时间没反应的网络连接,并关闭删除 * Input: * * Output: * * Others: * *************************************************/ void *check_connect_timeout(void* para) { map<int, sockStruct>::iterator it_find; while (1) { log_info("check_connect_timeout"); for(it_find = sock_map.begin(); it_find!=sock_map.end(); ++it_find){ if( time((time_t*)0) - (it_find->second).time > 120){ //时间更改 free((it_find->second).recvBuf); sock_map.erase(it_find); close(it_find->first); } } sleep(10); } }
Furzoom/demo-C
src/network/event/event_srv.cpp
C++
gpl-2.0
10,931
/* * Copyright (C) 2013-2020 Canonical, Ltd. * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * This code is a complete clean re-write of the stress tool by * Colin Ian King <colin.king@canonical.com> and attempts to be * backwardly compatible with the stress tool by Amos Waterland * <apw@rossby.metr.ou.edu> but has more stress tests and more * functionality. * */ #include "stress-ng.h" static const stress_help_t help[] = { { NULL, "rawdev N", "start N workers that read a raw device" }, { NULL, "rawdev-ops N", "stop after N rawdev read operations" }, { NULL, "rawdev-method M", "specify the rawdev reead method to use" }, { NULL, NULL, NULL } }; typedef void (*stress_rawdev_func)(const stress_args_t *args, const int fd, unsigned long blks, unsigned long blksz); #define MIN_BLKSZ ((int)512) #define MAX_BLKSZ ((int)(128 * KB)) typedef struct { const char *name; const stress_rawdev_func func; } stress_rawdev_method_info_t; #if defined(HAVE_SYS_SYSMACROS_H) && \ defined(BLKGETSIZE) && \ defined(BLKSSZGET) /* * stress_rawdev_supported() * check if we can run this as root */ static int stress_rawdev_supported(const char *name) { if (geteuid() != 0) { pr_inf("%s flood stressor will be skipped, " "need to be running as root for this stressor\n", name); return -1; } return 0; } static inline unsigned long shift_ul(unsigned long v, unsigned int shift) { v >>= shift; return (v == 0) ? 1 : v; } static char *stress_rawdev_path(const dev_t dev) { static char path[PATH_MAX]; DIR *dir; struct dirent *d; const dev_t majdev = makedev(major(dev), 0); dir = opendir("/dev"); if (!dir) return NULL; while ((d = readdir(dir)) != NULL) { int ret; struct stat stat_buf; (void)snprintf(path, sizeof(path), "/dev/%s", d->d_name); ret = stat(path, &stat_buf); if ((ret == 0) && (S_ISBLK(stat_buf.st_mode)) && (stat_buf.st_rdev == majdev)) { (void)closedir(dir); return path; } } (void)closedir(dir); return NULL; } static void stress_rawdev_sweep( const stress_args_t *args, const int fd, unsigned long blks, unsigned long blksz) { unsigned long i; int ret; char buf[blksz << 1]; char *aligned = stress_align_address(buf, blksz); off_t offset; for (i = 0; i < blks && keep_stressing(); i += shift_ul(blks, 8)) { offset = (off_t)i * (off_t)blksz; ret = pread(fd, aligned, (size_t)blksz, offset); if (ret < 0) { pr_err("%s: pread at %ju failed, errno=%d (%s)\n", args->name, (intmax_t)offset, errno, strerror(errno)); } inc_counter(args); } for (; i > 0 && keep_stressing(); i -= shift_ul(blks, 8)) { offset = (off_t)i * (off_t)blksz; ret = pread(fd, aligned, (size_t)blksz, offset); if (ret < 0) { pr_err("%s: pread at %ju failed, errno=%d (%s)\n", args->name, (intmax_t)offset, errno, strerror(errno)); } inc_counter(args); } } static void stress_rawdev_wiggle( const stress_args_t *args, const int fd, unsigned long blks, unsigned long blksz) { unsigned long i; int ret; char buf[blksz << 1]; char *aligned = stress_align_address(buf, blksz); off_t offset; for (i = shift_ul(blks, 8); i < blks && keep_stressing(); i += shift_ul(blks, 8)) { unsigned long j; for (j = 0; j < shift_ul(blks, 8) && keep_stressing(); j += shift_ul(blks, 10)) { offset = (off_t)(i - j) * (off_t)blksz; ret = pread(fd, aligned, (size_t)blksz, offset); if (ret < 0) { pr_err("%s: pread at %ju failed, errno=%d (%s)\n", args->name, (intmax_t)offset, errno, strerror(errno)); } inc_counter(args); } } } static void stress_rawdev_ends( const stress_args_t *args, const int fd, unsigned long blks, unsigned long blksz) { unsigned long i; char buf[blksz << 1]; char *aligned = stress_align_address(buf, blksz); off_t offset; for (i = 0; i < 128; i++) { int ret; offset = (off_t)i * (off_t)blksz; ret = pread(fd, aligned, (size_t)blksz, offset); if (ret < 0) { pr_err("%s: pread at %ju failed, errno=%d (%s)\n", args->name, (intmax_t)offset, errno, strerror(errno)); } inc_counter(args); offset = (off_t)(blks - (i + 1)) * (off_t)blksz; ret = pread(fd, aligned, (size_t)blksz, offset); if (ret < 0) { pr_err("%s: pread at %ju failed, errno=%d (%s)\n", args->name, (intmax_t)offset, errno, strerror(errno)); } inc_counter(args); } } static void stress_rawdev_random( const stress_args_t *args, const int fd, unsigned long blks, unsigned long blksz) { int i; char buf[blksz << 1]; char *aligned = stress_align_address(buf, blksz); for (i = 0; i < 256 && keep_stressing(); i++) { int ret; off_t offset = (off_t)blksz * (stress_mwc64() % blks); ret = pread(fd, aligned, (size_t)blksz, offset); if (ret < 0) { pr_err("%s: pread at %ju failed, errno=%d (%s)\n", args->name, (intmax_t)offset, errno, strerror(errno)); } inc_counter(args); } } static void stress_rawdev_burst( const stress_args_t *args, const int fd, unsigned long blks, unsigned long blksz) { int i; char buf[blksz << 1]; char *aligned = stress_align_address(buf, blksz); off_t blk = (stress_mwc64() % blks); for (i = 0; i < 256 && keep_stressing(); i++) { int ret; off_t offset = blk * blksz; ret = pread(fd, aligned, (size_t)blksz, offset); if (ret < 0) { pr_err("%s: pread at %ju failed, errno=%d (%s)\n", args->name, (intmax_t)offset, errno, strerror(errno)); } blk++; blk %= blks; inc_counter(args); } } static const stress_rawdev_method_info_t rawdev_methods[]; /* * stress_rawdev_all() * iterate over all rawdev methods */ static void stress_rawdev_all( const stress_args_t *args, const int fd, unsigned long blks, unsigned long blksz) { static int i = 1; /* Skip over stress_rawdev_all */ rawdev_methods[i++].func(args, fd, blks, blksz); if (!rawdev_methods[i].func) i = 1; } /* * rawdev methods */ static const stress_rawdev_method_info_t rawdev_methods[] = { { "all", stress_rawdev_all }, { "sweep", stress_rawdev_sweep }, { "wiggle", stress_rawdev_wiggle }, { "ends", stress_rawdev_ends }, { "random", stress_rawdev_random }, { "burst", stress_rawdev_burst }, { NULL, NULL } }; #endif #if defined(HAVE_SYS_SYSMACROS_H) && \ defined(BLKGETSIZE) && \ defined(BLKSSZGET) /* * stress_set_rawdev_method() * set the default rawdev method */ static int stress_set_rawdev_method(const char *name) { stress_rawdev_method_info_t const *info; for (info = rawdev_methods; info->func; info++) { if (!strcmp(info->name, name)) { stress_set_setting("rawdev-method", TYPE_ID_UINTPTR_T, &info); return 0; } } (void)fprintf(stderr, "rawdev-method must be one of:"); for (info = rawdev_methods; info->func; info++) { (void)fprintf(stderr, " %s", info->name); } (void)fprintf(stderr, "\n"); return -1; } #else /* * stress_set_rawdev_method() * set the default rawdev method */ static int stress_set_rawdev_method(const char *name) { (void)name; (void)fprintf(stderr, "option --rawdev-method not supported\n"); return -1; } #endif static const stress_opt_set_func_t opt_set_funcs[] = { { OPT_rawdev_method, stress_set_rawdev_method }, { 0, NULL } }; #if defined(HAVE_SYS_SYSMACROS_H) && \ defined(BLKGETSIZE) && \ defined(BLKSSZGET) static int stress_rawdev(const stress_args_t *args) { int ret; char path[PATH_MAX], *devpath; struct stat stat_buf; int fd; int blksz = 0; unsigned long blks; const stress_rawdev_method_info_t *rawdev_method = &rawdev_methods[0]; stress_rawdev_func func; stress_temp_dir_args(args, path, sizeof(path)); (void)stress_get_setting("rawdev-method", &rawdev_method); func = rawdev_method->func; fd = open(path, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); if (fd < 0) { ret = exit_status(errno); pr_err("%s: open failed: %d (%s)\n", args->name, errno, strerror(errno)); return ret; } ret = fstat(fd, &stat_buf); if (ret < 0) { pr_err("%s: cannot stat %s: errno=%d (%s)\n", args->name, path, errno, strerror(errno)); (void)unlink(path); (void)close(fd); return EXIT_FAILURE; } (void)unlink(path); (void)close(fd); devpath = stress_rawdev_path(stat_buf.st_dev); if (!devpath) { pr_inf("%s: cannot determine raw block device\n", args->name); return EXIT_NO_RESOURCE; } fd = open(devpath, O_RDONLY | O_NONBLOCK); if (fd < 0) { pr_inf("%s: cannot open raw block device: errno=%d (%s)\n", args->name, errno, strerror(errno)); return EXIT_NO_RESOURCE; } ret = ioctl(fd, BLKGETSIZE, &blks); if (ret < 0) { pr_inf("%s: cannot get block size: errno=%d (%s)\n", args->name, errno, strerror(errno)); (void)close(fd); return EXIT_NO_RESOURCE; } ret = ioctl(fd, BLKSSZGET, &blksz); if (ret < 0) { pr_inf("%s: cannot get block size: errno=%d (%s)\n", args->name, errno, strerror(errno)); (void)close(fd); return EXIT_NO_RESOURCE; } /* Truncate if blksize looks too big */ if (blksz > MAX_BLKSZ) blksz = MAX_BLKSZ; if (blksz < MIN_BLKSZ) blksz = MIN_BLKSZ; (void)close(fd); fd = open(devpath, O_RDONLY | O_DIRECT); if (fd < 0) { pr_inf("%s: cannot open raw block device: errno=%d (%s)\n", args->name, errno, strerror(errno)); return EXIT_NO_RESOURCE; } if (args->instance == 0) pr_dbg("%s: exercising %s (%lu blocks of size %d bytes)\n", args->name, devpath, blks, blksz); do { func(args, fd, blks, (unsigned long)blksz); } while (keep_stressing()); (void)close(fd); return EXIT_SUCCESS; } stressor_info_t stress_rawdev_info = { .stressor = stress_rawdev, .supported = stress_rawdev_supported, .class = CLASS_IO, .opt_set_funcs = opt_set_funcs, .help = help }; #else stressor_info_t stress_rawdev_info = { .stressor = stress_not_implemented, .class = CLASS_IO, .opt_set_funcs = opt_set_funcs, .help = help }; #endif
fuchsia-mirror/stress-ng
stress-rawdev.c
C
gpl-2.0
10,498
<?php /* core/themes/stable/templates/admin/indentation.html.twig */ class __TwigTemplate_da243963582487cd78cc26c7f07c99f6e00debf728b0d84c814c2ac8a1c833d1 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { $tags = array("for" => 12); $filters = array(); $functions = array(); try { $this->env->getExtension('sandbox')->checkSecurity( array('for'), array(), array() ); } catch (Twig_Sandbox_SecurityError $e) { $e->setTemplateFile($this->getTemplateName()); if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) { $e->setTemplateLine($tags[$e->getTagName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) { $e->setTemplateLine($filters[$e->getFilterName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) { $e->setTemplateLine($functions[$e->getFunctionName()]); } throw $e; } // line 12 $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable(range(1, (isset($context["size"]) ? $context["size"] : null))); foreach ($context['_seq'] as $context["_key"] => $context["i"]) { if (((isset($context["size"]) ? $context["size"] : null) > 0)) { echo "<div class=\"js-indentation indentation\">&nbsp;</div>"; } } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['i'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; } public function getTemplateName() { return "core/themes/stable/templates/admin/indentation.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 43 => 12,); } public function getSource() { return "{# /** * @file * Theme override for a set of indentation divs. * * These <div> tags are used for drag and drop tables. * * Available variables: * - size: Optional. The number of indentations to create. */ #} {% for i in 1..size if size > 0 %}<div class=\"js-indentation indentation\">&nbsp;</div>{% endfor %} "; } }
piratskul/MyAwesomeDrupal
sites/default/files/php/twig/590e4b87c5da1_indentation.html.twig_1FgGuSnZ772wD5cJJKrE7hjBR/ZIaxNaC_GNDAUWcImvVi_hn3XWMnZNyDjmQwbNQQIys.php
PHP
gpl-2.0
2,757
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code 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. Quake III Arena source code 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 Quake III Arena source code; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ /***************************************************************************** * name: files.c * * desc: handle based filesystem for Quake III Arena * * $Archive: /MissionPack/code/qcommon/files.c $ * *****************************************************************************/ #include "q_shared.h" #include "qcommon.h" #include "unzip.h" /* ============================================================================= QUAKE3 FILESYSTEM All of Quake's data access is through a hierarchical file system, but the contents of the file system can be transparently merged from several sources. A "qpath" is a reference to game file data. MAX_ZPATH is 256 characters, which must include a terminating zero. "..", "\\", and ":" are explicitly illegal in qpaths to prevent any references outside the quake directory system. The "base path" is the path to the directory holding all the game directories and usually the executable. It defaults to ".", but can be overridden with a "+set fs_basepath c:\quake3" command line to allow code debugging in a different directory. Basepath cannot be modified at all after startup. Any files that are created (demos, screenshots, etc) will be created relative to the base path, so base path should usually be writable. The "home path" is the path used for all write access. On win32 systems we have "base path" == "home path", but on *nix systems the base installation is usually readonly, and "home path" points to ~/.q3a or similar The user can also install custom mods and content in "home path", so it should be searched along with "home path" and "cd path" for game content. The "base game" is the directory under the paths where data comes from by default, and can be either "baseq3" or "demoq3". The "current game" may be the same as the base game, or it may be the name of another directory under the paths that should be searched for files before looking in the base game. This is the basis for addons. Clients automatically set the game directory after receiving a gamestate from a server, so only servers need to worry about +set fs_game. No other directories outside of the base game and current game will ever be referenced by filesystem functions. To save disk space and speed loading, directory trees can be collapsed into zip files. The files use a ".pk3" extension to prevent users from unzipping them accidentally, but otherwise the are simply normal uncompressed zip files. A game directory can have multiple zip files of the form "pak0.pk3", "pak1.pk3", etc. Zip files are searched in decending order from the highest number to the lowest, and will always take precedence over the filesystem. This allows a pk3 distributed as a patch to override all existing data. Because we will have updated executables freely available online, there is no point to trying to restrict demo / oem versions of the game with code changes. Demo / oem versions should be exactly the same executables as release versions, but with different data that automatically restricts where game media can come from to prevent add-ons from working. File search order: when FS_FOpenFileRead gets called it will go through the fs_searchpaths structure and stop on the first successful hit. fs_searchpaths is built with successive calls to FS_AddGameDirectory Additionally, we search in several subdirectories: current game is the current mode base game is a variable to allow mods based on other mods (such as baseq3 + missionpack content combination in a mod for instance) BASEGAME is the hardcoded base game ("baseq3") e.g. the qpath "sound/newstuff/test.wav" would be searched for in the following places: home path + current game's zip files home path + current game's directory base path + current game's zip files base path + current game's directory cd path + current game's zip files cd path + current game's directory home path + base game's zip file home path + base game's directory base path + base game's zip file base path + base game's directory cd path + base game's zip file cd path + base game's directory home path + BASEGAME's zip file home path + BASEGAME's directory base path + BASEGAME's zip file base path + BASEGAME's directory cd path + BASEGAME's zip file cd path + BASEGAME's directory server download, to be written to home path + current game's directory The filesystem can be safely shutdown and reinitialized with different basedir / cddir / game combinations, but all other subsystems that rely on it (sound, video) must also be forced to restart. Because the same files are loaded by both the clip model (CM_) and renderer (TR_) subsystems, a simple single-file caching scheme is used. The CM_ subsystems will load the file with a request to cache. Only one file will be kept cached at a time, so any models that are going to be referenced by both subsystems should alternate between the CM_ load function and the ref load function. TODO: A qpath that starts with a leading slash will always refer to the base game, even if another game is currently active. This allows character models, skins, and sounds to be downloaded to a common directory no matter which game is active. How to prevent downloading zip files? Pass pk3 file names in systeminfo, and download before FS_Restart()? Aborting a download disconnects the client from the server. How to mark files as downloadable? Commercial add-ons won't be downloadable. Non-commercial downloads will want to download the entire zip file. the game would have to be reset to actually read the zip in Auto-update information Path separators Casing separate server gamedir and client gamedir, so if the user starts a local game after having connected to a network game, it won't stick with the network game. allow menu options for game selection? Read / write config to floppy option. Different version coexistance? When building a pak file, make sure a q3config.cfg isn't present in it, or configs will never get loaded from disk! todo: downloading (outside fs?) game directory passing and restarting ============================================================================= */ // every time a new demo pk3 file is built, this checksum must be updated. // the easiest way to get it is to just run the game and see what it spits out #ifndef STANDALONE #define DEMO_PAK0_CHECKSUM 2985612116u static const unsigned int pak_checksums[] = { 1566731103u, 298122907u, 412165236u, 2991495316u, 1197932710u, 4087071573u, 3709064859u, 908855077u, 977125798u }; static const unsigned int missionpak_checksums[] = { 2430342401u, 511014160u, 2662638993u, 1438664554u }; #endif // if this is defined, the executable positively won't work with any paks other // than the demo pak, even if productid is present. This is only used for our // last demo release to prevent the mac and linux users from using the demo // executable with the production windows pak before the mac/linux products // hit the shelves a little later // NOW defined in build files //#define PRE_RELEASE_TADEMO #define MAX_ZPATH 256 #define MAX_SEARCH_PATHS 4096 #define MAX_FILEHASH_SIZE 1024 typedef struct fileInPack_s { char *name; // name of the file unsigned long pos; // file info position in zip unsigned long len; // uncompress file size struct fileInPack_s* next; // next file in the hash } fileInPack_t; typedef struct { char pakPathname[MAX_OSPATH]; // c:\quake3\baseq3 char pakFilename[MAX_OSPATH]; // c:\quake3\baseq3\pak0.pk3 char pakBasename[MAX_OSPATH]; // pak0 char pakGamename[MAX_OSPATH]; // baseq3 unzFile handle; // handle to zip file int checksum; // regular checksum int pure_checksum; // checksum for pure int numfiles; // number of files in pk3 int referenced; // referenced file flags int hashSize; // hash table size (power of 2) fileInPack_t* *hashTable; // hash table fileInPack_t* buildBuffer; // buffer with the filenames etc. } pack_t; typedef struct { char path[MAX_OSPATH]; // c:\quake3 char fullpath[MAX_OSPATH]; // c:\quake3\baseq3 char gamedir[MAX_OSPATH]; // baseq3 } directory_t; typedef struct searchpath_s { struct searchpath_s *next; pack_t *pack; // only one of pack / dir will be non NULL directory_t *dir; } searchpath_t; static char fs_gamedir[MAX_OSPATH]; // this will be a single file name with no separators static cvar_t *fs_debug; static cvar_t *fs_homepath; #ifdef __APPLE__ // Also search the .app bundle for .pk3 files static cvar_t *fs_apppath; #endif static cvar_t *fs_steampath; static cvar_t *fs_gogpath; static cvar_t *fs_basepath; static cvar_t *fs_basegame; static cvar_t *fs_gamedirvar; static searchpath_t *fs_searchpaths; static int fs_readCount; // total bytes read static int fs_loadCount; // total files read static int fs_loadStack; // total files in memory static int fs_packFiles = 0; // total number of files in packs static int fs_checksumFeed; typedef union qfile_gus { FILE* o; unzFile z; } qfile_gut; typedef struct qfile_us { qfile_gut file; qboolean unique; } qfile_ut; typedef struct { qfile_ut handleFiles; qboolean handleSync; int fileSize; int zipFilePos; int zipFileLen; qboolean zipFile; char name[MAX_ZPATH]; } fileHandleData_t; static fileHandleData_t fsh[MAX_FILE_HANDLES]; // TTimo - https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540 // wether we did a reorder on the current search path when joining the server static qboolean fs_reordered; // never load anything from pk3 files that are not present at the server when pure static int fs_numServerPaks = 0; static int fs_serverPaks[MAX_SEARCH_PATHS]; // checksums static char *fs_serverPakNames[MAX_SEARCH_PATHS]; // pk3 names // only used for autodownload, to make sure the client has at least // all the pk3 files that are referenced at the server side static int fs_numServerReferencedPaks; static int fs_serverReferencedPaks[MAX_SEARCH_PATHS]; // checksums static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS]; // pk3 names // last valid game folder used char lastValidBase[MAX_OSPATH]; char lastValidComBaseGame[MAX_OSPATH]; char lastValidFsBaseGame[MAX_OSPATH]; char lastValidGame[MAX_OSPATH]; #ifdef FS_MISSING FILE* missingFiles = NULL; #endif /* C99 defines __func__ */ #if __STDC_VERSION__ < 199901L # if __GNUC__ >= 2 || _MSC_VER >= 1300 # define __func__ __FUNCTION__ # else # define __func__ "(unknown)" # endif #endif /* ============== FS_Initialized ============== */ qboolean FS_Initialized( void ) { return (fs_searchpaths != NULL); } /* ================= FS_PakIsPure ================= */ qboolean FS_PakIsPure( pack_t *pack ) { int i; if ( fs_numServerPaks ) { for ( i = 0 ; i < fs_numServerPaks ; i++ ) { // FIXME: also use hashed file names // NOTE TTimo: a pk3 with same checksum but different name would be validated too // I don't see this as allowing for any exploit, it would only happen if the client does manips of its file names 'not a bug' if ( pack->checksum == fs_serverPaks[i] ) { return qtrue; // on the aproved list } } return qfalse; // not on the pure server pak list } return qtrue; } /* ================= FS_LoadStack return load stack ================= */ int FS_LoadStack( void ) { return fs_loadStack; } /* ================ return a hash value for the filename ================ */ static long FS_HashFileName( const char *fname, int hashSize ) { int i; long hash; char letter; hash = 0; i = 0; while (fname[i] != '\0') { letter = tolower(fname[i]); if (letter =='.') break; // don't include extension if (letter =='\\') letter = '/'; // damn path names if (letter == PATH_SEP) letter = '/'; // damn path names hash+=(long)(letter)*(i+119); i++; } hash = (hash ^ (hash >> 10) ^ (hash >> 20)); hash &= (hashSize-1); return hash; } static fileHandle_t FS_HandleForFile(void) { int i; for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) { if ( fsh[i].handleFiles.file.o == NULL ) { return i; } } Com_Error( ERR_DROP, "FS_HandleForFile: none free" ); return 0; } static FILE *FS_FileForHandle( fileHandle_t f ) { if ( f < 1 || f >= MAX_FILE_HANDLES ) { Com_Error( ERR_DROP, "FS_FileForHandle: out of range" ); } if (fsh[f].zipFile == qtrue) { Com_Error( ERR_DROP, "FS_FileForHandle: can't get FILE on zip file" ); } if ( ! fsh[f].handleFiles.file.o ) { Com_Error( ERR_DROP, "FS_FileForHandle: NULL" ); } return fsh[f].handleFiles.file.o; } void FS_ForceFlush( fileHandle_t f ) { FILE *file; file = FS_FileForHandle(f); setvbuf( file, NULL, _IONBF, 0 ); } /* ================ FS_fplength ================ */ long FS_fplength(FILE *h) { long pos; long end; pos = ftell(h); fseek(h, 0, SEEK_END); end = ftell(h); fseek(h, pos, SEEK_SET); return end; } /* ================ FS_filelength If this is called on a non-unique FILE (from a pak file), it will return the size of the pak file, not the expected size of the file. ================ */ long FS_filelength(fileHandle_t f) { FILE *h; h = FS_FileForHandle(f); if(h == NULL) return -1; else return FS_fplength(h); } /* ==================== FS_ReplaceSeparators Fix things up differently for win/unix/mac ==================== */ static void FS_ReplaceSeparators( char *path ) { char *s; qboolean lastCharWasSep = qfalse; for ( s = path ; *s ; s++ ) { if ( *s == '/' || *s == '\\' ) { if ( !lastCharWasSep ) { *s = PATH_SEP; lastCharWasSep = qtrue; } else { memmove (s, s + 1, strlen (s)); } } else { lastCharWasSep = qfalse; } } } /* =================== FS_BuildOSPath Qpath may have either forward or backwards slashes =================== */ char *FS_BuildOSPath( const char *base, const char *game, const char *qpath ) { char temp[MAX_OSPATH]; static char ospath[2][MAX_OSPATH]; static int toggle; toggle ^= 1; // flip-flop to allow two returns without clash if( !game || !game[0] ) { game = fs_gamedir; } Com_sprintf( temp, sizeof(temp), "/%s/%s", game, qpath ); FS_ReplaceSeparators( temp ); Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", base, temp ); return ospath[toggle]; } /* ============ FS_CreatePath Creates any directories needed to store the given filename ============ */ qboolean FS_CreatePath (char *OSPath) { char *ofs; char path[MAX_OSPATH]; // make absolutely sure that it can't back up the path // FIXME: is c: allowed??? if ( strstr( OSPath, ".." ) || strstr( OSPath, "::" ) ) { Com_Printf( "WARNING: refusing to create relative path \"%s\"\n", OSPath ); return qtrue; } Q_strncpyz( path, OSPath, sizeof( path ) ); FS_ReplaceSeparators( path ); // Skip creation of the root directory as it will always be there ofs = strchr( path, PATH_SEP ); if ( ofs != NULL ) { ofs++; } for (; ofs != NULL && *ofs ; ofs++) { if (*ofs == PATH_SEP) { // create the directory *ofs = 0; if (!Sys_Mkdir (path)) { Com_Error( ERR_FATAL, "FS_CreatePath: failed to create path \"%s\"", path ); } *ofs = PATH_SEP; } } return qfalse; } /* ================= FS_CheckFilenameIsMutable ERR_FATAL if trying to maniuplate a file with the platform library, QVM, or pk3 extension ================= */ static void FS_CheckFilenameIsMutable( const char *filename, const char *function ) { // Check if the filename ends with the library, QVM, or pk3 extension if( Sys_DllExtension( filename ) || COM_CompareExtension( filename, ".qvm" ) || COM_CompareExtension( filename, ".pk3" ) ) { Com_Error( ERR_FATAL, "%s: Not allowed to manipulate '%s' due " "to %s extension", function, filename, COM_GetExtension( filename ) ); } } /* =========== FS_Remove =========== */ void FS_Remove( const char *osPath ) { FS_CheckFilenameIsMutable( osPath, __func__ ); remove( osPath ); } /* =========== FS_HomeRemove =========== */ void FS_HomeRemove( const char *homePath ) { FS_CheckFilenameIsMutable( homePath, __func__ ); remove( FS_BuildOSPath( fs_homepath->string, fs_gamedir, homePath ) ); } /* ================ FS_FileInPathExists Tests if path and file exists ================ */ qboolean FS_FileInPathExists(const char *testpath) { FILE *filep; filep = Sys_FOpen(testpath, "rb"); if(filep) { fclose(filep); return qtrue; } return qfalse; } /* ================ FS_FileExists Tests if the file exists in the current gamedir, this DOES NOT search the paths. This is to determine if opening a file to write (which always goes into the current gamedir) will cause any overwrites. NOTE TTimo: this goes with FS_FOpenFileWrite for opening the file afterwards ================ */ qboolean FS_FileExists(const char *file) { return FS_FileInPathExists(FS_BuildOSPath(fs_homepath->string, fs_gamedir, file)); } /* ================ FS_SV_FileExists Tests if the file exists ================ */ qboolean FS_SV_FileExists( const char *file ) { char *testpath; testpath = FS_BuildOSPath( fs_homepath->string, file, ""); testpath[strlen(testpath)-1] = '\0'; return FS_FileInPathExists(testpath); } /* =========== FS_SV_FOpenFileWrite =========== */ fileHandle_t FS_SV_FOpenFileWrite( const char *filename ) { char *ospath; fileHandle_t f; if ( !fs_searchpaths ) { Com_Error( ERR_FATAL, "Filesystem call made without initialization" ); } ospath = FS_BuildOSPath( fs_homepath->string, filename, "" ); ospath[strlen(ospath)-1] = '\0'; f = FS_HandleForFile(); fsh[f].zipFile = qfalse; if ( fs_debug->integer ) { Com_Printf( "FS_SV_FOpenFileWrite: %s\n", ospath ); } FS_CheckFilenameIsMutable( ospath, __func__ ); if( FS_CreatePath( ospath ) ) { return 0; } Com_DPrintf( "writing to: %s\n", ospath ); fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "wb" ); Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) ); fsh[f].handleSync = qfalse; if (!fsh[f].handleFiles.file.o) { f = 0; } return f; } /* =========== FS_SV_FOpenFileRead Search for a file somewhere below the home path then base path in that order =========== */ long FS_SV_FOpenFileRead(const char *filename, fileHandle_t *fp) { char *ospath; fileHandle_t f = 0; if ( !fs_searchpaths ) { Com_Error( ERR_FATAL, "Filesystem call made without initialization" ); } f = FS_HandleForFile(); fsh[f].zipFile = qfalse; Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) ); // don't let sound stutter S_ClearSoundBuffer(); // search homepath ospath = FS_BuildOSPath( fs_homepath->string, filename, "" ); // remove trailing slash ospath[strlen(ospath)-1] = '\0'; if ( fs_debug->integer ) { Com_Printf( "FS_SV_FOpenFileRead (fs_homepath): %s\n", ospath ); } fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" ); fsh[f].handleSync = qfalse; if (!fsh[f].handleFiles.file.o) { // If fs_homepath == fs_basepath, don't bother if (Q_stricmp(fs_homepath->string,fs_basepath->string)) { // search basepath ospath = FS_BuildOSPath( fs_basepath->string, filename, "" ); ospath[strlen(ospath)-1] = '\0'; if ( fs_debug->integer ) { Com_Printf( "FS_SV_FOpenFileRead (fs_basepath): %s\n", ospath ); } fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" ); fsh[f].handleSync = qfalse; } // Check fs_steampath if (!fsh[f].handleFiles.file.o && fs_steampath->string[0]) { ospath = FS_BuildOSPath( fs_steampath->string, filename, "" ); ospath[strlen(ospath)-1] = '\0'; if ( fs_debug->integer ) { Com_Printf( "FS_SV_FOpenFileRead (fs_steampath): %s\n", ospath ); } fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" ); fsh[f].handleSync = qfalse; } // Check fs_gogpath if (!fsh[f].handleFiles.file.o && fs_gogpath->string[0]) { ospath = FS_BuildOSPath( fs_gogpath->string, filename, "" ); ospath[strlen(ospath)-1] = '\0'; if ( fs_debug->integer ) { Com_Printf( "FS_SV_FOpenFileRead (fs_gogpath): %s\n", ospath ); } fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" ); fsh[f].handleSync = qfalse; } if ( !fsh[f].handleFiles.file.o ) { f = 0; } } *fp = f; if (f) { return FS_filelength(f); } return -1; } /* =========== FS_SV_Rename =========== */ void FS_SV_Rename( const char *from, const char *to, qboolean safe ) { char *from_ospath, *to_ospath; if ( !fs_searchpaths ) { Com_Error( ERR_FATAL, "Filesystem call made without initialization" ); } // don't let sound stutter S_ClearSoundBuffer(); from_ospath = FS_BuildOSPath( fs_homepath->string, from, "" ); to_ospath = FS_BuildOSPath( fs_homepath->string, to, "" ); from_ospath[strlen(from_ospath)-1] = '\0'; to_ospath[strlen(to_ospath)-1] = '\0'; if ( fs_debug->integer ) { Com_Printf( "FS_SV_Rename: %s --> %s\n", from_ospath, to_ospath ); } if ( safe ) { FS_CheckFilenameIsMutable( to_ospath, __func__ ); } rename(from_ospath, to_ospath); } /* =========== FS_Rename =========== */ void FS_Rename( const char *from, const char *to ) { char *from_ospath, *to_ospath; if ( !fs_searchpaths ) { Com_Error( ERR_FATAL, "Filesystem call made without initialization" ); } // don't let sound stutter S_ClearSoundBuffer(); from_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, from ); to_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, to ); if ( fs_debug->integer ) { Com_Printf( "FS_Rename: %s --> %s\n", from_ospath, to_ospath ); } FS_CheckFilenameIsMutable( to_ospath, __func__ ); rename(from_ospath, to_ospath); } /* ============== FS_FCloseFile If the FILE pointer is an open pak file, leave it open. For some reason, other dll's can't just cal fclose() on files returned by FS_FOpenFile... ============== */ void FS_FCloseFile( fileHandle_t f ) { if ( !fs_searchpaths ) { Com_Error( ERR_FATAL, "Filesystem call made without initialization" ); } if (fsh[f].zipFile == qtrue) { unzCloseCurrentFile( fsh[f].handleFiles.file.z ); if ( fsh[f].handleFiles.unique ) { unzClose( fsh[f].handleFiles.file.z ); } Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) ); return; } // we didn't find it as a pak, so close it as a unique file if (fsh[f].handleFiles.file.o) { fclose (fsh[f].handleFiles.file.o); } Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) ); } /* =========== FS_FOpenFileWrite =========== */ fileHandle_t FS_FOpenFileWrite( const char *filename ) { char *ospath; fileHandle_t f; if ( !fs_searchpaths ) { Com_Error( ERR_FATAL, "Filesystem call made without initialization" ); } f = FS_HandleForFile(); fsh[f].zipFile = qfalse; ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename ); if ( fs_debug->integer ) { Com_Printf( "FS_FOpenFileWrite: %s\n", ospath ); } FS_CheckFilenameIsMutable( ospath, __func__ ); if( FS_CreatePath( ospath ) ) { return 0; } // enabling the following line causes a recursive function call loop // when running with +set logfile 1 +set developer 1 //Com_DPrintf( "writing to: %s\n", ospath ); fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "wb" ); Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) ); fsh[f].handleSync = qfalse; if (!fsh[f].handleFiles.file.o) { f = 0; } return f; } /* =========== FS_FOpenFileAppend =========== */ fileHandle_t FS_FOpenFileAppend( const char *filename ) { char *ospath; fileHandle_t f; if ( !fs_searchpaths ) { Com_Error( ERR_FATAL, "Filesystem call made without initialization" ); } f = FS_HandleForFile(); fsh[f].zipFile = qfalse; Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) ); // don't let sound stutter S_ClearSoundBuffer(); ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename ); if ( fs_debug->integer ) { Com_Printf( "FS_FOpenFileAppend: %s\n", ospath ); } FS_CheckFilenameIsMutable( ospath, __func__ ); if( FS_CreatePath( ospath ) ) { return 0; } fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "ab" ); fsh[f].handleSync = qfalse; if (!fsh[f].handleFiles.file.o) { f = 0; } return f; } /* =========== FS_FCreateOpenPipeFile =========== */ fileHandle_t FS_FCreateOpenPipeFile( const char *filename ) { char *ospath; FILE *fifo; fileHandle_t f; if ( !fs_searchpaths ) { Com_Error( ERR_FATAL, "Filesystem call made without initialization" ); } f = FS_HandleForFile(); fsh[f].zipFile = qfalse; Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) ); // don't let sound stutter S_ClearSoundBuffer(); ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename ); if ( fs_debug->integer ) { Com_Printf( "FS_FCreateOpenPipeFile: %s\n", ospath ); } FS_CheckFilenameIsMutable( ospath, __func__ ); fifo = Sys_Mkfifo( ospath ); if( fifo ) { fsh[f].handleFiles.file.o = fifo; fsh[f].handleSync = qfalse; } else { Com_Printf( S_COLOR_YELLOW "WARNING: Could not create new com_pipefile at %s. " "com_pipefile will not be used.\n", ospath ); f = 0; } return f; } /* =========== FS_FilenameCompare Ignore case and seprator char distinctions =========== */ qboolean FS_FilenameCompare( const char *s1, const char *s2 ) { int c1, c2; do { c1 = *s1++; c2 = *s2++; if (c1 >= 'a' && c1 <= 'z') { c1 -= ('a' - 'A'); } if (c2 >= 'a' && c2 <= 'z') { c2 -= ('a' - 'A'); } if ( c1 == '\\' || c1 == ':' ) { c1 = '/'; } if ( c2 == '\\' || c2 == ':' ) { c2 = '/'; } if (c1 != c2) { return qtrue; // strings not equal } } while (c1); return qfalse; // strings are equal } /* =========== FS_IsExt Return qtrue if ext matches file extension filename =========== */ qboolean FS_IsExt(const char *filename, const char *ext, int namelen) { int extlen; extlen = strlen(ext); if(extlen > namelen) return qfalse; filename += namelen - extlen; return !Q_stricmp(filename, ext); } /* =========== FS_IsDemoExt Return qtrue if filename has a demo extension =========== */ qboolean FS_IsDemoExt(const char *filename, int namelen) { char *ext_test; int index, protocol; ext_test = strrchr(filename, '.'); if(ext_test && !Q_stricmpn(ext_test + 1, DEMOEXT, ARRAY_LEN(DEMOEXT) - 1)) { protocol = atoi(ext_test + ARRAY_LEN(DEMOEXT)); if(protocol == com_protocol->integer) return qtrue; #ifdef LEGACY_PROTOCOL if(protocol == com_legacyprotocol->integer) return qtrue; #endif for(index = 0; demo_protocols[index]; index++) { if(demo_protocols[index] == protocol) return qtrue; } } return qfalse; } /* =========== FS_FOpenFileReadDir Tries opening file "filename" in searchpath "search" Returns filesize and an open FILE pointer. =========== */ extern qboolean com_fullyInitialized; long FS_FOpenFileReadDir(const char *filename, searchpath_t *search, fileHandle_t *file, qboolean uniqueFILE, qboolean unpure) { long hash; pack_t *pak; fileInPack_t *pakFile; directory_t *dir; char *netpath; FILE *filep; int len; if(filename == NULL) Com_Error(ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed"); // qpaths are not supposed to have a leading slash if(filename[0] == '/' || filename[0] == '\\') filename++; // make absolutely sure that it can't back up the path. // The searchpaths do guarantee that something will always // be prepended, so we don't need to worry about "c:" or "//limbo" if(strstr(filename, ".." ) || strstr(filename, "::")) { if(file == NULL) return qfalse; *file = 0; return -1; } // make sure the q3key file is only readable by the quake3.exe at initialization // any other time the key should only be accessed in memory using the provided functions if(com_fullyInitialized && strstr(filename, "q3key")) { if(file == NULL) return qfalse; *file = 0; return -1; } if(file == NULL) { // just wants to see if file is there // is the element a pak file? if(search->pack) { hash = FS_HashFileName(filename, search->pack->hashSize); if(search->pack->hashTable[hash]) { // look through all the pak file elements pak = search->pack; pakFile = pak->hashTable[hash]; do { // case and separator insensitive comparisons if(!FS_FilenameCompare(pakFile->name, filename)) { // found it! if(pakFile->len) return pakFile->len; else { // It's not nice, but legacy code depends // on positive value if file exists no matter // what size return 1; } } pakFile = pakFile->next; } while(pakFile != NULL); } } else if(search->dir) { dir = search->dir; netpath = FS_BuildOSPath(dir->path, dir->gamedir, filename); filep = Sys_FOpen(netpath, "rb"); if(filep) { len = FS_fplength(filep); fclose(filep); if(len) return len; else return 1; } } return 0; } *file = FS_HandleForFile(); fsh[*file].handleFiles.unique = uniqueFILE; // is the element a pak file? if(search->pack) { hash = FS_HashFileName(filename, search->pack->hashSize); if(search->pack->hashTable[hash]) { // disregard if it doesn't match one of the allowed pure pak files if(!unpure && !FS_PakIsPure(search->pack)) { *file = 0; return -1; } // look through all the pak file elements pak = search->pack; pakFile = pak->hashTable[hash]; do { // case and separator insensitive comparisons if(!FS_FilenameCompare(pakFile->name, filename)) { // found it! // mark the pak as having been referenced and mark specifics on cgame and ui // shaders, txt, arena files by themselves do not count as a reference as // these are loaded from all pk3s // from every pk3 file.. len = strlen(filename); if (!(pak->referenced & FS_GENERAL_REF)) { if(!FS_IsExt(filename, ".shader", len) && !FS_IsExt(filename, ".txt", len) && !FS_IsExt(filename, ".cfg", len) && !FS_IsExt(filename, ".config", len) && !FS_IsExt(filename, ".bot", len) && !FS_IsExt(filename, ".arena", len) && !FS_IsExt(filename, ".menu", len) && Q_stricmp(filename, "vm/qagame.qvm") != 0 && !strstr(filename, "levelshots")) { pak->referenced |= FS_GENERAL_REF; } } if(strstr(filename, "cgame.qvm")) pak->referenced |= FS_CGAME_REF; if(strstr(filename, "ui.qvm")) pak->referenced |= FS_UI_REF; if(uniqueFILE) { // open a new file on the pakfile fsh[*file].handleFiles.file.z = unzOpen(pak->pakFilename); if(fsh[*file].handleFiles.file.z == NULL) Com_Error(ERR_FATAL, "Couldn't open %s", pak->pakFilename); } else fsh[*file].handleFiles.file.z = pak->handle; Q_strncpyz(fsh[*file].name, filename, sizeof(fsh[*file].name)); fsh[*file].zipFile = qtrue; // set the file position in the zip file (also sets the current file info) unzSetOffset(fsh[*file].handleFiles.file.z, pakFile->pos); // open the file in the zip unzOpenCurrentFile(fsh[*file].handleFiles.file.z); fsh[*file].zipFilePos = pakFile->pos; fsh[*file].zipFileLen = pakFile->len; if(fs_debug->integer) { Com_Printf("FS_FOpenFileRead: %s (found in '%s')\n", filename, pak->pakFilename); } return pakFile->len; } pakFile = pakFile->next; } while(pakFile != NULL); } } else if(search->dir) { // check a file in the directory tree // if we are running restricted, the only files we // will allow to come from the directory are .cfg files len = strlen(filename); // FIXME TTimo I'm not sure about the fs_numServerPaks test // if you are using FS_ReadFile to find out if a file exists, // this test can make the search fail although the file is in the directory // I had the problem on https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=8 // turned out I used FS_FileExists instead if(!unpure && fs_numServerPaks) { if(!FS_IsExt(filename, ".cfg", len) && // for config files !FS_IsExt(filename, ".menu", len) && // menu files !FS_IsExt(filename, ".game", len) && // menu files !FS_IsExt(filename, ".dat", len) && // for journal files !FS_IsDemoExt(filename, len)) // demos { *file = 0; return -1; } } dir = search->dir; netpath = FS_BuildOSPath(dir->path, dir->gamedir, filename); filep = Sys_FOpen(netpath, "rb"); if (filep == NULL) { *file = 0; return -1; } Q_strncpyz(fsh[*file].name, filename, sizeof(fsh[*file].name)); fsh[*file].zipFile = qfalse; if(fs_debug->integer) { Com_Printf("FS_FOpenFileRead: %s (found in '%s%c%s')\n", filename, dir->path, PATH_SEP, dir->gamedir); } fsh[*file].handleFiles.file.o = filep; return FS_fplength(filep); } *file = 0; return -1; } /* =========== FS_FOpenFileRead Finds the file in the search path. Returns filesize and an open FILE pointer. Used for streaming data out of either a separate file or a ZIP file. =========== */ long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE) { searchpath_t *search; long len; qboolean isLocalConfig; if(!fs_searchpaths) Com_Error(ERR_FATAL, "Filesystem call made without initialization"); isLocalConfig = !strcmp(filename, "autoexec.cfg") || !strcmp(filename, Q3CONFIG_CFG); for(search = fs_searchpaths; search; search = search->next) { // autoexec.cfg and q3config.cfg can only be loaded outside of pk3 files. if (isLocalConfig && search->pack) continue; len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse); if(file == NULL) { if(len > 0) return len; } else { if(len >= 0 && *file) return len; } } #ifdef FS_MISSING if(missingFiles) fprintf(missingFiles, "%s\n", filename); #endif if(file) { *file = 0; return -1; } else { // When file is NULL, we're querying the existence of the file // If we've got here, it doesn't exist return 0; } } /* ================= FS_FindVM Find a suitable VM file in search path order. In each searchpath try: - open DLL file if DLL loading enabled - open QVM file Enable search for DLL by setting enableDll to FSVM_ENABLEDLL write found DLL or QVM to "found" and return VMI_NATIVE if DLL, VMI_COMPILED if QVM Return the searchpath in "startSearch". ================= */ int FS_FindVM(void **startSearch, char *found, int foundlen, const char *name, int enableDll) { searchpath_t *search, *lastSearch; directory_t *dir; pack_t *pack; char dllName[MAX_OSPATH], qvmName[MAX_OSPATH]; char *netpath; if(!fs_searchpaths) Com_Error(ERR_FATAL, "Filesystem call made without initialization"); if(enableDll) Com_sprintf(dllName, sizeof(dllName), "%s" ARCH_STRING DLL_EXT, name); Com_sprintf(qvmName, sizeof(qvmName), "vm/%s.qvm", name); lastSearch = *startSearch; if(*startSearch == NULL) search = fs_searchpaths; else search = lastSearch->next; while(search) { if(search->dir && !fs_numServerPaks) { dir = search->dir; if(enableDll) { netpath = FS_BuildOSPath(dir->path, dir->gamedir, dllName); if(FS_FileInPathExists(netpath)) { Q_strncpyz(found, netpath, foundlen); *startSearch = search; return VMI_NATIVE; } } if(FS_FOpenFileReadDir(qvmName, search, NULL, qfalse, qfalse) > 0) { *startSearch = search; return VMI_COMPILED; } } else if(search->pack) { pack = search->pack; if(lastSearch && lastSearch->pack) { // make sure we only try loading one VM file per game dir // i.e. if VM from pak7.pk3 fails we won't try one from pak6.pk3 if(!FS_FilenameCompare(lastSearch->pack->pakPathname, pack->pakPathname)) { search = search->next; continue; } } if(FS_FOpenFileReadDir(qvmName, search, NULL, qfalse, qfalse) > 0) { *startSearch = search; return VMI_COMPILED; } } search = search->next; } return -1; } /* ================= FS_Read Properly handles partial reads ================= */ int FS_Read( void *buffer, int len, fileHandle_t f ) { int block, remaining; int read; byte *buf; int tries; if ( !fs_searchpaths ) { Com_Error( ERR_FATAL, "Filesystem call made without initialization" ); } if ( !f ) { return 0; } buf = (byte *)buffer; fs_readCount += len; if (fsh[f].zipFile == qfalse) { remaining = len; tries = 0; while (remaining) { block = remaining; read = fread (buf, 1, block, fsh[f].handleFiles.file.o); if (read == 0) { // we might have been trying to read from a CD, which // sometimes returns a 0 read on windows if (!tries) { tries = 1; } else { return len-remaining; //Com_Error (ERR_FATAL, "FS_Read: 0 bytes read"); } } if (read == -1) { Com_Error (ERR_FATAL, "FS_Read: -1 bytes read"); } remaining -= read; buf += read; } return len; } else { return unzReadCurrentFile(fsh[f].handleFiles.file.z, buffer, len); } } /* ================= FS_Write Properly handles partial writes ================= */ int FS_Write( const void *buffer, int len, fileHandle_t h ) { int block, remaining; int written; byte *buf; int tries; FILE *f; if ( !fs_searchpaths ) { Com_Error( ERR_FATAL, "Filesystem call made without initialization" ); } if ( !h ) { return 0; } f = FS_FileForHandle(h); buf = (byte *)buffer; remaining = len; tries = 0; while (remaining) { block = remaining; written = fwrite (buf, 1, block, f); if (written == 0) { if (!tries) { tries = 1; } else { Com_Printf( "FS_Write: 0 bytes written\n" ); return 0; } } if (written == -1) { Com_Printf( "FS_Write: -1 bytes written\n" ); return 0; } remaining -= written; buf += written; } if ( fsh[h].handleSync ) { fflush( f ); } return len; } void QDECL FS_Printf( fileHandle_t h, const char *fmt, ... ) { va_list argptr; char msg[MAXPRINTMSG]; va_start (argptr,fmt); Q_vsnprintf (msg, sizeof(msg), fmt, argptr); va_end (argptr); FS_Write(msg, strlen(msg), h); } #define PK3_SEEK_BUFFER_SIZE 65536 /* ================= FS_Seek ================= */ int FS_Seek( fileHandle_t f, long offset, int origin ) { int _origin; if ( !fs_searchpaths ) { Com_Error( ERR_FATAL, "Filesystem call made without initialization" ); return -1; } if (fsh[f].zipFile == qtrue) { //FIXME: this is really, really crappy //(but better than what was here before) byte buffer[PK3_SEEK_BUFFER_SIZE]; int remainder; int currentPosition = FS_FTell( f ); // change negative offsets into FS_SEEK_SET if ( offset < 0 ) { switch( origin ) { case FS_SEEK_END: remainder = fsh[f].zipFileLen + offset; break; case FS_SEEK_CUR: remainder = currentPosition + offset; break; case FS_SEEK_SET: default: remainder = 0; break; } if ( remainder < 0 ) { remainder = 0; } origin = FS_SEEK_SET; } else { if ( origin == FS_SEEK_END ) { remainder = fsh[f].zipFileLen - currentPosition + offset; } else { remainder = offset; } } switch( origin ) { case FS_SEEK_SET: if ( remainder == currentPosition ) { return offset; } unzSetOffset(fsh[f].handleFiles.file.z, fsh[f].zipFilePos); unzOpenCurrentFile(fsh[f].handleFiles.file.z); //fallthrough case FS_SEEK_END: case FS_SEEK_CUR: while( remainder > PK3_SEEK_BUFFER_SIZE ) { FS_Read( buffer, PK3_SEEK_BUFFER_SIZE, f ); remainder -= PK3_SEEK_BUFFER_SIZE; } FS_Read( buffer, remainder, f ); return offset; default: Com_Error( ERR_FATAL, "Bad origin in FS_Seek" ); return -1; } } else { FILE *file; file = FS_FileForHandle(f); switch( origin ) { case FS_SEEK_CUR: _origin = SEEK_CUR; break; case FS_SEEK_END: _origin = SEEK_END; break; case FS_SEEK_SET: _origin = SEEK_SET; break; default: Com_Error( ERR_FATAL, "Bad origin in FS_Seek" ); break; } return fseek( file, offset, _origin ); } } /* ====================================================================================== CONVENIENCE FUNCTIONS FOR ENTIRE FILES ====================================================================================== */ int FS_FileIsInPAK(const char *filename, int *pChecksum ) { searchpath_t *search; pack_t *pak; fileInPack_t *pakFile; long hash = 0; if ( !fs_searchpaths ) { Com_Error( ERR_FATAL, "Filesystem call made without initialization" ); } if ( !filename ) { Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed" ); } // qpaths are not supposed to have a leading slash if ( filename[0] == '/' || filename[0] == '\\' ) { filename++; } // make absolutely sure that it can't back up the path. // The searchpaths do guarantee that something will always // be prepended, so we don't need to worry about "c:" or "//limbo" if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) { return -1; } // // search through the path, one element at a time // for ( search = fs_searchpaths ; search ; search = search->next ) { // if (search->pack) { hash = FS_HashFileName(filename, search->pack->hashSize); } // is the element a pak file? if ( search->pack && search->pack->hashTable[hash] ) { // disregard if it doesn't match one of the allowed pure pak files if ( !FS_PakIsPure(search->pack) ) { continue; } // look through all the pak file elements pak = search->pack; pakFile = pak->hashTable[hash]; do { // case and separator insensitive comparisons if ( !FS_FilenameCompare( pakFile->name, filename ) ) { if (pChecksum) { *pChecksum = pak->pure_checksum; } return 1; } pakFile = pakFile->next; } while(pakFile != NULL); } } return -1; } /* ============ FS_ReadFileDir Filename are relative to the quake search path a null buffer will just return the file length without loading If searchPath is non-NULL search only in that specific search path ============ */ long FS_ReadFileDir(const char *qpath, void *searchPath, qboolean unpure, void **buffer) { fileHandle_t h; searchpath_t *search; byte* buf; qboolean isConfig; long len; if ( !fs_searchpaths ) { Com_Error( ERR_FATAL, "Filesystem call made without initialization" ); } if ( !qpath || !qpath[0] ) { Com_Error( ERR_FATAL, "FS_ReadFile with empty name" ); } buf = NULL; // quiet compiler warning // if this is a .cfg file and we are playing back a journal, read // it from the journal file if ( strstr( qpath, ".cfg" ) ) { isConfig = qtrue; if ( com_journal && com_journal->integer == 2 ) { int r; Com_DPrintf( "Loading %s from journal file.\n", qpath ); r = FS_Read( &len, sizeof( len ), com_journalDataFile ); if ( r != sizeof( len ) ) { if (buffer != NULL) *buffer = NULL; return -1; } // if the file didn't exist when the journal was created if (!len) { if (buffer == NULL) { return 1; // hack for old journal files } *buffer = NULL; return -1; } if (buffer == NULL) { return len; } buf = Hunk_AllocateTempMemory(len+1); *buffer = buf; r = FS_Read( buf, len, com_journalDataFile ); if ( r != len ) { Com_Error( ERR_FATAL, "Read from journalDataFile failed" ); } fs_loadCount++; fs_loadStack++; // guarantee that it will have a trailing 0 for string operations buf[len] = 0; return len; } } else { isConfig = qfalse; } search = searchPath; if(search == NULL) { // look for it in the filesystem or pack files len = FS_FOpenFileRead(qpath, &h, qfalse); } else { // look for it in a specific search path only len = FS_FOpenFileReadDir(qpath, search, &h, qfalse, unpure); } if ( h == 0 ) { if ( buffer ) { *buffer = NULL; } // if we are journalling and it is a config file, write a zero to the journal file if ( isConfig && com_journal && com_journal->integer == 1 ) { Com_DPrintf( "Writing zero for %s to journal file.\n", qpath ); len = 0; FS_Write( &len, sizeof( len ), com_journalDataFile ); FS_Flush( com_journalDataFile ); } return -1; } if ( !buffer ) { if ( isConfig && com_journal && com_journal->integer == 1 ) { Com_DPrintf( "Writing len for %s to journal file.\n", qpath ); FS_Write( &len, sizeof( len ), com_journalDataFile ); FS_Flush( com_journalDataFile ); } FS_FCloseFile( h); return len; } fs_loadCount++; fs_loadStack++; buf = Hunk_AllocateTempMemory(len+1); *buffer = buf; FS_Read (buf, len, h); // guarantee that it will have a trailing 0 for string operations buf[len] = 0; FS_FCloseFile( h ); // if we are journalling and it is a config file, write it to the journal file if ( isConfig && com_journal && com_journal->integer == 1 ) { Com_DPrintf( "Writing %s to journal file.\n", qpath ); FS_Write( &len, sizeof( len ), com_journalDataFile ); FS_Write( buf, len, com_journalDataFile ); FS_Flush( com_journalDataFile ); } return len; } /* ============ FS_ReadFile Filename are relative to the quake search path a null buffer will just return the file length without loading ============ */ long FS_ReadFile(const char *qpath, void **buffer) { return FS_ReadFileDir(qpath, NULL, qfalse, buffer); } /* ============= FS_FreeFile ============= */ void FS_FreeFile( void *buffer ) { if ( !fs_searchpaths ) { Com_Error( ERR_FATAL, "Filesystem call made without initialization" ); } if ( !buffer ) { Com_Error( ERR_FATAL, "FS_FreeFile( NULL )" ); } fs_loadStack--; Hunk_FreeTempMemory( buffer ); // if all of our temp files are free, clear all of our space if ( fs_loadStack == 0 ) { Hunk_ClearTempMemory(); } } /* ============ FS_WriteFile Filename are relative to the quake search path ============ */ void FS_WriteFile( const char *qpath, const void *buffer, int size ) { fileHandle_t f; if ( !fs_searchpaths ) { Com_Error( ERR_FATAL, "Filesystem call made without initialization" ); } if ( !qpath || !buffer ) { Com_Error( ERR_FATAL, "FS_WriteFile: NULL parameter" ); } f = FS_FOpenFileWrite( qpath ); if ( !f ) { Com_Printf( "Failed to open %s\n", qpath ); return; } FS_Write( buffer, size, f ); FS_FCloseFile( f ); } /* ========================================================================== ZIP FILE LOADING ========================================================================== */ /* ================= FS_LoadZipFile Creates a new pak_t in the search chain for the contents of a zip file. ================= */ static pack_t *FS_LoadZipFile(const char *zipfile, const char *basename) { fileInPack_t *buildBuffer; pack_t *pack; unzFile uf; int err; unz_global_info gi; char filename_inzip[MAX_ZPATH]; unz_file_info file_info; int i, len; long hash; int fs_numHeaderLongs; int *fs_headerLongs; char *namePtr; fs_numHeaderLongs = 0; uf = unzOpen(zipfile); err = unzGetGlobalInfo (uf,&gi); if (err != UNZ_OK) return NULL; len = 0; unzGoToFirstFile(uf); for (i = 0; i < gi.number_entry; i++) { err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0); if (err != UNZ_OK) { break; } len += strlen(filename_inzip) + 1; unzGoToNextFile(uf); } buildBuffer = Z_Malloc( (gi.number_entry * sizeof( fileInPack_t )) + len ); namePtr = ((char *) buildBuffer) + gi.number_entry * sizeof( fileInPack_t ); fs_headerLongs = Z_Malloc( ( gi.number_entry + 1 ) * sizeof(int) ); fs_headerLongs[ fs_numHeaderLongs++ ] = LittleLong( fs_checksumFeed ); // get the hash table size from the number of files in the zip // because lots of custom pk3 files have less than 32 or 64 files for (i = 1; i <= MAX_FILEHASH_SIZE; i <<= 1) { if (i > gi.number_entry) { break; } } pack = Z_Malloc( sizeof( pack_t ) + i * sizeof(fileInPack_t *) ); pack->hashSize = i; pack->hashTable = (fileInPack_t **) (((char *) pack) + sizeof( pack_t )); for(i = 0; i < pack->hashSize; i++) { pack->hashTable[i] = NULL; } Q_strncpyz( pack->pakFilename, zipfile, sizeof( pack->pakFilename ) ); Q_strncpyz( pack->pakBasename, basename, sizeof( pack->pakBasename ) ); // strip .pk3 if needed if ( strlen( pack->pakBasename ) > 4 && !Q_stricmp( pack->pakBasename + strlen( pack->pakBasename ) - 4, ".pk3" ) ) { pack->pakBasename[strlen( pack->pakBasename ) - 4] = 0; } pack->handle = uf; pack->numfiles = gi.number_entry; unzGoToFirstFile(uf); for (i = 0; i < gi.number_entry; i++) { err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0); if (err != UNZ_OK) { break; } if (file_info.uncompressed_size > 0) { fs_headerLongs[fs_numHeaderLongs++] = LittleLong(file_info.crc); } Q_strlwr( filename_inzip ); hash = FS_HashFileName(filename_inzip, pack->hashSize); buildBuffer[i].name = namePtr; strcpy( buildBuffer[i].name, filename_inzip ); namePtr += strlen(filename_inzip) + 1; // store the file position in the zip buildBuffer[i].pos = unzGetOffset(uf); buildBuffer[i].len = file_info.uncompressed_size; buildBuffer[i].next = pack->hashTable[hash]; pack->hashTable[hash] = &buildBuffer[i]; unzGoToNextFile(uf); } pack->checksum = Com_BlockChecksum( &fs_headerLongs[ 1 ], sizeof(*fs_headerLongs) * ( fs_numHeaderLongs - 1 ) ); pack->pure_checksum = Com_BlockChecksum( fs_headerLongs, sizeof(*fs_headerLongs) * fs_numHeaderLongs ); pack->checksum = LittleLong( pack->checksum ); pack->pure_checksum = LittleLong( pack->pure_checksum ); Z_Free(fs_headerLongs); pack->buildBuffer = buildBuffer; return pack; } /* ================= FS_FreePak Frees a pak structure and releases all associated resources ================= */ static void FS_FreePak(pack_t *thepak) { unzClose(thepak->handle); Z_Free(thepak->buildBuffer); Z_Free(thepak); } /* ================= FS_GetZipChecksum Compares whether the given pak file matches a referenced checksum ================= */ qboolean FS_CompareZipChecksum(const char *zipfile) { pack_t *thepak; int index, checksum; thepak = FS_LoadZipFile(zipfile, ""); if(!thepak) return qfalse; checksum = thepak->checksum; FS_FreePak(thepak); for(index = 0; index < fs_numServerReferencedPaks; index++) { if(checksum == fs_serverReferencedPaks[index]) return qtrue; } return qfalse; } /* ================================================================================= DIRECTORY SCANNING FUNCTIONS ================================================================================= */ #define MAX_FOUND_FILES 0x1000 static int FS_ReturnPath( const char *zname, char *zpath, int *depth ) { int len, at, newdep; newdep = 0; zpath[0] = 0; len = 0; at = 0; while(zname[at] != 0) { if (zname[at]=='/' || zname[at]=='\\') { len = at; newdep++; } at++; } strcpy(zpath, zname); zpath[len] = 0; *depth = newdep; return len; } /* ================== FS_AddFileToList ================== */ static int FS_AddFileToList( char *name, char *list[MAX_FOUND_FILES], int nfiles ) { int i; if ( nfiles == MAX_FOUND_FILES - 1 ) { return nfiles; } for ( i = 0 ; i < nfiles ; i++ ) { if ( !Q_stricmp( name, list[i] ) ) { return nfiles; // already in list } } list[nfiles] = CopyString( name ); nfiles++; return nfiles; } /* =============== FS_ListFilteredFiles Returns a uniqued list of files that match the given criteria from all search paths =============== */ char **FS_ListFilteredFiles( const char *path, const char *extension, char *filter, int *numfiles, qboolean allowNonPureFilesOnDisk ) { int nfiles; char **listCopy; char *list[MAX_FOUND_FILES]; searchpath_t *search; int i; int pathLength; int extensionLength; int length, pathDepth, temp; pack_t *pak; fileInPack_t *buildBuffer; char zpath[MAX_ZPATH]; if ( !fs_searchpaths ) { Com_Error( ERR_FATAL, "Filesystem call made without initialization" ); } if ( !path ) { *numfiles = 0; return NULL; } if ( !extension ) { extension = ""; } pathLength = strlen( path ); if ( path[pathLength-1] == '\\' || path[pathLength-1] == '/' ) { pathLength--; } extensionLength = strlen( extension ); nfiles = 0; FS_ReturnPath(path, zpath, &pathDepth); // // search through the path, one element at a time, adding to list // for (search = fs_searchpaths ; search ; search = search->next) { // is the element a pak file? if (search->pack) { //ZOID: If we are pure, don't search for files on paks that // aren't on the pure list if ( !FS_PakIsPure(search->pack) ) { continue; } // look through all the pak file elements pak = search->pack; buildBuffer = pak->buildBuffer; for (i = 0; i < pak->numfiles; i++) { char *name; int zpathLen, depth; // check for directory match name = buildBuffer[i].name; // if (filter) { // case insensitive if (!Com_FilterPath( filter, name, qfalse )) continue; // unique the match nfiles = FS_AddFileToList( name, list, nfiles ); } else { zpathLen = FS_ReturnPath(name, zpath, &depth); if ( (depth-pathDepth)>2 || pathLength > zpathLen || Q_stricmpn( name, path, pathLength ) ) { continue; } // check for extension match length = strlen( name ); if ( length < extensionLength ) { continue; } if ( Q_stricmp( name + length - extensionLength, extension ) ) { continue; } // unique the match temp = pathLength; if (pathLength) { temp++; // include the '/' } nfiles = FS_AddFileToList( name + temp, list, nfiles ); } } } else if (search->dir) { // scan for files in the filesystem char *netpath; int numSysFiles; char **sysFiles; char *name; // don't scan directories for files if we are pure or restricted if ( fs_numServerPaks && !allowNonPureFilesOnDisk ) { continue; } else { netpath = FS_BuildOSPath( search->dir->path, search->dir->gamedir, path ); sysFiles = Sys_ListFiles( netpath, extension, filter, &numSysFiles, qfalse ); for ( i = 0 ; i < numSysFiles ; i++ ) { // unique the match name = sysFiles[i]; nfiles = FS_AddFileToList( name, list, nfiles ); } Sys_FreeFileList( sysFiles ); } } } // return a copy of the list *numfiles = nfiles; if ( !nfiles ) { return NULL; } listCopy = Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ) ); for ( i = 0 ; i < nfiles ; i++ ) { listCopy[i] = list[i]; } listCopy[i] = NULL; return listCopy; } /* ================= FS_ListFiles ================= */ char **FS_ListFiles( const char *path, const char *extension, int *numfiles ) { return FS_ListFilteredFiles( path, extension, NULL, numfiles, qfalse ); } /* ================= FS_FreeFileList ================= */ void FS_FreeFileList( char **list ) { int i; if ( !fs_searchpaths ) { Com_Error( ERR_FATAL, "Filesystem call made without initialization" ); } if ( !list ) { return; } for ( i = 0 ; list[i] ; i++ ) { Z_Free( list[i] ); } Z_Free( list ); } /* ================ FS_GetFileList ================ */ int FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) { int nFiles, i, nTotal, nLen; char **pFiles = NULL; *listbuf = 0; nFiles = 0; nTotal = 0; if (Q_stricmp(path, "$modlist") == 0) { return FS_GetModList(listbuf, bufsize); } pFiles = FS_ListFiles(path, extension, &nFiles); for (i =0; i < nFiles; i++) { nLen = strlen(pFiles[i]) + 1; if (nTotal + nLen + 1 < bufsize) { strcpy(listbuf, pFiles[i]); listbuf += nLen; nTotal += nLen; } else { nFiles = i; break; } } FS_FreeFileList(pFiles); return nFiles; } /* ======================= Sys_ConcatenateFileLists mkv: Naive implementation. Concatenates three lists into a new list, and frees the old lists from the heap. bk001129 - from cvs1.17 (mkv) FIXME TTimo those two should move to common.c next to Sys_ListFiles ======================= */ static unsigned int Sys_CountFileList(char **list) { int i = 0; if (list) { while (*list) { list++; i++; } } return i; } static char** Sys_ConcatenateFileLists( char **list0, char **list1 ) { int totalLength = 0; char** cat = NULL, **dst, **src; totalLength += Sys_CountFileList(list0); totalLength += Sys_CountFileList(list1); /* Create new list. */ dst = cat = Z_Malloc( ( totalLength + 1 ) * sizeof( char* ) ); /* Copy over lists. */ if (list0) { for (src = list0; *src; src++, dst++) *dst = *src; } if (list1) { for (src = list1; *src; src++, dst++) *dst = *src; } // Terminate the list *dst = NULL; // Free our old lists. // NOTE: not freeing their content, it's been merged in dst and still being used if (list0) Z_Free( list0 ); if (list1) Z_Free( list1 ); return cat; } /* ================ FS_GetModDescription ================ */ void FS_GetModDescription( const char *modDir, char *description, int descriptionLen ) { fileHandle_t descHandle; char descPath[MAX_QPATH]; int nDescLen; FILE *file; Com_sprintf( descPath, sizeof ( descPath ), "%s/description.txt", modDir ); nDescLen = FS_SV_FOpenFileRead( descPath, &descHandle ); if ( nDescLen > 0 && descHandle ) { file = FS_FileForHandle(descHandle); Com_Memset( description, 0, descriptionLen ); nDescLen = fread(description, 1, descriptionLen, file); if (nDescLen >= 0) { description[nDescLen] = '\0'; } FS_FCloseFile(descHandle); } else { Q_strncpyz( description, modDir, descriptionLen ); } } /* ================ FS_GetModList Returns a list of mod directory names A mod directory is a peer to baseq3 with a pk3 or pk3dir in it ================ */ int FS_GetModList( char *listbuf, int bufsize ) { int nMods, i, j, k, nTotal, nLen, nPaks, nDirs, nPakDirs, nPotential, nDescLen; char **pFiles = NULL; char **pPaks = NULL; char **pDirs = NULL; char *name, *path; char description[MAX_OSPATH]; int dummy; char **pFiles0 = NULL; qboolean bDrop = qfalse; // paths to search for mods const char * const paths[] = { fs_basepath->string, fs_homepath->string, fs_steampath->string, fs_gogpath->string }; *listbuf = 0; nMods = nTotal = 0; // iterate through paths and get list of potential mods for (i = 0; i < ARRAY_LEN(paths); i++) { pFiles0 = Sys_ListFiles(paths[i], NULL, NULL, &dummy, qtrue); // Sys_ConcatenateFileLists frees the lists so Sys_FreeFileList isn't required pFiles = Sys_ConcatenateFileLists(pFiles, pFiles0); } nPotential = Sys_CountFileList(pFiles); for (i = 0; i < nPotential; i++) { name = pFiles[i]; // NOTE: cleaner would involve more changes // ignore duplicate mod directories if (i != 0) { bDrop = qfalse; for (j = 0; j < i; j++) { if (Q_stricmp(pFiles[j], name) == 0) { // this one can be dropped bDrop = qtrue; break; } } } // we also drop "baseq3" "." and ".." if (bDrop || Q_stricmp(name, com_basegame->string) == 0 || Q_stricmpn(name, ".", 1) == 0) { continue; } // in order to be a valid mod the directory must contain at least one .pk3 or .pk3dir // we didn't keep the information when we merged the directory names, as to what OS Path it was found under // so we will try each of them here for (j = 0; j < ARRAY_LEN(paths); j++) { path = FS_BuildOSPath(paths[j], name, ""); nPaks = nDirs = nPakDirs = 0; pPaks = Sys_ListFiles(path, ".pk3", NULL, &nPaks, qfalse); pDirs = Sys_ListFiles(path, "/", NULL, &nDirs, qfalse); for (k = 0; k < nDirs; k++) { // we only want to count directories ending with ".pk3dir" if (FS_IsExt(pDirs[k], ".pk3dir", strlen(pDirs[k]))) { nPakDirs++; } } // we only use Sys_ListFiles to check whether files are present Sys_FreeFileList(pPaks); Sys_FreeFileList(pDirs); if (nPaks > 0 || nPakDirs > 0) { break; } } if (nPaks > 0 || nPakDirs > 0) { nLen = strlen(name) + 1; // nLen is the length of the mod path // we need to see if there is a description available FS_GetModDescription(name, description, sizeof(description)); nDescLen = strlen(description) + 1; if (nTotal + nLen + 1 + nDescLen + 1 < bufsize) { strcpy(listbuf, name); listbuf += nLen; strcpy(listbuf, description); listbuf += nDescLen; nTotal += nLen + nDescLen; nMods++; } else { break; } } } Sys_FreeFileList( pFiles ); return nMods; } //============================================================================ /* ================ FS_Dir_f ================ */ void FS_Dir_f( void ) { char *path; char *extension; char **dirnames; int ndirs; int i; if ( Cmd_Argc() < 2 || Cmd_Argc() > 3 ) { Com_Printf( "usage: dir <directory> [extension]\n" ); return; } if ( Cmd_Argc() == 2 ) { path = Cmd_Argv( 1 ); extension = ""; } else { path = Cmd_Argv( 1 ); extension = Cmd_Argv( 2 ); } Com_Printf( "Directory of %s %s\n", path, extension ); Com_Printf( "---------------\n" ); dirnames = FS_ListFiles( path, extension, &ndirs ); for ( i = 0; i < ndirs; i++ ) { Com_Printf( "%s\n", dirnames[i] ); } FS_FreeFileList( dirnames ); } /* =========== FS_ConvertPath =========== */ void FS_ConvertPath( char *s ) { while (*s) { if ( *s == '\\' || *s == ':' ) { *s = '/'; } s++; } } /* =========== FS_PathCmp Ignore case and seprator char distinctions =========== */ int FS_PathCmp( const char *s1, const char *s2 ) { int c1, c2; do { c1 = *s1++; c2 = *s2++; if (c1 >= 'a' && c1 <= 'z') { c1 -= ('a' - 'A'); } if (c2 >= 'a' && c2 <= 'z') { c2 -= ('a' - 'A'); } if ( c1 == '\\' || c1 == ':' ) { c1 = '/'; } if ( c2 == '\\' || c2 == ':' ) { c2 = '/'; } if (c1 < c2) { return -1; // strings not equal } if (c1 > c2) { return 1; } } while (c1); return 0; // strings are equal } /* ================ FS_SortFileList ================ */ void FS_SortFileList(char **filelist, int numfiles) { int i, j, k, numsortedfiles; char **sortedlist; sortedlist = Z_Malloc( ( numfiles + 1 ) * sizeof( *sortedlist ) ); sortedlist[0] = NULL; numsortedfiles = 0; for (i = 0; i < numfiles; i++) { for (j = 0; j < numsortedfiles; j++) { if (FS_PathCmp(filelist[i], sortedlist[j]) < 0) { break; } } for (k = numsortedfiles; k > j; k--) { sortedlist[k] = sortedlist[k-1]; } sortedlist[j] = filelist[i]; numsortedfiles++; } Com_Memcpy(filelist, sortedlist, numfiles * sizeof( *filelist ) ); Z_Free(sortedlist); } /* ================ FS_NewDir_f ================ */ void FS_NewDir_f( void ) { char *filter; char **dirnames; int ndirs; int i; if ( Cmd_Argc() < 2 ) { Com_Printf( "usage: fdir <filter>\n" ); Com_Printf( "example: fdir *q3dm*.bsp\n"); return; } filter = Cmd_Argv( 1 ); Com_Printf( "---------------\n" ); dirnames = FS_ListFilteredFiles( "", "", filter, &ndirs, qfalse ); FS_SortFileList(dirnames, ndirs); for ( i = 0; i < ndirs; i++ ) { FS_ConvertPath(dirnames[i]); Com_Printf( "%s\n", dirnames[i] ); } Com_Printf( "%d files listed\n", ndirs ); FS_FreeFileList( dirnames ); } /* ============ FS_Path_f ============ */ void FS_Path_f( void ) { searchpath_t *s; int i; Com_Printf ("We are looking in the current search path:\n"); for (s = fs_searchpaths; s; s = s->next) { if (s->pack) { Com_Printf ("%s (%i files)\n", s->pack->pakFilename, s->pack->numfiles); if ( fs_numServerPaks ) { if ( !FS_PakIsPure(s->pack) ) { Com_Printf( " not on the pure list\n" ); } else { Com_Printf( " on the pure list\n" ); } } } else { Com_Printf ("%s%c%s\n", s->dir->path, PATH_SEP, s->dir->gamedir ); } } Com_Printf( "\n" ); for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) { if ( fsh[i].handleFiles.file.o ) { Com_Printf( "handle %i: %s\n", i, fsh[i].name ); } } } /* ============ FS_TouchFile_f ============ */ void FS_TouchFile_f( void ) { fileHandle_t f; if ( Cmd_Argc() != 2 ) { Com_Printf( "Usage: touchFile <file>\n" ); return; } FS_FOpenFileRead( Cmd_Argv( 1 ), &f, qfalse ); if ( f ) { FS_FCloseFile( f ); } } /* ============ FS_Which ============ */ qboolean FS_Which(const char *filename, void *searchPath) { searchpath_t *search = searchPath; if(FS_FOpenFileReadDir(filename, search, NULL, qfalse, qfalse) > 0) { if(search->pack) { Com_Printf("File \"%s\" found in \"%s\"\n", filename, search->pack->pakFilename); return qtrue; } else if(search->dir) { Com_Printf( "File \"%s\" found at \"%s\"\n", filename, search->dir->fullpath); return qtrue; } } return qfalse; } /* ============ FS_Which_f ============ */ void FS_Which_f( void ) { searchpath_t *search; char *filename; filename = Cmd_Argv(1); if ( !filename[0] ) { Com_Printf( "Usage: which <file>\n" ); return; } // qpaths are not supposed to have a leading slash if ( filename[0] == '/' || filename[0] == '\\' ) { filename++; } // just wants to see if file is there for(search = fs_searchpaths; search; search = search->next) { if(FS_Which(filename, search)) return; } Com_Printf("File not found: \"%s\"\n", filename); } //=========================================================================== static int QDECL paksort( const void *a, const void *b ) { char *aa, *bb; aa = *(char **)a; bb = *(char **)b; return FS_PathCmp( aa, bb ); } /* ================ FS_AddGameDirectory Sets fs_gamedir, adds the directory to the head of the path, then loads the zip headers ================ */ void FS_AddGameDirectory( const char *path, const char *dir ) { searchpath_t *sp; searchpath_t *search; pack_t *pak; char curpath[MAX_OSPATH + 1], *pakfile; int numfiles; char **pakfiles; int pakfilesi; char **pakfilestmp; int numdirs; char **pakdirs; int pakdirsi; char **pakdirstmp; int pakwhich; int len; // Unique for ( sp = fs_searchpaths ; sp ; sp = sp->next ) { if ( sp->dir && !Q_stricmp(sp->dir->path, path) && !Q_stricmp(sp->dir->gamedir, dir)) { return; // we've already got this one } } Q_strncpyz( fs_gamedir, dir, sizeof( fs_gamedir ) ); // find all pak files in this directory Q_strncpyz(curpath, FS_BuildOSPath(path, dir, ""), sizeof(curpath)); curpath[strlen(curpath) - 1] = '\0'; // strip the trailing slash // Get .pk3 files pakfiles = Sys_ListFiles(curpath, ".pk3", NULL, &numfiles, qfalse); qsort( pakfiles, numfiles, sizeof(char*), paksort ); if ( fs_numServerPaks ) { numdirs = 0; pakdirs = NULL; } else { // Get top level directories (we'll filter them later since the Sys_ListFiles filtering is terrible) pakdirs = Sys_ListFiles(curpath, "/", NULL, &numdirs, qfalse); qsort( pakdirs, numdirs, sizeof(char *), paksort ); } pakfilesi = 0; pakdirsi = 0; while((pakfilesi < numfiles) || (pakdirsi < numdirs)) { // Check if a pakfile or pakdir comes next if (pakfilesi >= numfiles) { // We've used all the pakfiles, it must be a pakdir. pakwhich = 0; } else if (pakdirsi >= numdirs) { // We've used all the pakdirs, it must be a pakfile. pakwhich = 1; } else { // Could be either, compare to see which name comes first // Need tmp variables for appropriate indirection for paksort() pakfilestmp = &pakfiles[pakfilesi]; pakdirstmp = &pakdirs[pakdirsi]; pakwhich = (paksort(pakfilestmp, pakdirstmp) < 0); } if (pakwhich) { // The next .pk3 file is before the next .pk3dir pakfile = FS_BuildOSPath(path, dir, pakfiles[pakfilesi]); if ((pak = FS_LoadZipFile(pakfile, pakfiles[pakfilesi])) == 0) { // This isn't a .pk3! Next! pakfilesi++; continue; } Q_strncpyz(pak->pakPathname, curpath, sizeof(pak->pakPathname)); // store the game name for downloading Q_strncpyz(pak->pakGamename, dir, sizeof(pak->pakGamename)); fs_packFiles += pak->numfiles; search = Z_Malloc(sizeof(searchpath_t)); search->pack = pak; search->next = fs_searchpaths; fs_searchpaths = search; pakfilesi++; } else { // The next .pk3dir is before the next .pk3 file // But wait, this could be any directory, we're filtering to only ending with ".pk3dir" here. len = strlen(pakdirs[pakdirsi]); if (!FS_IsExt(pakdirs[pakdirsi], ".pk3dir", len)) { // This isn't a .pk3dir! Next! pakdirsi++; continue; } pakfile = FS_BuildOSPath(path, dir, pakdirs[pakdirsi]); // add the directory to the search path search = Z_Malloc(sizeof(searchpath_t)); search->dir = Z_Malloc(sizeof(*search->dir)); Q_strncpyz(search->dir->path, curpath, sizeof(search->dir->path)); // c:\quake3\baseq3 Q_strncpyz(search->dir->fullpath, pakfile, sizeof(search->dir->fullpath)); // c:\quake3\baseq3\mypak.pk3dir Q_strncpyz(search->dir->gamedir, pakdirs[pakdirsi], sizeof(search->dir->gamedir)); // mypak.pk3dir search->next = fs_searchpaths; fs_searchpaths = search; pakdirsi++; } } // done Sys_FreeFileList( pakfiles ); Sys_FreeFileList( pakdirs ); // // add the directory to the search path // search = Z_Malloc (sizeof(searchpath_t)); search->dir = Z_Malloc( sizeof( *search->dir ) ); Q_strncpyz(search->dir->path, path, sizeof(search->dir->path)); Q_strncpyz(search->dir->fullpath, curpath, sizeof(search->dir->fullpath)); Q_strncpyz(search->dir->gamedir, dir, sizeof(search->dir->gamedir)); search->next = fs_searchpaths; fs_searchpaths = search; } /* ================ FS_idPak ================ */ qboolean FS_idPak(char *pak, char *base, int numPaks) { int i; for (i = 0; i < NUM_ID_PAKS; i++) { if ( !FS_FilenameCompare(pak, va("%s/pak%d", base, i)) ) { break; } } if (i < numPaks) { return qtrue; } return qfalse; } /* ================ FS_CheckDirTraversal Check whether the string contains stuff like "../" to prevent directory traversal bugs and return qtrue if it does. ================ */ qboolean FS_CheckDirTraversal(const char *checkdir) { if(strstr(checkdir, "../") || strstr(checkdir, "..\\")) return qtrue; return qfalse; } /* ================ FS_InvalidGameDir return true if path is a reference to current directory or directory traversal ================ */ qboolean FS_InvalidGameDir( const char *gamedir ) { if ( !strcmp( gamedir, "." ) || !strcmp( gamedir, ".." ) || !strcmp( gamedir, "/" ) || !strcmp( gamedir, "\\" ) || strstr( gamedir, "/.." ) || strstr( gamedir, "\\.." ) || FS_CheckDirTraversal( gamedir ) ) { return qtrue; } return qfalse; } /* ================ FS_ComparePaks ---------------- dlstring == qtrue Returns a list of pak files that we should download from the server. They all get stored in the current gamedir and an FS_Restart will be fired up after we download them all. The string is the format: @remotename@localname [repeat] static int fs_numServerReferencedPaks; static int fs_serverReferencedPaks[MAX_SEARCH_PATHS]; static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS]; ---------------- dlstring == qfalse we are not interested in a download string format, we want something human-readable (this is used for diagnostics while connecting to a pure server) ================ */ qboolean FS_ComparePaks( char *neededpaks, int len, qboolean dlstring ) { searchpath_t *sp; qboolean havepak; char *origpos = neededpaks; int i; if (!fs_numServerReferencedPaks) return qfalse; // Server didn't send any pack information along *neededpaks = 0; for ( i = 0 ; i < fs_numServerReferencedPaks ; i++ ) { // Ok, see if we have this pak file havepak = qfalse; // never autodownload any of the id paks if(FS_idPak(fs_serverReferencedPakNames[i], BASEGAME, NUM_ID_PAKS) #ifndef STANDALONE || FS_idPak(fs_serverReferencedPakNames[i], BASETA, NUM_TA_PAKS) #endif ) { continue; } // Make sure the server cannot make us write to non-quake3 directories. if(FS_CheckDirTraversal(fs_serverReferencedPakNames[i])) { Com_Printf("WARNING: Invalid download name %s\n", fs_serverReferencedPakNames[i]); continue; } for ( sp = fs_searchpaths ; sp ; sp = sp->next ) { if ( sp->pack && sp->pack->checksum == fs_serverReferencedPaks[i] ) { havepak = qtrue; // This is it! break; } } if ( !havepak && fs_serverReferencedPakNames[i] && *fs_serverReferencedPakNames[i] ) { // Don't got it if (dlstring) { // We need this to make sure we won't hit the end of the buffer or the server could // overwrite non-pk3 files on clients by writing so much crap into neededpaks that // Q_strcat cuts off the .pk3 extension. origpos += strlen(origpos); // Remote name Q_strcat( neededpaks, len, "@"); Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] ); Q_strcat( neededpaks, len, ".pk3" ); // Local name Q_strcat( neededpaks, len, "@"); // Do we have one with the same name? if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) ) { char st[MAX_ZPATH]; // We already have one called this, we need to download it to another name // Make something up with the checksum in it Com_sprintf( st, sizeof( st ), "%s.%08x.pk3", fs_serverReferencedPakNames[i], fs_serverReferencedPaks[i] ); Q_strcat( neededpaks, len, st ); } else { Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] ); Q_strcat( neededpaks, len, ".pk3" ); } // Find out whether it might have overflowed the buffer and don't add this file to the // list if that is the case. if(strlen(origpos) + (origpos - neededpaks) >= len - 1) { *origpos = '\0'; break; } } else { Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] ); Q_strcat( neededpaks, len, ".pk3" ); // Do we have one with the same name? if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) ) { Q_strcat( neededpaks, len, " (local file exists with wrong checksum)"); } Q_strcat( neededpaks, len, "\n"); } } } if ( *neededpaks ) { return qtrue; } return qfalse; // We have them all } /* ================ FS_Shutdown Frees all resources. ================ */ void FS_Shutdown( qboolean closemfp ) { searchpath_t *p, *next; int i; for(i = 0; i < MAX_FILE_HANDLES; i++) { if (fsh[i].fileSize) { FS_FCloseFile(i); } } // free everything for(p = fs_searchpaths; p; p = next) { next = p->next; if(p->pack) FS_FreePak(p->pack); if (p->dir) Z_Free(p->dir); Z_Free(p); } // any FS_ calls will now be an error until reinitialized fs_searchpaths = NULL; Cmd_RemoveCommand( "path" ); Cmd_RemoveCommand( "dir" ); Cmd_RemoveCommand( "fdir" ); Cmd_RemoveCommand( "touchFile" ); Cmd_RemoveCommand( "which" ); #ifdef FS_MISSING if (closemfp) { fclose(missingFiles); } #endif } #ifndef STANDALONE void Com_AppendCDKey( const char *filename ); void Com_ReadCDKey( const char *filename ); #endif /* ================ FS_ReorderPurePaks NOTE TTimo: the reordering that happens here is not reflected in the cvars (\cvarlist *pak*) this can lead to misleading situations, see https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540 ================ */ static void FS_ReorderPurePaks( void ) { searchpath_t *s; int i; searchpath_t **p_insert_index, // for linked list reordering **p_previous; // when doing the scan fs_reordered = qfalse; // only relevant when connected to pure server if ( !fs_numServerPaks ) return; p_insert_index = &fs_searchpaths; // we insert in order at the beginning of the list for ( i = 0 ; i < fs_numServerPaks ; i++ ) { p_previous = p_insert_index; // track the pointer-to-current-item for (s = *p_insert_index; s; s = s->next) { // the part of the list before p_insert_index has been sorted already if (s->pack && fs_serverPaks[i] == s->pack->checksum) { fs_reordered = qtrue; // move this element to the insert list *p_previous = s->next; s->next = *p_insert_index; *p_insert_index = s; // increment insert list p_insert_index = &s->next; break; // iterate to next server pack } p_previous = &s->next; } } } /* ================ FS_Startup ================ */ static void FS_Startup( const char *gameName ) { const char *homePath; Com_Printf( "----- FS_Startup -----\n" ); fs_packFiles = 0; fs_debug = Cvar_Get( "fs_debug", "0", 0 ); fs_basepath = Cvar_Get ("fs_basepath", Sys_DefaultInstallPath(), CVAR_INIT|CVAR_PROTECTED ); fs_basegame = Cvar_Get ("fs_basegame", "", CVAR_INIT ); homePath = Sys_DefaultHomePath(); if (!homePath || !homePath[0]) { homePath = fs_basepath->string; } fs_homepath = Cvar_Get ("fs_homepath", homePath, CVAR_INIT|CVAR_PROTECTED ); fs_gamedirvar = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO ); if (!gameName[0]) { Cvar_ForceReset( "com_basegame" ); } if (!FS_FilenameCompare(fs_gamedirvar->string, gameName)) { // This is the standard base game. Servers and clients should // use "" and not the standard basegame name because this messes // up pak file negotiation and lots of other stuff Cvar_ForceReset( "fs_game" ); } if (FS_InvalidGameDir(gameName)) { Com_Error( ERR_DROP, "Invalid com_basegame '%s'", gameName ); } if (FS_InvalidGameDir(fs_basegame->string)) { Com_Error( ERR_DROP, "Invalid fs_basegame '%s'", fs_basegame->string ); } if (FS_InvalidGameDir(fs_gamedirvar->string)) { Com_Error( ERR_DROP, "Invalid fs_game '%s'", fs_gamedirvar->string ); } // add search path elements in reverse priority order fs_gogpath = Cvar_Get ("fs_gogpath", Sys_GogPath(), CVAR_INIT|CVAR_PROTECTED ); if (fs_gogpath->string[0]) { FS_AddGameDirectory( fs_gogpath->string, gameName ); } fs_steampath = Cvar_Get ("fs_steampath", Sys_SteamPath(), CVAR_INIT|CVAR_PROTECTED ); if (fs_steampath->string[0]) { FS_AddGameDirectory( fs_steampath->string, gameName ); } if (fs_basepath->string[0]) { FS_AddGameDirectory( fs_basepath->string, gameName ); } // fs_homepath is somewhat particular to *nix systems, only add if relevant #ifdef __APPLE__ fs_apppath = Cvar_Get ("fs_apppath", Sys_DefaultAppPath(), CVAR_INIT|CVAR_PROTECTED ); // Make MacOSX also include the base path included with the .app bundle if (fs_apppath->string[0]) FS_AddGameDirectory(fs_apppath->string, gameName); #endif // NOTE: same filtering below for mods and basegame if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string,fs_basepath->string)) { FS_CreatePath ( fs_homepath->string ); FS_AddGameDirectory ( fs_homepath->string, gameName ); } // check for additional base game so mods can be based upon other mods if ( fs_basegame->string[0] && Q_stricmp( fs_basegame->string, gameName ) ) { if (fs_gogpath->string[0]) { FS_AddGameDirectory(fs_gogpath->string, fs_basegame->string); } if (fs_steampath->string[0]) { FS_AddGameDirectory(fs_steampath->string, fs_basegame->string); } if (fs_basepath->string[0]) { FS_AddGameDirectory(fs_basepath->string, fs_basegame->string); } if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string,fs_basepath->string)) { FS_AddGameDirectory(fs_homepath->string, fs_basegame->string); } } // check for additional game folder for mods if ( fs_gamedirvar->string[0] && Q_stricmp( fs_gamedirvar->string, gameName ) ) { if (fs_gogpath->string[0]) { FS_AddGameDirectory(fs_gogpath->string, fs_gamedirvar->string); } if (fs_steampath->string[0]) { FS_AddGameDirectory(fs_steampath->string, fs_gamedirvar->string); } if (fs_basepath->string[0]) { FS_AddGameDirectory(fs_basepath->string, fs_gamedirvar->string); } if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string,fs_basepath->string)) { FS_AddGameDirectory(fs_homepath->string, fs_gamedirvar->string); } } #ifndef STANDALONE if (!com_standalone->integer) { Com_ReadCDKey(BASEGAME); if (fs_gamedirvar->string[0]) { Com_AppendCDKey(fs_gamedirvar->string); } } #endif // add our commands Cmd_AddCommand ("path", FS_Path_f); Cmd_AddCommand ("dir", FS_Dir_f ); Cmd_AddCommand ("fdir", FS_NewDir_f ); Cmd_AddCommand ("touchFile", FS_TouchFile_f ); Cmd_AddCommand ("which", FS_Which_f ); // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=506 // reorder the pure pk3 files according to server order FS_ReorderPurePaks(); // print the current search paths FS_Path_f(); fs_gamedirvar->modified = qfalse; // We just loaded, it's not modified Com_Printf( "----------------------\n" ); #ifdef FS_MISSING if (missingFiles == NULL) { missingFiles = Sys_FOpen( "\\missing.txt", "ab" ); } #endif Com_Printf( "%d files in pk3 files\n", fs_packFiles ); } #ifndef STANDALONE /* =================== FS_CheckPak0 Check whether any of the original id pak files is present, and start up in standalone mode, if there are none and a different com_basegame was set. Note: If you're building a game that doesn't depend on the Q3 media pak0.pk3, you'll want to remove this by defining STANDALONE in q_shared.h =================== */ static void FS_CheckPak0( void ) { searchpath_t *path; pack_t *curpack; qboolean founddemo = qfalse; unsigned int foundPak = 0, foundTA = 0; for( path = fs_searchpaths; path; path = path->next ) { const char* pakBasename = path->pack->pakBasename; if(!path->pack) continue; curpack = path->pack; if(!Q_stricmpn( curpack->pakGamename, "demoq3", MAX_OSPATH ) && !Q_stricmpn( pakBasename, "pak0", MAX_OSPATH )) { if(curpack->checksum == DEMO_PAK0_CHECKSUM) founddemo = qtrue; } else if(!Q_stricmpn( curpack->pakGamename, BASEGAME, MAX_OSPATH ) && strlen(pakBasename) == 4 && !Q_stricmpn( pakBasename, "pak", 3 ) && pakBasename[3] >= '0' && pakBasename[3] <= '0' + NUM_ID_PAKS - 1) { if( curpack->checksum != pak_checksums[pakBasename[3]-'0'] ) { if(pakBasename[3] == '0') { Com_Printf("\n\n" "**************************************************\n" "WARNING: " BASEGAME "/pak0.pk3 is present but its checksum (%u)\n" "is not correct. Please re-copy pak0.pk3 from your\n" "legitimate Q3 CDROM.\n" "**************************************************\n\n\n", curpack->checksum ); } else { Com_Printf("\n\n" "**************************************************\n" "WARNING: " BASEGAME "/pak%d.pk3 is present but its checksum (%u)\n" "is not correct. Please re-install the point release\n" "**************************************************\n\n\n", pakBasename[3]-'0', curpack->checksum ); } } foundPak |= 1<<(pakBasename[3]-'0'); } else if(!Q_stricmpn(curpack->pakGamename, BASETA, MAX_OSPATH) && strlen(pakBasename) == 4 && !Q_stricmpn(pakBasename, "pak", 3) && pakBasename[3] >= '0' && pakBasename[3] <= '0' + NUM_TA_PAKS - 1) { if(curpack->checksum != missionpak_checksums[pakBasename[3]-'0']) { Com_Printf("\n\n" "**************************************************\n" "WARNING: " BASETA "/pak%d.pk3 is present but its checksum (%u)\n" "is not correct. Please re-install Team Arena\n" "**************************************************\n\n\n", pakBasename[3]-'0', curpack->checksum ); } foundTA |= 1 << (pakBasename[3]-'0'); } else { int index; // Finally check whether this pak's checksum is listed because the user tried // to trick us by renaming the file, and set foundPak's highest bit to indicate this case. for(index = 0; index < ARRAY_LEN(pak_checksums); index++) { if(curpack->checksum == pak_checksums[index]) { Com_Printf("\n\n" "**************************************************\n" "WARNING: %s is renamed pak file %s%cpak%d.pk3\n" "Running in standalone mode won't work\n" "Please rename, or remove this file\n" "**************************************************\n\n\n", curpack->pakFilename, BASEGAME, PATH_SEP, index); foundPak |= 0x80000000; } } for(index = 0; index < ARRAY_LEN(missionpak_checksums); index++) { if(curpack->checksum == missionpak_checksums[index]) { Com_Printf("\n\n" "**************************************************\n" "WARNING: %s is renamed pak file %s%cpak%d.pk3\n" "Running in standalone mode won't work\n" "Please rename, or remove this file\n" "**************************************************\n\n\n", curpack->pakFilename, BASETA, PATH_SEP, index); foundTA |= 0x80000000; } } } } if(!foundPak && !foundTA && Q_stricmp(com_basegame->string, BASEGAME)) { Cvar_Set("com_standalone", "1"); } else Cvar_Set("com_standalone", "0"); if(!com_standalone->integer) { if(!(foundPak & 0x01)) { if(founddemo) { Com_Printf( "\n\n" "**************************************************\n" "WARNING: It looks like you're using pak0.pk3\n" "from the demo. This may work fine, but it is not\n" "guaranteed or supported.\n" "**************************************************\n\n\n" ); foundPak |= 0x01; } } } if(!com_standalone->integer && (foundPak & 0x1ff) != 0x1ff) { char errorText[MAX_STRING_CHARS] = ""; if((foundPak & 0x01) != 0x01) { Q_strcat(errorText, sizeof(errorText), "\"pak0.pk3\" is missing. Please copy it " "from your legitimate Q3 CDROM. "); } if((foundPak & 0x1fe) != 0x1fe) { Q_strcat(errorText, sizeof(errorText), "Point Release files are missing. Please " "re-install the 1.32 point release. "); } Q_strcat(errorText, sizeof(errorText), va("Also check that your ioq3 executable is in " "the correct place and that every file " "in the \"%s\" directory is present and readable", BASEGAME)); Com_Error(ERR_FATAL, "%s", errorText); } if(!com_standalone->integer && foundTA && (foundTA & 0x0f) != 0x0f) { char errorText[MAX_STRING_CHARS] = ""; if((foundTA & 0x01) != 0x01) { Com_sprintf(errorText, sizeof(errorText), "\"" BASETA "%cpak0.pk3\" is missing. Please copy it " "from your legitimate Quake 3 Team Arena CDROM. ", PATH_SEP); } if((foundTA & 0x0e) != 0x0e) { Q_strcat(errorText, sizeof(errorText), "Team Arena Point Release files are missing. Please " "re-install the latest Team Arena point release."); } Com_Error(ERR_FATAL, "%s", errorText); } } #endif /* ===================== FS_LoadedPakChecksums Returns a space separated string containing the checksums of all loaded pk3 files. Servers with sv_pure set will get this string and pass it to clients. ===================== */ const char *FS_LoadedPakChecksums( void ) { static char info[BIG_INFO_STRING]; searchpath_t *search; info[0] = 0; for ( search = fs_searchpaths ; search ; search = search->next ) { // is the element a pak file? if ( !search->pack ) { continue; } Q_strcat( info, sizeof( info ), va("%i ", search->pack->checksum ) ); } return info; } /* ===================== FS_LoadedPakNames Returns a space separated string containing the names of all loaded pk3 files. Servers with sv_pure set will get this string and pass it to clients. ===================== */ const char *FS_LoadedPakNames( void ) { static char info[BIG_INFO_STRING]; searchpath_t *search; info[0] = 0; for ( search = fs_searchpaths ; search ; search = search->next ) { // is the element a pak file? if ( !search->pack ) { continue; } if (*info) { Q_strcat(info, sizeof( info ), " " ); } Q_strcat( info, sizeof( info ), search->pack->pakBasename ); } return info; } /* ===================== FS_LoadedPakPureChecksums Returns a space separated string containing the pure checksums of all loaded pk3 files. Servers with sv_pure use these checksums to compare with the checksums the clients send back to the server. ===================== */ const char *FS_LoadedPakPureChecksums( void ) { static char info[BIG_INFO_STRING]; searchpath_t *search; info[0] = 0; for ( search = fs_searchpaths ; search ; search = search->next ) { // is the element a pak file? if ( !search->pack ) { continue; } Q_strcat( info, sizeof( info ), va("%i ", search->pack->pure_checksum ) ); } return info; } /* ===================== FS_ReferencedPakChecksums Returns a space separated string containing the checksums of all referenced pk3 files. The server will send this to the clients so they can check which files should be auto-downloaded. ===================== */ const char *FS_ReferencedPakChecksums( void ) { static char info[BIG_INFO_STRING]; searchpath_t *search; info[0] = 0; for ( search = fs_searchpaths ; search ; search = search->next ) { // is the element a pak file? if ( search->pack ) { if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, com_basegame->string, strlen(com_basegame->string))) { Q_strcat( info, sizeof( info ), va("%i ", search->pack->checksum ) ); } } } return info; } /* ===================== FS_ReferencedPakPureChecksums Returns a space separated string containing the pure checksums of all referenced pk3 files. Servers with sv_pure set will get this string back from clients for pure validation The string has a specific order, "cgame ui @ ref1 ref2 ref3 ..." ===================== */ const char *FS_ReferencedPakPureChecksums( void ) { static char info[BIG_INFO_STRING]; searchpath_t *search; int nFlags, numPaks, checksum; info[0] = 0; checksum = fs_checksumFeed; numPaks = 0; for (nFlags = FS_CGAME_REF; nFlags; nFlags = nFlags >> 1) { if (nFlags & FS_GENERAL_REF) { // add a delimter between must haves and general refs //Q_strcat(info, sizeof(info), "@ "); info[strlen(info)+1] = '\0'; info[strlen(info)+2] = '\0'; info[strlen(info)] = '@'; info[strlen(info)] = ' '; } for ( search = fs_searchpaths ; search ; search = search->next ) { // is the element a pak file and has it been referenced based on flag? if ( search->pack && (search->pack->referenced & nFlags)) { Q_strcat( info, sizeof( info ), va("%i ", search->pack->pure_checksum ) ); if (nFlags & (FS_CGAME_REF | FS_UI_REF)) { break; } checksum ^= search->pack->pure_checksum; numPaks++; } } } // last checksum is the encoded number of referenced pk3s checksum ^= numPaks; Q_strcat( info, sizeof( info ), va("%i ", checksum ) ); return info; } /* ===================== FS_ReferencedPakNames Returns a space separated string containing the names of all referenced pk3 files. The server will send this to the clients so they can check which files should be auto-downloaded. ===================== */ const char *FS_ReferencedPakNames( void ) { static char info[BIG_INFO_STRING]; searchpath_t *search; info[0] = 0; // we want to return ALL pk3's from the fs_game path // and referenced one's from baseq3 for ( search = fs_searchpaths ; search ; search = search->next ) { // is the element a pak file? if ( search->pack ) { if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, com_basegame->string, strlen(com_basegame->string))) { if (*info) { Q_strcat(info, sizeof( info ), " " ); } Q_strcat( info, sizeof( info ), search->pack->pakGamename ); Q_strcat( info, sizeof( info ), "/" ); Q_strcat( info, sizeof( info ), search->pack->pakBasename ); } } } return info; } /* ===================== FS_ClearPakReferences ===================== */ void FS_ClearPakReferences( int flags ) { searchpath_t *search; if ( !flags ) { flags = -1; } for ( search = fs_searchpaths; search; search = search->next ) { // is the element a pak file and has it been referenced? if ( search->pack ) { search->pack->referenced &= ~flags; } } } /* ===================== FS_PureServerSetLoadedPaks If the string is empty, all data sources will be allowed. If not empty, only pk3 files that match one of the space separated checksums will be checked for files, with the exception of .cfg and .dat files. ===================== */ void FS_PureServerSetLoadedPaks( const char *pakSums, const char *pakNames ) { int i, c, d; Cmd_TokenizeString( pakSums ); c = Cmd_Argc(); if ( c > MAX_SEARCH_PATHS ) { c = MAX_SEARCH_PATHS; } fs_numServerPaks = c; for ( i = 0 ; i < c ; i++ ) { fs_serverPaks[i] = atoi( Cmd_Argv( i ) ); } if (fs_numServerPaks) { Com_DPrintf( "Connected to a pure server.\n" ); } else { if (fs_reordered) { // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540 // force a restart to make sure the search order will be correct Com_DPrintf( "FS search reorder is required\n" ); FS_Restart(fs_checksumFeed); return; } } for ( i = 0 ; i < c ; i++ ) { if (fs_serverPakNames[i]) { Z_Free(fs_serverPakNames[i]); } fs_serverPakNames[i] = NULL; } if ( pakNames && *pakNames ) { Cmd_TokenizeString( pakNames ); d = Cmd_Argc(); if ( d > MAX_SEARCH_PATHS ) { d = MAX_SEARCH_PATHS; } for ( i = 0 ; i < d ; i++ ) { fs_serverPakNames[i] = CopyString( Cmd_Argv( i ) ); } } } /* ===================== FS_PureServerSetReferencedPaks The checksums and names of the pk3 files referenced at the server are sent to the client and stored here. The client will use these checksums to see if any pk3 files need to be auto-downloaded. ===================== */ void FS_PureServerSetReferencedPaks( const char *pakSums, const char *pakNames ) { int i, c, d = 0; Cmd_TokenizeString( pakSums ); c = Cmd_Argc(); if ( c > MAX_SEARCH_PATHS ) { c = MAX_SEARCH_PATHS; } for ( i = 0 ; i < c ; i++ ) { fs_serverReferencedPaks[i] = atoi( Cmd_Argv( i ) ); } for (i = 0 ; i < ARRAY_LEN(fs_serverReferencedPakNames); i++) { if(fs_serverReferencedPakNames[i]) Z_Free(fs_serverReferencedPakNames[i]); fs_serverReferencedPakNames[i] = NULL; } if ( pakNames && *pakNames ) { Cmd_TokenizeString( pakNames ); d = Cmd_Argc(); if(d > c) d = c; for ( i = 0 ; i < d ; i++ ) { fs_serverReferencedPakNames[i] = CopyString( Cmd_Argv( i ) ); } } // ensure that there are as many checksums as there are pak names. if(d < c) c = d; fs_numServerReferencedPaks = c; } /* ================ FS_InitFilesystem Called only at initial startup, not when the filesystem is resetting due to a game change ================ */ void FS_InitFilesystem( void ) { // allow command line parms to override our defaults // we have to specially handle this, because normal command // line variable sets don't happen until after the filesystem // has already been initialized Com_StartupVariable("fs_basepath"); Com_StartupVariable("fs_homepath"); Com_StartupVariable("fs_game"); if(!FS_FilenameCompare(Cvar_VariableString("fs_game"), com_basegame->string)) Cvar_Set("fs_game", ""); // try to start up normally FS_Startup(com_basegame->string); #ifndef STANDALONE FS_CheckPak0( ); #endif // if we can't find default.cfg, assume that the paths are // busted and error out now, rather than getting an unreadable // graphics screen when the font fails to load if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) { Com_Error( ERR_FATAL, "Couldn't load default.cfg" ); } Q_strncpyz(lastValidBase, fs_basepath->string, sizeof(lastValidBase)); Q_strncpyz(lastValidComBaseGame, com_basegame->string, sizeof(lastValidComBaseGame)); Q_strncpyz(lastValidFsBaseGame, fs_basegame->string, sizeof(lastValidFsBaseGame)); Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame)); } /* ================ FS_Restart ================ */ void FS_Restart( int checksumFeed ) { const char *lastGameDir; // free anything we currently have loaded FS_Shutdown(qfalse); // set the checksum feed fs_checksumFeed = checksumFeed; // clear pak references FS_ClearPakReferences(0); // try to start up normally FS_Startup(com_basegame->string); #ifndef STANDALONE FS_CheckPak0( ); #endif // if we can't find default.cfg, assume that the paths are // busted and error out now, rather than getting an unreadable // graphics screen when the font fails to load if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) { // this might happen when connecting to a pure server not using BASEGAME/pak0.pk3 // (for instance a TA demo server) if (lastValidBase[0]) { FS_PureServerSetLoadedPaks("", ""); Cvar_Set("fs_basepath", lastValidBase); Cvar_Set("com_basegame", lastValidComBaseGame); Cvar_Set("fs_basegame", lastValidFsBaseGame); Cvar_Set("fs_game", lastValidGame); lastValidBase[0] = '\0'; lastValidComBaseGame[0] = '\0'; lastValidFsBaseGame[0] = '\0'; lastValidGame[0] = '\0'; FS_Restart(checksumFeed); Com_Error( ERR_DROP, "Invalid game folder" ); return; } Com_Error( ERR_FATAL, "Couldn't load default.cfg" ); } lastGameDir = ( lastValidGame[0] ) ? lastValidGame : lastValidComBaseGame; if ( Q_stricmp( FS_GetCurrentGameDir(), lastGameDir ) ) { Sys_RemovePIDFile( lastGameDir ); Sys_InitPIDFile( FS_GetCurrentGameDir() ); // skip the q3config.cfg if "safe" is on the command line if ( !Com_SafeMode() ) { Cbuf_AddText ("exec " Q3CONFIG_CFG "\n"); } } Q_strncpyz(lastValidBase, fs_basepath->string, sizeof(lastValidBase)); Q_strncpyz(lastValidComBaseGame, com_basegame->string, sizeof(lastValidComBaseGame)); Q_strncpyz(lastValidFsBaseGame, fs_basegame->string, sizeof(lastValidFsBaseGame)); Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame)); } /* ================= FS_ConditionalRestart Restart if necessary Return qtrue if restarting due to game directory changed, qfalse otherwise ================= */ qboolean FS_ConditionalRestart(int checksumFeed, qboolean disconnect) { if(fs_gamedirvar->modified) { if(FS_FilenameCompare(lastValidGame, fs_gamedirvar->string) && (*lastValidGame || FS_FilenameCompare(fs_gamedirvar->string, com_basegame->string)) && (*fs_gamedirvar->string || FS_FilenameCompare(lastValidGame, com_basegame->string))) { Com_GameRestart(checksumFeed, disconnect); return qtrue; } else fs_gamedirvar->modified = qfalse; } if(checksumFeed != fs_checksumFeed) FS_Restart(checksumFeed); else if(fs_numServerPaks && !fs_reordered) FS_ReorderPurePaks(); return qfalse; } /* ======================================================================================== Handle based file calls for virtual machines ======================================================================================== */ int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) { int r; qboolean sync; sync = qfalse; switch( mode ) { case FS_READ: r = FS_FOpenFileRead( qpath, f, qtrue ); break; case FS_WRITE: *f = FS_FOpenFileWrite( qpath ); r = 0; if (*f == 0) { r = -1; } break; case FS_APPEND_SYNC: sync = qtrue; case FS_APPEND: *f = FS_FOpenFileAppend( qpath ); r = 0; if (*f == 0) { r = -1; } break; default: Com_Error( ERR_FATAL, "FS_FOpenFileByMode: bad mode" ); return -1; } if (!f) { return r; } if ( *f ) { fsh[*f].fileSize = r; } fsh[*f].handleSync = sync; return r; } int FS_FTell( fileHandle_t f ) { int pos; if (fsh[f].zipFile == qtrue) { pos = unztell(fsh[f].handleFiles.file.z); } else { pos = ftell(fsh[f].handleFiles.file.o); } return pos; } void FS_Flush( fileHandle_t f ) { fflush(fsh[f].handleFiles.file.o); } void FS_FilenameCompletion( const char *dir, const char *ext, qboolean stripExt, void(*callback)(const char *s), qboolean allowNonPureFilesOnDisk ) { char **filenames; int nfiles; int i; char filename[ MAX_STRING_CHARS ]; filenames = FS_ListFilteredFiles( dir, ext, NULL, &nfiles, allowNonPureFilesOnDisk ); FS_SortFileList( filenames, nfiles ); for( i = 0; i < nfiles; i++ ) { FS_ConvertPath( filenames[ i ] ); Q_strncpyz( filename, filenames[ i ], MAX_STRING_CHARS ); if( stripExt ) { COM_StripExtension(filename, filename, sizeof(filename)); } callback( filename ); } FS_FreeFileList( filenames ); } const char *FS_GetCurrentGameDir(void) { if(fs_gamedirvar->string[0]) return fs_gamedirvar->string; return com_basegame->string; }
wtfbbqhax/ioq3
code/qcommon/files.c
C
gpl-2.0
101,169
<?php if (!defined ('TYPO3_MODE')) { die ('Access denied.'); } $TCA['tx_t3rating_domain_model_vote'] = array( 'ctrl' => $TCA['tx_t3rating_domain_model_vote']['ctrl'], 'interface' => array( 'showRecordFieldList' => 'sys_language_uid, l10n_parent, l10n_diffsource, hidden, choice, user, voting, visitor_hash', ), 'types' => array( '1' => array('showitem' => 'sys_language_uid;;;;1-1-1, l10n_parent, l10n_diffsource, hidden;;1, choice, user, voting, visitor_hash,--div--;LLL:EXT:cms/locallang_ttc.xlf:tabs.access,starttime, endtime'), ), 'palettes' => array( '1' => array('showitem' => ''), ), 'columns' => array( 'sys_language_uid' => array( 'exclude' => 1, 'label' => 'LLL:EXT:lang/locallang_general.xlf:LGL.language', 'config' => array( 'type' => 'select', 'foreign_table' => 'sys_language', 'foreign_table_where' => 'ORDER BY sys_language.title', 'items' => array( array('LLL:EXT:lang/locallang_general.xlf:LGL.allLanguages', -1), array('LLL:EXT:lang/locallang_general.xlf:LGL.default_value', 0) ), ), ), 'l10n_parent' => array( 'displayCond' => 'FIELD:sys_language_uid:>:0', 'exclude' => 1, 'label' => 'LLL:EXT:lang/locallang_general.xlf:LGL.l18n_parent', 'config' => array( 'type' => 'select', 'items' => array( array('', 0), ), 'foreign_table' => 'tx_t3rating_domain_model_vote', 'foreign_table_where' => 'AND tx_t3rating_domain_model_vote.pid=###CURRENT_PID### AND tx_t3rating_domain_model_vote.sys_language_uid IN (-1,0)', ), ), 'l10n_diffsource' => array( 'config' => array( 'type' => 'passthrough', ), ), 't3ver_label' => array( 'label' => 'LLL:EXT:lang/locallang_general.xlf:LGL.versionLabel', 'config' => array( 'type' => 'input', 'size' => 30, 'max' => 255, ) ), 'hidden' => array( 'exclude' => 1, 'label' => 'LLL:EXT:lang/locallang_general.xlf:LGL.hidden', 'config' => array( 'type' => 'check', ), ), 'starttime' => array( 'exclude' => 1, 'l10n_mode' => 'mergeIfNotBlank', 'label' => 'LLL:EXT:lang/locallang_general.xlf:LGL.starttime', 'config' => array( 'type' => 'input', 'size' => 13, 'max' => 20, 'eval' => 'datetime', 'checkbox' => 0, 'default' => 0, 'range' => array( 'lower' => mktime(0, 0, 0, date('m'), date('d'), date('Y')) ), ), ), 'endtime' => array( 'exclude' => 1, 'l10n_mode' => 'mergeIfNotBlank', 'label' => 'LLL:EXT:lang/locallang_general.xlf:LGL.endtime', 'config' => array( 'type' => 'input', 'size' => 13, 'max' => 20, 'eval' => 'datetime', 'checkbox' => 0, 'default' => 0, 'range' => array( 'lower' => mktime(0, 0, 0, date('m'), date('d'), date('Y')) ), ), ), 'choice' => array( 'exclude' => 0, 'label' => 'LLL:EXT:t3rating/Resources/Private/Language/locallang_db.xlf:tx_t3rating_domain_model_vote.choice', 'config' => array( 'type' => 'select', 'foreign_table' => 'tx_t3rating_domain_model_choice', 'minitems' => 0, 'maxitems' => 1, ), ), 'user' => array( 'exclude' => 0, 'label' => 'LLL:EXT:t3rating/Resources/Private/Language/locallang_db.xlf:tx_t3rating_domain_model_vote.user', 'config' => array( 'type' => 'select', 'foreign_table' => 'fe_users', 'minitems' => 0, 'maxitems' => 1, ), ), 'visitor_hash' => array( 'label' => 'LLL:EXT:t3rating/Resources/Private/Language/locallang_db.xlf:tx_t3rating_domain_model_vote.visitorHash', 'config' => array( 'type' => 'input', 'readOnly' => TRUE, ), ), 'voting' => array( 'exclude' => 0, 'label' => 'LLL:EXT:t3rating/Resources/Private/Language/locallang_db.xlf:tx_t3rating_domain_model_vote.voting', 'config' => array( 'type' => 'select', 'foreign_table' => 'tx_t3rating_domain_model_voting', 'minitems' => 0, 'maxitems' => 1, ), ), ), ); ## EXTENSION BUILDER DEFAULTS END TOKEN - Everything BEFORE this line is overwritten with the defaults of the extension builder ?>
dwenzel/t3rating
Configuration/TCA/Vote.php
PHP
gpl-2.0
4,044
<?php namespace XoopsModules\Xoopspoll\Common; /* You may not change or alter any portion of this comment or credits of supporting developers from this source code or any supporting source code which is considered copyrighted (c) material of the original comment or credit authors. 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. */ /** * Configurator Class * * @copyright XOOPS Project (https://xoops.org) * @license http://www.fsf.org/copyleft/gpl.html GNU public license * @author XOOPS Development Team */ /** * Class Configurator */ class Configurator { public $name; public $paths = []; public $uploadFolders = []; public $copyBlankFiles = []; public $copyTestFolders = []; public $templateFolders = []; public $oldFiles = []; public $oldFolders = []; public $renameTables = []; public $modCopyright; /** * Configurator constructor. */ public function __construct() { $moduleDirName = \basename(\dirname(__DIR__, 2)); $moduleDirNameUpper = mb_strtoupper($moduleDirName); $config = require \dirname(__DIR__, 2) . '/config/config.php'; $this->name = $config->name; $this->paths = $config->paths; $this->uploadFolders = $config->uploadFolders; $this->copyBlankFiles = $config->copyBlankFiles; $this->copyTestFolders = $config->copyTestFolders; $this->templateFolders = $config->templateFolders; $this->oldFiles = $config->oldFiles; $this->oldFolders = $config->oldFolders; $this->renameTables = $config->renameTables; $this->modCopyright = $config->modCopyright; $this->icons = include \dirname(__DIR__, 2) . '/config/icons.php'; $this->paths = include \dirname(__DIR__, 2) . '/config/paths.php'; } }
mambax7/xoopspoll
class/Common/Configurator.php
PHP
gpl-2.0
2,031
<?php if( is_front_page() || is_page_template( 'template-landing-page.php' ) || ( is_home() && ! is_paged() ) ) : ?> <?php get_sidebar( 'footer-wide' ); ?> <?php endif; ?> <div id="footer"> <?php get_sidebar( 'footer' ); ?> <div id="copyright"> <p class="copyright twocol"><?php pinboard_copyright_notice(); ?></p> <?php if( pinboard_get_option( 'theme_credit_link' ) || pinboard_get_option( 'author_credit_link' ) || pinboard_get_option( 'wordpress_credit_link' ) ) : ?> <p class="credits twocol"> <?php $theme_credit_link = '<a href="' . esc_url( 'https://www.onedesigns.com/themes/pinboard' ) . '" title="' . esc_attr( __( 'Pinboard Theme', 'pinboard' ) ) . '">' . __( 'Pinboard Theme', 'pinboard' ) . '</a>'; ?> <?php $author_credit_link = '<a href="' . esc_url( 'https://www.onedesigns.com/' ) . '" title="' . esc_attr( __( 'One Designs', 'pinboard' ) ) . '">' . __( 'One Designs', 'pinboard' ) . '</a>'; ?> <?php $wordpress_credit_link = '<a href="' . esc_url( 'https://wordpress.org/' ) . '" title="' . esc_attr( __( 'WordPress', 'pinboard' ) ) . '">' . __( 'WordPress', 'pinboard' ) . '</a>';; ?> <?php if( pinboard_get_option( 'theme_credit_link' ) && pinboard_get_option( 'author_credit_link' ) && pinboard_get_option( 'wordpress_credit_link' ) ) : ?> <?php echo sprintf( __( 'Powered by %1$s by %2$s and %3$s', 'pinboard' ), $theme_credit_link, $author_credit_link, $wordpress_credit_link ); ?> <?php elseif( pinboard_get_option( 'theme_credit_link' ) && pinboard_get_option( 'author_credit_link' ) && ! pinboard_get_option( 'wordpress_credit_link' ) ) : ?> <?php echo sprintf( __( 'Powered by %1$s by %2$s', 'pinboard' ), $theme_credit_link, $author_credit_link ); ?> <?php elseif( pinboard_get_option( 'theme_credit_link' ) && ! pinboard_get_option( 'author_credit_link' ) && pinboard_get_option( 'wordpress_credit_link' ) ) : ?> <?php echo sprintf( __( 'Powered by %1$s and %2$s', 'pinboard' ), $theme_credit_link, $wordpress_credit_link ); ?> <?php elseif( ! pinboard_get_option( 'theme_credit_link' ) && pinboard_get_option( 'author_credit_link' ) && pinboard_get_option( 'wordpress_credit_link' ) ) : ?> <?php echo sprintf( __( 'Powered by %1$s and %2$s', 'pinboard' ), $author_credit_link, $wordpress_credit_link ); ?> <?php elseif( pinboard_get_option( 'theme_credit_link' ) && ! pinboard_get_option( 'author_credit_link' ) && ! pinboard_get_option( 'wordpress_credit_link' ) ) : ?> <?php echo sprintf( __( 'Powered by %1$s', 'pinboard' ), $theme_credit_link ); ?> <?php elseif( ! pinboard_get_option( 'theme_credit_link' ) && pinboard_get_option( 'author_credit_link' ) && ! pinboard_get_option( 'wordpress_credit_link' ) ) : ?> <?php echo sprintf( __( 'Powered by %1$s', 'pinboard' ), $author_credit_link ); ?> <?php elseif( ! pinboard_get_option( 'theme_credit_link' ) && ! pinboard_get_option( 'author_credit_link' ) && pinboard_get_option( 'wordpress_credit_link' ) ) : ?> <?php echo sprintf( __( 'Powered by %1$s', 'pinboard' ), $wordpress_credit_link ); ?> <?php endif; ?> </p> <?php endif; ?> <div class="clear"></div> </div><!-- #copyright --> </div><!-- #footer --> </div><!-- #wrapper --> <?php wp_footer(); ?> </body> </html>
norskclassoslo/saifshams
wp-content/themes/pinboard/footer.php
PHP
gpl-2.0
3,320
#include <fas/pattern/type_list.hpp> #include <fas/misc/json.hpp> namespace ap = ::fas::pattern; namespace aj= ::fas::json; namespace fas { namespace pattern { template<typename TLI, typename left_type, typename FT> struct type_list_inst_getter { static typename FT::type & get(const FT &fld, TLI&data) { return data.right_value.get(fld); } }; template<typename TLI, typename FT> struct type_list_inst_getter<TLI, FT, FT> { static typename FT::type & get(const FT &fld, TLI&data) { return data.value; } }; /* template<bool b, typename FT, typename TLI> struct type_list_inst_getter { FT& get(const FT &fld, const TLI& data) { return data.right_value.get(fld); } }; template<true, typename FT, typename TLI> struct type_list_inst_getter { FT& get(const FT &fld, const TLI& data) { return data.right_value.get(fld); } }; */ /** * промежуточное представление анкеты. для каждого field_... создаётся экземпляр field_something::type */ template< typename T > struct type_list_inst { typedef typename T::left_type left_type ; typedef typename T::left_type::type value_type ; typedef typename T::left_type::json_type json_type; value_type value; type_list_inst<typename T::right_type> right_value; template<typename FT> typename FT::type & get(const FT &fld) { return type_list_inst_getter<type_list_inst<T>, left_type, FT>::get(fld,*this); /* if (std::is_same<FT,left_type>::value) { return (*this); } else { return right_value.template get(fld); }*/ } }; /* template<typename TLI> value_type& get(const left_type &p) { return value; }*/ template<> struct type_list_inst<ap::empty_type> { ap::empty_type value; ap::empty_type right_value; typedef ap::empty_type left_type ; typedef ap::empty_type json_type ; typedef ap::empty_type value_type ; /* template<typename FT> typename FT::type & get(const FT &fld) { }*/ }; /** * промежуточное представление запроса для расширенных полей. для каждого field_... создаётся экземпляр std::vector<field_something::type> */ template< typename T > struct type_list_inst_arr { typedef typename T::left_type left_type ; typedef typename T::left_type::type value_type ; typedef aj::array<std::vector<typename T::left_type::json_type> > json_type; std::vector<value_type> value; type_list_inst_arr<typename T::right_type> right_value; }; template<> struct type_list_inst_arr<ap::empty_type> { ap::empty_type value; ap::empty_type right_value; typedef ap::empty_type left_type ; typedef ap::empty_type json_type ; typedef ap::empty_type value_type ; }; }}
mambaru/leveldb-daemon
common/ap_type_list_inst.hpp
C++
gpl-2.0
2,701
/* // this line must stay at top so the whole PCH thing works... #include "cg_headers.h" //#include "cg_local.h" #include "cg_media.h" #include "cg_text.h" */ // Copyright (C) 1999-2000 Id Software, Inc. // // cg_drawtools.c -- helper functions called by cg_draw, cg_scoreboard, cg_info, etc #include "cg_local.h" #include "../game/q_shared.h" /* ================ UI_DrawRect Coordinates are 640*480 virtual values ================= */ void CG_DrawRect( float x, float y, float width, float height, float size, const float *color ) { trap_R_SetColor( color ); CG_DrawTopBottom(x, y, width, height, size); CG_DrawSides(x, y, width, height, size); trap_R_SetColor( NULL ); } /* ================= CG_GetColorForHealth ================= */ void CG_GetColorForHealth( int health, int armor, vec4_t hcolor ) { int count; int max; // calculate the total points of damage that can // be sustained at the current health / armor level if ( health <= 0 ) { VectorClear( hcolor ); // black hcolor[3] = 1; return; } count = armor; max = health * ARMOR_PROTECTION / ( 1.0 - ARMOR_PROTECTION ); if ( max < count ) { count = max; } health += count; // set the color based on health hcolor[0] = 1.0; hcolor[3] = 1.0; if ( health >= 100 ) { hcolor[2] = 1.0; } else if ( health < 66 ) { hcolor[2] = 0; } else { hcolor[2] = ( health - 66 ) / 33.0; } if ( health > 60 ) { hcolor[1] = 1.0; } else if ( health < 30 ) { hcolor[1] = 0; } else { hcolor[1] = ( health - 30 ) / 30.0; } } /* ================ CG_DrawSides Coords are virtual 640x480 ================ */ void CG_DrawSides(float x, float y, float w, float h, float size) { size *= cgs.screenXScale; trap_R_DrawStretchPic( x, y, size, h, 0, 0, 0, 0, cgs.media.whiteShader ); trap_R_DrawStretchPic( x + w - size, y, size, h, 0, 0, 0, 0, cgs.media.whiteShader ); } void CG_DrawTopBottom(float x, float y, float w, float h, float size) { size *= cgs.screenYScale; trap_R_DrawStretchPic( x, y, w, size, 0, 0, 0, 0, cgs.media.whiteShader ); trap_R_DrawStretchPic( x, y + h - size, w, size, 0, 0, 0, 0, cgs.media.whiteShader ); } /* ------------------------- CGC_FillRect2 real coords ------------------------- */ void CG_FillRect2( float x, float y, float width, float height, const float *color ) { trap_R_SetColor( color ); trap_R_DrawStretchPic( x, y, width, height, 0, 0, 0, 0, cgs.media.whiteShader); trap_R_SetColor( NULL ); } /* ================ CG_FillRect Coordinates are 640*480 virtual values ================= */ void CG_FillRect( float x, float y, float width, float height, const float *color ) { trap_R_SetColor( color ); trap_R_DrawStretchPic( x, y, width, height, 0, 0, 0, 0, cgs.media.whiteShader); trap_R_SetColor( NULL ); } /* ================ CG_DrawPic Coordinates are 640*480 virtual values A width of 0 will draw with the original image width ================= */ void CG_DrawPic( float x, float y, float width, float height, qhandle_t hShader ) { trap_R_DrawStretchPic( x, y, width, height, 0, 0, 1, 1, hShader ); } /* ================ CG_DrawRotatePic Coordinates are 640*480 virtual values A width of 0 will draw with the original image width rotates around the upper right corner of the passed in point ================= */ void CG_DrawRotatePic( float x, float y, float width, float height,float angle, qhandle_t hShader ) { trap_R_DrawRotatePic( x, y, width, height, 0, 0, 1, 1, angle, hShader ); } /* ================ CG_DrawRotatePic2 Coordinates are 640*480 virtual values A width of 0 will draw with the original image width Actually rotates around the center point of the passed in coordinates ================= */ void CG_DrawRotatePic2( float x, float y, float width, float height,float angle, qhandle_t hShader ) { trap_R_DrawRotatePic2( x, y, width, height, 0, 0, 1, 1, angle, hShader ); } /* =============== CG_DrawChar Coordinates and size in 640*480 virtual screen size =============== */ void CG_DrawChar( int x, int y, int width, int height, int ch ) { int row, col; float frow, fcol; float size; float ax, ay, aw, ah; float size2; ch &= 255; if ( ch == ' ' ) { return; } ax = x; ay = y; aw = width; ah = height; row = ch>>4; col = ch&15; frow = row*0.0625; fcol = col*0.0625; size = 0.03125; size2 = 0.0625; trap_R_DrawStretchPic( ax, ay, aw, ah, fcol, frow, fcol + size, frow + size2, cgs.media.charsetShader ); } /* ================== CG_DrawStringExt Draws a multi-colored string with a drop shadow, optionally forcing to a fixed color. Coordinates are at 640 by 480 virtual resolution ================== */ #include "../ui/menudef.h" // for "ITEM_TEXTSTYLE_SHADOWED" void CG_DrawStringExt( int x, int y, const char *string, const float *setColor, qboolean forceColor, qboolean shadow, int charWidth, int charHeight, int maxChars ) { if (trap_Language_IsAsian()) { // hack-a-doodle-do (post-release quick fix code)... // vec4_t color; memcpy(color,setColor, sizeof(color)); // de-const it CG_Text_Paint(x, y, 1.0f, // float scale, color, // vec4_t color, string, // const char *text, 0.0f, // float adjust, 0, // int limit, shadow ? ITEM_TEXTSTYLE_SHADOWED : 0, // int style, FONT_MEDIUM // iMenuFont ) ; } else { vec4_t color; const char *s; int xx; // draw the drop shadow if (shadow) { color[0] = color[1] = color[2] = 0; color[3] = setColor[3]; trap_R_SetColor( color ); s = string; xx = x; while ( *s ) { if ( Q_IsColorString( s ) ) { s += 2; continue; } CG_DrawChar( xx + 2, y + 2, charWidth, charHeight, *s ); xx += charWidth; s++; } } // draw the colored text s = string; xx = x; trap_R_SetColor( setColor ); while ( *s ) { if ( Q_IsColorString( s ) ) { if ( !forceColor ) { memcpy( color, g_color_table[ColorIndex(*(s+1))], sizeof( color ) ); color[3] = setColor[3]; trap_R_SetColor( color ); } s += 2; continue; } CG_DrawChar( xx, y, charWidth, charHeight, *s ); xx += charWidth; s++; } trap_R_SetColor( NULL ); } } void CG_DrawBigString( int x, int y, const char *s, float alpha ) { float color[4]; color[0] = color[1] = color[2] = 1.0; color[3] = alpha; CG_DrawStringExt( x, y, s, color, qfalse, qtrue, BIGCHAR_WIDTH, BIGCHAR_HEIGHT, 0 ); } void CG_DrawBigStringColor( int x, int y, const char *s, vec4_t color ) { CG_DrawStringExt( x, y, s, color, qtrue, qtrue, BIGCHAR_WIDTH, BIGCHAR_HEIGHT, 0 ); } void CG_DrawSmallString( int x, int y, const char *s, float alpha ) { float color[4]; color[0] = color[1] = color[2] = 1.0; color[3] = alpha; CG_DrawStringExt( x, y, s, color, qfalse, qfalse, SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT, 0 ); } void CG_DrawSmallStringColor( int x, int y, const char *s, vec4_t color ) { CG_DrawStringExt( x, y, s, color, qtrue, qfalse, SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT, 0 ); } /* ================= CG_DrawStrlen Returns character count, skiping color escape codes ================= */ int CG_DrawStrlen( const char *str ) { const char *s = str; int count = 0; while ( *s ) { if ( Q_IsColorString( s ) ) { s += 2; } else { count++; s++; } } return count; } /* ============= CG_TileClearBox This repeats a 64*64 tile graphic to fill the screen around a sized down refresh window. ============= */ static void CG_TileClearBox( int x, int y, int w, int h, qhandle_t hShader ) { float s1, t1, s2, t2; s1 = x/64.0; t1 = y/64.0; s2 = (x+w)/64.0; t2 = (y+h)/64.0; trap_R_DrawStretchPic( x, y, w, h, s1, t1, s2, t2, hShader ); } /* ============== CG_TileClear Clear around a sized down screen ============== */ void CG_TileClear( void ) { int top, bottom, left, right; int w, h; w = cgs.glconfig.vidWidth; h = cgs.glconfig.vidHeight; if ( cg.refdef.x == 0 && cg.refdef.y == 0 && cg.refdef.width == w && cg.refdef.height == h ) { return; // full screen rendering } top = cg.refdef.y; bottom = top + cg.refdef.height-1; left = cg.refdef.x; right = left + cg.refdef.width-1; // clear above view screen CG_TileClearBox( 0, 0, w, top, cgs.media.backTileShader ); // clear below view screen CG_TileClearBox( 0, bottom, w, h - bottom, cgs.media.backTileShader ); // clear left of view screen CG_TileClearBox( 0, top, left, bottom - top + 1, cgs.media.backTileShader ); // clear right of view screen CG_TileClearBox( right, top, w - right, bottom - top + 1, cgs.media.backTileShader ); } /* ================ CG_FadeColor ================ */ float *CG_FadeColor( int startMsec, int totalMsec ) { static vec4_t color; int t; if ( startMsec == 0 ) { return NULL; } t = cg.time - startMsec; if ( t >= totalMsec ) { return NULL; } // fade out if ( totalMsec - t < FADE_TIME ) { color[3] = ( totalMsec - t ) * 1.0/FADE_TIME; } else { color[3] = 1.0; } color[0] = color[1] = color[2] = 1; return color; } /* ================= CG_ColorForHealth ================= */ void CG_ColorForGivenHealth( vec4_t hcolor, int health ) { // set the color based on health hcolor[0] = 1.0; if ( health >= 100 ) { hcolor[2] = 1.0; } else if ( health < 66 ) { hcolor[2] = 0; } else { hcolor[2] = ( health - 66 ) / 33.0; } if ( health > 60 ) { hcolor[1] = 1.0; } else if ( health < 30 ) { hcolor[1] = 0; } else { hcolor[1] = ( health - 30 ) / 30.0; } } /* ================= CG_ColorForHealth ================= */ void CG_ColorForHealth( vec4_t hcolor ) { int health; int count; int max; // calculate the total points of damage that can // be sustained at the current health / armor level health = cg.snap->ps.stats[STAT_HEALTH]; if ( health <= 0 ) { VectorClear( hcolor ); // black hcolor[3] = 1; return; } count = cg.snap->ps.stats[STAT_ARMOR]; max = health * ARMOR_PROTECTION / ( 1.0 - ARMOR_PROTECTION ); if ( max < count ) { count = max; } health += count; hcolor[3] = 1.0; CG_ColorForGivenHealth( hcolor, health ); } /* ============== CG_DrawNumField Take x,y positions as if 640 x 480 and scales them to the proper resolution ============== */ void CG_DrawNumField (int x, int y, int width, int value,int charWidth,int charHeight,int style,qboolean zeroFill) { char num[16], *ptr; int l; int frame; int xWidth; int i = 0; if (width < 1) { return; } // draw number string if (width > 5) { width = 5; } switch ( width ) { case 1: value = value > 9 ? 9 : value; value = value < 0 ? 0 : value; break; case 2: value = value > 99 ? 99 : value; value = value < -9 ? -9 : value; break; case 3: value = value > 999 ? 999 : value; value = value < -99 ? -99 : value; break; case 4: value = value > 9999 ? 9999 : value; value = value < -999 ? -999 : value; break; } Com_sprintf (num, sizeof(num), "%i", value); l = strlen(num); if (l > width) l = width; // FIXME: Might need to do something different for the chunky font?? switch(style) { case NUM_FONT_SMALL: xWidth = charWidth; break; case NUM_FONT_CHUNKY: xWidth = (charWidth/1.2f) + 2; break; default: case NUM_FONT_BIG: xWidth = (charWidth/2) + 7;//(charWidth/6); break; } if ( zeroFill ) { for (i = 0; i < (width - l); i++ ) { switch(style) { case NUM_FONT_SMALL: CG_DrawPic( x,y, charWidth, charHeight, cgs.media.smallnumberShaders[0] ); break; case NUM_FONT_CHUNKY: CG_DrawPic( x,y, charWidth, charHeight, cgs.media.chunkyNumberShaders[0] ); break; default: case NUM_FONT_BIG: CG_DrawPic( x,y, charWidth, charHeight, cgs.media.numberShaders[0] ); break; } x += 2 + (xWidth); } } else { x += 2 + (xWidth)*(width - l); } ptr = num; while (*ptr && l) { if (*ptr == '-') frame = STAT_MINUS; else frame = *ptr -'0'; switch(style) { case NUM_FONT_SMALL: CG_DrawPic( x,y, charWidth, charHeight, cgs.media.smallnumberShaders[frame] ); x++; // For a one line gap break; case NUM_FONT_CHUNKY: CG_DrawPic( x,y, charWidth, charHeight, cgs.media.chunkyNumberShaders[frame] ); break; default: case NUM_FONT_BIG: CG_DrawPic( x,y, charWidth, charHeight, cgs.media.numberShaders[frame] ); break; } x += (xWidth); ptr++; l--; } } #include "../ui/ui_shared.h" // for some text style junk void UI_DrawProportionalString( int x, int y, const char* str, int style, vec4_t color ) { // having all these different style defines (1 for UI, one for CG, and now one for the re->font stuff) // is dumb, but for now... // int iStyle = 0; int iMenuFont = (style & UI_SMALLFONT) ? FONT_SMALL : FONT_MEDIUM; switch (style & (UI_LEFT|UI_CENTER|UI_RIGHT)) { default: case UI_LEFT: { // nada... } break; case UI_CENTER: { x -= CG_Text_Width(str, 1.0, iMenuFont) / 2; } break; case UI_RIGHT: { x -= CG_Text_Width(str, 1.0, iMenuFont) / 2; } break; } if (style & UI_DROPSHADOW) { iStyle = ITEM_TEXTSTYLE_SHADOWED; } else if ( style & (UI_BLINK|UI_PULSE) ) { iStyle = ITEM_TEXTSTYLE_BLINK; } CG_Text_Paint(x, y, 1.0, color, str, 0, 0, iStyle, iMenuFont); } void UI_DrawScaledProportionalString( int x, int y, const char* str, int style, vec4_t color, float scale) { // having all these different style defines (1 for UI, one for CG, and now one for the re->font stuff) // is dumb, but for now... // int iStyle = 0; switch (style & (UI_LEFT|UI_CENTER|UI_RIGHT)) { default: case UI_LEFT: { // nada... } break; case UI_CENTER: { x -= CG_Text_Width(str, scale, FONT_MEDIUM) / 2; } break; case UI_RIGHT: { x -= CG_Text_Width(str, scale, FONT_MEDIUM) / 2; } break; } if (style & UI_DROPSHADOW) { iStyle = ITEM_TEXTSTYLE_SHADOWED; } else if ( style & (UI_BLINK|UI_PULSE) ) { iStyle = ITEM_TEXTSTYLE_BLINK; } CG_Text_Paint(x, y, scale, color, str, 0, 0, iStyle, FONT_MEDIUM); }
ouned/JK2-1.04
cgame/cg_drawtools.c
C
gpl-2.0
13,918
<?php /** * likes * * @author likes * @link http://community.elgg.org/pg/profile/pedroprez * @copyright (c) Keetup 2010 * @link http://www.keetup.com/ * @license GNU General Public License (GPL) version 2 */ //Add river itemtime $time_posted = friendly_time($vars['item']->posted); $time_posted = <<<EOT <span class="river_item_time"> $time_posted </span> EOT; $vars['body'] = preg_replace('/\<\!\-\-\s?itemtime\s?\-\-\>/', $time_posted, $vars['body'], 1); //Add river action buttons $item_action_view = elgg_view('river/item/actions', $vars); $item_action = <<<EOT <span class='river_action_links'> $item_action_view </span> EOT; $vars['body'] = preg_replace('/\<\!\-\-\s?river_actions\s?\-\-\>/', $item_action, $vars['body'], 1); $separator = "<div class='item_separator'>&nbsp;</div>"; $vars['body'] = preg_replace('/\<\!\-\-\s?separator\s?\-\-\>/', $separator, $vars['body'], 2); $river_content = <<<EOT <p class="river_item_body"> {$vars['body']} </p> EOT; //get the site admins choice avatars or action icons $avatar_icon = get_plugin_setting("avatar_icon","riverdashboard"); if(!$avatar_icon) { $avatar_icon = "icon"; } if($avatar_icon == "icon"){ ?> <div class="river_item"> <div class="river_<?php echo $vars['item']->type; ?>"> <div class="river_<?php echo $vars['item']->subtype; ?>"> <div class="river_<?php echo $vars['item']->action_type; ?>"> <div class="river_<?php echo $vars['item']->type; ?>_<?php if($vars['item']->subtype) echo $vars['item']->subtype . "_"; ?><?php echo $vars['item']->action_type; ?>"> <?php echo $river_content ?> </div> </div> </div> </div> </div> <?php } else { ?> <div class="river_item"> <span class="river_item_useravatar"> <?php echo elgg_view("profile/icon",array('entity' => get_entity($vars['item']->subject_guid), 'size' => 'tiny')); ?> </span> <?php echo $river_content ?> <div class="clearfloat"></div> </div> <?php } ?>
FEIBookUV/feibook
Code/mod/likes/views/default/river/item/wrapper.php
PHP
gpl-2.0
2,033
/***************************************************************************** * fbosd.c : framebuffer osd plugin for vlc ***************************************************************************** * Copyright (C) 2007-2008, the VideoLAN team * $Id$ * * Authors: Jean-Paul Saman * Copied from modules/video_output/fb.c by Samuel Hocevar <sam@zoy.org> * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ /***************************************************************************** * Preamble *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc_common.h> #include <vlc_plugin.h> #include <vlc_fs.h> #include <vlc_modules.h> #include <stdlib.h> /* free() */ #include <string.h> /* strerror() */ #include <fcntl.h> /* open() */ #include <unistd.h> /* close() */ #include <sys/ioctl.h> #include <sys/mman.h> /* mmap() */ #include <linux/fb.h> #include <vlc_image.h> #include <vlc_interface.h> #include <vlc_input.h> #include <vlc_vout.h> #include <vlc_filter.h> #include <vlc_osd.h> #include <vlc_strings.h> #undef FBOSD_BLENDING #undef FBOSD_DEBUG /***************************************************************************** * Local prototypes *****************************************************************************/ static int Create ( vlc_object_t * ); static void Destroy ( vlc_object_t * ); static void Run ( intf_thread_t * ); static int Init ( intf_thread_t * ); static void End ( intf_thread_t * ); static int OpenDisplay ( intf_thread_t * ); static void CloseDisplay ( intf_thread_t * ); /* Load modules needed for rendering and blending */ #if defined(FBOSD_BLENDING) static int OpenBlending ( intf_thread_t * ); static void CloseBlending ( intf_thread_t * ); #endif static int OpenTextRenderer ( intf_thread_t * ); static void CloseTextRenderer( intf_thread_t * ); /* Manipulate the overlay buffer */ static int OverlayCallback( vlc_object_t *, char const *, vlc_value_t, vlc_value_t, void * ); static picture_t *AllocatePicture( video_format_t * ); static void DeAllocatePicture( picture_t *, video_format_t * ); static void SetOverlayTransparency( intf_thread_t *, bool ); static picture_t *LoadImage( intf_thread_t *, video_format_t *, char * ); #if defined(FBOSD_BLENDING) static int BlendPicture( intf_thread_t *, video_format_t *, video_format_t *, picture_t *, picture_t * ); #else static picture_t *ConvertImage( intf_thread_t *, picture_t *, video_format_t *, video_format_t * ); #endif static int RenderPicture( intf_thread_t *, int, int, picture_t *, picture_t * ); static picture_t *RenderText( intf_thread_t *, const char *, text_style_t *, video_format_t * ); #define DEVICE_TEXT N_("Framebuffer device") #define DEVICE_LONGTEXT N_( \ "Framebuffer device to use for rendering (usually /dev/fb0).") #define ASPECT_RATIO_TEXT N_("Video aspect ratio") #define ASPECT_RATIO_LONGTEXT N_( \ "Aspect ratio of the video image (4:3, 16:9). Default is square pixels." ) #define FBOSD_IMAGE_TEXT N_("Image file") #define FBOSD_IMAGE_LONGTEXT N_( \ "Filename of image file to use on the overlay framebuffer." ) #define ALPHA_TEXT N_("Transparency of the image") #define ALPHA_LONGTEXT N_( "Transparency value of the new image " \ "used in blending. By default it set to fully opaque (255). " \ "(from 0 for full transparency to 255 for full opacity)" ) #define FBOSD_TEXT N_("Text") #define FBOSD_LONGTEXT N_( "Text to display on the overlay framebuffer." ) #define POSX_TEXT N_("X coordinate") #define POSX_LONGTEXT N_("X coordinate of the rendered image") #define POSY_TEXT N_("Y coordinate") #define POSY_LONGTEXT N_("Y coordinate of the rendered image") #define POS_TEXT N_("Position") #define POS_LONGTEXT N_( \ "You can enforce the picture position on the overlay " \ "(0=center, 1=left, 2=right, 4=top, 8=bottom, you can " \ "also use combinations of these values, e.g. 6=top-right).") #define OPACITY_TEXT N_("Opacity") #define OPACITY_LONGTEXT N_("Opacity (inverse of transparency) of " \ "overlayed text. 0 = transparent, 255 = totally opaque. " ) #define SIZE_TEXT N_("Font size, pixels") #define SIZE_LONGTEXT N_("Font size, in pixels. Default is -1 (use default " \ "font size)." ) #define COLOR_TEXT N_("Color") #define COLOR_LONGTEXT N_("Color of the text that will be rendered on "\ "the video. This must be an hexadecimal (like HTML colors). The first two "\ "chars are for red, then green, then blue. #000000 = black, #FF0000 = red,"\ " #00FF00 = green, #FFFF00 = yellow (red + green), #FFFFFF = white" ) #define CLEAR_TEXT N_( "Clear overlay framebuffer" ) #define CLEAR_LONGTEXT N_( "The displayed overlay images is cleared by " \ "making the overlay completely transparent. All previously rendered " \ "images and text will be cleared from the cache." ) #define RENDER_TEXT N_( "Render text or image" ) #define RENDER_LONGTEXT N_( "Render the image or text in current overlay " \ "buffer." ) #define DISPLAY_TEXT N_( "Display on overlay framebuffer" ) #define DISPLAY_LONGTEXT N_( "All rendered images and text will be " \ "displayed on the overlay framebuffer." ) static const int pi_pos_values[] = { 0, 1, 2, 4, 8, 5, 6, 9, 10 }; static const char *const ppsz_pos_descriptions[] = { N_("Center"), N_("Left"), N_("Right"), N_("Top"), N_("Bottom"), N_("Top-Left"), N_("Top-Right"), N_("Bottom-Left"), N_("Bottom-Right") }; static const int pi_color_values[] = { 0xf0000000, 0x00000000, 0x00808080, 0x00C0C0C0, 0x00FFFFFF, 0x00800000, 0x00FF0000, 0x00FF00FF, 0x00FFFF00, 0x00808000, 0x00008000, 0x00008080, 0x0000FF00, 0x00800080, 0x00000080, 0x000000FF, 0x0000FFFF}; static const char *const ppsz_color_descriptions[] = { N_("Default"), N_("Black"), N_("Gray"), N_("Silver"), N_("White"), N_("Maroon"), N_("Red"), N_("Fuchsia"), N_("Yellow"), N_("Olive"), N_("Green"), N_("Teal"), N_("Lime"), N_("Purple"), N_("Navy"), N_("Blue"), N_("Aqua") }; vlc_module_begin () set_shortname( "fbosd" ) set_category( CAT_INTERFACE ) set_subcategory( SUBCAT_INTERFACE_MAIN ) add_loadfile( "fbosd-dev", "/dev/fb0", DEVICE_TEXT, DEVICE_LONGTEXT, false ) add_string( "fbosd-aspect-ratio", "", ASPECT_RATIO_TEXT, ASPECT_RATIO_LONGTEXT, true ) add_string( "fbosd-image", NULL, FBOSD_IMAGE_TEXT, FBOSD_IMAGE_LONGTEXT, true ) add_string( "fbosd-text", NULL, FBOSD_TEXT, FBOSD_LONGTEXT, true ) add_integer_with_range( "fbosd-alpha", 255, 0, 255, ALPHA_TEXT, ALPHA_LONGTEXT, true ) set_section( N_("Position"), NULL ) add_integer( "fbosd-x", 0, POSX_TEXT, POSX_LONGTEXT, false ) add_integer( "fbosd-y", 0, POSY_TEXT, POSY_LONGTEXT, false ) add_integer( "fbosd-position", 8, POS_TEXT, POS_LONGTEXT, true ) change_integer_list( pi_pos_values, ppsz_pos_descriptions ); set_section( N_("Font"), NULL ) add_integer_with_range( "fbosd-font-opacity", 255, 0, 255, OPACITY_TEXT, OPACITY_LONGTEXT, false ) add_integer( "fbosd-font-color", 0x00FFFFFF, COLOR_TEXT, COLOR_LONGTEXT, false ) change_integer_list( pi_color_values, ppsz_color_descriptions ); add_integer( "fbosd-font-size", -1, SIZE_TEXT, SIZE_LONGTEXT, false ) set_section( N_("Commands"), NULL ) add_bool( "fbosd-clear", false, CLEAR_TEXT, CLEAR_LONGTEXT, true ) add_bool( "fbosd-render", false, RENDER_TEXT, RENDER_LONGTEXT, true ) add_bool( "fbosd-display", false, DISPLAY_TEXT, DISPLAY_LONGTEXT, true ) set_description( N_("GNU/Linux osd/overlay framebuffer interface") ) set_capability( "interface", 10 ) set_callbacks( Create, Destroy ) vlc_module_end () /***************************************************************************** * fbosd_render_t: render descriptor *****************************************************************************/ struct fbosd_render_t { #define FBOSD_RENDER_IMAGE 0 #define FBOSD_RENDER_TEXT 1 int i_type; #define FBOSD_STATE_FREE 0 #define FBOSD_STATE_RESERVED 1 #define FBOSD_STATE_RENDER 2 int i_state; /* Font style */ text_style_t* p_text_style; /* font control */ char *psz_string; /* Position */ bool b_absolute; int i_x; int i_y; int i_pos; int i_alpha; /* transparency for images */ }; #define FBOSD_RENDER_MAX 10 /***************************************************************************** * intf_sys_t: interface framebuffer method descriptor *****************************************************************************/ struct intf_sys_t { /* Framebuffer information */ int i_fd; /* device handle */ struct fb_var_screeninfo var_info; /* current mode information */ bool b_pan; /* does device supports panning ? */ struct fb_cmap fb_cmap; /* original colormap */ uint16_t *p_palette; /* original palette */ /* Overlay framebuffer format */ video_format_t fmt_out; picture_t *p_overlay; size_t i_page_size; /* page size */ int i_width; int i_height; int i_aspect; int i_bytes_per_pixel; /* Image and Picture rendering */ image_handler_t *p_image; #if defined(FBOSD_BLENDING) filter_t *p_blend; /* alpha blending module */ #endif filter_t *p_text; /* text renderer module */ /* Render */ struct fbosd_render_t render[FBOSD_RENDER_MAX]; /* Font style */ text_style_t *p_style; /* font control */ /* Position */ bool b_absolute; int i_x; int i_y; int i_pos; int i_alpha; /* transparency for images */ /* commands control */ bool b_need_update; /* update display with \overlay buffer */ bool b_clear; /* clear overlay buffer make it tranparent */ bool b_render; /* render an image or text in overlay buffer */ }; /***************************************************************************** * Create: allocates FB interface thread output method *****************************************************************************/ static int Create( vlc_object_t *p_this ) { intf_thread_t *p_intf = (intf_thread_t *)p_this; intf_sys_t *p_sys; char *psz_aspect; char *psz_tmp; int i; /* Allocate instance and initialize some members */ p_intf->p_sys = p_sys = calloc( 1, sizeof( intf_sys_t ) ); if( !p_intf->p_sys ) return VLC_ENOMEM; p_sys->p_style = text_style_New(); if( !p_sys->p_style ) { free( p_intf->p_sys ); return VLC_ENOMEM; } p_intf->pf_run = Run; p_sys->p_image = image_HandlerCreate( p_this ); if( !p_sys->p_image ) { text_style_Delete( p_sys->p_style ); free( p_sys ); return VLC_ENOMEM; } p_sys->i_alpha = var_CreateGetIntegerCommand( p_intf, "fbosd-alpha" ); var_AddCallback( p_intf, "fbosd-alpha", OverlayCallback, NULL ); /* Use PAL by default */ p_sys->i_width = p_sys->fmt_out.i_width = 704; p_sys->i_height = p_sys->fmt_out.i_height = 576; p_sys->i_aspect = -1; psz_aspect = var_CreateGetNonEmptyString( p_intf, "fbosd-aspect-ratio" ); if( psz_aspect ) { char *psz_parser = strchr( psz_aspect, ':' ); if( psz_parser ) { *psz_parser++ = '\0'; p_sys->i_aspect = ( atoi( psz_aspect ) * VOUT_ASPECT_FACTOR ) / atoi( psz_parser ); p_sys->fmt_out.i_sar_num = p_sys->i_aspect * p_sys->i_height; p_sys->fmt_out.i_sar_den = VOUT_ASPECT_FACTOR * p_sys->i_width; } msg_Dbg( p_intf, "using aspect ratio %d:%d", atoi( psz_aspect ), atoi( psz_parser ) ); free( psz_aspect ); } psz_tmp = var_CreateGetNonEmptyStringCommand( p_intf, "fbosd-image" ); var_AddCallback( p_intf, "fbosd-image", OverlayCallback, NULL ); if( psz_tmp && *psz_tmp ) { p_sys->render[0].i_type = FBOSD_RENDER_IMAGE; p_sys->render[0].i_state = FBOSD_STATE_RENDER; p_sys->render[0].psz_string = strdup( psz_tmp ); } free( psz_tmp ); psz_tmp = var_CreateGetNonEmptyStringCommand( p_intf, "fbosd-text" ); var_AddCallback( p_intf, "fbosd-text", OverlayCallback, NULL ); if( psz_tmp && *psz_tmp ) { p_sys->render[1].i_type = FBOSD_RENDER_TEXT; p_sys->render[1].i_state = FBOSD_STATE_RENDER; p_sys->render[1].psz_string = strdup( psz_tmp ); } free( psz_tmp ); p_sys->i_pos = var_CreateGetIntegerCommand( p_intf, "fbosd-position" ); p_sys->i_x = var_CreateGetIntegerCommand( p_intf, "fbosd-x" ); p_sys->i_y = var_CreateGetIntegerCommand( p_intf, "fbosd-y" ); var_AddCallback( p_intf, "fbosd-position", OverlayCallback, NULL ); var_AddCallback( p_intf, "fbosd-x", OverlayCallback, NULL ); var_AddCallback( p_intf, "fbosd-y", OverlayCallback, NULL ); p_sys->p_style->i_font_size = var_CreateGetIntegerCommand( p_intf, "fbosd-font-size" ); p_sys->p_style->i_font_color = var_CreateGetIntegerCommand( p_intf, "fbosd-font-color" ); p_sys->p_style->i_font_alpha = 255 - var_CreateGetIntegerCommand( p_intf, "fbosd-font-opacity" ); var_AddCallback( p_intf, "fbosd-font-color", OverlayCallback, NULL ); var_AddCallback( p_intf, "fbosd-font-size", OverlayCallback, NULL ); var_AddCallback( p_intf, "fbosd-font-opacity", OverlayCallback, NULL ); for( i = 0; i < FBOSD_RENDER_MAX; i++ ) p_sys->render[i].p_text_style = text_style_New(); p_sys->b_clear = var_CreateGetBoolCommand( p_intf, "fbosd-clear" ); p_sys->b_render = var_CreateGetBoolCommand( p_intf, "fbosd-render" ); p_sys->b_need_update = var_CreateGetBoolCommand( p_intf, "fbosd-display" ); var_AddCallback( p_intf, "fbosd-clear", OverlayCallback, NULL ); var_AddCallback( p_intf, "fbosd-render", OverlayCallback, NULL ); var_AddCallback( p_intf, "fbosd-display", OverlayCallback, NULL ); /* Check if picture position was overridden */ p_sys->b_absolute = true; if( ( p_sys->i_x >= 0 ) && ( p_sys->i_y >= 0 ) ) { p_sys->b_absolute = false; p_sys->i_y = (p_sys->i_y < p_sys->i_height) ? p_sys->i_y : p_sys->i_height; p_sys->i_x = (p_sys->i_x < p_sys->i_width) ? p_sys->i_x : p_sys->i_width; } p_sys->render[0].i_x = p_sys->render[1].i_x = p_sys->i_x; p_sys->render[0].i_y = p_sys->render[1].i_y = p_sys->i_y; p_sys->render[0].i_pos = p_sys->render[1].i_pos = p_sys->i_pos; p_sys->render[0].i_alpha = p_sys->render[1].i_alpha = p_sys->i_alpha; /* Initialize framebuffer */ if( OpenDisplay( p_intf ) ) { Destroy( VLC_OBJECT(p_intf) ); return VLC_EGENERIC; } Init( p_intf ); #if defined(FBOSD_BLENDING) /* Load the blending module */ if( OpenBlending( p_intf ) ) { msg_Err( p_intf, "Unable to load image blending module" ); Destroy( VLC_OBJECT(p_intf) ); return VLC_EGENERIC; } #endif /* Load text renderer module */ if( OpenTextRenderer( p_intf ) ) { msg_Err( p_intf, "Unable to load text rendering module" ); Destroy( VLC_OBJECT(p_intf) ); return VLC_EGENERIC; } p_sys->b_render = true; p_sys->b_need_update = true; return VLC_SUCCESS; } /***************************************************************************** * Destroy: destroy FB interface thread output method ***************************************************************************** * Terminate an output method created by Create *****************************************************************************/ static void Destroy( vlc_object_t *p_this ) { intf_thread_t *p_intf = (intf_thread_t *)p_this; intf_sys_t *p_sys = p_intf->p_sys; int i; p_sys->b_need_update = false; p_sys->b_render = false; p_sys->b_clear = false; var_DelCallback( p_intf, "fbosd-alpha", OverlayCallback, NULL ); var_Destroy( p_intf, "fbosd-alpha" ); var_DelCallback( p_intf, "fbosd-x", OverlayCallback, NULL ); var_DelCallback( p_intf, "fbosd-y", OverlayCallback, NULL ); var_DelCallback( p_intf, "fbosd-position", OverlayCallback, NULL ); var_DelCallback( p_intf, "fbosd-image", OverlayCallback, NULL ); var_DelCallback( p_intf, "fbosd-text", OverlayCallback, NULL ); var_DelCallback( p_intf, "fbosd-font-size", OverlayCallback, NULL ); var_DelCallback( p_intf, "fbosd-font-color", OverlayCallback, NULL ); var_DelCallback( p_intf, "fbosd-font-opacity", OverlayCallback, NULL ); var_DelCallback( p_intf, "fbosd-clear", OverlayCallback, NULL ); var_DelCallback( p_intf, "fbosd-render", OverlayCallback, NULL ); var_DelCallback( p_intf, "fbosd-display", OverlayCallback, NULL ); var_Destroy( p_intf, "fbosd-x" ); var_Destroy( p_intf, "fbosd-y" ); var_Destroy( p_intf, "fbosd-position" ); var_Destroy( p_intf, "fbosd-image" ); var_Destroy( p_intf, "fbosd-text" ); var_Destroy( p_intf, "fbosd-font-size" ); var_Destroy( p_intf, "fbosd-font-color" ); var_Destroy( p_intf, "fbosd-font-opacity" ); var_Destroy( p_intf, "fbosd-clear" ); var_Destroy( p_intf, "fbosd-render" ); var_Destroy( p_intf, "fbosd-display" ); var_Destroy( p_intf, "fbosd-aspect-ratio" ); CloseDisplay( p_intf ); for( i = 0; i < FBOSD_RENDER_MAX; i++ ) { free( p_sys->render[i].psz_string ); p_sys->render[i].i_state = FBOSD_STATE_FREE; text_style_Delete( p_sys->render[i].p_text_style ); } #if defined(FBOSD_BLENDING) if( p_sys->p_blend ) CloseBlending( p_intf ); #endif if( p_sys->p_text ) CloseTextRenderer( p_intf ); if( p_sys->p_image ) image_HandlerDelete( p_sys->p_image ); if( p_sys->p_overlay ) picture_Release( p_sys->p_overlay ); text_style_Delete( p_sys->p_style ); free( p_sys ); } #if defined(FBOSD_BLENDING) static int OpenBlending( intf_thread_t *p_intf ) { if( p_intf->p_sys->p_blend ) return VLC_EGENERIC; p_intf->p_sys->p_blend = vlc_object_create( p_intf, sizeof(filter_t) ); p_intf->p_sys->p_blend->fmt_out.video.i_x_offset = p_intf->p_sys->p_blend->fmt_out.video.i_y_offset = 0; p_intf->p_sys->p_blend->fmt_out.video.i_sar_num = p_intf->p_sys->fmt_out.i_sar_num; p_intf->p_sys->p_blend->fmt_out.video.i_sar_den = p_intf->p_sys->fmt_out.i_sar_den; p_intf->p_sys->p_blend->fmt_out.video.i_chroma = p_intf->p_sys->fmt_out.i_chroma; if( var_InheritBool( p_intf, "freetype-yuvp" ) ) p_intf->p_sys->p_blend->fmt_in.video.i_chroma = VLC_CODEC_YUVP; else p_intf->p_sys->p_blend->fmt_in.video.i_chroma = VLC_CODEC_YUVA; p_intf->p_sys->p_blend->p_module = module_need( p_intf->p_sys->p_blend, "video blending", NULL, false ); if( !p_intf->p_sys->p_blend->p_module ) return VLC_EGENERIC; return VLC_SUCCESS; } static void CloseBlending( intf_thread_t *p_intf ) { if( p_intf->p_sys->p_blend ) { if( p_intf->p_sys->p_blend->p_module ) module_unneed( p_intf->p_sys->p_blend, p_intf->p_sys->p_blend->p_module ); vlc_object_release( p_intf->p_sys->p_blend ); } } #endif static int OpenTextRenderer( intf_thread_t *p_intf ) { char *psz_modulename = NULL; if( p_intf->p_sys->p_text ) return VLC_EGENERIC; p_intf->p_sys->p_text = vlc_object_create( p_intf, sizeof(filter_t) ); p_intf->p_sys->p_text->fmt_out.video.i_width = p_intf->p_sys->p_text->fmt_out.video.i_visible_width = p_intf->p_sys->i_width; p_intf->p_sys->p_text->fmt_out.video.i_height = p_intf->p_sys->p_text->fmt_out.video.i_visible_height = p_intf->p_sys->i_height; psz_modulename = var_CreateGetString( p_intf, "text-renderer" ); if( psz_modulename && *psz_modulename ) { p_intf->p_sys->p_text->p_module = module_need( p_intf->p_sys->p_text, "text renderer", psz_modulename, true ); } if( !p_intf->p_sys->p_text->p_module ) { p_intf->p_sys->p_text->p_module = module_need( p_intf->p_sys->p_text, "text renderer", NULL, false ); } free( psz_modulename ); if( !p_intf->p_sys->p_text->p_module ) return VLC_EGENERIC; return VLC_SUCCESS; } static void CloseTextRenderer( intf_thread_t *p_intf ) { if( p_intf->p_sys->p_text ) { if( p_intf->p_sys->p_text->p_module ) module_unneed( p_intf->p_sys->p_text, p_intf->p_sys->p_text->p_module ); vlc_object_release( p_intf->p_sys->p_text ); } } /***************************************************************************** * AllocatePicture: * allocate a picture buffer for use with the overlay fb. *****************************************************************************/ static picture_t *AllocatePicture( video_format_t *p_fmt ) { picture_t *p_picture = picture_NewFromFormat( p_fmt ); if( !p_picture ) return NULL; if( !p_fmt->p_palette && ( p_fmt->i_chroma == VLC_CODEC_YUVP ) ) { p_fmt->p_palette = malloc( sizeof(video_palette_t) ); if( !p_fmt->p_palette ) { picture_Release( p_picture ); return NULL; } } else { p_fmt->p_palette = NULL; } return p_picture; } /***************************************************************************** * DeAllocatePicture: * Deallocate a picture buffer and free all associated memory. *****************************************************************************/ static void DeAllocatePicture( picture_t *p_pic, video_format_t *p_fmt ) { if( p_fmt ) { free( p_fmt->p_palette ); p_fmt->p_palette = NULL; } if( p_pic ) picture_Release( p_pic ); } /***************************************************************************** * SetOverlayTransparency: Set the transparency for this overlay fb, * - true is make transparent * - false is make non tranparent *****************************************************************************/ static void SetOverlayTransparency( intf_thread_t *p_intf, bool b_transparent ) { intf_sys_t *p_sys = p_intf->p_sys; size_t i_size = p_sys->fmt_out.i_width * p_sys->fmt_out.i_height * p_sys->i_bytes_per_pixel; size_t i_page_size = (p_sys->i_page_size > i_size) ? i_size : p_sys->i_page_size; if( p_sys->p_overlay ) { msg_Dbg( p_intf, "Make overlay %s", b_transparent ? "transparent" : "opaque" ); if( b_transparent ) memset( p_sys->p_overlay->p[0].p_pixels, 0xFF, i_page_size ); else memset( p_sys->p_overlay->p[0].p_pixels, 0x00, i_page_size ); } } #if defined(FBOSD_BLENDING) /***************************************************************************** * BlendPicture: Blend two pictures together.. *****************************************************************************/ static int BlendPicture( intf_thread_t *p_intf, video_format_t *p_fmt_src, video_format_t *p_fmt_dst, picture_t *p_pic_src, picture_t *p_pic_dst ) { intf_sys_t *p_sys = p_intf->p_sys; if( p_sys->p_blend && p_sys->p_blend->p_module ) { int i_x_offset = p_sys->i_x; int i_y_offset = p_sys->i_y; memcpy( &p_sys->p_blend->fmt_in.video, p_fmt_src, sizeof( video_format_t ) ); /* Update the output picture size */ p_sys->p_blend->fmt_out.video.i_width = p_sys->p_blend->fmt_out.video.i_visible_width = p_fmt_dst->i_width; p_sys->p_blend->fmt_out.video.i_height = p_sys->p_blend->fmt_out.video.i_visible_height = p_fmt_dst->i_height; i_x_offset = __MAX( i_x_offset, 0 ); i_y_offset = __MAX( i_y_offset, 0 ); p_sys->p_blend->pf_video_blend( p_sys->p_blend, p_pic_dst, p_pic_src, p_pic_dst, i_x_offset, i_y_offset, p_sys->i_alpha ); return VLC_SUCCESS; } return VLC_EGENERIC; } static int InvertAlpha( intf_thread_t *p_intf, picture_t **p_pic, video_format_t fmt ) { uint8_t *p_begin = NULL, *p_end = NULL; uint8_t i_skip = 0; if( *p_pic && ((*p_pic)->i_planes != 1) ) { msg_Err( p_intf, "cannot invert alpha channel too many planes %d (only 1 supported)", (*p_pic)->i_planes ); return VLC_EGENERIC; } switch( fmt.i_chroma ) { case VLC_CODEC_RGB24: p_begin = (uint8_t *)(*p_pic)->p[Y_PLANE].p_pixels; p_end = (uint8_t *)(*p_pic)->p[Y_PLANE].p_pixels + ( fmt.i_height * (*p_pic)->p[Y_PLANE].i_pitch ); i_skip = 3; break; case VLC_CODEC_RGB32: p_begin = (uint8_t *)(*p_pic)->p[Y_PLANE].p_pixels; p_end = (uint8_t *)(*p_pic)->p[Y_PLANE].p_pixels + ( fmt.i_height * (*p_pic)->p[Y_PLANE].i_pitch ); i_skip = 4; break; default: msg_Err( p_intf, "cannot invert alpha channel chroma not supported %4.4s", (char *)&fmt.i_chroma ); return VLC_EGENERIC; } for( ; p_begin < p_end; p_begin += i_skip ) { uint8_t i_opacity = 0; if( *p_begin != 0xFF ) i_opacity = 255 - *p_begin; *p_begin = i_opacity; } /* end of kludge */ return VLC_SUCCESS; } #endif /***************************************************************************** * RenderPicture: Render the picture into the p_dest buffer. * We don't take transparent pixels into account, so we don't have to blend * the two images together. *****************************************************************************/ static int RenderPicture( intf_thread_t *p_intf, int i_x_offset, int i_y_offset, picture_t *p_src, picture_t *p_dest ) { int i; VLC_UNUSED( p_intf ); if( !p_dest && !p_src ) return VLC_EGENERIC; for( i = 0; i < p_src->i_planes ; i++ ) { if( p_src->p[i].i_pitch == p_dest->p[i].i_pitch ) { /* There are margins, but with the same width : perfect ! */ vlc_memcpy( p_dest->p[i].p_pixels, p_src->p[i].p_pixels, p_src->p[i].i_pitch * p_src->p[i].i_visible_lines ); } else { /* We need to proceed line by line */ uint8_t *p_in = p_src->p[i].p_pixels; uint8_t *p_out = p_dest->p[i].p_pixels; int i_x = i_x_offset * p_src->p[i].i_pixel_pitch; int i_x_clip, i_y_clip; /* Check boundaries, clip the image if necessary */ i_x_clip = ( i_x + p_src->p[i].i_visible_pitch ) - p_dest->p[i].i_visible_pitch; i_x_clip = ( i_x_clip > 0 ) ? i_x_clip : 0; i_y_clip = ( i_y_offset + p_src->p[i].i_visible_lines ) - p_dest->p[i].i_visible_lines; i_y_clip = ( i_y_clip > 0 ) ? i_y_clip : 0; #if defined(FBOSD_DEBUG) msg_Dbg( p_intf, "i_pitch (%d,%d), (%d,%d)/(%d,%d)", p_dest->p[i].i_visible_pitch, p_src->p[i].i_visible_pitch, i_x_offset, i_y_offset, i_x, i_x_clip ); #endif if( ( i_y_offset <= p_dest->p[i].i_visible_lines ) && ( i_x <= p_dest->p[i].i_visible_pitch ) ) { int i_line; p_out += ( i_y_offset * p_dest->p[i].i_pitch ); for( i_line = 0; i_line < ( p_src->p[i].i_visible_lines - i_y_clip ); i_line++ ) { vlc_memcpy( p_out + i_x, p_in, p_src->p[i].i_visible_pitch - i_x_clip ); p_in += p_src->p[i].i_pitch; p_out += p_dest->p[i].i_pitch; } } } } return VLC_SUCCESS; } /***************************************************************************** * RenderText - Render text to the desired picture format *****************************************************************************/ static picture_t *RenderText( intf_thread_t *p_intf, const char *psz_string, text_style_t *p_style, video_format_t *p_fmt ) { intf_sys_t *p_sys = p_intf->p_sys; subpicture_region_t *p_region; picture_t *p_dest = NULL; if( !psz_string ) return p_dest; if( p_sys->p_text && p_sys->p_text->p_module ) { video_format_t fmt; memset( &fmt, 0, sizeof(fmt) ); fmt.i_chroma = VLC_CODEC_TEXT; fmt.i_width = fmt.i_visible_width = 0; fmt.i_height = fmt.i_visible_height = 0; fmt.i_x_offset = 0; fmt.i_y_offset = 0; p_region = subpicture_region_New( &fmt ); if( !p_region ) return p_dest; p_region->psz_text = strdup( psz_string ); if( !p_region->psz_text ) { subpicture_region_Delete( p_region ); return NULL; } p_region->p_style = text_style_Duplicate( p_style ); p_region->i_align = SUBPICTURE_ALIGN_LEFT | SUBPICTURE_ALIGN_TOP; if( p_sys->p_text->pf_render_text ) { video_format_t fmt_out; memset( &fmt_out, 0, sizeof(video_format_t) ); p_sys->p_text->pf_render_text( p_sys->p_text, p_region, p_region ); #if defined(FBOSD_BLENDING) fmt_out = p_region->fmt; fmt_out.i_bits_per_pixel = 32; vlc_memcpy( p_fmt, &fmt_out, sizeof(video_format_t) ); /* FIXME not needed to copy the picture anymore no ? */ p_dest = AllocatePicture( VLC_OBJECT(p_intf), &fmt_out ); if( !p_dest ) { subpicture_region_Delete( p_region ); return NULL; } picture_Copy( p_dest, p_region->p_picture ); #else fmt_out.i_chroma = p_fmt->i_chroma; p_dest = ConvertImage( p_intf, p_region->p_picture, &p_region->fmt, &fmt_out ); #endif subpicture_region_Delete( p_region ); return p_dest; } subpicture_region_Delete( p_region ); } return p_dest; } /***************************************************************************** * LoadImage: Load an image from file into a picture buffer. *****************************************************************************/ static picture_t *LoadImage( intf_thread_t *p_intf, video_format_t *p_fmt, char *psz_file ) { picture_t *p_pic = NULL; if( psz_file && p_intf->p_sys->p_image ) { video_format_t fmt_in, fmt_out; memset( &fmt_in, 0, sizeof(fmt_in) ); memset( &fmt_out, 0, sizeof(fmt_out) ); fmt_out.i_chroma = p_fmt->i_chroma; p_pic = image_ReadUrl( p_intf->p_sys->p_image, psz_file, &fmt_in, &fmt_out ); msg_Dbg( p_intf, "image size %dx%d chroma %4.4s", fmt_out.i_width, fmt_out.i_height, (char *)&p_fmt->i_chroma ); } return p_pic; } #if ! defined(FBOSD_BLENDING) /***************************************************************************** * Convertmage: Convert image to another fourcc *****************************************************************************/ static picture_t *ConvertImage( intf_thread_t *p_intf, picture_t *p_pic, video_format_t *p_fmt_in, video_format_t *p_fmt_out ) { intf_sys_t *p_sys = p_intf->p_sys; picture_t *p_old = NULL; if( p_sys->p_image ) { p_old = image_Convert( p_sys->p_image, p_pic, p_fmt_in, p_fmt_out ); msg_Dbg( p_intf, "converted image size %dx%d chroma %4.4s", p_fmt_out->i_width, p_fmt_out->i_height, (char *)&p_fmt_out->i_chroma ); } return p_old; } #endif /***************************************************************************** * Init: initialize framebuffer video thread output method *****************************************************************************/ static int Init( intf_thread_t *p_intf ) { intf_sys_t *p_sys = p_intf->p_sys; /* Initialize the output structure: RGB with square pixels, whatever * the input format is, since it's the only format we know */ switch( p_sys->var_info.bits_per_pixel ) { case 8: /* FIXME: set the palette */ p_sys->fmt_out.i_chroma = VLC_CODEC_RGB8; break; case 15: p_sys->fmt_out.i_chroma = VLC_CODEC_RGB15; break; case 16: p_sys->fmt_out.i_chroma = VLC_CODEC_RGB16; break; case 24: p_sys->fmt_out.i_chroma = VLC_CODEC_RGB24; break; case 32: p_sys->fmt_out.i_chroma = VLC_CODEC_RGB32; break; default: msg_Err( p_intf, "unknown screen depth %i", p_sys->var_info.bits_per_pixel ); return VLC_EGENERIC; } p_sys->fmt_out.i_bits_per_pixel = p_sys->var_info.bits_per_pixel; p_sys->fmt_out.i_width = p_sys->i_width; p_sys->fmt_out.i_height = p_sys->i_height; /* Assume we have square pixels */ if( p_sys->i_aspect < 0 ) { p_sys->fmt_out.i_sar_num = 1; p_sys->fmt_out.i_sar_den = 1; } else { p_sys->fmt_out.i_sar_num = p_sys->i_aspect * p_sys->i_height; p_sys->fmt_out.i_sar_den = VOUT_ASPECT_FACTOR * p_sys->i_width; } /* Allocate overlay buffer */ p_sys->p_overlay = AllocatePicture( &p_sys->fmt_out ); if( !p_sys->p_overlay ) return VLC_EGENERIC; SetOverlayTransparency( p_intf, true ); /* We know the chroma, allocate a buffer which will be used * to write to the overlay framebuffer */ p_sys->p_overlay->p->i_pixel_pitch = p_sys->i_bytes_per_pixel; p_sys->p_overlay->p->i_lines = p_sys->var_info.yres; p_sys->p_overlay->p->i_visible_lines = p_sys->var_info.yres; if( p_sys->var_info.xres_virtual ) { p_sys->p_overlay->p->i_pitch = p_sys->var_info.xres_virtual * p_sys->i_bytes_per_pixel; } else { p_sys->p_overlay->p->i_pitch = p_sys->var_info.xres * p_sys->i_bytes_per_pixel; } p_sys->p_overlay->p->i_visible_pitch = p_sys->var_info.xres * p_sys->i_bytes_per_pixel; p_sys->p_overlay->i_planes = 1; return VLC_SUCCESS; } /***************************************************************************** * End: terminate framebuffer interface *****************************************************************************/ static void End( intf_thread_t *p_intf ) { intf_sys_t *p_sys = p_intf->p_sys; /* CleanUp */ SetOverlayTransparency( p_intf, false ); if( p_sys->p_overlay ) { int ret; ret = write( p_sys->i_fd, p_sys->p_overlay->p[0].p_pixels, p_sys->i_page_size ); if( ret < 0 ) msg_Err( p_intf, "unable to clear overlay" ); } DeAllocatePicture( p_intf->p_sys->p_overlay, &p_intf->p_sys->fmt_out ); p_intf->p_sys->p_overlay = NULL; } /***************************************************************************** * OpenDisplay: initialize framebuffer *****************************************************************************/ static int OpenDisplay( intf_thread_t *p_intf ) { intf_sys_t *p_sys = p_intf->p_sys; char *psz_device; /* framebuffer device path */ struct fb_fix_screeninfo fix_info; /* framebuffer fix information */ /* Open framebuffer device */ if( !(psz_device = var_InheritString( p_intf, "fbosd-dev" )) ) { msg_Err( p_intf, "don't know which fb osd/overlay device to open" ); return VLC_EGENERIC; } p_sys->i_fd = vlc_open( psz_device, O_RDWR ); if( p_sys->i_fd == -1 ) { msg_Err( p_intf, "cannot open %s (%m)", psz_device ); free( psz_device ); return VLC_EGENERIC; } free( psz_device ); /* Get framebuffer device information */ if( ioctl( p_sys->i_fd, FBIOGET_VSCREENINFO, &p_sys->var_info ) ) { msg_Err( p_intf, "cannot get fb info (%m)" ); close( p_sys->i_fd ); return VLC_EGENERIC; } /* Get some info on the framebuffer itself */ if( ioctl( p_sys->i_fd, FBIOGET_FSCREENINFO, &fix_info ) == 0 ) { p_sys->i_width = p_sys->fmt_out.i_width = p_sys->var_info.xres; p_sys->i_height = p_sys->fmt_out.i_height = p_sys->var_info.yres; } /* FIXME: if the image is full-size, it gets cropped on the left * because of the xres / xres_virtual slight difference */ msg_Dbg( p_intf, "%ix%i (virtual %ix%i)", p_sys->var_info.xres, p_sys->var_info.yres, p_sys->var_info.xres_virtual, p_sys->var_info.yres_virtual ); p_sys->fmt_out.i_width = p_sys->i_width; p_sys->fmt_out.i_height = p_sys->i_height; p_sys->p_palette = NULL; p_sys->b_pan = ( fix_info.ypanstep || fix_info.ywrapstep ); switch( p_sys->var_info.bits_per_pixel ) { case 8: p_sys->p_palette = malloc( 8 * 256 * sizeof( uint16_t ) ); if( !p_sys->p_palette ) { close( p_sys->i_fd ); return VLC_ENOMEM; } p_sys->fb_cmap.start = 0; p_sys->fb_cmap.len = 256; p_sys->fb_cmap.red = p_sys->p_palette; p_sys->fb_cmap.green = p_sys->p_palette + 256 * sizeof( uint16_t ); p_sys->fb_cmap.blue = p_sys->p_palette + 2 * 256 * sizeof( uint16_t ); p_sys->fb_cmap.transp = p_sys->p_palette + 3 * 256 * sizeof( uint16_t ); /* Save the colormap */ ioctl( p_sys->i_fd, FBIOGETCMAP, &p_sys->fb_cmap ); p_sys->i_bytes_per_pixel = 1; break; case 15: case 16: p_sys->i_bytes_per_pixel = 2; break; case 24: p_sys->i_bytes_per_pixel = 3; break; case 32: p_sys->i_bytes_per_pixel = 4; break; default: msg_Err( p_intf, "screen depth %d is not supported", p_sys->var_info.bits_per_pixel ); close( p_sys->i_fd ); return VLC_EGENERIC; } p_sys->i_page_size = p_sys->i_width * p_sys->i_height * p_sys->i_bytes_per_pixel; msg_Dbg( p_intf, "framebuffer type=%d, visual=%d, ypanstep=%d, " "ywrap=%d, accel=%d", fix_info.type, fix_info.visual, fix_info.ypanstep, fix_info.ywrapstep, fix_info.accel ); return VLC_SUCCESS; } /***************************************************************************** * CloseDisplay: terminate FB interface thread *****************************************************************************/ static void CloseDisplay( intf_thread_t *p_intf ) { intf_sys_t *p_sys = p_intf->p_sys; /* Restore palette */ if( p_sys->var_info.bits_per_pixel == 8 ) { ioctl( p_sys->i_fd, FBIOPUTCMAP, &p_sys->fb_cmap ); free( p_sys->p_palette ); p_sys->p_palette = NULL; } /* Close fb */ close( p_sys->i_fd ); } static void Render( intf_thread_t *p_intf, struct fbosd_render_t *render ) { intf_sys_t *p_sys = p_intf->p_sys; if( render->i_state != FBOSD_STATE_RENDER ) return; if( !render->psz_string ) return; if( render->i_type == FBOSD_RENDER_IMAGE ) { picture_t *p_pic; p_pic = LoadImage( p_intf, &p_sys->fmt_out, render->psz_string ); if( p_pic ) { RenderPicture( p_intf, render->i_x, render->i_y, p_pic, p_sys->p_overlay ); picture_Release( p_pic ); } } else if( render->i_type == FBOSD_RENDER_TEXT ) { picture_t *p_text; #if defined(FBOSD_BLENDING) video_format_t fmt_in; memset( &fmt_in, 0, sizeof(video_format_t) ); p_text = RenderText( p_intf, render->psz_string, render->p_text_style, &fmt_in ); if( p_text ) { BlendPicture( p_intf, &fmt_in, &p_sys->fmt_out, p_text, p_sys->p_overlay ); msg_Dbg( p_intf, "releasing picture" ); DeAllocatePicture( p_text, &fmt_in ); } #else p_text = RenderText( p_intf, render->psz_string, render->p_text_style, &p_sys->fmt_out ); if( p_text ) { RenderPicture( p_intf, render->i_x, render->i_y, p_text, p_sys->p_overlay ); picture_Release( p_text ); } #endif } } static void RenderClear( intf_thread_t *p_intf, struct fbosd_render_t *render ) { intf_sys_t *p_sys = p_intf->p_sys; text_style_Delete( render->p_text_style ); render->p_text_style = text_style_New(); free( render->psz_string ); render->psz_string = NULL; render->i_x = p_sys->i_x; render->i_y = p_sys->i_y; render->i_pos = p_sys->i_pos; render->i_alpha = p_sys->i_alpha; render->b_absolute = p_sys->b_absolute; render->i_state = FBOSD_STATE_FREE; } static bool isRendererReady( intf_thread_t *p_intf ) { intf_sys_t *p_sys = p_intf->p_sys; int i; /* Check if there are more items to render */ for( i = 0; i < FBOSD_RENDER_MAX; i++ ) { if( p_sys->render[i].i_state == FBOSD_STATE_RESERVED ) return false; } return true; } /***************************************************************************** * Run: thread ***************************************************************************** * This part of the interface is in a separate thread so that we can call * exec() from within it without annoying the rest of the program. *****************************************************************************/ static void Run( intf_thread_t *p_intf ) { intf_sys_t *p_sys = p_intf->p_sys; int canc = vlc_savecancel(); while( vlc_object_alive( p_intf ) ) { int i; /* Is there somthing to render? */ for( i = 0; i < FBOSD_RENDER_MAX; i++ ) { if( p_sys->render[i].i_state == FBOSD_STATE_RENDER ) { Render( p_intf, &p_sys->render[i] ); RenderClear( p_intf, &p_sys->render[i] ); } } if( p_sys->b_clear ) { SetOverlayTransparency( p_intf, true ); var_SetString( p_intf, "fbosd-image", "" ); var_SetString( p_intf, "fbosd-text", "" ); p_sys->b_clear = false; p_sys->b_need_update = true; } if( p_sys->b_need_update && p_sys->p_overlay && isRendererReady( p_intf ) ) { int ret; #if defined(FBOSD_BLENDING) /* Reverse alpha channel to work around FPGA bug */ InvertAlpha( p_intf, &p_sys->p_overlay, p_sys->fmt_out ); #endif ret = write( p_sys->i_fd, p_sys->p_overlay->p[0].p_pixels, p_sys->i_page_size ); if( ret < 0 ) msg_Err( p_intf, "unable to write to overlay" ); lseek( p_sys->i_fd, 0, SEEK_SET ); /* clear the picture */ memset( p_sys->p_overlay->p[0].p_pixels, 0xFF, p_sys->i_page_size ); p_sys->b_need_update = false; } msleep( INTF_IDLE_SLEEP ); } End( p_intf ); vlc_restorecancel( canc ); } static int OverlayCallback( vlc_object_t *p_this, char const *psz_cmd, vlc_value_t oldval, vlc_value_t newval, void *p_data ) { intf_thread_t *p_intf = (intf_thread_t *) p_this; intf_sys_t *p_sys = p_intf->p_sys; VLC_UNUSED(oldval); VLC_UNUSED(p_data); if( !strncmp( psz_cmd, "fbosd-display", 13 ) ) { p_sys->b_need_update = true; } else if( !strncmp( psz_cmd, "fbosd-clear", 11 ) ) { int i; /* Clear the entire render list */ for( i = 0; i < FBOSD_RENDER_MAX; i++ ) { RenderClear( p_intf, &p_sys->render[i] ); } p_sys->b_clear = true; } else if( !strncmp( psz_cmd, "fbosd-render", 12 ) ) { int i; /* Are we already busy with on slot ? */ for( i = 0; i < FBOSD_RENDER_MAX; i++ ) { if( p_sys->render[i].i_state == FBOSD_STATE_RESERVED ) { p_sys->render[i].i_state = FBOSD_STATE_RENDER; break; } } } else { int i; /* Are we already busy with on slot ? */ for( i = 0; i < FBOSD_RENDER_MAX; i++ ) { if( p_sys->render[i].i_state == FBOSD_STATE_RESERVED ) break; } /* No, then find first FREE slot */ if( p_sys->render[i].i_state != FBOSD_STATE_RESERVED ) { for( i = 0; i < FBOSD_RENDER_MAX; i++ ) { if( p_sys->render[i].i_state == FBOSD_STATE_FREE ) break; } if( p_sys->render[i].i_state != FBOSD_STATE_FREE ) { msg_Warn( p_this, "render space depleated" ); return VLC_SUCCESS; } } /* Found a free slot */ p_sys->render[i].i_state = FBOSD_STATE_RESERVED; if( !strncmp( psz_cmd, "fbosd-image", 11 ) ) { free( p_sys->render[i].psz_string ); p_sys->render[i].psz_string = strdup( newval.psz_string ); p_sys->render[i].i_type = FBOSD_RENDER_IMAGE; } else if( !strncmp( psz_cmd, "fbosd-text", 10 ) ) { free( p_sys->render[i].psz_string ); p_sys->render[i].psz_string = strdup( newval.psz_string ); p_sys->render[i].i_type = FBOSD_RENDER_TEXT; } else if( !strncmp( psz_cmd, "fbosd-x", 7 ) ) { p_sys->render[i].b_absolute = false; p_sys->render[i].i_x = (newval.i_int < p_sys->i_width) ? newval.i_int : p_sys->i_width; } else if( !strncmp( psz_cmd, "fbosd-y", 7 ) ) { p_sys->render[i].b_absolute = false; p_sys->render[i].i_y = (newval.i_int < p_sys->i_height) ? newval.i_int : p_sys->i_height; } else if( !strncmp( psz_cmd, "fbosd-position", 14 ) ) { p_sys->render[i].b_absolute = true; p_sys->render[i].i_pos = newval.i_int; } else if( !strncmp( psz_cmd, "fbosd-font-size", 15 ) ) { p_sys->render[i].p_text_style->i_font_size = newval.i_int; } else if( !strncmp( psz_cmd, "fbosd-font-color", 16 ) ) { p_sys->render[i].p_text_style->i_font_color = newval.i_int; } else if( !strncmp( psz_cmd, "fbosd-font-opacity", 18 ) ) { p_sys->render[i].p_text_style->i_font_alpha = 255 - newval.i_int; } else if( !strncmp( psz_cmd, "fbosd-alpha", 11 ) ) { p_sys->render[i].i_alpha = newval.i_int; } } return VLC_SUCCESS; }
MessiahAndrw/Stereoscopic-VLC
modules/gui/fbosd.c
C
gpl-2.0
49,533
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18444 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace BrushTeeth3.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
Meowse/TechnicolorMillinery
Chris.Sopcak/Homework1/BrushTeeth3/BrushTeeth3/Properties/Settings.Designer.cs
C#
gpl-2.0
1,068
# Rails >= 3 module RedmineStealth class MailInterceptor def self.delivering_email(msg) if RedmineStealth.cloaked? msg.perform_deliveries = false if logger = ActionMailer::Base.logger logger.info("Squelching notification: #{msg.subject}") end end end end end ActionMailer::Base.register_interceptor(RedmineStealth::MailInterceptor)
teleological/redmine_stealth
lib/redmine_stealth/mail_interceptor.rb
Ruby
gpl-2.0
394
/***************************************************************************** * Free42 -- an HP-42S calculator simulator * Copyright (C) 2004-2019 Thomas Okken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2, * as published by the Free Software Foundation. * * 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/. *****************************************************************************/ #import <UIKit/UIKit.h> @class RootViewController; @interface Free42AppDelegate : NSObject <UIApplicationDelegate> { RootViewController *rootViewController; } @property (nonatomic, retain) IBOutlet RootViewController *rootViewController; + (const char *) getVersion; @end
melak/free42
iphone/Classes/Free42AppDelegate.h
C
gpl-2.0
1,109
DELETE FROM `spell_bonus_data` WHERE `entry` IN (703); INSERT INTO `spell_bonus_data` VALUES (703, 0, 0, 0, 0.07, 'rogue- garrote');
TheSecretPublisher/ThisIsSparta
sql/forgottenlands/old/world/2013_05_15_rogue_garrote.sql
SQL
gpl-2.0
134
#ifndef _module_h_ #define _module_h_ #define MODULE_PATH CARD_DRIVE"ML/MODULES/" /* module info structures */ #define MODULE_INFO_PREFIX __module_info_ #define MODULE_STRINGS_PREFIX __module_strings_ #define MODULE_PARAMS_PREFIX __module_params_ #define MODULE_PROPHANDLERS_PREFIX __module_prophandlers_ #define MODULE_CBR_PREFIX __module_cbr_ #define MODULE_CONFIG_PREFIX __module_config_ #define MODULE_PROPHANDLER_PREFIX __module_prophandler_ #define MODULE_MAGIC 0x5A #define STR(x) STR_(x) #define STR_(x) #x #define MODULE_COUNT_MAX 32 #define MODULE_NAME_LENGTH 8 #define MODULE_FILENAME_LENGTH 64 #define MODULE_STATUS_LENGTH 64 /* some callbacks that may be needed by modules. more to come. ideas? needs? */ #define CBR_PRE_SHOOT 1 /* called before image is taken */ #define CBR_POST_SHOOT 2 /* called after image is taken */ #define CBR_SHOOT_TASK 3 /* called periodically from shoot task */ #define CBR_DISPLAY_FILTER 4 /** * Display filters (things that alter the LiveView image) * * - ctx=0: should return 1 if the display filter mode should be enabled, 0 if not * (but must not do any heavy processing!!!) * * - else: ctx is a (struct display_filter_buffers *), see vram.h * (contains src_buf and dst_buf) * in this case, the cbr should paint the new image in dst_buf, * usually by processing the data from src_buf * * - note: some cameras do not support display filters; in this case, this CBR will not be called */ #define CBR_SECONDS_CLOCK 5 /* called every second */ #define CBR_VSYNC 6 /* called for every LiveView frame; can do display tricks; must not do any heavy processing!!! */ #define CBR_KEYPRESS 7 /* when a key was pressed, this cbr gets the translated key as ctx */ #define CBR_KEYPRESS_RAW 8 /* when a key was pressed, this cbr gets the raw (struct event *) as ctx */ #define CBR_VSYNC_SETPARAM 9 /* called from every LiveView frame; can change FRAME_ISO, FRAME_SHUTTER_TIMER, just like for HDR video */ /* portable key codes. intentionally defines to make numbers hardcoded so changed order wont change the integer number */ #define MODULE_KEY_PRESS_HALFSHUTTER ( 1) #define MODULE_KEY_UNPRESS_HALFSHUTTER ( 2) #define MODULE_KEY_PRESS_FULLSHUTTER ( 3) #define MODULE_KEY_UNPRESS_FULLSHUTTER ( 4) #define MODULE_KEY_WHEEL_UP ( 5) #define MODULE_KEY_WHEEL_DOWN ( 6) #define MODULE_KEY_WHEEL_LEFT ( 7) #define MODULE_KEY_WHEEL_RIGHT ( 8) #define MODULE_KEY_PRESS_SET ( 9) #define MODULE_KEY_UNPRESS_SET (10) #define MODULE_KEY_JOY_CENTER (11) #define MODULE_KEY_PRESS_UP (12) #define MODULE_KEY_PRESS_UP_RIGHT (13) #define MODULE_KEY_PRESS_UP_LEFT (14) #define MODULE_KEY_PRESS_RIGHT (15) #define MODULE_KEY_PRESS_LEFT (16) #define MODULE_KEY_PRESS_DOWN_RIGHT (17) #define MODULE_KEY_PRESS_DOWN_LEFT (18) #define MODULE_KEY_PRESS_DOWN (19) #define MODULE_KEY_UNPRESS_UDLR (20) #define MODULE_KEY_PRESS_ZOOMIN (21) #define MODULE_KEY_MENU (22) #define MODULE_KEY_INFO (23) #define MODULE_KEY_PLAY (24) #define MODULE_KEY_TRASH (25) #define MODULE_KEY_RATE (26) #define MODULE_KEY_REC (27) #define MODULE_KEY_LV (28) #define MODULE_KEY_Q (29) #define MODULE_KEY_PICSTYLE (30) #define MODULE_KEY_PRESS_FLASH_MOVIE (31) #define MODULE_KEY_UNPRESS_FLASH_MOVIE (32) #define MODULE_KEY_PRESS_DP (33) #define MODULE_KEY_UNPRESS_DP (34) #define MODULE_KEY_CANON 0 #define MODULE_KEY_PORTABLE 1 /* update major if older modules will *not* be compatible */ #define MODULE_MAJOR 3 /* update minor if older modules will be compatible, but newer module will not run on older magic lantern versions */ #define MODULE_MINOR 0 /* update patch if nothing regarding to compatibility changes */ #define MODULE_PATCH 0 /* module description that every module should deliver - optional. if not supplied, only the symbols are visible to other plugins. this might be useful for libraries. */ typedef struct { /* major determines the generic compatibilty, minor is backward compatible (e.g. new hooks) */ const unsigned char api_magic; const unsigned char api_major; const unsigned char api_minor; const unsigned char api_patch; /* the plugin's name and init/deinit functions */ const char *name; const char *long_name; unsigned int (*init) (); unsigned int (*deinit) (); } module_info_t; /* modules can have parameters - optional */ typedef struct { /* pointer to parameter in memory */ const void *parameter; /* stringified type like "uint32_t", "int32_t". restrict to stdint.h types */ const char *type; /* name of the parameter, must match to variable name */ const char *name; /* description for the user */ const char *desc; } module_parminfo_t; /* this struct supplies additional information like license, author etc - optional */ typedef struct { const char *name; const char *value; } module_strpair_t; /* this struct supplies a list of callback routines to call - optional */ typedef struct { const char *name; const char *symbol; unsigned int type; unsigned int (*handler) (unsigned int); unsigned int ctx; } module_cbr_t; /* this struct supplies a list of config entries liek CONFIG_INT - optional */ typedef struct { const char *name; const struct config_var *ref; } module_config_t; /* this struct supplies additional information like license, author etc - optional */ typedef struct { const char *name; void (*handler)(unsigned int property, void * priv, void * addr, unsigned int len); const unsigned int property; const unsigned int property_length; } module_prophandler_t; /* index of all loaded modules */ typedef struct { char name[MODULE_NAME_LENGTH+1]; char filename[MODULE_FILENAME_LENGTH+1]; char long_filename[MODULE_FILENAME_LENGTH+1]; char status[MODULE_STATUS_LENGTH+1]; char long_status[MODULE_STATUS_LENGTH+1]; module_info_t *info; module_strpair_t *strings; module_parminfo_t *params; module_prophandler_t **prop_handlers; module_cbr_t *cbr; module_config_t *config; int valid; int enabled; int error; } module_entry_t; #define MODULE_INFO_START() MODULE_INFO_START_(MODULE_INFO_PREFIX,MODULE_NAME) #define MODULE_INFO_START_(prefix,modname) MODULE_INFO_START__(prefix,modname) #define MODULE_INFO_START__(prefix,modname) module_info_t prefix##modname = \ {\ .api_magic = MODULE_MAGIC, \ .api_major = MODULE_MAJOR, \ .api_minor = MODULE_MINOR, \ .api_patch = MODULE_PATCH, \ .name = #modname, #define MODULE_INIT(func) .init = &func, #define MODULE_DEINIT(func) .deinit = &func, #define MODULE_LONGNAME(name) .long_name = name, #define MODULE_CB_SHOOT_TASK(func) .cb_shoot_task = &func, #define MODULE_CB_PRE_SHOOT(func) .cb_pre_shoot = &func, #define MODULE_CB_POST_SHOOT(func) .cb_post_shoot = &func, #define MODULE_INFO_END() }; #define MODULE_STRINGS_START() MODULE_STRINGS_START_(MODULE_STRINGS_PREFIX,MODULE_NAME) #define MODULE_STRINGS_START_(prefix,modname) MODULE_STRINGS_START__(prefix,modname) #define MODULE_STRINGS_START__(prefix,modname) module_strpair_t prefix##modname[] = { #define MODULE_STRING(field,value) { field, value }, #define MODULE_STRINGS_END() { (const char *)0, (const char *)0 }\ }; #define MODULE_CBRS_START() MODULE_CBRS_START_(MODULE_CBR_PREFIX,MODULE_NAME) #define MODULE_CBRS_START_(prefix,modname) MODULE_CBRS_START__(prefix,modname) #define MODULE_CBRS_START__(prefix,modname) module_cbr_t prefix##modname[] = { #define MODULE_CBR(cb_type,cbr,context) { .name = #cb_type, .symbol = #cbr, .type = cb_type, .handler = cbr, .ctx = context }, #define MODULE_CBRS_END() { (void *)0, (void *)0, 0, (void *)0, 0 }\ }; #define MODULE_CONFIGS_START() MODULE_CONFIGS_START_(MODULE_CONFIG_PREFIX,MODULE_NAME) #define MODULE_CONFIGS_START_(prefix,modname) MODULE_CONFIGS_START__(prefix,modname) #define MODULE_CONFIGS_START__(prefix,modname) module_config_t prefix##modname[] = { #define MODULE_CONFIG(cfg) { .name = #cfg, .ref = &__config_##cfg }, #define MODULE_CONFIGS_END() { (void *)0, (void *)0 }\ }; #define MODULE_PARAMS_START() MODULE_PARAMS_START_(MODULE_PARAMS_PREFIX,MODULE_NAME) #define MODULE_PARAMS_START_(prefix,modname) MODULE_PARAMS_START__(prefix,modname) #define MODULE_PARAMS_START__(prefix,modname) module_parminfo_t prefix##modname[] = { #define MODULE_PARAM(var,typestr,descr) { .parameter = &var, .name = #var, .type = typestr, .desc = descr }, #define MODULE_PARAMS_END() { (void *)0, (const char *)0, (const char *)0, (const char *)0 }\ }; #define MODULE_PROPHANDLERS_START() MODULE_PROPHANDLERS_START_(MODULE_PROPHANDLERS_PREFIX,MODULE_NAME,MODULE_PROPHANDLER_PREFIX) #define MODULE_PROPHANDLERS_START_(prefix,modname,ph_prefix) MODULE_PROPHANDLERS_START__(prefix,modname,ph_prefix) #define MODULE_PROPHANDLERS_START__(prefix,modname,ph_prefix) module_prophandler_t *prefix##modname[] = { #define MODULE_PROPHANDLER(id) MODULE_PROPHANDLER_(MODULE_PROPHANDLERS_PREFIX,MODULE_NAME,MODULE_PROPHANDLER_PREFIX,id) #define MODULE_PROPHANDLER_(prefix,modname,ph_prefix,id) MODULE_PROPHANDLER__(prefix,modname,ph_prefix,id) #define MODULE_PROPHANDLER__(prefix,modname,ph_prefix,id) &ph_prefix##modname##_##id##_block, #define MODULE_PROPHANDLERS_END() NULL\ }; #if defined(MODULE) extern char *module_card_drive; #define MODULE_CARD_DRIVE module_card_drive #define PROP_HANDLER(id) MODULE_PROP_ENTRY_(MODULE_PROPHANDLER_PREFIX,MODULE_NAME, id, #id) #define MODULE_PROP_ENTRY_(prefix,modname,id,idstr) MODULE_PROP_ENTRY__(prefix,modname,id,idstr) #define MODULE_PROP_ENTRY__(prefix,modname,id,idstr) void prefix##modname##_##id(unsigned int, void *, void *, unsigned int);\ module_prophandler_t prefix##modname##_##id##_block = { \ .name = idstr, \ .handler = &prefix##modname##_##id, \ .property = id, \ .property_length = 0, \ }; \ void prefix##modname##_##id( \ unsigned int property, \ void * token, \ void * buf, \ unsigned int len \ ) #endif /* load all available modules. will be used on magic lantern boot */ void module_load_all(void); void module_unload_all(void); /* explicitely load a standalone module. this is comparable to an executable */ void *module_load(char *filename); int module_exec(void *module, char *symbol, int count, ...); int module_unload(void *module); unsigned int module_get_symbol(void *module, char *symbol); /* execute all callback routines of given type. maybe it will get extended to support varargs */ int module_exec_cbr(unsigned int type); int module_set_config_cbr(unsigned int (*load_func)(char *, module_entry_t *), unsigned int (save_func)(char *, module_entry_t *)); int module_unset_config_cbr(); #endif
frantony/magic-lantern
src/module.h
C
gpl-2.0
14,579
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUserOptionsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('user_options', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->string('option'); $table->string('value'); $table->timestamps(); $table->foreign('user_id')->references('id')->on('users'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('user_options'); } }
poctob/zoe
database/migrations/2015_09_30_142129_create_user_options_table.php
PHP
gpl-2.0
770
<?php /** * Most Liked Content tempplate */ // Block direct requests if ( !defined('ABSPATH') ) die('-1'); ?> <?php echo $before_widget; ?> <?php if (!empty($title)): echo $before_title . $title . $after_title; endif ?> <?php if (count($post_loop) > 0): ?> <ul class="likebtn-mlw"> <?php foreach ($post_loop as $post): ?> <li id="post-<?php echo $post['id'] ?>" class="likebtn-mlw-item" > <a href="<?php echo $post['link'] ?>" title="<?php echo $post['title'] ?>"> <?php if ($show_thumbnail): ?> <?php if( 'image/' == substr( $post['post_mime_type'], 0, 6 ) ): ?> <?php echo wp_get_attachment_image( $post['id'], $thumbnail_size, array('class' => 'likebtn-item-thumbnail') ); ?> <?php else: ?> <?php echo get_the_post_thumbnail($post['id'], $thumbnail_size, array('class' => 'likebtn-item-thumbnail')); ?> <?php endif ?> <?php endif ?> <div class="likebtn-mlw-title"> <?php echo $post['title'] ?> <?php if ($show_date && $post['date']): ?> <span class="likebtn-mlw-date">[<?php echo date_i18n(get_option('date_format'), $post['date']) ?> ]</span> <?php endif ?> <?php if ($show_likes || $show_dislikes): ?> <span class="likebtn-item-likes"><nobr>( <?php endif ?> <?php echo $show_likes ? $post['likes'] : ''; ?> <?php if ($show_likes && $show_dislikes): ?> / <?php endif ?> <?php echo $show_dislikes ? $post['dislikes'] : ''; ?> <?php if ($show_likes || $show_dislikes): ?> )</nobr></span> <?php endif ?> </div> </a> <?php if ($show_excerpt): ?> <div class="likebtn-mlw-excerpt"><?php echo $post['excerpt'] ?></div> <?php endif ?> <?php if ($show_thumbnail || $show_excerpt): ?> <br/> <?php endif ?> </li> <?php endforeach; ?> </ul> <?php else: // No items ?> <div class="likebtn-mlw-no-items"> <p><?php _e('No items liked yet.', LIKEBTN_I18N_DOMAIN); ?></p> </div> <?php endif; echo $after_widget; ?>
andrescabsi14/a2clean
wp-content/plugins/likebtn-like-button/templates/most-liked-widget.php
PHP
gpl-2.0
2,418
<?php /** * Part Name: Logo In Menu */ ?> <header id="masthead" class="site-header masthead-logo-in-menu" role="banner"> <nav role="navigation" class="site-navigation main-navigation primary <?php if( siteorigin_setting('navigation_use_sticky_menu') ) echo 'use-sticky-menu' ?>"> <div class="full-container"> <a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home" class="logo"><img src="http://qwerty.ie/headstuff/wp-content/uploads/2014/02/headstuff.png" width="181" height="40" alt="HeadStuff.org"/> </a> <?php if( siteorigin_setting('navigation_menu_search') ) : ?> <div id="search-icon"> <div id="search-icon-icon"><div class="icon"></div></div> <form method="get" class="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>" role="search"> <input type="text" class="field" name="s" value="<?php echo esc_attr( get_search_query() ); ?>" /> </form> </div> <?php endif; ?> <?php wp_nav_menu( array( 'theme_location' => 'primary', 'link_before' => '<span class="icon"></span>' ) ); ?> </div> </nav><!-- .site-navigation .main-navigation --> </header><!-- #masthead .site-header -->
adshannon81/Headstuff.org
wp-content/themes/vantage/parts/masthead-logo-in-menu.php
PHP
gpl-2.0
1,223
<?php /** * These functions are needed to load Multisite. * * @since 3.0.0 * * @package WordPress * @subpackage Multisite */ /** * Whether a subdomain configuration is enabled. * * @since 3.0.0 * * @return bool True if subdomain configuration is enabled, false otherwise. */ function is_subdomain_install() { if ( defined('SUBDOMAIN_INSTALL') ) return SUBDOMAIN_INSTALL; <<<<<<< HEAD if ( defined('VHOST') && VHOST == 'yes' ) return true; return false; ======= return ( defined( 'VHOST' ) && VHOST == 'yes' ); >>>>>>> c4ed0da5825345f6b0fe3527d88a7e02d1806836 } /** * Returns array of network plugin files to be included in global scope. * * The default directory is wp-content/plugins. To change the default directory * manually, define `WP_PLUGIN_DIR` and `WP_PLUGIN_URL` in `wp-config.php`. * * @access private * @since 3.1.0 * * @return array Files to include. */ function wp_get_active_network_plugins() { $active_plugins = (array) get_site_option( 'active_sitewide_plugins', array() ); if ( empty( $active_plugins ) ) return array(); $plugins = array(); $active_plugins = array_keys( $active_plugins ); sort( $active_plugins ); foreach ( $active_plugins as $plugin ) { if ( ! validate_file( $plugin ) // $plugin must validate as file && '.php' == substr( $plugin, -4 ) // $plugin must end with '.php' && file_exists( WP_PLUGIN_DIR . '/' . $plugin ) // $plugin must exist ) $plugins[] = WP_PLUGIN_DIR . '/' . $plugin; } return $plugins; } /** * Checks status of current blog. * * Checks if the blog is deleted, inactive, archived, or spammed. * * Dies with a default message if the blog does not pass the check. * * To change the default message when a blog does not pass the check, * use the wp-content/blog-deleted.php, blog-inactive.php and * blog-suspended.php drop-ins. * * @since 3.0.0 * <<<<<<< HEAD * @return bool|string Returns true on success, or drop-in file to include. ======= * @return true|string Returns true on success, or drop-in file to include. >>>>>>> c4ed0da5825345f6b0fe3527d88a7e02d1806836 */ function ms_site_check() { $blog = get_blog_details(); /** * Filter checking the status of the current blog. * * @since 3.0.0 * * @param bool null Whether to skip the blog status check. Default null. */ $check = apply_filters( 'ms_site_check', null ); if ( null !== $check ) return true; // Allow super admins to see blocked sites if ( is_super_admin() ) return true; if ( '1' == $blog->deleted ) { if ( file_exists( WP_CONTENT_DIR . '/blog-deleted.php' ) ) return WP_CONTENT_DIR . '/blog-deleted.php'; else wp_die( __( 'This site is no longer available.' ), '', array( 'response' => 410 ) ); } if ( '2' == $blog->deleted ) { if ( file_exists( WP_CONTENT_DIR . '/blog-inactive.php' ) ) return WP_CONTENT_DIR . '/blog-inactive.php'; else wp_die( sprintf( __( 'This site has not been activated yet. If you are having problems activating your site, please contact <a href="mailto:%1$s">%1$s</a>.' ), str_replace( '@', ' AT ', get_site_option( 'admin_email', 'support@' . get_current_site()->domain ) ) ) ); } if ( $blog->archived == '1' || $blog->spam == '1' ) { if ( file_exists( WP_CONTENT_DIR . '/blog-suspended.php' ) ) return WP_CONTENT_DIR . '/blog-suspended.php'; else wp_die( __( 'This site has been archived or suspended.' ), '', array( 'response' => 410 ) ); } return true; } /** * Retrieve a network object by its domain and path. * * @since 3.9.0 * <<<<<<< HEAD * @param string $domain Domain to check. * @param string $path Path to check. * @param int|null $segments Path segments to use. Defaults to null, or the full path. * @return object|bool Network object if successful. False when no network is found. ======= * @global wpdb $wpdb * * @param string $domain Domain to check. * @param string $path Path to check. * @param int|null $segments Path segments to use. Defaults to null, or the full path. * @return object|false Network object if successful. False when no network is found. >>>>>>> c4ed0da5825345f6b0fe3527d88a7e02d1806836 */ function get_network_by_path( $domain, $path, $segments = null ) { global $wpdb; $domains = array( $domain ); $pieces = explode( '.', $domain ); /* * It's possible one domain to search is 'com', but it might as well * be 'localhost' or some other locally mapped domain. */ while ( array_shift( $pieces ) ) { if ( $pieces ) { $domains[] = implode( '.', $pieces ); } } /* * If we've gotten to this function during normal execution, there is * more than one network installed. At this point, who knows how many * we have. Attempt to optimize for the situation where networks are * only domains, thus meaning paths never need to be considered. * * This is a very basic optimization; anything further could have drawbacks * depending on the setup, so this is best done per-install. */ $using_paths = true; if ( wp_using_ext_object_cache() ) { $using_paths = wp_cache_get( 'networks_have_paths', 'site-options' ); if ( false === $using_paths ) { $using_paths = (bool) $wpdb->get_var( "SELECT id FROM $wpdb->site WHERE path <> '/' LIMIT 1" ); wp_cache_add( 'networks_have_paths', (int) $using_paths, 'site-options' ); } } $paths = array(); if ( $using_paths ) { $path_segments = array_filter( explode( '/', trim( $path, "/" ) ) ); /** * Filter the number of path segments to consider when searching for a site. * * @since 3.9.0 * * @param int|null $segments The number of path segments to consider. WordPress by default looks at * one path segment. The function default of null only makes sense when you * know the requested path should match a network. * @param string $domain The requested domain. * @param string $path The requested path, in full. */ $segments = apply_filters( 'network_by_path_segments_count', $segments, $domain, $path ); if ( null !== $segments && count($path_segments ) > $segments ) { $path_segments = array_slice( $path_segments, 0, $segments ); } while ( count( $path_segments ) ) { $paths[] = '/' . implode( '/', $path_segments ) . '/'; array_pop( $path_segments ); } $paths[] = '/'; } /** * Determine a network by its domain and path. * * This allows one to short-circuit the default logic, perhaps by * replacing it with a routine that is more optimal for your setup. * * Return null to avoid the short-circuit. Return false if no network * can be found at the requested domain and path. Otherwise, return * an object from wp_get_network(). * * @since 3.9.0 * * @param null|bool|object $network Network value to return by path. * @param string $domain The requested domain. * @param string $path The requested path, in full. * @param int|null $segments The suggested number of paths to consult. * Default null, meaning the entire path was to be consulted. * @param array $paths The paths to search for, based on $path and $segments. */ $pre = apply_filters( 'pre_get_network_by_path', null, $domain, $path, $segments, $paths ); if ( null !== $pre ) { return $pre; } // @todo Consider additional optimization routes, perhaps as an opt-in for plugins. // We already have paths covered. What about how far domains should be drilled down (including www)? $search_domains = "'" . implode( "', '", $wpdb->_escape( $domains ) ) . "'"; if ( ! $using_paths ) { $network = $wpdb->get_row( "SELECT id, domain, path FROM $wpdb->site WHERE domain IN ($search_domains) ORDER BY CHAR_LENGTH(domain) DESC LIMIT 1" ); if ( $network ) { return wp_get_network( $network ); } return false; } else { $search_paths = "'" . implode( "', '", $wpdb->_escape( $paths ) ) . "'"; $networks = $wpdb->get_results( "SELECT id, domain, path FROM $wpdb->site WHERE domain IN ($search_domains) AND path IN ($search_paths) ORDER BY CHAR_LENGTH(domain) DESC, CHAR_LENGTH(path) DESC" ); } /* * Domains are sorted by length of domain, then by length of path. * The domain must match for the path to be considered. Otherwise, * a network with the path of / will suffice. */ $found = false; foreach ( $networks as $network ) { if ( $network->domain === $domain || "www.$network->domain" === $domain ) { if ( in_array( $network->path, $paths, true ) ) { $found = true; break; } } if ( $network->path === '/' ) { $found = true; break; } } if ( $found ) { return wp_get_network( $network ); } return false; } /** * Retrieve an object containing information about the requested network. * * @since 3.9.0 * <<<<<<< HEAD * @param object|int $network The network's database row or ID. * @return object|bool Object containing network information if found, false if not. ======= * @global wpdb $wpdb * * @param object|int $network The network's database row or ID. * @return object|false Object containing network information if found, false if not. >>>>>>> c4ed0da5825345f6b0fe3527d88a7e02d1806836 */ function wp_get_network( $network ) { global $wpdb; if ( ! is_object( $network ) ) { $network = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->site WHERE id = %d", $network ) ); if ( ! $network ) { return false; } } return $network; } /** * Retrieve a site object by its domain and path. * * @since 3.9.0 * <<<<<<< HEAD * @param string $domain Domain to check. * @param string $path Path to check. * @param int|null $segments Path segments to use. Defaults to null, or the full path. * @return object|bool Site object if successful. False when no site is found. ======= * @global wpdb $wpdb * * @param string $domain Domain to check. * @param string $path Path to check. * @param int|null $segments Path segments to use. Defaults to null, or the full path. * @return object|false Site object if successful. False when no site is found. >>>>>>> c4ed0da5825345f6b0fe3527d88a7e02d1806836 */ function get_site_by_path( $domain, $path, $segments = null ) { global $wpdb; $path_segments = array_filter( explode( '/', trim( $path, '/' ) ) ); /** * Filter the number of path segments to consider when searching for a site. * * @since 3.9.0 * * @param int|null $segments The number of path segments to consider. WordPress by default looks at * one path segment following the network path. The function default of * null only makes sense when you know the requested path should match a site. * @param string $domain The requested domain. * @param string $path The requested path, in full. */ $segments = apply_filters( 'site_by_path_segments_count', $segments, $domain, $path ); if ( null !== $segments && count( $path_segments ) > $segments ) { $path_segments = array_slice( $path_segments, 0, $segments ); } $paths = array(); while ( count( $path_segments ) ) { $paths[] = '/' . implode( '/', $path_segments ) . '/'; array_pop( $path_segments ); } $paths[] = '/'; /** * Determine a site by its domain and path. * * This allows one to short-circuit the default logic, perhaps by * replacing it with a routine that is more optimal for your setup. * * Return null to avoid the short-circuit. Return false if no site * can be found at the requested domain and path. Otherwise, return * a site object. * * @since 3.9.0 * * @param null|bool|object $site Site value to return by path. * @param string $domain The requested domain. * @param string $path The requested path, in full. * @param int|null $segments The suggested number of paths to consult. * Default null, meaning the entire path was to be consulted. * @param array $paths The paths to search for, based on $path and $segments. */ $pre = apply_filters( 'pre_get_site_by_path', null, $domain, $path, $segments, $paths ); if ( null !== $pre ) { return $pre; } /* * @todo * get_blog_details(), caching, etc. Consider alternative optimization routes, * perhaps as an opt-in for plugins, rather than using the pre_* filter. * For example: The segments filter can expand or ignore paths. * If persistent caching is enabled, we could query the DB for a path <> '/' * then cache whether we can just always ignore paths. */ // Either www or non-www is supported, not both. If a www domain is requested, // query for both to provide the proper redirect. $domains = array( $domain ); if ( 'www.' === substr( $domain, 0, 4 ) ) { $domains[] = substr( $domain, 4 ); $search_domains = "'" . implode( "', '", $wpdb->_escape( $domains ) ) . "'"; } if ( count( $paths ) > 1 ) { $search_paths = "'" . implode( "', '", $wpdb->_escape( $paths ) ) . "'"; } if ( count( $domains ) > 1 && count( $paths ) > 1 ) { $site = $wpdb->get_row( "SELECT * FROM $wpdb->blogs WHERE domain IN ($search_domains) AND path IN ($search_paths) ORDER BY CHAR_LENGTH(domain) DESC, CHAR_LENGTH(path) DESC LIMIT 1" ); } elseif ( count( $domains ) > 1 ) { $sql = $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE path = %s", $paths[0] ); $sql .= " AND domain IN ($search_domains) ORDER BY CHAR_LENGTH(domain) DESC LIMIT 1"; $site = $wpdb->get_row( $sql ); } elseif ( count( $paths ) > 1 ) { $sql = $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain = %s", $domains[0] ); $sql .= " AND path IN ($search_paths) ORDER BY CHAR_LENGTH(path) DESC LIMIT 1"; $site = $wpdb->get_row( $sql ); } else { $site = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain = %s AND path = %s", $domains[0], $paths[0] ) ); } if ( $site ) { // @todo get_blog_details() return $site; } return false; } /** * Displays a failure message. * * Used when a blog's tables do not exist. Checks for a missing $wpdb->site table as well. * * @access private * @since 3.0.0 <<<<<<< HEAD ======= * * @global wpdb $wpdb * @global string $domain * @global string $path >>>>>>> c4ed0da5825345f6b0fe3527d88a7e02d1806836 */ function ms_not_installed() { global $wpdb, $domain, $path; if ( ! is_admin() ) { dead_db(); } wp_load_translations_early(); $title = __( 'Error establishing a database connection' ); $msg = '<h1>' . $title . '</h1>'; $msg .= '<p>' . __( 'If your site does not display, please contact the owner of this network.' ) . ''; $msg .= ' ' . __( 'If you are the owner of this network please check that MySQL is running properly and all tables are error free.' ) . '</p>'; $query = $wpdb->prepare( "SHOW TABLES LIKE %s", $wpdb->esc_like( $wpdb->site ) ); if ( ! $wpdb->get_var( $query ) ) { $msg .= '<p>' . sprintf( /* translators: %s: table name */ __( '<strong>Database tables are missing.</strong> This means that MySQL is not running, WordPress was not installed properly, or someone deleted %s. You really should look at your database now.' ), '<code>' . $wpdb->site . '</code>' ) . '</p>'; } else { $msg .= '<p>' . sprintf( /* translators: 1: site url, 2: table name, 3: database name */ __( '<strong>Could not find site %1$s.</strong> Searched for table %2$s in database %3$s. Is that right?' ), '<code>' . rtrim( $domain . $path, '/' ) . '</code>', '<code>' . $wpdb->blogs . '</code>', '<code>' . DB_NAME . '</code>' ) . '</p>'; } $msg .= '<p><strong>' . __( 'What do I do now?' ) . '</strong> '; $msg .= __( 'Read the <a target="_blank" href="https://codex.wordpress.org/Debugging_a_WordPress_Network">bug report</a> page. Some of the guidelines there may help you figure out what went wrong.' ); $msg .= ' ' . __( 'If you&#8217;re still stuck with this message, then check that your database contains the following tables:' ) . '</p><ul>'; foreach ( $wpdb->tables('global') as $t => $table ) { if ( 'sitecategories' == $t ) continue; $msg .= '<li>' . $table . '</li>'; } $msg .= '</ul>'; wp_die( $msg, $title, array( 'response' => 500 ) ); } /** * This deprecated function formerly set the site_name property of the $current_site object. * * This function simply returns the object, as before. * The bootstrap takes care of setting site_name. * * @access private * @since 3.0.0 * @deprecated 3.9.0 Use get_current_site() instead. * * @param object $current_site * @return object */ function get_current_site_name( $current_site ) { _deprecated_function( __FUNCTION__, '3.9', 'get_current_site()' ); return $current_site; } /** * This deprecated function managed much of the site and network loading in multisite. * * The current bootstrap code is now responsible for parsing the site and network load as * well as setting the global $current_site object. * * @access private * @since 3.0.0 * @deprecated 3.9.0 * <<<<<<< HEAD ======= * @global object $current_site * >>>>>>> c4ed0da5825345f6b0fe3527d88a7e02d1806836 * @return object */ function wpmu_current_site() { global $current_site; _deprecated_function( __FUNCTION__, '3.9' ); return $current_site; }
creative2020/mu2
wp-includes/ms-load.php
PHP
gpl-2.0
17,259
<?php /** * Your Inspiration Themes * * @package WordPress * @subpackage Your Inspiration Themes * @author Your Inspiration Themes Team <info@yithemes.com> * * This source file is subject to the GNU GENERAL PUBLIC LICENSE (GPL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://www.gnu.org/licenses/gpl-3.0.txt */ /** * Manage the Dyanimc CSS useful for the theme. * * All rules will be added with the method ->add( $rule, $args ); * * Then, all css generated will be saved in cache/custom.css, only when is called the * method ->save_css(); * * @since 1.0.0 */ class YIT_Css { /** * All rules to save in file css * * @var array * @access protected * @since 1.0.0 */ protected $_rules = array(); /** * Filename where to save the custom css * * @var string * @access protected * @since 1.0.0 */ protected $_customFilename = 'custom.css'; /** * Filename where to save the custom css * * @var string * @access protected * @since 1.0.0 */ protected $_styleFilename = 'style.css'; /** * String to save internal stylesheets content * * @var string * @access protected * @since 1.0.0 */ protected $_style = ''; /** * All stylesheets to enqueue * * @var array * @access protected * @since 1.0.0 */ protected $_stylesheets = array(); /** * Init of class * * @since 1.0.0 */ public function init() { add_action( 'wp_enqueue_scripts', array( &$this, 'enqueue' ), 15 ); add_action( 'wp_enqueue_scripts', array( &$this, 'enqueue_custom' ), 16 ); add_action( 'init', array( &$this, 'custom_file_exists' ) ); } /** * Return the custom.css filename including the id of the site * if the site is in a Network * * @return string * @since 1.0.0 */ protected function _getCustomFilename() { global $wpdb; $index = $wpdb->blogid != 0 ? '-' . $wpdb->blogid : ''; return str_replace( '.css', $index . '.css', $this->_customFilename ); } /** * Generate custom.css file if it doesn't exist * * @return bool * @since 1.0.0 */ public function custom_file_exists() { $file = yit_get_model( 'cache' )->locate_file( $this->_getCustomFilename() ); if( !file_exists($file) ) { return $this->save_css(); } else { return true; } } /** * Enqueue custom.css file * * @return void * @since 1.0.0 */ public function enqueue_custom() { if( $this->custom_file_exists() ) { wp_enqueue_style( 'cache-custom', yit_get_model('cache')->locate_url( $this->_getCustomFilename() ), array(), false, 'all' ); } } /** * Save the file with all css * * @return bool * @since 1.0.0 */ public function save_css() { global $wpdb; $css = array(); // collect all css rules do_action( 'yit_save_css' ); foreach ( $this->_rules as $rule => $args ) { $args_css = array(); foreach ( $args as $arg => $value ) { //if ( $value == '' ) continue; $args_css[] = $arg . ': ' . $value . ';'; } $css[] = $rule . ' { ' . implode( ' ', $args_css ) . ' }'; } $css = apply_filters( 'yit_custom_style', implode( "\n", $css ) ); // save the css in the file $index = $wpdb->blogid != 0 ? '-' . $wpdb->blogid : ''; return yit_file_put_contents( yit_get_model( 'cache' )->locate_file( str_replace( '.css', $index . '.css', $this->_customFilename ) ), $css ); } /** * Add the rule css * * @param string $rule * @param array $args * @return bool * @since 1.0.0 */ public function add( $rule, $args = array() ) { if ( isset( $this->_rules[ $rule ] ) ) { $this->_rules[ $rule ] = array_merge( $this->_rules[ $rule ], $args ); } else { $this->_rules[ $rule ] = $args; } } /** * Add the rule by option. You can pass an option args and the method will * automatically add the css in the system. * * @param array $option * @param mixed $value * @return bool * @since 1.0.0 */ public function add_by_option( $option, $value ) { if ( ! isset( $option['style'] ) ) { return; } // used to store the properties of the rules $args = array(); if( $option['id'] == 'header-height' && $value != $option['std'] ) { $this->add( $option['style']['selectors'], array( 'min-height' => "{$value}px" ) ); } elseif ( $option['type'] == 'colorpicker' ) { $properties = explode( ',', $option['style']['properties'] ); if ( isset( $option['opacity'] ) && $value[0] == '#' ) { $value = yit_get_model('colors')->hex2rgb( $value ); $value = "rgba( $value[0], $value[1], $value[2], $option[opacity] )"; } foreach( $properties as $property ) { $args[ $property ] = $value; } $this->add( $option['style']['selectors'], $args ); } elseif ( $option['type'] == 'bgpreview') { $this->add( $option['style']['selectors'], array( 'background' => "{$value['color']} url('{$value['image']}')" ) ); } elseif ( $option['type'] == 'typography' ) { if ( isset( $value['size'] ) && isset( $value['unit'] ) ) { $args['font-size'] = $value['size'] . $value['unit']; } if ( isset( $value['family'] ) ) { if( strpos( $value['family'], ',' ) ) { $args['font-family'] = stripslashes( preg_replace( '/:[0-9a-z]+/', '', $value['family'] ) ); } else { $args['font-family'] = "'" . stripslashes( preg_replace( '/:[0-9a-z]+/', '', $value['family'] ) ) . "', sans-serif"; } } if ( isset( $value['color'] ) ) { $args['color'] = $value['color']; } if ( isset( $option['opacity'] ) && $value['color'][0] == '#' ) { $value['color'] = yit_get_model('colors')->hex2rgb( $value['color'] ); $value['color'] = "rgba( $value[color][0], $value[color][1], $value[color][2], $option[opacity] )"; } if ( isset( $value['style'] ) ) { switch ( $value['style'] ) { case 'bold' : $args['font-style'] = 'normal'; $args['font-weight'] = '700'; break; case 'extra-bold' : $args['font-style'] = 'normal'; $args['font-weight'] = '800'; break; case 'italic' : $args['font-style'] = 'italic'; $args['font-weight'] = 'normal'; break; case 'bold-italic' : $args['font-style'] = 'italic'; $args['font-weight'] = '700'; break; case 'regular' : $args['font-style'] = 'normal'; $args['font-weight'] = '400'; break; } } $this->add( $option['style']['selectors'], $args ); } elseif ( $option['type'] == 'upload' && $value ) { $this->add( $option['style']['selectors'], array( $option['style']['properties'] => "url('$value')" ) ); } elseif ( $option['type'] == 'number' ) { $this->add( $option['style']['selectors'], array( $option['style']['properties'] => "{$value}px" ) ); } elseif ( $option['type'] == 'select' ) { $this->add( $option['style']['selectors'], array( $option['style']['properties'] => "$value" ) ); } } /** * Remove a rule css * * @param string $rule * @param array $args * @return bool * @since 1.0.0 */ public function remove( $rule, $args = array() ) { if ( ! isset( $this->_rules[ $rule ] ) ) { return; } if ( ! empty( $args ) ) { foreach ( $args as $arg ) { if ( ! isset( $this->_rules[ $rule ][ $arg ] ) ) { continue; } unset( $this->_rules[ $rule ][ $arg ] ); } return; } unset( $this->_rules[ $rule ] ); return; } /** * Add the stylesheet into the class * * @param int $priority * @param string $handle * @param string|boolean $src * @param array $deps * @param string|boolean $ver * @param string $media * @param bool $exclude * * @return void * @since 1.0.0 * */ public function add_stylesheet( $priority = 0, $handle, $src = false, $deps = array(), $ver = false, $media = 'all', $exclude = false ) { $this->_stylesheets[] = array( 'type' => ( $src && strpos($src, get_template_directory_uri()) !== false ) ? 'yit' : 'external', 'priority' => $priority, 'handle' => $handle, 'src' => $src, 'deps' => $deps, 'ver' => $ver, 'media' => $media, 'exclude' => $exclude ); } /** * Enqueue stylesheets with wp_enqueue_style * * @return void * @since 1.0.0 */ public function enqueue() { usort( $this->_stylesheets, array( $this, 'sortByPriority' ) ); $excludedStylesheets = array(); foreach( $this->_stylesheets as $s ) { extract($s); if( $type == 'external' ) { wp_enqueue_style( $handle, $src, $deps, $ver, $media ); } elseif( $type == 'yit' ) { if( !$exclude && ($media == 'all' || $media == 'screen') ) { //wp_enqueue_style( $handle, $src, $deps, $ver, $media ); $filename = str_replace( get_template_directory_uri(), get_template_directory(), $src); $style = ""; if( file_exists( $filename ) ) { $style = file_get_contents($filename); } $this->_style .= "/* {$handle} - {$src} */\n" . $this->replacePath($src, $style) . "\n\n"; } elseif( !$exclude ) { wp_enqueue_style( $handle, $src, $deps, $ver, $media ); } else { $excludedStylesheets[] = $s; } } } //save the css in the file using cache $cache = yit_get_model('cache'); global $wpdb; $index = $wpdb->blogid != 0 ? '-' . $wpdb->blogid : ''; $this->_styleFilename = str_replace( '.css', $index . '.css', $this->_styleFilename ); if( YIT_DEBUG || $cache->is_expired( $this->_styleFilename) ) { $cache->save( $this->_styleFilename, $this->_style ); } wp_enqueue_style( "styles-minified", yit_get_model('cache')->locate_url( $this->_styleFilename ) ); //include the excluded stylesheets above foreach( $excludedStylesheets as $s ) { extract($s); wp_enqueue_style( $handle, $src, $deps, $ver, $media ); } } /** * Sort stylesheets by priority * * @param int $a * @param int $b * * @return bool * @since 1.0.0 */ protected function sortByPriority($a, $b) { return $a['priority'] - $b['priority']; } /** * Compress stylesheet removing comments, tabs, spaces, newlines, etc. * * @param string $buffer * * @return string * @since 1.0.0 */ function compress($buffer) { /* remove comments */ $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer); /* remove tabs, spaces, newlines, etc. */ $buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer); return $buffer; } /** * Fix image paths in css. * * @param string $fileContent Css string * @param string $file File incl path to calculate relative paths from. * @return string */ function replacePath( $file, $fileContent ) { if ( preg_match_all( "/url\(\s*[\'|\"]?([A-Za-z0-9_\-\/\.\\%?&#]+)[\'|\"]?\s*\)/ix", $fileContent, $urlMatches ) ) { $urlMatches = array_unique( $urlMatches[1] ); $cssPathArray = explode( '/', $file ); // Pop the css file name array_pop( $cssPathArray ); $cssPathCount = count( $cssPathArray ); foreach ( $urlMatches as $match ) { $match = str_replace( '\\', '/', $match ); $relativeCount = substr_count( $match, '../' ); // Replace path if it is realtive if ( $match[0] !== '/' and strpos( $match, 'http:' ) === false ) { $cssPathSlice = $relativeCount === 0 ? $cssPathArray : array_slice( $cssPathArray , 0, $cssPathCount - $relativeCount ); $newMatchPath = ""; //self::getWwwDir(); if ( !empty( $cssPathSlice ) ) { $newMatchPath .= implode( '/', $cssPathSlice ) . '/'; } $newMatchPath .= str_replace( '../', '', $match ); $newMatchPath_parsed = parse_url( $newMatchPath ); $newMatchPath = str_replace( "$newMatchPath_parsed[scheme]://$newMatchPath_parsed[host]", '', $newMatchPath ); $fileContent = str_replace( $match, $newMatchPath, $fileContent ); } } } return $this->compress($fileContent); } } if ( ! function_exists( 'yit_save_css' ) ) { /** * Save the file with all css * * @return bool * @since 1.0.0 */ function yit_save_css() { yit_get_model('css')->save_css(); } } if ( ! function_exists( 'yit_add_css' ) ) { /** * Add the rule css * * @return null * @since 1.0.0 */ function yit_add_css( $rule, $args = array() ) { yit_get_model('css')->add( $rule, $args ); } } if ( ! function_exists( 'yit_add_css_by_option' ) ) { /** * Add the rule css * * @return null * @since 1.0.0 */ function yit_add_css_by_option( $option, $value ) { yit_get_model('css')->add_by_option( $option, $value ); } } if( ! function_exists( 'yit_enqueue_style' ) ) { /** * A safe way to add/enqueue a CSS style file to the wordpress * generated page. * * @param int $priority * @param string $handle * @param string|boolean $src * @param array $deps * @param string|boolean $ver * @param string $media * * @return void * @since 1.0.0 */ function yit_enqueue_style( $priority = 0, $handle, $src = false, $deps = array(), $ver = false, $media = 'all', $exclude = false ) { yit_get_model('css')->add_stylesheet( $priority, $handle, $src, $deps, $ver, $media, $exclude ); } }
google-code/aha-mua-com
wp-content/themes/AHAMUA-SHOP/core/yit/Css.php
PHP
gpl-2.0
15,988
/* * Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/> * * 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 <http://www.gnu.org/licenses/>. */ /* Script Data Start SDName: Boss palehoof SDAuthor: LordVanMartin SD%Complete: SDComment: SDCategory: Script Data End */ #include <algorithm> #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "utgarde_pinnacle.h" enum Spells { SPELL_ARCING_SMASH = 48260, SPELL_IMPALE = 48261, H_SPELL_IMPALE = 59268, SPELL_WITHERING_ROAR = 48256, H_SPELL_WITHERING_ROAR = 59267, SPELL_FREEZE = 16245 }; //Orb spells enum OrbSpells { SPELL_ORB_VISUAL = 48044, SPELL_ORB_CHANNEL = 48048 }; //not in db enum Yells { SAY_AGGRO = 0, SAY_SLAY = 1 //SAY_DEATH = 2 Missing in database }; enum Creatures { NPC_STASIS_CONTROLLER = 26688 }; struct Locations { float x, y, z; }; struct Locations moveLocs[]= { {261.6f, -449.3f, 109.5f}, {263.3f, -454.0f, 109.5f}, {291.5f, -450.4f, 109.5f}, {291.5f, -454.0f, 109.5f}, {310.0f, -453.4f, 109.5f}, {238.6f, -460.7f, 109.5f} }; enum Phase { PHASE_FRENZIED_WORGEN, PHASE_RAVENOUS_FURLBORG, PHASE_MASSIVE_JORMUNGAR, PHASE_FEROCIOUS_RHINO, PHASE_GORTOK_PALEHOOF, PHASE_NONE }; class boss_palehoof : public CreatureScript { public: boss_palehoof() : CreatureScript("boss_palehoof") { } CreatureAI* GetAI(Creature* creature) const OVERRIDE { return new boss_palehoofAI(creature); } struct boss_palehoofAI : public ScriptedAI { boss_palehoofAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); } uint32 uiArcingSmashTimer; uint32 uiImpaleTimer; uint32 uiWhiteringRoarTimer; uint32 uiWaitingTimer; Phase currentPhase; uint8 AddCount; Phase Sequence[4]; InstanceScript* instance; void Reset() OVERRIDE { /// There is a good reason to store them like this, we are going to shuffle the order. for (uint32 i = PHASE_FRENZIED_WORGEN; i < PHASE_GORTOK_PALEHOOF; ++i) Sequence[i] = Phase(i); /// This ensures a random order and only executes each phase once. std::random_shuffle(Sequence, Sequence + PHASE_GORTOK_PALEHOOF); uiArcingSmashTimer = 15000; uiImpaleTimer = 12000; uiWhiteringRoarTimer = 10000; me->GetMotionMaster()->MoveTargetedHome(); AddCount = 0; currentPhase = PHASE_NONE; if (instance) { instance->SetData(DATA_GORTOK_PALEHOOF_EVENT, NOT_STARTED); Creature* temp = Unit::GetCreature((*me), instance->GetData64(DATA_NPC_FRENZIED_WORGEN)); if (temp && !temp->IsAlive()) temp->Respawn(); temp = Unit::GetCreature((*me), instance->GetData64(DATA_NPC_FEROCIOUS_RHINO)); if (temp && !temp->IsAlive()) temp->Respawn(); temp = Unit::GetCreature((*me), instance->GetData64(DATA_NPC_MASSIVE_JORMUNGAR)); if (temp && !temp->IsAlive()) temp->Respawn(); temp = Unit::GetCreature((*me), instance->GetData64(DATA_NPC_RAVENOUS_FURBOLG)); if (temp && !temp->IsAlive()) temp->Respawn(); GameObject* go = instance->instance->GetGameObject(instance->GetData64(DATA_GORTOK_PALEHOOF_SPHERE)); if (go) { go->SetGoState(GO_STATE_READY); go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); } } } void EnterCombat(Unit* /*who*/) OVERRIDE { Talk(SAY_AGGRO); } void AttackStart(Unit* who) OVERRIDE { if (!who) return; if (me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE)) return; if (me->Attack(who, true)) { me->AddThreat(who, 0.0f); me->SetInCombatWith(who); who->SetInCombatWith(me); DoStartMovement(who); } } void UpdateAI(uint32 diff) OVERRIDE { if (currentPhase != PHASE_GORTOK_PALEHOOF) return; //Return since we have no target if (!UpdateVictim()) return; Creature* temp = Unit::GetCreature((*me), instance ? instance->GetData64(DATA_NPC_ORB) : 0); if (temp && temp->IsAlive()) temp->DisappearAndDie(); if (uiArcingSmashTimer <= diff) { DoCast(me, SPELL_ARCING_SMASH); uiArcingSmashTimer = urand(13000, 17000); } else uiArcingSmashTimer -= diff; if (uiImpaleTimer <= diff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) DoCast(target, SPELL_IMPALE); uiImpaleTimer = urand(8000, 12000); } else uiImpaleTimer -= diff; if (uiWhiteringRoarTimer <= diff) { DoCast(me, SPELL_WITHERING_ROAR); uiWhiteringRoarTimer = urand(8000, 12000); } else uiWhiteringRoarTimer -= diff; DoMeleeAttackIfReady(); } void JustDied(Unit* /*killer*/) OVERRIDE { //Talk(SAY_DEATH); if (instance) instance->SetData(DATA_GORTOK_PALEHOOF_EVENT, DONE); Creature* temp = Unit::GetCreature((*me), instance ? instance->GetData64(DATA_NPC_ORB) : 0); if (temp && temp->IsAlive()) temp->DisappearAndDie(); } void KilledUnit(Unit* /*victim*/) OVERRIDE { Talk(SAY_SLAY); } void NextPhase() { if (currentPhase == PHASE_NONE) { instance->SetData(DATA_GORTOK_PALEHOOF_EVENT, IN_PROGRESS); me->SummonCreature(NPC_STASIS_CONTROLLER, moveLocs[5].x, moveLocs[5].y, moveLocs[5].z, 0, TEMPSUMMON_CORPSE_DESPAWN); } Phase move = PHASE_NONE; if (AddCount >= DUNGEON_MODE(2, 4)) move = PHASE_GORTOK_PALEHOOF; else move = Sequence[AddCount++]; //send orb to summon spot Creature* pOrb = Unit::GetCreature((*me), instance ? instance->GetData64(DATA_NPC_ORB) : 0); if (pOrb && pOrb->IsAlive()) { if (currentPhase == PHASE_NONE) pOrb->CastSpell(me, SPELL_ORB_VISUAL, true); pOrb->GetMotionMaster()->MovePoint(move, moveLocs[move].x, moveLocs[move].y, moveLocs[move].z); } currentPhase = move; } void JustReachedHome() OVERRIDE { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE|UNIT_FLAG_NOT_SELECTABLE|UNIT_FLAG_NOT_ATTACKABLE_1|UNIT_FLAG_IMMUNE_TO_PC); me->SetStandState(UNIT_STAND_STATE_STAND); DoCast(me, SPELL_FREEZE); } }; }; //ravenous furbolg's spells enum RavenousSpells { SPELL_CHAIN_LIGHTING = 48140, H_SPELL_CHAIN_LIGHTING = 59273, SPELL_CRAZED = 48139, SPELL_TERRIFYING_ROAR = 48144 }; class npc_ravenous_furbolg : public CreatureScript { public: npc_ravenous_furbolg() : CreatureScript("npc_ravenous_furbolg") { } CreatureAI* GetAI(Creature* creature) const OVERRIDE { return new npc_ravenous_furbolgAI(creature); } struct npc_ravenous_furbolgAI : public ScriptedAI { npc_ravenous_furbolgAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); } uint32 uiChainLightingTimer; uint32 uiCrazedTimer; uint32 uiTerrifyingRoarTimer; InstanceScript* instance; void Reset() OVERRIDE { uiChainLightingTimer = 5000; uiCrazedTimer = 10000; uiTerrifyingRoarTimer = 15000; me->GetMotionMaster()->MoveTargetedHome(); if (instance) if (instance->GetData(DATA_GORTOK_PALEHOOF_EVENT) == IN_PROGRESS) { Creature* pPalehoof = Unit::GetCreature((*me), instance ? instance->GetData64(DATA_GORTOK_PALEHOOF) : 0); if (pPalehoof && pPalehoof->IsAlive()) CAST_AI(boss_palehoof::boss_palehoofAI, pPalehoof->AI())->Reset(); } } void UpdateAI(uint32 diff) OVERRIDE { //Return since we have no target if (!UpdateVictim()) return; if (uiChainLightingTimer <= diff) { DoCastVictim(SPELL_CHAIN_LIGHTING); uiChainLightingTimer = 5000 + rand() % 5000; } else uiChainLightingTimer -= diff; if (uiCrazedTimer <= diff) { DoCast(me, SPELL_CRAZED); uiCrazedTimer = 8000 + rand() % 4000; } else uiCrazedTimer -= diff; if (uiTerrifyingRoarTimer <= diff) { DoCast(me, SPELL_TERRIFYING_ROAR); uiTerrifyingRoarTimer = 10000 + rand() % 10000; } else uiTerrifyingRoarTimer -= diff; DoMeleeAttackIfReady(); } void AttackStart(Unit* who) OVERRIDE { if (!who) return; if (me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE)) return; if (me->Attack(who, true)) { me->AddThreat(who, 0.0f); me->SetInCombatWith(who); who->SetInCombatWith(me); DoStartMovement(who); } } void JustDied(Unit* /*killer*/) OVERRIDE { if (instance) { Creature* pPalehoof = Unit::GetCreature((*me), instance ? instance->GetData64(DATA_GORTOK_PALEHOOF) : 0); if (pPalehoof) CAST_AI(boss_palehoof::boss_palehoofAI, pPalehoof->AI())->NextPhase(); } } void JustReachedHome() OVERRIDE { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_IMMUNE_TO_PC); me->SetStandState(UNIT_STAND_STATE_STAND); DoCast(me, SPELL_FREEZE); } }; }; //frenzied worgen's spells enum FrenziedSpells { SPELL_MORTAL_WOUND = 48137, H_SPELL_MORTAL_WOUND = 59265, SPELL_ENRAGE_1 = 48138, SPELL_ENRAGE_2 = 48142 }; class npc_frenzied_worgen : public CreatureScript { public: npc_frenzied_worgen() : CreatureScript("npc_frenzied_worgen") { } CreatureAI* GetAI(Creature* creature) const OVERRIDE { return new npc_frenzied_worgenAI(creature); } struct npc_frenzied_worgenAI : public ScriptedAI { npc_frenzied_worgenAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); } uint32 uiMortalWoundTimer; uint32 uiEnrage1Timer; uint32 uiEnrage2Timer; InstanceScript* instance; void Reset() OVERRIDE { uiMortalWoundTimer = 5000; uiEnrage1Timer = 15000; uiEnrage2Timer = 10000; me->GetMotionMaster()->MoveTargetedHome(); if (instance) if (instance->GetData(DATA_GORTOK_PALEHOOF_EVENT) == IN_PROGRESS) { Creature* pPalehoof = Unit::GetCreature((*me), instance ? instance->GetData64(DATA_GORTOK_PALEHOOF) : 0); if (pPalehoof && pPalehoof->IsAlive()) CAST_AI(boss_palehoof::boss_palehoofAI, pPalehoof->AI())->Reset(); } } void UpdateAI(uint32 diff) OVERRIDE { //Return since we have no target if (!UpdateVictim()) return; if (uiMortalWoundTimer <= diff) { DoCastVictim(SPELL_MORTAL_WOUND); uiMortalWoundTimer = 3000 + rand() % 4000; } else uiMortalWoundTimer -= diff; if (uiEnrage1Timer <= diff) { DoCast(me, SPELL_ENRAGE_1); uiEnrage1Timer = 15000; } else uiEnrage1Timer -= diff; if (uiEnrage2Timer <= diff) { DoCast(me, SPELL_ENRAGE_2); uiEnrage2Timer = 10000; } else uiEnrage2Timer -= diff; DoMeleeAttackIfReady(); } void AttackStart(Unit* who) OVERRIDE { if (!who) return; if (me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE)) return; if (me->Attack(who, true)) { me->AddThreat(who, 0.0f); me->SetInCombatWith(who); who->SetInCombatWith(me); DoStartMovement(who); } if (instance) instance->SetData(DATA_GORTOK_PALEHOOF_EVENT, IN_PROGRESS); } void JustDied(Unit* /*killer*/) OVERRIDE { if (instance) { Creature* pPalehoof = Unit::GetCreature((*me), instance->GetData64(DATA_GORTOK_PALEHOOF)); if (pPalehoof) CAST_AI(boss_palehoof::boss_palehoofAI, pPalehoof->AI())->NextPhase(); } } void JustReachedHome() OVERRIDE { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_IMMUNE_TO_PC); me->SetStandState(UNIT_STAND_STATE_STAND); DoCast(me, SPELL_FREEZE); } }; }; //ferocious rhino's spells enum FerociousSpells { SPELL_GORE = 48130, H_SPELL_GORE = 59264, SPELL_GRIEVOUS_WOUND = 48105, H_SPELL_GRIEVOUS_WOUND = 59263, SPELL_STOMP = 48131 }; class npc_ferocious_rhino : public CreatureScript { public: npc_ferocious_rhino() : CreatureScript("npc_ferocious_rhino") { } CreatureAI* GetAI(Creature* creature) const OVERRIDE { return new npc_ferocious_rhinoAI(creature); } struct npc_ferocious_rhinoAI : public ScriptedAI { npc_ferocious_rhinoAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); } uint32 uiStompTimer; uint32 uiGoreTimer; uint32 uiGrievousWoundTimer; InstanceScript* instance; void Reset() OVERRIDE { uiStompTimer = 10000; uiGoreTimer = 15000; uiGrievousWoundTimer = 20000; me->GetMotionMaster()->MoveTargetedHome(); if (instance) if (instance->GetData(DATA_GORTOK_PALEHOOF_EVENT) == IN_PROGRESS) { Creature* pPalehoof = Unit::GetCreature((*me), instance ? instance->GetData64(DATA_GORTOK_PALEHOOF) : 0); if (pPalehoof && pPalehoof->IsAlive()) CAST_AI(boss_palehoof::boss_palehoofAI, pPalehoof->AI())->Reset(); } } void UpdateAI(uint32 diff) OVERRIDE { //Return since we have no target if (!UpdateVictim()) return; if (uiStompTimer <= diff) { DoCastVictim(SPELL_STOMP); uiStompTimer = 8000 + rand() % 4000; } else uiStompTimer -= diff; if (uiGoreTimer <= diff) { DoCastVictim(SPELL_GORE); uiGoreTimer = 13000 + rand() % 4000; } else uiGoreTimer -= diff; if (uiGrievousWoundTimer <= diff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) DoCast(target, SPELL_GRIEVOUS_WOUND); uiGrievousWoundTimer = 18000 + rand() % 4000; } else uiGrievousWoundTimer -= diff; DoMeleeAttackIfReady(); } void AttackStart(Unit* who) OVERRIDE { if (!who) return; if (me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE)) return; if (me->Attack(who, true)) { me->AddThreat(who, 0.0f); me->SetInCombatWith(who); who->SetInCombatWith(me); DoStartMovement(who); } } void JustDied(Unit* /*killer*/) OVERRIDE { if (instance) { Creature* pPalehoof = Unit::GetCreature((*me), instance ? instance->GetData64(DATA_GORTOK_PALEHOOF) : 0); if (pPalehoof) CAST_AI(boss_palehoof::boss_palehoofAI, pPalehoof->AI())->NextPhase(); } } void JustReachedHome() OVERRIDE { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_IMMUNE_TO_PC); me->SetStandState(UNIT_STAND_STATE_STAND); DoCast(me, SPELL_FREEZE); } }; }; //massive jormungar's spells enum MassiveSpells { SPELL_ACID_SPIT = 48132, SPELL_ACID_SPLATTER = 48136, H_SPELL_ACID_SPLATTER = 59272, SPELL_POISON_BREATH = 48133, H_SPELL_POISON_BREATH = 59271 }; enum MassiveAdds { CREATURE_JORMUNGAR_WORM = 27228 }; class npc_massive_jormungar : public CreatureScript { public: npc_massive_jormungar() : CreatureScript("npc_massive_jormungar") { } CreatureAI* GetAI(Creature* creature) const OVERRIDE { return new npc_massive_jormungarAI(creature); } struct npc_massive_jormungarAI : public ScriptedAI { npc_massive_jormungarAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); } uint32 uiAcidSpitTimer; uint32 uiAcidSplatterTimer; uint32 uiPoisonBreathTimer; InstanceScript* instance; void Reset() OVERRIDE { uiAcidSpitTimer = 3000; uiAcidSplatterTimer = 12000; uiPoisonBreathTimer = 10000; me->GetMotionMaster()->MoveTargetedHome(); if (instance) if (instance->GetData(DATA_GORTOK_PALEHOOF_EVENT) == IN_PROGRESS) { Creature* pPalehoof = Unit::GetCreature((*me), instance ? instance->GetData64(DATA_GORTOK_PALEHOOF) : 0); if (pPalehoof && pPalehoof->IsAlive()) CAST_AI(boss_palehoof::boss_palehoofAI, pPalehoof->AI())->Reset(); } } void UpdateAI(uint32 diff) OVERRIDE { //Return since we have no target if (!UpdateVictim()) return; if (uiAcidSpitTimer <= diff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) DoCast(target, SPELL_ACID_SPIT); uiAcidSpitTimer = 2000 + rand() % 2000; } else uiAcidSpitTimer -= diff; if (uiAcidSplatterTimer <= diff) { DoCast(me, SPELL_POISON_BREATH); uiAcidSplatterTimer = 10000 + rand() % 4000; } else uiAcidSplatterTimer -= diff; if (uiPoisonBreathTimer <= diff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) DoCast(target, SPELL_POISON_BREATH); uiPoisonBreathTimer = 8000 + rand() % 4000; } else uiPoisonBreathTimer -= diff; DoMeleeAttackIfReady(); } void AttackStart(Unit* who) OVERRIDE { if (!who) return; if (me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE)) return; if (me->Attack(who, true)) { me->AddThreat(who, 0.0f); me->SetInCombatWith(who); who->SetInCombatWith(me); DoStartMovement(who); } } void JustDied(Unit* /*killer*/) OVERRIDE { if (instance) { Creature* pPalehoof = Unit::GetCreature((*me), instance ? instance->GetData64(DATA_GORTOK_PALEHOOF) : 0); if (pPalehoof) CAST_AI(boss_palehoof::boss_palehoofAI, pPalehoof->AI())->NextPhase(); } } void JustReachedHome() OVERRIDE { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_IMMUNE_TO_PC); me->SetStandState(UNIT_STAND_STATE_STAND); DoCast(me, SPELL_FREEZE); } }; }; class npc_palehoof_orb : public CreatureScript { public: npc_palehoof_orb() : CreatureScript("npc_palehoof_orb") { } CreatureAI* GetAI(Creature* creature) const OVERRIDE { return new npc_palehoof_orbAI(creature); } struct npc_palehoof_orbAI : public ScriptedAI { npc_palehoof_orbAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); } InstanceScript* instance; uint32 SummonTimer; Phase currentPhase; void Reset() OVERRIDE { currentPhase = PHASE_NONE; SummonTimer = 5000; //! HACK: Creature's can't have MOVEMENTFLAG_FLYING me->AddUnitMovementFlag(MOVEMENTFLAG_FLYING); me->RemoveAurasDueToSpell(SPELL_ORB_VISUAL); me->SetSpeed(MOVE_FLIGHT, 0.5f); } void UpdateAI(uint32 diff) OVERRIDE { if (currentPhase == PHASE_NONE) return; if (SummonTimer <= diff) { if (currentPhase<5&&currentPhase >= 0) { Creature* pNext = NULL; switch (currentPhase) { case PHASE_FRENZIED_WORGEN: pNext = Unit::GetCreature((*me), instance ? instance->GetData64(DATA_NPC_FRENZIED_WORGEN) : 0); break; case PHASE_RAVENOUS_FURLBORG: pNext = Unit::GetCreature((*me), instance ? instance->GetData64(DATA_NPC_RAVENOUS_FURBOLG) : 0); break; case PHASE_MASSIVE_JORMUNGAR: pNext = Unit::GetCreature((*me), instance ? instance->GetData64(DATA_NPC_MASSIVE_JORMUNGAR) : 0); break; case PHASE_FEROCIOUS_RHINO: pNext = Unit::GetCreature((*me), instance ? instance->GetData64(DATA_NPC_FEROCIOUS_RHINO) : 0); break; case PHASE_GORTOK_PALEHOOF: pNext = Unit::GetCreature((*me), instance ? instance->GetData64(DATA_GORTOK_PALEHOOF) : 0); break; default: break; } if (pNext) { pNext->RemoveAurasDueToSpell(SPELL_FREEZE); pNext->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_IMMUNE_TO_PC); pNext->SetStandState(UNIT_STAND_STATE_STAND); pNext->SetInCombatWithZone(); pNext->Attack(pNext->SelectNearestTarget(100), true); } currentPhase = PHASE_NONE; } } else SummonTimer -= diff; } void MovementInform(uint32 type, uint32 id) OVERRIDE { if (type != POINT_MOTION_TYPE) return; if (id > 4) return; Creature* pNext = NULL; switch (id) { case PHASE_FRENZIED_WORGEN: pNext = Unit::GetCreature((*me), instance ? instance->GetData64(DATA_NPC_FRENZIED_WORGEN) : 0); break; case PHASE_RAVENOUS_FURLBORG: pNext = Unit::GetCreature((*me), instance ? instance->GetData64(DATA_NPC_RAVENOUS_FURBOLG) : 0); break; case PHASE_MASSIVE_JORMUNGAR: pNext = Unit::GetCreature((*me), instance ? instance->GetData64(DATA_NPC_MASSIVE_JORMUNGAR) : 0); break; case PHASE_FEROCIOUS_RHINO: pNext = Unit::GetCreature((*me), instance ? instance->GetData64(DATA_NPC_FEROCIOUS_RHINO) : 0); break; case PHASE_GORTOK_PALEHOOF: pNext = Unit::GetCreature((*me), instance ? instance->GetData64(DATA_GORTOK_PALEHOOF) : 0); break; default: break; } if (pNext) DoCast(pNext, SPELL_ORB_CHANNEL, false); currentPhase = (Phase)id; SummonTimer = 5000; } }; }; class go_palehoof_sphere : public GameObjectScript { public: go_palehoof_sphere() : GameObjectScript("go_palehoof_sphere") { } bool OnGossipHello(Player* /*player*/, GameObject* go) OVERRIDE { InstanceScript* instance = go->GetInstanceScript(); Creature* pPalehoof = Unit::GetCreature(*go, instance ? instance->GetData64(DATA_GORTOK_PALEHOOF) : 0); if (pPalehoof && pPalehoof->IsAlive()) { go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); go->SetGoState(GO_STATE_ACTIVE); CAST_AI(boss_palehoof::boss_palehoofAI, pPalehoof->AI())->NextPhase(); } return true; } }; void AddSC_boss_palehoof() { new boss_palehoof(); new npc_ravenous_furbolg(); new npc_frenzied_worgen(); new npc_ferocious_rhino(); new npc_massive_jormungar(); new npc_palehoof_orb(); new go_palehoof_sphere(); }
idskiv/wotlk
src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_palehoof.cpp
C++
gpl-2.0
27,437
// Populate the database function populateDB(tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS profiles (id INTEGER PRIMARY KEY, name, description, direction, latitude, longitude, altitude, accuracy, altitudeAccuracy, photo)'); tx.executeSql('CREATE TABLE IF NOT EXISTS beds (id INTEGER PRIMARY KEY, profileid INTEGER, position INTEGER, name, thickness, facies, notes, boundary, paleocurrent, lit1group, lit1type, lit1percentage, lit2group, lit2type, lit2percentage, lit3group, lit3type, lit3percentage, sizeclasticbase, phiclasticbase, sizeclastictop, phiclastictop, sizecarbobase, phicarbobase, sizecarbotop, phicarbotop, bioturbationtype, bioturbationintensity, structures, bedsymbols, audio)'); tx.executeSql('CREATE TABLE IF NOT EXISTS bedphotos (id INTEGER PRIMARY KEY, profileid INTEGER, bedid INTEGER, photo, description)'); tx.executeSql('CREATE TABLE IF NOT EXISTS typelithology (id INTEGER PRIMARY KEY, name UNIQUE ON CONFLICT IGNORE)'); tx.executeSql('CREATE TABLE IF NOT EXISTS indexlithology (id INTEGER PRIMARY KEY, typeid INTEGER, name UNIQUE ON CONFLICT IGNORE)'); tx.executeSql('CREATE TABLE IF NOT EXISTS typestructure (id INTEGER PRIMARY KEY, name UNIQUE ON CONFLICT IGNORE)'); tx.executeSql('CREATE TABLE IF NOT EXISTS indexstructure (id INTEGER PRIMARY KEY, typeid INTEGER, name UNIQUE ON CONFLICT IGNORE)'); tx.executeSql('CREATE TABLE IF NOT EXISTS grainclastic (name, phi)'); tx.executeSql('CREATE TABLE IF NOT EXISTS graincarbonate (name, phi)'); tx.executeSql('CREATE TABLE IF NOT EXISTS bioturbation (name)'); tx.executeSql('CREATE TABLE IF NOT EXISTS boundaries (name)'); tx.executeSql('SELECT * FROM typelithology',[], function (tx,result) { if (result.rows.length == 0) { tx.executeSql('INSERT INTO typelithology (id, name) VALUES (1, "Basic")'); tx.executeSql('INSERT INTO typelithology (id, name) VALUES (2, "Carbonates")'); tx.executeSql('INSERT INTO typelithology (id, name) VALUES (3, "Other")'); } }, errorCB); tx.executeSql('SELECT * FROM indexlithology',[], function (tx,result) { if (result.rows.length == 0) { tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (1, 1, "Mudstone")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (2, 1, "Claystone")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (3, 1, "Shale")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (4, 1, "Siltstone")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (5, 1, "Sandstone")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (6, 1, "Conglomerate")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (7, 1, "Coal")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (8, 1, "Limestone")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (9, 1, "Chert")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (10, 1, "Volcaniclastic")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (11, 2, "Lime mudstone")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (12, 2, "Wackestone")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (13, 2, "Packstone")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (14, 2, "Grainstone")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (15, 2, "Halite")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (16, 2, "Gypsum/Anhydrite")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (17, 2, "Dolomite")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (18, 3, "Breccia")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (19, 3, "Matrix-supported conglomerate")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (20, 3, "Clast-supported conglomerate")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (21, 3, "Lava")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (22, 3, "Fine ash")'); tx.executeSql('INSERT INTO indexlithology (id, typeid, name) VALUES (23, 3, "Coarse ash")'); } }, errorCB); tx.executeSql('SELECT * FROM typestructure',[], function (tx,result) { if (result.rows.length == 0) { tx.executeSql('INSERT INTO typestructure (id, name) VALUES (1, "Sedimentary structures")'); tx.executeSql('INSERT INTO typestructure (id, name) VALUES (2, "Fossils")'); tx.executeSql('INSERT INTO typestructure (id, name) VALUES (3, "Trace fossils")'); tx.executeSql('INSERT INTO typestructure (id, name) VALUES (4, "Other")'); } }, errorCB); tx.executeSql('SELECT * FROM indexstructure',[], function (tx,result) { if (result.rows.length == 0) { tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (1, 1, "Current ripple cross-lamination")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (2, 1, "Wave ripple cross-lamination")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (3, 1, "Planar cross bedding")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (4, 1, "Trough cross bedding")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (5, 1, "Horizontal planar lamination")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (6, 1, "Hummocky cross stratification")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (7, 1, "Swaley cross stratification")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (8, 1, "Mudcracks")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (9, 1, "Synaeresis cracks")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (10, 1, "Convolute lamination")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (11, 1, "Load casts")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (12, 1, "Water structures")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (13, 1, "Herring-bone cross bedding")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (14, 2, "Shells")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (15, 2, "Bivalves")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (16, 2, "Gastropods")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (17, 2, "Cephalopods")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (18, 2, "Brachiopods")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (19, 2, "Echinoids")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (20, 2, "Crinoids")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (21, 2, "Solitary corals")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (22, 2, "Colonial corals")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (23, 2, "Foraminifera")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (24, 2, "Algae")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (25, 2, "Bryozoa")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (26, 2, "Stromatolites")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (27, 2, "Vertebrates")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (28, 2, "Plant material")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (29, 2, "Roots")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (30, 2, "Logs")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (31, 2, "Tree stumps")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (32, 2, "Ostracods")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (33, 2, "Radiolaria")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (34, 2, "Sponges")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (35, 3, "Minor bioturbation")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (36, 3, "Moderate bioturbation")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (37, 3, "Intense bioturbation")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (38, 3, "Tracks")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (39, 3, "Trails")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (40, 3, "Vertical burrows")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (41, 3, "Horizontal burrows")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (42, 4, "Nodules and concretions")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (43, 4, "Intraclasts")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (44, 4, "Mudclasts")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (45, 4, "Flute marks")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (46, 4, "Groove marks")'); tx.executeSql('INSERT INTO indexstructure (id, typeid, name) VALUES (47, 4, "Scours")'); } }, errorCB); tx.executeSql('SELECT * FROM grainclastic',[], function (tx,result) { if (result.rows.length == 0) { tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("clay", "10.0")'); tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("clay/silt", "8.0")'); tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("silt", "6.0")'); tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("silt/vf", "4.0")'); tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("vf", "3.5")'); tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("vf/f", "3.0")'); tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("f", "2.5")'); tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("f/m", "2.0")'); tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("m", "1.5")'); tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("m/c", "1.0")'); tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("c", "0.5")'); tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("c/vc", "0.0")'); tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("vc", "-0.5")'); tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("vc/granule", "-1.0")'); tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("granule", "-1.5")'); tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("granule/pebble", "-2.3")'); tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("pebble", "-3.0")'); tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("pebble/cobble", "-4.5")'); tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("cobble", "-6.0")'); tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("cobble/boulder", "-8.0")'); tx.executeSql('INSERT INTO grainclastic (name, phi) VALUES ("boulder", "-10.0")'); } }, errorCB); tx.executeSql('SELECT * FROM graincarbonate',[], function (tx,result) { if (result.rows.length == 0) { tx.executeSql('INSERT INTO graincarbonate (name, phi) VALUES ("mudstone", "6.0")'); tx.executeSql('INSERT INTO graincarbonate (name, phi) VALUES ("wackestone", "3.5")'); tx.executeSql('INSERT INTO graincarbonate (name, phi) VALUES ("packstone", "1.5")'); tx.executeSql('INSERT INTO graincarbonate (name, phi) VALUES ("grainstone", "-0.5")'); tx.executeSql('INSERT INTO graincarbonate (name, phi) VALUES ("rudstone fine", "-1.5")'); tx.executeSql('INSERT INTO graincarbonate (name, phi) VALUES ("rudstone medium", "-3.0")'); tx.executeSql('INSERT INTO graincarbonate (name, phi) VALUES ("rudstone", "-6.0")'); } }, errorCB); tx.executeSql('SELECT * FROM bioturbation',[], function (tx,result) { if (result.rows.length == 0) { tx.executeSql('INSERT INTO bioturbation (name) VALUES ("Minor bioturbation")'); tx.executeSql('INSERT INTO bioturbation (name) VALUES ("Moderate bioturbation")'); tx.executeSql('INSERT INTO bioturbation (name) VALUES ("Intense bioturbation")'); tx.executeSql('INSERT INTO bioturbation (name) VALUES ("Tracks")'); tx.executeSql('INSERT INTO bioturbation (name) VALUES ("Trails")'); tx.executeSql('INSERT INTO bioturbation (name) VALUES ("Vertical burrows")'); tx.executeSql('INSERT INTO bioturbation (name) VALUES ("Horizontal burrows")'); } }, errorCB); tx.executeSql('SELECT * FROM boundaries',[], function (tx,result) { if (result.rows.length == 0) { tx.executeSql('INSERT INTO boundaries (name) VALUES ("Sharp")'); tx.executeSql('INSERT INTO boundaries (name) VALUES ("Erosion")'); tx.executeSql('INSERT INTO boundaries (name) VALUES ("Gradational")'); } }, errorCB); } // Transaction error callback function errorCB(tx, err) { alert("Error processing SQL: "+err); }
pwlw/SedMob
js/database.js
JavaScript
gpl-2.0
13,336
<?php /** * The base configurations of the WordPress. * * This file has the following configurations: MySQL settings, Table Prefix, * Secret Keys, WordPress Language, and ABSPATH. You can find more information * by visiting {@link http://codex.wordpress.org/Editing_wp-config.php Editing * wp-config.php} Codex page. You can get the MySQL settings from your web host. * * This file is used by the wp-config.php creation script during the * installation. You don't have to use the web site, you can just copy this file * to "wp-config.php" and fill in the values. * * @package WordPress */ // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define('DB_NAME', 'bold_wordpress'); /** MySQL database username */ define('DB_USER', 'bold_wordpress'); /** MySQL database password */ define('DB_PASSWORD', 'pa55word'); /** MySQL hostname */ define('DB_HOST', 'localhost'); /** Database Charset to use in creating database tables. */ define('DB_CHARSET', 'utf8'); /** The Database Collate type. Don't change this if in doubt. */ define('DB_COLLATE', ''); /**#@+ * Authentication Unique Keys and Salts. * * Change these to different unique phrases! * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service} * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again. * * @since 2.6.0 */ define('AUTH_KEY', 'pd0:.NP|AB&x>4|vS]>U:78A+yv*Mn0B6&%.fok:*1A43W,oQ@z+~K1T I~uw-O7'); define('SECURE_AUTH_KEY', 'pFCkoUaUR|dww,n]gNS8:=59OsIN5<c4hYSEnq/)+#&s,p~HMF.TEK!:$ w>I(9<'); define('LOGGED_IN_KEY', '!;:G--eWJ]#+wsIBJgrXZLb^u~P!+wn9=j6,q1djU_41wt7Py10MgjtI!5&qQi y'); define('NONCE_KEY', '+$*sdF3FC$:|57_ea TjY+&f/`BhQ@.0MoO-Tr`[=S3 Ot-ycWVRPhQWHGiYe!dL'); define('AUTH_SALT', 'xQiK2:#YK($KV,@9O/yC<A+cvB,JC_[)7N_t`S13P`$H0IG`$VjpdS/q;Jf#,b%M'); define('SECURE_AUTH_SALT', ';`Sb${ya]Yd}w=Dn8WS!1h$JC!XDW<oF!W`=tD4=mYx$)Nl(!d_=x;CXO2S^|R=U'); define('LOGGED_IN_SALT', '[l`lR#eskqZm|7*ZtpDWO^EP6!/Y67YD13{%$lLO7)* 5|+hlbI[+(3odJ=lT[Mb'); define('NONCE_SALT', ']46}(L=SPaqF8-Zq@Jk0wU[D2Wm]J2`)_fJ$5P#?6p8wqZKDBg:1dKu||2L~0qUx'); /**#@-*/ /** * WordPress Database Table prefix. * * You can have multiple installations in one database if you give each a unique * prefix. Only numbers, letters, and underscores please! */ $table_prefix = 'wp_'; /** * WordPress Localized Language, defaults to English. * * Change this to localize WordPress. A corresponding MO file for the chosen * language must be installed to wp-content/languages. For example, install * de_DE.mo to wp-content/languages and set WPLANG to 'de_DE' to enable German * language support. */ define('WPLANG', ''); /** * For developers: WordPress debugging mode. * * Change this to true to enable the display of notices during development. * It is strongly recommended that plugin and theme developers use WP_DEBUG * in their development environments. */ define('WP_DEBUG', false); /* That's all, stop editing! Happy blogging. */ /** Absolute path to the WordPress directory. */ if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); /** Sets up WordPress vars and included files. */ require_once(ABSPATH . 'wp-settings.php');
cdawsonhall/BOLD-production
wp-config.php
PHP
gpl-2.0
3,465
/* * kprobe - kprobe demo * * Written in 2012 by Prashant P Shah <pshah.mumbai@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/module.h> #include <linux/kprobes.h> static struct kprobe kp; static unsigned int counter = 0; static int Pre_handler(struct kprobe *p, struct pt_regs *regs) { printk(KERN_INFO "mykprobe: %s = %d\n", __FUNCTION__, counter++); return 0; } static void Post_handler(struct kprobe *p, struct pt_regs *regs, unsigned long flags) { printk(KERN_INFO "mykprobe: %s = %d\n", __FUNCTION__, counter++); } static int __init mykprobe_init(void) { printk(KERN_INFO "mykprobe: %s\n", __FUNCTION__); kp.pre_handler = Pre_handler; kp.post_handler = Post_handler; kp.addr = (kprobe_opcode_t *)0xffffffff81445ce0; /* from /proc/kallsyms */ register_kprobe(&kp); return 0; } static void __exit mykprobe_exit(void) { printk(KERN_INFO "mykprobe: %s\n", __FUNCTION__); unregister_kprobe(&kp); } module_init(mykprobe_init); module_exit(mykprobe_exit); MODULE_LICENSE("Dual MIT/GPL"); MODULE_AUTHOR("Me");
prashants/km
probes/kprobe.c
C
gpl-2.0
2,143
<?php require_once __DIR__.'/_config.php'; $jsonFile = DATA_DIR.'/blog.json'; $blog = new Blog(array( 'templateUrl' => 'http://'.$_SERVER['SERVER_NAME'] )); $data = json_decode(file_get_contents($jsonFile), true); $data['urls'] = $blog->getUrls(); echo $blog->render('blog', $data); ?>
JonathanMatthey/hudsongray-website2
wp-content/themes/grey/blog-static.php
PHP
gpl-2.0
294
/* * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.truffle.sl.nodes.expression; import java.math.*; import com.oracle.truffle.api.dsl.*; import com.oracle.truffle.api.nodes.*; import com.oracle.truffle.api.source.*; import com.oracle.truffle.sl.nodes.*; import com.oracle.truffle.sl.runtime.*; /** * The {@code ==} operator of SL is defined on all types. Therefore, we need a * {@link #equal(Object, Object) generic implementation} that can handle all possible types. But * since {@code ==} can only return {@code true} when the type of the left and right operand are the * same, the specializations already cover all possible cases that can return {@code true} and the * generic case is trivial. * <p> * Note that we do not need the analogous {@code =!} operator, because we can just * {@link SLLogicalNotNode negate} the {@code ==} operator. */ @NodeInfo(shortName = "==") public abstract class SLEqualNode extends SLBinaryNode { public SLEqualNode(SourceSection src) { super(src); } @Specialization protected boolean equal(long left, long right) { return left == right; } @Specialization protected boolean equal(BigInteger left, BigInteger right) { return left.equals(right); } @Specialization protected boolean equal(boolean left, boolean right) { return left == right; } @Specialization protected boolean equal(String left, String right) { return left.equals(right); } @Specialization protected boolean equal(SLFunction left, SLFunction right) { /* * Our function registry maintains one canonical SLFunction object per function name, so we * do not need equals(). */ return left == right; } @Specialization protected boolean equal(SLNull left, SLNull right) { /* There is only the singleton instance of SLNull, so we do not need equals(). */ return left == right; } /** * The {@link Generic} annotation informs the Truffle DSL that this method should be executed * when no {@link Specialization specialized method} matches. The operand types must be * {@link Object}. */ @Generic protected boolean equal(Object left, Object right) { /* * We covered all the cases that can return true in specializations. If we compare two * values with different types, no specialization matches and we end up here. */ assert !left.equals(right); return false; } }
dain/graal
graal/com.oracle.truffle.sl/src/com/oracle/truffle/sl/nodes/expression/SLEqualNode.java
Java
gpl-2.0
3,564
<?php /** ------------------------------------------------------------------------- briefcasefactory - Briefcase Factory 4.0.8 ------------------------------------------------------------------------- * @author thePHPfactory * @copyright Copyright (C) 2011 SKEPSIS Consult SRL. All Rights Reserved. * @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL * Websites: http://www.thePHPfactory.com * Technical Support: Forum - http://www.thePHPfactory.com/forum/ ------------------------------------------------------------------------- */ defined('_JEXEC') or die; defined('JPATH_BASE') or die; class JFormFieldBriefcaseStorageFolder extends JFormField { public $type = 'BriefcaseStorageFolder'; protected function getInput() { if (!$this->value) { $this->value = JPATH_SITE . '/media/com_briefcasefactory/'; } $html = array(); $html[] = '<input type="hidden" class="storageFolder" name="' . $this->name . '" id="' . $this->id . '" value="' . htmlspecialchars($this->value, ENT_COMPAT, 'UTF-8') . '" />'; $html[] = '<a href="index.php?option=com_briefcasefactory&view=storagefolder&tmpl=component&folder=' . base64_encode($this->value) . '" class="modal storageFolder" rel="{ handler: \'iframe\' }">'; $html[] = $this->value; $html[] = '</a>'; return implode("\n", $html); } }
Xervmon/b2b
administrator/components/com_briefcasefactory/models/fields/briefcasestoragefolder.php
PHP
gpl-2.0
1,380
/* * soc-pcm.c -- ALSA SoC PCM * * Copyright 2005 Wolfson Microelectronics PLC. * Copyright 2005 Openedhand Ltd. * Copyright (C) 2010 Slimlogic Ltd. * Copyright (C) 2010 Texas Instruments Inc. * * Authors: Liam Girdwood <lrg@ti.com> * Mark Brown <broonie@opensource.wolfsonmicro.com> * * 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. * */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/pm_runtime.h> #include <linux/slab.h> #include <linux/workqueue.h> #include <linux/debugfs.h> #include <linux/dma-mapping.h> #include <linux/export.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/soc.h> #include <sound/soc-dpcm.h> #include <sound/initval.h> /* ASoC no host IO hardware. * TODO: fine tune these values for all host less transfers. */ static const struct snd_pcm_hardware no_host_hardware = { .info = SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_MMAP_VALID | SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_RESUME, .formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S32_LE, .period_bytes_min = PAGE_SIZE >> 2, .period_bytes_max = PAGE_SIZE >> 1, .periods_min = 2, .periods_max = 4, .buffer_bytes_max = PAGE_SIZE, }; /* * We can only hw_free, stop, pause or suspend a BE DAI if any of it's FE * are not running, paused or suspended for the specified stream direction. */ int snd_soc_dpcm_can_be_free_stop(struct snd_soc_pcm_runtime *fe, struct snd_soc_pcm_runtime *be, int stream) { struct snd_soc_dpcm_params *dpcm_params; list_for_each_entry(dpcm_params, &be->dpcm[stream].fe_clients, list_fe) { if (dpcm_params->fe == fe) continue; if (dpcm_params->fe->dpcm[stream].state == SND_SOC_DPCM_STATE_START || dpcm_params->fe->dpcm[stream].state == SND_SOC_DPCM_STATE_PAUSED || dpcm_params->fe->dpcm[stream].state == SND_SOC_DPCM_STATE_SUSPEND) return 0; } return 1; } EXPORT_SYMBOL_GPL(snd_soc_dpcm_can_be_free_stop); /* * We can only change hw params a BE DAI if any of it's FE are not prepared, * running, paused or suspended for the specified stream direction. */ static int snd_soc_dpcm_can_be_params(struct snd_soc_pcm_runtime *fe, struct snd_soc_pcm_runtime *be, int stream) { struct snd_soc_dpcm_params *dpcm_params; list_for_each_entry(dpcm_params, &be->dpcm[stream].fe_clients, list_fe) { if (dpcm_params->fe == fe) continue; if (dpcm_params->fe->dpcm[stream].state == SND_SOC_DPCM_STATE_START || dpcm_params->fe->dpcm[stream].state == SND_SOC_DPCM_STATE_PAUSED || dpcm_params->fe->dpcm[stream].state == SND_SOC_DPCM_STATE_SUSPEND || dpcm_params->fe->dpcm[stream].state == SND_SOC_DPCM_STATE_PREPARE) return 0; } return 1; } static int soc_pcm_apply_symmetry(struct snd_pcm_substream *substream, struct snd_soc_dai *soc_dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; int ret; if (!soc_dai->driver->symmetric_rates && !rtd->dai_link->symmetric_rates) return 0; /* This can happen if multiple streams are starting simultaneously - * the second can need to get its constraints before the first has * picked a rate. Complain and allow the application to carry on. */ if (!soc_dai->rate) { dev_warn(soc_dai->dev, "Not enforcing symmetric_rates due to race\n"); return 0; } dev_dbg(soc_dai->dev, "Symmetry forces %dHz rate\n", soc_dai->rate); ret = snd_pcm_hw_constraint_minmax(substream->runtime, SNDRV_PCM_HW_PARAM_RATE, soc_dai->rate, soc_dai->rate); if (ret < 0) { dev_err(soc_dai->dev, "Unable to apply rate symmetry constraint: %d\n", ret); return ret; } return 0; } /* * List of sample sizes that might go over the bus for parameter * application. There ought to be a wildcard sample size for things * like the DAC/ADC resolution to use but there isn't right now. */ static int sample_sizes[] = { 8, 16, 24, 32, }; static void soc_pcm_apply_msb(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { int ret, i, bits; if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) bits = dai->driver->playback.sig_bits; else bits = dai->driver->capture.sig_bits; if (!bits) return; for (i = 0; i < ARRAY_SIZE(sample_sizes); i++) { if (bits >= sample_sizes[i]) continue; ret = snd_pcm_hw_constraint_msbits(substream->runtime, 0, sample_sizes[i], bits); if (ret != 0) dev_warn(dai->dev, "Failed to set MSB %d/%d: %d\n", bits, sample_sizes[i], ret); } } /* * stream event, send event to FE and all active BEs. */ int dpcm_dapm_stream_event(struct snd_soc_pcm_runtime *fe, int dir, const char *stream, int event) { struct snd_soc_dpcm_params *dpcm_params; snd_soc_dapm_rtd_stream_event(fe, dir, event); list_for_each_entry(dpcm_params, &fe->dpcm[dir].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; dev_dbg(be->dev, "pm: BE %s stream %s event %d dir %d\n", be->dai_link->name, stream, event, dir); snd_soc_dapm_rtd_stream_event(be, dir, event); } return 0; } /* * Called by ALSA when a PCM substream is opened, the runtime->hw record is * then initialized and any private data can be allocated. This also calls * startup for the cpu DAI, platform, machine and codec DAI. */ static int soc_pcm_open(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_pcm_runtime *runtime = substream->runtime; struct snd_soc_platform *platform = rtd->platform; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; struct snd_soc_dai *codec_dai = rtd->codec_dai; struct snd_soc_dai_driver *cpu_dai_drv = cpu_dai->driver; struct snd_soc_dai_driver *codec_dai_drv = codec_dai->driver; int ret = 0; pm_runtime_get_sync(cpu_dai->dev); pm_runtime_get_sync(codec_dai->dev); pm_runtime_get_sync(platform->dev); mutex_lock_nested(&rtd->pcm_mutex, rtd->pcm_subclass); if (rtd->dai_link->no_host_mode == SND_SOC_DAI_LINK_NO_HOST) snd_soc_set_runtime_hwparams(substream, &no_host_hardware); /* startup the audio subsystem */ if (cpu_dai->driver->ops->startup) { ret = cpu_dai->driver->ops->startup(substream, cpu_dai); if (ret < 0) { printk(KERN_ERR "asoc: can't open interface %s\n", cpu_dai->name); goto out; } } if (platform->driver->ops && platform->driver->ops->open) { ret = platform->driver->ops->open(substream); if (ret < 0) { printk(KERN_ERR "asoc: can't open platform %s\n", platform->name); goto platform_err; } } if (codec_dai->driver->ops->startup) { if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { ret = codec_dai->driver->ops->startup(substream, codec_dai); if (ret < 0) { printk(KERN_ERR "asoc: can't open codec %s\n", codec_dai->name); goto codec_dai_err; } } else { if (!codec_dai->capture_active) { ret = codec_dai->driver->ops->startup(substream, codec_dai); if (ret < 0) { printk(KERN_ERR "can't open codec %s\n", codec_dai->name); goto codec_dai_err; } } } } if (rtd->dai_link->ops && rtd->dai_link->ops->startup) { ret = rtd->dai_link->ops->startup(substream); if (ret < 0) { printk(KERN_ERR "asoc: %s startup failed\n", rtd->dai_link->name); goto machine_err; } } /* DSP DAI links compat checks are different */ if (rtd->dai_link->dynamic || rtd->dai_link->no_pcm) goto dynamic; /* Check that the codec and cpu DAIs are compatible */ if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { runtime->hw.rate_min = max(codec_dai_drv->playback.rate_min, cpu_dai_drv->playback.rate_min); runtime->hw.rate_max = min(codec_dai_drv->playback.rate_max, cpu_dai_drv->playback.rate_max); runtime->hw.channels_min = max(codec_dai_drv->playback.channels_min, cpu_dai_drv->playback.channels_min); runtime->hw.channels_max = min(codec_dai_drv->playback.channels_max, cpu_dai_drv->playback.channels_max); runtime->hw.formats = codec_dai_drv->playback.formats & cpu_dai_drv->playback.formats; runtime->hw.rates = codec_dai_drv->playback.rates & cpu_dai_drv->playback.rates; if (codec_dai_drv->playback.rates & (SNDRV_PCM_RATE_KNOT | SNDRV_PCM_RATE_CONTINUOUS)) runtime->hw.rates |= cpu_dai_drv->playback.rates; if (cpu_dai_drv->playback.rates & (SNDRV_PCM_RATE_KNOT | SNDRV_PCM_RATE_CONTINUOUS)) runtime->hw.rates |= codec_dai_drv->playback.rates; } else { runtime->hw.rate_min = max(codec_dai_drv->capture.rate_min, cpu_dai_drv->capture.rate_min); runtime->hw.rate_max = min(codec_dai_drv->capture.rate_max, cpu_dai_drv->capture.rate_max); runtime->hw.channels_min = max(codec_dai_drv->capture.channels_min, cpu_dai_drv->capture.channels_min); runtime->hw.channels_max = min(codec_dai_drv->capture.channels_max, cpu_dai_drv->capture.channels_max); runtime->hw.formats = codec_dai_drv->capture.formats & cpu_dai_drv->capture.formats; runtime->hw.rates = codec_dai_drv->capture.rates & cpu_dai_drv->capture.rates; if (codec_dai_drv->capture.rates & (SNDRV_PCM_RATE_KNOT | SNDRV_PCM_RATE_CONTINUOUS)) runtime->hw.rates |= cpu_dai_drv->capture.rates; if (cpu_dai_drv->capture.rates & (SNDRV_PCM_RATE_KNOT | SNDRV_PCM_RATE_CONTINUOUS)) runtime->hw.rates |= codec_dai_drv->capture.rates; } ret = -EINVAL; snd_pcm_limit_hw_rates(runtime); if (!runtime->hw.rates) { printk(KERN_ERR "asoc: %s <-> %s No matching rates\n", codec_dai->name, cpu_dai->name); goto config_err; } if (!runtime->hw.formats) { printk(KERN_ERR "asoc: %s <-> %s No matching formats\n", codec_dai->name, cpu_dai->name); goto config_err; } if (!runtime->hw.channels_min || !runtime->hw.channels_max || runtime->hw.channels_min > runtime->hw.channels_max) { printk(KERN_ERR "asoc: %s <-> %s No matching channels\n", codec_dai->name, cpu_dai->name); goto config_err; } soc_pcm_apply_msb(substream, codec_dai); soc_pcm_apply_msb(substream, cpu_dai); /* Symmetry only applies if we've already got an active stream. */ if (cpu_dai->active) { ret = soc_pcm_apply_symmetry(substream, cpu_dai); if (ret != 0) goto config_err; } if (codec_dai->active) { ret = soc_pcm_apply_symmetry(substream, codec_dai); if (ret != 0) goto config_err; } pr_debug("asoc: %s <-> %s info:\n", codec_dai->name, cpu_dai->name); pr_debug("asoc: rate mask 0x%x\n", runtime->hw.rates); pr_debug("asoc: min ch %d max ch %d\n", runtime->hw.channels_min, runtime->hw.channels_max); pr_debug("asoc: min rate %d max rate %d\n", runtime->hw.rate_min, runtime->hw.rate_max); dynamic: if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { cpu_dai->playback_active++; codec_dai->playback_active++; } else { cpu_dai->capture_active++; codec_dai->capture_active++; } cpu_dai->active++; codec_dai->active++; rtd->codec->active++; mutex_unlock(&rtd->pcm_mutex); return 0; config_err: if (rtd->dai_link->ops && rtd->dai_link->ops->shutdown) rtd->dai_link->ops->shutdown(substream); machine_err: if (codec_dai->driver->ops->shutdown) codec_dai->driver->ops->shutdown(substream, codec_dai); codec_dai_err: if (platform->driver->ops && platform->driver->ops->close) platform->driver->ops->close(substream); platform_err: if (cpu_dai->driver->ops->shutdown) cpu_dai->driver->ops->shutdown(substream, cpu_dai); out: mutex_unlock(&rtd->pcm_mutex); pm_runtime_put(platform->dev); pm_runtime_put(codec_dai->dev); pm_runtime_put(cpu_dai->dev); return ret; } /* * Power down the audio subsystem pmdown_time msecs after close is called. * This is to ensure there are no pops or clicks in between any music tracks * due to DAPM power cycling. */ static void close_delayed_work(struct work_struct *work) { struct snd_soc_pcm_runtime *rtd = container_of(work, struct snd_soc_pcm_runtime, delayed_work.work); struct snd_soc_dai *codec_dai = rtd->codec_dai; mutex_lock_nested(&rtd->pcm_mutex, rtd->pcm_subclass); pr_debug("pop wq checking: %s status: %s waiting: %s\n", codec_dai->driver->playback.stream_name, codec_dai->playback_active ? "active" : "inactive", rtd->pop_wait ? "yes" : "no"); /* are we waiting on this codec DAI stream */ if (rtd->pop_wait == 1) { rtd->pop_wait = 0; snd_soc_dapm_stream_event(rtd, codec_dai->driver->playback.stream_name, SND_SOC_DAPM_STREAM_STOP); } mutex_unlock(&rtd->pcm_mutex); } /* * Called by ALSA when a PCM substream is closed. Private data can be * freed here. The cpu DAI, codec DAI, machine and platform are also * shutdown. */ static int soc_pcm_close(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_platform *platform = rtd->platform; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; struct snd_soc_dai *codec_dai = rtd->codec_dai; struct snd_soc_codec *codec = rtd->codec; mutex_lock_nested(&rtd->pcm_mutex, rtd->pcm_subclass); if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { cpu_dai->playback_active--; codec_dai->playback_active--; } else { cpu_dai->capture_active--; codec_dai->capture_active--; } cpu_dai->active--; codec_dai->active--; codec->active--; /* clear the corresponding DAIs rate when inactive */ if (!cpu_dai->active) cpu_dai->rate = 0; if (!codec_dai->active) codec_dai->rate = 0; /* Muting the DAC suppresses artifacts caused during digital * shutdown, for example from stopping clocks. */ if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) snd_soc_dai_digital_mute(codec_dai, 1); if (cpu_dai->driver->ops->shutdown) cpu_dai->driver->ops->shutdown(substream, cpu_dai); if (codec_dai->driver->ops->shutdown) { if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { codec_dai->driver->ops->shutdown(substream, codec_dai); } else { if (!codec_dai->capture_active) codec_dai->driver->ops->shutdown(substream, codec_dai); } } if (rtd->dai_link->ops && rtd->dai_link->ops->shutdown) rtd->dai_link->ops->shutdown(substream); if (platform->driver->ops && platform->driver->ops->close) platform->driver->ops->close(substream); cpu_dai->runtime = NULL; if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { if (!rtd->pmdown_time || codec->ignore_pmdown_time || rtd->dai_link->ignore_pmdown_time) { /* powered down playback stream now */ snd_soc_dapm_stream_event(rtd, codec_dai->driver->playback.stream_name, SND_SOC_DAPM_STREAM_STOP); } else { /* start delayed pop wq here for playback streams */ rtd->pop_wait = 1; queue_delayed_work(system_power_efficient_wq, &rtd->delayed_work, msecs_to_jiffies(rtd->pmdown_time)); } } else { /* capture streams can be powered down now */ if (!codec_dai->capture_active) snd_soc_dapm_stream_event(rtd, codec_dai->driver->capture.stream_name, SND_SOC_DAPM_STREAM_STOP); } mutex_unlock(&rtd->pcm_mutex); pm_runtime_put(platform->dev); pm_runtime_put(codec_dai->dev); pm_runtime_put(cpu_dai->dev); return 0; } /* * Called by ALSA when the PCM substream is prepared, can set format, sample * rate, etc. This function is non atomic and can be called multiple times, * it can refer to the runtime info. */ static int soc_pcm_prepare(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_platform *platform = rtd->platform; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; struct snd_soc_dai *codec_dai = rtd->codec_dai; int ret = 0; mutex_lock_nested(&rtd->pcm_mutex, rtd->pcm_subclass); if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) snd_soc_dapm_stream_event(rtd, codec_dai->driver->playback.stream_name, SND_SOC_DAPM_STREAM_START); if (rtd->dai_link->ops && rtd->dai_link->ops->prepare) { ret = rtd->dai_link->ops->prepare(substream); if (ret < 0) { printk(KERN_ERR "asoc: machine prepare error\n"); goto out; } } if (platform->driver->ops && platform->driver->ops->prepare) { ret = platform->driver->ops->prepare(substream); if (ret < 0) { printk(KERN_ERR "asoc: platform prepare error\n"); goto out; } } if (codec_dai->driver->ops->prepare) { ret = codec_dai->driver->ops->prepare(substream, codec_dai); if (ret < 0) { printk(KERN_ERR "asoc: codec DAI prepare error\n"); goto out; } } if (cpu_dai->driver->ops->prepare) { ret = cpu_dai->driver->ops->prepare(substream, cpu_dai); if (ret < 0) { printk(KERN_ERR "asoc: cpu DAI prepare error\n"); goto out; } } /* cancel any delayed stream shutdown that is pending */ if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK && rtd->pop_wait) { rtd->pop_wait = 0; cancel_delayed_work(&rtd->delayed_work); } if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) { if (codec_dai->capture_active == 1) snd_soc_dapm_stream_event(rtd, codec_dai->driver->capture.stream_name, SND_SOC_DAPM_STREAM_START); } snd_soc_dai_digital_mute(codec_dai, 0); out: if (ret < 0 && substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { pr_err("%s: Issue stop stream for codec_dai due to op failure %d = ret\n", __func__, ret); snd_soc_dapm_stream_event(rtd, codec_dai->driver->playback.stream_name, SND_SOC_DAPM_STREAM_STOP); } mutex_unlock(&rtd->pcm_mutex); return ret; } /* * Called by ALSA when the hardware params are set by application. This * function can also be called multiple times and can allocate buffers * (using snd_pcm_lib_* ). It's non-atomic. */ static int soc_pcm_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_platform *platform = rtd->platform; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; struct snd_soc_dai *codec_dai = rtd->codec_dai; int ret = 0; mutex_lock_nested(&rtd->pcm_mutex, rtd->pcm_subclass); /* perform any hw_params fixups */ if ((rtd->dai_link->no_host_mode == SND_SOC_DAI_LINK_NO_HOST) && rtd->dai_link->be_hw_params_fixup) { ret = rtd->dai_link->be_hw_params_fixup(rtd, params); if (ret < 0) { dev_err(rtd->card->dev, "ASoC: fixup failed for %s\n", rtd->dai_link->name); } } if (rtd->dai_link->ops && rtd->dai_link->ops->hw_params) { ret = rtd->dai_link->ops->hw_params(substream, params); if (ret < 0) { printk(KERN_ERR "asoc: machine hw_params failed\n"); goto out; } } if (codec_dai->driver->ops->hw_params) { if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { ret = codec_dai->driver->ops->hw_params(substream, params, codec_dai); if (ret < 0) { printk(KERN_ERR "not set codec %s hw params\n", codec_dai->name); goto codec_err; } } else { if (codec_dai->capture_active == 1) { ret = codec_dai->driver->ops->hw_params( substream, params, codec_dai); if (ret < 0) { printk(KERN_ERR "fail: %s hw params\n", codec_dai->name); goto codec_err; } } } } if (cpu_dai->driver->ops->hw_params) { ret = cpu_dai->driver->ops->hw_params(substream, params, cpu_dai); if (ret < 0) { printk(KERN_ERR "asoc: interface %s hw params failed\n", cpu_dai->name); goto interface_err; } } if (platform->driver->ops && platform->driver->ops->hw_params) { ret = platform->driver->ops->hw_params(substream, params); if (ret < 0) { printk(KERN_ERR "asoc: platform %s hw params failed\n", platform->name); goto platform_err; } } /* store the rate for each DAIs */ cpu_dai->rate = params_rate(params); codec_dai->rate = params_rate(params); /* malloc a page for hostless IO. * FIXME: rework with alsa-lib changes so that this malloc is not required. */ if (rtd->dai_link->no_host_mode == SND_SOC_DAI_LINK_NO_HOST) { substream->dma_buffer.dev.type = SNDRV_DMA_TYPE_DEV; substream->dma_buffer.dev.dev = rtd->dev; substream->dma_buffer.dev.dev->coherent_dma_mask = DMA_BIT_MASK(32); substream->dma_buffer.private_data = NULL; ret = snd_pcm_lib_malloc_pages(substream, PAGE_SIZE); if (ret < 0) goto platform_err; } out: mutex_unlock(&rtd->pcm_mutex); return ret; platform_err: if (cpu_dai->driver->ops->hw_free) cpu_dai->driver->ops->hw_free(substream, cpu_dai); interface_err: if (codec_dai->driver->ops->hw_free) codec_dai->driver->ops->hw_free(substream, codec_dai); codec_err: if (rtd->dai_link->ops && rtd->dai_link->ops->hw_free) rtd->dai_link->ops->hw_free(substream); mutex_unlock(&rtd->pcm_mutex); return ret; } /* * Frees resources allocated by hw_params, can be called multiple times */ static int soc_pcm_hw_free(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_platform *platform = rtd->platform; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; struct snd_soc_dai *codec_dai = rtd->codec_dai; struct snd_soc_codec *codec = rtd->codec; mutex_lock_nested(&rtd->pcm_mutex, rtd->pcm_subclass); /* apply codec digital mute */ if (!codec->active) snd_soc_dai_digital_mute(codec_dai, 1); /* free any machine hw params */ if (rtd->dai_link->ops && rtd->dai_link->ops->hw_free) rtd->dai_link->ops->hw_free(substream); /* free any DMA resources */ if (platform->driver->ops && platform->driver->ops->hw_free) platform->driver->ops->hw_free(substream); /* now free hw params for the DAIs */ if (codec_dai->driver->ops->hw_free) codec_dai->driver->ops->hw_free(substream, codec_dai); if (cpu_dai->driver->ops->hw_free) cpu_dai->driver->ops->hw_free(substream, cpu_dai); if (rtd->dai_link->no_host_mode == SND_SOC_DAI_LINK_NO_HOST) snd_pcm_lib_free_pages(substream); mutex_unlock(&rtd->pcm_mutex); return 0; } static int soc_pcm_trigger(struct snd_pcm_substream *substream, int cmd) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_platform *platform = rtd->platform; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; struct snd_soc_dai *codec_dai = rtd->codec_dai; int ret; if (codec_dai->driver->ops->trigger) { if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { ret = codec_dai->driver->ops->trigger(substream, cmd, codec_dai); if (ret < 0) return ret; } else { if (codec_dai->capture_active == 1) { ret = codec_dai->driver->ops->trigger( substream, cmd, codec_dai); if (ret < 0) return ret; } } } if (platform->driver->ops && platform->driver->ops->trigger) { ret = platform->driver->ops->trigger(substream, cmd); if (ret < 0) return ret; } if (cpu_dai->driver->ops->trigger) { ret = cpu_dai->driver->ops->trigger(substream, cmd, cpu_dai); if (ret < 0) return ret; } return 0; } int soc_pcm_bespoke_trigger(struct snd_pcm_substream *substream, int cmd) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_platform *platform = rtd->platform; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; struct snd_soc_dai *codec_dai = rtd->codec_dai; int ret; if (codec_dai->driver->ops->bespoke_trigger) { ret = codec_dai->driver->ops->bespoke_trigger(substream, cmd, codec_dai); if (ret < 0) return ret; } if (platform->driver->bespoke_trigger) { ret = platform->driver->bespoke_trigger(substream, cmd); if (ret < 0) return ret; } if (cpu_dai->driver->ops->bespoke_trigger) { ret = cpu_dai->driver->ops->bespoke_trigger(substream, cmd, cpu_dai); if (ret < 0) return ret; } return 0; } /* * soc level wrapper for pointer callback * If cpu_dai, codec_dai, platform driver has the delay callback, than * the runtime->delay will be updated accordingly. */ static snd_pcm_uframes_t soc_pcm_pointer(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_platform *platform = rtd->platform; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; struct snd_soc_dai *codec_dai = rtd->codec_dai; struct snd_pcm_runtime *runtime = substream->runtime; snd_pcm_uframes_t offset = 0; snd_pcm_sframes_t delay = 0; if (platform->driver->ops && platform->driver->ops->pointer) offset = platform->driver->ops->pointer(substream); if (cpu_dai->driver->ops->delay) delay += cpu_dai->driver->ops->delay(substream, cpu_dai); if (codec_dai->driver->ops->delay) delay += codec_dai->driver->ops->delay(substream, codec_dai); if (platform->driver->delay) delay += platform->driver->delay(substream, codec_dai); runtime->delay = delay; return offset; } static inline int be_connect(struct snd_soc_pcm_runtime *fe, struct snd_soc_pcm_runtime *be, int stream) { struct snd_soc_dpcm_params *dpcm_params; if (!fe->dpcm[stream].runtime && !fe->fe_compr) { dev_err(fe->dev, "%s no runtime\n", fe->dai_link->name); return -ENODEV; } /* only add new dpcm_paramss */ list_for_each_entry(dpcm_params, &fe->dpcm[stream].be_clients, list_be) { if (dpcm_params->be == be && dpcm_params->fe == fe) return 0; } dpcm_params = kzalloc(sizeof(struct snd_soc_dpcm_params), GFP_KERNEL); if (!dpcm_params) return -ENOMEM; dpcm_params->be = be; dpcm_params->fe = fe; be->dpcm[stream].runtime = fe->dpcm[stream].runtime; dpcm_params->state = SND_SOC_DPCM_LINK_STATE_NEW; list_add(&dpcm_params->list_be, &fe->dpcm[stream].be_clients); list_add(&dpcm_params->list_fe, &be->dpcm[stream].fe_clients); dev_dbg(fe->dev, " connected new DSP %s path %s %s %s\n", stream ? "capture" : "playback", fe->dai_link->name, stream ? "<-" : "->", be->dai_link->name); #ifdef CONFIG_DEBUG_FS dpcm_params->debugfs_state = debugfs_create_u32(be->dai_link->name, 0644, fe->debugfs_dpcm_root, &dpcm_params->state); #endif return 1; } static inline void be_reparent(struct snd_soc_pcm_runtime *fe, struct snd_soc_pcm_runtime *be, int stream) { struct snd_soc_dpcm_params *dpcm_params; struct snd_pcm_substream *fe_substream, *be_substream; /* reparent if BE is connected to other FEs */ if (!be->dpcm[stream].users) return; be_substream = snd_soc_dpcm_get_substream(be, stream); list_for_each_entry(dpcm_params, &be->dpcm[stream].fe_clients, list_fe) { if (dpcm_params->fe != fe) { dev_dbg(fe->dev, " reparent %s path %s %s %s\n", stream ? "capture" : "playback", dpcm_params->fe->dai_link->name, stream ? "<-" : "->", dpcm_params->be->dai_link->name); fe_substream = snd_soc_dpcm_get_substream(dpcm_params->fe, stream); be_substream->runtime = fe_substream->runtime; break; } } } void dpcm_be_disconnect(struct snd_soc_pcm_runtime *fe, int stream) { struct snd_soc_dpcm_params *dpcm_params, *d; list_for_each_entry_safe(dpcm_params, d, &fe->dpcm[stream].be_clients, list_be) { dev_dbg(fe->dev, "BE %s disconnect check for %s\n", stream ? "capture" : "playback", dpcm_params->be->dai_link->name); if (dpcm_params->state == SND_SOC_DPCM_LINK_STATE_FREE) { dev_dbg(fe->dev, " freed DSP %s path %s %s %s\n", stream ? "capture" : "playback", fe->dai_link->name, stream ? "<-" : "->", dpcm_params->be->dai_link->name); /* BEs still alive need new FE */ be_reparent(fe, dpcm_params->be, stream); #ifdef CONFIG_DEBUG_FS debugfs_remove(dpcm_params->debugfs_state); #endif list_del(&dpcm_params->list_be); list_del(&dpcm_params->list_fe); kfree(dpcm_params); } } } static struct snd_soc_pcm_runtime *be_get_rtd(struct snd_soc_card *card, struct snd_soc_dapm_widget *widget) { struct snd_soc_pcm_runtime *be; int i; if (!widget->sname) { dev_err(card->dev, "widget %s has no stream\n", widget->name); return NULL; } for (i = 0; i < card->num_links; i++) { be = &card->rtd[i]; if (!strcmp(widget->sname, be->dai_link->stream_name)) return be; } dev_err(card->dev, "can't get BE for %s\n", widget->name); return NULL; } static struct snd_soc_dapm_widget *be_get_widget(struct snd_soc_card *card, struct snd_soc_pcm_runtime *rtd) { struct snd_soc_dapm_widget *widget; list_for_each_entry(widget, &card->widgets, list) { if (!widget->sname) continue; if (!strcmp(widget->sname, rtd->dai_link->stream_name)) return widget; } dev_err(card->dev, "can't get widget for %s\n", rtd->dai_link->stream_name); return NULL; } static int widget_in_list(struct snd_soc_dapm_widget_list *list, struct snd_soc_dapm_widget *widget) { int i; for (i = 0; i < list->num_widgets; i++) { if (widget == list->widgets[i]) return 1; } return 0; } int dpcm_path_get(struct snd_soc_pcm_runtime *fe, int stream, struct snd_soc_dapm_widget_list **list_) { struct snd_soc_dai *cpu_dai = fe->cpu_dai; struct snd_soc_dapm_widget_list *list; int paths; list = kzalloc(sizeof(struct snd_soc_dapm_widget_list) + sizeof(struct snd_soc_dapm_widget *), GFP_KERNEL); if (list == NULL) return -ENOMEM; /* get number of valid DAI paths and their widgets */ paths = snd_soc_dapm_dai_get_connected_widgets(cpu_dai, stream, &list); dev_dbg(fe->dev, "found %d audio %s paths\n", paths, stream ? "capture" : "playback"); *list_ = list; return paths; } static int be_prune_old(struct snd_soc_pcm_runtime *fe, int stream, struct snd_soc_dapm_widget_list **list_) { struct snd_soc_card *card = fe->card; struct snd_soc_dpcm_params *dpcm_params; struct snd_soc_dapm_widget_list *list = *list_; struct snd_soc_dapm_widget *widget; int old = 0; /* Destroy any old FE <--> BE connections */ list_for_each_entry(dpcm_params, &fe->dpcm[stream].be_clients, list_be) { /* is there a valid widget for this BE */ widget = be_get_widget(card, dpcm_params->be); if (!widget) { dev_err(fe->dev, "no widget found for %s\n", dpcm_params->be->dai_link->name); continue; } /* prune the BE if it's no longer in our active list */ if (widget_in_list(list, widget)) continue; dev_dbg(fe->dev, "pruning %s BE %s for %s\n", stream ? "capture" : "playback", dpcm_params->be->dai_link->name, fe->dai_link->name); dpcm_params->state = SND_SOC_DPCM_LINK_STATE_FREE; dpcm_params->be->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_BE; old++; } dev_dbg(fe->dev, "found %d old BEs\n", old); return old; } static int be_add_new(struct snd_soc_pcm_runtime *fe, int stream, struct snd_soc_dapm_widget_list **list_) { struct snd_soc_card *card = fe->card; struct snd_soc_dapm_widget_list *list = *list_; enum snd_soc_dapm_type be_type; int i, new = 0, err; if (stream == SNDRV_PCM_STREAM_PLAYBACK) be_type = snd_soc_dapm_aif_out; else be_type = snd_soc_dapm_aif_in; /* Create any new FE <--> BE connections */ for (i = 0; i < list->num_widgets; i++) { if (list->widgets[i]->id == be_type) { struct snd_soc_pcm_runtime *be; /* is there a valid BE rtd for this widget */ be = be_get_rtd(card, list->widgets[i]); if (!be) { dev_err(fe->dev, "no BE found for %s\n", list->widgets[i]->name); continue; } /* don't connect if FE is not running */ if (!fe->dpcm[stream].runtime && !fe->fe_compr) continue; /* newly connected FE and BE */ err = be_connect(fe, be, stream); if (err < 0) { dev_err(fe->dev, "can't connect %s\n", list->widgets[i]->name); break; } else if (err == 0) /* already connected */ continue; /* new */ be->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_BE; new++; } } dev_dbg(fe->dev, "found %d new BEs\n", new); return new; } /* * Find the corresponding BE DAIs that source or sink audio to this * FE substream. */ int dpcm_process_paths(struct snd_soc_pcm_runtime *fe, int stream, struct snd_soc_dapm_widget_list **list, int new) { if (new) return be_add_new(fe, stream, list); else return be_prune_old(fe, stream, list); return 0; } /* * Clear the runtime pending state of all BE's. */ void dpcm_clear_pending_state(struct snd_soc_pcm_runtime *fe, int stream) { struct snd_soc_dpcm_params *dpcm_params; list_for_each_entry(dpcm_params, &fe->dpcm[stream].be_clients, list_be) dpcm_params->be->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_NO; } /* Unwind the BE startup */ static void soc_dpcm_be_dai_startup_unwind(struct snd_soc_pcm_runtime *fe, int stream) { struct snd_soc_dpcm_params *dpcm_params; /* disable any enabled and non active backends */ list_for_each_entry(dpcm_params, &fe->dpcm[stream].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_pcm_substream *be_substream = snd_soc_dpcm_get_substream(be, stream); if (be->dpcm[stream].users == 0) dev_err(be->dev, "no users %s at close - state %d\n", stream ? "capture" : "playback", be->dpcm[stream].state); if (--be->dpcm[stream].users != 0) continue; if (be->dpcm[stream].state != SND_SOC_DPCM_STATE_OPEN) continue; soc_pcm_close(be_substream); be_substream->runtime = NULL; be->dpcm[stream].state = SND_SOC_DPCM_STATE_CLOSE; } } /* Startup all new BE */ int dpcm_be_dai_startup(struct snd_soc_pcm_runtime *fe, int stream) { struct snd_soc_dpcm_params *dpcm_params; int err, count = 0; /* only startup BE DAIs that are either sinks or sources to this FE DAI */ list_for_each_entry(dpcm_params, &fe->dpcm[stream].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_pcm_substream *be_substream = snd_soc_dpcm_get_substream(be, stream); if (!be_substream) { dev_err(be->dev, "ASoC: no backend %s stream\n", stream ? "capture" : "playback"); continue; } /* is this op for this BE ? */ if (!snd_soc_dpcm_be_can_update(fe, be, stream)) continue; /* first time the dpcm_params is open ? */ if (be->dpcm[stream].users == DPCM_MAX_BE_USERS) dev_err(be->dev, "too many users %s at open - state %d\n", stream ? "capture" : "playback", be->dpcm[stream].state); if (be->dpcm[stream].users++ != 0) continue; if ((be->dpcm[stream].state != SND_SOC_DPCM_STATE_NEW) && (be->dpcm[stream].state != SND_SOC_DPCM_STATE_CLOSE)) continue; dev_dbg(be->dev, "ASoC: open %s BE %s\n", stream ? "capture" : "playback", be->dai_link->name); be_substream->runtime = be->dpcm[stream].runtime; err = soc_pcm_open(be_substream); if (err < 0) { dev_err(be->dev, "BE open failed %d\n", err); be->dpcm[stream].users--; if (be->dpcm[stream].users < 0) dev_err(be->dev, "no users %s at unwind - state %d\n", stream ? "capture" : "playback", be->dpcm[stream].state); be->dpcm[stream].state = SND_SOC_DPCM_STATE_CLOSE; goto unwind; } be->dpcm[stream].state = SND_SOC_DPCM_STATE_OPEN; count++; } return count; unwind: /* disable any enabled and non active backends */ list_for_each_entry_continue_reverse(dpcm_params, &fe->dpcm[stream].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_pcm_substream *be_substream = snd_soc_dpcm_get_substream(be, stream); if (!snd_soc_dpcm_be_can_update(fe, be, stream)) continue; if (be->dpcm[stream].users == 0) dev_err(be->dev, "no users %s at close - state %d\n", stream ? "capture" : "playback", be->dpcm[stream].state); if (--be->dpcm[stream].users != 0) continue; if (be->dpcm[stream].state != SND_SOC_DPCM_STATE_OPEN) continue; soc_pcm_close(be_substream); be_substream->runtime = NULL; be->dpcm[stream].state = SND_SOC_DPCM_STATE_CLOSE; } return err; } void soc_dpcm_set_dynamic_runtime(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; struct snd_soc_dai_driver *cpu_dai_drv = cpu_dai->driver; if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { runtime->hw.rate_min = cpu_dai_drv->playback.rate_min; runtime->hw.rate_max = cpu_dai_drv->playback.rate_max; runtime->hw.channels_min = cpu_dai_drv->playback.channels_min; runtime->hw.channels_max = cpu_dai_drv->playback.channels_max; runtime->hw.formats &= cpu_dai_drv->playback.formats; runtime->hw.rates = cpu_dai_drv->playback.rates; } else { runtime->hw.rate_min = cpu_dai_drv->capture.rate_min; runtime->hw.rate_max = cpu_dai_drv->capture.rate_max; runtime->hw.channels_min = cpu_dai_drv->capture.channels_min; runtime->hw.channels_max = cpu_dai_drv->capture.channels_max; runtime->hw.formats &= cpu_dai_drv->capture.formats; runtime->hw.rates = cpu_dai_drv->capture.rates; } } static int soc_dpcm_fe_dai_startup(struct snd_pcm_substream *fe_substream) { struct snd_soc_pcm_runtime *fe = fe_substream->private_data; struct snd_pcm_runtime *runtime = fe_substream->runtime; int stream = fe_substream->stream, ret = 0; fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_FE; ret = dpcm_be_dai_startup(fe, fe_substream->stream); if (ret < 0) { dev_err(fe->dev,"dpcm: failed to start some BEs %d\n", ret); goto be_err; } dev_dbg(fe->dev, "dpcm: open FE %s\n", fe->dai_link->name); /* start the DAI frontend */ ret = soc_pcm_open(fe_substream); if (ret < 0) { dev_err(fe->dev,"dpcm: failed to start FE %d\n", ret); goto unwind; } fe->dpcm[stream].state = SND_SOC_DPCM_STATE_OPEN; soc_dpcm_set_dynamic_runtime(fe_substream); snd_pcm_limit_hw_rates(runtime); fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_NO; return 0; unwind: soc_dpcm_be_dai_startup_unwind(fe, fe_substream->stream); be_err: fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_NO; return ret; } /* BE shutdown - called on DAPM sync updates (i.e. FE is already running)*/ int dpcm_be_dai_shutdown(struct snd_soc_pcm_runtime *fe, int stream) { struct snd_soc_dpcm_params *dpcm_params; /* only shutdown backends that are either sinks or sources to this frontend DAI */ list_for_each_entry(dpcm_params, &fe->dpcm[stream].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_pcm_substream *be_substream = snd_soc_dpcm_get_substream(be, stream); /* is this op for this BE ? */ if (!snd_soc_dpcm_be_can_update(fe, be, stream)) continue; if (be->dpcm[stream].users == 0) dev_err(be->dev, "no users %s at close - state %d\n", stream ? "capture" : "playback", be->dpcm[stream].state); if (--be->dpcm[stream].users != 0) continue; if ((be->dpcm[stream].state != SND_SOC_DPCM_STATE_HW_FREE) && (be->dpcm[stream].state != SND_SOC_DPCM_STATE_OPEN)) continue; dev_dbg(be->dev, "dpcm: close BE %s\n", dpcm_params->fe->dai_link->name); soc_pcm_close(be_substream); be_substream->runtime = NULL; be->dpcm[stream].state = SND_SOC_DPCM_STATE_CLOSE; } return 0; } /* FE +BE shutdown - called on FE PCM ops */ static int soc_dpcm_fe_dai_shutdown(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *fe = substream->private_data; int stream = substream->stream; fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_FE; dev_dbg(fe->dev, "dpcm: close FE %s\n", fe->dai_link->name); /* now shutdown the frontend */ soc_pcm_close(substream); /* shutdown the BEs */ dpcm_be_dai_shutdown(fe, substream->stream); /* run the stream event for each BE */ if (stream == SNDRV_PCM_STREAM_PLAYBACK) dpcm_dapm_stream_event(fe, stream, fe->cpu_dai->driver->playback.stream_name, SND_SOC_DAPM_STREAM_STOP); else dpcm_dapm_stream_event(fe, stream, fe->cpu_dai->driver->capture.stream_name, SND_SOC_DAPM_STREAM_STOP); fe->dpcm[stream].state = SND_SOC_DPCM_STATE_CLOSE; fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_NO; return 0; } int dpcm_fe_dai_hw_params_be(struct snd_soc_pcm_runtime *fe, struct snd_soc_pcm_runtime *be, struct snd_pcm_hw_params *params, int stream) { int ret; struct snd_soc_dpcm_params *dpcm; struct snd_pcm_substream *be_substream = snd_soc_dpcm_get_substream(be, stream); /* is this op for this BE ? */ if (!snd_soc_dpcm_be_can_update(fe, be, stream)) return 0; /* only allow hw_params() if no connected FEs are running */ if (!snd_soc_dpcm_can_be_params(fe, be, stream)) return 0; if ((be->dpcm[stream].state != SND_SOC_DPCM_STATE_OPEN) && (be->dpcm[stream].state != SND_SOC_DPCM_STATE_HW_PARAMS) && (be->dpcm[stream].state != SND_SOC_DPCM_STATE_HW_FREE)) return 0; dev_dbg(be->dev, "ASoC: hw_params BE %s\n", fe->dai_link->name); /* perform any hw_params fixups */ if (be->dai_link->be_hw_params_fixup) { ret = be->dai_link->be_hw_params_fixup(be, params); if (ret < 0) { dev_err(be->dev, "ASoC: hw_params BE fixup failed %d\n", ret); goto unwind; } } ret = soc_pcm_hw_params(be_substream, params); if (ret < 0) { dev_err(be->dev, "ASoC: hw_params BE failed %d\n", ret); goto unwind; } be->dpcm[stream].state = SND_SOC_DPCM_STATE_HW_PARAMS; return 0; unwind: /* disable any enabled and non active backends */ list_for_each_entry(dpcm, &fe->dpcm[stream].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm->be; struct snd_pcm_substream *be_substream = snd_soc_dpcm_get_substream(be, stream); if (!snd_soc_dpcm_be_can_update(fe, be, stream)) continue; /* only allow hw_free() if no connected FEs are running */ if (!snd_soc_dpcm_can_be_free_stop(fe, be, stream)) continue; if ((be->dpcm[stream].state != SND_SOC_DPCM_STATE_OPEN) && (be->dpcm[stream].state != SND_SOC_DPCM_STATE_HW_PARAMS) && (be->dpcm[stream].state != SND_SOC_DPCM_STATE_HW_FREE) && (be->dpcm[stream].state != SND_SOC_DPCM_STATE_STOP)) continue; soc_pcm_hw_free(be_substream); } return ret; } int dpcm_be_dai_hw_params(struct snd_soc_pcm_runtime *fe, int stream) { struct snd_soc_dpcm_params *dpcm_params; int ret; list_for_each_entry(dpcm_params, &fe->dpcm[stream].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_pcm_substream *be_substream = snd_soc_dpcm_get_substream(be, stream); /* is this op for this BE ? */ if (!snd_soc_dpcm_be_can_update(fe, be, stream)) continue; /* only allow hw_params() if no connected FEs are running */ if (!snd_soc_dpcm_can_be_params(fe, be, stream)) continue; if ((be->dpcm[stream].state != SND_SOC_DPCM_STATE_OPEN) && (be->dpcm[stream].state != SND_SOC_DPCM_STATE_HW_PARAMS) && (be->dpcm[stream].state != SND_SOC_DPCM_STATE_HW_FREE)) continue; dev_dbg(be->dev, "dpcm: hw_params BE %s\n", dpcm_params->fe->dai_link->name); /* copy params for each dpcm_params */ memcpy(&dpcm_params->hw_params, &fe->dpcm[stream].hw_params, sizeof(struct snd_pcm_hw_params)); /* perform any hw_params fixups */ if (be->dai_link->be_hw_params_fixup) { ret = be->dai_link->be_hw_params_fixup(be, &dpcm_params->hw_params); if (ret < 0) { dev_err(be->dev, "dpcm: hw_params BE fixup failed %d\n", ret); goto unwind; } } ret = soc_pcm_hw_params(be_substream, &dpcm_params->hw_params); if (ret < 0) { dev_err(dpcm_params->be->dev, "dpcm: hw_params BE failed %d\n", ret); goto unwind; } be->dpcm[stream].state = SND_SOC_DPCM_STATE_HW_PARAMS; } return 0; unwind: /* disable any enabled and non active backends */ list_for_each_entry_continue_reverse(dpcm_params, &fe->dpcm[stream].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_pcm_substream *be_substream = snd_soc_dpcm_get_substream(be, stream); if (!snd_soc_dpcm_be_can_update(fe, be, stream)) continue; /* only allow hw_free() if no connected FEs are running */ if (!snd_soc_dpcm_can_be_free_stop(fe, be, stream)) continue; if ((be->dpcm[stream].state != SND_SOC_DPCM_STATE_OPEN) && (be->dpcm[stream].state != SND_SOC_DPCM_STATE_HW_PARAMS) && (be->dpcm[stream].state != SND_SOC_DPCM_STATE_HW_FREE) && (be->dpcm[stream].state != SND_SOC_DPCM_STATE_STOP)) continue; soc_pcm_hw_free(be_substream); } return ret; } int soc_dpcm_fe_dai_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { struct snd_soc_pcm_runtime *fe = substream->private_data; int ret, stream = substream->stream; mutex_lock(&fe->card->dpcm_mutex); fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_FE; memcpy(&fe->dpcm[substream->stream].hw_params, params, sizeof(struct snd_pcm_hw_params)); ret = dpcm_be_dai_hw_params(fe, substream->stream); if (ret < 0) { dev_err(fe->dev,"dpcm: hw_params failed for some BEs %d\n", ret); goto out; } dev_dbg(fe->dev, "dpcm: hw_params FE %s rate %d chan %x fmt %d\n", fe->dai_link->name, params_rate(params), params_channels(params), params_format(params)); /* call hw_params on the frontend */ ret = soc_pcm_hw_params(substream, params); if (ret < 0) { dev_err(fe->dev,"dpcm: hw_params FE failed %d\n", ret); dpcm_be_dai_hw_free(fe, stream); } else fe->dpcm[stream].state = SND_SOC_DPCM_STATE_HW_PARAMS; out: fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_NO; mutex_unlock(&fe->card->dpcm_mutex); return ret; } static int dpcm_do_trigger(struct snd_soc_dpcm_params *dpcm_params, struct snd_pcm_substream *substream, int cmd) { int ret; dev_dbg(dpcm_params->be->dev, "dpcm: trigger BE %s cmd %d\n", dpcm_params->fe->dai_link->name, cmd); ret = soc_pcm_trigger(substream, cmd); if (ret < 0) dev_err(dpcm_params->be->dev,"dpcm: trigger BE failed %d\n", ret); return ret; } int dpcm_be_dai_trigger(struct snd_soc_pcm_runtime *fe, int stream, int cmd) { struct snd_soc_dpcm_params *dpcm_params; int ret = 0; list_for_each_entry(dpcm_params, &fe->dpcm[stream].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_pcm_substream *be_substream = snd_soc_dpcm_get_substream(be, stream); /* is this op for this BE ? */ if (!snd_soc_dpcm_be_can_update(fe, be, stream)) continue; switch (cmd) { case SNDRV_PCM_TRIGGER_START: if ((be->dpcm[stream].state != SND_SOC_DPCM_STATE_PREPARE) && (be->dpcm[stream].state != SND_SOC_DPCM_STATE_STOP)) continue; ret = dpcm_do_trigger(dpcm_params, be_substream, cmd); if (ret) return ret; be->dpcm[stream].state = SND_SOC_DPCM_STATE_START; break; case SNDRV_PCM_TRIGGER_RESUME: if ((be->dpcm[stream].state != SND_SOC_DPCM_STATE_SUSPEND)) continue; ret = dpcm_do_trigger(dpcm_params, be_substream, cmd); if (ret) return ret; be->dpcm[stream].state = SND_SOC_DPCM_STATE_START; break; case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: if ((be->dpcm[stream].state != SND_SOC_DPCM_STATE_PAUSED)) continue; ret = dpcm_do_trigger(dpcm_params, be_substream, cmd); if (ret) return ret; be->dpcm[stream].state = SND_SOC_DPCM_STATE_START; break; case SNDRV_PCM_TRIGGER_STOP: if (be->dpcm[stream].state != SND_SOC_DPCM_STATE_START) continue; if (!snd_soc_dpcm_can_be_free_stop(fe, be, stream)) continue; ret = dpcm_do_trigger(dpcm_params, be_substream, cmd); if (ret) return ret; be->dpcm[stream].state = SND_SOC_DPCM_STATE_STOP; break; case SNDRV_PCM_TRIGGER_SUSPEND: if (be->dpcm[stream].state != SND_SOC_DPCM_STATE_STOP) continue; if (!snd_soc_dpcm_can_be_free_stop(fe, be, stream)) continue; ret = dpcm_do_trigger(dpcm_params, be_substream, cmd); if (ret) return ret; be->dpcm[stream].state = SND_SOC_DPCM_STATE_SUSPEND; break; case SNDRV_PCM_TRIGGER_PAUSE_PUSH: if (be->dpcm[stream].state != SND_SOC_DPCM_STATE_START) continue; if (!snd_soc_dpcm_can_be_free_stop(fe, be, stream)) continue; ret = dpcm_do_trigger(dpcm_params, be_substream, cmd); if (ret) return ret; be->dpcm[stream].state = SND_SOC_DPCM_STATE_PAUSED; break; } } return ret; } EXPORT_SYMBOL_GPL(dpcm_be_dai_trigger); int soc_dpcm_fe_dai_trigger(struct snd_pcm_substream *substream, int cmd) { struct snd_soc_pcm_runtime *fe = substream->private_data; int stream = substream->stream, ret; enum snd_soc_dpcm_trigger trigger = fe->dai_link->trigger[stream]; fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_FE; switch (trigger) { case SND_SOC_DPCM_TRIGGER_PRE: /* call trigger on the frontend before the backend. */ dev_dbg(fe->dev, "dpcm: pre trigger FE %s cmd %d\n", fe->dai_link->name, cmd); ret = soc_pcm_trigger(substream, cmd); if (ret < 0) { dev_err(fe->dev,"dpcm: trigger FE failed %d\n", ret); goto out; } ret = dpcm_be_dai_trigger(fe, substream->stream, cmd); break; case SND_SOC_DPCM_TRIGGER_POST: /* call trigger on the frontend after the backend. */ ret = dpcm_be_dai_trigger(fe, substream->stream, cmd); if (ret < 0) { dev_err(fe->dev,"dpcm: trigger FE failed %d\n", ret); goto out; } dev_dbg(fe->dev, "dpcm: post trigger FE %s cmd %d\n", fe->dai_link->name, cmd); ret = soc_pcm_trigger(substream, cmd); break; case SND_SOC_DPCM_TRIGGER_BESPOKE: /* bespoke trigger() - handles both FE and BEs */ dev_dbg(fe->dev, "dpcm: bespoke trigger FE %s cmd %d\n", fe->dai_link->name, cmd); ret = soc_pcm_bespoke_trigger(substream, cmd); if (ret < 0) { dev_err(fe->dev,"dpcm: trigger FE failed %d\n", ret); goto out; } break; default: dev_err(fe->dev, "dpcm: invalid trigger cmd %d for %s\n", cmd, fe->dai_link->name); ret = -EINVAL; goto out; } switch (cmd) { case SNDRV_PCM_TRIGGER_START: case SNDRV_PCM_TRIGGER_RESUME: case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: fe->dpcm[stream].state = SND_SOC_DPCM_STATE_START; break; case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_SUSPEND: fe->dpcm[stream].state = SND_SOC_DPCM_STATE_STOP; break; case SNDRV_PCM_TRIGGER_PAUSE_PUSH: fe->dpcm[stream].state = SND_SOC_DPCM_STATE_PAUSED; break; } out: fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_NO; return ret; } int dpcm_fe_dai_prepare_be(struct snd_soc_pcm_runtime *fe, struct snd_soc_pcm_runtime *be, int stream) { struct snd_pcm_substream *be_substream = snd_soc_dpcm_get_substream(be, stream); int ret = 0; /* is this op for this BE ? */ if (!snd_soc_dpcm_be_can_update(fe, be, stream)) return 0; if ((be->dpcm[stream].state != SND_SOC_DPCM_STATE_HW_PARAMS) && (be->dpcm[stream].state != SND_SOC_DPCM_STATE_STOP)) return 0; dev_dbg(be->dev, "ASoC: prepare BE %s\n", fe->dai_link->name); ret = soc_pcm_prepare(be_substream); if (ret < 0) { dev_err(be->dev, "ASoC: backend prepare failed %d\n", ret); return ret; } be->dpcm[stream].state = SND_SOC_DPCM_STATE_PREPARE; return ret; } int dpcm_be_dai_prepare(struct snd_soc_pcm_runtime *fe, int stream) { struct snd_soc_dpcm_params *dpcm_params; int ret = 0; list_for_each_entry(dpcm_params, &fe->dpcm[stream].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_pcm_substream *be_substream = snd_soc_dpcm_get_substream(be, stream); /* is this op for this BE ? */ if (!snd_soc_dpcm_be_can_update(fe, be, stream)) continue; if ((be->dpcm[stream].state != SND_SOC_DPCM_STATE_HW_PARAMS) && (be->dpcm[stream].state != SND_SOC_DPCM_STATE_STOP)) continue; dev_dbg(be->dev, "dpcm: prepare BE %s\n", dpcm_params->fe->dai_link->name); ret = soc_pcm_prepare(be_substream); if (ret < 0) { dev_err(be->dev, "dpcm: backend prepare failed %d\n", ret); break; } be->dpcm[stream].state = SND_SOC_DPCM_STATE_PREPARE; } return ret; } static void dpcm_be_async_prepare(void *data, async_cookie_t cookie) { struct snd_soc_dpcm_params *dpcm = data; struct snd_soc_pcm_runtime *be = dpcm->be; int stream = dpcm->stream; struct snd_pcm_substream *be_substream = snd_soc_dpcm_get_substream(be, stream); int ret; dev_dbg(be->dev, "%s ASoC: prepare BE %s\n", __func__, dpcm->fe->dai_link->name); ret = soc_pcm_prepare(be_substream); if (ret < 0) { be->err_ops = ret; dev_err(be->dev, "ASoC: backend prepare failed %d\n", ret); return; } be->dpcm[stream].state = SND_SOC_DPCM_STATE_PREPARE; } void dpcm_be_dai_prepare_async(struct snd_soc_pcm_runtime *fe, int stream, struct async_domain *domain) { struct snd_soc_dpcm_params *dpcm; struct snd_soc_dpcm_params *dpcm_async[DPCM_MAX_BE_USERS]; int i = 0, j; list_for_each_entry(dpcm, &fe->dpcm[stream].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm->be; be->err_ops = 0; /* is this op for this BE ? */ if (!snd_soc_dpcm_be_can_update(fe, be, stream)) continue; if ((be->dpcm[stream].state != SND_SOC_DPCM_STATE_HW_PARAMS) && (be->dpcm[stream].state != SND_SOC_DPCM_STATE_STOP)) continue; /* does this BE support async op ?*/ if ((fe->dai_link->async_ops & ASYNC_DPCM_SND_SOC_PREPARE) && (be->dai_link->async_ops & ASYNC_DPCM_SND_SOC_PREPARE)) { dpcm->stream = stream; async_schedule_domain(dpcm_be_async_prepare, dpcm, domain); } else { dpcm_async[i++] = dpcm; } } for (j = 0; j < i; j++) { struct snd_soc_dpcm_params *dpcm = dpcm_async[j]; struct snd_soc_pcm_runtime *be = dpcm->be; struct snd_pcm_substream *be_substream = snd_soc_dpcm_get_substream(be, stream); int ret; dev_dbg(be->dev, "ASoC: prepare BE %s\n", dpcm->fe->dai_link->name); ret = soc_pcm_prepare(be_substream); if (ret < 0) { dev_err(be->dev, "ASoC: backend prepare failed %d\n", ret); be->err_ops = ret; return; } be->dpcm[stream].state = SND_SOC_DPCM_STATE_PREPARE; } } int soc_dpcm_fe_dai_prepare(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *fe = substream->private_data; struct snd_soc_dpcm_params *dpcm; int stream = substream->stream, ret = 0; ASYNC_DOMAIN_EXCLUSIVE(async_domain); mutex_lock(&fe->card->dpcm_mutex); fe->err_ops = 0; dev_dbg(fe->dev, "ASoC: prepare FE %s\n", fe->dai_link->name); fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_FE; /* there is no point preparing this FE if there are no BEs */ if (list_empty(&fe->dpcm[stream].be_clients)) { dev_err(fe->dev, "dpcm: no backend DAIs enabled for %s\n", fe->dai_link->name); ret = -EINVAL; goto out; } ret = dpcm_be_dai_prepare(fe, substream->stream); if (ret < 0) { dev_err(fe->dev, "ASoC: prepare FE %s failed\n", fe->dai_link->name); goto out; } if (!(fe->dai_link->async_ops & ASYNC_DPCM_SND_SOC_PREPARE)) { ret = dpcm_be_dai_prepare(fe, substream->stream); if (ret < 0) goto out; /* call prepare on the frontend */ ret = soc_pcm_prepare(substream); if (ret < 0) { dev_err(fe->dev, "ASoC: prepare FE %s failed\n", fe->dai_link->name); goto out; } } else { dpcm_be_dai_prepare_async(fe, substream->stream, &async_domain); /* call prepare on the frontend */ ret = soc_pcm_prepare(substream); if (ret < 0) { fe->err_ops = ret; dev_err(fe->dev, "ASoC: prepare FE %s failed\n", fe->dai_link->name); } async_synchronize_full_domain(&async_domain); /* check if any BE failed */ list_for_each_entry(dpcm, &fe->dpcm[stream].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm->be; if (be->err_ops < 0) { ret = be->err_ops; goto out; } } /* check if FE failed */ if (fe->err_ops < 0) { ret = fe->err_ops; goto out; } } /* run the stream event for each BE */ if (stream == SNDRV_PCM_STREAM_PLAYBACK) dpcm_dapm_stream_event(fe, stream, fe->cpu_dai->driver->playback.stream_name, SND_SOC_DAPM_STREAM_START); else dpcm_dapm_stream_event(fe, stream, fe->cpu_dai->driver->capture.stream_name, SND_SOC_DAPM_STREAM_START); fe->dpcm[stream].state = SND_SOC_DPCM_STATE_PREPARE; out: fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_NO; mutex_unlock(&fe->card->dpcm_mutex); return ret; } int dpcm_be_dai_hw_free(struct snd_soc_pcm_runtime *fe, int stream) { struct snd_soc_dpcm_params *dpcm_params; /* only hw_params backends that are either sinks or sources * to this frontend DAI */ list_for_each_entry(dpcm_params, &fe->dpcm[stream].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_pcm_substream *be_substream = snd_soc_dpcm_get_substream(be, stream); /* is this op for this BE ? */ if (!snd_soc_dpcm_be_can_update(fe, be, stream)) continue; /* only free hw when no longer used - check all FEs */ if (!snd_soc_dpcm_can_be_free_stop(fe, be, stream)) continue; if ((be->dpcm[stream].state != SND_SOC_DPCM_STATE_HW_PARAMS) && (be->dpcm[stream].state != SND_SOC_DPCM_STATE_PREPARE) && (be->dpcm[stream].state != SND_SOC_DPCM_STATE_HW_FREE) && (be->dpcm[stream].state != SND_SOC_DPCM_STATE_PAUSED) && (be->dpcm[stream].state != SND_SOC_DPCM_STATE_STOP) && !((be->dpcm[stream].state == SND_SOC_DPCM_STATE_START) && ((fe->dpcm[stream].state != SND_SOC_DPCM_STATE_START) && (fe->dpcm[stream].state != SND_SOC_DPCM_STATE_PAUSED) && (fe->dpcm[stream].state != SND_SOC_DPCM_STATE_SUSPEND)))) continue; dev_dbg(be->dev, "dpcm: hw_free BE %s\n", dpcm_params->fe->dai_link->name); soc_pcm_hw_free(be_substream); be->dpcm[stream].state = SND_SOC_DPCM_STATE_HW_FREE; } return 0; } int soc_dpcm_fe_dai_hw_free(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *fe = substream->private_data; int err, stream = substream->stream; mutex_lock(&fe->card->dpcm_mutex); fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_FE; dev_dbg(fe->dev, "dpcm: hw_free FE %s\n", fe->dai_link->name); /* call hw_free on the frontend */ err = soc_pcm_hw_free(substream); if (err < 0) dev_err(fe->dev,"dpcm: hw_free FE %s failed\n", fe->dai_link->name); /* only hw_params backends that are either sinks or sources * to this frontend DAI */ err = dpcm_be_dai_hw_free(fe, stream); fe->dpcm[stream].state = SND_SOC_DPCM_STATE_HW_FREE; fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_NO; mutex_unlock(&fe->card->dpcm_mutex); return 0; } static int soc_pcm_ioctl(struct snd_pcm_substream *substream, unsigned int cmd, void *arg) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_platform *platform = rtd->platform; if (platform->driver->ops->ioctl) return platform->driver->ops->ioctl(substream, cmd, arg); return snd_pcm_lib_ioctl(substream, cmd, arg); } static int dpcm_run_update_shutdown(struct snd_soc_pcm_runtime *fe, int stream) { struct snd_pcm_substream *substream = snd_soc_dpcm_get_substream(fe, stream); enum snd_soc_dpcm_trigger trigger = fe->dai_link->trigger[stream]; int err; dev_dbg(fe->dev, "runtime %s close on FE %s\n", stream ? "capture" : "playback", fe->dai_link->name); if (trigger == SND_SOC_DPCM_TRIGGER_BESPOKE) { /* call bespoke trigger - FE takes care of all BE triggers */ dev_dbg(fe->dev, "dpcm: bespoke trigger FE %s cmd stop\n", fe->dai_link->name); err = soc_pcm_bespoke_trigger(substream, SNDRV_PCM_TRIGGER_STOP); if (err < 0) dev_err(fe->dev,"dpcm: trigger FE failed %d\n", err); } else { dev_dbg(fe->dev, "dpcm: trigger FE %s cmd stop\n", fe->dai_link->name); err = dpcm_be_dai_trigger(fe, stream, SNDRV_PCM_TRIGGER_STOP); if (err < 0) dev_err(fe->dev,"dpcm: trigger FE failed %d\n", err); } err = dpcm_be_dai_hw_free(fe, stream); if (err < 0) dev_err(fe->dev,"dpcm: hw_free FE failed %d\n", err); err = dpcm_be_dai_shutdown(fe, stream); if (err < 0) dev_err(fe->dev,"dpcm: shutdown FE failed %d\n", err); /* run the stream event for each BE */ if (stream == SNDRV_PCM_STREAM_PLAYBACK) dpcm_dapm_stream_event(fe, stream, fe->cpu_dai->driver->playback.stream_name, SND_SOC_DAPM_STREAM_NOP); else dpcm_dapm_stream_event(fe, stream, fe->cpu_dai->driver->capture.stream_name, SND_SOC_DAPM_STREAM_NOP); return 0; } static int dpcm_run_update_startup(struct snd_soc_pcm_runtime *fe, int stream) { struct snd_pcm_substream *substream = snd_soc_dpcm_get_substream(fe, stream); struct snd_soc_dpcm_params *dpcm_params; enum snd_soc_dpcm_trigger trigger = fe->dai_link->trigger[stream]; int ret; dev_dbg(fe->dev, "runtime %s open on FE %s\n", stream ? "capture" : "playback", fe->dai_link->name); /* Only start the BE if the FE is ready */ if (fe->dpcm[stream].state == SND_SOC_DPCM_STATE_HW_FREE || fe->dpcm[stream].state == SND_SOC_DPCM_STATE_CLOSE) return -EINVAL; /* startup must always be called for new BEs */ ret = dpcm_be_dai_startup(fe, stream); if (ret < 0) { goto disconnect; return ret; } /* keep going if FE state is > open */ if (fe->dpcm[stream].state == SND_SOC_DPCM_STATE_OPEN) return 0; ret = dpcm_be_dai_hw_params(fe, stream); if (ret < 0) { goto close; return ret; } /* keep going if FE state is > hw_params */ if (fe->dpcm[stream].state == SND_SOC_DPCM_STATE_HW_PARAMS) return 0; ret = dpcm_be_dai_prepare(fe, stream); if (ret < 0) { goto hw_free; return ret; } /* run the stream event for each BE */ if (stream == SNDRV_PCM_STREAM_PLAYBACK) dpcm_dapm_stream_event(fe, stream, fe->cpu_dai->driver->playback.stream_name, SND_SOC_DAPM_STREAM_NOP); else dpcm_dapm_stream_event(fe, stream, fe->cpu_dai->driver->capture.stream_name, SND_SOC_DAPM_STREAM_NOP); /* keep going if FE state is > prepare */ if (fe->dpcm[stream].state == SND_SOC_DPCM_STATE_PREPARE || fe->dpcm[stream].state == SND_SOC_DPCM_STATE_STOP) return 0; if (trigger == SND_SOC_DPCM_TRIGGER_BESPOKE) { /* call trigger on the frontend - FE takes care of all BE triggers */ dev_dbg(fe->dev, "dpcm: bespoke trigger FE %s cmd start\n", fe->dai_link->name); ret = soc_pcm_bespoke_trigger(substream, SNDRV_PCM_TRIGGER_START); if (ret < 0) { dev_err(fe->dev,"dpcm: bespoke trigger FE failed %d\n", ret); goto hw_free; } } else { dev_dbg(fe->dev, "dpcm: trigger FE %s cmd start\n", fe->dai_link->name); ret = dpcm_be_dai_trigger(fe, stream, SNDRV_PCM_TRIGGER_START); if (ret < 0) { dev_err(fe->dev,"dpcm: trigger FE failed %d\n", ret); goto hw_free; } } return 0; hw_free: dpcm_be_dai_hw_free(fe, stream); close: dpcm_be_dai_shutdown(fe, stream); disconnect: /* disconnect any non started BEs */ list_for_each_entry(dpcm_params, &fe->dpcm[stream].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; if (be->dpcm[stream].state != SND_SOC_DPCM_STATE_START) dpcm_params->state = SND_SOC_DPCM_LINK_STATE_FREE; } return ret; } static int dpcm_run_new_update(struct snd_soc_pcm_runtime *fe, int stream) { int ret; fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_BE; ret = dpcm_run_update_startup(fe, stream); if (ret < 0) dev_err(fe->dev, "failed to startup some BEs\n"); fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_NO; return ret; } static int dpcm_run_old_update(struct snd_soc_pcm_runtime *fe, int stream) { int ret; fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_BE; ret = dpcm_run_update_shutdown(fe, stream); if (ret < 0) dev_err(fe->dev, "failed to shutdown some BEs\n"); fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_NO; return ret; } /* called when any mixer updates change FE -> BE the stream */ int soc_dpcm_runtime_update(struct snd_soc_dapm_widget *widget) { struct snd_soc_card *card; int i, ret = 0, old, new, paths; if (widget->codec) card = widget->codec->card; else if (widget->platform) card = widget->platform->card; else return -EINVAL; mutex_lock(&card->dpcm_mutex); for (i = 0; i < card->num_rtd; i++) { struct snd_soc_dapm_widget_list *list; struct snd_soc_pcm_runtime *fe = &card->rtd[i]; /* make sure link is FE */ if (!fe->dai_link->dynamic) continue; /* only check active links */ if (!fe->cpu_dai->active) continue; /* DAPM sync will call this to update DSP paths */ dev_dbg(fe->dev, "DPCM runtime update for FE %s\n", fe->dai_link->name); /* skip if FE doesn't have playback capability */ if (!fe->cpu_dai->driver->playback.channels_min) goto capture; paths = dpcm_path_get(fe, SNDRV_PCM_STREAM_PLAYBACK, &list); if (paths < 0) { dev_warn(fe->dev, "%s no valid %s route from source to sink\n", fe->dai_link->name, "playback"); ret = paths; goto out; } /* update any new playback paths */ new = dpcm_process_paths(fe, SNDRV_PCM_STREAM_PLAYBACK, &list, 1); if (new) { dpcm_run_new_update(fe, SNDRV_PCM_STREAM_PLAYBACK); dpcm_clear_pending_state(fe, SNDRV_PCM_STREAM_PLAYBACK); dpcm_be_disconnect(fe, SNDRV_PCM_STREAM_PLAYBACK); } /* update any old playback paths */ old = dpcm_process_paths(fe, SNDRV_PCM_STREAM_PLAYBACK, &list, 0); if (old) { dpcm_run_old_update(fe, SNDRV_PCM_STREAM_PLAYBACK); dpcm_clear_pending_state(fe, SNDRV_PCM_STREAM_PLAYBACK); dpcm_be_disconnect(fe, SNDRV_PCM_STREAM_PLAYBACK); } dpcm_path_put(&list); capture: /* skip if FE doesn't have capture capability */ if (!fe->cpu_dai->driver->capture.channels_min) continue; paths = dpcm_path_get(fe, SNDRV_PCM_STREAM_CAPTURE, &list); if (paths < 0) { dev_warn(fe->dev, "%s no valid %s route from source to sink\n", fe->dai_link->name, "capture"); ret = paths; goto out; } /* update any new capture paths */ new = dpcm_process_paths(fe, SNDRV_PCM_STREAM_CAPTURE, &list, 1); if (new) { dpcm_run_new_update(fe, SNDRV_PCM_STREAM_CAPTURE); dpcm_clear_pending_state(fe, SNDRV_PCM_STREAM_CAPTURE); dpcm_be_disconnect(fe, SNDRV_PCM_STREAM_CAPTURE); } /* update any old capture paths */ old = dpcm_process_paths(fe, SNDRV_PCM_STREAM_CAPTURE, &list, 0); if (old) { dpcm_run_old_update(fe, SNDRV_PCM_STREAM_CAPTURE); dpcm_clear_pending_state(fe, SNDRV_PCM_STREAM_CAPTURE); dpcm_be_disconnect(fe, SNDRV_PCM_STREAM_CAPTURE); } dpcm_path_put(&list); } out: mutex_unlock(&card->dpcm_mutex); return ret; } int soc_dpcm_be_digital_mute(struct snd_soc_pcm_runtime *fe, int mute) { struct snd_soc_dpcm_params *dpcm_params; list_for_each_entry(dpcm_params, &fe->dpcm[SNDRV_PCM_STREAM_PLAYBACK].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_soc_dai *dai = be->codec_dai; struct snd_soc_dai_driver *drv = dai->driver; if (be->dai_link->ignore_suspend) continue; dev_dbg(be->dev, "BE digital mute %s\n", be->dai_link->name); if (drv->ops->digital_mute && dai->playback_active) drv->ops->digital_mute(dai, mute); } return 0; } int soc_dpcm_be_cpu_dai_suspend(struct snd_soc_pcm_runtime *fe) { struct snd_soc_dpcm_params *dpcm_params; /* suspend for playback */ list_for_each_entry(dpcm_params, &fe->dpcm[SNDRV_PCM_STREAM_PLAYBACK].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_soc_dai *dai = be->cpu_dai; struct snd_soc_dai_driver *drv = dai->driver; if (be->dai_link->ignore_suspend) continue; dev_dbg(be->dev, "pm: BE CPU DAI playback suspend %s\n", be->dai_link->name); if (drv->suspend && !drv->ac97_control) drv->suspend(dai); } /* suspend for capture */ list_for_each_entry(dpcm_params, &fe->dpcm[SNDRV_PCM_STREAM_CAPTURE].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_soc_dai *dai = be->cpu_dai; struct snd_soc_dai_driver *drv = dai->driver; if (be->dai_link->ignore_suspend) continue; dev_dbg(be->dev, "pm: BE CPU DAI capture suspend %s\n", be->dai_link->name); if (drv->suspend && !drv->ac97_control) drv->suspend(dai); } return 0; } int soc_dpcm_be_ac97_cpu_dai_suspend(struct snd_soc_pcm_runtime *fe) { struct snd_soc_dpcm_params *dpcm_params; /* suspend for playback */ list_for_each_entry(dpcm_params, &fe->dpcm[SNDRV_PCM_STREAM_PLAYBACK].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_soc_dai *dai = be->cpu_dai; struct snd_soc_dai_driver *drv = dai->driver; if (be->dai_link->ignore_suspend) continue; dev_dbg(be->dev, "pm: BE CPU DAI playback suspend %s\n", be->dai_link->name); if (drv->suspend && drv->ac97_control) drv->suspend(dai); } /* suspend for capture */ list_for_each_entry(dpcm_params, &fe->dpcm[SNDRV_PCM_STREAM_CAPTURE].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_soc_dai *dai = be->cpu_dai; struct snd_soc_dai_driver *drv = dai->driver; if (be->dai_link->ignore_suspend) continue; dev_dbg(be->dev, "pm: BE CPU DAI capture suspend %s\n", be->dai_link->name); if (drv->suspend && drv->ac97_control) drv->suspend(dai); } return 0; } int soc_dpcm_be_platform_suspend(struct snd_soc_pcm_runtime *fe) { struct snd_soc_dpcm_params *dpcm_params; /* suspend for playback */ list_for_each_entry(dpcm_params, &fe->dpcm[SNDRV_PCM_STREAM_PLAYBACK].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_soc_platform *platform = be->platform; struct snd_soc_platform_driver *drv = platform->driver; struct snd_soc_dai *dai = be->cpu_dai; if (be->dai_link->ignore_suspend) continue; dev_dbg(be->dev, "pm: BE platform playback suspend %s\n", be->dai_link->name); if (drv->suspend && !platform->suspended) { drv->suspend(dai); platform->suspended = 1; } } /* suspend for capture */ list_for_each_entry(dpcm_params, &fe->dpcm[SNDRV_PCM_STREAM_CAPTURE].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_soc_platform *platform = be->platform; struct snd_soc_platform_driver *drv = platform->driver; struct snd_soc_dai *dai = be->cpu_dai; if (be->dai_link->ignore_suspend) continue; dev_dbg(be->dev, "pm: BE platform capture suspend %s\n", be->dai_link->name); if (drv->suspend && !platform->suspended) { drv->suspend(dai); platform->suspended = 1; } } return 0; } int soc_dpcm_fe_suspend(struct snd_soc_pcm_runtime *fe) { struct snd_soc_dai *dai = fe->cpu_dai; struct snd_soc_dai_driver *dai_drv = dai->driver; struct snd_soc_platform *platform = fe->platform; struct snd_soc_platform_driver *plat_drv = platform->driver; if (dai_drv->suspend && !dai_drv->ac97_control) dai_drv->suspend(dai); if (plat_drv->suspend && !platform->suspended) { plat_drv->suspend(dai); platform->suspended = 1; } soc_dpcm_be_cpu_dai_suspend(fe); soc_dpcm_be_platform_suspend(fe); return 0; } int soc_dpcm_be_cpu_dai_resume(struct snd_soc_pcm_runtime *fe) { struct snd_soc_dpcm_params *dpcm_params; /* resume for playback */ list_for_each_entry(dpcm_params, &fe->dpcm[SNDRV_PCM_STREAM_PLAYBACK].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_soc_dai *dai = be->cpu_dai; struct snd_soc_dai_driver *drv = dai->driver; if (be->dai_link->ignore_suspend) continue; dev_dbg(be->dev, "pm: BE CPU DAI playback resume %s\n", be->dai_link->name); if (drv->resume && !drv->ac97_control) drv->resume(dai); } /* suspend for capture */ list_for_each_entry(dpcm_params, &fe->dpcm[SNDRV_PCM_STREAM_CAPTURE].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_soc_dai *dai = be->cpu_dai; struct snd_soc_dai_driver *drv = dai->driver; if (be->dai_link->ignore_suspend) continue; dev_dbg(be->dev, "pm: BE CPU DAI capture resume %s\n", be->dai_link->name); if (drv->resume && !drv->ac97_control) drv->resume(dai); } return 0; } int soc_dpcm_be_ac97_cpu_dai_resume(struct snd_soc_pcm_runtime *fe) { struct snd_soc_dpcm_params *dpcm_params; /* resume for playback */ list_for_each_entry(dpcm_params, &fe->dpcm[SNDRV_PCM_STREAM_PLAYBACK].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_soc_dai *dai = be->cpu_dai; struct snd_soc_dai_driver *drv = dai->driver; if (be->dai_link->ignore_suspend) continue; dev_dbg(be->dev, "pm: BE CPU DAI playback resume %s\n", be->dai_link->name); if (drv->resume && drv->ac97_control) drv->resume(dai); } /* suspend for capture */ list_for_each_entry(dpcm_params, &fe->dpcm[SNDRV_PCM_STREAM_CAPTURE].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_soc_dai *dai = be->cpu_dai; struct snd_soc_dai_driver *drv = dai->driver; if (be->dai_link->ignore_suspend) continue; dev_dbg(be->dev, "pm: BE CPU DAI capture resume %s\n", be->dai_link->name); if (drv->resume && drv->ac97_control) drv->resume(dai); } return 0; } int soc_dpcm_be_platform_resume(struct snd_soc_pcm_runtime *fe) { struct snd_soc_dpcm_params *dpcm_params; /* resume for playback */ list_for_each_entry(dpcm_params, &fe->dpcm[SNDRV_PCM_STREAM_PLAYBACK].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_soc_platform *platform = be->platform; struct snd_soc_platform_driver *drv = platform->driver; struct snd_soc_dai *dai = be->cpu_dai; if (be->dai_link->ignore_suspend) continue; dev_dbg(be->dev, "pm: BE platform playback resume %s\n", be->dai_link->name); if (drv->resume && platform->suspended) { drv->resume(dai); platform->suspended = 0; } } /* resume for capture */ list_for_each_entry(dpcm_params, &fe->dpcm[SNDRV_PCM_STREAM_CAPTURE].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; struct snd_soc_platform *platform = be->platform; struct snd_soc_platform_driver *drv = platform->driver; struct snd_soc_dai *dai = be->cpu_dai; if (be->dai_link->ignore_suspend) continue; dev_dbg(be->dev, "pm: BE platform capture resume %s\n", be->dai_link->name); if (drv->resume && platform->suspended) { drv->resume(dai); platform->suspended = 0; } } return 0; } int soc_dpcm_fe_resume(struct snd_soc_pcm_runtime *fe) { struct snd_soc_dai *dai = fe->cpu_dai; struct snd_soc_dai_driver *dai_drv = dai->driver; struct snd_soc_platform *platform = fe->platform; struct snd_soc_platform_driver *plat_drv = platform->driver; soc_dpcm_be_cpu_dai_resume(fe); soc_dpcm_be_platform_resume(fe); if (dai_drv->resume && !dai_drv->ac97_control) dai_drv->resume(dai); if (plat_drv->resume && platform->suspended) { plat_drv->resume(dai); platform->suspended = 0; } return 0; } /* called when opening FE stream */ int soc_dpcm_fe_dai_open(struct snd_pcm_substream *fe_substream) { struct snd_soc_pcm_runtime *fe = fe_substream->private_data; struct snd_soc_dpcm_params *dpcm_params; struct snd_soc_dapm_widget_list *list; int ret; int stream = fe_substream->stream; mutex_lock(&fe->card->dpcm_mutex); fe->dpcm[stream].runtime = fe_substream->runtime; if (dpcm_path_get(fe, stream, &list) <= 0) { dev_warn(fe->dev, "asoc: %s no valid %s route\n", fe->dai_link->name, stream ? "capture" : "playback"); } /* calculate valid and active FE <-> BE dpcm_paramss */ dpcm_process_paths(fe, stream, &list, 1); ret = soc_dpcm_fe_dai_startup(fe_substream); if (ret < 0) { /* clean up all links */ list_for_each_entry(dpcm_params, &fe->dpcm[stream].be_clients, list_be) dpcm_params->state = SND_SOC_DPCM_LINK_STATE_FREE; dpcm_be_disconnect(fe, stream); fe->dpcm[stream].runtime = NULL; } dpcm_clear_pending_state(fe, stream); dpcm_path_put(&list); mutex_unlock(&fe->card->dpcm_mutex); return ret; } /* called when closing FE stream */ int soc_dpcm_fe_dai_close(struct snd_pcm_substream *fe_substream) { struct snd_soc_pcm_runtime *fe = fe_substream->private_data; struct snd_soc_dpcm_params *dpcm_params; int stream = fe_substream->stream, ret; mutex_lock(&fe->card->dpcm_mutex); ret = soc_dpcm_fe_dai_shutdown(fe_substream); /* mark FE's links ready to prune */ list_for_each_entry(dpcm_params, &fe->dpcm[stream].be_clients, list_be) dpcm_params->state = SND_SOC_DPCM_LINK_STATE_FREE; dpcm_be_disconnect(fe, stream); fe->dpcm[stream].runtime = NULL; mutex_unlock(&fe->card->dpcm_mutex); return ret; } /* create a new pcm */ int soc_new_pcm(struct snd_soc_pcm_runtime *rtd, int num) { struct snd_soc_codec *codec = rtd->codec; struct snd_soc_platform *platform = rtd->platform; struct snd_soc_dai *codec_dai = rtd->codec_dai; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; struct snd_pcm_substream *substream[2]; struct snd_pcm *pcm; char new_name[64]; int ret = 0, playback = 0, capture = 0; if (rtd->dai_link->dynamic || rtd->dai_link->no_pcm) { if (cpu_dai->driver->playback.channels_min) playback = 1; if (cpu_dai->driver->capture.channels_min) capture = 1; } else { if (codec_dai->driver->playback.channels_min) playback = 1; if (codec_dai->driver->capture.channels_min) capture = 1; } /* create the PCM */ if (rtd->dai_link->no_pcm) { snprintf(new_name, sizeof(new_name), "(%s)", rtd->dai_link->stream_name); ret = snd_pcm_new_soc_be(rtd->card->snd_card, new_name, num, playback, capture, &pcm); } else { if (rtd->dai_link->dynamic) snprintf(new_name, sizeof(new_name), "%s (*)", rtd->dai_link->stream_name); else snprintf(new_name, sizeof(new_name), "%s %s-%d", rtd->dai_link->stream_name, codec_dai->name, num); ret = snd_pcm_new(rtd->card->snd_card, new_name, num, playback, capture, &pcm); } if (ret < 0) { printk(KERN_ERR "asoc: can't create pcm for codec %s\n", codec->name); return ret; } dev_dbg(rtd->card->dev, "registered pcm #%d %s\n",num, new_name); rtd->pcm = pcm; pcm->private_data = rtd; INIT_DELAYED_WORK(&rtd->delayed_work, close_delayed_work); substream[SNDRV_PCM_STREAM_PLAYBACK] = pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream; substream[SNDRV_PCM_STREAM_CAPTURE] = pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream; if (rtd->dai_link->no_pcm) { if (playback) substream[SNDRV_PCM_STREAM_PLAYBACK]->private_data = rtd; if (capture) substream[SNDRV_PCM_STREAM_CAPTURE]->private_data = rtd; goto out; } /* setup any hostless PCMs - i.e. no host IO is performed */ if (rtd->dai_link->no_host_mode) { if (substream[SNDRV_PCM_STREAM_PLAYBACK]) { substream[SNDRV_PCM_STREAM_PLAYBACK]->hw_no_buffer = 1; snd_soc_set_runtime_hwparams( substream[SNDRV_PCM_STREAM_PLAYBACK], &no_host_hardware); } if (substream[SNDRV_PCM_STREAM_CAPTURE]) { substream[SNDRV_PCM_STREAM_CAPTURE]->hw_no_buffer = 1; snd_soc_set_runtime_hwparams( substream[SNDRV_PCM_STREAM_CAPTURE], &no_host_hardware); } } /* ASoC PCM operations */ if (rtd->dai_link->dynamic) { rtd->ops.open = soc_dpcm_fe_dai_open; rtd->ops.hw_params = soc_dpcm_fe_dai_hw_params; rtd->ops.prepare = soc_dpcm_fe_dai_prepare; rtd->ops.trigger = soc_dpcm_fe_dai_trigger; rtd->ops.hw_free = soc_dpcm_fe_dai_hw_free; rtd->ops.close = soc_dpcm_fe_dai_close; rtd->ops.pointer = soc_pcm_pointer; rtd->ops.ioctl = soc_pcm_ioctl; } else { rtd->ops.open = soc_pcm_open; rtd->ops.hw_params = soc_pcm_hw_params; rtd->ops.prepare = soc_pcm_prepare; rtd->ops.trigger = soc_pcm_trigger; rtd->ops.hw_free = soc_pcm_hw_free; rtd->ops.close = soc_pcm_close; rtd->ops.pointer = soc_pcm_pointer; rtd->ops.ioctl = soc_pcm_ioctl; } if (platform->driver->ops) { rtd->ops.ack = platform->driver->ops->ack; rtd->ops.copy = platform->driver->ops->copy; rtd->ops.silence = platform->driver->ops->silence; rtd->ops.page = platform->driver->ops->page; rtd->ops.mmap = platform->driver->ops->mmap; rtd->ops.restart = platform->driver->ops->restart; } if (playback) snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &rtd->ops); if (capture) snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &rtd->ops); if (platform->driver->pcm_new) { ret = platform->driver->pcm_new(rtd); if (ret < 0) { pr_err("asoc: platform pcm constructor failed\n"); return ret; } } pcm->private_free = platform->driver->pcm_free; out: printk(KERN_INFO "asoc: %s <-> %s mapping ok\n", codec_dai->name, cpu_dai->name); return ret; } #ifdef CONFIG_DEBUG_FS static char *dpcm_state_string(enum snd_soc_dpcm_state state) { switch (state) { case SND_SOC_DPCM_STATE_NEW: return "new"; case SND_SOC_DPCM_STATE_OPEN: return "open"; case SND_SOC_DPCM_STATE_HW_PARAMS: return "hw_params"; case SND_SOC_DPCM_STATE_PREPARE: return "prepare"; case SND_SOC_DPCM_STATE_START: return "start"; case SND_SOC_DPCM_STATE_STOP: return "stop"; case SND_SOC_DPCM_STATE_SUSPEND: return "suspend"; case SND_SOC_DPCM_STATE_PAUSED: return "paused"; case SND_SOC_DPCM_STATE_HW_FREE: return "hw_free"; case SND_SOC_DPCM_STATE_CLOSE: return "close"; } return "unknown"; } static int soc_dpcm_state_open_file(struct inode *inode, struct file *file) { file->private_data = inode->i_private; return 0; } static ssize_t soc_dpcm_show_state(struct snd_soc_pcm_runtime *fe, int stream, char *buf, size_t size) { struct snd_pcm_hw_params *params = &fe->dpcm[stream].hw_params; struct snd_soc_dpcm_params *dpcm_params; ssize_t offset = 0; /* FE state */ offset += snprintf(buf + offset, size - offset, "[%s - %s]\n", fe->dai_link->name, stream ? "Capture" : "Playback"); offset += snprintf(buf + offset, size - offset, "State: %s\n", dpcm_state_string(fe->dpcm[stream].state)); if ((fe->dpcm[stream].state >= SND_SOC_DPCM_STATE_HW_PARAMS) && (fe->dpcm[stream].state <= SND_SOC_DPCM_STATE_STOP)) offset += snprintf(buf + offset, size - offset, "Hardware Params: " "Format = %s, Channels = %d, Rate = %d\n", snd_pcm_format_name(params_format(params)), params_channels(params), params_rate(params)); /* BEs state */ offset += snprintf(buf + offset, size - offset, "Backends:\n"); if (list_empty(&fe->dpcm[stream].be_clients)) { offset += snprintf(buf + offset, size - offset, " No active DSP links\n"); goto out; } list_for_each_entry(dpcm_params, &fe->dpcm[stream].be_clients, list_be) { struct snd_soc_pcm_runtime *be = dpcm_params->be; offset += snprintf(buf + offset, size - offset, "- %s\n", be->dai_link->name); offset += snprintf(buf + offset, size - offset, " State: %s\n", dpcm_state_string(fe->dpcm[stream].state)); if ((be->dpcm[stream].state >= SND_SOC_DPCM_STATE_HW_PARAMS) && (be->dpcm[stream].state <= SND_SOC_DPCM_STATE_STOP)) offset += snprintf(buf + offset, size - offset, " Hardware Params: " "Format = %s, Channels = %d, Rate = %d\n", snd_pcm_format_name(params_format(params)), params_channels(params), params_rate(params)); } out: return offset; } static ssize_t soc_dpcm_state_read_file(struct file *file, char __user *user_buf, size_t count, loff_t *ppos) { struct snd_soc_pcm_runtime *fe = file->private_data; ssize_t out_count = PAGE_SIZE, offset = 0, ret = 0; char *buf; buf = kmalloc(out_count, GFP_KERNEL); if (!buf) return -ENOMEM; if (fe->cpu_dai->driver->playback.channels_min) offset += soc_dpcm_show_state(fe, SNDRV_PCM_STREAM_PLAYBACK, buf + offset, out_count - offset); if (fe->cpu_dai->driver->capture.channels_min) offset += soc_dpcm_show_state(fe, SNDRV_PCM_STREAM_CAPTURE, buf + offset, out_count - offset); ret = simple_read_from_buffer(user_buf, count, ppos, buf, offset); kfree(buf); return ret; } static const struct file_operations soc_dpcm_state_fops = { .open = soc_dpcm_state_open_file, .read = soc_dpcm_state_read_file, .llseek = default_llseek, }; int soc_dpcm_debugfs_add(struct snd_soc_pcm_runtime *rtd) { rtd->debugfs_dpcm_root = debugfs_create_dir(rtd->dai_link->name, rtd->card->debugfs_card_root); if (!rtd->debugfs_dpcm_root) { dev_dbg(rtd->dev, "ASoC: Failed to create dpcm debugfs directory %s\n", rtd->dai_link->name); return -EINVAL; } rtd->debugfs_dpcm_state = debugfs_create_file("state", 0644, rtd->debugfs_dpcm_root, rtd, &soc_dpcm_state_fops); return 0; } #endif
dorimanx/DORIMANX_LG_STOCK_LP_KERNEL
sound/soc/soc-pcm.c
C
gpl-2.0
83,706
/* * Copyright (C) 2018, STMicroelectronics - All Rights Reserved * Author(s): Antonio Borneo <borneo.antonio@gmail.com> for STMicroelectronics * * 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 <http://www.gnu.org/licenses/>. */ /* * The content of this file is mainly copied/inspired from Linux kernel * code in include/linux/types.h include/linux/bitmap.h include/linux/bitops.h */ #ifndef OPENOCD_HELPER_BITS_H #define OPENOCD_HELPER_BITS_H #include <helper/types.h> #define BIT(nr) (1UL << (nr)) #define BITS_PER_BYTE 8 #define BITS_PER_LONG (BITS_PER_BYTE * sizeof(long)) #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, BITS_PER_BYTE * sizeof(long)) #define BIT_MASK(nr) (1UL << ((nr) % BITS_PER_LONG)) #define BIT_WORD(nr) ((nr) / BITS_PER_LONG) #define DECLARE_BITMAP(name, bits) unsigned long name[BITS_TO_LONGS(bits)] /** * bitmap_zero - Clears all the bits in memory * @param dst the address of the bitmap * @param nbits the number of bits to clear */ static inline void bitmap_zero(unsigned long *dst, unsigned int nbits) { unsigned int len = BITS_TO_LONGS(nbits) * sizeof(unsigned long); memset(dst, 0, len); } /** * clear_bit - Clear a bit in memory * @param nr the bit to set * @param addr the address to start counting from */ static inline void clear_bit(unsigned int nr, volatile unsigned long *addr) { unsigned long mask = BIT_MASK(nr); unsigned long *p = ((unsigned long *)addr) + BIT_WORD(nr); *p &= ~mask; } /** * set_bit - Set a bit in memory * @param nr the bit to set * @param addr the address to start counting from */ static inline void set_bit(unsigned int nr, volatile unsigned long *addr) { unsigned long mask = BIT_MASK(nr); unsigned long *p = ((unsigned long *)addr) + BIT_WORD(nr); *p |= mask; } /** * test_bit - Determine whether a bit is set * @param nr bit number to test * @param addr Address to start counting from */ static inline int test_bit(unsigned int nr, const volatile unsigned long *addr) { return 1UL & (addr[BIT_WORD(nr)] >> (nr % BITS_PER_LONG)); } #endif /* OPENOCD_HELPER_BITS_H */
olerem/openocd
src/helper/bits.h
C
gpl-2.0
2,725
/*! \file debug.h * \b 接口说明: * * * \b 功能描述: * * 调试信息打印 * * \b 历史记录: * * <作者> <时间> <修改记录> <br> * zuokongxiao 2014-06-12 创建文件 <br> */ #ifndef __DEBUG_H #define __DEBUG_H /******************************************************************************/ /* 头文件 */ /******************************************************************************/ #include <stdio.h> #include <string.h> #include <ctype.h> #include <errno.h> /******************************************************************************/ /* 宏定义 */ /******************************************************************************/ /*! 配置是否输出调试信息 */ #define PRINTF_MSG_EN (1) /*! 配置是否输出调试信息 */ #define DEBUG_MSG_EN (2) /*! 配置是否输出错误信息 */ #define ERROR_MSG_EN (1) /*! printf 宏定义 */ #if PRINTF_MSG_EN > 0 #define PRINTF_MSG(arg...) printf(##arg) #else #define PRINTF_MSG(arg...) ((void)0) #endif /*! 调试信息 */ #if DEBUG_MSG_EN == 1 //普通打印 #define PRINTF_MSG(arg...) printf(##arg) #elif DEBUG_MSG_EN == 2 //打印文件名、行号 #define DEBUG_MSG(format,arg...) do{ \ print_run_time(__FILE__, __LINE__); \ printf(format, ##arg); \ } while(0) #elif DEBUG_MSG_EN == 3 //打印文件名、行号、函数名 #define DEBUG_MSG(format,arg...) do{ \ print_run_time(__FILE__, __LINE__); \ printf("[F:%s] "format, __FUNCTION__, ##arg); \ } while(0) #else #define DEBUG_MSG(arg) ((void)0) #endif /*! 错误信息 */ #if ERROR_MSG_EN == 1 #define ERROR_MSG(format,arg...) do{ \ print_run_time(__FILE__, __LINE__); \ printf("[E:%s] "format, strerror(errno), ##arg); \ } while(0) #else #define ERROR_MSG() ((void)0) #endif /******************************************************************************/ /* 外部接口函数声明 */ /******************************************************************************/ void print_run_time(char *pFile, int lLine); #endif /*!< end __DEBUG_H */ /********************************end of file***********************************/
zuokong2006/am3359
app/include/debug.h
C
gpl-2.0
2,549
package com.devicehive.sspasov.client.ui.activities; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import com.devicehive.sspasov.client.R; import com.devicehive.sspasov.client.config.ClientConfig; import com.devicehive.sspasov.client.config.ClientPreferences; import com.devicehive.sspasov.client.utils.APIValidator; import com.devicehive.sspasov.client.utils.L; import com.github.clans.fab.FloatingActionButton; public class StartupConfigurationActivity extends AppCompatActivity implements View.OnClickListener { // --------------------------------------------------------------------------------------------- // Constants // --------------------------------------------------------------------------------------------- private static final String TAG = StartupConfigurationActivity.class.getSimpleName(); public static final String API = "api"; // --------------------------------------------------------------------------------------------- // Fields // --------------------------------------------------------------------------------------------- private EditText etApiEndpoint; private FloatingActionButton btnContinue; private ClientPreferences prefs; private boolean isEmpty; // --------------------------------------------------------------------------------------------- // Activity life cycle // --------------------------------------------------------------------------------------------- @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_startup_configuration); L.d(TAG, "onCreate()"); prefs = new ClientPreferences(this); setupToolbar(); setupViews(); //TODO: DEBUG ONLY if (L.isUsingDebugData()) { etApiEndpoint.setText("http://nn8170.pg.devicehive.com/api"); } } // --------------------------------------------------------------------------------------------- // Private methods // --------------------------------------------------------------------------------------------- private void setupViews() { etApiEndpoint = (EditText) findViewById(R.id.et_startup_api_endpoint); btnContinue = (FloatingActionButton) findViewById(R.id.btn_startup_continue); btnContinue.setOnClickListener(this); if (getIntent() != null && getIntent().hasExtra(API)) { etApiEndpoint.setText(getIntent().getStringExtra(API)); } } private void setupToolbar() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_startup_activity); toolbar.setTitle(getString(R.string.title_activity_startup_configuration)); toolbar.setTitleTextColor(getResources().getColor(android.R.color.white)); } // --------------------------------------------------------------------------------------------- // Override methods // --------------------------------------------------------------------------------------------- @Override public void onClick(View v) { L.d(TAG, "onClick()"); etApiEndpoint.setError(null); isEmpty = false; if (TextUtils.isEmpty(etApiEndpoint.getText())) { etApiEndpoint.setError(getString(R.string.empty_api_endpoint)); isEmpty = true; } if (!isEmpty) { if (APIValidator.validate(etApiEndpoint.getText().toString())) { prefs.setServerUrlSync(etApiEndpoint.getText().toString()); ClientConfig.API_ENDPOINT = prefs.getServerUrl(); Intent loginActivity = new Intent(this, LoginActivity.class); startActivity(loginActivity); finish(); } else { etApiEndpoint.setError(getString(R.string.invalid_url)); } } } }
sspasov/DeviceHiveClient
deviceHiveAndroidClient/src/main/java/com/devicehive/sspasov/client/ui/activities/StartupConfigurationActivity.java
Java
gpl-2.0
4,093
<?php /** * Element: Block * Displays a block with optionally a title and description * * @package NoNumber Framework * @version 14.10.3 * * @author Peter van Westen <peter@nonumber.nl> * @link http://www.nonumber.nl * @copyright Copyright © 2014 NoNumber All Rights Reserved * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL */ defined('_JEXEC') or die; require_once JPATH_PLUGINS . '/system/nnframework/helpers/text.php'; class JFormFieldNN_Block extends JFormField { public $type = 'Block'; private $params = null; protected function getLabel() { return ''; } protected function getInput() { $this->params = $this->element->attributes(); JHtml::stylesheet('nnframework/style.min.css', false, true); $title = $this->get('label'); $description = $this->get('description'); $start = $this->get('start', 0); $end = $this->get('end', 0); $hastitle = ($title || $description); JHtml::stylesheet('nnframework/style.min.css', false, true); $html = array(); if ($start || !$end) { $html[] = $this->getTitleBlock($title, $description, $start); if ($start || !$hastitle) { $html[] = '<div class="nn_panel"><div class="nn_block' . (!$hastitle ? ' nn_block_notitle' : '') . '">'; } if ($start) { $html[] = '<ul class="adminformlist"><li>'; } } if ($end || !$start) { if ($end) { $html[] = '<div style="clear: both;"></div></li></ul>'; } if ($end || !$hastitle) { $html[] = '<div style="clear: both;"></div>'; $html[] = '</div></div>'; } } return implode('', $html); } private function getTitleBlock($title = '', $description = '', $start = 0) { $nostyle = $this->get('nostyle', 0); if ($title) { $title = NNText::html_entity_decoder(JText::_($title)); } if ($description) { // variables $v1 = JText::_($this->get('var1')); $v2 = JText::_($this->get('var2')); $v3 = JText::_($this->get('var3')); $v4 = JText::_($this->get('var4')); $v5 = JText::_($this->get('var5')); $description = NNText::html_entity_decoder(trim(JText::sprintf($description, $v1, $v2, $v3, $v4, $v5))); $description = str_replace('span style="font-family:monospace;"', 'span class="nn_code"', $description); } $html = array(); if ($title) { if ($nostyle) { $html[] = '<div style="clear:both;"><div>'; } else { $class = 'nn_panel nn_panel_title'; if ($start || $description) { $class .= ' nn_panel_top'; } $html[] = '<div class="' . $class . '"><div class="nn_block nn_title">'; } $html[] = $title; $html[] = '<div style="clear: both;"></div>'; $html[] = '</div></div>'; } if ($description) { if ($nostyle) { $html[] = '<div style="clear:both;"><div>'; } else { $class = 'nn_panel nn_panel_description'; if ($start) { $class .= ' nn_panel_top'; } if ($title) { $class .= ' nn_panel_hastitle'; } $html[] = '<div class="' . $class . '"><div class="nn_block nn_title">'; } $html[] = $description; $html[] = '<div style="clear: both;"></div>'; $html[] = '</div></div>'; } return implode('', $html); } private function get($val, $default = '') { return (isset($this->params[$val]) && (string) $this->params[$val] != '') ? (string) $this->params[$val] : $default; } }
nazarkin659/best4hunting
plugins/system/nnframework/fields/block.php
PHP
gpl-2.0
3,410
/******************************************************* Copyright (C) 2013 James Higley 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ********************************************************/ #include "reportbase.h" #include "constants.h" #include "mmex.h" #include "mmSimpleDialogs.h" #include "mmDateRange.h" #include "model/Model_Account.h" mmPrintableBase::mmPrintableBase(const wxString& title) : m_title(title) , m_date_range(nullptr) , m_initial(true) , m_date_selection(0) , m_account_selection(0) , m_chart_selection(0) , accountArray_(nullptr) , m_only_active(false) , m_settings("") , m_begin_date(wxDateTime::Today()) , m_end_date(wxDateTime::Today()) { } mmPrintableBase::~mmPrintableBase() { Document j_doc; if (!j_doc.Parse(m_settings.c_str()).HasParseError()) { if (j_doc.HasMember("ID") && j_doc["ID"].IsInt()) { int id = j_doc["ID"].GetInt(); StringBuffer json_buffer; PrettyWriter<StringBuffer> json_writer(json_buffer); json_writer.StartObject(); json_writer.Key("ID"); json_writer.Int(id); if (m_date_selection) { json_writer.Key("REPORTPERIOD"); json_writer.Int(m_date_selection); } json_writer.Key("DATE1"); json_writer.String(m_begin_date.FormatISODate().c_str()); json_writer.Key("DATE2"); json_writer.String(m_end_date.FormatISODate().c_str()); if (m_account_selection) { json_writer.Key("ACCOUNTSELECTION"); json_writer.Int(m_account_selection); if (accountArray_ && !accountArray_->empty()) { json_writer.Key("ACCOUNTS"); json_writer.StartArray(); for (const auto& entry : *accountArray_) { json_writer.String(entry.c_str()); } json_writer.EndArray(); } } if (m_chart_selection) { json_writer.Key("CHART"); json_writer.Int(m_chart_selection); } json_writer.EndObject(); const wxString& rj_key = wxString::Format("REPORT_%d", id); const wxString& rj_value = json_buffer.GetString(); Model_Infotable::instance().Set(rj_key, rj_value); } } if (accountArray_) delete accountArray_; } void mmPrintableBase::date_range(const mmDateRange* date_range, int selection) { this->m_date_range = date_range; this->m_date_selection = selection; } const wxString mmPrintableBase::getAccountNames() const { wxString accountsMsg; if (accountArray_) { for (const auto& entry : *accountArray_) { accountsMsg.Append((accountsMsg.empty() ? "" : ", ") + entry); } } else { accountsMsg << _("All Accounts"); } if (accountsMsg.empty()) { accountsMsg = _("None"); } accountsMsg.Prepend(_("Accounts: ")); return accountsMsg; } void mmPrintableBase::setAccounts(int selection, const wxString& name) { if ((selection == 1) || (m_account_selection != selection)) { m_account_selection = selection; if (accountArray_) { delete accountArray_; accountArray_ = nullptr; } switch (selection) { case 0: // All Accounts break; case 1: // Select Accounts { wxArrayString* accountSelections = new wxArrayString(); Model_Account::Data_Set accounts = (m_only_active ? Model_Account::instance().find(Model_Account::ACCOUNTTYPE(Model_Account::all_type()[Model_Account::INVESTMENT], NOT_EQUAL) , Model_Account::STATUS(Model_Account::OPEN)) : Model_Account::instance().find(Model_Account::ACCOUNTTYPE(Model_Account::all_type()[Model_Account::INVESTMENT], NOT_EQUAL))); std::stable_sort(accounts.begin(), accounts.end(), SorterByACCOUNTNAME()); mmMultiChoiceDialog mcd(0, _("Choose Accounts"), m_title, accounts); if (mcd.ShowModal() == wxID_OK) { for (const auto &i : mcd.GetSelections()) { accountSelections->Add(accounts.at(i).ACCOUNTNAME); } } accountArray_ = accountSelections; } break; default: // All of Account type { wxArrayString* accountSelections = new wxArrayString(); auto accounts = Model_Account::instance().find(Model_Account::ACCOUNTTYPE(name) , Model_Account::STATUS(Model_Account::CLOSED, NOT_EQUAL)); for (const auto &i : accounts) { accountSelections->Add(i.ACCOUNTNAME); } accountArray_ = accountSelections; } } } } //---------------------------------------------------------------------- mmGeneralReport::mmGeneralReport(const Model_Report::Data* report) : mmPrintableBase(report->REPORTNAME) , m_report(report) { } wxString mmGeneralReport::getHTMLText() { return Model_Report::instance().get_html(this->m_report); } int mmGeneralReport::report_parameters() { int params = 0; const auto content = m_report->SQLCONTENT.Lower(); if (content.Contains("&begin_date") || content.Contains("&end_date")) params |= RepParams::DATE_RANGE; else if (content.Contains("&single_date")) params |= RepParams::SINGLE_DATE; return params; } mmPrintableBaseSpecificAccounts::mmPrintableBaseSpecificAccounts(const wxString& report_name, int sort_column) : mmPrintableBase(report_name) , accountArray_(0) { } const char * mmPrintableBase::m_template = ""; mmPrintableBaseSpecificAccounts::~mmPrintableBaseSpecificAccounts() { if (accountArray_) delete accountArray_; } void mmPrintableBaseSpecificAccounts::getSpecificAccounts() { wxArrayString* selections = new wxArrayString(); wxArrayString accounts; for (const auto &account : Model_Account::instance().all(Model_Account::COL_ACCOUNTNAME)) { if (Model_Account::type(account) == Model_Account::INVESTMENT) continue; accounts.Add(account.ACCOUNTNAME); } wxMultiChoiceDialog mcd(0, _("Choose Accounts"), m_title, accounts); wxButton* ok = static_cast<wxButton*>(mcd.FindWindow(wxID_OK)); if (ok) ok->SetLabel(_("&OK ")); wxButton* ca = static_cast<wxButton*>(mcd.FindWindow(wxID_CANCEL)); if (ca) ca->SetLabel(wxGetTranslation(g_CancelLabel)); if (mcd.ShowModal() == wxID_OK) { wxArrayInt arraySel = mcd.GetSelections(); for (size_t i = 0; i < arraySel.size(); ++i) { selections->Add(accounts.Item(arraySel[i])); } } if (accountArray_) delete accountArray_; accountArray_ = selections; } mm_html_template::mm_html_template(const wxString& arg_template): html_template(arg_template.ToStdWstring()) { this->load_context(); } void mm_html_template::load_context() { (*this)(L"TODAY") = wxDate::Now().FormatISODate(); for (const auto &r: Model_Infotable::instance().all()) (*this)(r.INFONAME.ToStdWstring()) = r.INFOVALUE; (*this)(L"INFOTABLE") = Model_Infotable::to_loop_t(); const Model_Currency::Data* currency = Model_Currency::GetBaseCurrency(); if (currency) currency->to_template(*this); } const wxString mmPrintableBase::getReportTitle() const { wxString title = m_title; if (m_date_range) { if (m_date_range->title().IsEmpty()) title += " - " + _("Custom"); else title += " - " + wxGetTranslation(m_date_range->title()); } return title; } const wxString mmPrintableBase::getFileName() const { wxString file_name = getReportTitle(); file_name.Replace(" - ", "-"); file_name.Replace(" ", "_"); file_name.Replace("/", "-"); return file_name; }
omalleypat/moneymanagerex
src/reports/reportbase.cpp
C++
gpl-2.0
8,721
#include "armsim.h" int main(int argc, char *argv[]) { printf("%d\n%s\n%s\n",argc+1,argv[0],argv[1]); return 0; }
nandhp/arm
echo.c
C
gpl-2.0
118
<?php /** * 消息分包 * * Date: 17-3-25 * Time: 下午8:40 * author :李华 yehong0000@163.com */ namespace NsqClient\lib\message; use NsqClient\lib\exception\MessageException; class Unpack { /** * 消息类型 */ const FRAME_TYPE_RESPONSE = 0;//响应 const FRAME_TYPE_ERROR = 1;//错误响应 const FRAME_TYPE_MESSAGE = 2;//消息响应 /** * 心跳查询 */ const HEARTBEAT = '_heartbeat_'; /** * 成功响应体 */ const OK = 'OK'; public static function getFrame($receive = '') { $frame = []; $type = self::getInt(substr($receive, 4, 4)); $frame['type'] = $type; switch ($type) { case self::FRAME_TYPE_RESPONSE: $frame['msg'] = substr($receive, 8); break; case self::FRAME_TYPE_ERROR: $frame['msg'] = substr($receive, 8); break; case self::FRAME_TYPE_MESSAGE: //纳秒级时间戳 $frame['timestamp'] = self::getLong(substr($receive, 8, 8)); //尝试次数 $frame['attempts'] = self::getShort(substr($receive, 16, 2)); //消息id $frame['id'] = self::getString(substr($receive, 18, 16)); //消息内容 $frame['msg'] = substr($receive, 34); break; default: throw new MessageException('未知的消息类型', -1); } return $frame; } /** * 消息类型检查 * * @param array $frame * @param $type * @param $response * * @return bool */ private static function checkMessage(array $frame, $type, $response = null) { return isset($frame['type'], $frame['msg']) && $frame['type'] === $type && ($response === NULL || $frame['msg'] === $response); } /** * 是否是响应消息 * * @param $frame * * @return bool */ public static function isResponse($frame) { return self::checkMessage($frame, self::FRAME_TYPE_RESPONSE); } /** * 是否是消费消息 * * @param $frame * * @return bool */ public static function isMessage($frame) { return self::checkMessage($frame, self::FRAME_TYPE_MESSAGE); } /** * 是否是心跳检查 * * @param $frame * * @return bool */ public static function isHeartbeat($frame) { //确切的说心跳检查不属于响应类型。也没有第4-8字节表示消息类型,但是此处为了处理方便将其归结为响应类型 return self::checkMessage($frame, self::FRAME_TYPE_RESPONSE, self::HEARTBEAT); } /** * 是否是成功响应 * * @param $frame * * @return bool */ public static function isOk($frame) { return self::checkMessage($frame, self::FRAME_TYPE_RESPONSE, self::OK); } /** * 是否是错误响应 * * @param $frame * * @return bool */ public static function isError($frame) { return self::checkMessage($frame, self::FRAME_TYPE_ERROR); } /** * 获取4字节整型数据 * * @param $param * * @return int */ private static function getInt($param) { $param = unpack('N', $param); $data = reset($param); if (PHP_INT_SIZE !== 4) { $data = sprintf('%u', $data); } return intval($data); } /** * @param $param * * @return mixed */ private static function getShort($param) { $param = unpack('n', $param); return reset($param); } /** * 解包8位长整型 * * @param $param * * @return string */ private static function getLong($param) { $hi = unpack('N', substr($param, 0, 4)); $lo = unpack('N', substr($param, 4)); $hi = sprintf("%u", $hi[1]); $lo = sprintf("%u", $lo[1]); return \bcadd(bcmul($hi, "4294967296"), $lo); } /** * 解包16位字符串 * * @param $param * * @return string */ private static function getString($param) { $temp = unpack("c16chars", $param); $out = ""; foreach ($temp as $v) { if ($v > 0) { $out .= chr($v); } } return $out; } }
tttlkkkl/nsq_swoole_client
src/lib/message/Unpack.php
PHP
gpl-2.0
4,537
// // Copyright (c) 2006 by Grant Yoshida -- Modified for Bandleader's purposes. // // Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu> // Creation Date: Thu May 11 21:10:02 PDT 2000 // Last Modified: Sat Oct 13 14:51:43 PDT 2001 (updated for ALSA 0.9 interface) // Last Modified: Thu Jun 24 02:38:04 PDT 2004 (frozen as ALSA 0.9 interface) // Filename: ...sig/maint/code/control/Sequencer_alsa09.cpp // Web Address: http://sig.sapp.org/src/sig/Sequencer_alsa09.cpp // Syntax: C++ // // Description: Basic MIDI input/output functionality for the // Linux ALSA raw midi devices. This class // is inherited by the classes MidiInPort_alsa and // MidiOutPort_alsa. // #if defined(LINUX) && defined(ALSA) #include "Collection.h" #include "Sequencer_alsa09.h" #include <unistd.h> #include <sys/ioctl.h> #include <fcntl.h> #include <string.h> #include <stdio.h> #include <dirent.h> /* for reading filename for MIDI info */ // use the following include for older alsa 0.9: //#include <sys/asoundlib.h> // use the following include for newer alsa 0.9: #include <alsa/asoundlib.h> #ifndef OLDCPP #include <iostream> #else #include <iostream.h> #endif typedef unsigned char uchar; // define static variables: int Sequencer_alsa09::class_count = 0; int Sequencer_alsa09::initialized = 0; // static variables for MIDI I/O information database int Sequencer_alsa09::indevcount = 0; int Sequencer_alsa09::outdevcount = 0; Collection<snd_rawmidi_t*> Sequencer_alsa09::rawmidi_in; Collection<snd_rawmidi_t*> Sequencer_alsa09::rawmidi_out; Collection<int> Sequencer_alsa09::midiincard; Collection<int> Sequencer_alsa09::midioutcard; Collection<int> Sequencer_alsa09::midiindevice; Collection<int> Sequencer_alsa09::midioutdevice; Collection<char*> Sequencer_alsa09::midiinname; Collection<char*> Sequencer_alsa09::midioutname; /////////////////////////////// // // Sequencer_alsa09::Sequencer_alsa09 -- // default value: autoOpen = 1; // Sequencer_alsa09::Sequencer_alsa09(int autoOpen) { if (class_count < 0) { cerr << "Unusual class instantiation count: " << class_count << endl; exit(1); } else if (class_count == 0) { buildInfoDatabase(); } // will not autoOpen class_count++; } ////////////////////////////// // // Sequencer_alsa09::~Sequencer_alsa09 -- // Sequencer_alsa09::~Sequencer_alsa09() { if (class_count == 1) { close(); removeInfoDatabase(); } else if (class_count <= 0) { cerr << "Unusual class instantiation count: " << class_count << endl; exit(1); } class_count--; } ////////////////////////////// // // Sequencer_alsa09::close -- close the sequencer device. The device // automatically closes once the program ends. // void Sequencer_alsa09::close(void) { int i; for (i=0; i<getNumInputs(); i++) { if (rawmidi_in[i] != NULL) { snd_rawmidi_close(rawmidi_in[i]); rawmidi_in[i] = NULL; } } for (i=0; i<getNumOutputs(); i++) { if (rawmidi_out[i] != NULL) { snd_rawmidi_close(rawmidi_out[i]); rawmidi_out[i] = NULL; } } } void Sequencer_alsa09::closeInput(int index) { if (index < 0 || index >= rawmidi_in.getSize()) { return; } if (rawmidi_in[index] != NULL) { snd_rawmidi_close(rawmidi_in[index]); rawmidi_in[index] = NULL; } } void Sequencer_alsa09::closeOutput(int index) { if (index < 0 || index >= rawmidi_out.getSize()) { return; } if (rawmidi_out[index] != NULL) { snd_rawmidi_close(rawmidi_out[index]); rawmidi_out[index] = NULL; } } ////////////////////////////// // // Sequencer_alsa09::displayInputs -- display a list of the // available MIDI input devices. // default values: out = cout, initial = "\t" // void Sequencer_alsa09::displayInputs(ostream& out, char* initial) { for (int i=0; i<getNumInputs(); i++) { out << initial << i << ": " << getInputName(i) << '\n'; } } ////////////////////////////// // // Sequencer_alsa09::displayOutputs -- display a list of the // available MIDI output devices. // default values: out = cout, initial = "\t" // void Sequencer_alsa09::displayOutputs(ostream& out, char* initial) { for (int i=0; i<getNumOutputs(); i++) { out << initial << i << ": " << getOutputName(i) << '\n'; } } ////////////////////////////// // // Sequencer_alsa09::getInputName -- returns a string to the name of // the specified input device. The string will remain valid as // long as there are any sequencer devices in existence. // const char* Sequencer_alsa09::getInputName(int aDevice) { if (initialized == 0) { buildInfoDatabase(); } return midiinname[aDevice]; } ////////////////////////////// // // Sequencer_alsa09::getNumInputs -- returns the total number of // MIDI inputs that can be used. // int Sequencer_alsa09::getNumInputs(void) { if (initialized == 0) { buildInfoDatabase(); } return indevcount; } ////////////////////////////// // // Sequencer_alsa09::getNumOutputs -- returns the total number of // MIDI inputs that can be used. // int Sequencer_alsa09::getNumOutputs(void) { if (initialized == 0) { buildInfoDatabase(); } return outdevcount; } ////////////////////////////// // // Sequencer_alsa09::getOutputName -- returns a string to the name of // the specified output device. The string will remain valid as // long as there are any sequencer devices in existence. // const char* Sequencer_alsa09::getOutputName(int aDevice) { if (initialized == 0) { buildInfoDatabase(); } return midioutname[aDevice]; } ////////////////////////////// // // Sequencer_alsa09::is_open -- returns true if the // sequencer device is open, false otherwise. // int Sequencer_alsa09::is_open(int mode, int index) { if (mode == 0) { // midi output if (rawmidi_out[index] != NULL) { return 1; } else { return 0; } } else { if (rawmidi_in[index] != NULL) { return 1; } else { return 0; } } } int Sequencer_alsa09::is_open_in(int index) { return is_open(1, index); } int Sequencer_alsa09::is_open_out(int index) { return is_open(0, index); } ///////////////////////////// // // Sequencer_alsa09::open -- returns true if the device // was successfully opended (or already opened) // int Sequencer_alsa09::open(int direction, int index) { if (direction == 0) { return openOutput(index); } else { return openInput(index); } } int Sequencer_alsa09::openInput(int index) { if (rawmidi_in[index] != NULL) { return 1; } int status; char devname[128] = {0}; sprintf(devname, "hw:%d,%d", midiincard[index], midiindevice[index]); status = snd_rawmidi_open(&rawmidi_in[index], NULL, devname, 0); if (status == 0) { return 1; } else { return 0; } } int Sequencer_alsa09::openOutput(int index) { if (rawmidi_out[index] != NULL) { return 1; } int status; char devname[128] = {0}; sprintf(devname, "hw:%d,%d", midioutcard[index], midioutdevice[index]); status = snd_rawmidi_open(NULL, &rawmidi_out[index], devname, 0); if (status == 0) { return 1; } else { return 0; } } ////////////////////////////// // // Sequencer_alsa09::read -- reads MIDI bytes and also stores the // device from which the byte was read from. Timing is not // saved from the device. If needed, then it would have to // be saved in this function, or just return the raw packet // data (use rawread function). // void Sequencer_alsa09::read(int dev, uchar* buf, int count) { if (is_open_in(dev)) { snd_rawmidi_read(rawmidi_in[dev], buf, count); } else { cout << "Warning: MIDI input " << dev << " is not open for reading" << endl; } } ////////////////////////////// // // Sequencer_alsa09::rebuildInfoDatabase -- rebuild the internal // database that keeps track of the MIDI input and output devices. // void Sequencer_alsa09::rebuildInfoDatabase(void) { removeInfoDatabase(); buildInfoDatabase(); } /////////////////////////////// // // Sequencer_alsa09::write -- Send a byte out the specified MIDI // port which can be either an internal or an external synthesizer. // int Sequencer_alsa09::write(int aDevice, int aByte) { uchar byte[1]; byte[0] = (uchar)aByte; return write(aDevice, byte, 1); } int Sequencer_alsa09::write(int aDevice, uchar* bytes, int count) { if (is_open_out(aDevice)) { int status = snd_rawmidi_write(rawmidi_out[aDevice], bytes, count); return status == count ? 1 : 0; } else { cout << "Warning: MIDI output " << aDevice << " is not open for writing" << endl; return 0; } return 0; } int Sequencer_alsa09::write(int aDevice, char* bytes, int count) { return write(aDevice, (uchar*)bytes, count); } int Sequencer_alsa09::write(int aDevice, int* bytes, int count) { uchar *newBytes; newBytes = new uchar[count]; for (int i=0; i<count; i++) { newBytes[i] = (uchar)bytes[i]; } int status = write(aDevice, newBytes, count); delete [] newBytes; return status; } /////////////////////////////////////////////////////////////////////////// // // private functions // ////////////////////////////// // // Sequencer_alsa09::buildInfoDatabase -- determines the number // of MIDI input and output devices available from // /dev/snd/midiC%dD%d, and determines their names. // void Sequencer_alsa09::buildInfoDatabase(void) { if (initialized) { return; } initialized = 1; if (indevcount != 0 || outdevcount != 0) { cout << "Error: Sequencer_alsa09 is already running" << endl; cout << "Indevcout = " << indevcount << " and " << " outdevcount = " << outdevcount << endl; exit(1); } indevcount = 0; outdevcount = 0; midiincard.setSize(0); midiincard.allowGrowth(); midioutcard.setSize(0); midioutcard.allowGrowth(); midiindevice.setSize(0); midiindevice.allowGrowth(); midioutdevice.setSize(0); midioutdevice.allowGrowth(); midiinname.setSize(0); midiinname.allowGrowth(); midioutname.setSize(0); midioutname.allowGrowth(); rawmidi_in.setSize(256); rawmidi_out.setSize(256); // read number of MIDI inputs/output available Collection<int> cards; Collection<int> devices; getPossibleMidiStreams(cards, devices); char devname[128] = {0}; // check for MIDI input streams int i; for (i=0; i<cards.getSize(); i++) { sprintf(devname, "hw:%d,%d", cards[i], devices[i]); if (snd_rawmidi_open(&rawmidi_in[indevcount], NULL, devname, 0) == 0){ midiincard.append(cards[i]); midiindevice.append(devices[i]); snd_rawmidi_close(rawmidi_in[indevcount]); rawmidi_in[indevcount] = NULL; indevcount++; } } for (i=0; i<rawmidi_in.getSize(); i++) { rawmidi_in[i] = NULL; } // check for MIDI output streams for (i=0; i<cards.getSize(); i++) { sprintf(devname, "hw:%d,%d", cards[i], devices[i]); if (snd_rawmidi_open(NULL, &rawmidi_out[outdevcount], devname, 0) == 0) { midioutcard.append(cards[i]); midioutdevice.append(devices[i]); snd_rawmidi_close(rawmidi_out[outdevcount]); rawmidi_out[indevcount] = NULL; outdevcount++; } } for (i=0; i<rawmidi_out.getSize(); i++) { rawmidi_out[i] = NULL; } char buffer[256] = {0}; char* temp; for (i=0; i<indevcount; i++) { sprintf(buffer, "MIDI input %d: card %d, device %d", i, midiincard[i], midiindevice[i]); temp = new char[strlen(buffer) + 1]; strcpy(temp, buffer); midiinname.append(temp); } for (i=0; i<outdevcount; i++) { sprintf(buffer, "MIDI output %d: card %d, device %d", i, midioutcard[i], midioutdevice[i]); temp = new char[strlen(buffer) + 1]; strcpy(temp, buffer); midioutname.append(temp); } midiincard.allowGrowth(0); midioutcard.allowGrowth(0); midiindevice.allowGrowth(0); midioutdevice.allowGrowth(0); midiinname.allowGrowth(0); midioutname.allowGrowth(0); rawmidi_in.allowGrowth(0); rawmidi_out.allowGrowth(0); } ////////////////////////////// // // Sequencer_alsa09::getInDeviceValue -- // int Sequencer_alsa09::getInDeviceValue(int aDevice) const { return midiindevice[aDevice]; } ////////////////////////////// // // Sequencer_alsa09::getInCardValue -- // int Sequencer_alsa09::getInCardValue(int aDevice) const { return midiincard[aDevice]; } ////////////////////////////// // // Sequencer_alsa09::getOutDeviceValue -- // int Sequencer_alsa09::getOutDeviceValue(int aDevice) const { return midioutdevice[aDevice]; } ////////////////////////////// // // Sequencer_alsa09::getOutCardValue -- // int Sequencer_alsa09::getOutCardValue(int aDevice) const { return midioutcard[aDevice]; } ////////////////////////////// // // Sequencer_alsa09::removeInfoDatabase -- // void Sequencer_alsa09::removeInfoDatabase(void) { if (rawmidi_in.getSize() != 0) { close(); } if (rawmidi_out.getSize() != 0) { close(); } rawmidi_in.setSize(0); rawmidi_out.setSize(0); midiincard.setSize(0); midioutcard.setSize(0); midiindevice.setSize(0); midioutdevice.setSize(0); int i; for (i=0; i<midiinname.getSize(); i++) { if (midiinname[i] != NULL) { delete [] midiinname[i]; } } for (i=0; i<midioutname.getSize(); i++) { if (midioutname[i] != NULL) { delete [] midioutname[i]; } } indevcount = 0; outdevcount = 0; initialized = 0; } ////////////////////////////// // // getPossibleMidiStreams -- read the directory /dev/snd for files // that match the pattern midiC%dD%d, and extract the card/device // numbers from these filenames. // void Sequencer_alsa09::getPossibleMidiStreams(Collection<int>& cards, Collection<int>& devices) { cards.setSize(0); devices.setSize(0); cards.allowGrowth(1); devices.allowGrowth(1); DIR* dir = opendir("/dev/snd"); if (dir == NULL) { cout << "Error determining ALSA MIDI info: no directory called /dev/snd" << endl; exit(1); } // read each file in the directory and store information if it is a MIDI dev int card; int device; struct dirent *dinfo; dinfo = readdir(dir); int count; while (dinfo != NULL) { if (strncmp(dinfo->d_name, "midi", 4) == 0) { count = sscanf(dinfo->d_name, "midiC%dD%d", &card, &device); if (count == 2) { cards.append(card); devices.append(device); } } dinfo = readdir(dir); } closedir(dir); cards.allowGrowth(0); devices.allowGrowth(0); } #endif /* LINUX and ALSA */ // md5sum: 8ccf0e750be06aeea90cdc8a7cc4499c - Sequencer_alsa09.cpp =css= 20030102
google-code/bandleader
src/improv/improv/Sequencer_alsa09.cpp
C++
gpl-2.0
15,254
<?php /** * TomatoCMS * * LICENSE * * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://www.gnu.org/licenses/gpl-2.0.txt * 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 license@tomatocms.com so we can send you a copy immediately. * * @copyright Copyright (c) 2009-2010 TIG Corporation (http://www.tig.vn) * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2 * @version $Id: RequestLog.php 2057 2010-04-07 03:18:22Z huuphuoc $ * @since 2.0.5 */ interface Tomato_Modules_Core_Model_Interface_RequestLog { public function create($log); }
tucq88/os_thoibaonh
app/modules/core/model/interface/RequestLog.php
PHP
gpl-2.0
833
#ifndef DEF_TRANSMOGRIFICATION_H #define DEF_TRANSMOGRIFICATION_H #define PRESETS // comment this line to disable preset feature totally #define MAX_OPTIONS 25 // do not alter class Item; class Player; class WorldSession; struct ItemTemplate; enum TransmogTrinityStrings // Language.h might have same entries, appears when executing SQL, change if needed { LANG_ERR_TRANSMOG_OK = 11100, // change this LANG_ERR_TRANSMOG_INVALID_SLOT, LANG_ERR_TRANSMOG_INVALID_SRC_ENTRY, LANG_ERR_TRANSMOG_MISSING_SRC_ITEM, LANG_ERR_TRANSMOG_MISSING_DEST_ITEM, LANG_ERR_TRANSMOG_INVALID_ITEMS, LANG_ERR_TRANSMOG_NOT_ENOUGH_MONEY, LANG_ERR_TRANSMOG_NOT_ENOUGH_TOKENS, LANG_ERR_UNTRANSMOG_OK, LANG_ERR_UNTRANSMOG_NO_TRANSMOGS, #ifdef PRESETS LANG_PRESET_ERR_INVALID_NAME, #endif }; class Transmogrification { private: Transmogrification() { }; ~Transmogrification() { }; Transmogrification(const Transmogrification&); Transmogrification& operator=(const Transmogrification&); public: static Transmogrification* instance() { // Thread safe in C++11 standard static Transmogrification instance; return &instance; } #ifdef PRESETS bool EnableSetInfo; uint32 SetNpcText; bool EnableSets; uint8 MaxSets; float SetCostModifier; int32 SetCopperCost; void LoadPlayerSets(Player* player); void PresetTransmog(Player* player, Item* itemTransmogrified, uint32 fakeEntry, uint8 slot); #endif bool EnableTransmogInfo; uint32 TransmogNpcText; // Use IsAllowed() and IsNotAllowed() // these are thread unsafe, but assumed to be static data so it should be safe std::set<uint32> Allowed; std::set<uint32> NotAllowed; float ScaledCostModifier; int32 CopperCost; bool RequireToken; uint32 TokenEntry; uint32 TokenAmount; bool AllowPoor; bool AllowCommon; bool AllowUncommon; bool AllowRare; bool AllowEpic; bool AllowLegendary; bool AllowArtifact; bool AllowHeirloom; bool AllowMixedArmorTypes; bool AllowMixedWeaponTypes; bool AllowFishingPoles; bool IgnoreReqRace; bool IgnoreReqClass; bool IgnoreReqSkill; bool IgnoreReqSpell; bool IgnoreReqLevel; bool IgnoreReqEvent; bool IgnoreReqStats; bool IsAllowed(uint32 entry) const; bool IsNotAllowed(uint32 entry) const; bool IsAllowedQuality(uint32 quality) const; bool IsRangedWeapon(uint32 Class, uint32 SubClass) const; void LoadConfig(bool reload); // thread unsafe std::string GetItemIcon(uint32 entry, uint32 width, uint32 height, int x, int y) const; std::string GetSlotIcon(uint8 slot, uint32 width, uint32 height, int x, int y) const; const char * GetSlotName(uint8 slot, WorldSession* session) const; std::string GetItemLink(Item* item, WorldSession* session) const; std::string GetItemLink(uint32 entry, WorldSession* session) const; uint32 GetFakeEntry(const Item* item); void UpdateItem(Player* player, Item* item) const; void DeleteFakeEntry(Player* player, Item* item); void SetFakeEntry(Player* player, Item* item, uint32 entry); TransmogTrinityStrings Transmogrify(Player* player, uint64 itemGUID, uint8 slot, bool no_cost = false); bool CanTransmogrifyItemWithItem(Player* player, ItemTemplate const* destination, ItemTemplate const* source) const; bool SuitableForTransmogrification(Player* player, ItemTemplate const* proto) const; // bool CanBeTransmogrified(Item const* item); // bool CanTransmogrify(Item const* item); uint32 GetSpecialPrice(ItemTemplate const* proto) const; std::vector<uint64> GetItemList(const Player* player) const; }; #define sTransmogrification Transmogrification::instance() #endif
yolinlin/trinitycore
src/server/scripts/Custom/Transmogrification.h
C
gpl-2.0
3,789
/* ---------------------------------------------------------------------------------- BrainBay - OpenSource Application for realtime BodySignalProcessing & HCI with the OpenEEG hardware, GPL 2003-2010 Author: Chris Veigl, contact: chris@shifz.org Co-Authors: Jeremy Wilkerson (Modules: AND, OR, NOT, WAV, CORELLATION, EVALUATOR) Lester John (Module MATLAB-transfer) Stephan Gerhard (QDS parser) Franz Stobl ( NIA support ) Credits: Jim Peters (digital filter works), Jeff Molofee (OpenGL-tutorial), John Roark (SkinDialog) AllenD (COM-Port control), Aleksandar B. Samardz (Expression Evaluator Library) Craig Peacock (PortTalk IO driver) the used non-standard Libraries are: Multimedia and OpenGL: winmm.lib opengl32.lib glu32.lib vfw32.lib glaux.lib SDL (Simple Direct Media Layer): SDL.lib SDL_net.lib SDL_sound.lib modplug.lib OpenCV - Intels's Computer Vision Library: cv.lib cvcam.lib cxcore.lib highgui.lib Matlab Engine (only in special Matlab Release): libeng.lib libmx.lib Jim Peters's Filter Library: fidlib.lib (http://uazu.net) Skinned Dialog by John Roark: skinstyle.lib (http://www.codeproject.com/dialog/skinstyle.asp) GNU LibMatheval by Aleksandar B. Samardz: matheval.lib (http://www.gnu.org/software/libmatheval) Video Input Camera Capture Library: http://muonics.net/school/spring05/videoInput/ Project-Site: http://brainbay.lo-res.org Link to the OpenEEG-Project: http://openeeg.sf.net ------------------------------------------------------------------------------------- MODULE: brainBay.cpp - Main Module creates the Main Window, handle Menu events, provides a mouse-oriented interface for moving and linking objects 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; See the GNU General Public License for more details. -------------------------------------------------------------------------------------*/ #include "brainBay.h" #include "ob_osci.h" #include "ob_skindialog.h" #include "ob_neurobit.h" LRESULT CALLBACK AboutDlgHandler( HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam ); LRESULT CALLBACK SCALEDlgHandler( HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam ); LRESULT CALLBACK COLORDlgHandler(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); //extern int lk_work (void); extern NEUROBITOBJ * NB_OBJ; int check_keys(void) { static int mode=0; if (mode) { if (!GetAsyncKeyState(116) && !GetAsyncKeyState(117) && !GetAsyncKeyState(118) && !GetAsyncKeyState(119)) mode=0; else return(0); } if (GetAsyncKeyState(118)) {mode=1; SendMessage(ghWndMain,WM_COMMAND,IDM_PLAY,0);} else if (GetAsyncKeyState(119)) {mode=1;SendMessage(ghWndMain,WM_COMMAND,IDM_STOP,0);} else if (GetAsyncKeyState(116)) {mode=1; SendMessage(ghWndStatusbox,WM_COMMAND,IDC_DESIGN,0);} else if (GetAsyncKeyState(117)) {mode=1; SendMessage(ghWndStatusbox,WM_COMMAND,IDC_HIDE,0);} return(0); } /* // used to convert capture files int conv_file(void) { HANDLE hFile,hFile2; BOOL bSuccess = FALSE; DWORD dwRead,dwWritten; unsigned char buffer[3]; unsigned char buffer2[3]; int num=0; hFile = CreateFile( (LPCTSTR) "c:\\capture3.txt", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if (hFile == INVALID_HANDLE_VALUE) printf ("file1 open error\n"); hFile2 = CreateFile((LPCTSTR) "c:\\cp.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile2 == INVALID_HANDLE_VALUE) printf ("file1 open error\n"); if ((hFile != INVALID_HANDLE_VALUE) && (hFile2 != INVALID_HANDLE_VALUE)) { do { ReadFile(hFile, (unsigned char *) buffer , 2, &dwRead, NULL); if (dwRead==2) { if ((buffer[0]>='0') && (buffer[0]<='9')) buffer2[0]=(buffer[0]-'0') * 16; else if ((buffer[0]>='A') && (buffer[0]<='F')) buffer2[0]=(buffer[0]-'A'+10) * 16; if ((buffer[1]>='0') && (buffer[1]<='9')) buffer2[0]+=(buffer[1]-'0'); else if ((buffer[1]>='A') && (buffer[1]<='F')) buffer2[0]+=(buffer[1]-'A'+10); printf ("%d,",buffer2[0]); WriteFile(hFile2, (unsigned char * )buffer2, 1, &dwWritten, NULL); num++; } printf ("read %d bytes\n",num); } while (dwRead==2); } else printf ("file open error\n"); CloseHandle(hFile); CloseHandle(hFile2); printf("done !\n"); return(0); } */ //----------------------------------------------------------------------- // FUNCTION WinMain // PURPOSE: application entry point, register MainWindow class //----------------------------------------------------------------------- int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { MSG msg; hInst=hInstance; // conv_file(); init_path(); register_classes(hInstance); if(!(ghWndMain=CreateWindow("brainBay_Class", "BrainBay", WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, 10, 20, 900, 520, NULL, NULL, hInstance, NULL))) critical_error("can't create main Window"); else {GLOBAL.left=20;GLOBAL.top=20;GLOBAL.right=900;GLOBAL.bottom=520; } ShowWindow( ghWndMain, SW_SHOWNORMAL ); UpdateWindow( ghWndMain ); create_logfile(); write_logfile("BrainBay start."); GlobalInitialize(); ghWndStatusbox=CreateDialog(hInst, (LPCTSTR)IDD_STATUSBOX, ghWndMain, (DLGPROC)StatusDlgHandler); if(!(ghWndDesign=CreateWindow("Design_Class", "Design", WS_CLIPSIBLINGS | WS_CAPTION | WS_THICKFRAME | WS_CHILD | WS_HSCROLL | WS_VSCROLL ,GLOBAL.design_left, GLOBAL.design_top, GLOBAL.design_right-GLOBAL.design_left, GLOBAL.design_bottom-GLOBAL.design_top, ghWndMain, NULL, hInst, NULL))) report_error("can't create Design Window"); else { SCROLLINFO si; ZeroMemory(&si, sizeof(si)); si.cbSize = sizeof(si); si.fMask = SIF_TRACKPOS|SIF_RANGE|SIF_TRACKPOS; GetScrollInfo(ghWndDesign, SB_HORZ, &si); si.nMax=5000; si.nMin=0; si.nPos=0; si.nTrackPos=0; SetScrollInfo(ghWndDesign, SB_HORZ, &si,TRUE); GetScrollInfo(ghWndDesign, SB_VERT, &si); si.nMax=5000; si.nMin=0; si.nPos=0; si.nTrackPos=0; SetScrollInfo(ghWndDesign, SB_VERT, &si,TRUE); ShowWindow( ghWndDesign, TRUE ); UpdateWindow( ghWndDesign ); } if (GLOBAL.startup) { if (!load_configfile(GLOBAL.configfile)) report_error("Could not load Config File"); //else sort_objects(); } update_status_window(); //////////// // main message loop while (TRUE) { check_keys(); if(!GetMessage(&msg, NULL, 0, 0)) break; TranslateMessage(&msg); DispatchMessage(&msg); if(!PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { if (DRAW.particles) InvalidateRect(ghWndAnimation,NULL,FALSE); } } return msg.wParam; } // // function: MainWndHandler(HWND, unsigned, WORD, LONG) // // purpose: make initialisations (globals, Def-TTY settings) // create Toolbox Dialog // // process Menu Selections // load/save Config // play/capture Archive // open midi-device // change com settings // connect/disconnect to EEG-amp // load/save Config // // scale and paint the channel-oscilloscope // // // LRESULT CALLBACK MainWndHandler(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; char sztemp[256]; switch( message ) { case WM_CREATE: break; case WM_ENABLE: if ((wParam==TRUE) && (NB_OBJ != NULL)) { NB_OBJ->update_channelinfo(); NB_OBJ=NULL; } break; case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Menüauswahlen analysieren: switch( wmId ) { case IDM_NEWCONFIG: stop_timer(); TTY.read_pause=1; //BreakDownCommPort(); CAPTFILE.do_read=0; close_captfile(); if (ghWndAnimation!=NULL) SendMessage(ghWndAnimation,WM_CLOSE,0,0); ghWndAnimation=NULL; close_toolbox(); write_logfile("new config: deleting all objects."); while (GLOBAL.objects>0) free_object(0); deviceobject=NULL; GLOBAL.showdesign=TRUE; ShowWindow(ghWndDesign,TRUE); SetWindowPos(ghWndDesign,HWND_TOP,0,0,0,0,SWP_DRAWFRAME|SWP_NOMOVE|SWP_NOSIZE); SetDlgItemText(ghWndStatusbox,IDC_DESIGN,"Hide Design"); GLOBAL.hidestatus=FALSE; ShowWindow(ghWndStatusbox,TRUE); SetWindowText(ghWndMain,"BrainBay"); GLOBAL.configfile[0]=0; init_system_time(); PACKET.readstate=0; GLOBAL.session_length=0; SetDlgItemText(ghWndStatusbox,IDC_STATUS,"ready."); SetDlgItemInt(ghWndStatusbox,IDC_SAMPLINGRATE,PACKETSPERSECOND,0); SetDlgItemText(ghWndStatusbox,IDC_STATUS,"Configuration loaded"); SetDlgItemText(ghWndStatusbox,IDC_TIME,"0.0"); SetDlgItemText(ghWndStatusbox,IDC_JUMPPOS,"0.0"); SetDlgItemText(ghWndStatusbox,IDC_SESSLEN,"0.0"); SendMessage(GetDlgItem(ghWndStatusbox,IDC_SESSIONPOS),TBM_SETPOS,TRUE,(LONG)0); SendMessage(GetDlgItem(ghWndStatusbox,IDC_SESSIONPOS),TBM_SETSELEND,TRUE,(LONG)0); SendMessage(GetDlgItem(ghWndStatusbox,IDC_SESSIONPOS),TBM_SETSELSTART,TRUE,(LONG)0); InvalidateRect(ghWndDesign,NULL,TRUE); InvalidateRect(ghWndMain,NULL,TRUE); break; case IDM_SAVECONFIG: { char configfilename[MAX_PATH]; int save_toolbox=GLOBAL.showtoolbox; close_toolbox(); GLOBAL.showtoolbox=save_toolbox; strcpy(configfilename,GLOBAL.resourcepath); if (GLOBAL.configfile[0]==0) strcat(configfilename,"CONFIGURATIONS\\*.con"); else strcpy(configfilename,GLOBAL.configfile); if (open_file_dlg(hWnd,configfilename, FT_CONFIGURATION, OPEN_SAVE)) { if (!save_configfile(configfilename)) report_error("Could not save Config File"); else { char * d_name,new_name[80]; write_logfile("configruation saved."); d_name=configfilename; while (strstr(d_name,"\\")) d_name=strstr(d_name,"\\")+1; strcpy(new_name,"BrainBay - ");strcat(new_name,d_name); SetWindowText(ghWndMain,new_name); } } if (GLOBAL.showtoolbox!=-1) { actobject=objects[GLOBAL.showtoolbox]; actobject->make_dialog(); } } break; case IDM_LOADCONFIG: { char configfilename[MAX_PATH]; close_toolbox(); strcpy(configfilename,GLOBAL.resourcepath); strcat(configfilename,"CONFIGURATIONS\\*.con"); if (open_file_dlg(hWnd,configfilename, FT_CONFIGURATION, OPEN_LOAD)) { write_logfile("load config: free existing objects."); if (!load_configfile(configfilename)) report_error("Could not load Config File"); else sort_objects(); } } break; case IDM_ABOUT: close_toolbox(); DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)AboutDlgHandler); break; case IDM_HELP: { char tmpfile [250]; close_toolbox(); strcpy(tmpfile,GLOBAL.resourcepath); strcat(tmpfile,"BrainBay-user_manual.pdf"); ShellExecute(0, "open", tmpfile, NULL, NULL, SW_SHOWNORMAL); } break; case IDM_VIEWLASTLOGFILE: { char tmpfile [250]; close_toolbox(); strcpy(tmpfile,GLOBAL.resourcepath); strcat(tmpfile,"bbay.log"); ShellExecute(0, "open", tmpfile, NULL, NULL, SW_SHOWNORMAL); } break; case IDM_EXIT: DestroyWindow( hWnd ); break; case IDM_PLAY: SendMessage(ghWndStatusbox,WM_COMMAND, IDC_RUNSESSION,0); break; case IDM_STOP: SendMessage(ghWndStatusbox,WM_COMMAND, IDC_STOPSESSION,0); break; case IDM_NEUROSERVER: strcpy(sztemp,GLOBAL.resourcepath); strcat(sztemp,"NETWORK\\nsd.exe"); ShellExecute(hWnd, "open", sztemp, NULL, NULL, SW_SHOWNORMAL); break; case IDM_READEDF: { char edffilename[MAX_PATH]; close_toolbox(); strcpy(edffilename,GLOBAL.resourcepath); strcat(edffilename,"ARCHIVES\\*.edf"); if (open_file_dlg(hWnd,edffilename, FT_EDF, OPEN_LOAD)) { strcpy(sztemp,GLOBAL.resourcepath); strcat(sztemp,"NETWORK\\readedf.exe"); ShellExecute(hWnd, NULL, sztemp, edffilename, NULL, SW_SHOWNORMAL); } } break; case IDM_EDITCOLORS: close_toolbox(); display_toolbox(CreateDialog(hInst, (LPCTSTR)IDD_EDITCOLORBOX, ghWndStatusbox, (DLGPROC)COLORDlgHandler)); break; case IDM_EDITSCALES: close_toolbox(); display_toolbox(CreateDialog(hInst, (LPCTSTR)IDD_EDITSCALEBOX, ghWndStatusbox, (DLGPROC)SCALEDlgHandler)); break; case IDM_SETTINGS: if (ghWndSettings==NULL) ghWndSettings=CreateDialog(hInst, (LPCTSTR)IDD_SETTINGSBOX, ghWndStatusbox, (DLGPROC)SETTINGSDlgHandler); else SetForegroundWindow(ghWndSettings); break; case IDM_DEVICESETTINGS: if (deviceobject) { close_toolbox(); actobject=deviceobject; // GLOBAL.showtoolbox=find_object(devicebox); actobject->make_dialog(); if (actobject->displayWnd) SetWindowPos(actobject->displayWnd,HWND_TOP,0,0,0,0,SWP_DRAWFRAME|SWP_NOMOVE|SWP_NOSIZE); } else report ("No Amplifier Device present in the design"); break; case IDM_INSERTMODEEG: if (!count_objects(OB_EEG)) create_object(OB_EEG); break; case IDM_INSERTMIDI: create_object(OB_MIDI); break; case IDM_INSERTSPECTRUM: create_object(OB_FFT); break; case IDM_INSERTTHRESHOLD: create_object(OB_THRESHOLD); break; case IDM_INSERTFILTER: create_object(OB_FILTER); break; case IDM_INSERTMAGNITUDE:create_object(OB_MAGNITUDE); break; case IDM_INSERTPARTICLE:create_object(OB_PARTICLE); break; case IDM_INSERTOSCI:create_object(OB_OSCI); break; case IDM_INSERTTRANSLATE:create_object(OB_TRANSLATE); break; case IDM_INSERTSIGNAL:create_object(OB_SIGNAL); break; case IDM_INSERTAND:create_object(OB_AND); break; case IDM_INSERTOR:create_object(OB_OR); break; case IDM_INSERTNOT:create_object(OB_NOT); break; case IDM_INSERTWAV: if (!count_objects(OB_WAV)) create_object(OB_WAV); else report_error("Currently only one Sound player is supported."); break; case IDM_INSERTTCPRECEIVER:create_object(OB_TCP_RECEIVER); break; case IDM_INSERTDOKU:create_object(OB_DOKU); break; case IDM_INSERTEVAL:create_object(OB_EVAL); break; case IDM_INSERTAVI:create_object(OB_AVI); break; case IDM_INSERTAVERAGE:create_object(OB_AVERAGE); break; case IDM_INSERTCORR:create_object(OB_CORR); break; case IDM_INSERTEDFWRITER:create_object(OB_EDF_WRITER); break; case IDM_INSERTTCPSENDER:create_object(OB_TCP_SENDER); break; case IDM_INSERTEDFREADER:create_object(OB_EDF_READER); break; case IDM_INSERTCOMPARE:create_object(OB_COMPARE); break; case IDM_INSERTBALLGAME:create_object(OB_BALLGAME); break; case IDM_INSERTMIXER4:create_object(OB_MIXER4); break; case IDM_INSERTMOUSE:create_object(OB_MOUSE); break; case IDM_INSERTERPDETECT:create_object(OB_ERPDETECT); break; case IDM_INSERTCOM_WRITER:create_object(OB_COM_WRITER); break; case IDM_INSERTCAM: if (!count_objects(OB_CAM)) create_object(OB_CAM); break; case IDM_INSERTINTEGRATE:create_object(OB_INTEGRATE); break; case IDM_INSERTDEBOUNCE:create_object(OB_DEBOUNCE); break; case IDM_INSERTSAMPLE_HOLD:create_object(OB_SAMPLE_HOLD); break; case IDM_INSERTCONSTANT:create_object(OB_CONSTANT); break; case IDM_INSERTMATLAB:create_object(OB_MATLAB); break; case IDM_INSERTCOUNTER:create_object(OB_COUNTER); break; case IDM_INSERTSKINDIALOG: if (!count_objects(OB_SKINDIALOG)) create_object(OB_SKINDIALOG); break; case IDM_INSERTFILE_WRITER:create_object(OB_FILE_WRITER); break; case IDM_INSERTDEVIATION:create_object(OB_DEVIATION); break; case IDM_INSERTMCIPLAYER:create_object(OB_MCIPLAYER); break; case IDM_INSERTKEYSTRIKE:create_object(OB_KEYSTRIKE); break; case IDM_INSERTPEAKDETECT:create_object(OB_PEAKDETECT); break; case IDM_INSERTSPELLER:create_object(OB_SPELLER); break; case IDM_INSERTMARTINI:create_object(OB_MARTINI); break; case IDM_INSERTFILE_READER:create_object(OB_FILE_READER); break; case IDM_INSERTPORT_IO:create_object(OB_PORT_IO); break; case IDM_INSERTARRAY3600:create_object(OB_ARRAY3600); break; case IDM_INSERTCOMREADER:create_object(OB_COMREADER); break; case IDM_INSERTOPTIMA: if (!count_objects(OB_NEUROBIT)) create_object(OB_NEUROBIT); break; case IDM_INSERTMIN:create_object(OB_MIN); break; case IDM_INSERTMAX:create_object(OB_MAX); break; case IDM_INSERTROUND:create_object(OB_ROUND); break; case IDM_INSERTDIFFERENTIATE:create_object(OB_DIFFERENTIATE); break; case IDM_INSERTDELAY:create_object(OB_DELAY); break; case IDM_INSERTLIMITER:create_object(OB_LIMITER); break; case IDM_COPY: if (actobject) { copy_object=actobject; if ((copy_object->type!=OB_EEG)&&(copy_object->type!=OB_WAV)&&(copy_object->type!=OB_CAM) &&(copy_object->type!=OB_SKINDIALOG)&&(copy_object->type!=OB_NEUROBIT)) { HANDLE hFile; char tmpfile[256]; create_object(copy_object->type); strcpy(tmpfile,GLOBAL.resourcepath); strcat(tmpfile,"tmp_copy.con"); hFile = CreateFile(tmpfile, GENERIC_WRITE, 0, NULL,CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile != INVALID_HANDLE_VALUE) { copy_object->save(hFile); save_property(hFile,"end Object",P_END,NULL); CloseHandle(hFile); } hFile = CreateFile(tmpfile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if(hFile != INVALID_HANDLE_VALUE) { load_next_config_buffer(hFile); actobject->load(hFile); CloseHandle(hFile); DeleteFile(tmpfile); } actobject->xPos+=10; actobject->yPos+=10; } close_toolbox(); } break; default: return DefWindowProc( hWnd, message, wParam, lParam ); } break; case WM_ACTIVATE: { /* char t[50]; static int cn=0; cn++; sprintf(t,"%d:%d,%d",cn,HIWORD(lParam),LOWORD(lParam)); //==WA_CLICKACTIVE)) SendDlgItemMessage(ghWndStatusbox,IDC_LIST2, LB_ADDSTRING, 0, (LPARAM) t); SendDlgItemMessage(ghWndStatusbox,IDC_LIST2, LB_SETCURSEL, SendDlgItemMessage(ghWndStatusbox,IDC_LIST2, LB_GETCOUNT, 0, 0)-1, 0); UpdateWindow(ghWndStatusbox); */ if ((LOWORD(lParam)==WA_CLICKACTIVE) || (HIWORD(lParam)==WA_CLICKACTIVE)) SetWindowPos(ghWndMain,HWND_TOP,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE); SetFocus(ghWndMain); } break; case WM_ACTIVATEAPP: { /* char t[50]; static int cn=0; cn++; sprintf(t,"%d:%d,%d",cn,HIWORD(lParam),LOWORD(lParam)); //==WA_CLICKACTIVE)) SendDlgItemMessage(ghWndStatusbox,IDC_LIST2, LB_ADDSTRING, 0, (LPARAM) t); SendDlgItemMessage(ghWndStatusbox,IDC_LIST2, LB_SETCURSEL, SendDlgItemMessage(ghWndStatusbox,IDC_LIST2, LB_GETCOUNT, 0, 0)-1, 0); UpdateWindow(ghWndStatusbox); */ // if ((LOWORD(lParam)==1828) || (LOWORD(lParam)==964)) //SetWindowPos(ghWndMain,HWND_TOP,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE); SetWindowPos(ghWndMain,0,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE); // return DefWindowProc( hWnd, message, wParam, lParam ); } break; case WM_KEYDOWN: if (lParam==KEY_DELETE ) SendMessage(ghWndDesign, message,wParam,lParam); break; case WM_SIZE: if (wParam== SIZE_MAXIMIZED) { GLOBAL.main_maximized=lParam; ShowWindow(ghWndStatusbox,TRUE); GLOBAL.hidestatus=FALSE; if (GLOBAL.session_length==0) SetWindowPos(ghWndStatusbox, ghWndMain, 4, HIWORD(lParam)+15, LOWORD(lParam)-8,HIWORD(lParam), 0); else SetWindowPos(ghWndStatusbox, ghWndMain, 4, HIWORD(lParam)-20, LOWORD(lParam)-8,HIWORD(lParam), 0); } else if (wParam== SIZE_RESTORED) { WINDOWPLACEMENT wndpl; GetWindowPlacement(ghWndMain, &wndpl); GLOBAL.top=wndpl.rcNormalPosition.top; GLOBAL.left=wndpl.rcNormalPosition.left; GLOBAL.right=wndpl.rcNormalPosition.right; GLOBAL.bottom=wndpl.rcNormalPosition.bottom; GLOBAL.main_maximized=0; update_status_window(); } else if (wParam== SIZE_MINIMIZED) { ShowWindow(ghWndStatusbox,FALSE); GLOBAL.hidestatus=TRUE; } break; case WM_MOVE: { WINDOWPLACEMENT wndpl; GetWindowPlacement(ghWndMain, &wndpl); GLOBAL.top=wndpl.rcNormalPosition.top; GLOBAL.left=wndpl.rcNormalPosition.left; GLOBAL.right=wndpl.rcNormalPosition.right; GLOBAL.bottom=wndpl.rcNormalPosition.bottom; update_status_window(); } break; //case WM_PAINT: // break; case WM_DESTROY: actobject=0; GlobalCleanup(); PostQuitMessage( 0 ); break; case WM_INPUT: if ((TTY.CONNECTED) && (!GLOBAL.loading)) ReadNIA( wParam, lParam); // NIA Daten vorhanden: auslesen return(TRUE); default: return DefWindowProc( hWnd, message, wParam, lParam ); } return 0; }
dadymax/BrainBayRaiseUp
brainBay.cpp
C++
gpl-2.0
22,374
<!DOCTYPE html> <html xml:lang="en-US" lang="en-US" xmlns="http://www.w3.org/1999/xhtml"> <head lang="en-US"> <title>My Family Tree - Page, Marvin Ray</title> <meta charset="UTF-8" /> <meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" /> <meta name ="apple-mobile-web-app-capable" content="yes" /> <meta name="generator" content="Gramps 4.2.2 http://gramps-project.org/" /> <meta name="author" content="" /> <link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" /> <link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" /> <link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" /> <link href="../../../css/ancestortree.css" media="screen" rel="stylesheet" type="text/css" /> </head> <body> <div id="header"> <h1 id="SiteTitle">My Family Tree</h1> </div> <div class="wrapper" id="nav" role="navigation"> <div class="container"> <ul class="menu" id="dropmenu"> <li class = "CurrentSection"><a href="../../../individuals.html" title="Individuals">Individuals</a></li> <li><a href="../../../index.html" title="Surnames">Surnames</a></li> <li><a href="../../../places.html" title="Places">Places</a></li> <li><a href="../../../sources.html" title="Sources">Sources</a></li> <li><a href="../../../media.html" title="Media">Media</a></li> <li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li> </ul> </div> </div> <div class="content" id="IndividualDetail"> <h3>Page, Marvin Ray<sup><small> <a href="#sref1">1</a></small></sup></h3> <div id="summaryarea"> <table class="infolist"> <tr> <td class="ColumnAttribute">Birth Name</td> <td class="ColumnValue"> Page, Marvin Ray </td> </tr> <tr> <td class="ColumnAttribute">Gramps&nbsp;ID</td> <td class="ColumnValue">I0897</td> </tr> <tr> <td class="ColumnAttribute">Gender</td> <td class="ColumnValue">male</td> </tr> </table> </div> <div class="subsection" id="events"> <h4>Events</h4> <table class="infolist eventlist"> <thead> <tr> <th class="ColumnEvent">Event</th> <th class="ColumnDate">Date</th> <th class="ColumnPlace">Place</th> <th class="ColumnDescription">Description</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnEvent"> Birth </td> <td class="ColumnDate">1941-07-30</td> <td class="ColumnPlace"> <a href="../../../plc/b/d/HYWJQCL563RRLWZ4DB.html" title="Wheeling, WV-OH, USA"> Wheeling, WV-OH, USA </a> </td> <td class="ColumnDescription"> Birth of Page, Marvin Ray </td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> <tr> <td class="ColumnEvent"> LVG </td> <td class="ColumnDate">&nbsp;</td> <td class="ColumnPlace">&nbsp;</td> <td class="ColumnDescription"> Custom FTW5 tag to specify LIVING not specified in GEDCOM 5.5 </td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> </tbody> </table> </div> <div class="subsection" id="parents"> <h4>Parents</h4> <table class="infolist"> <thead> <tr> <th class="ColumnAttribute">Relation to main person</th> <th class="ColumnValue">Name</th> <th class="ColumnValue">Relation within this family (if not by birth)</th> </tr> </thead> <tbody> </tbody> <tr> <td class="ColumnAttribute">Father</td> <td class="ColumnValue"> <a href="../../../ppl/q/q/A32KQCOX3HHWYTDRQQ.html">Page, Vernett Gail<span class="grampsid"> [I0456]</span></a> </td> </tr> <tr> <td class="ColumnAttribute">Mother</td> <td class="ColumnValue"> <a href="../../../ppl/o/n/4CBKQC8IISHZA54PNO.html">Norman, Dorothy Louise<span class="grampsid"> [I0892]</span></a> </td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Brother</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/t/t/RCBKQCI7AZ2E2OL3TT.html">Page, Dwayne Alan<span class="grampsid"> [I0893]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Sister</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/1/v/4EBKQCSLW07FX8UKV1.html">Page, Sylvia Louise<span class="grampsid"> [I0895]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/8/b/AFBKQCQB4SH8L948B8.html">Page, Marvin Ray<span class="grampsid"> [I0897]</span></a></td> <td class="ColumnValue"></td> </tr> </table> </div> <div class="subsection" id="families"> <h4>Families</h4> <table class="infolist"> <tr class="BeginFamily"> <td class="ColumnType">&nbsp</td> <td class="ColumnAttribute">&nbsp</td> <td class="ColumnValue"><a href="" title="Family of Page, Marvin Ray and Morton, Gail Darlene">Family of Page, Marvin Ray and Morton, Gail Darlene<span class="grampsid"> [F0275]</span></a></td> </tr> <tr class="BeginFamily"> <td class="ColumnType">Married</td> <td class="ColumnAttribute">Wife</td> <td class="ColumnValue"> <a href="../../../ppl/t/l/8GBKQCXC1R0Y1FCVLT.html">Morton, Gail Darlene<span class="grampsid"> [I0898]</span></a> </td> </tr> <tr> <td class="ColumnType">&nbsp;</td> <td class="ColumnAttribute">&nbsp;</td> <td class="ColumnValue"> <table class="infolist eventlist"> <thead> <tr> <th class="ColumnEvent">Event</th> <th class="ColumnDate">Date</th> <th class="ColumnPlace">Place</th> <th class="ColumnDescription">Description</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnEvent"> Marriage </td> <td class="ColumnDate">&nbsp;</td> <td class="ColumnPlace"> <a href="../../../plc/f/z/K3CLQC5F9SA8N3L3ZF.html" title="Muscatine, Muscatine, IA, USA"> Muscatine, Muscatine, IA, USA </a> </td> <td class="ColumnDescription"> Marriage of Page, Marvin Ray and Morton, Gail Darlene </td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> </tbody> </table> </td> <tr> <td class="ColumnType">&nbsp;</td> <td class="ColumnAttribute">Children</td> <td class="ColumnValue"> <ol> <li> <a href="../../../ppl/8/3/YLBKQCX69OR70TOI38.html">Page, Debra Dale<span class="grampsid"> [I0907]</span></a> </li> <li> <a href="../../../ppl/q/g/CNBKQCFJFLYKYYPGQ.html">Page, Darvin Ray<span class="grampsid"> [I0909]</span></a> </li> </ol> </td> </tr> </tr> </table> </div> <div class="subsection" id="pedigree"> <h4>Pedigree</h4> <ol class="pedigreegen"> <li> <a href="../../../ppl/q/q/A32KQCOX3HHWYTDRQQ.html">Page, Vernett Gail<span class="grampsid"> [I0456]</span></a> <ol> <li class="spouse"> <a href="../../../ppl/o/n/4CBKQC8IISHZA54PNO.html">Norman, Dorothy Louise<span class="grampsid"> [I0892]</span></a> <ol> <li> <a href="../../../ppl/t/t/RCBKQCI7AZ2E2OL3TT.html">Page, Dwayne Alan<span class="grampsid"> [I0893]</span></a> </li> <li> <a href="../../../ppl/1/v/4EBKQCSLW07FX8UKV1.html">Page, Sylvia Louise<span class="grampsid"> [I0895]</span></a> </li> <li class="thisperson"> Page, Marvin Ray <ol class="spouselist"> <li class="spouse"> <a href="../../../ppl/t/l/8GBKQCXC1R0Y1FCVLT.html">Morton, Gail Darlene<span class="grampsid"> [I0898]</span></a> <ol> <li> <a href="../../../ppl/8/3/YLBKQCX69OR70TOI38.html">Page, Debra Dale<span class="grampsid"> [I0907]</span></a> </li> <li> <a href="../../../ppl/q/g/CNBKQCFJFLYKYYPGQ.html">Page, Darvin Ray<span class="grampsid"> [I0909]</span></a> </li> </ol> </li> </ol> </li> </ol> </li> </ol> </li> </ol> </div> <div class="subsection" id="tree"> <h4>Ancestors</h4> <div id="treeContainer" style="width:735px; height:602px;"> <div class="boxbg male AncCol0" style="top: 269px; left: 6px;"> <a class="noThumb" href="../../../ppl/8/b/AFBKQCQB4SH8L948B8.html"> Page, Marvin Ray </a> </div> <div class="shadow" style="top: 274px; left: 10px;"></div> <div class="bvline" style="top: 301px; left: 165px; width: 15px"></div> <div class="gvline" style="top: 306px; left: 165px; width: 20px"></div> <div class="boxbg male AncCol1" style="top: 119px; left: 196px;"> <a class="noThumb" href="../../../ppl/q/q/A32KQCOX3HHWYTDRQQ.html"> Page, Vernett Gail </a> </div> <div class="shadow" style="top: 124px; left: 200px;"></div> <div class="bvline" style="top: 151px; left: 180px; width: 15px;"></div> <div class="gvline" style="top: 156px; left: 185px; width: 20px;"></div> <div class="bhline" style="top: 151px; left: 180px; height: 150px;"></div> <div class="gvline" style="top: 156px; left: 185px; height: 150px;"></div> <div class="bvline" style="top: 151px; left: 355px; width: 15px"></div> <div class="gvline" style="top: 156px; left: 355px; width: 20px"></div> <div class="boxbg male AncCol2" style="top: 44px; left: 386px;"> <a class="noThumb" href="../../../ppl/v/6/RNXJQCOC61TJFQUQ6V.html"> Page, Andrew Vincent </a> </div> <div class="shadow" style="top: 49px; left: 390px;"></div> <div class="bvline" style="top: 76px; left: 370px; width: 15px;"></div> <div class="gvline" style="top: 81px; left: 375px; width: 20px;"></div> <div class="bhline" style="top: 76px; left: 370px; height: 75px;"></div> <div class="gvline" style="top: 81px; left: 375px; height: 75px;"></div> <div class="bvline" style="top: 76px; left: 545px; width: 15px"></div> <div class="gvline" style="top: 81px; left: 545px; width: 20px"></div> <div class="boxbg male AncCol3" style="top: 7px; left: 576px;"> <a class="noThumb" href="../../../ppl/q/g/9HUJQC6ONNW8SMSKGQ.html"> Page, David </a> </div> <div class="shadow" style="top: 12px; left: 580px;"></div> <div class="bvline" style="top: 39px; left: 560px; width: 15px;"></div> <div class="gvline" style="top: 44px; left: 565px; width: 20px;"></div> <div class="bhline" style="top: 39px; left: 560px; height: 37px;"></div> <div class="gvline" style="top: 44px; left: 565px; height: 37px;"></div> <div class="boxbg female AncCol3" style="top: 81px; left: 576px;"> <a class="noThumb" href="../../../ppl/4/s/EIUJQCVLRWQ1G8CS4.html"> Douglas, Elizabeth </a> </div> <div class="shadow" style="top: 86px; left: 580px;"></div> <div class="bvline" style="top: 113px; left: 560px; width: 15px;"></div> <div class="gvline" style="top: 118px; left: 565px; width: 20px;"></div> <div class="bhline" style="top: 76px; left: 560px; height: 37px;"></div> <div class="gvline" style="top: 81px; left: 565px; height: 37px;"></div> <div class="boxbg female AncCol2" style="top: 194px; left: 386px;"> <a class="noThumb" href="../../../ppl/t/n/ZQAKQCOD490M89DYNT.html"> Zimmerman, Edith Irene </a> </div> <div class="shadow" style="top: 199px; left: 390px;"></div> <div class="bvline" style="top: 226px; left: 370px; width: 15px;"></div> <div class="gvline" style="top: 231px; left: 375px; width: 20px;"></div> <div class="bhline" style="top: 151px; left: 370px; height: 75px;"></div> <div class="gvline" style="top: 156px; left: 375px; height: 75px;"></div> <div class="boxbg female AncCol1" style="top: 419px; left: 196px;"> <a class="noThumb" href="../../../ppl/o/n/4CBKQC8IISHZA54PNO.html"> Norman, Dorothy Louise </a> </div> <div class="shadow" style="top: 424px; left: 200px;"></div> <div class="bvline" style="top: 451px; left: 180px; width: 15px;"></div> <div class="gvline" style="top: 456px; left: 185px; width: 20px;"></div> <div class="bhline" style="top: 301px; left: 180px; height: 150px;"></div> <div class="gvline" style="top: 306px; left: 185px; height: 150px;"></div> </div> </div> <div class="subsection" id="sourcerefs"> <h4>Source References</h4> <ol> <li> <a href="../../../src/x/a/X5TJQC9JXU4RKT6VAX.html" title="Import from test2.ged" name ="sref1"> Import from test2.ged <span class="grampsid"> [S0003]</span> </a> </li> </ol> </div> </div> <div class="fullclear"></div> <div id="footer"> <p id="createdate"> Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.2 on 2015-12-25<br />Last change was the 2007-07-26 08:34:25 </p> <p id="copyright"> </p> </div> </body> </html>
belissent/testing-example-reports
gramps42/gramps/example_NAVWEB0/ppl/8/b/AFBKQCQB4SH8L948B8.html
HTML
gpl-2.0
13,648
#ifndef ES705_RWDB_H #define ES705_RWDB_H /* MQ100 states */ #define MQ100_STATE_RESET (0) #define MQ100_STATE_NORMAL (1) struct es705_rwdb_device_callbacks; /** * Register rdb callbacks * @param callbacks - structure containing * callbacks from es705 rdb/wdb driver * @return */ int es705_rdb_register(const struct es705_rwdb_device_callbacks *callbacks); /** * Note: can we expect all of these * functions to be executed in process context? */ struct es705_rwdb_device_callbacks { /** * cookie using for callbacks */ void *priv; /** * Callback when firmware has been downloaded, device has been * initialized and is ready for rdb/wdb * * @param es705_priv - es705 private data. this cookie will be * returned with all calls to es705_wdb * @return on success, a pointer to the callee's private data, * this cookie must be returned with every other callback * on failure, return NULL */ void * (*probe)(void *es705_priv); /** * This function is called when audience driver * has detected the an interrupt from the device * @param priv - cookie returned from probe() */ void (*intr)(void *priv); /** * Callback whenever the device state changes. * e.g. when firmware has been downloaded * Use MQ100_STATE_XXX values for state param. * @param priv - cookie returned from probe() */ void (*status)(void *priv, u8 state); }; /* * Writes buf to es705 using wdb * this function will prepend 0x802F 0xffff * @param: buf - wdb data * @param: len - length * @return: no. of bytes written */ int es705_wdb(const void *buf, int len); /* * Reads buf from es705 using rdb * @param: buf - rdb data Max Size supported * - 2*PAGE_SIZE Ensure buffer allocated has enough space * for rdb * @param: id - type specifier * @return: no. of bytes read */ int es705_rdb(void *buf, int id); int es705_rdb_register(const struct es705_rwdb_device_callbacks *callbacks); #endif
meizuosc/m75
kernel/sound/soc/codecs/audience/es705-api.h
C
gpl-2.0
1,953
/********************************************************************** ** Copyright (C) 2001 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #ifndef LIBFLASH_PLUGIN_H #define LIBFLASH_PLUGIN_H #include <qstring.h> #include <qapplication.h> #include "flash.h" #include <qpe/mediaplayerplugininterface.h> class LibFlashPlugin : public MediaPlayerDecoder { public: LibFlashPlugin(); ~LibFlashPlugin() { close(); } const char *pluginName() { return "LibFlashPlugin: " PLUGIN_NAME " " FLASH_VERSION_STRING; } const char *pluginComment() { return "This is the libflash library: " PLUGIN_NAME " " FLASH_VERSION_STRING; } double pluginVersion() { return 1.0; } bool isFileSupported( const QString& fileName ) { return fileName.right(4) == ".swf"; } bool open( const QString& fileName ); bool close() { FlashClose( file ); file = NULL; return TRUE; } bool isOpen() { return file != NULL; } const QString &fileInfo() { return strInfo = qApp->translate( "MediaPlayer", "No Information Available", "media plugin text" ); } // If decoder doesn't support audio then return 0 here int audioStreams() { return 1; } int audioChannels( int /*stream*/ ) { return 2; } int audioFrequency( int /*stream*/ ) { return 44100; } int audioSamples( int /*stream*/ ) { return 1000000; } bool audioSetSample( long sample, int stream ); long audioGetSample( int stream ); //bool audioReadMonoSamples( short *output, long samples, long& samplesRead, int stream ); //bool audioReadStereoSamples( short *output, long samples, long& samplesRead, int stream ); bool audioReadSamples( short *output, int channels, long samples, long& samplesRead, int stream ); //bool audioReadSamples( short *output, int channel, long samples, int stream ); //bool audioReReadSamples( short *output, int channel, long samples, int stream ); // If decoder doesn't support video then return 0 here int videoStreams(); int videoWidth( int stream ); int videoHeight( int stream ); double videoFrameRate( int stream ); int videoFrames( int stream ); bool videoSetFrame( long frame, int stream ); long videoGetFrame( int stream ); bool videoReadFrame( unsigned char **output_rows, int in_x, int in_y, int in_w, int in_h, ColorFormat color_model, int stream ); bool videoReadScaledFrame( unsigned char **output_rows, int in_x, int in_y, int in_w, int in_h, int out_w, int out_h, ColorFormat color_model, int stream ); bool videoReadYUVFrame( char *y_output, char *u_output, char *v_output, int in_x, int in_y, int in_w, int in_h, int stream ); // Profiling double getTime(); // Ignore if these aren't supported bool setSMP( int cpus ); bool setMMX( bool useMMX ); // Capabilities bool supportsAudio() { return TRUE; } bool supportsVideo() { return TRUE; } bool supportsYUV() { return TRUE; } bool supportsMMX() { return TRUE; } bool supportsSMP() { return TRUE; } bool supportsStereo() { return TRUE; } bool supportsScaling() { return TRUE; } private: FlashHandle file; FlashDisplay *fd; QString strInfo; }; #endif
opieproject/opie
core/multimedia/opieplayer/libflash/libflashplugin.h
C
gpl-2.0
3,843
<?php /** * Elgg Feedback plugin * Feedback interface for Elgg sites * * @package Feedback * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU Public License version 2 * @author Prashant Juvekar * @copyright Prashant Juvekar * @link http://www.linkedin.com/in/prashantjuvekar * * for Elgg 1.8 by iionly * iionly@gmx.de */ $icon = elgg_view('icon/default', array('entity' => $vars['entity'], 'size' => 'small')); $controls .= elgg_view("output/confirmlink",array('href' => $vars['url'] . "action/feedback/delete?guid=" . $vars['entity']->guid, 'confirm' => elgg_echo('deleteconfirm'), 'class' => 'elgg-icon elgg-icon-delete')); $mood = elgg_echo ( "feedback:mood:" . $vars['entity']->mood ); $about = elgg_echo ( "feedback:about:" . $vars['entity']->about ); $page = "Unknown"; if ( !empty($vars['entity']->page) ) { $page = $vars['entity']->page; $page = "<a href='" . $page . "'>" . $page . "</a>"; } $info = "<div style='float:left;width:25%'><b>".elgg_echo('feedback:list:mood').": </b>" . $mood . "</div>"; $info .= "<div style='float:left;width:25%'><b>".elgg_echo('feedback:list:about').": </b>" . $about . "</div>"; $info .= $controls . "<br />"; $info .= "<b>".elgg_echo('feedback:list:page').": </b>" . $page . "<br />"; $info .= "<b>".elgg_echo('feedback:list:from').": </b>" . $vars['entity']->id . "<br />"; $info .= nl2br($vars['entity']->txt); echo elgg_view('page/components/image_block', array('image' => $icon, 'body' => $info, 'class' => 'submitted-feedback'));
weSPOT/wespot_iwe
mod/feedback/views/default/feedback/listing.php
PHP
gpl-2.0
1,561
/* Copyright (C) 2007 Martin Richards 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, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.Windows.Forms; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Drawing; using WikiFunctions.Controls; namespace WikiFunctions.Parse { /// <summary> /// Provides a form and functions for setting and applying multiple find and replacements on a text string. /// </summary> public partial class FindandReplace : Form { public FindandReplace() { InitializeComponent(); } private string EditSummary = ""; private readonly HideText Remove = new HideText(true, false, true); private readonly List<Replacement> ReplacementList = new List<Replacement>(); private bool ApplyDefault; private bool ApplyDefaultFormatting { get { return ApplyDefault; } set { ApplyDefault = value; dataGridView1.AllowUserToAddRows = value; } } /// <summary> /// Returns proper direction arrow depending on locale /// Currently returns only LTR arrow due to direction conflict /// demonstrated by http://ar.wikipedia.org/w/index.php?diff=1192871 /// </summary> public static string Arrow { get { return " → ";//Variables.RTL ? " ← " : " → "; } } private static Replacement RowToReplacement(DataGridViewRow dataGridRow) { Replacement rep = new Replacement { Enabled = ((bool) dataGridRow.Cells["enabled"].FormattedValue) }; if (dataGridRow.Cells["replace"].Value == null) dataGridRow.Cells["replace"].Value = ""; string f = Encode(dataGridRow.Cells["find"].Value.ToString()); string r = Encode(dataGridRow.Cells["replace"].Value.ToString()); if (!(bool)dataGridRow.Cells["regex"].FormattedValue) { f = Regex.Escape(f); rep.IsRegex = false; } else rep.IsRegex = true; rep.Find = f; rep.Replace = r; rep.RegularExpressionOptions = RegexOptions.None; if (!(bool)dataGridRow.Cells["casesensitive"].FormattedValue) rep.RegularExpressionOptions = rep.RegularExpressionOptions | RegexOptions.IgnoreCase; if ((bool)dataGridRow.Cells["multi"].FormattedValue) rep.RegularExpressionOptions = rep.RegularExpressionOptions | RegexOptions.Multiline; if ((bool)dataGridRow.Cells["single"].FormattedValue) rep.RegularExpressionOptions = rep.RegularExpressionOptions | RegexOptions.Singleline; rep.Comment = (string)dataGridRow.Cells["comment"].FormattedValue ?? ""; return rep; } public void MakeList() { ReplacementList.Clear(); foreach (DataGridViewRow dataGridRow in dataGridView1.Rows) { if (dataGridRow.IsNewRow) continue; if (dataGridRow.Cells["find"].Value == null) continue; ReplacementList.Add(RowToReplacement(dataGridRow)); } } private static readonly Regex NewlineRegex = new Regex(@"(?<!\\)\\n", RegexOptions.Compiled), TabulationRegex = new Regex(@"(?<!\\)\\t", RegexOptions.Compiled); private static string PrepareReplacePart(string replace) { replace = NewlineRegex.Replace(replace, "\n"); return TabulationRegex.Replace(replace, "\t"); } /// <summary> /// /// </summary> public int NoOfReplacements { get { return ReplacementList.Count; } } /// <summary> /// /// </summary> public bool HasReplacements { get { return NoOfReplacements != 0; } } /// <summary> /// Applies a series of defined find and replacements to the supplied article text. /// </summary> /// <param name="articleText">The wiki text of the article.</param> /// <param name="editSummary"></param> /// <param name="strTitle"></param> /// <returns>The modified article text.</returns> public string MultipleFindAndReplace(string articleText, string strTitle, ref string editSummary) { if (!HasReplacements) return articleText; EditSummary = ""; RemovedSummary = ""; if (chkIgnoreMore.Checked) articleText = Remove.HideMore(articleText); else if (chkIgnoreLinks.Checked) articleText = Remove.Hide(articleText); foreach (Replacement rep in ReplacementList) { if (!rep.Enabled) continue; articleText = PerformFindAndReplace(rep.Find, rep.Replace, articleText, strTitle, rep.RegularExpressionOptions); } if (chkIgnoreMore.Checked) articleText = Remove.AddBackMore(articleText); else if (chkIgnoreLinks.Checked) articleText = Remove.AddBack(articleText); if (chkAddToSummary.Checked) { if (!string.IsNullOrEmpty(EditSummary)) editSummary = ", Replaced: " + EditSummary.Trim(); if (!string.IsNullOrEmpty(RemovedSummary)) editSummary += ", Removed: " + RemovedSummary.Trim(); } return articleText; } private string Summary = ""; private string RemovedSummary = ""; private string PerformFindAndReplace(string findThis, string replaceWith, string articleText, string articleTitle, RegexOptions rOptions) { findThis = Tools.ApplyKeyWords(articleTitle, findThis); replaceWith = Tools.ApplyKeyWords(articleTitle, PrepareReplacePart(replaceWith)); Regex findRegex = new Regex(findThis, rOptions); MatchCollection matches = findRegex.Matches(articleText); if (matches.Count > 0) { articleText = findRegex.Replace(articleText, replaceWith); if (matches[0].Value != matches[0].Result(replaceWith)) { if (!string.IsNullOrEmpty(matches[0].Result(replaceWith))) { Summary = matches[0].Value + Arrow + matches[0].Result(replaceWith); if (matches.Count > 1) Summary += " (" + matches.Count + ")"; EditSummary += Summary + ", "; } else { RemovedSummary += matches[0].Value; if (matches.Count > 1) RemovedSummary += " (" + matches.Count + ")"; RemovedSummary += ", "; } } } return articleText; } private void btnDone_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; } private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { lnkWpRE.LinkVisited = true; Tools.OpenENArticleInBrowser("Regular_expression", false); } private void lblMsdn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { lblMsdn.LinkVisited = true; Tools.OpenURLInBrowser("http://msdn.microsoft.com/en-us/library/hs600312.aspx"); } private void btnClear_Click(object sender, EventArgs e) { if (MessageBox.Show("Do you really want to clear the whole table?", "Really clear?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) Clear(); } /// <summary> /// Clears the set replacements. /// </summary> public void Clear() { ReplacementList.Clear(); dataGridView1.Rows.Clear(); } private static string Encode(string text) { return text.Replace("\\r\\n", "\r\n"); } private static string Decode(string text) { return text.Replace("\n", "\\r\\n"); } #region loading/saving /// <summary> /// Adds a find and replacement task. /// </summary> /// <param name="find">The string to find.</param> /// <param name="replaceWith">The replacement string.</param> /// <param name="caseSensitive"></param> /// <param name="isRegex"></param> /// <param name="multiline"></param> /// <param name="singleline"></param> /// <param name="lineEnabled"></param> /// <param name="lineComment"></param> public void AddNew(string find, string replaceWith, bool caseSensitive, bool isRegex, bool multiline, bool singleline, bool lineEnabled, string lineComment) { dataGridView1.Rows.Add(find, replaceWith, caseSensitive, isRegex, multiline, singleline, lineEnabled, lineComment); if (!lineEnabled) dataGridView1.Rows[dataGridView1.Rows.Count - 1].DefaultCellStyle.BackColor = Color.LightGray; MakeList(); } /// <summary> /// /// </summary> /// <param name="r"></param> public void AddNew(Replacement r) { bool caseSens = !r.RegularExpressionOptions.ToString().Contains("IgnoreCase"); bool multiine = r.RegularExpressionOptions.ToString().Contains("Multiline"); bool singleLine = r.RegularExpressionOptions.ToString().Contains("Singleline"); if (!r.IsRegex) dataGridView1.Rows.Add(Regex.Unescape(Decode(r.Find)), Decode(r.Replace), caseSens, r.IsRegex, multiine, singleLine, r.Enabled, r.Comment); else dataGridView1.Rows.Add(Decode(r.Find), Decode(r.Replace), caseSens, r.IsRegex, multiine, singleLine, r.Enabled, r.Comment); if (!r.Enabled) dataGridView1.Rows[dataGridView1.Rows.Count - 1].DefaultCellStyle.BackColor = Color.LightGray; ReplacementList.Add(r); } /// <summary> /// /// </summary> /// <param name="rList"></param> public void AddNew(List<Replacement> rList) { foreach (Replacement r in rList) { AddNew(r); } } /// <summary> /// Gets the find and replace settings. /// </summary> public List<Replacement> GetList() { return ReplacementList; } /// <summary> /// Gets or sets whether the replacements ignore external links and images /// </summary> public bool IgnoreLinks { get { return chkIgnoreLinks.Checked; } set { chkIgnoreLinks.Checked = value; } } /// <summary> /// Gets or sets whether the replacements ignore headings, internal link targets, templates, and refs /// </summary> public bool IgnoreMore { get { return chkIgnoreMore.Checked; } set { chkIgnoreMore.Checked = value; } } /// <summary> /// Gets or sets whether the summary should be used /// </summary> public bool AppendToSummary { get { return chkAddToSummary.Checked; } set { chkAddToSummary.Checked = value; } } /// <summary> /// Gets or sets whether the replacements are made after or before the general fixes /// </summary> public bool AfterOtherFixes { get { return chkAfterOtherFixes.Checked; } set { chkAfterOtherFixes.Checked = value; } } #endregion #region Events private void ChangeChecked(string col, int value) { dataGridView1.EndEdit(); foreach (DataGridViewRow r in dataGridView1.Rows) { if (r.IsNewRow) break; r.Cells[col].Value = value; } } private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex < 0) return; dataGridView1.EndEdit(); if (!(bool)dataGridView1.Rows[e.RowIndex].Cells["enabled"].FormattedValue) dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightGray; else dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White; dataGridView1.EndEdit(); } private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) { if (!ApplyDefaultFormatting) return; dataGridView1.Rows[e.RowIndex].Cells["enabled"].Value = 1; } private void FindandReplace_Shown(object sender, EventArgs e) { ApplyDefaultFormatting = true; } private void FindandReplace_FormClosing(object sender, FormClosingEventArgs e) { ApplyDefaultFormatting = false; MakeList(); Hide(); } #endregion #region Context menu private void allCaseSensitiveToolStripMenuItem_Click(object sender, EventArgs e) { ChangeChecked("casesensitive", 1); } private void uncheckAllCaseSensitiveToolStripMenuItem_Click(object sender, EventArgs e) { ChangeChecked("casesensitive", 0); } private void checkAllRegularExpressionsToolStripMenuItem_Click(object sender, EventArgs e) { ChangeChecked("regex", 1); } private void uncheckAllRegularExpressionsToolStripMenuItem_Click(object sender, EventArgs e) { ChangeChecked("regex", 0); } private void checkAllMultlineToolStripMenuItem_Click(object sender, EventArgs e) { ChangeChecked("multi", 1); } private void uncheckAllMultilineToolStripMenuItem_Click(object sender, EventArgs e) { ChangeChecked("multi", 0); } private void enableAllToolStripMenuItem_Click(object sender, EventArgs e) { ChangeChecked("enabled", 1); } private void disableAllToolStripMenuItem_Click(object sender, EventArgs e) { ChangeChecked("enabled", 0); } private void checkAllSinglelineToolStripMenuItem_Click(object sender, EventArgs e) { ChangeChecked("single", 1); } private void uncheckAllSinglelineToolStripMenuItem_Click(object sender, EventArgs e) { ChangeChecked("single", 0); } private void deleteRowToolStripMenuItem_Click(object sender, EventArgs e) { while (dataGridView1.SelectedRows.Count > 0) { if (dataGridView1.Rows[dataGridView1.SelectedRows[0].Index].IsNewRow) { dataGridView1.SelectedRows[0].Selected = false; continue; } dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index); } } private void FindAndReplaceContextMenu_Opening(object sender, System.ComponentModel.CancelEventArgs e) { deleteRowToolStripMenuItem.Enabled = (dataGridView1.SelectedRows.Count > 0); testRegexToolStripMenuItem.Enabled = createRetfRuleToolStripMenuItem.Enabled = ((dataGridView1.CurrentRow != null) && ((bool)dataGridView1.CurrentRow.Cells["regex"].FormattedValue)); } private void testRegexToolStripMenuItem_Click(object sender, EventArgs e) { DataGridViewRow row = dataGridView1.CurrentRow; if (row == null) return; using (RegexTester t = new RegexTester(true)) { t.Find = (string)row.Cells["find"].Value; t.Replace = (string)row.Cells["replace"].Value; t.Multiline = (bool)row.Cells["multi"].FormattedValue; t.Singleline = (bool)row.Cells["single"].FormattedValue; t.IgnoreCase = !(bool)row.Cells["casesensitive"].FormattedValue; if (Variables.MainForm != null && Variables.MainForm.EditBox.Enabled) t.ArticleText = Variables.MainForm.EditBox.Text; if (t.ShowDialog(this) != DialogResult.OK) return; row.Cells["find"].Value = t.Find; row.Cells["replace"].Value = t.Replace; row.Cells["multi"].Value = t.Multiline; row.Cells["single"].Value = t.Singleline; row.Cells["casesensitive"].Value = !t.IgnoreCase; } } #endregion private void chkIgnoreMore_CheckedChanged(object sender, EventArgs e) { if (chkIgnoreMore.Checked) chkIgnoreLinks.Checked = true; } private void chkIgnoreLinks_CheckedChanged(object sender, EventArgs e) { if (!chkIgnoreLinks.Checked) chkIgnoreMore.Checked = false; } private void txtSearch_TextChanged(object sender, EventArgs e) { btnSearch.Enabled = txtSearch.Text.Length > 0; } private void btnSearch_Click(object sender, EventArgs e) { for (int i = 0; i < 2; i++) for (int j = 0; j < dataGridView1.Rows.Count; j++) { DataGridViewCell c = dataGridView1.Rows[j].Cells[i]; if (c.Value != null && c.Value.ToString().Contains(txtSearch.Text)) { dataGridView1.ClearSelection(); dataGridView1.EndEdit(); dataGridView1.CurrentCell = c; if (!c.Displayed) dataGridView1.FirstDisplayedScrollingRowIndex = c.RowIndex; dataGridView1.Focus(); dataGridView1.BeginEdit(false); } } } private void txtSearch_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == 13) { e.Handled = true; btnSearch_Click(null, null); } } private void addRowToolStripMenuItem_Click(object sender, EventArgs e) { if (dataGridView1.SelectedRows.Count > 0) dataGridView1.Rows.Insert(dataGridView1.SelectedRows[0].Index, 1); else dataGridView1.Rows.Add(); } private void moveUpToolStripMenuItem_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in dataGridView1.SelectedRows) { if (row.Index > 0) { int index = row.Index; DataGridViewRow tmp = row; dataGridView1.Rows.Remove(row); dataGridView1.Rows.Insert(index - 1, tmp); } } } private void moveDownToolStripMenuItem_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in dataGridView1.SelectedRows) { if (row.Index != (dataGridView1.Rows.Count - 2)) { int index = row.Index; DataGridViewRow tmp = row; dataGridView1.Rows.Remove(row); dataGridView1.Rows.Insert(index + 1, tmp); } } } private void moveToTopToolStripMenuItem_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in dataGridView1.SelectedRows) { if (row.Index > 0) { DataGridViewRow tmp = row; dataGridView1.Rows.Remove(row); dataGridView1.Rows.Insert(0, tmp); } } } private void moveToBottomToolStripMenuItem_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in dataGridView1.SelectedRows) { if (row.Index != (dataGridView1.Rows.Count - 2)) { DataGridViewRow tmp = row; dataGridView1.Rows.Remove(row); dataGridView1.Rows.Add(tmp); } } } private void createRetfRuleToolStripMenuItem_Click(object sender, EventArgs e) { DataGridViewRow row = dataGridView1.CurrentRow; if (row == null) return; string typoName = (string)row.Cells["Comment"].Value; if (string.IsNullOrEmpty(typoName)) typoName = "<enter a name>"; Tools.CopyToClipboard(RegExTypoFix.CreateRule((string)row.Cells["find"].Value, (string)row.Cells["replace"].Value, typoName)); } } public class Replacement { public Replacement() { } public Replacement(string find, string replace, bool isRegex, bool enabled, RegexOptions regularExpressionOptions, string comment) { Find = find; Replace = replace; IsRegex = isRegex; Enabled = enabled; RegularExpressionOptions = regularExpressionOptions; Comment = comment; } public string Find, Replace, Comment; public bool IsRegex, Enabled; public RegexOptions RegularExpressionOptions; } }
svn2github/autowikibrowser
tags/REL_4_5_3_2/WikiFunctions/Parse/FindandReplace.cs
C#
gpl-2.0
23,714
<?php /** * @package LiveUpdate * @copyright Copyright ©2011 Nicholas K. Dionysopoulos / AkeebaBackup.com * @license GNU LGPLv3 or later <http://www.gnu.org/copyleft/lesser.html> */ defined('_JEXEC') or die(); /** * Configuration class for your extension's updates. Override to your liking. */ class LiveUpdateConfig extends LiveUpdateAbstractConfig { var $_extensionName = 'com_cmc'; var $_extensionTitle = 'CMC - Mailchimp for Joomla!'; var $_versionStrategy = 'vcompare'; var $_updateURL = 'https://compojoom.com/index.php?option=com_ars&view=update&format=ini&id=13'; var $_requiresAuthorization = false; /** var $_storageAdapter = 'component'; var $_storageConfig = array( 'extensionName' => 'com_akeebasubs', 'key' => 'liveupdate' ); */ public function __construct() { parent::__construct(); // Dev releases use the "newest" strategy if(substr($this->_currentVersion,1,2) == 'ev') { $this->_versionStrategy = 'newest'; } } }
smetal/gvdd
administrator/components/com_cmc/liveupdate/config.php
PHP
gpl-2.0
986
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2017 - ROLI Ltd. JUCE is an open source library subject to commercial or open-source licensing. The code included in this file is provided under the terms of the ISC license http://www.isc.org/downloads/software-support-policy/isc-license. Permission To use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted provided that the above copyright notice and this permission notice appear in all copies. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { class ThreadPool; class ThreadPoolThread; //============================================================================== /** A task that is executed by a ThreadPool object. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by its threads. The runJob() method needs to be implemented to do the task, and if the code that does the work takes a significant time to run, it must keep checking the shouldExit() method to see if something is trying to interrupt the job. If shouldExit() returns true, the runJob() method must return immediately. @see ThreadPool, Thread */ class JUCE_API ThreadPoolJob { public: //============================================================================== /** Creates a thread pool job object. After creating your job, add it to a thread pool with ThreadPool::addJob(). */ explicit ThreadPoolJob (const String& name); /** Destructor. */ virtual ~ThreadPoolJob(); //============================================================================== /** Returns the name of this job. @see setJobName */ String getJobName() const; /** Changes the job's name. @see getJobName */ void setJobName (const String& newName); //============================================================================== /** These are the values that can be returned by the runJob() method. */ enum JobStatus { jobHasFinished = 0, /**< indicates that the job has finished and can be removed from the pool. */ jobNeedsRunningAgain /**< indicates that the job would like to be called again when a thread is free. */ }; /** Peforms the actual work that this job needs to do. Your subclass must implement this method, in which is does its work. If the code in this method takes a significant time to run, it must repeatedly check the shouldExit() method to see if something is trying to interrupt the job. If shouldExit() ever returns true, the runJob() method must return immediately. If this method returns jobHasFinished, then the job will be removed from the pool immediately. If it returns jobNeedsRunningAgain, then the job will be left in the pool and will get a chance to run again as soon as a thread is free. @see shouldExit() */ virtual JobStatus runJob() = 0; //============================================================================== /** Returns true if this job is currently running its runJob() method. */ bool isRunning() const noexcept { return isActive; } /** Returns true if something is trying to interrupt this job and make it stop. Your runJob() method must call this whenever it gets a chance, and if it ever returns true, the runJob() method must return immediately. @see signalJobShouldExit() */ bool shouldExit() const noexcept { return shouldStop; } /** Calling this will cause the shouldExit() method to return true, and the job should (if it's been implemented correctly) stop as soon as possible. @see shouldExit() */ void signalJobShouldExit(); /** Add a listener to this thread job which will receive a callback when signalJobShouldExit was called on this thread job. @see signalJobShouldExit, removeListener */ void addListener (Thread::Listener*); /** Removes a listener added with addListener. */ void removeListener (Thread::Listener*); //============================================================================== /** If the calling thread is being invoked inside a runJob() method, this will return the ThreadPoolJob that it belongs to. */ static ThreadPoolJob* getCurrentThreadPoolJob(); //============================================================================== private: friend class ThreadPool; friend class ThreadPoolThread; String jobName; ThreadPool* pool = nullptr; bool shouldStop = false, isActive = false, shouldBeDeleted = false; ListenerList<Thread::Listener, Array<Thread::Listener*, CriticalSection>> listeners; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolJob) }; //============================================================================== /** A set of threads that will run a list of jobs. When a ThreadPoolJob object is added to the ThreadPool's list, its runJob() method will be called by the next pooled thread that becomes free. @see ThreadPoolJob, Thread */ class JUCE_API ThreadPool { public: //============================================================================== /** Creates a thread pool. Once you've created a pool, you can give it some jobs by calling addJob(). @param numberOfThreads the number of threads to run. These will be started immediately, and will run until the pool is deleted. @param threadStackSize the size of the stack of each thread. If this value is zero then the default stack size of the OS will be used. */ ThreadPool (int numberOfThreads, size_t threadStackSize = 0); /** Creates a thread pool with one thread per CPU core. Once you've created a pool, you can give it some jobs by calling addJob(). If you want to specify the number of threads, use the other constructor; this one creates a pool which has one thread for each CPU core. @see SystemStats::getNumCpus() */ ThreadPool(); /** Destructor. This will attempt to remove all the jobs before deleting, but if you want to specify a timeout, you should call removeAllJobs() explicitly before deleting the pool. */ ~ThreadPool(); //============================================================================== /** A callback class used when you need to select which ThreadPoolJob objects are suitable for some kind of operation. @see ThreadPool::removeAllJobs */ class JUCE_API JobSelector { public: virtual ~JobSelector() {} /** Should return true if the specified thread matches your criteria for whatever operation that this object is being used for. Any implementation of this method must be extremely fast and thread-safe! */ virtual bool isJobSuitable (ThreadPoolJob* job) = 0; }; //============================================================================== /** Adds a job to the queue. Once a job has been added, then the next time a thread is free, it will run the job's ThreadPoolJob::runJob() method. Depending on the return value of the runJob() method, the pool will either remove the job from the pool or add it to the back of the queue to be run again. If deleteJobWhenFinished is true, then the job object will be owned and deleted by the pool when not needed - if you do this, make sure that your object's destructor is thread-safe. If deleteJobWhenFinished is false, the pointer will be used but not deleted, and the caller is responsible for making sure the object is not deleted before it has been removed from the pool. */ void addJob (ThreadPoolJob* job, bool deleteJobWhenFinished); /** Adds a lambda function to be called as a job. This will create an internal ThreadPoolJob object to encapsulate and call the lambda. */ void addJob (std::function<ThreadPoolJob::JobStatus()> job); /** Adds a lambda function to be called as a job. This will create an internal ThreadPoolJob object to encapsulate and call the lambda. */ void addJob (std::function<void()> job); /** Tries to remove a job from the pool. If the job isn't yet running, this will simply remove it. If it is running, it will wait for it to finish. If the timeout period expires before the job finishes running, then the job will be left in the pool and this will return false. It returns true if the job is successfully stopped and removed. @param job the job to remove @param interruptIfRunning if true, then if the job is currently busy, its ThreadPoolJob::signalJobShouldExit() method will be called to try to interrupt it. If false, then if the job will be allowed to run until it stops normally (or the timeout expires) @param timeOutMilliseconds the length of time this method should wait for the job to finish before giving up and returning false */ bool removeJob (ThreadPoolJob* job, bool interruptIfRunning, int timeOutMilliseconds); /** Tries to remove all jobs from the pool. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit() methods called to try to interrupt them @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish before giving up and returning false @param selectedJobsToRemove if this is not a nullptr, the JobSelector object is asked to decide which jobs should be removed. If it is a nullptr, all jobs are removed @returns true if all jobs are successfully stopped and removed; false if the timeout period expires while waiting for one or more jobs to stop */ bool removeAllJobs (bool interruptRunningJobs, int timeOutMilliseconds, JobSelector* selectedJobsToRemove = nullptr); /** Returns the number of jobs currently running or queued. */ int getNumJobs() const noexcept; /** Returns the number of threads assigned to this thread pool. */ int getNumThreads() const noexcept; /** Returns one of the jobs in the queue. Note that this can be a very volatile list as jobs might be continuously getting shifted around in the list, and this method may return nullptr if the index is currently out-of-range. */ ThreadPoolJob* getJob (int index) const noexcept; /** Returns true if the given job is currently queued or running. @see isJobRunning() */ bool contains (const ThreadPoolJob* job) const noexcept; /** Returns true if the given job is currently being run by a thread. */ bool isJobRunning (const ThreadPoolJob* job) const noexcept; /** Waits until a job has finished running and has been removed from the pool. This will wait until the job is no longer in the pool - i.e. until its runJob() method returns ThreadPoolJob::jobHasFinished. If the timeout period expires before the job finishes, this will return false; it returns true if the job has finished successfully. */ bool waitForJobToFinish (const ThreadPoolJob* job, int timeOutMilliseconds) const; /** If the given job is in the queue, this will move it to the front so that it is the next one to be executed. */ void moveJobToFront (const ThreadPoolJob* jobToMove) noexcept; /** Returns a list of the names of all the jobs currently running or queued. If onlyReturnActiveJobs is true, only the ones currently running are returned. */ StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const; /** Changes the priority of all the threads. This will call Thread::setPriority() for each thread in the pool. May return false if for some reason the priority can't be changed. */ bool setThreadPriorities (int newPriority); private: //============================================================================== Array<ThreadPoolJob*> jobs; class ThreadPoolThread; friend class ThreadPoolJob; friend class ThreadPoolThread; friend struct ContainerDeletePolicy<ThreadPoolThread>; OwnedArray<ThreadPoolThread> threads; CriticalSection lock; WaitableEvent jobFinishedSignal; bool runNextJob (ThreadPoolThread&); ThreadPoolJob* pickNextJobToRun(); void addToDeleteList (OwnedArray<ThreadPoolJob>&, ThreadPoolJob*) const; void createThreads (int numThreads, size_t threadStackSize = 0); void stopThreads(); // Note that this method has changed, and no longer has a parameter to indicate // whether the jobs should be deleted - see the new method for details. void removeAllJobs (bool, int, bool); JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPool) }; } // namespace juce
pingdynasty/FirmwareSender
JuceLibraryCode/modules/juce_core/threads/juce_ThreadPool.h
C
gpl-2.0
14,356
# -*- coding: utf-8 -*- """ IMU Plugin Copyright (C) 2015 Olaf Lüke <olaf@tinkerforge.com> Copyright (C) 2015 Matthias Bolte <matthias@tinkerforge.com> Copyright (C) 2019 Erik Fleckstein <erik@tinkerforge.com> imu_3d_widget.py: IMU OpenGL representation 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, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. """ import sys import ctypes import ctypes.util import math import array import os from PyQt5.QtGui import QMatrix4x4, QQuaternion from brickv.utils import get_resources_path from brickv.render_widget import RenderWidget class IMU3DWidget(RenderWidget): def __init__(self, parent=None): super().__init__(get_resources_path(os.path.join('plugin_system', 'plugins', 'imu', 'imu.obj')), parent) self.save_orientation_flag = False self.has_save_orientation = False self.reference_orientation = QQuaternion() self.rotation = QQuaternion() def save_orientation(self): self.save_orientation_flag = True def get_state(self): return self.save_orientation_flag, self.reference_orientation, self.has_save_orientation def set_state(self, tup): self.save_orientation_flag, self.reference_orientation, self.has_save_orientation = tup def get_model_matrix(self): result = super().get_model_matrix() result.rotate(self.rotation) return result def update_orientation(self, w, x, y, z): if self.save_orientation_flag: self.reference_orientation = QQuaternion(w, x, y, z) self.save_orientation_flag = False self.has_save_orientation = True if not self.has_save_orientation: return self.rotation = self.reference_orientation.conjugate() * QQuaternion(w, x, y, z) super().update()
Tinkerforge/brickv
src/brickv/plugin_system/plugins/imu/imu_3d_widget.py
Python
gpl-2.0
2,398
SELECT AB.Frame, @minerals := IFNULL(Minerals, @minerals) AS Minerals, @gas := IFNULL(Gas, @gas) AS Gas, @supply := IFNULL(Supply, @supply) AS Supply, @totMinerals := IFNULL(TotalMinerals, @totMinerals) AS TotalMinerals, @totGas := IFNULL(TotalGas, @totGas) AS TotalGas, @totSupply := IFNULL(TotalSupply, @totSupply) AS TotalSupply, @winnerA := IFNULL(WinnerA, @winnerA) AS WinnerA, @enemyMinerals := IFNULL(EnemyMinerals, @enemyMinerals) AS EnemyMinerals, @enemyGas := IFNULL(EnemyGas, @enemyGas) AS EnemyGas, @enemySupply := IFNULL(EnemySupply, @enemySupply) AS EnemySupply, @enemyTotMinerals := IFNULL(EnemyTotalMinerals, @enemyTotMinerals) AS EnemyTotalMinerals, @enemyTotGas := IFNULL(EnemyTotalGas, @enemyTotGas) AS EnemyTotalGas, @enemyTotSupply := IFNULL(EnemyTotalSupply, @enemyTotSupply) AS EnemyTotalSupply, @winnerB := IFNULL(WinnerB, @winnerB) AS WinnerB, @ground := IFNULL(GroundUnitValue, @ground) AS GroundUnitValue, @building := IFNULL(BuildingValue, @building) AS BuildingValue, @air := IFNULL(AirUnitValue, @air) AS AirUnitValue, @aObservedEnemyGround := IFNULL(AObservedEnemyGroundUnitValue, @aObservedEnemyGround) AS AObservedEnemyGroundUnitValue, @aObservedEnemyBuilding := IFNULL(AObservedEnemyBuildingValue, @aObservedEnemyBuilding) AS AObservedEnemyBuildingValue, @aObservedEnemyAir := IFNULL(AObservedEnemyAirUnitValue, @aObservedEnemyAir) AS AObservedEnemyAirUnitValue, @enemyGround := IFNULL(EnemyGroundUnitValue, @enemyGround) AS EnemyGroundUnitValue, @enemyBuilding := IFNULL(EnemyBuildingValue, @enemyBuilding) AS EnemyBuildingValue, @enemyAir := IFNULL(EnemyAirUnitValue, @enemyAir) AS EnemyAirUnitValue, @bObservedEnemyGround := IFNULL(BObservedEnemyGroundUnitValue, @bObservedEnemyGround) AS BObservedEnemyGroundUnitValue, @bObservedEnemyBuilding := IFNULL(BObservedEnemyBuildingValue, @bObservedEnemyBuilding) AS BObservedEnemyBuildingValue, @bObservedEnemyAir := IFNULL(BObservedEnemyAirUnitValue, @bObservedEnemyAir) AS BObservedEnemyAirUnitValue, @resourcesA := IFNULL(AObservedResourceValue, @resourcesA) AObservedResourceValue, @resourcesB := IFNULL(BObservedResourceValue, @resourcesB) AS BObservedResourceValue FROM ( SELECT IFNULL(A.Frame, B.Frame) AS Frame, A.Minerals, A.Gas, A.Supply, A.TotalMinerals, A.TotalGas, A.TotalSupply, A.Winner AS WinnerA, B.Minerals AS EnemyMinerals, B.Gas AS EnemyGas, B.Supply AS EnemySupply, B.TotalMinerals AS EnemyTotalMinerals, B.TotalGas AS EnemyTotalGas, B.TotalSupply AS EnemyTotalSupply, B.Winner AS WinnerB FROM ( SELECT rc.Frame, pr.PlayerReplayID, rc.Minerals, rc.Gas, rc.Supply, rc.TotalMinerals, rc.TotalGas, rc.TotalSupply, pr.Winner FROM resourcechange rc INNER JOIN playerreplay pr ON pr.PlayerReplayID = rc.PlayerReplayID INNER JOIN replay r ON r.ReplayID = pr.ReplayID WHERE r.ReplayID = 266 AND pr.PlayerReplayID = 543 -- AND Frame > 0 ORDER BY rc.Frame ASC ) AS A LEFT JOIN ( SELECT rc.Frame, pr.PlayerReplayID, rc.Minerals, rc.Gas, rc.Supply, rc.TotalMinerals, rc.TotalGas, rc.TotalSupply, pr.Winner FROM resourcechange rc INNER JOIN playerreplay pr ON pr.PlayerReplayID = rc.PlayerReplayID INNER JOIN replay r ON r.ReplayID = pr.ReplayID WHERE r.ReplayID = 266 AND pr.PlayerReplayID = 544 -- AND Frame > 0 ORDER BY rc.Frame ASC ) AS B ON A.Frame = B.Frame AND A.PlayerReplayID != B.PlayerReplayID UNION ALL SELECT IFNULL(A.Frame, B.Frame) AS Frame, A.Minerals, A.Gas, A.Supply, A.TotalMinerals, A.TotalGas, A.TotalSupply, A.Winner AS WinnerA, B.Minerals, B.Gas, B.Supply, B.TotalMinerals AS EnemyTotalMinerals, B.TotalGas AS EnemyTotalGas, B.TotalSupply AS EnemyTotalSupply, B.Winner AS WinnerB FROM ( SELECT rc.Frame, pr.PlayerReplayID, rc.Minerals, rc.Gas, rc.Supply, rc.TotalMinerals, rc.TotalGas, rc.TotalSupply, pr.Winner FROM resourcechange rc INNER JOIN playerreplay pr ON pr.PlayerReplayID = rc.PlayerReplayID INNER JOIN replay r ON r.ReplayID = pr.ReplayID WHERE r.ReplayID = 266 AND pr.PlayerReplayID = 543 -- AND Frame > 0 ORDER BY rc.Frame ASC ) AS A RIGHT JOIN ( SELECT rc.Frame, pr.PlayerReplayID, rc.Minerals, rc.Gas, rc.Supply, rc.TotalMinerals, rc.TotalGas, rc.TotalSupply, pr.Winner FROM resourcechange rc INNER JOIN playerreplay pr ON pr.PlayerReplayID = rc.PlayerReplayID INNER JOIN replay r ON r.ReplayID = pr.ReplayID WHERE r.ReplayID = 266 AND pr.PlayerReplayID = 544 -- AND Frame > 0 ORDER BY rc.Frame ASC ) AS B ON A.Frame = B.Frame AND A.PlayerReplayID != B.PlayerReplayID WHERE A.Frame IS NULL ) AS AB LEFT JOIN ( SELECT DISTINCT rc.Frame, sum(GroundUnitValue) AS GroundUnitValue, sum(BuildingValue) AS BuildingValue, sum(AirUnitValue) AS AirUnitValue, sum(EnemyGroundUnitValue) AS AObservedEnemyGroundUnitValue, sum(EnemyBuildingValue) AS AObservedEnemyBuildingValue, sum(EnemyAirUnitValue) AS AObservedEnemyAirUnitValue, sum(ResourceValue) AS AObservedResourceValue FROM resourcechange rc INNER JOIN regionvaluechange AS R1 ON rc.PlayerReplayID = R1.PlayerReplayID WHERE rc.PlayerReplayID = 543 AND R1.Frame = ( SELECT max(Frame) FROM regionvaluechange WHERE PlayerReplayID = 543 AND RegionID = R1.RegionID AND Frame <= rc.Frame GROUP BY RegionID ) -- and rc.Frame > 0 GROUP BY rc.Frame ORDER BY rc.Frame ) AS C ON AB.Frame = C.Frame LEFT JOIN ( SELECT DISTINCT rc.Frame, sum(GroundUnitValue) AS EnemyGroundUnitValue, sum(BuildingValue) AS EnemyBuildingValue, sum(AirUnitValue) AS EnemyAirUnitValue, sum(EnemyGroundUnitValue) AS BObservedEnemyGroundUnitValue, sum(EnemyBuildingValue) AS BObservedEnemyBuildingValue, sum(EnemyAirUnitValue) AS BObservedEnemyAirUnitValue, sum(ResourceValue) AS BObservedResourceValue FROM resourcechange rc INNER JOIN regionvaluechange AS R1 ON rc.PlayerReplayID = R1.PlayerReplayID WHERE rc.PlayerReplayID = 544 AND R1.Frame = ( SELECT max(Frame) FROM regionvaluechange WHERE PlayerReplayID = 544 AND RegionID = R1.RegionID AND Frame <= rc.Frame GROUP BY RegionID ) -- and rc.Frame > 0 GROUP BY rc.Frame ORDER BY rc.Frame ) AS D ON AB.Frame = D.Frame CROSS JOIN ( SELECT @minerals := 0, @gas := 0, @supply := 0, @enemyMinerals := 0, @enemyGas := 0, @enemySupply := 0, @totMinerals := 0, @totGas := 0, @totSupply := 0, @winnerA := 0, @enemyTotMinerals := 0, @enemyTotGas := 0, @enemyTotSupply := 0, @winnerB := 0, @ground := 0, @building := 0, @air := 0, @aObservedEnemyGround := 0, @aObservedEnemyBuilding := 0, @aObservedEnemyAir := 0, @enemyGround := 0, @enemyBuilding := 0, @enemyAir := 0, @bObservedEnemyGround := 0, @bObservedEnemyBuilding := 0, @bObservedEnemyAir := 0, @resourcesA := 0, @resourcesB := 0 ) AS var_init ORDER BY AB.Frame;
analca3/TFG
Consultas/replay.sql
SQL
gpl-2.0
6,978
/* FreeTDS - Library of routines accessing Sybase and Microsoft databases * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004 Brian Bruns * Copyright (C) 2005-2008 Frediano Ziglio * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include <config.h> #include <stdarg.h> #include <stdio.h> #include <assert.h> #if HAVE_STDLIB_H #include <stdlib.h> #endif /* HAVE_STDLIB_H */ #if HAVE_STRING_H #include <string.h> #endif /* HAVE_STRING_H */ #include <ctype.h> #include "tdsodbc.h" #include "tdsconvert.h" #ifdef DMALLOC #include <dmalloc.h> #endif TDS_RCSID(var, "$Id: prepare_query.c,v 1.81 2011-06-05 09:21:49 freddy77 Exp $"); #define TDS_ISSPACE(c) isspace((unsigned char) (c)) static int prepared_rpc(struct _hstmt *stmt, int compute_row) { int nparam = stmt->params ? stmt->params->num_cols : 0; const char *p = stmt->prepared_pos - 1; for (;;) { TDSPARAMINFO *temp_params; TDSCOLUMN *curcol; TDS_SERVER_TYPE type; const char *start; while (TDS_ISSPACE(*++p)); if (!*p) return SQL_SUCCESS; /* we have certainly a parameter */ if (!(temp_params = tds_alloc_param_result(stmt->params))) { odbc_errs_add(&stmt->errs, "HY001", NULL); return SQL_ERROR; } stmt->params = temp_params; curcol = temp_params->columns[nparam]; switch (*p) { case ',': if (IS_TDS7_PLUS(stmt->dbc->tds_socket)) { tds_set_param_type(stmt->dbc->tds_socket, curcol, SYBVOID); curcol->column_size = curcol->column_cur_size = 0; } else { /* TODO is there a better type ? */ tds_set_param_type(stmt->dbc->tds_socket, curcol, SYBINTN); curcol->column_size = curcol->on_server.column_size = 4; curcol->column_cur_size = -1; } if (compute_row) if (!tds_alloc_param_data(curcol)) { tds_free_param_result(temp_params); return SQL_ERROR; } --p; break; default: /* add next parameter to list */ start = p; if (!(p = parse_const_param(p, &type))) { tds_free_param_result(temp_params); return SQL_ERROR; } tds_set_param_type(stmt->dbc->tds_socket, curcol, type); switch (type) { case SYBVARCHAR: curcol->column_size = p - start; break; case SYBVARBINARY: curcol->column_size = (p - start) / 2 -1; break; default: assert(0); case SYBINT4: case SYBFLT8: curcol->column_cur_size = curcol->column_size; break; } curcol->on_server.column_size = curcol->column_size; /* TODO support other type other than VARCHAR, do not strip escape in prepare_call */ if (compute_row) { char *dest; int len; CONV_RESULT cr; if (!tds_alloc_param_data(curcol)) { tds_free_param_result(temp_params); return SQL_ERROR; } dest = (char *) curcol->column_data; switch (type) { case SYBVARCHAR: if (*start != '\'') { memcpy(dest, start, p - start); curcol->column_cur_size = p - start; } else { ++start; for (;;) { if (*start == '\'') ++start; if (start >= p) break; *dest++ = *start++; } curcol->column_cur_size = dest - (char *) curcol->column_data; } break; case SYBVARBINARY: cr.cb.len = curcol->column_size; cr.cb.ib = dest; len = tds_convert(NULL, SYBVARCHAR, start, p - start, TDS_CONVERT_BINARY, &cr); if (len >= 0 && len <= curcol->column_size) curcol->column_cur_size = len; break; case SYBINT4: *((TDS_INT *) dest) = strtol(start, NULL, 10); break; case SYBFLT8: *((TDS_FLOAT *) dest) = strtod(start, NULL); break; default: break; } } --p; break; case '?': /* find binded parameter */ if (stmt->param_num > stmt->apd->header.sql_desc_count || stmt->param_num > stmt->ipd->header.sql_desc_count) { tds_free_param_result(temp_params); /* TODO set error */ return SQL_ERROR; } switch (odbc_sql2tds (stmt, &stmt->ipd->records[stmt->param_num - 1], &stmt->apd->records[stmt->param_num - 1], curcol, compute_row, stmt->apd, stmt->curr_param_row)) { case SQL_ERROR: return SQL_ERROR; case SQL_NEED_DATA: return SQL_NEED_DATA; } ++stmt->param_num; break; } ++nparam; while (TDS_ISSPACE(*++p)); if (!*p || *p != ',') return SQL_SUCCESS; stmt->prepared_pos = (char *) p + 1; } } int parse_prepared_query(struct _hstmt *stmt, int compute_row) { /* try setting this parameter */ TDSPARAMINFO *temp_params; int nparam = stmt->params ? stmt->params->num_cols : 0; if (stmt->prepared_pos) return prepared_rpc(stmt, compute_row); tdsdump_log(TDS_DBG_FUNC, "parsing %d parameters\n", nparam); for (; stmt->param_num <= stmt->param_count; ++nparam, ++stmt->param_num) { /* find bound parameter */ if (stmt->param_num > stmt->apd->header.sql_desc_count || stmt->param_num > stmt->ipd->header.sql_desc_count) { tdsdump_log(TDS_DBG_FUNC, "parse_prepared_query: logic_error: parameter out of bounds: " "%d > %d || %d > %d\n", stmt->param_num, stmt->apd->header.sql_desc_count, stmt->param_num, stmt->ipd->header.sql_desc_count); return SQL_ERROR; } /* add a column to parameters */ if (!(temp_params = tds_alloc_param_result(stmt->params))) { odbc_errs_add(&stmt->errs, "HY001", NULL); return SQL_ERROR; } stmt->params = temp_params; switch (odbc_sql2tds (stmt, &stmt->ipd->records[stmt->param_num - 1], &stmt->apd->records[stmt->param_num - 1], stmt->params->columns[nparam], compute_row, stmt->apd, stmt->curr_param_row)) { case SQL_ERROR: return SQL_ERROR; case SQL_NEED_DATA: return SQL_NEED_DATA; } } return SQL_SUCCESS; } int start_parse_prepared_query(struct _hstmt *stmt, int compute_row) { /* TODO should be NULL already ?? */ tds_free_param_results(stmt->params); stmt->params = NULL; stmt->param_num = 0; stmt->param_num = stmt->prepared_query_is_func ? 2 : 1; return parse_prepared_query(stmt, compute_row); } static TDS_INT odbc_wchar2hex(TDS_CHAR *dest, TDS_UINT destlen, const SQLWCHAR * src, TDS_UINT srclen) { unsigned int i; SQLWCHAR hex1, c = 0; /* if srclen if odd we must add a "0" before ... */ i = 0; /* number where to start converting */ if (srclen & 1) { ++srclen; i = 1; --src; } for (; i < srclen; ++i) { hex1 = src[i]; if ('0' <= hex1 && hex1 <= '9') hex1 &= 0x0f; else { hex1 &= (SQLWCHAR) ~0x20u; /* mask off 0x20 to ensure upper case */ if ('A' <= hex1 && hex1 <= 'F') { hex1 -= ('A' - 10); } else { tdsdump_log(TDS_DBG_INFO1, "error_handler: attempt to convert data stopped by syntax error in source field \n"); return TDS_CONVERT_SYNTAX; } } assert(hex1 < 0x10); if ((i/2u) >= destlen) continue; if (i & 1) dest[i / 2u] = c | hex1; else c = hex1 << 4; } return srclen / 2u; } int continue_parse_prepared_query(struct _hstmt *stmt, SQLPOINTER DataPtr, SQLLEN StrLen_or_Ind) { struct _drecord *drec_apd, *drec_ipd; SQLLEN len; int need_bytes; TDSCOLUMN *curcol; TDSBLOB *blob; int sql_src_type; assert(stmt); tdsdump_log(TDS_DBG_FUNC, "continue_parse_prepared_query with parameter %d\n", stmt->param_num); if (!stmt->params) { tdsdump_log(TDS_DBG_FUNC, "error? continue_parse_prepared_query: no parameters provided"); return SQL_ERROR; } if (stmt->param_num > stmt->apd->header.sql_desc_count || stmt->param_num > stmt->ipd->header.sql_desc_count) return SQL_ERROR; drec_apd = &stmt->apd->records[stmt->param_num - 1]; drec_ipd = &stmt->ipd->records[stmt->param_num - 1]; curcol = stmt->params->columns[stmt->param_num - (stmt->prepared_query_is_func ? 2 : 1)]; blob = NULL; if (is_blob_col(curcol)) blob = (TDSBLOB *) curcol->column_data; assert(curcol->column_cur_size <= curcol->column_size); need_bytes = curcol->column_size - curcol->column_cur_size; if (DataPtr == NULL) { switch(StrLen_or_Ind) { case SQL_NULL_DATA: case SQL_DEFAULT_PARAM: break; /* OK */ default: odbc_errs_add(&stmt->errs, "HY009", NULL); /* Invalid use of null pointer */ return SQL_ERROR; } } /* get C type */ sql_src_type = drec_apd->sql_desc_concise_type; if (sql_src_type == SQL_C_DEFAULT) sql_src_type = odbc_sql_to_c_type_default(drec_ipd->sql_desc_concise_type); switch(StrLen_or_Ind) { case SQL_NTS: if (sql_src_type == SQL_C_WCHAR) len = sqlwcslen((SQLWCHAR *) DataPtr); else len = strlen((char *) DataPtr); break; case SQL_NULL_DATA: len = 0; break; case SQL_DEFAULT_PARAM: /* FIXME: use the default if the parameter has one. */ odbc_errs_add(&stmt->errs, "07S01", NULL); /* Invalid use of default parameter */ return SQL_ERROR; default: if (DataPtr && StrLen_or_Ind < 0) { /* * "The argument DataPtr was not a null pointer, and * the argument StrLen_or_Ind was less than 0 * but not equal to SQL_NTS or SQL_NULL_DATA." */ odbc_errs_add(&stmt->errs, "HY090", NULL); return SQL_ERROR; } len = StrLen_or_Ind; break; } if (!blob && len > need_bytes) len = need_bytes; /* copy to destination */ if (blob) { TDS_CHAR *p; int binary_convert = 0; SQLLEN orig_len = len; if (sql_src_type == SQL_C_CHAR || sql_src_type == SQL_C_WCHAR) { switch (tds_get_conversion_type(curcol->column_type, curcol->column_size)) { case SYBBINARY: case SYBVARBINARY: case XSYBBINARY: case XSYBVARBINARY: case SYBLONGBINARY: case SYBIMAGE: if (len && sql_src_type == SQL_C_CHAR && !*((char*)DataPtr+len-1)) --len; if (sql_src_type == SQL_C_WCHAR) len /= sizeof(SQLWCHAR); if (!len) return SQL_SUCCESS; binary_convert = 1; orig_len = len; len = len / 2u + 1u; break; } } if (blob->textvalue) p = (TDS_CHAR *) realloc(blob->textvalue, len + curcol->column_cur_size); else { assert(curcol->column_cur_size == 0); p = (TDS_CHAR *) malloc(len); } if (!p) { odbc_errs_add(&stmt->errs, "HY001", NULL); /* Memory allocation error */ return SQL_ERROR; } blob->textvalue = p; p += curcol->column_cur_size; if (binary_convert) { int res; len = orig_len; if (curcol->column_cur_size > 0 && curcol->column_text_sqlputdatainfo) { SQLWCHAR data[2]; data[0] = curcol->column_text_sqlputdatainfo; data[1] = (sql_src_type == SQL_C_CHAR) ? *(unsigned char*)DataPtr : *(SQLWCHAR*)DataPtr; res = odbc_wchar2hex(p, 1, data, 2); if (res < 0) { odbc_convert_err_set(&stmt->errs, res); return SQL_ERROR; } p += res; DataPtr = (SQLPOINTER) (((char*)DataPtr) + (sql_src_type == SQL_C_CHAR ? 1 : sizeof(SQLWCHAR))); --len; } if (len&1) { --len; curcol->column_text_sqlputdatainfo = (sql_src_type == SQL_C_CHAR) ? ((char*)DataPtr)[len] : ((SQLWCHAR*)DataPtr)[len]; } res = (sql_src_type == SQL_C_CHAR) ? tds_char2hex(p, len / 2u, (const TDS_CHAR*) DataPtr, len): odbc_wchar2hex(p, len / 2u, (const SQLWCHAR*) DataPtr, len); if (res < 0) { odbc_convert_err_set(&stmt->errs, res); return SQL_ERROR; } p += res; len = p - (blob->textvalue + curcol->column_cur_size); } else { memcpy(blob->textvalue + curcol->column_cur_size, DataPtr, len); } } else { memcpy(curcol->column_data + curcol->column_cur_size, DataPtr, len); } curcol->column_cur_size += len; if (blob && curcol->column_cur_size > curcol->column_size) curcol->column_size = curcol->column_cur_size; return SQL_SUCCESS; }
mattdurham/freetds
src/odbc/prepare_query.c
C
gpl-2.0
12,136
/* * This file is part of the TrinityCore 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 <http://www.gnu.org/licenses/>. */ #include "UnitAI.h" #include "Creature.h" #include "CreatureAIImpl.h" #include "MotionMaster.h" #include "Player.h" #include "QuestDef.h" #include "Spell.h" #include "SpellAuraEffects.h" #include "SpellAuras.h" #include "SpellInfo.h" #include "SpellMgr.h" void UnitAI::AttackStart(Unit* victim) { if (victim && me->Attack(victim, true)) { // Clear distracted state on attacking if (me->HasUnitState(UNIT_STATE_DISTRACTED)) { me->ClearUnitState(UNIT_STATE_DISTRACTED); me->GetMotionMaster()->Clear(); } me->GetMotionMaster()->MoveChase(victim); } } void UnitAI::InitializeAI() { if (!me->isDead()) Reset(); } void UnitAI::AttackStartCaster(Unit* victim, float dist) { if (victim && me->Attack(victim, false)) me->GetMotionMaster()->MoveChase(victim, dist); } void UnitAI::DoMeleeAttackIfReady() { if (me->HasUnitState(UNIT_STATE_CASTING)) return; Unit* victim = me->GetVictim(); if (!me->IsWithinMeleeRange(victim)) return; //Make sure our attack is ready and we aren't currently casting before checking distance if (me->isAttackReady()) { if (ShouldSparWith(victim)) me->FakeAttackerStateUpdate(victim); else me->AttackerStateUpdate(victim); me->resetAttackTimer(); } if (me->haveOffhandWeapon() && me->isAttackReady(OFF_ATTACK)) { if (ShouldSparWith(victim)) me->FakeAttackerStateUpdate(victim, OFF_ATTACK); else me->AttackerStateUpdate(victim, OFF_ATTACK); me->resetAttackTimer(OFF_ATTACK); } } bool UnitAI::DoSpellAttackIfReady(uint32 spellId) { if (me->HasUnitState(UNIT_STATE_CASTING) || !me->isAttackReady()) return true; if (SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId)) { if (me->IsWithinCombatRange(me->GetVictim(), spellInfo->GetMaxRange(false))) { me->CastSpell(me->GetVictim(), spellInfo, TRIGGERED_NONE); me->resetAttackTimer(); return true; } } return false; } Unit* UnitAI::SelectTarget(SelectAggroTarget targetType, uint32 position, float dist, bool playerOnly, int32 aura) { return SelectTarget(targetType, position, DefaultTargetSelector(me, dist, playerOnly, aura)); } void UnitAI::SelectTargetList(std::list<Unit*>& targetList, uint32 num, SelectAggroTarget targetType, float dist, bool playerOnly, int32 aura) { SelectTargetList(targetList, DefaultTargetSelector(me, dist, playerOnly, aura), num, targetType); } void UnitAI::DoCast(uint32 spellId) { Unit* target = NULL; switch (AISpellInfo[spellId].target) { default: case AITARGET_SELF: target = me; break; case AITARGET_VICTIM: target = me->GetVictim(); break; case AITARGET_ENEMY: { if (SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId)) { bool playerOnly = spellInfo->HasAttribute(SPELL_ATTR3_ONLY_TARGET_PLAYERS); target = SelectTarget(SELECT_TARGET_RANDOM, 0, spellInfo->GetMaxRange(false), playerOnly); } break; } case AITARGET_ALLY: target = me; break; case AITARGET_BUFF: target = me; break; case AITARGET_DEBUFF: { if (SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId)) { bool playerOnly = spellInfo->HasAttribute(SPELL_ATTR3_ONLY_TARGET_PLAYERS); float range = spellInfo->GetMaxRange(false); DefaultTargetSelector targetSelector(me, range, playerOnly, -(int32)spellId); if (!spellInfo->HasAuraInterruptFlag(AURA_INTERRUPT_FLAG_NOT_VICTIM) && targetSelector(me->GetVictim())) target = me->GetVictim(); else target = SelectTarget(SELECT_TARGET_RANDOM, 0, targetSelector); } break; } } if (target) me->CastSpell(target, spellId, false); } void UnitAI::DoCast(Unit* victim, uint32 spellId, bool triggered) { if (!victim || (me->HasUnitState(UNIT_STATE_CASTING) && !triggered)) return; me->CastSpell(victim, spellId, triggered); } void UnitAI::DoCastVictim(uint32 spellId, bool triggered) { if (!me->GetVictim() || (me->HasUnitState(UNIT_STATE_CASTING) && !triggered)) return; me->CastSpell(me->GetVictim(), spellId, triggered); } void UnitAI::DoCastAOE(uint32 spellId, bool triggered) { if (!triggered && me->HasUnitState(UNIT_STATE_CASTING)) return; me->CastSpell((Unit*)NULL, spellId, triggered); } #define UPDATE_TARGET(a) {if (AIInfo->target<a) AIInfo->target=a;} void UnitAI::FillAISpellInfo() { AISpellInfo = new AISpellInfoType[sSpellMgr->GetSpellInfoStoreSize()]; AISpellInfoType* AIInfo = AISpellInfo; const SpellInfo* spellInfo; for (uint32 i = 0; i < sSpellMgr->GetSpellInfoStoreSize(); ++i, ++AIInfo) { spellInfo = sSpellMgr->GetSpellInfo(i); if (!spellInfo) continue; if (spellInfo->HasAttribute(SPELL_ATTR0_CASTABLE_WHILE_DEAD)) AIInfo->condition = AICOND_DIE; else if (spellInfo->IsPassive() || spellInfo->GetDuration() == -1) AIInfo->condition = AICOND_AGGRO; else AIInfo->condition = AICOND_COMBAT; if (AIInfo->cooldown < spellInfo->RecoveryTime) AIInfo->cooldown = spellInfo->RecoveryTime; if (!spellInfo->GetMaxRange(false)) UPDATE_TARGET(AITARGET_SELF) else { for (SpellEffectInfo const* effect : spellInfo->GetEffectsForDifficulty(DIFFICULTY_NONE)) { if (!effect) continue; uint32 targetType = effect->TargetA.GetTarget(); if (targetType == TARGET_UNIT_TARGET_ENEMY || targetType == TARGET_DEST_TARGET_ENEMY) UPDATE_TARGET(AITARGET_VICTIM) else if (targetType == TARGET_UNIT_DEST_AREA_ENEMY) UPDATE_TARGET(AITARGET_ENEMY) if (effect->Effect == SPELL_EFFECT_APPLY_AURA) { if (targetType == TARGET_UNIT_TARGET_ENEMY) UPDATE_TARGET(AITARGET_DEBUFF) else if (spellInfo->IsPositive()) UPDATE_TARGET(AITARGET_BUFF) } } } AIInfo->realCooldown = spellInfo->RecoveryTime + spellInfo->StartRecoveryTime; AIInfo->maxRange = spellInfo->GetMaxRange(false) * 3 / 4; } } uint32 UnitAI::GetDialogStatus(Player* /*player*/) { return DIALOG_STATUS_SCRIPTED_NO_STATUS; } ThreatManager& UnitAI::GetThreatManager() { return me->getThreatManager(); } bool DefaultTargetSelector::operator()(Unit const* target) const { if (!me) return false; if (!target) return false; if (m_playerOnly && (target->GetTypeId() != TYPEID_PLAYER)) return false; if (m_dist > 0.0f && !me->IsWithinCombatRange(target, m_dist)) return false; if (m_dist < 0.0f && me->IsWithinCombatRange(target, -m_dist)) return false; if (m_aura) { if (m_aura > 0) { if (!target->HasAura(m_aura)) return false; } else { if (target->HasAura(-m_aura)) return false; } } return true; } SpellTargetSelector::SpellTargetSelector(Unit* caster, uint32 spellId) : _caster(caster), _spellInfo(sSpellMgr->GetSpellInfo(spellId)) { ASSERT(_spellInfo); } bool SpellTargetSelector::operator()(Unit const* target) const { if (!target) return false; if (_spellInfo->CheckTarget(_caster, target) != SPELL_CAST_OK) return false; // copypasta from Spell::CheckRange float minRange = 0.0f; float maxRange = 0.0f; float rangeMod = 0.0f; if (_spellInfo->RangeEntry) { if (_spellInfo->RangeEntry->Flags & SPELL_RANGE_MELEE) { rangeMod = _caster->GetCombatReach() + 4.0f / 3.0f; rangeMod += target->GetCombatReach(); rangeMod = std::max(rangeMod, NOMINAL_MELEE_RANGE); } else { float meleeRange = 0.0f; if (_spellInfo->RangeEntry->Flags & SPELL_RANGE_RANGED) { meleeRange = _caster->GetCombatReach() + 4.0f / 3.0f; meleeRange += target->GetCombatReach(); meleeRange = std::max(meleeRange, NOMINAL_MELEE_RANGE); } minRange = _caster->GetSpellMinRangeForTarget(target, _spellInfo) + meleeRange; maxRange = _caster->GetSpellMaxRangeForTarget(target, _spellInfo); rangeMod = _caster->GetCombatReach(); rangeMod += target->GetCombatReach(); if (minRange > 0.0f && !(_spellInfo->RangeEntry->Flags & SPELL_RANGE_RANGED)) minRange += rangeMod; } if (_caster->isMoving() && target->isMoving() && !_caster->IsWalking() && !target->IsWalking() && (_spellInfo->RangeEntry->Flags & SPELL_RANGE_MELEE || target->GetTypeId() == TYPEID_PLAYER)) rangeMod += 8.0f / 3.0f; } maxRange += rangeMod; minRange *= minRange; maxRange *= maxRange; if (target != _caster) { if (_caster->GetExactDistSq(target) > maxRange) return false; if (minRange > 0.0f && _caster->GetExactDistSq(target) < minRange) return false; } return true; } bool NonTankTargetSelector::operator()(Unit const* target) const { if (!target) return false; if (_playerOnly && target->GetTypeId() != TYPEID_PLAYER) return false; if (HostileReference* currentVictim = _source->getThreatManager().getCurrentVictim()) return target->GetGUID() != currentVictim->getUnitGuid(); return target != _source->GetVictim(); } bool PowerUsersSelector::operator()(Unit const* target) const { if (!_me || !target) return false; if (target->GetPowerType() != _power) return false; if (_playerOnly && target->GetTypeId() != TYPEID_PLAYER) return false; if (_dist > 0.0f && !_me->IsWithinCombatRange(target, _dist)) return false; if (_dist < 0.0f && _me->IsWithinCombatRange(target, -_dist)) return false; return true; } bool FarthestTargetSelector::operator()(Unit const* target) const { if (!_me || !target) return false; if (_playerOnly && target->GetTypeId() != TYPEID_PLAYER) return false; if (_dist > 0.0f && !_me->IsWithinCombatRange(target, _dist)) return false; if (_inLos && !_me->IsWithinLOSInMap(target)) return false; return true; } void SortByDistanceTo(Unit* reference, std::list<Unit*>& targets) { targets.sort(Trinity::ObjectDistanceOrderPred(reference)); }
Pirricli/TrinityCore
src/server/game/AI/CoreAI/UnitAI.cpp
C++
gpl-2.0
11,906
#ifndef SELECTMAP_H #define SELECTMAP_H #include <QDialog> #include <QHash> #include <QSqlDatabase> #include <QSqlRelationalTableModel> #include <QSqlQuery> #include <QSqlError> #include <QSqlResult> #include <QString> namespace Ui { class SelectMap; } class SelectMap : public QDialog { Q_OBJECT public: explicit SelectMap(QWidget *parent = 0); ~SelectMap(); int id; void setup(QString table); private: Ui::SelectMap *ui; private slots: void on_buttonBox_rejected(); void on_buttonBox_accepted(); }; #endif // SELECTMAP_H
Berimor66/humblemaps
selectmap.h
C
gpl-2.0
601
#nav-bar toolbarbutton[checked="true"] { background-color: #ddd; border-right: 1px solid #b9b9b9; border-left: 1px solid #b9b9b9; } label.twitter-url { text-decoration: none; cursor: pointer; color: #00f; } richlistitem[new="true"] { background-color: #ffa; } richlistbox:focus richlistitem[selected="true"] label.twitter-url { color: #fff; }
cfinke/TwitterBar
twitterbar-client/chrome/skin/sidebar.css
CSS
gpl-2.0
355
<!DOCTYPE html> <!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]--> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>compute dpd/atom command &mdash; LAMMPS documentation</title> <link rel="stylesheet" href="_static/css/theme.css" type="text/css" /> <link rel="stylesheet" href="_static/sphinxcontrib-images/LightBox2/lightbox2/css/lightbox.css" type="text/css" /> <link rel="top" title="LAMMPS documentation" href="index.html"/> <script src="_static/js/modernizr.min.js"></script> </head> <body class="wy-body-for-nav" role="document"> <div class="wy-grid-for-nav"> <nav data-toggle="wy-nav-shift" class="wy-nav-side"> <div class="wy-side-nav-search"> <a href="Manual.html" class="icon icon-home"> LAMMPS </a> <div role="search"> <form id="rtd-search-form" class="wy-form" action="search.html" method="get"> <input type="text" name="q" placeholder="Search docs" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation"> <ul> <li class="toctree-l1"><a class="reference internal" href="Section_intro.html">1. Introduction</a></li> <li class="toctree-l1"><a class="reference internal" href="Section_start.html">2. Getting Started</a></li> <li class="toctree-l1"><a class="reference internal" href="Section_commands.html">3. Commands</a></li> <li class="toctree-l1"><a class="reference internal" href="Section_packages.html">4. Packages</a></li> <li class="toctree-l1"><a class="reference internal" href="Section_accelerate.html">5. Accelerating LAMMPS performance</a></li> <li class="toctree-l1"><a class="reference internal" href="Section_howto.html">6. How-to discussions</a></li> <li class="toctree-l1"><a class="reference internal" href="Section_example.html">7. Example problems</a></li> <li class="toctree-l1"><a class="reference internal" href="Section_perf.html">8. Performance &amp; scalability</a></li> <li class="toctree-l1"><a class="reference internal" href="Section_tools.html">9. Additional tools</a></li> <li class="toctree-l1"><a class="reference internal" href="Section_modify.html">10. Modifying &amp; extending LAMMPS</a></li> <li class="toctree-l1"><a class="reference internal" href="Section_python.html">11. Python interface to LAMMPS</a></li> <li class="toctree-l1"><a class="reference internal" href="Section_errors.html">12. Errors</a></li> <li class="toctree-l1"><a class="reference internal" href="Section_history.html">13. Future and history</a></li> </ul> </div> &nbsp; </nav> <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"> <nav class="wy-nav-top" role="navigation" aria-label="top navigation"> <i data-toggle="wy-nav-top" class="fa fa-bars"></i> <a href="Manual.html">LAMMPS</a> </nav> <div class="wy-nav-content"> <div class="rst-content"> <div role="navigation" aria-label="breadcrumbs navigation"> <ul class="wy-breadcrumbs"> <li><a href="Manual.html">Docs</a> &raquo;</li> <li>compute dpd/atom command</li> <li class="wy-breadcrumbs-aside"> <a href="http://lammps.sandia.gov">Website</a> <a href="Section_commands.html#comm">Commands</a> </li> </ul> <hr/> </div> <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article"> <div itemprop="articleBody"> <div class="section" id="compute-dpd-atom-command"> <span id="index-0"></span><h1>compute dpd/atom command</h1> <div class="section" id="syntax"> <h2>Syntax</h2> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">compute</span> <span class="n">ID</span> <span class="n">group</span><span class="o">-</span><span class="n">ID</span> <span class="n">dpd</span><span class="o">/</span><span class="n">atom</span> </pre></div> </div> <ul class="simple"> <li>ID, group-ID are documented in <a class="reference internal" href="compute.html"><span class="doc">compute</span></a> command</li> <li>dpd/atom = style name of this compute command</li> </ul> </div> <div class="section" id="examples"> <h2>Examples</h2> <p>compute 1 all dpd/atom</p> </div> <div class="section" id="description"> <h2>Description</h2> <p>Define a computation that accesses the per-particle internal conductive energy (u_cond), internal mechanical energy (u_mech) and internal temperatures (dpdTheta) for each particle in a group. See the <a class="reference internal" href="compute_dpd.html"><span class="doc">compute dpd</span></a> command if you want the total internal conductive energy, the total internal mechanical energy, and average internal temperature of the entire system or group of dpd particles.</p> <p><strong>Output info:</strong></p> <p>This compute calculates a per-particle array with 3 columns (u_cond, u_mech, dpdTheta), which can be accessed by indices 1-3 by any command that uses per-particle values from a compute as input. See <a class="reference internal" href="Section_howto.html#howto-15"><span class="std std-ref">Section_howto15</span></a> for an overview of LAMMPS output options.</p> <p>The per-particle array values will be in energy (u_cond, u_mech) and temperature (dpdTheta) <a class="reference internal" href="units.html"><span class="doc">units</span></a>.</p> </div> <div class="section" id="restrictions"> <h2>Restrictions</h2> <p>The compute <em>dpd/atom</em> is only available if LAMMPS is built with the USER-DPD package.</p> </div> <div class="section" id="related-commands"> <h2>Related commands</h2> <p><a class="reference internal" href="dump.html"><span class="doc">dump custom</span></a>, <a class="reference internal" href="compute_dpd.html"><span class="doc">compute dpd</span></a></p> <p><strong>Default:</strong> none</p> <hr class="docutils" /> <p id="larentzos"><strong>(Larentzos)</strong> J.P. Larentzos, J.K. Brennan, J.D. Moore, and W.D. Mattson, &#8220;LAMMPS Implementation of Constant Energy Dissipative Particle Dynamics (DPD-E)&#8221;, ARL-TR-6863, U.S. Army Research Laboratory, Aberdeen Proving Ground, MD (2014).</p> </div> </div> </div> </div> <footer> <hr/> <div role="contentinfo"> <p> &copy; Copyright 2013 Sandia Corporation. </p> </div> Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. </footer> </div> </div> </section> </div> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT:'./', VERSION:'', COLLAPSE_INDEX:false, FILE_SUFFIX:'.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/javascript" src="_static/sphinxcontrib-images/LightBox2/lightbox2/js/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="_static/sphinxcontrib-images/LightBox2/lightbox2/js/lightbox.min.js"></script> <script type="text/javascript" src="_static/sphinxcontrib-images/LightBox2/lightbox2-customize/jquery-noconflict.js"></script> <script type="text/javascript" src="_static/js/theme.js"></script> <script type="text/javascript"> jQuery(function () { SphinxRtdTheme.StickyNav.enable(); }); </script> </body> </html>
zimmermant/dlvo_lammps
doc/html/compute_dpd_atom.html
HTML
gpl-2.0
8,317
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <imprec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\DICOM; use PHPExiftool\Driver\AbstractTag; class CumulativeDoseToDoseReference extends AbstractTag { protected $Id = '3008,0052'; protected $Name = 'CumulativeDoseToDoseReference'; protected $FullName = 'DICOM::Main'; protected $GroupName = 'DICOM'; protected $g0 = 'DICOM'; protected $g1 = 'DICOM'; protected $g2 = 'Image'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Cumulative Dose To Dose Reference'; }
Droces/casabio
vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/DICOM/CumulativeDoseToDoseReference.php
PHP
gpl-2.0
758
"C:\Program Files\MySQL\MySQL Server 5.6\bin\mysql.exe" -h localhost -udayz -ppass4dayz dayz -e "call removeDamagedVehicles"
rmnelson/dayz
scripts/maintenance/dbfunctions.bat
Batchfile
gpl-2.0
124
/****************************************************************************** * Icinga 2 * * Copyright (C) 2012-2017 Icinga Development Team (https://www.icinga.com/) * * * * 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, write to the Free Software Foundation * * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * ******************************************************************************/ #ifndef ARRAY_H #define ARRAY_H #include "base/i2-base.hpp" #include "base/objectlock.hpp" #include "base/value.hpp" #include <boost/range/iterator.hpp> #include <vector> #include <set> namespace icinga { /** * An array of Value items. * * @ingroup base */ class I2_BASE_API Array : public Object { public: DECLARE_OBJECT(Array); /** * An iterator that can be used to iterate over array elements. */ typedef std::vector<Value>::iterator Iterator; typedef std::vector<Value>::size_type SizeType; inline Array(void) { } inline Array(std::initializer_list<Value> init) : m_Data(init) { } inline ~Array(void) { } Value Get(SizeType index) const; void Set(SizeType index, const Value& value); void Set(SizeType index, Value&& value); void Add(const Value& value); void Add(Value&& value); /** * Returns an iterator to the beginning of the array. * * Note: Caller must hold the object lock while using the iterator. * * @returns An iterator. */ inline Iterator Begin(void) { ASSERT(OwnsLock()); return m_Data.begin(); } /** * Returns an iterator to the end of the array. * * Note: Caller must hold the object lock while using the iterator. * * @returns An iterator. */ inline Iterator End(void) { ASSERT(OwnsLock()); return m_Data.end(); } size_t GetLength(void) const; bool Contains(const Value& value) const; void Insert(SizeType index, const Value& value); void Remove(SizeType index); void Remove(Iterator it); void Resize(SizeType newSize); void Clear(void); void Reserve(SizeType newSize); void CopyTo(const Array::Ptr& dest) const; Array::Ptr ShallowClone(void) const; static Object::Ptr GetPrototype(void); template<typename T> static Array::Ptr FromVector(const std::vector<T>& v) { Array::Ptr result = new Array(); ObjectLock olock(result); std::copy(v.begin(), v.end(), std::back_inserter(result->m_Data)); return result; } template<typename T> std::set<T> ToSet(void) { ObjectLock olock(this); return std::set<T>(Begin(), End()); } template<typename T> static Array::Ptr FromSet(const std::set<T>& v) { Array::Ptr result = new Array(); ObjectLock olock(result); std::copy(v.begin(), v.end(), std::back_inserter(result->m_Data)); return result; } virtual Object::Ptr Clone(void) const override; Array::Ptr Reverse(void) const; void Sort(void); virtual String ToString(void) const override; virtual Value GetFieldByName(const String& field, bool sandboxed, const DebugInfo& debugInfo) const override; virtual void SetFieldByName(const String& field, const Value& value, const DebugInfo& debugInfo) override; private: std::vector<Value> m_Data; /**< The data for the array. */ }; inline Array::Iterator begin(Array::Ptr x) { return x->Begin(); } inline Array::Iterator end(Array::Ptr x) { return x->End(); } } #endif /* ARRAY_H */
Tontonitch/icinga2
lib/base/array.hpp
C++
gpl-2.0
4,328
<?php /** * 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; under version 2 * of the License (non-upgradable). * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Copyright (c) 2015 (original work) Open Assessment Technologies SA; * */ /** * Validates that the value is a valid email address. * * @author Aleh Hutnikau <hutnikau@1pt.com> * @package tao */ class tao_helpers_form_validators_Email extends tao_helpers_form_Validator { /** * Overrides parent default message * * @return string */ protected function getDefaultMessage() { return __('This is not a valid email address.'); } /** * Validates a value to see if it is a valid email. * * @access public * @author Aleh Hutnikau <hutnikau@1pt.com> * @param string $values the value to be validated * @return boolean whether the value is a valid email */ public function evaluate($values) { return (bool) filter_var($values, FILTER_VALIDATE_EMAIL); } }
oat-sa/tao-core
helpers/form/validators/class.Email.php
PHP
gpl-2.0
1,569
// pk 4/05 int MatrixExpEigenPrepare void MatrixExp(Matrix& A, Real t, Matrix& Exp); void Eigenvector(Matrix& A, Real ev, ColumnVector& C, Matrix& A_inv, bool right); int MatrixExpEigenPrepare(Matrix& A, ColumnVector& V, Matrix& U, Matrix& Uinv, SimpleIntArray& Cplx); void MatrixExpEigen(Matrix& Mexp, ColumnVector& V, Matrix& U, Matrix& Uinv, SimpleIntArray& Cplx, Real t); void LUDecompose(Matrix& A, SimpleIntArray& Indx, double& pd); void InvertMatrix(Matrix& A, Matrix& A_inv); void LUBackSubst(Matrix& A, SimpleIntArray& Indx, ColumnVector& B); // body file: nm_exp.cpp
ihh/dart
src/newmat/nm_exp.h
C
gpl-2.0
615
/* File: WaveDriverAirportExtreme.h Program: KisMAC Author: Michael Roßberg mick@binaervarianz.de Changes: Vitalii Parovishnyk(1012-2015) Description: KisMAC is a wireless stumbler for MacOS X. This file is part of KisMAC. Most parts of this file are based on aircrack by Christophe Devine. KisMAC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation; KisMAC 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 KisMAC; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #import "WaveDriver.h" enum APExtType { APExtTypeUnknown, APExtTypeBcm, APExtTypeAth5414 }; #define DLT_PRISM_HEADER 119 #define DLT_IEEE802_11 105 #define DLT_IEEE802_11_RADIO_AVS 163 #define DLT_IEEE802_11_RADIO 127 #define DLT_TYPE_ERR -1 @class CWInterface; @interface WaveDriverAirportExtreme : WaveDriver { enum APExtType _apeType; int DLTType; CWInterface * airportInterface; } @end
IGRSoft/KisMac2
Sources/WaveDrivers/WaveDriverAirportExtreme.h
C
gpl-2.0
1,397
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head><title></title> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta name="generator" content="Doxygen 1.8.8"/> <link rel="stylesheet" type="text/css" href="search.css"/> <script type="text/javascript" src="defines_6.js"></script> <script type="text/javascript" src="search.js"></script> </head> <body class="SRPage"> <div id="SRIndex"> <div class="SRStatus" id="Loading">Carregando...</div> <div id="SRResults"></div> <script type="text/javascript"><!-- createResults(); --></script> <div class="SRStatus" id="Searching">Procurando...</div> <div class="SRStatus" id="NoMatches">Nenhuma entrada encontrada</div> <script type="text/javascript"><!-- document.getElementById("Loading").style.display="none"; document.getElementById("NoMatches").style.display="none"; var searchResults = new SearchResults("searchResults"); searchResults.Search(); --></script> </div> </body> </html>
5putnik/discreta12eueumesmoehugo
doc/html/search/defines_6.html
HTML
gpl-2.0
1,036
class AddEditDashboardPermission < ActiveRecord::Migration def self.up permission = Permission.find_or_create_by_name("edit_dashboard") accounts = Account.all.select(&:owner) MethodCallbackFuture.create!(:models => accounts, :method => :grant_all_permissions_to_owner, :system => true) end def self.down Permission.find_by_name("edit_dashboard").destroy accounts = Account.all.select(&:owner) MethodCallbackFuture.create!(:models => accounts, :method => :grant_all_permissions_to_owner, :system => true) end end
xlsuite/xlsuite
db/migrate/20090409004839_add_edit_dashboard_permission.rb
Ruby
gpl-2.0
545
<!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.9.1"/> <title>PHPUnit: Member List</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/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </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">PHPUnit </div> <div id="projectbrief">PHPUnit TYPO3 extension</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <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 class="current"><a href="annotated.html"><span>Classes</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> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </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><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">Tx_Phpunit_ViewHelpers_ProgressBarViewHelper Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="classTx__Phpunit__ViewHelpers__ProgressBarViewHelper.html">Tx_Phpunit_ViewHelpers_ProgressBarViewHelper</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>$outputService</b> (defined in <a class="el" href="classTx__Phpunit__ViewHelpers__AbstractViewHelper.html">Tx_Phpunit_ViewHelpers_AbstractViewHelper</a>)</td><td class="entry"><a class="el" href="classTx__Phpunit__ViewHelpers__AbstractViewHelper.html">Tx_Phpunit_ViewHelpers_AbstractViewHelper</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr><td class="entry"><a class="el" href="classTx__Phpunit__ViewHelpers__AbstractViewHelper.html#a18a7ca07ea062306f760c6a742b46491">__destruct</a>()</td><td class="entry"><a class="el" href="classTx__Phpunit__ViewHelpers__AbstractViewHelper.html">Tx_Phpunit_ViewHelpers_AbstractViewHelper</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classTx__Phpunit__ViewHelpers__AbstractViewHelper.html#a053a6215a4af33c0bb3ae0ec909463b8">getLanguageService</a>()</td><td class="entry"><a class="el" href="classTx__Phpunit__ViewHelpers__AbstractViewHelper.html">Tx_Phpunit_ViewHelpers_AbstractViewHelper</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr><td class="entry"><a class="el" href="classTx__Phpunit__ViewHelpers__AbstractViewHelper.html#a187191a8d7bdd1418d4753db560eb90f">injectOutputService</a>(Tx_Phpunit_Service_OutputService $service)</td><td class="entry"><a class="el" href="classTx__Phpunit__ViewHelpers__AbstractViewHelper.html">Tx_Phpunit_ViewHelpers_AbstractViewHelper</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classTx__Phpunit__ViewHelpers__ProgressBarViewHelper.html#af010a4319ebdfcdebb5f15846c94f85c">render</a>()</td><td class="entry"><a class="el" href="classTx__Phpunit__ViewHelpers__ProgressBarViewHelper.html">Tx_Phpunit_ViewHelpers_ProgressBarViewHelper</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classTx__Phpunit__ViewHelpers__AbstractViewHelper.html#a322365f8d7b099c6e7e2f4d57a23f221">translate</a>($key)</td><td class="entry"><a class="el" href="classTx__Phpunit__ViewHelpers__AbstractViewHelper.html">Tx_Phpunit_ViewHelpers_AbstractViewHelper</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Fri Nov 27 2015 21:18:51 for PHPUnit by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
tomasnorre/ext-phpunit
Documentation/Api/html/classTx__Phpunit__ViewHelpers__ProgressBarViewHelper-members.html
HTML
gpl-2.0
6,317
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Set of functions used to build dumps of tables as PHP Arrays * * @package PhpMyAdmin-Export * @subpackage PHP */ namespace PMA\libraries\plugins\export; use PMA\libraries\plugins\ExportPlugin; use PMA\libraries\properties\plugins\ExportPluginProperties; use PMA\libraries\properties\options\items\HiddenPropertyItem; use PMA\libraries\properties\options\groups\OptionsPropertyMainGroup; use PMA\libraries\properties\options\groups\OptionsPropertyRootGroup; use PMA; /** * Handles the export for the PHP Array class * * @package PhpMyAdmin-Export * @subpackage PHP */ class ExportPhparray extends ExportPlugin { /** * Constructor */ public function __construct() { $this->setProperties(); } /** * Sets the export PHP Array properties * * @return void */ protected function setProperties() { $exportPluginProperties = new ExportPluginProperties(); $exportPluginProperties->setText('PHP array'); $exportPluginProperties->setExtension('php'); $exportPluginProperties->setMimeType('text/plain'); $exportPluginProperties->setOptionsText(__('Options')); // create the root group that will be the options field for // $exportPluginProperties // this will be shown as "Format specific options" $exportSpecificOptions = new OptionsPropertyRootGroup( "Format Specific Options" ); // general options main group $generalOptions = new OptionsPropertyMainGroup("general_opts"); // create primary items and add them to the group $leaf = new HiddenPropertyItem("structure_or_data"); $generalOptions->addProperty($leaf); // add the main group to the root group $exportSpecificOptions->addProperty($generalOptions); // set the options for the export plugin property item $exportPluginProperties->setOptions($exportSpecificOptions); $this->properties = $exportPluginProperties; } /** * Outputs export header * * @return bool Whether it succeeded */ public function exportHeader() { PMA_exportOutputHandler( '<?php' . $GLOBALS['crlf'] . '/**' . $GLOBALS['crlf'] . ' * Export to PHP Array plugin for PHPMyAdmin' . $GLOBALS['crlf'] . ' * @version 0.2b' . $GLOBALS['crlf'] . ' */' . $GLOBALS['crlf'] . $GLOBALS['crlf'] ); return true; } /** * Outputs export footer * * @return bool Whether it succeeded */ public function exportFooter() { return true; } /** * Outputs database header * * @param string $db Database name * @param string $db_alias Aliases of db * * @return bool Whether it succeeded */ public function exportDBHeader($db, $db_alias = '') { if (empty($db_alias)) { $db_alias = $db; } PMA_exportOutputHandler( '//' . $GLOBALS['crlf'] . '// Database ' . PMA\libraries\Util::backquote($db_alias) . $GLOBALS['crlf'] . '//' . $GLOBALS['crlf'] ); return true; } /** * Outputs database footer * * @param string $db Database name * * @return bool Whether it succeeded */ public function exportDBFooter($db) { return true; } /** * Outputs CREATE DATABASE statement * * @param string $db Database name * @param string $export_type 'server', 'database', 'table' * @param string $db_alias Aliases of db * * @return bool Whether it succeeded */ public function exportDBCreate($db, $export_type, $db_alias = '') { return true; } /** * Outputs the content of a table in PHP array format * * @param string $db database name * @param string $table table name * @param string $crlf the end of line sequence * @param string $error_url the url to go back in case of error * @param string $sql_query SQL query for obtaining data * @param array $aliases Aliases of db/table/columns * * @return bool Whether it succeeded */ public function exportData( $db, $table, $crlf, $error_url, $sql_query, $aliases = array() ) { $db_alias = $db; $table_alias = $table; $this->initAlias($aliases, $db_alias, $table_alias); $result = $GLOBALS['dbi']->query( $sql_query, null, PMA\libraries\DatabaseInterface::QUERY_UNBUFFERED ); $columns_cnt = $GLOBALS['dbi']->numFields($result); $columns = array(); for ($i = 0; $i < $columns_cnt; $i++) { $col_as = $GLOBALS['dbi']->fieldName($result, $i); if (!empty($aliases[$db]['tables'][$table]['columns'][$col_as])) { $col_as = $aliases[$db]['tables'][$table]['columns'][$col_as]; } $columns[$i] = stripslashes($col_as); } // fix variable names (based on // https://php.net/manual/language.variables.basics.php) if (!preg_match( '/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $table_alias ) ) { // fix invalid characters in variable names by replacing them with // underscores $tablefixed = preg_replace( '/[^a-zA-Z0-9_\x7f-\xff]/', '_', $table_alias ); // variable name must not start with a number or dash... if (preg_match('/^[a-zA-Z_\x7f-\xff]/', $tablefixed) === 0) { $tablefixed = '_' . $tablefixed; } } else { $tablefixed = $table; } $buffer = ''; $record_cnt = 0; // Output table name as comment $buffer .= $crlf . '// ' . PMA\libraries\Util::backquote($db_alias) . '.' . PMA\libraries\Util::backquote($table_alias) . $crlf; $buffer .= '$' . $tablefixed . ' = array('; while ($record = $GLOBALS['dbi']->fetchRow($result)) { $record_cnt++; if ($record_cnt == 1) { $buffer .= $crlf . ' array('; } else { $buffer .= ',' . $crlf . ' array('; } for ($i = 0; $i < $columns_cnt; $i++) { $buffer .= var_export($columns[$i], true) . " => " . var_export($record[$i], true) . (($i + 1 >= $columns_cnt) ? '' : ','); } $buffer .= ')'; } $buffer .= $crlf . ');' . $crlf; if (!PMA_exportOutputHandler($buffer)) { return false; } $GLOBALS['dbi']->freeResult($result); return true; } }
rawr-man/phpmyadmin2.0
libraries/plugins/export/ExportPhparray.php
PHP
gpl-2.0
7,008
<?php /** * @version 1.0.0 * @package com_legalconfirm * @copyright Copyright (C) 2013. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt * @author Abhishek Gupta <abhishek.gupta@daffodilsw.com> - http:// */ // no direct access defined('_JEXEC') or die; JHTML::_('behavior.modal'); $app = JFactory::getApplication(); $this->requestdata = $app->getUserState('com_legalconfirm.selectedlawfirmoffices.data'); //echo "<pre>"; print_r($this->requestdata); exit; $this->requestclientid = $app->getUserState('com_legalconfirm.clientprofile.clientid'); ?> <script> //var jq = jQuery.noConflict(); jQuery(document).ready(function(){ jQuery('.lawfirmremove').click(function(){ var t =jQuery(this).attr('id'); var lawfirmidt =jQuery(this).attr('name'); var tt = '#removelawfirm_'+lawfirmidt; var url = 'index.php?option=com_legalconfirm&format=raw&task=clientprofile.removelawfirm'; jQuery.ajax({ type: 'POST', url: url, data: 'lawfirmid=' + lawfirmidt, datatype:'json', success: function(res) { if(res) jQuery(tt).css('display','none'); }, error:function(){ alert("Lawfirm remove failure, please try again.."); } }); }); }); </script> <div class="addmore-wrraper"> <?php echo JText::_('COM_LEGALCONFIRM_ADDED_LAWFIRMS');?> <div class="submit1"> <a href="<?php echo JRoute::_('index.php?option=com_legalconfirm&view=clientlawfirmadd&tmpl=component&id='.$this->client->clientid);?>" class="modal" rel="{handler: 'iframe', size: {x: 700}}""> <?php echo JText::_('COM_LEGALCONFIRM_ADD_MORE_LAWFIRM');?> </a> </div> <div class="add-more-Lawfirm" id="add-more-Lawfirm"> <table> <tr class="rownew"> <th><?php echo JText::_('COM_LEGALCONFIRM_CLIENT_LAWFIRM_NAME');?></th> <th><?php echo JText::_('COM_LEGALCONFIRM_CLIENT_LAWFIRM_EMAIL');?></th> <th></th> </tr> <?php foreach ($this->requestdata as $newlawfirm): $lawfirmdataarry = $this->findlawfirmdetail($newlawfirm['lawfirm']); $checked = JHTML::_('grid.id', $i, $lawfirmdataarry->lawfirm); ?> <tr class="rownew" id="removelawfirm_<?php echo $lawfirmdataarry->lawfirmid;?>"> <td> <?php if(strlen($lawfirmdataarry->accounting_firm) > 10) echo substr($lawfirmdataarry->accounting_firm, 0,10).'..'; else echo $lawfirmdataarry->accounting_firm; ?> </td> <td> <?php if(strlen($lawfirmdataarry->email) > 20) echo substr($lawfirmdataarry->email, 0,20).'..'; else echo $lawfirmdataarry->email; ?> </td> <td> <a href="#" class="lawfirmremove" name ="<?php echo $lawfirmdataarry->lawfirmid; ?>" id="lawfirm_<?php echo $lawfirmdataarry->lawfirmid;?>"><?php echo JText::_('COM_LEGALCONFIRM_CLIENT_LAWFIRM_REMOVE');?></a> </td> </tr> <?php endforeach;?> </table> </div> </div> <script type="text/javascript"> //var jq = jQuery.noConflict(); jQuery(document).ready(function(){ jQuery('#add-more-Lawfirm').slimscroll({ height: '100px' }); }); </script>
yogendra9891/legalconfirm
components/com_legalconfirm/views/clientprofile/tmpl/default_lawfirmaddremove.php
PHP
gpl-2.0
3,048