code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
#!/usr/bin/env bash INTERFACE="${INTERFACE:-wlo1}" systemctl enable netctl-auto@$INTERFACE systemctl --user enable maintenance.timer systemctl --user enable battery.timer
AliGhahraei/scripts
arch-install/config/enable-systemd-timers.sh
Shell
gpl-3.0
172
package standalone_tools; import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.Set; import framework.DataQuery; import framework.DiffComplexDetector; import framework.DiffComplexDetector.SPEnrichment; import framework.DiffSeedCombDetector; import framework.QuantDACOResultSet; import framework.Utilities; /** * CompleXChange cmd-tool * @author Thorsten Will */ public class CompleXChange { static String version_string = "CompleXChange 1.01"; private static String path_group1 = "[GROUP1-FOLDER]"; private static String path_group2 = "[GROUP2-FOLDER]"; private static Map<String, QuantDACOResultSet> group1; private static Map<String, QuantDACOResultSet> group2; private static String path_seed = "no seed file defined"; private static Set<String> seed = null; private static String output_folder; private static double FDR = 0.05; private static boolean parametric = false; private static boolean paired = false; private static boolean incorporate_supersets = false; private static double min_variant_fraction = 0.75; private static boolean human_readable = false; private static boolean also_seedcomb_calcs = false; private static boolean also_seed_enrich = false; private static boolean filter_allosome = false; private static int no_threads = Math.max(Runtime.getRuntime().availableProcessors() / 2, 1); // assuming HT/SMT systems /** * Reads all matching output pairs of JDACO results/major transcripts from a certain folder: * [folder]/[sample-string]_complexes.txt(.gz) and [folder]/[sample-string]_major-transcripts.txt(.gz) * @param folder * @return */ public static Map<String, QuantDACOResultSet> readQuantDACOComplexes(String folder) { Map<String, QuantDACOResultSet> data = new HashMap<>(); for (File f:Utilities.getAllSuffixMatchingFilesInSubfolders(folder, "_major-transcripts.txt")) { String gz = ""; if (f.getName().endsWith(".gz")) gz = ".gz"; String pre = f.getAbsolutePath().split("_major-transcripts")[0]; String sample = f.getName().split("_major-transcripts")[0]; QuantDACOResultSet qdr = new QuantDACOResultSet(pre + "_complexes.txt" + gz, seed, pre + "_major-transcripts.txt" + gz); data.put(sample, qdr); } return data; } /** * Prints the help message */ public static void printHelp() { System.out.println("usage: java -jar CompleXChange.jar ([OPTIONS]) [GROUP1-FOLDER] [GROUP2-FOLDER] [OUTPUT-FOLDER]"); System.out.println(); System.out.println("[OPTIONS] (optional) :"); System.out.println(" -fdr=[FDR] : false discovery rate (default: 0.05)"); System.out.println(" -mf=[MIN_VAR_FRACTION] : fraction of either group a complex must be part of to be considered in the analysis (default: 0.75)"); System.out.println(" -s=[SEED-FILE] : file listing proteins around which the complexes are centered, e.g. seed file used for JDACO complex predictions (default: none)"); System.out.println(" -t=[#threads] : number of threads to be used (default: #cores/2)"); System.out.println(" -nd : assume normal distribution when testing (default: no assumption, non-parametric tests applied)"); System.out.println(" -p : assume paired/dependent data (default: unpaired/independent tests applied)"); System.out.println(" -ss : also associate supersets in the analyses (default: no supersets)"); System.out.println(" -enr : determine seed proteins enriched in up/down-regulated complexes (as in GSEA)"); System.out.println(" -sc : additional analysis based on seed combinations rather than sole complexes (as in GSEA)"); System.out.println(" -hr : additionally output human readable files with gene names and rounded numbers (default: no output)"); System.out.println(" -f : filter complexes with allosome proteins (default: no filtering)"); System.out.println(); System.out.println("[GROUPx-FOLDER] :"); System.out.println(" Standard PPIXpress/JDACO-output is read from those folders. JDACO results and major transcripts are needed."); System.out.println(); System.out.println("[OUTPUT-FOLDER]"); System.out.println(" The outcome is written to this folder. If it does not exist, it is created."); System.out.println(); System.exit(0); } /** * Prints the version of the program */ public static void printVersion() { System.out.println(version_string); System.exit(0); } /** * Parse arguments * @param args */ public static void parseInput(String[] args) { for (String arg:args) { // help needed? if (arg.equals("-h") || arg.equals("-help")) printHelp(); // output version else if (arg.equals("-version")) printVersion(); // parse FDR else if (arg.startsWith("-fdr=")) FDR = Double.parseDouble(arg.split("=")[1]); // parse min_variant_fraction else if (arg.startsWith("-mf=")) min_variant_fraction = Double.parseDouble(arg.split("=")[1]); // add seed file else if (arg.startsWith("-s=")) { path_seed = arg.split("=")[1]; seed = Utilities.readEntryFile(path_seed); if (seed == null) System.exit(1); // error will be thrown by the utility-function if (seed.isEmpty()) { System.err.println("Seed file " + path_seed + " is empty."); System.exit(1); } } // parse #threads else if (arg.startsWith("-t=")) no_threads = Math.max(Integer.parseInt(arg.split("=")[1]), 1); // parametric? else if (arg.equals("-nd")) parametric = true; // paired? else if (arg.equals("-p")) paired = true; // supersets? else if (arg.equals("-ss")) incorporate_supersets = true; // seed combinations? else if (arg.equals("-sc")) also_seedcomb_calcs = true; // seed enrichment? else if (arg.equals("-enr")) also_seed_enrich = true; // output human readable files? else if (arg.equals("-hr")) human_readable = true; // filter allosome proteins? else if (arg.equals("-f")) filter_allosome = true; // read groupwise input else if (group1 == null) { path_group1 = arg; if (!path_group1.endsWith("/")) path_group1 += "/"; group1 = readQuantDACOComplexes(path_group1); } else if (group2 == null) { path_group2 = arg; if (!path_group2.endsWith("/")) path_group2 += "/"; group2 = readQuantDACOComplexes(path_group2); } // set output-folder else if (output_folder == null) { output_folder = arg; if (!output_folder.endsWith("/")) output_folder += "/"; } } // some final checks if (group1 == null || group1.isEmpty() || group2 == null || group2.isEmpty()) { if (group1 == null || group1.isEmpty()) System.err.println(path_group1 + " does not exist or contains no useable data."); if (group2 == null || group2.isEmpty()) System.err.println(path_group2 + " does not exist or contains no useable data."); System.exit(1); } if (group1.size() < 2 || group2.size() < 2) { if (group1.size() < 2) System.err.println(path_group1 + " does not contain enough data. At least two samples per group are needed for a statistical evaluation."); if (group2.size() < 2) System.err.println(path_group2 + " does not contain enough data. At least two samples per group are needed for a statistical evaluation."); System.exit(1); } if (output_folder == null) { System.err.println("Please add an output folder."); System.exit(1); } // check for invalid usage of seedcomb mode if (also_seedcomb_calcs && seed == null) { also_seedcomb_calcs = false; System.out.println("Analysis of seed combination variants in complexes requires a seed file, this additional analysis is skipped."); } if (also_seed_enrich && seed == null) { also_seed_enrich = false; System.out.println("Analysis of seed protein enrichment in complexes requires a seed file, this additional analysis is skipped."); } } public static void main(String[] args) { if (args.length == 1 && args[0].equals("-version")) printVersion(); if (args.length < 3) { printHelp(); } // parse cmd-line and set all parameters try { parseInput(args); } catch (Exception e) { System.out.println("Something went wrong while reading the command-line, please check your input!"); System.out.println(); printHelp(); } // preface if (group1.size() < 5 || group2.size() < 5) { System.out.println("Computations will run as intended, but be aware that at least five samples per group are recommended to gather meaningful results."); } System.out.println("Seed: " + path_seed); System.out.println("FDR: " + FDR); String test = "Wilcoxon rank sum test (unpaired, non-parametric)"; if (paired && parametric) test = "paired t-test (paired, parametric)"; else if (paired) test = "Wilcoxon signed-rank test (paired, non-parametric)"; else if (parametric) test = "Welch's unequal variances t-test (unpaired, parametric)"; System.out.println("Statistical test: " + test); System.out.println("Min. fraction: " + min_variant_fraction); System.out.println("Incorporate supersets: " + (incorporate_supersets ? "yes" : "no")); if (filter_allosome) { System.out.print("Filtering of complexes with allosome proteins enabled. Downloading data ... "); String db = DataQuery.getEnsemblOrganismDatabaseFromProteins(group1.values().iterator().next().getAbundantSeedProteins()); DataQuery.getAllosomeProteins(db); System.out.println("done."); } System.out.println(); // computations boolean output_to_write = false; System.out.println("Processing " + path_group1 + " (" + group1.keySet().size() + ") vs " + path_group2 + " (" + group2.keySet().size() + ") ..."); System.out.flush(); DiffComplexDetector dcd = new DiffComplexDetector(group1, group2, FDR, parametric, paired, incorporate_supersets, min_variant_fraction, no_threads, filter_allosome); if (seed != null) System.out.println(dcd.getRawPValues().size() + " complexes tested, " + dcd.getSignificanceSortedComplexes().size() +" (" + dcd.getSignSortedVariants(false, false).size() + " seed combination variants) significant."); else System.out.println(dcd.getRawPValues().size() + " complexes tested, " + dcd.getSignificanceSortedComplexes().size() + " significant."); System.out.flush(); output_to_write = !dcd.getSignificanceSortedComplexes().isEmpty(); DiffSeedCombDetector dscd = null; if (also_seedcomb_calcs) { dscd = new DiffSeedCombDetector(group1, group2, FDR, parametric, paired, incorporate_supersets, min_variant_fraction, no_threads, filter_allosome); System.out.println(dscd.getVariantsRawPValues().size() + " seed combinations tested, " + dscd.getSignificanceSortedVariants().size() + " significant."); if (!dscd.getSignificanceSortedVariants().isEmpty()) output_to_write = true; System.out.flush(); } SPEnrichment spe = null; if (seed == null && also_seed_enrich) { System.out.println("Please specify a seed protein file if seed protein enrichment should be determined."); System.out.flush(); } else if (seed != null && also_seed_enrich) { System.out.println("Calculating seed protein enrichment with 10000 permutations to approximate null distribution and only considering seed proteins participating in at least 10 complexes."); System.out.flush(); spe = dcd.calculateSPEnrichment(FDR, 10000, 10); if (!spe.getSignificanceSortedSeedProteins().isEmpty()) output_to_write = true; } /* * write file-output */ if (!output_to_write) { System.out.println("Since there is nothing to report, no output is written."); System.exit(0); } // check if output-folder exists, otherwise create it File f = new File(output_folder); if (!f.exists()) f.mkdir(); // write output files System.out.println("Writing results ..."); dcd.writeSignSortedComplexes(output_folder + "diff_complexes.txt", false); if (seed != null) { dcd.writeSignSortedVariants(output_folder + "diff_seedcomb_in_complexes.txt", false); if (also_seedcomb_calcs) dscd.writeSignSortedVariants(output_folder + "diff_seed_combinations.txt", false); if (also_seed_enrich) spe.writeSignificantSeedProteins(output_folder + "enriched_seed_proteins.txt"); } if (human_readable) { System.out.println("Retrieving data on gene names ..."); System.out.flush(); System.out.println("Output human readable results ..."); dcd.writeSignSortedComplexes(output_folder + "diff_complexes_hr.txt", true); if (seed != null) { dcd.writeSignSortedVariants(output_folder + "diff_seedcomb_in_complexes_hr.txt", true); if (also_seedcomb_calcs) dscd.writeSignSortedVariants(output_folder + "diff_seed_combinations_hr.txt", true); } } } }
edeltoaster/jdaco_dev
jdaco_dev/src/standalone_tools/CompleXChange.java
Java
gpl-3.0
12,876
// black-box testing package router_test import ( "testing" "github.com/kataras/iris" "github.com/kataras/iris/context" "github.com/kataras/iris/core/router" "github.com/kataras/iris/httptest" ) type testController struct { router.Controller } var writeMethod = func(c router.Controller) { c.Ctx.Writef(c.Ctx.Method()) } func (c *testController) Get() { writeMethod(c.Controller) } func (c *testController) Post() { writeMethod(c.Controller) } func (c *testController) Put() { writeMethod(c.Controller) } func (c *testController) Delete() { writeMethod(c.Controller) } func (c *testController) Connect() { writeMethod(c.Controller) } func (c *testController) Head() { writeMethod(c.Controller) } func (c *testController) Patch() { writeMethod(c.Controller) } func (c *testController) Options() { writeMethod(c.Controller) } func (c *testController) Trace() { writeMethod(c.Controller) } type ( testControllerAll struct{ router.Controller } testControllerAny struct{ router.Controller } // exactly same as All ) func (c *testControllerAll) All() { writeMethod(c.Controller) } func (c *testControllerAny) All() { writeMethod(c.Controller) } func TestControllerMethodFuncs(t *testing.T) { app := iris.New() app.Controller("/", new(testController)) app.Controller("/all", new(testControllerAll)) app.Controller("/any", new(testControllerAny)) e := httptest.New(t, app) for _, method := range router.AllMethods { e.Request(method, "/").Expect().Status(httptest.StatusOK). Body().Equal(method) e.Request(method, "/all").Expect().Status(httptest.StatusOK). Body().Equal(method) e.Request(method, "/any").Expect().Status(httptest.StatusOK). Body().Equal(method) } } type testControllerPersistence struct { router.Controller Data string `iris:"persistence"` } func (t *testControllerPersistence) Get() { t.Ctx.WriteString(t.Data) } func TestControllerPersistenceFields(t *testing.T) { data := "this remains the same for all requests" app := iris.New() app.Controller("/", &testControllerPersistence{Data: data}) e := httptest.New(t, app) e.GET("/").Expect().Status(httptest.StatusOK). Body().Equal(data) } type testControllerBeginAndEndRequestFunc struct { router.Controller Username string } // called before of every method (Get() or Post()). // // useful when more than one methods using the // same request values or context's function calls. func (t *testControllerBeginAndEndRequestFunc) BeginRequest(ctx context.Context) { t.Username = ctx.Params().Get("username") // or t.Params.Get("username") because the // t.Ctx == ctx and is being initialized before this "BeginRequest" } // called after every method (Get() or Post()). func (t *testControllerBeginAndEndRequestFunc) EndRequest(ctx context.Context) { ctx.Writef("done") // append "done" to the response } func (t *testControllerBeginAndEndRequestFunc) Get() { t.Ctx.Writef(t.Username) } func (t *testControllerBeginAndEndRequestFunc) Post() { t.Ctx.Writef(t.Username) } func TestControllerBeginAndEndRequestFunc(t *testing.T) { app := iris.New() app.Controller("/profile/{username}", new(testControllerBeginAndEndRequestFunc)) e := httptest.New(t, app) usernames := []string{ "kataras", "makis", "efi", "rg", "bill", "whoisyourdaddy", } doneResponse := "done" for _, username := range usernames { e.GET("/profile/" + username).Expect().Status(httptest.StatusOK). Body().Equal(username + doneResponse) e.POST("/profile/" + username).Expect().Status(httptest.StatusOK). Body().Equal(username + doneResponse) } }
EriconYu/stocksniper
src/vendor/github.com/kataras/iris/core/router/controller_test.go
GO
gpl-3.0
3,581
/* * Geopaparazzi - Digital field mapping on Android based devices * Copyright (C) 2016 HydroloGIS (www.hydrologis.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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package eu.geopaparazzi.library.profiles.objects; import android.os.Parcel; import android.os.Parcelable; import eu.geopaparazzi.library.network.download.IDownloadable; /** * Created by hydrologis on 19/03/18. */ public class ProfileOtherfiles extends ARelativePathResource implements Parcelable, IDownloadable { public String url = ""; public String modifiedDate = ""; public long size = -1; private String destinationPath = ""; public ProfileOtherfiles() { } protected ProfileOtherfiles(Parcel in) { url = in.readString(); modifiedDate = in.readString(); size = in.readLong(); destinationPath = in.readString(); } public static final Creator<ProfileOtherfiles> CREATOR = new Creator<ProfileOtherfiles>() { @Override public ProfileOtherfiles createFromParcel(Parcel in) { return new ProfileOtherfiles(in); } @Override public ProfileOtherfiles[] newArray(int size) { return new ProfileOtherfiles[size]; } }; @Override public long getSize() { return size; } @Override public String getUrl() { return url; } @Override public String getDestinationPath() { return destinationPath; } @Override public void setDestinationPath(String path) { destinationPath = path; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(url); dest.writeString(modifiedDate); dest.writeLong(size); dest.writeString(destinationPath); } }
geopaparazzi/geopaparazzi
geopaparazzi_library/src/main/java/eu/geopaparazzi/library/profiles/objects/ProfileOtherfiles.java
Java
gpl-3.0
2,473
#from moderation import moderation #from .models import SuccessCase #moderation.register(SuccessCase)
djangobrasil/djangobrasil.org
src/djangobrasil/success_cases/moderator.py
Python
gpl-3.0
104
document.addEventListener("DOMContentLoaded", function(event) { if (/android|blackberry|iPhone|iPad|iPod|webOS/i.test(navigator.userAgent) === false) { var linkDescrs = document.querySelectorAll('.link-descr'); Array.prototype.forEach.call(linkDescrs, function(el, i) { el.parentNode.addEventListener('mouseenter', animateTypeText); el.parentNode.addEventListener('mouseleave', destroyTypeText); }); } else { var linkDescrs = document.querySelectorAll('.link-descr'); Array.prototype.forEach.call(linkDescrs, function(el, i) { removeClass(el, 'link-descr'); }); } }); var addClass = function(elem, add_class) { elem.setAttribute("class", elem.getAttribute("class") + ' ' + add_class); }; var removeClass = function(elem, rem_class) { var origClass = elem.getAttribute("class"); var remClassRegex = new Regexp("(\\s*)"+rem_class+"(\\s*)"); var classMatch = origClass.match(remClassRegex); var replaceString = ''; if (classMatch[1].length > 0 || classMatch[2].length > 0) { replaceString = ' '; } var newClass = origClass.replace(remClassRegex, replaceString); elem.setAttribute("class", newClass); }; var animateTypeText = function() { var elem = this; var typeArea = document.createElement("span"); typeArea.setAttribute("class", "link-subtext"); elem.insertBefore(typeArea, elem.querySelector("span:last-of-type")); setTimeout(addLetter(elem), 40); }; var addLetter = function(elem) { // if (elem.parentElement.querySelector(":hover") === elem) { var subtextSpan = elem.querySelector(".link-subtext"); var descrText = elem.querySelector(".link-descr").textContent; if (subtextSpan === null) { return; } var currentText = subtextSpan.textContent.slice(0,-1); var currentPos = currentText.length; subtextSpan.textContent = currentText + descrText.slice(currentPos, currentPos+1) + "\u258B"; if (currentText.length < descrText.length) { setTimeout(function(){addLetter(elem)}, 40); } // } }; var destroyTypeText = function() { var elem = this; elem.removeChild(elem.querySelector('.link-subtext')); };
thedanielgray/thedanielgray.github.io
js/gray.js
JavaScript
gpl-3.0
2,070
<?xml version="1.0" encoding="iso-8859-1"?> <!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> <!-- template designed by Marco Von Ballmoos --> <title>File Source for THead.php</title> <link rel="stylesheet" href="../media/stylesheet.css" /> </head> <body> <h1>Source for file THead.php</h1> <p>Documentation is available at <a href="../Elements/_Elements---Table---THead.php.html">THead.php</a></p> <div class="src-code"> <div class="src-code"><ol><li><div class="src-line"><a name="a1"></a><span class="src-php">&lt;?php</span></div></li> <li><div class="src-line"><a name="a2"></a><span class="src-doc">/**</span></div></li> <li><div class="src-line"><a name="a3"></a><span class="src-doc">&nbsp;*&nbsp;The&nbsp;&lt;thead&gt;&nbsp;tag&nbsp;is&nbsp;used&nbsp;to&nbsp;group&nbsp;the&nbsp;header&nbsp;content&nbsp;in&nbsp;an&nbsp;HTML&nbsp;table.</span></div></li> <li><div class="src-line"><a name="a4"></a><span class="src-doc">&nbsp;*&nbsp;</span></div></li> <li><div class="src-line"><a name="a5"></a><span class="src-doc">&nbsp;*&nbsp;&lt;p&gt;The&nbsp;thead&nbsp;element&nbsp;should&nbsp;be&nbsp;used&nbsp;in&nbsp;conjunction&nbsp;with&nbsp;the&nbsp;tbody&nbsp;and&nbsp;tfoot&nbsp;elements.&lt;/p&gt;</span></div></li> <li><div class="src-line"><a name="a6"></a><span class="src-doc">&nbsp;*&nbsp;&lt;p&gt;The&nbsp;tbody&nbsp;element&nbsp;is&nbsp;used&nbsp;to&nbsp;group&nbsp;the&nbsp;body&nbsp;content&nbsp;in&nbsp;an&nbsp;HTML&nbsp;table&nbsp;and&nbsp;the&nbsp;tfoot</span></div></li> <li><div class="src-line"><a name="a7"></a><span class="src-doc">&nbsp;*&nbsp;element&nbsp;is&nbsp;used&nbsp;to&nbsp;group&nbsp;the&nbsp;footer&nbsp;content&nbsp;in&nbsp;an&nbsp;HTML&nbsp;table.&lt;/p&gt;</span></div></li> <li><div class="src-line"><a name="a8"></a><span class="src-doc">&nbsp;*&nbsp;&lt;p&gt;&lt;b&gt;Note:&lt;/b&gt;&nbsp;&lt;tfoot&gt;&nbsp;must&nbsp;appear&nbsp;before&nbsp;&lt;tbody&gt;&nbsp;within&nbsp;a&nbsp;table,&nbsp;so&nbsp;that&nbsp;a&nbsp;browser</span></div></li> <li><div class="src-line"><a name="a9"></a><span class="src-doc">&nbsp;*&nbsp;can&nbsp;render&nbsp;the&nbsp;foot&nbsp;before&nbsp;receiving&nbsp;all&nbsp;the&nbsp;rows&nbsp;of&nbsp;data.&lt;/p&gt;</span></div></li> <li><div class="src-line"><a name="a10"></a><span class="src-doc">&nbsp;*&nbsp;&lt;p&gt;Notice&nbsp;that&nbsp;these&nbsp;elements&nbsp;will&nbsp;not&nbsp;affect&nbsp;the&nbsp;layout&nbsp;of&nbsp;the&nbsp;table&nbsp;by&nbsp;default.</span></div></li> <li><div class="src-line"><a name="a11"></a><span class="src-doc">&nbsp;*&nbsp;However,&nbsp;you&nbsp;can&nbsp;use&nbsp;CSS&nbsp;to&nbsp;let&nbsp;these&nbsp;elements&nbsp;affect&nbsp;the&nbsp;table's&nbsp;layout.&lt;/p&gt;</span></div></li> <li><div class="src-line"><a name="a12"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-inlinetag">{@link&nbsp;http://www.w3schools.com/tags/tag_thead.asp&nbsp;}</span></div></li> <li><div class="src-line"><a name="a13"></a><span class="src-doc">&nbsp;*&nbsp;</span></div></li> <li><div class="src-line"><a name="a14"></a><span class="src-doc">&nbsp;*&nbsp;PHP&nbsp;version&nbsp;5</span></div></li> <li><div class="src-line"><a name="a15"></a><span class="src-doc">&nbsp;*&nbsp;</span></div></li> <li><div class="src-line"><a name="a16"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@example</span><span class="src-doc">&nbsp;&nbsp;&nbsp;simple.php&nbsp;How&nbsp;to&nbsp;use</span></div></li> <li><div class="src-line"><a name="a17"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@filesource</span></div></li> <li><div class="src-line"><a name="a18"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@category</span><span class="src-doc">&nbsp;&nbsp;Element</span></div></li> <li><div class="src-line"><a name="a19"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@package</span><span class="src-doc">&nbsp;&nbsp;&nbsp;Elements</span></div></li> <li><div class="src-line"><a name="a20"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@author</span><span class="src-doc">&nbsp;&nbsp;&nbsp;&nbsp;Jens&nbsp;Peters&nbsp;&lt;[email protected]&gt;</span></div></li> <li><div class="src-line"><a name="a21"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@copyright</span><span class="src-doc">&nbsp;2011&nbsp;Jens&nbsp;Peters</span></div></li> <li><div class="src-line"><a name="a22"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@license</span><span class="src-doc">&nbsp;&nbsp;&nbsp;http://www.gnu.org/licenses/lgpl.html&nbsp;GNU&nbsp;LGPL&nbsp;v3</span></div></li> <li><div class="src-line"><a name="a23"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@version</span><span class="src-doc">&nbsp;&nbsp;&nbsp;1.1</span></div></li> <li><div class="src-line"><a name="a24"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@link</span><span class="src-doc">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;http://launchpad.net/htmlbuilder</span></div></li> <li><div class="src-line"><a name="a25"></a><span class="src-doc">&nbsp;*/</span></div></li> <li><div class="src-line"><a name="a26"></a>namespace&nbsp;<span class="src-id">HTMLBuilder</span>\<span class="src-id">Elements</span>\<span class="src-id"><a href="../Elements/General/Table.html">Table</a></span><span class="src-sym">;</span></div></li> <li><div class="src-line"><a name="a27"></a>use&nbsp;<span class="src-id">HTMLBuilder</span>\<span class="src-id">Elements</span>\<span class="src-id"><a href="../Elements/Base/Root.html">Root</a></span><span class="src-sym">;</span></div></li> <li><div class="src-line"><a name="a28"></a>&nbsp;</div></li> <li><div class="src-line"><a name="a29"></a><span class="src-doc">/**</span></div></li> <li><div class="src-line"><a name="a30"></a><span class="src-doc">&nbsp;*&nbsp;The&nbsp;&lt;thead&gt;&nbsp;tag&nbsp;is&nbsp;used&nbsp;to&nbsp;group&nbsp;the&nbsp;header&nbsp;content&nbsp;in&nbsp;an&nbsp;HTML&nbsp;table.</span></div></li> <li><div class="src-line"><a name="a31"></a><span class="src-doc">&nbsp;*&nbsp;</span></div></li> <li><div class="src-line"><a name="a32"></a><span class="src-doc">&nbsp;*&nbsp;&lt;p&gt;The&nbsp;thead&nbsp;element&nbsp;should&nbsp;be&nbsp;used&nbsp;in&nbsp;conjunction&nbsp;with&nbsp;the&nbsp;tbody&nbsp;and&nbsp;tfoot&nbsp;elements.&lt;/p&gt;</span></div></li> <li><div class="src-line"><a name="a33"></a><span class="src-doc">&nbsp;*&nbsp;&lt;p&gt;The&nbsp;tbody&nbsp;element&nbsp;is&nbsp;used&nbsp;to&nbsp;group&nbsp;the&nbsp;body&nbsp;content&nbsp;in&nbsp;an&nbsp;HTML&nbsp;table&nbsp;and&nbsp;the&nbsp;tfoot</span></div></li> <li><div class="src-line"><a name="a34"></a><span class="src-doc">&nbsp;*&nbsp;element&nbsp;is&nbsp;used&nbsp;to&nbsp;group&nbsp;the&nbsp;footer&nbsp;content&nbsp;in&nbsp;an&nbsp;HTML&nbsp;table.&lt;/p&gt;</span></div></li> <li><div class="src-line"><a name="a35"></a><span class="src-doc">&nbsp;*&nbsp;&lt;p&gt;&lt;b&gt;Note:&lt;/b&gt;&nbsp;&lt;tfoot&gt;&nbsp;must&nbsp;appear&nbsp;before&nbsp;&lt;tbody&gt;&nbsp;within&nbsp;a&nbsp;table,&nbsp;so&nbsp;that&nbsp;a&nbsp;browser</span></div></li> <li><div class="src-line"><a name="a36"></a><span class="src-doc">&nbsp;*&nbsp;can&nbsp;render&nbsp;the&nbsp;foot&nbsp;before&nbsp;receiving&nbsp;all&nbsp;the&nbsp;rows&nbsp;of&nbsp;data.&lt;/p&gt;</span></div></li> <li><div class="src-line"><a name="a37"></a><span class="src-doc">&nbsp;*&nbsp;&lt;p&gt;Notice&nbsp;that&nbsp;these&nbsp;elements&nbsp;will&nbsp;not&nbsp;affect&nbsp;the&nbsp;layout&nbsp;of&nbsp;the&nbsp;table&nbsp;by&nbsp;default.</span></div></li> <li><div class="src-line"><a name="a38"></a><span class="src-doc">&nbsp;*&nbsp;However,&nbsp;you&nbsp;can&nbsp;use&nbsp;CSS&nbsp;to&nbsp;let&nbsp;these&nbsp;elements&nbsp;affect&nbsp;the&nbsp;table's&nbsp;layout.&lt;/p&gt;</span></div></li> <li><div class="src-line"><a name="a39"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-inlinetag">{@link&nbsp;http://www.w3schools.com/tags/tag_thead.asp&nbsp;}</span></div></li> <li><div class="src-line"><a name="a40"></a><span class="src-doc">&nbsp;*&nbsp;</span></div></li> <li><div class="src-line"><a name="a41"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@category</span><span class="src-doc">&nbsp;&nbsp;&nbsp;Element</span></div></li> <li><div class="src-line"><a name="a42"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@example</span><span class="src-doc">&nbsp;&nbsp;&nbsp;&nbsp;simple.php&nbsp;see&nbsp;HOW&nbsp;TO&nbsp;USE</span></div></li> <li><div class="src-line"><a name="a43"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@example</span><span class="src-doc">&nbsp;&nbsp;&nbsp;&nbsp;debug.php&nbsp;see&nbsp;HOW&nbsp;TO&nbsp;DEBUG</span></div></li> <li><div class="src-line"><a name="a44"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@package</span><span class="src-doc">&nbsp;&nbsp;&nbsp;&nbsp;Elements</span></div></li> <li><div class="src-line"><a name="a45"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@subpackage</span><span class="src-doc">&nbsp;General</span></div></li> <li><div class="src-line"><a name="a46"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@author</span><span class="src-doc">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Jens&nbsp;Peters&nbsp;&lt;[email protected]&gt;</span></div></li> <li><div class="src-line"><a name="a47"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@license</span><span class="src-doc">&nbsp;&nbsp;&nbsp;&nbsp;http://www.gnu.org/licenses/lgpl.html&nbsp;GNU&nbsp;LGPL&nbsp;v3</span></div></li> <li><div class="src-line"><a name="a48"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@link</span><span class="src-doc">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;http://launchpad.net/htmlbuilder</span></div></li> <li><div class="src-line"><a name="a49"></a><span class="src-doc">&nbsp;*/</span></div></li> <li><div class="src-line"><a name="a50"></a><span class="src-key">class&nbsp;</span><a href="../Elements/General/THead.html">THead</a>&nbsp;<span class="src-key">extends&nbsp;</span><a href="../Elements/General/RootRow.html">RootRow</a>&nbsp;<span class="src-sym">{</span></div></li> <li><div class="src-line"><a name="a51"></a>&nbsp;</div></li> <li><div class="src-line"><a name="a52"></a>&nbsp;&nbsp;&nbsp;&nbsp;<span class="src-key">public&nbsp;</span><span class="src-key">function&nbsp;</span><a href="../Elements/General/THead.html#methodinitElement">initElement</a><span class="src-sym">(</span><span class="src-sym">)&nbsp;</span><span class="src-sym">{</span></div></li> <li><div class="src-line"><a name="a53"></a>&nbsp;</div></li> <li><div class="src-line"><a name="a54"></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="src-var">$this</span><span class="src-sym">-&gt;</span><a href="../Elements/Base/Root.html#var$_allowedChildren">_allowedChildren</a>&nbsp;=&nbsp;<span class="src-key">array&nbsp;</span><span class="src-sym">(</span></div></li> <li><div class="src-line"><a name="a55"></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="src-str">&quot;tr&quot;</span></div></li> <li><div class="src-line"><a name="a56"></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line"><a name="a57"></a>&nbsp;&nbsp;&nbsp;&nbsp;<span class="src-sym">}</span></div></li> <li><div class="src-line"><a name="a58"></a><span class="src-sym">}</span></div></li> </ol></div> </div> <p class="notes" id="credit"> Documentation generated on Sat, 22 Dec 2012 00:28:46 +0100 by <a href="http://www.phpdoc.org" target="_blank">phpDocumentor 1.4.4</a> </p> </body> </html>
lasso/textura
src/htmlbuilder/phpdoc/__filesource/fsource_Elements__ElementsTableTHead.php.html
HTML
gpl-3.0
12,283
package de.turnierverwaltung.control.settingsdialog; import java.awt.Dialog; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.sql.SQLException; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import de.turnierverwaltung.control.ExceptionHandler; import de.turnierverwaltung.control.MainControl; import de.turnierverwaltung.control.Messages; import de.turnierverwaltung.control.PropertiesControl; import de.turnierverwaltung.control.ratingdialog.DWZListToSQLITEControl; import de.turnierverwaltung.control.ratingdialog.ELOListToSQLITEControl; import de.turnierverwaltung.control.sqlite.SaveTournamentControl; import de.turnierverwaltung.model.TournamentConstants; import de.turnierverwaltung.view.settingsdialog.SettingsView; import say.swing.JFontChooser; public class ActionListenerSettingsControl { private final MainControl mainControl; private final SettingsControl esControl; private JDialog dialog; public ActionListenerSettingsControl(final MainControl mainControl, final SettingsControl esControl) { super(); this.mainControl = mainControl; this.esControl = esControl; addPropertiesActionListener(); } public void addActionListeners() { esControl.getEigenschaftenView().getFontChooserButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final JFontChooser fontChooser = esControl.getEigenschaftenView().getFontChooser(); fontChooser.setSelectedFont(mainControl.getPropertiesControl().getFont()); final int result = fontChooser.showDialog(esControl.getEigenschaftenView()); if (result == JFontChooser.OK_OPTION) { final Font selectedFont = fontChooser.getSelectedFont(); MainControl.setUIFont(selectedFont); mainControl.getPropertiesControl().setFont(selectedFont); mainControl.getPropertiesControl().writeProperties(); } } }); esControl.getEigenschaftenView().getOkButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { mainControl.getPropertiesControl().writeSettingsDialogProperties(dialog.getBounds().x, dialog.getBounds().y, dialog.getBounds().width, dialog.getBounds().height); dialog.dispose(); final PropertiesControl ppC = mainControl.getPropertiesControl(); final SettingsView settingsView = esControl.getEigenschaftenView(); ppC.setTableComumnBlack(settingsView.getBlackTextField().getText()); ppC.setTableComumnWhite(settingsView.getWhiteTextField().getText()); ppC.setTableComumnMeeting(settingsView.getMeetingTextField().getText()); ppC.setTableComumnNewDWZ(settingsView.getNewDWZTextField().getText()); ppC.setTableComumnOldDWZ(settingsView.getOldDWZTextField().getText()); ppC.setTableComumnNewELO(settingsView.getNewELOTextField().getText()); ppC.setTableComumnOldELO(settingsView.getOldELOTextField().getText()); ppC.setTableComumnPlayer(settingsView.getPlayerTextField().getText()); ppC.setTableComumnPoints(settingsView.getPointsTextField().getText()); ppC.setTableComumnRanking(settingsView.getRankingTextField().getText()); ppC.setTableComumnResult(settingsView.getResultTextField().getText()); ppC.setTableComumnSonnebornBerger(settingsView.getSbbTextField().getText()); ppC.setTableComumnRound(settingsView.getRoundTextField().getText()); ppC.setSpielfrei(settingsView.getSpielfreiTextField().getText()); if (mainControl.getPlayerListControl() != null) { mainControl.getPlayerListControl().testPlayerListForDoubles(); } ppC.setCutForename(settingsView.getForenameLengthBox().getValue()); ppC.setCutSurname(settingsView.getSurnameLengthBox().getValue()); ppC.setWebserverPath(settingsView.getWebserverPathTextField().getText()); ppC.checkCrossTableColumnForDoubles(); ppC.checkMeetingTableColumnForDoubles(); ppC.setCSSTable(settingsView.getTableCSSTextField().getText()); ppC.writeProperties(); esControl.setTableColumns(); } }); esControl.getEigenschaftenView().getOpenVereineCSVButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { // vereine.csv final File path = new File(mainControl.getPropertiesControl().getDefaultPath()); final JFileChooser fc = new JFileChooser(path); final FileFilter filter = new FileNameExtensionFilter("CSV file", "csv", "CSV"); fc.setFileFilter(filter); final int returnVal = fc.showOpenDialog(esControl.getEigenschaftenView()); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = fc.getSelectedFile(); // This is where a real application would open the // file. mainControl.getPropertiesControl().setPathToVereineCVS(file.getAbsolutePath()); mainControl.getPropertiesControl().writeProperties(); esControl.getEigenschaftenView() .setOpenVereineCSVLabel(mainControl.getPropertiesControl().getPathToVereineCVS()); } } }); esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { final DWZListToSQLITEControl dwzL = new DWZListToSQLITEControl(mainControl); dwzL.convertDWZListToSQLITE(); esControl.getEigenschaftenView() .setOpenPlayersCSVLabel(mainControl.getPropertiesControl().getPathToPlayersCSV()); esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(false); } }); esControl.getEigenschaftenView().getOpenPlayersCSVButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { // spieler.csv final File path = new File(mainControl.getPropertiesControl().getDefaultPath()); final JFileChooser fc = new JFileChooser(path); final FileFilter filter = new FileNameExtensionFilter("CSV or SQLite file", "csv", "CSV", "sqlite", "SQLite"); fc.setFileFilter(filter); final int returnVal = fc.showOpenDialog(esControl.getEigenschaftenView()); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = fc.getSelectedFile(); // This is where a real application would open the // file. mainControl.getPropertiesControl().setPathToPlayersCSV(file.getAbsolutePath()); mainControl.getPropertiesControl().writeProperties(); esControl.getEigenschaftenView() .setOpenPlayersCSVLabel(mainControl.getPropertiesControl().getPathToPlayersCSV()); final String filename = file.getName(); final int positionEXT = filename.lastIndexOf('.'); if (positionEXT > 0) { final String newFile = filename.substring(positionEXT); if (newFile.equals(".sqlite")) { esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(false); } else { esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(true); } } } } }); esControl.getEigenschaftenView().getConvertELOToSQLITEButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { final ELOListToSQLITEControl eloL = new ELOListToSQLITEControl(mainControl); eloL.convertELOListToSQLITE(); esControl.getEigenschaftenView() .setOpenPlayersELOLabel(mainControl.getPropertiesControl().getPathToPlayersELO()); esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(false); } }); esControl.getEigenschaftenView().getOpenPlayersELOButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { // spieler.csv final File path = new File(mainControl.getPropertiesControl().getDefaultPath()); final JFileChooser fc = new JFileChooser(path); final FileFilter filter = new FileNameExtensionFilter("TXT or SQLite file", "txt", "TXT", "sqlite", "SQLite"); fc.setFileFilter(filter); final int returnVal = fc.showOpenDialog(esControl.getEigenschaftenView()); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = fc.getSelectedFile(); // This is where a real application would open the // file. mainControl.getPropertiesControl().setPathToPlayersELO(file.getAbsolutePath()); mainControl.getPropertiesControl().writeProperties(); esControl.getEigenschaftenView() .setOpenPlayersELOLabel(mainControl.getPropertiesControl().getPathToPlayersELO()); final String filename = file.getName(); final int positionEXT = filename.lastIndexOf('.'); if (positionEXT > 0) { final String newFile = filename.substring(positionEXT); if (newFile.equals(".sqlite")) { esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(false); } else { esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(true); } } } } }); esControl.getEigenschaftenView().getOpenDefaultPathButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final File path = new File(mainControl.getPropertiesControl().getDefaultPath()); final JFileChooser fc = new JFileChooser(path); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.setMultiSelectionEnabled(false); final int returnVal = fc.showOpenDialog(esControl.getEigenschaftenView()); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = fc.getSelectedFile(); // This is where a real application would open the // file. mainControl.getPropertiesControl().setDefaultPath(file.getAbsolutePath()); mainControl.getPropertiesControl().writeProperties(); esControl.getEigenschaftenView() .setOpenDefaultPathLabel(mainControl.getPropertiesControl().getDefaultPath()); } } }); esControl.getEigenschaftenView() .setOpenVereineCSVLabel(mainControl.getPropertiesControl().getPathToVereineCVS()); esControl.getEigenschaftenView() .setOpenPlayersCSVLabel(mainControl.getPropertiesControl().getPathToPlayersCSV()); esControl.getEigenschaftenView() .setOpenPlayersELOLabel(mainControl.getPropertiesControl().getPathToPlayersELO()); esControl.getEigenschaftenView().getGermanLanguageCheckBox().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { mainControl.getLanguagePropertiesControl().setLanguageToGerman(); mainControl.getPropertiesControl().writeProperties(); } }); esControl.getEigenschaftenView().getEnglishLanguageCheckBox().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { mainControl.getLanguagePropertiesControl().setLanguageToEnglish(); mainControl.getPropertiesControl().writeProperties(); } }); esControl.getEigenschaftenView().getSpielerListeAuswahlBox().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final int anzahlProTab = esControl.getEigenschaftenView().getSpielerListeAuswahlBox() .getSelectedIndex(); mainControl.getPropertiesControl().setSpielerProTab(anzahlProTab); mainControl.getPropertiesControl().writeProperties(); } }); esControl.getEigenschaftenView().getTurnierListeAuswahlBox().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { final int anzahlProTab = esControl.getEigenschaftenView().getTurnierListeAuswahlBox() .getSelectedIndex(); mainControl.getPropertiesControl().setTurniereProTab(anzahlProTab); mainControl.getPropertiesControl().writeProperties(); } }); String filename = mainControl.getPropertiesControl().getPathToPlayersELO(); int positionEXT = filename.lastIndexOf('.'); if (positionEXT > 0) { final String newFile = filename.substring(positionEXT); if (newFile.equals(".sqlite")) { esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(false); } else { esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(true); } } else { esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(false); } filename = mainControl.getPropertiesControl().getPathToPlayersCSV(); positionEXT = filename.lastIndexOf('.'); if (positionEXT > 0) { final String newFile = filename.substring(positionEXT); if (newFile.equals(".sqlite")) { esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(false); } else { esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(true); } } else { esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(false); } esControl.getEigenschaftenView().getResetPropertiesButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final int abfrage = beendenHinweis(); if (abfrage > 0) { if (mainControl.getHauptPanel().getTabCount() == TournamentConstants.TAB_ACTIVE_TOURNAMENT + 1) { if (mainControl.getChangedGames().isEmpty() == false) { final SaveTournamentControl saveTournament = new SaveTournamentControl(mainControl); try { saveTournament.saveChangedPartien(); } catch (final SQLException e1) { final ExceptionHandler eh = new ExceptionHandler(mainControl); eh.fileSQLError(e1.getMessage()); } } } } mainControl.getPropertiesControl().resetProperties(); mainControl.getPropertiesControl().writeProperties(); JOptionPane.showMessageDialog(null, Messages.getString("EigenschaftenControl.29"), Messages.getString("EigenschaftenControl.28"), JOptionPane.INFORMATION_MESSAGE); System.exit(0); } }); } private void addPropertiesActionListener() { mainControl.getNaviView().getPropertiesButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { mainControl.getSettingsControl().setEigenschaftenView(new SettingsView()); final SettingsView eigenschaftenView = mainControl.getSettingsControl().getEigenschaftenView(); mainControl.getSettingsControl().setItemListenerControl( new ItemListenerSettingsControl(mainControl, mainControl.getSettingsControl())); mainControl.getSettingsControl().getItemListenerControl().addItemListeners(); if (dialog == null) { dialog = new JDialog(); } else { dialog.dispose(); dialog = new JDialog(); } // dialog.setAlwaysOnTop(true); dialog.getContentPane().add(eigenschaftenView); dialog.pack(); dialog.setLocationRelativeTo(null); dialog.setBounds(mainControl.getPropertiesControl().getSettingsDialogX(), mainControl.getPropertiesControl().getSettingsDialogY(), mainControl.getPropertiesControl().getSettingsDialogWidth(), mainControl.getPropertiesControl().getSettingsDialogHeight()); dialog.setEnabled(true); if (mainControl.getPropertiesControl() == null) { mainControl.setPropertiesControl(new PropertiesControl(mainControl)); } final PropertiesControl ppC = mainControl.getPropertiesControl(); ppC.readProperties(); eigenschaftenView.getCheckBoxHeaderFooter().setSelected(ppC.getOnlyTables()); eigenschaftenView.getCheckBoxohneDWZ().setSelected(ppC.getNoDWZ()); eigenschaftenView.getCheckBoxohneFolgeDWZ().setSelected(ppC.getNoFolgeDWZ()); eigenschaftenView.getCheckBoxohneELO().setSelected(ppC.getNoELO()); eigenschaftenView.getCheckBoxohneFolgeELO().setSelected(ppC.getNoFolgeELO()); eigenschaftenView.getSpielerListeAuswahlBox().setSelectedIndex(ppC.getSpielerProTab()); eigenschaftenView.getTurnierListeAuswahlBox().setSelectedIndex(ppC.getTurniereProTab()); eigenschaftenView.getForenameLengthBox().setValue(ppC.getCutForename()); eigenschaftenView.getSurnameLengthBox().setValue(ppC.getCutSurname()); eigenschaftenView.getWebserverPathTextField().setText(ppC.getWebserverPath()); // eigenschaftenView.getCheckBoxohneDWZ().setSelected(ppC.getNoDWZ()); eigenschaftenView.getCheckBoxhtmlToClipboard().setSelected(ppC.gethtmlToClipboard()); if (eigenschaftenView.getCheckBoxohneDWZ().isSelected() == true) { eigenschaftenView.getCheckBoxohneFolgeDWZ().setSelected(true); eigenschaftenView.getCheckBoxohneFolgeDWZ().setEnabled(false); ppC.setNoFolgeDWZ(true); } if (eigenschaftenView.getCheckBoxohneELO().isSelected() == true) { eigenschaftenView.getCheckBoxohneFolgeELO().setSelected(true); eigenschaftenView.getCheckBoxohneFolgeELO().setEnabled(false); ppC.setNoFolgeELO(true); } eigenschaftenView.getCheckBoxPDFLinks().setSelected(ppC.getPDFLinks()); eigenschaftenView.getWebserverPathTextField().setEnabled(ppC.getPDFLinks()); if (mainControl.getPropertiesControl().getLanguage().equals("german")) { //$NON-NLS-1$ eigenschaftenView.getGermanLanguageCheckBox().setSelected(true); eigenschaftenView.getEnglishLanguageCheckBox().setSelected(false); mainControl.getLanguagePropertiesControl().setLanguageToGerman(); } else if (mainControl.getPropertiesControl().getLanguage().equals("english")) { //$NON-NLS-1$ eigenschaftenView.getGermanLanguageCheckBox().setSelected(false); eigenschaftenView.getEnglishLanguageCheckBox().setSelected(true); mainControl.getLanguagePropertiesControl().setLanguageToEnglish(); } eigenschaftenView.setOpenDefaultPathLabel(ppC.getDefaultPath()); eigenschaftenView.getTableCSSTextField().setText(ppC.getCSSTable()); esControl.setTableColumns(); addActionListeners(); esControl.getItemListenerControl().addItemListeners(); dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); dialog.setVisible(true); } }); } private int beendenHinweis() { int abfrage = 0; if (mainControl.getHauptPanel().getTabCount() == TournamentConstants.TAB_ACTIVE_TOURNAMENT + 1) { if (mainControl.getChangedGames().isEmpty() == false) { final String hinweisText = Messages.getString("NaviController.21") //$NON-NLS-1$ + Messages.getString("NaviController.22") //$NON-NLS-1$ + Messages.getString("NaviController.33"); //$NON-NLS-1$ abfrage = 1; // Custom button text final Object[] options = { Messages.getString("NaviController.24"), //$NON-NLS-1$ Messages.getString("NaviController.25") }; //$NON-NLS-1$ abfrage = JOptionPane.showOptionDialog(mainControl, hinweisText, Messages.getString("NaviController.26"), //$NON-NLS-1$ JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]); } } return abfrage; } }
mars7105/JKLubTV
src/de/turnierverwaltung/control/settingsdialog/ActionListenerSettingsControl.java
Java
gpl-3.0
18,976
namespace Ribbonizer.Ribbon { using System.Collections.Generic; using System.Linq; using Ribbonizer.Ribbon.DefinitionValidation; using Ribbonizer.Ribbon.Tabs; internal class RibbonInitializer : IRibbonInitializer { private readonly IEnumerable<IRibbonDefinitionValidator> definitionValidators; private readonly IRibbonTabViewCacheInitializer tabViewCacheInitializer; public RibbonInitializer(IEnumerable<IRibbonDefinitionValidator> definitionValidators, IRibbonTabViewCacheInitializer tabViewCacheInitializer) { this.definitionValidators = definitionValidators; this.tabViewCacheInitializer = tabViewCacheInitializer; } public void InitializeRibbonViewTree() { IEnumerable<IRibbonDefinitionViolation> violations = this.definitionValidators .SelectMany(x => x.Validate()) .ToList(); if (violations.Any()) { throw new RibbonDefinitionViolationException(violations); } this.tabViewCacheInitializer.InitializeCache(); } } }
BrunoJuchli/RibbonizerSample
Ribbonizer/Ribbon/RibbonInitializer.cs
C#
gpl-3.0
1,152
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2015 Satpy developers # # This file is part of satpy. # # satpy is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # satpy 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 # satpy. If not, see <http://www.gnu.org/licenses/>. """Fetch avhrr calibration coefficients.""" import datetime as dt import os.path import sys import h5py import urllib2 BASE_URL = "http://www.star.nesdis.noaa.gov/smcd/spb/fwu/homepage/" + \ "AVHRR/Op_Cal_AVHRR/" URLS = { "Metop-B": {"ch1": BASE_URL + "Metop1_AVHRR_Libya_ch1.txt", "ch2": BASE_URL + "Metop1_AVHRR_Libya_ch2.txt", "ch3a": BASE_URL + "Metop1_AVHRR_Libya_ch3a.txt"}, "Metop-A": {"ch1": BASE_URL + "Metop2_AVHRR_Libya_ch1.txt", "ch2": BASE_URL + "Metop2_AVHRR_Libya_ch2.txt", "ch3a": BASE_URL + "Metop2_AVHRR_Libya_ch3a.txt"}, "NOAA-16": {"ch1": BASE_URL + "N16_AVHRR_Libya_ch1.txt", "ch2": BASE_URL + "N16_AVHRR_Libya_ch2.txt"}, "NOAA-17": {"ch1": BASE_URL + "N17_AVHRR_Libya_ch1.txt", "ch2": BASE_URL + "N17_AVHRR_Libya_ch2.txt", "ch3a": BASE_URL + "N17_AVHRR_Libya_ch3a.txt"}, "NOAA-18": {"ch1": BASE_URL + "N18_AVHRR_Libya_ch1.txt", "ch2": BASE_URL + "N18_AVHRR_Libya_ch2.txt"}, "NOAA-19": {"ch1": BASE_URL + "N19_AVHRR_Libya_ch1.txt", "ch2": BASE_URL + "N19_AVHRR_Libya_ch2.txt"} } def get_page(url): """Retrieve the given page.""" return urllib2.urlopen(url).read() def get_coeffs(page): """Parse coefficients from the page.""" coeffs = {} coeffs['datetime'] = [] coeffs['slope1'] = [] coeffs['intercept1'] = [] coeffs['slope2'] = [] coeffs['intercept2'] = [] slope1_idx, intercept1_idx, slope2_idx, intercept2_idx = \ None, None, None, None date_idx = 0 for row in page.lower().split('\n'): row = row.split() if len(row) == 0: continue if row[0] == 'update': # Get the column indices from the header line slope1_idx = row.index('slope_lo') intercept1_idx = row.index('int_lo') slope2_idx = row.index('slope_hi') intercept2_idx = row.index('int_hi') continue if slope1_idx is None: continue # In some cases the fields are connected, skip those rows if max([slope1_idx, intercept1_idx, slope2_idx, intercept2_idx]) >= len(row): continue try: dat = dt.datetime.strptime(row[date_idx], "%m/%d/%Y") except ValueError: continue coeffs['datetime'].append([dat.year, dat.month, dat.day]) coeffs['slope1'].append(float(row[slope1_idx])) coeffs['intercept1'].append(float(row[intercept1_idx])) coeffs['slope2'].append(float(row[slope2_idx])) coeffs['intercept2'].append(float(row[intercept2_idx])) return coeffs def get_all_coeffs(): """Get all available calibration coefficients for the satellites.""" coeffs = {} for platform in URLS: if platform not in coeffs: coeffs[platform] = {} for chan in URLS[platform].keys(): url = URLS[platform][chan] print(url) page = get_page(url) coeffs[platform][chan] = get_coeffs(page) return coeffs def save_coeffs(coeffs, out_dir=''): """Save calibration coefficients to HDF5 files.""" for platform in coeffs.keys(): fname = os.path.join(out_dir, "%s_calibration_data.h5" % platform) fid = h5py.File(fname, 'w') for chan in coeffs[platform].keys(): fid.create_group(chan) fid[chan]['datetime'] = coeffs[platform][chan]['datetime'] fid[chan]['slope1'] = coeffs[platform][chan]['slope1'] fid[chan]['intercept1'] = coeffs[platform][chan]['intercept1'] fid[chan]['slope2'] = coeffs[platform][chan]['slope2'] fid[chan]['intercept2'] = coeffs[platform][chan]['intercept2'] fid.close() print("Calibration coefficients saved for %s" % platform) def main(): """Create calibration coefficient files for AVHRR.""" out_dir = sys.argv[1] coeffs = get_all_coeffs() save_coeffs(coeffs, out_dir=out_dir) if __name__ == "__main__": main()
pytroll/satpy
utils/fetch_avhrr_calcoeffs.py
Python
gpl-3.0
4,773
<?php /** * Belgian Scouting Web Platform * Copyright (C) 2014 Julien Dupuis * * This code is licensed under the GNU General Public License. * * This is free software, and you are welcome to redistribute it * under under the terms of the GNU General Public License. * * It is distributed 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/>. **/ /** * This Eloquent class represents a privilege of a leader * * Columns: * - operation: A string representing which operation this privilege allows * - scope: 'S' if the privilege is limited to the leader's section, 'U' for unit if they can use this privilege on any section * - member_id: The leader affected by this privilege * * Note : predefined privileges are privileges that can be automatically applied to classes * of members : * A: Simple leader * R: Leader in charge / Section webmaster * S: Unit co-leader * U: Unit main leader */ class Privilege extends Eloquent { var $guarded = array('id', 'created_at', 'updated_at'); // Following are all the privileges with // - id: the string representing the privilege // - text: a textual description of the privilege // - section: true if this privilege can be applied to only a section, false if it is a global privilige // - predefined: in which predefined classes it will be applied public static $UPDATE_OWN_LISTING_ENTRY = array( 'id' => 'Update own listing entry', 'text' => 'Modifier ses données personnelles dans le listing', 'section' => false, 'predefined' => "ARSU" ); public static $EDIT_PAGES = array( 'id' => 'Edit pages', 'text' => 'Modifier les pages #delasection', 'section' => true, 'predefined' => "RSU" ); public static $EDIT_SECTION_EMAIL_AND_SUBGROUP = array( 'id' => "Edit section e-mail address and subgroup name", 'text' => "Changer l'adresse e-mail #delasection", 'section' => true, 'predefined' => "RSU" ); public static $EDIT_CALENDAR = array( 'id' => "Edit calendar", 'text' => 'Modifier les entrées du calendrier #delasection', 'section' => true, 'predefined' => "ARSU" ); public static $MANAGE_ATTENDANCE = array( 'id' => "Manage attendance", 'text' => 'Cocher les présences aux activités #delasection', 'section' => true, 'predefined' => "ARSU" ); public static $MANAGE_EVENT_PAYMENTS = array( 'id' => "Manage event payments", 'text' => 'Cocher le paiement des membres pour les activités #delasection', 'section' => true, 'predefined' => "ARSU" ); public static $EDIT_NEWS = array( 'id' => "Edit news", 'text' => 'Poster des nouvelles (actualités) pour #lasection', 'section' => true, 'predefined' => "RSU" ); public static $EDIT_DOCUMENTS = array( 'id' => "Edit documents", 'text' => 'Modifier les documents #delasection', 'section' => true, 'predefined' => "RSU" ); public static $SEND_EMAILS = array( 'id' => "Send e-mails", 'text' => 'Envoyer des e-mails aux membres #delasection', 'section' => true, 'predefined' => "RSU" ); public static $POST_PHOTOS = array( 'id' => "Post photos", 'text' => 'Ajouter/supprimer des photos pour #lasection', 'section' => true, 'predefined' => "ARSU" ); public static $MANAGE_ACCOUNTING = array( 'id' => "Manage accounting", 'text' => 'Gérer les comptes #delasection', 'section' => true, 'predefined' => "RSU" ); public static $SECTION_TRANSFER = array( 'id' => "Section transfer", 'text' => "Changer les scouts de section", 'section' => false, 'predefined' => "SU", ); public static $EDIT_LISTING_LIMITED = array( 'id' => "Edit listing limited", 'text' => 'Modifier les données non sensibles du listing #delasection', 'section' => true, 'predefined' => "RSU" ); public static $EDIT_LISTING_ALL = array( 'id' => "Edit listing all", 'text' => 'Modifier les données sensibles du listing #delasection', 'section' => true, 'predefined' => "U" ); public static $VIEW_HEALTH_CARDS = array( 'id' => "View health cards", 'text' => 'Consulter les fiches santé #delasection', 'section' => true, 'predefined' => "ARSU" ); public static $EDIT_LEADER_PRIVILEGES = array( 'id' => "Edit leader privileges", 'text' => 'Changer les privilèges des animateurs #delasection', 'section' => true, 'predefined' => "RSU" ); public static $UPDATE_PAYMENT_STATUS = array( 'id' => "Update payment status", 'text' => 'Modifier le statut de paiement', 'section' => false, 'predefined' => "SU" ); public static $MANAGE_ANNUAL_FEAST_REGISTRATION = array( 'id' => "Manage annual feast registration", 'text' => "Valider les inscriptions pour la fête d'unité", 'section' => false, 'predefined' => "SU" ); public static $MANAGE_SUGGESIONS = array( 'id' => "Manage suggestions", 'text' => "Répondre aux suggestions et les supprimer", 'section' => false, 'predefined' => "SU" ); public static $EDIT_GLOBAL_PARAMETERS = array( 'id' => "Edit global parameters", 'text' => "Changer les paramètres du site", 'section' => false, 'predefined' => "U" ); public static $EDIT_STYLE = array( 'id' => "Edit style", 'text' => "Modifier le style du site", 'section' => false, 'predefined' => "U" ); public static $MANAGE_SECTIONS = array( 'id' => "Manage sections", 'text' => "Créer, modifier et supprimer les sections", 'section' => false, 'predefined' => "U" ); public static $DELETE_USERS = array( 'id' => "Delete users", 'text' => "Supprimer des comptes d'utilisateurs", 'section' => false, 'predefined' => "U" ); public static $DELETE_GUEST_BOOK_ENTRIES = array( 'id' => "Delete guest book entries", 'text' => "Supprimer des entrées du livre d'or", 'section' => false, 'predefined' => "U" ); /** * Returns the list of privileges */ public static function getPrivilegeList() { return array( self::$UPDATE_OWN_LISTING_ENTRY, self::$EDIT_CALENDAR, self::$MANAGE_ATTENDANCE, self::$MANAGE_EVENT_PAYMENTS, self::$POST_PHOTOS, self::$VIEW_HEALTH_CARDS, self::$EDIT_PAGES, self::$EDIT_DOCUMENTS, self::$EDIT_NEWS, self::$SEND_EMAILS, self::$EDIT_SECTION_EMAIL_AND_SUBGROUP, self::$MANAGE_ACCOUNTING, self::$SECTION_TRANSFER, self::$EDIT_LISTING_LIMITED, self::$EDIT_LEADER_PRIVILEGES, self::$MANAGE_ANNUAL_FEAST_REGISTRATION, self::$MANAGE_SUGGESIONS, self::$UPDATE_PAYMENT_STATUS, self::$EDIT_LISTING_ALL, self::$EDIT_GLOBAL_PARAMETERS, self::$EDIT_STYLE, self::$MANAGE_SECTIONS, self::$DELETE_GUEST_BOOK_ENTRIES, self::$DELETE_USERS, ); } /** * Returns the list of privileges sorted in 4 categories * * @param boolean $forSection Whether this is for a section leader or a unit leader */ public static function getPrivilegeArrayByCategory($forSection = false) { // The four categories $basicPrivileges = array(); $leaderInChargePrivileges = array(); $unitTeamPrivileges = array(); $unitLeaderPrivileges = array(); // Sort privileges into categories foreach (self::getPrivilegeList() as $privilege) { if (strpos($privilege['predefined'], "A") !== false) { if ($forSection) { if ($privilege['section']) { $basicPrivileges[] = array('privilege' => $privilege, 'scope' => 'S'); $unitTeamPrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } else { $basicPrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } } else { if ($privilege['section']) $leaderInChargePrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); else $basicPrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } } elseif (strpos($privilege['predefined'], "R") !== false) { if ($forSection) { if ($privilege['section']) { $leaderInChargePrivileges[] = array('privilege' => $privilege, 'scope' => 'S'); $unitTeamPrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } else { $leaderInChargePrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } } else { $leaderInChargePrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } } elseif (strpos($privilege['predefined'], "S") !== false) { $unitTeamPrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } elseif (strpos($privilege['predefined'], "U") !== false) { $unitLeaderPrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } } // Return list of categories return array( "Gestion de base" => $basicPrivileges, "Gestion avancée" => $leaderInChargePrivileges, "Gestion de l'unité" => $unitTeamPrivileges, "Gestion avancée de l'unité" => $unitLeaderPrivileges, ); } /** * Sets and saves all the privileges from the base category to the given leader */ public static function addBasePrivilegesForLeader($leader) { foreach (self::getPrivilegeList() as $privilege) { if (strpos($privilege['predefined'], "A") !== false) { try { Privilege::create(array( 'operation' => $privilege['id'], 'scope' => $privilege['section'] ? 'S' : 'U', 'member_id' => $leader->id, )); } catch (Exception $e) { Log::error($e); } } } } /** * Sets ($state = true) or unsets ($state = false) and saves a privilege for a leader in a given scope */ public static function set($operation, $scope, $leaderId, $state) { // Find existing privilege $privilege = Privilege::where('operation', '=', $operation) ->where('scope', '=', $scope) ->where('member_id', '=', $leaderId) ->first(); if ($privilege && !$state) { // Privilege exists and should be removed $privilege->delete(); } elseif (!$privilege && $state) { // Privilege does not exist and should be created Privilege::create(array( 'operation' => $operation, 'scope' => $scope, 'member_id' => $leaderId, )); } } }
juldup/scouting-web-platform
app/models/Privilege.php
PHP
gpl-3.0
11,158
<?php /** * WES WebExploitScan Web GPLv4 http://github.com/libre/webexploitscan * * The PHP page that serves all page requests on WebExploitScan installation. * * The routines here dispatch control to the appropriate handler, which then * prints the appropriate page. * * All WebExploitScan code is released under the GNU General Public License. * See COPYRIGHT.txt and LICENSE.txt. */ $NAME='Php-MS-PHP-Antimalware-Scanner malware_signature- ID 2155'; $TAGCLEAR='A<?php[^}]{1,600}}}define([\'"]startTime[\'"],getTime());if(!function_exists([\'"]shellexec[\'"])){functions+shellexec($cmd){'; $TAGBASE64='QTw/cGhwW159XXsxLDYwMH19fWRlZmluZShbXCciXXN0YXJ0VGltZVtcJyJdLGdldFRpbWUoKSk7aWYoIWZ1bmN0aW9uX2V4aXN0cyhbXCciXXNoZWxsZXhlY1tcJyJdKSl7ZnVuY3Rpb25zK3NoZWxsZXhlYygkY21kKXs='; $TAGHEX='413c3f7068705b5e7d5d7b312c3630307d7d7d646566696e65285b5c27225d737461727454696d655b5c27225d2c67657454696d652829293b6966282166756e6374696f6e5f657869737473285b5c27225d7368656c6c657865635b5c27225d29297b66756e6374696f6e732b7368656c6c657865632824636d64297b'; $TAGHEXPHP=''; $TAGURI='A%3C%3Fphp%5B%5E%7D%5D%7B1%2C600%7D%7D%7Ddefine%28%5B%5C%27%22%5DstartTime%5B%5C%27%22%5D%2CgetTime%28%29%29%3Bif%28%21function_exists%28%5B%5C%27%22%5Dshellexec%5B%5C%27%22%5D%29%29%7Bfunctions%2Bshellexec%28%24cmd%29%7B'; $TAGCLEAR2=''; $TAGBASE642=''; $TAGHEX2=''; $TAGHEXPHP2=''; $TAGURI2=''; $DATEADD='10/09/2019'; $LINK='Webexploitscan.org ;Php-MS-PHP-Antimalware-Scanner malware_signature- ID 2155 '; $ACTIVED='1'; $VSTATR='malware_signature';
libre/webexploitscan
wes/data/rules/fullscan/10092019-MS-PHP-Antimalware-Scanner-2155-malware_signature.php
PHP
gpl-3.0
1,524
#define TYPEDEPARGS 0, 1, 2, 3 #define SINGLEARGS #define REALARGS #define OCTFILENAME comp_ufilterbankheapint // change to filename #define OCTFILEHELP "This function calls the C-library\n\ phase=comp_ufilterbankheapint(s,tgrad,fgrad,cfreq,a,do_real,tol,phasetype)\n Yeah." #include "ltfat_oct_template_helper.h" static inline void fwd_ufilterbankheapint( const double s[], const double tgrad[], const double fgrad[], const double cfreq[], ltfat_int a, ltfat_int M, ltfat_int L, ltfat_int W, int do_real, double tol, int phasetype, double phase[]) { if (phasetype == 1) ltfat_ufilterbankheapint_d( s, tgrad, fgrad, cfreq, a, M, L, W, do_real, tol, phase); else ltfat_ufilterbankheapint_relgrad_d( s, tgrad, fgrad, cfreq, a, M, L, W, do_real, tol, phase); } static inline void fwd_ufilterbankheapint( const float s[], const float tgrad[], const float fgrad[], const float cfreq[], ltfat_int a, ltfat_int M, ltfat_int L, ltfat_int W, int do_real, float tol, int phasetype, float phase[]) { if (phasetype == 1) ltfat_ufilterbankheapint_s( s, tgrad, fgrad, cfreq, a, M, L, W, do_real, tol, phase); else ltfat_ufilterbankheapint_relgrad_s( s, tgrad, fgrad, cfreq, a, M, L, W, do_real, tol, phase); } template <class LTFAT_TYPE, class LTFAT_REAL, class LTFAT_COMPLEX> octave_value_list octFunction(const octave_value_list& args, int nargout) { // Input data MArray<LTFAT_REAL> s = ltfatOctArray<LTFAT_REAL>(args(0)); MArray<LTFAT_REAL> tgrad = ltfatOctArray<LTFAT_REAL>(args(1)); MArray<LTFAT_REAL> fgrad = ltfatOctArray<LTFAT_REAL>(args(2)); MArray<LTFAT_REAL> cfreq = ltfatOctArray<LTFAT_REAL>(args(3)); octave_idx_type a = args(4).int_value(); octave_idx_type do_real = args(5).int_value(); double tol = args(6).double_value(); octave_idx_type phasetype = args(7).int_value(); octave_idx_type M = s.columns(); octave_idx_type N = s.rows(); octave_idx_type W = 1; octave_idx_type L = (octave_idx_type)( N * a); // phasetype--; MArray<LTFAT_REAL> phase(dim_vector(N, M, W)); fwd_ufilterbankheapint( s.data(), tgrad.data(), fgrad.data(), cfreq.data(), a, M, L, W, do_real, tol, phasetype, phase.fortran_vec()); return octave_value(phase); }
ltfat/ltfat
oct/comp_ufilterbankheapint.cc
C++
gpl-3.0
2,458
/** * This file is part of RagEmu. * http://ragemu.org - https://github.com/RagEmu/Renewal * * Copyright (C) 2016 RagEmu Dev Team * Copyright (C) 2012-2015 Hercules Dev Team * Copyright (C) Athena Dev Teams * * RagEmu is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef COMMON_MD5CALC_H #define COMMON_MD5CALC_H #include "common/ragemu.h" /** @file * md5 calculation algorithm. * * The source code referred to the following URL. * http://www.geocities.co.jp/SiliconValley-Oakland/8878/lab17/lab17.html */ /// The md5 interface struct md5_interface { /** * Hashes a string, returning the hash in string format. * * @param[in] string The source string (NUL terminated). * @param[out] output Output buffer (at least 33 bytes available). */ void (*string) (const char *string, char *output); /** * Hashes a string, returning the buffer in binary format. * * @param[in] string The source string. * @param[out] output Output buffer (at least 16 bytes available). */ void (*binary) (const uint8 *buf, const int buf_size, uint8 *output); /** * Generates a random salt. * * @param[in] len The desired salt length. * @param[out] output The output buffer (at least len bytes available). */ void (*salt) (int len, char *output); }; #ifdef RAGEMU_CORE void md5_defaults(void); #endif // RAGEMU_CORE HPShared struct md5_interface *md5; ///< Pointer to the md5 interface. #endif /* COMMON_MD5CALC_H */
RagEmu/Renewal
src/common/md5calc.h
C
gpl-3.0
2,043
// OpenCppCoverage is an open source code coverage for C++. // Copyright (C) 2014 OpenCppCoverage // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // 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/>. using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.Shell.Interop; using System; namespace OpenCppCoverage.VSPackage { class OutputWindowWriter { //--------------------------------------------------------------------- public OutputWindowWriter(DTE2 dte, IVsOutputWindow outputWindow) { // These lines show the output windows Window output = dte.Windows.Item(EnvDTE.Constants.vsWindowKindOutput); output.Activate(); if (Microsoft.VisualStudio.ErrorHandler.Failed(outputWindow.GetPane(OpenCppCoverageOutputPaneGuid, out outputWindowPane_))) { if (Microsoft.VisualStudio.ErrorHandler.Failed(outputWindow.CreatePane(OpenCppCoverageOutputPaneGuid, "OpenCppCoverage", 1, 1))) throw new Exception("Cannot create new pane."); if (Microsoft.VisualStudio.ErrorHandler.Failed(outputWindow.GetPane(OpenCppCoverageOutputPaneGuid, out outputWindowPane_))) throw new Exception("Cannot get the pane."); } outputWindowPane_.Clear(); ActivatePane(); } //--------------------------------------------------------------------- public void ActivatePane() { outputWindowPane_.Activate(); } //--------------------------------------------------------------------- public bool WriteLine(string message) { return Microsoft.VisualStudio.ErrorHandler.Succeeded(outputWindowPane_.OutputString(message + "\n")); } readonly IVsOutputWindowPane outputWindowPane_; public readonly static Guid OpenCppCoverageOutputPaneGuid = new Guid("CB47C727-5E45-467B-A4CD-4A025986A8A0"); } }
OpenCppCoverage/OpenCppCoveragePlugin
VSPackage/OutputWindowWriter.cs
C#
gpl-3.0
2,517
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Michael DeHaan <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: git author: - "Ansible Core Team" - "Michael DeHaan" version_added: "0.0.1" short_description: Deploy software (or files) from git checkouts description: - Manage I(git) checkouts of repositories to deploy files or software. options: repo: description: - git, SSH, or HTTP(S) protocol address of the git repository. type: str required: true aliases: [ name ] dest: description: - The path of where the repository should be checked out. This is equivalent to C(git clone [repo_url] [directory]). The repository named in I(repo) is not appended to this path and the destination directory must be empty. This parameter is required, unless I(clone) is set to C(no). type: path required: true version: description: - What version of the repository to check out. This can be the literal string C(HEAD), a branch name, a tag name. It can also be a I(SHA-1) hash, in which case I(refspec) needs to be specified if the given revision is not already available. type: str default: "HEAD" accept_hostkey: description: - If C(yes), ensure that "-o StrictHostKeyChecking=no" is present as an ssh option. type: bool default: 'no' version_added: "1.5" accept_newhostkey: description: - As of OpenSSH 7.5, "-o StrictHostKeyChecking=accept-new" can be used which is safer and will only accepts host keys which are not present or are the same. if C(yes), ensure that "-o StrictHostKeyChecking=accept-new" is present as an ssh option. type: bool default: 'no' version_added: "2.12" ssh_opts: description: - Creates a wrapper script and exports the path as GIT_SSH which git then automatically uses to override ssh arguments. An example value could be "-o StrictHostKeyChecking=no" (although this particular option is better set by I(accept_hostkey)). type: str version_added: "1.5" key_file: description: - Specify an optional private key file path, on the target host, to use for the checkout. type: path version_added: "1.5" reference: description: - Reference repository (see "git clone --reference ..."). version_added: "1.4" remote: description: - Name of the remote. type: str default: "origin" refspec: description: - Add an additional refspec to be fetched. If version is set to a I(SHA-1) not reachable from any branch or tag, this option may be necessary to specify the ref containing the I(SHA-1). Uses the same syntax as the C(git fetch) command. An example value could be "refs/meta/config". type: str version_added: "1.9" force: description: - If C(yes), any modified files in the working repository will be discarded. Prior to 0.7, this was always 'yes' and could not be disabled. Prior to 1.9, the default was `yes`. type: bool default: 'no' version_added: "0.7" depth: description: - Create a shallow clone with a history truncated to the specified number or revisions. The minimum possible value is C(1), otherwise ignored. Needs I(git>=1.9.1) to work correctly. type: int version_added: "1.2" clone: description: - If C(no), do not clone the repository even if it does not exist locally. type: bool default: 'yes' version_added: "1.9" update: description: - If C(no), do not retrieve new revisions from the origin repository. - Operations like archive will work on the existing (old) repository and might not respond to changes to the options version or remote. type: bool default: 'yes' version_added: "1.2" executable: description: - Path to git executable to use. If not supplied, the normal mechanism for resolving binary paths will be used. type: path version_added: "1.4" bare: description: - If C(yes), repository will be created as a bare repo, otherwise it will be a standard repo with a workspace. type: bool default: 'no' version_added: "1.4" umask: description: - The umask to set before doing any checkouts, or any other repository maintenance. type: raw version_added: "2.2" recursive: description: - If C(no), repository will be cloned without the --recursive option, skipping sub-modules. type: bool default: 'yes' version_added: "1.6" single_branch: description: - Clone only the history leading to the tip of the specified I(branch). type: bool default: 'no' version_added: '2.11' track_submodules: description: - If C(yes), submodules will track the latest commit on their master branch (or other branch specified in .gitmodules). If C(no), submodules will be kept at the revision specified by the main project. This is equivalent to specifying the --remote flag to git submodule update. type: bool default: 'no' version_added: "1.8" verify_commit: description: - If C(yes), when cloning or checking out a I(version) verify the signature of a GPG signed commit. This requires git version>=2.1.0 to be installed. The commit MUST be signed and the public key MUST be present in the GPG keyring. type: bool default: 'no' version_added: "2.0" archive: description: - Specify archive file path with extension. If specified, creates an archive file of the specified format containing the tree structure for the source tree. Allowed archive formats ["zip", "tar.gz", "tar", "tgz"]. - This will clone and perform git archive from local directory as not all git servers support git archive. type: path version_added: "2.4" archive_prefix: description: - Specify a prefix to add to each file path in archive. Requires I(archive) to be specified. version_added: "2.10" type: str separate_git_dir: description: - The path to place the cloned repository. If specified, Git repository can be separated from working tree. type: path version_added: "2.7" gpg_whitelist: description: - A list of trusted GPG fingerprints to compare to the fingerprint of the GPG-signed commit. - Only used when I(verify_commit=yes). - Use of this feature requires Git 2.6+ due to its reliance on git's C(--raw) flag to C(verify-commit) and C(verify-tag). type: list elements: str default: [] version_added: "2.9" requirements: - git>=1.7.1 (the command line tool) notes: - "If the task seems to be hanging, first verify remote host is in C(known_hosts). SSH will prompt user to authorize the first contact with a remote host. To avoid this prompt, one solution is to use the option accept_hostkey. Another solution is to add the remote host public key in C(/etc/ssh/ssh_known_hosts) before calling the git module, with the following command: ssh-keyscan -H remote_host.com >> /etc/ssh/ssh_known_hosts." - Supports C(check_mode). ''' EXAMPLES = ''' - name: Git checkout ansible.builtin.git: repo: 'https://foosball.example.org/path/to/repo.git' dest: /srv/checkout version: release-0.22 - name: Read-write git checkout from github ansible.builtin.git: repo: [email protected]:mylogin/hello.git dest: /home/mylogin/hello - name: Just ensuring the repo checkout exists ansible.builtin.git: repo: 'https://foosball.example.org/path/to/repo.git' dest: /srv/checkout update: no - name: Just get information about the repository whether or not it has already been cloned locally ansible.builtin.git: repo: 'https://foosball.example.org/path/to/repo.git' dest: /srv/checkout clone: no update: no - name: Checkout a github repo and use refspec to fetch all pull requests ansible.builtin.git: repo: https://github.com/ansible/ansible-examples.git dest: /src/ansible-examples refspec: '+refs/pull/*:refs/heads/*' - name: Create git archive from repo ansible.builtin.git: repo: https://github.com/ansible/ansible-examples.git dest: /src/ansible-examples archive: /tmp/ansible-examples.zip - name: Clone a repo with separate git directory ansible.builtin.git: repo: https://github.com/ansible/ansible-examples.git dest: /src/ansible-examples separate_git_dir: /src/ansible-examples.git - name: Example clone of a single branch ansible.builtin.git: single_branch: yes branch: master - name: Avoid hanging when http(s) password is missing ansible.builtin.git: repo: https://github.com/ansible/could-be-a-private-repo dest: /src/from-private-repo environment: GIT_TERMINAL_PROMPT: 0 # reports "terminal prompts disabled" on missing password # or GIT_ASKPASS: /bin/true # for git before version 2.3.0, reports "Authentication failed" on missing password ''' RETURN = ''' after: description: Last commit revision of the repository retrieved during the update. returned: success type: str sample: 4c020102a9cd6fe908c9a4a326a38f972f63a903 before: description: Commit revision before the repository was updated, "null" for new repository. returned: success type: str sample: 67c04ebe40a003bda0efb34eacfb93b0cafdf628 remote_url_changed: description: Contains True or False whether or not the remote URL was changed. returned: success type: bool sample: True warnings: description: List of warnings if requested features were not available due to a too old git version. returned: error type: str sample: git version is too old to fully support the depth argument. Falling back to full checkouts. git_dir_now: description: Contains the new path of .git directory if it is changed. returned: success type: str sample: /path/to/new/git/dir git_dir_before: description: Contains the original path of .git directory if it is changed. returned: success type: str sample: /path/to/old/git/dir ''' import filecmp import os import re import shlex import stat import sys import shutil import tempfile from distutils.version import LooseVersion from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six import b, string_types from ansible.module_utils._text import to_native, to_text from ansible.module_utils.common.process import get_bin_path def relocate_repo(module, result, repo_dir, old_repo_dir, worktree_dir): if os.path.exists(repo_dir): module.fail_json(msg='Separate-git-dir path %s already exists.' % repo_dir) if worktree_dir: dot_git_file_path = os.path.join(worktree_dir, '.git') try: shutil.move(old_repo_dir, repo_dir) with open(dot_git_file_path, 'w') as dot_git_file: dot_git_file.write('gitdir: %s' % repo_dir) result['git_dir_before'] = old_repo_dir result['git_dir_now'] = repo_dir except (IOError, OSError) as err: # if we already moved the .git dir, roll it back if os.path.exists(repo_dir): shutil.move(repo_dir, old_repo_dir) module.fail_json(msg=u'Unable to move git dir. %s' % to_text(err)) def head_splitter(headfile, remote, module=None, fail_on_error=False): '''Extract the head reference''' # https://github.com/ansible/ansible-modules-core/pull/907 res = None if os.path.exists(headfile): rawdata = None try: f = open(headfile, 'r') rawdata = f.readline() f.close() except Exception: if fail_on_error and module: module.fail_json(msg="Unable to read %s" % headfile) if rawdata: try: rawdata = rawdata.replace('refs/remotes/%s' % remote, '', 1) refparts = rawdata.split(' ') newref = refparts[-1] nrefparts = newref.split('/', 2) res = nrefparts[-1].rstrip('\n') except Exception: if fail_on_error and module: module.fail_json(msg="Unable to split head from '%s'" % rawdata) return res def unfrackgitpath(path): if path is None: return None # copied from ansible.utils.path return os.path.normpath(os.path.realpath(os.path.expanduser(os.path.expandvars(path)))) def get_submodule_update_params(module, git_path, cwd): # or: git submodule [--quiet] update [--init] [-N|--no-fetch] # [-f|--force] [--rebase] [--reference <repository>] [--merge] # [--recursive] [--] [<path>...] params = [] # run a bad submodule command to get valid params cmd = "%s submodule update --help" % (git_path) rc, stdout, stderr = module.run_command(cmd, cwd=cwd) lines = stderr.split('\n') update_line = None for line in lines: if 'git submodule [--quiet] update ' in line: update_line = line if update_line: update_line = update_line.replace('[', '') update_line = update_line.replace(']', '') update_line = update_line.replace('|', ' ') parts = shlex.split(update_line) for part in parts: if part.startswith('--'): part = part.replace('--', '') params.append(part) return params def write_ssh_wrapper(module_tmpdir): try: # make sure we have full permission to the module_dir, which # may not be the case if we're sudo'ing to a non-root user if os.access(module_tmpdir, os.W_OK | os.R_OK | os.X_OK): fd, wrapper_path = tempfile.mkstemp(prefix=module_tmpdir + '/') else: raise OSError except (IOError, OSError): fd, wrapper_path = tempfile.mkstemp() fh = os.fdopen(fd, 'w+b') template = b("""#!/bin/sh if [ -z "$GIT_SSH_OPTS" ]; then BASEOPTS="" else BASEOPTS=$GIT_SSH_OPTS fi # Let ssh fail rather than prompt BASEOPTS="$BASEOPTS -o BatchMode=yes" if [ -z "$GIT_KEY" ]; then ssh $BASEOPTS "$@" else ssh -i "$GIT_KEY" -o IdentitiesOnly=yes $BASEOPTS "$@" fi """) fh.write(template) fh.close() st = os.stat(wrapper_path) os.chmod(wrapper_path, st.st_mode | stat.S_IEXEC) return wrapper_path def set_git_ssh(ssh_wrapper, key_file, ssh_opts): if os.environ.get("GIT_SSH"): del os.environ["GIT_SSH"] os.environ["GIT_SSH"] = ssh_wrapper if os.environ.get("GIT_KEY"): del os.environ["GIT_KEY"] if key_file: os.environ["GIT_KEY"] = key_file if os.environ.get("GIT_SSH_OPTS"): del os.environ["GIT_SSH_OPTS"] if ssh_opts: os.environ["GIT_SSH_OPTS"] = ssh_opts def get_version(module, git_path, dest, ref="HEAD"): ''' samples the version of the git repo ''' cmd = "%s rev-parse %s" % (git_path, ref) rc, stdout, stderr = module.run_command(cmd, cwd=dest) sha = to_native(stdout).rstrip('\n') return sha def ssh_supports_acceptnewhostkey(module): try: ssh_path = get_bin_path('ssh') except ValueError as err: module.fail_json( msg='Remote host is missing ssh command, so you cannot ' 'use acceptnewhostkey option.', details=to_text(err)) supports_acceptnewhostkey = True cmd = [ssh_path, '-o', 'StrictHostKeyChecking=accept-new', '-V'] rc, stdout, stderr = module.run_command(cmd) if rc != 0: supports_acceptnewhostkey = False return supports_acceptnewhostkey def get_submodule_versions(git_path, module, dest, version='HEAD'): cmd = [git_path, 'submodule', 'foreach', git_path, 'rev-parse', version] (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json( msg='Unable to determine hashes of submodules', stdout=out, stderr=err, rc=rc) submodules = {} subm_name = None for line in out.splitlines(): if line.startswith("Entering '"): subm_name = line[10:-1] elif len(line.strip()) == 40: if subm_name is None: module.fail_json() submodules[subm_name] = line.strip() subm_name = None else: module.fail_json(msg='Unable to parse submodule hash line: %s' % line.strip()) if subm_name is not None: module.fail_json(msg='Unable to find hash for submodule: %s' % subm_name) return submodules def clone(git_path, module, repo, dest, remote, depth, version, bare, reference, refspec, git_version_used, verify_commit, separate_git_dir, result, gpg_whitelist, single_branch): ''' makes a new git repo if it does not already exist ''' dest_dirname = os.path.dirname(dest) try: os.makedirs(dest_dirname) except Exception: pass cmd = [git_path, 'clone'] if bare: cmd.append('--bare') else: cmd.extend(['--origin', remote]) is_branch_or_tag = is_remote_branch(git_path, module, dest, repo, version) or is_remote_tag(git_path, module, dest, repo, version) if depth: if version == 'HEAD' or refspec: cmd.extend(['--depth', str(depth)]) elif is_branch_or_tag: cmd.extend(['--depth', str(depth)]) cmd.extend(['--branch', version]) else: # only use depth if the remote object is branch or tag (i.e. fetchable) module.warn("Ignoring depth argument. " "Shallow clones are only available for " "HEAD, branches, tags or in combination with refspec.") if reference: cmd.extend(['--reference', str(reference)]) if single_branch: if git_version_used is None: module.fail_json(msg='Cannot find git executable at %s' % git_path) if git_version_used < LooseVersion('1.7.10'): module.warn("git version '%s' is too old to use 'single-branch'. Ignoring." % git_version_used) else: cmd.append("--single-branch") if is_branch_or_tag: cmd.extend(['--branch', version]) needs_separate_git_dir_fallback = False if separate_git_dir: if git_version_used is None: module.fail_json(msg='Cannot find git executable at %s' % git_path) if git_version_used < LooseVersion('1.7.5'): # git before 1.7.5 doesn't have separate-git-dir argument, do fallback needs_separate_git_dir_fallback = True else: cmd.append('--separate-git-dir=%s' % separate_git_dir) cmd.extend([repo, dest]) module.run_command(cmd, check_rc=True, cwd=dest_dirname) if needs_separate_git_dir_fallback: relocate_repo(module, result, separate_git_dir, os.path.join(dest, ".git"), dest) if bare and remote != 'origin': module.run_command([git_path, 'remote', 'add', remote, repo], check_rc=True, cwd=dest) if refspec: cmd = [git_path, 'fetch'] if depth: cmd.extend(['--depth', str(depth)]) cmd.extend([remote, refspec]) module.run_command(cmd, check_rc=True, cwd=dest) if verify_commit: verify_commit_sign(git_path, module, dest, version, gpg_whitelist) def has_local_mods(module, git_path, dest, bare): if bare: return False cmd = "%s status --porcelain" % (git_path) rc, stdout, stderr = module.run_command(cmd, cwd=dest) lines = stdout.splitlines() lines = list(filter(lambda c: not re.search('^\\?\\?.*$', c), lines)) return len(lines) > 0 def reset(git_path, module, dest): ''' Resets the index and working tree to HEAD. Discards any changes to tracked files in working tree since that commit. ''' cmd = "%s reset --hard HEAD" % (git_path,) return module.run_command(cmd, check_rc=True, cwd=dest) def get_diff(module, git_path, dest, repo, remote, depth, bare, before, after): ''' Return the difference between 2 versions ''' if before is None: return {'prepared': '>> Newly checked out %s' % after} elif before != after: # Ensure we have the object we are referring to during git diff ! git_version_used = git_version(git_path, module) fetch(git_path, module, repo, dest, after, remote, depth, bare, '', git_version_used) cmd = '%s diff %s %s' % (git_path, before, after) (rc, out, err) = module.run_command(cmd, cwd=dest) if rc == 0 and out: return {'prepared': out} elif rc == 0: return {'prepared': '>> No visual differences between %s and %s' % (before, after)} elif err: return {'prepared': '>> Failed to get proper diff between %s and %s:\n>> %s' % (before, after, err)} else: return {'prepared': '>> Failed to get proper diff between %s and %s' % (before, after)} return {} def get_remote_head(git_path, module, dest, version, remote, bare): cloning = False cwd = None tag = False if remote == module.params['repo']: cloning = True elif remote == 'file://' + os.path.expanduser(module.params['repo']): cloning = True else: cwd = dest if version == 'HEAD': if cloning: # cloning the repo, just get the remote's HEAD version cmd = '%s ls-remote %s -h HEAD' % (git_path, remote) else: head_branch = get_head_branch(git_path, module, dest, remote, bare) cmd = '%s ls-remote %s -h refs/heads/%s' % (git_path, remote, head_branch) elif is_remote_branch(git_path, module, dest, remote, version): cmd = '%s ls-remote %s -h refs/heads/%s' % (git_path, remote, version) elif is_remote_tag(git_path, module, dest, remote, version): tag = True cmd = '%s ls-remote %s -t refs/tags/%s*' % (git_path, remote, version) else: # appears to be a sha1. return as-is since it appears # cannot check for a specific sha1 on remote return version (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=cwd) if len(out) < 1: module.fail_json(msg="Could not determine remote revision for %s" % version, stdout=out, stderr=err, rc=rc) out = to_native(out) if tag: # Find the dereferenced tag if this is an annotated tag. for tag in out.split('\n'): if tag.endswith(version + '^{}'): out = tag break elif tag.endswith(version): out = tag rev = out.split()[0] return rev def is_remote_tag(git_path, module, dest, remote, version): cmd = '%s ls-remote %s -t refs/tags/%s' % (git_path, remote, version) (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) if to_native(version, errors='surrogate_or_strict') in out: return True else: return False def get_branches(git_path, module, dest): branches = [] cmd = '%s branch --no-color -a' % (git_path,) (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json(msg="Could not determine branch data - received %s" % out, stdout=out, stderr=err) for line in out.split('\n'): if line.strip(): branches.append(line.strip()) return branches def get_annotated_tags(git_path, module, dest): tags = [] cmd = [git_path, 'for-each-ref', 'refs/tags/', '--format', '%(objecttype):%(refname:short)'] (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json(msg="Could not determine tag data - received %s" % out, stdout=out, stderr=err) for line in to_native(out).split('\n'): if line.strip(): tagtype, tagname = line.strip().split(':') if tagtype == 'tag': tags.append(tagname) return tags def is_remote_branch(git_path, module, dest, remote, version): cmd = '%s ls-remote %s -h refs/heads/%s' % (git_path, remote, version) (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) if to_native(version, errors='surrogate_or_strict') in out: return True else: return False def is_local_branch(git_path, module, dest, branch): branches = get_branches(git_path, module, dest) lbranch = '%s' % branch if lbranch in branches: return True elif '* %s' % branch in branches: return True else: return False def is_not_a_branch(git_path, module, dest): branches = get_branches(git_path, module, dest) for branch in branches: if branch.startswith('* ') and ('no branch' in branch or 'detached from' in branch or 'detached at' in branch): return True return False def get_repo_path(dest, bare): if bare: repo_path = dest else: repo_path = os.path.join(dest, '.git') # Check if the .git is a file. If it is a file, it means that the repository is in external directory respective to the working copy (e.g. we are in a # submodule structure). if os.path.isfile(repo_path): with open(repo_path, 'r') as gitfile: data = gitfile.read() ref_prefix, gitdir = data.rstrip().split('gitdir: ', 1) if ref_prefix: raise ValueError('.git file has invalid git dir reference format') # There is a possibility the .git file to have an absolute path. if os.path.isabs(gitdir): repo_path = gitdir else: repo_path = os.path.join(repo_path.split('.git')[0], gitdir) if not os.path.isdir(repo_path): raise ValueError('%s is not a directory' % repo_path) return repo_path def get_head_branch(git_path, module, dest, remote, bare=False): ''' Determine what branch HEAD is associated with. This is partly taken from lib/ansible/utils/__init__.py. It finds the correct path to .git/HEAD and reads from that file the branch that HEAD is associated with. In the case of a detached HEAD, this will look up the branch in .git/refs/remotes/<remote>/HEAD. ''' try: repo_path = get_repo_path(dest, bare) except (IOError, ValueError) as err: # No repo path found """``.git`` file does not have a valid format for detached Git dir.""" module.fail_json( msg='Current repo does not have a valid reference to a ' 'separate Git dir or it refers to the invalid path', details=to_text(err), ) # Read .git/HEAD for the name of the branch. # If we're in a detached HEAD state, look up the branch associated with # the remote HEAD in .git/refs/remotes/<remote>/HEAD headfile = os.path.join(repo_path, "HEAD") if is_not_a_branch(git_path, module, dest): headfile = os.path.join(repo_path, 'refs', 'remotes', remote, 'HEAD') branch = head_splitter(headfile, remote, module=module, fail_on_error=True) return branch def get_remote_url(git_path, module, dest, remote): '''Return URL of remote source for repo.''' command = [git_path, 'ls-remote', '--get-url', remote] (rc, out, err) = module.run_command(command, cwd=dest) if rc != 0: # There was an issue getting remote URL, most likely # command is not available in this version of Git. return None return to_native(out).rstrip('\n') def set_remote_url(git_path, module, repo, dest, remote): ''' updates repo from remote sources ''' # Return if remote URL isn't changing. remote_url = get_remote_url(git_path, module, dest, remote) if remote_url == repo or unfrackgitpath(remote_url) == unfrackgitpath(repo): return False command = [git_path, 'remote', 'set-url', remote, repo] (rc, out, err) = module.run_command(command, cwd=dest) if rc != 0: label = "set a new url %s for %s" % (repo, remote) module.fail_json(msg="Failed to %s: %s %s" % (label, out, err)) # Return False if remote_url is None to maintain previous behavior # for Git versions prior to 1.7.5 that lack required functionality. return remote_url is not None def fetch(git_path, module, repo, dest, version, remote, depth, bare, refspec, git_version_used, force=False): ''' updates repo from remote sources ''' set_remote_url(git_path, module, repo, dest, remote) commands = [] fetch_str = 'download remote objects and refs' fetch_cmd = [git_path, 'fetch'] refspecs = [] if depth: # try to find the minimal set of refs we need to fetch to get a # successful checkout currenthead = get_head_branch(git_path, module, dest, remote) if refspec: refspecs.append(refspec) elif version == 'HEAD': refspecs.append(currenthead) elif is_remote_branch(git_path, module, dest, repo, version): if currenthead != version: # this workaround is only needed for older git versions # 1.8.3 is broken, 1.9.x works # ensure that remote branch is available as both local and remote ref refspecs.append('+refs/heads/%s:refs/heads/%s' % (version, version)) refspecs.append('+refs/heads/%s:refs/remotes/%s/%s' % (version, remote, version)) elif is_remote_tag(git_path, module, dest, repo, version): refspecs.append('+refs/tags/' + version + ':refs/tags/' + version) if refspecs: # if refspecs is empty, i.e. version is neither heads nor tags # assume it is a version hash # fall back to a full clone, otherwise we might not be able to checkout # version fetch_cmd.extend(['--depth', str(depth)]) if not depth or not refspecs: # don't try to be minimalistic but do a full clone # also do this if depth is given, but version is something that can't be fetched directly if bare: refspecs = ['+refs/heads/*:refs/heads/*', '+refs/tags/*:refs/tags/*'] else: # ensure all tags are fetched if git_version_used >= LooseVersion('1.9'): fetch_cmd.append('--tags') else: # old git versions have a bug in --tags that prevents updating existing tags commands.append((fetch_str, fetch_cmd + [remote])) refspecs = ['+refs/tags/*:refs/tags/*'] if refspec: refspecs.append(refspec) if force: fetch_cmd.append('--force') fetch_cmd.extend([remote]) commands.append((fetch_str, fetch_cmd + refspecs)) for (label, command) in commands: (rc, out, err) = module.run_command(command, cwd=dest) if rc != 0: module.fail_json(msg="Failed to %s: %s %s" % (label, out, err), cmd=command) def submodules_fetch(git_path, module, remote, track_submodules, dest): changed = False if not os.path.exists(os.path.join(dest, '.gitmodules')): # no submodules return changed gitmodules_file = open(os.path.join(dest, '.gitmodules'), 'r') for line in gitmodules_file: # Check for new submodules if not changed and line.strip().startswith('path'): path = line.split('=', 1)[1].strip() # Check that dest/path/.git exists if not os.path.exists(os.path.join(dest, path, '.git')): changed = True # Check for updates to existing modules if not changed: # Fetch updates begin = get_submodule_versions(git_path, module, dest) cmd = [git_path, 'submodule', 'foreach', git_path, 'fetch'] (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) if rc != 0: module.fail_json(msg="Failed to fetch submodules: %s" % out + err) if track_submodules: # Compare against submodule HEAD # FIXME: determine this from .gitmodules version = 'master' after = get_submodule_versions(git_path, module, dest, '%s/%s' % (remote, version)) if begin != after: changed = True else: # Compare against the superproject's expectation cmd = [git_path, 'submodule', 'status'] (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) if rc != 0: module.fail_json(msg='Failed to retrieve submodule status: %s' % out + err) for line in out.splitlines(): if line[0] != ' ': changed = True break return changed def submodule_update(git_path, module, dest, track_submodules, force=False): ''' init and update any submodules ''' # get the valid submodule params params = get_submodule_update_params(module, git_path, dest) # skip submodule commands if .gitmodules is not present if not os.path.exists(os.path.join(dest, '.gitmodules')): return (0, '', '') cmd = [git_path, 'submodule', 'sync'] (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) if 'remote' in params and track_submodules: cmd = [git_path, 'submodule', 'update', '--init', '--recursive', '--remote'] else: cmd = [git_path, 'submodule', 'update', '--init', '--recursive'] if force: cmd.append('--force') (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json(msg="Failed to init/update submodules: %s" % out + err) return (rc, out, err) def set_remote_branch(git_path, module, dest, remote, version, depth): """set refs for the remote branch version This assumes the branch does not yet exist locally and is therefore also not checked out. Can't use git remote set-branches, as it is not available in git 1.7.1 (centos6) """ branchref = "+refs/heads/%s:refs/heads/%s" % (version, version) branchref += ' +refs/heads/%s:refs/remotes/%s/%s' % (version, remote, version) cmd = "%s fetch --depth=%s %s %s" % (git_path, depth, remote, branchref) (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json(msg="Failed to fetch branch from remote: %s" % version, stdout=out, stderr=err, rc=rc) def switch_version(git_path, module, dest, remote, version, verify_commit, depth, gpg_whitelist): cmd = '' if version == 'HEAD': branch = get_head_branch(git_path, module, dest, remote) (rc, out, err) = module.run_command("%s checkout --force %s" % (git_path, branch), cwd=dest) if rc != 0: module.fail_json(msg="Failed to checkout branch %s" % branch, stdout=out, stderr=err, rc=rc) cmd = "%s reset --hard %s/%s --" % (git_path, remote, branch) else: # FIXME check for local_branch first, should have been fetched already if is_remote_branch(git_path, module, dest, remote, version): if depth and not is_local_branch(git_path, module, dest, version): # git clone --depth implies --single-branch, which makes # the checkout fail if the version changes # fetch the remote branch, to be able to check it out next set_remote_branch(git_path, module, dest, remote, version, depth) if not is_local_branch(git_path, module, dest, version): cmd = "%s checkout --track -b %s %s/%s" % (git_path, version, remote, version) else: (rc, out, err) = module.run_command("%s checkout --force %s" % (git_path, version), cwd=dest) if rc != 0: module.fail_json(msg="Failed to checkout branch %s" % version, stdout=out, stderr=err, rc=rc) cmd = "%s reset --hard %s/%s" % (git_path, remote, version) else: cmd = "%s checkout --force %s" % (git_path, version) (rc, out1, err1) = module.run_command(cmd, cwd=dest) if rc != 0: if version != 'HEAD': module.fail_json(msg="Failed to checkout %s" % (version), stdout=out1, stderr=err1, rc=rc, cmd=cmd) else: module.fail_json(msg="Failed to checkout branch %s" % (branch), stdout=out1, stderr=err1, rc=rc, cmd=cmd) if verify_commit: verify_commit_sign(git_path, module, dest, version, gpg_whitelist) return (rc, out1, err1) def verify_commit_sign(git_path, module, dest, version, gpg_whitelist): if version in get_annotated_tags(git_path, module, dest): git_sub = "verify-tag" else: git_sub = "verify-commit" cmd = "%s %s %s" % (git_path, git_sub, version) if gpg_whitelist: cmd += " --raw" (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json(msg='Failed to verify GPG signature of commit/tag "%s"' % version, stdout=out, stderr=err, rc=rc) if gpg_whitelist: fingerprint = get_gpg_fingerprint(err) if fingerprint not in gpg_whitelist: module.fail_json(msg='The gpg_whitelist does not include the public key "%s" for this commit' % fingerprint, stdout=out, stderr=err, rc=rc) return (rc, out, err) def get_gpg_fingerprint(output): """Return a fingerprint of the primary key. Ref: https://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=blob;f=doc/DETAILS;hb=HEAD#l482 """ for line in output.splitlines(): data = line.split() if data[1] != 'VALIDSIG': continue # if signed with a subkey, this contains the primary key fingerprint data_id = 11 if len(data) == 11 else 2 return data[data_id] def git_version(git_path, module): """return the installed version of git""" cmd = "%s --version" % git_path (rc, out, err) = module.run_command(cmd) if rc != 0: # one could fail_json here, but the version info is not that important, # so let's try to fail only on actual git commands return None rematch = re.search('git version (.*)$', to_native(out)) if not rematch: return None return LooseVersion(rematch.groups()[0]) def git_archive(git_path, module, dest, archive, archive_fmt, archive_prefix, version): """ Create git archive in given source directory """ cmd = [git_path, 'archive', '--format', archive_fmt, '--output', archive, version] if archive_prefix is not None: cmd.insert(-1, '--prefix') cmd.insert(-1, archive_prefix) (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json(msg="Failed to perform archive operation", details="Git archive command failed to create " "archive %s using %s directory." "Error: %s" % (archive, dest, err)) return rc, out, err def create_archive(git_path, module, dest, archive, archive_prefix, version, repo, result): """ Helper function for creating archive using git_archive """ all_archive_fmt = {'.zip': 'zip', '.gz': 'tar.gz', '.tar': 'tar', '.tgz': 'tgz'} _, archive_ext = os.path.splitext(archive) archive_fmt = all_archive_fmt.get(archive_ext, None) if archive_fmt is None: module.fail_json(msg="Unable to get file extension from " "archive file name : %s" % archive, details="Please specify archive as filename with " "extension. File extension can be one " "of ['tar', 'tar.gz', 'zip', 'tgz']") repo_name = repo.split("/")[-1].replace(".git", "") if os.path.exists(archive): # If git archive file exists, then compare it with new git archive file. # if match, do nothing # if does not match, then replace existing with temp archive file. tempdir = tempfile.mkdtemp() new_archive_dest = os.path.join(tempdir, repo_name) new_archive = new_archive_dest + '.' + archive_fmt git_archive(git_path, module, dest, new_archive, archive_fmt, archive_prefix, version) # filecmp is supposed to be efficient than md5sum checksum if filecmp.cmp(new_archive, archive): result.update(changed=False) # Cleanup before exiting try: shutil.rmtree(tempdir) except OSError: pass else: try: shutil.move(new_archive, archive) shutil.rmtree(tempdir) result.update(changed=True) except OSError as e: module.fail_json(msg="Failed to move %s to %s" % (new_archive, archive), details=u"Error occurred while moving : %s" % to_text(e)) else: # Perform archive from local directory git_archive(git_path, module, dest, archive, archive_fmt, archive_prefix, version) result.update(changed=True) # =========================================== def main(): module = AnsibleModule( argument_spec=dict( dest=dict(type='path'), repo=dict(required=True, aliases=['name']), version=dict(default='HEAD'), remote=dict(default='origin'), refspec=dict(default=None), reference=dict(default=None), force=dict(default='no', type='bool'), depth=dict(default=None, type='int'), clone=dict(default='yes', type='bool'), update=dict(default='yes', type='bool'), verify_commit=dict(default='no', type='bool'), gpg_whitelist=dict(default=[], type='list', elements='str'), accept_hostkey=dict(default='no', type='bool'), accept_newhostkey=dict(default='no', type='bool'), key_file=dict(default=None, type='path', required=False), ssh_opts=dict(default=None, required=False), executable=dict(default=None, type='path'), bare=dict(default='no', type='bool'), recursive=dict(default='yes', type='bool'), single_branch=dict(default=False, type='bool'), track_submodules=dict(default='no', type='bool'), umask=dict(default=None, type='raw'), archive=dict(type='path'), archive_prefix=dict(), separate_git_dir=dict(type='path'), ), mutually_exclusive=[('separate_git_dir', 'bare'), ('accept_hostkey', 'accept_newhostkey')], required_by={'archive_prefix': ['archive']}, supports_check_mode=True ) dest = module.params['dest'] repo = module.params['repo'] version = module.params['version'] remote = module.params['remote'] refspec = module.params['refspec'] force = module.params['force'] depth = module.params['depth'] update = module.params['update'] allow_clone = module.params['clone'] bare = module.params['bare'] verify_commit = module.params['verify_commit'] gpg_whitelist = module.params['gpg_whitelist'] reference = module.params['reference'] single_branch = module.params['single_branch'] git_path = module.params['executable'] or module.get_bin_path('git', True) key_file = module.params['key_file'] ssh_opts = module.params['ssh_opts'] umask = module.params['umask'] archive = module.params['archive'] archive_prefix = module.params['archive_prefix'] separate_git_dir = module.params['separate_git_dir'] result = dict(changed=False, warnings=list()) if module.params['accept_hostkey']: if ssh_opts is not None: if ("-o StrictHostKeyChecking=no" not in ssh_opts) and ("-o StrictHostKeyChecking=accept-new" not in ssh_opts): ssh_opts += " -o StrictHostKeyChecking=no" else: ssh_opts = "-o StrictHostKeyChecking=no" if module.params['accept_newhostkey']: if not ssh_supports_acceptnewhostkey(module): module.warn("Your ssh client does not support accept_newhostkey option, therefore it cannot be used.") else: if ssh_opts is not None: if ("-o StrictHostKeyChecking=no" not in ssh_opts) and ("-o StrictHostKeyChecking=accept-new" not in ssh_opts): ssh_opts += " -o StrictHostKeyChecking=accept-new" else: ssh_opts = "-o StrictHostKeyChecking=accept-new" # evaluate and set the umask before doing anything else if umask is not None: if not isinstance(umask, string_types): module.fail_json(msg="umask must be defined as a quoted octal integer") try: umask = int(umask, 8) except Exception: module.fail_json(msg="umask must be an octal integer", details=str(sys.exc_info()[1])) os.umask(umask) # Certain features such as depth require a file:/// protocol for path based urls # so force a protocol here ... if os.path.expanduser(repo).startswith('/'): repo = 'file://' + os.path.expanduser(repo) # We screenscrape a huge amount of git commands so use C locale anytime we # call run_command() module.run_command_environ_update = dict(LANG='C', LC_ALL='C', LC_MESSAGES='C', LC_CTYPE='C') if separate_git_dir: separate_git_dir = os.path.realpath(separate_git_dir) gitconfig = None if not dest and allow_clone: module.fail_json(msg="the destination directory must be specified unless clone=no") elif dest: dest = os.path.abspath(dest) try: repo_path = get_repo_path(dest, bare) if separate_git_dir and os.path.exists(repo_path) and separate_git_dir != repo_path: result['changed'] = True if not module.check_mode: relocate_repo(module, result, separate_git_dir, repo_path, dest) repo_path = separate_git_dir except (IOError, ValueError) as err: # No repo path found """``.git`` file does not have a valid format for detached Git dir.""" module.fail_json( msg='Current repo does not have a valid reference to a ' 'separate Git dir or it refers to the invalid path', details=to_text(err), ) gitconfig = os.path.join(repo_path, 'config') # create a wrapper script and export # GIT_SSH=<path> as an environment variable # for git to use the wrapper script ssh_wrapper = write_ssh_wrapper(module.tmpdir) set_git_ssh(ssh_wrapper, key_file, ssh_opts) module.add_cleanup_file(path=ssh_wrapper) git_version_used = git_version(git_path, module) if depth is not None and git_version_used < LooseVersion('1.9.1'): module.warn("git version is too old to fully support the depth argument. Falling back to full checkouts.") depth = None recursive = module.params['recursive'] track_submodules = module.params['track_submodules'] result.update(before=None) local_mods = False if (dest and not os.path.exists(gitconfig)) or (not dest and not allow_clone): # if there is no git configuration, do a clone operation unless: # * the user requested no clone (they just want info) # * we're doing a check mode test # In those cases we do an ls-remote if module.check_mode or not allow_clone: remote_head = get_remote_head(git_path, module, dest, version, repo, bare) result.update(changed=True, after=remote_head) if module._diff: diff = get_diff(module, git_path, dest, repo, remote, depth, bare, result['before'], result['after']) if diff: result['diff'] = diff module.exit_json(**result) # there's no git config, so clone clone(git_path, module, repo, dest, remote, depth, version, bare, reference, refspec, git_version_used, verify_commit, separate_git_dir, result, gpg_whitelist, single_branch) elif not update: # Just return having found a repo already in the dest path # this does no checking that the repo is the actual repo # requested. result['before'] = get_version(module, git_path, dest) result.update(after=result['before']) if archive: # Git archive is not supported by all git servers, so # we will first clone and perform git archive from local directory if module.check_mode: result.update(changed=True) module.exit_json(**result) create_archive(git_path, module, dest, archive, archive_prefix, version, repo, result) module.exit_json(**result) else: # else do a pull local_mods = has_local_mods(module, git_path, dest, bare) result['before'] = get_version(module, git_path, dest) if local_mods: # failure should happen regardless of check mode if not force: module.fail_json(msg="Local modifications exist in repository (force=no).", **result) # if force and in non-check mode, do a reset if not module.check_mode: reset(git_path, module, dest) result.update(changed=True, msg='Local modifications exist.') # exit if already at desired sha version if module.check_mode: remote_url = get_remote_url(git_path, module, dest, remote) remote_url_changed = remote_url and remote_url != repo and unfrackgitpath(remote_url) != unfrackgitpath(repo) else: remote_url_changed = set_remote_url(git_path, module, repo, dest, remote) result.update(remote_url_changed=remote_url_changed) if module.check_mode: remote_head = get_remote_head(git_path, module, dest, version, remote, bare) result.update(changed=(result['before'] != remote_head or remote_url_changed), after=remote_head) # FIXME: This diff should fail since the new remote_head is not fetched yet?! if module._diff: diff = get_diff(module, git_path, dest, repo, remote, depth, bare, result['before'], result['after']) if diff: result['diff'] = diff module.exit_json(**result) else: fetch(git_path, module, repo, dest, version, remote, depth, bare, refspec, git_version_used, force=force) result['after'] = get_version(module, git_path, dest) # switch to version specified regardless of whether # we got new revisions from the repository if not bare: switch_version(git_path, module, dest, remote, version, verify_commit, depth, gpg_whitelist) # Deal with submodules submodules_updated = False if recursive and not bare: submodules_updated = submodules_fetch(git_path, module, remote, track_submodules, dest) if submodules_updated: result.update(submodules_changed=submodules_updated) if module.check_mode: result.update(changed=True, after=remote_head) module.exit_json(**result) # Switch to version specified submodule_update(git_path, module, dest, track_submodules, force=force) # determine if we changed anything result['after'] = get_version(module, git_path, dest) if result['before'] != result['after'] or local_mods or submodules_updated or remote_url_changed: result.update(changed=True) if module._diff: diff = get_diff(module, git_path, dest, repo, remote, depth, bare, result['before'], result['after']) if diff: result['diff'] = diff if archive: # Git archive is not supported by all git servers, so # we will first clone and perform git archive from local directory if module.check_mode: result.update(changed=True) module.exit_json(**result) create_archive(git_path, module, dest, archive, archive_prefix, version, repo, result) module.exit_json(**result) if __name__ == '__main__': main()
dmsimard/ansible
lib/ansible/modules/git.py
Python
gpl-3.0
53,677
<?php /**************************************************************************/ /* PHP-NUKE: Advanced Content Management System */ /* ============================================ */ /* */ /* This is the language module with all the system messages */ /* */ /* If you made a translation, please go to the site and send to me */ /* the translated file. Please keep the original text order by modules, */ /* and just one message per line, also double check your translation! */ /* */ /* You need to change the second quoted phrase, not the capital one! */ /* */ /* If you need to use double quotes (') remember to add a backslash (\), */ /* so your entry will look like: This is \'double quoted\' text. */ /* And, if you use HTML code, please double check it. */ /* If you create the correct translation for this file please post it */ /* in the forums at www.ravenphpscripts.com */ /* */ /**************************************************************************/ define('_MA_ARTICLE','Articles'); define('_MA_ARTICLEID','Article #'); define('_MA_ARTICLE_AUTHOR_UPDATE','has been tied to '); define('_MA_ARTICLE_UPDATE_WARNING','You must enter an Article ID <strong>and</strong> an author username to move an article.'); define('_MA_READS_TO_MAKE_TOP10','Reads to make top 10: '); define('_MA_NO_AUTHORS','No User Authors'); define('_TOPWELCOME','Welcome to the Articles and Authors page for '); define('_WELCOME','Welcome'); define('_SUBMITCONTENT','Submit Content'); define('_SUBMITARTICLE','Submit Article'); define('_WRITEREVIEW','Write Review'); define('_SUBMITWEBLINK','Submit Web Link'); define('_STATISTICS','Statistics'); define('_QUICKSTATOVERVIEW','Quick Stat Overview'); define('_TOPRECENTSTORIES','Top Stories in the last 30 days'); define('_TOPALLSTORIES','Top Stories of all time'); define('_TOPAUTHORS','Top Authors'); define('_MONTHLYARTICLEOVERVIEW','Monthly Article Overview'); define('_ARTICLECOUNTBYTOPIC','Article Count By Topic'); define('_ARTICLECOUNTBYCATEGORY','Article Count By Category'); define('_STORYREADS','Reads'); define('_STORIES','Stories'); define('_STORYAVGREADS','Avg Reads'); define('_OVERALL','Overall'); define('_RECENT','Recent'); define('_STORYTITLE','Title'); define('_STORYDATE','Date'); define('_AUTHORNAME','Author'); define('_READSPERDAY','Reads Per Day'); define('_READSTORIES','most read stories'); define('_TOP','Top'); define('_AUTHORS','Authors'); define('_NUMSTORIES','# Stories'); define('_TOTALRATINGS','Total Ratings'); define('_AVGRATINGS','Avg Rating'); define('_MONTH','Month'); define('_CATEGORY','Category'); define('_LVOTES','votes'); define('_HITS','Hits'); define('_LINKSDATESTRING','%d. %m. %Y'); ?>
TGates71/PNPv1-Languages
PNPv101-lang-english/modules/MetAuthors/language/lang-english.php
PHP
gpl-3.0
3,154
/* This file is part of SpatGRIS. Developers: Samuel Béland, Olivier Bélanger, Nicolas Masson SpatGRIS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SpatGRIS 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 SpatGRIS. If not, see <http://www.gnu.org/licenses/>. */ #include "sg_AbstractSliceComponent.hpp" //============================================================================== AbstractSliceComponent::AbstractSliceComponent(GrisLookAndFeel & lookAndFeel, SmallGrisLookAndFeel & smallLookAndFeel) : mLayout(LayoutComponent::Orientation::vertical, false, false, lookAndFeel) , mVuMeter(smallLookAndFeel) , mMuteSoloComponent(*this, lookAndFeel, smallLookAndFeel) { JUCE_ASSERT_MESSAGE_THREAD; addAndMakeVisible(mLayout); } //============================================================================== void AbstractSliceComponent::setState(PortState const state, bool const soloMode) { JUCE_ASSERT_MESSAGE_THREAD; mMuteSoloComponent.setPortState(state); mVuMeter.setMuted(soloMode ? state != PortState::solo : state == PortState::muted); repaint(); }
GRIS-UdeM/spatServerGRIS
Source/sg_AbstractSliceComponent.cpp
C++
gpl-3.0
1,548
#include "main/SimpleCardProtocol.hh" #include "bridge/BridgeConstants.hh" #include "bridge/CardShuffle.hh" #include "bridge/CardType.hh" #include "bridge/Position.hh" #include "engine/SimpleCardManager.hh" #include "main/Commands.hh" #include "main/PeerCommandSender.hh" #include "messaging/CardTypeJsonSerializer.hh" #include "messaging/FunctionMessageHandler.hh" #include "messaging/JsonSerializer.hh" #include "messaging/JsonSerializerUtility.hh" #include "messaging/UuidJsonSerializer.hh" #include "Logging.hh" #include <algorithm> #include <optional> #include <string> #include <tuple> #include <utility> namespace Bridge { namespace Main { using CardVector = std::vector<CardType>; using Engine::CardManager; using Messaging::failure; using Messaging::Identity; using Messaging::JsonSerializer; using Messaging::Reply; using Messaging::success; class SimpleCardProtocol::Impl : public Bridge::Observer<CardManager::ShufflingState> { public: Impl( const Uuid& gameUuid, std::shared_ptr<PeerCommandSender> peerCommandSender); bool acceptPeer( const Identity& identity, const PositionVector& positions); Reply<> deal(const Identity& identity, const CardVector& cards); const Uuid gameUuid; const std::shared_ptr<Engine::SimpleCardManager> cardManager { std::make_shared<Engine::SimpleCardManager>()}; private: void handleNotify(const CardManager::ShufflingState& state) override; bool expectingCards {false}; std::optional<Identity> leaderIdentity; const std::shared_ptr<PeerCommandSender> peerCommandSender; }; SimpleCardProtocol::Impl::Impl( const Uuid& gameUuid, std::shared_ptr<PeerCommandSender> peerCommandSender) : gameUuid {gameUuid}, peerCommandSender {std::move(peerCommandSender)} { } void SimpleCardProtocol::Impl::handleNotify( const CardManager::ShufflingState& state) { if (state == CardManager::ShufflingState::REQUESTED) { if (!leaderIdentity) { log(LogLevel::DEBUG, "Simple card protocol: Generating deck"); auto cards = generateShuffledDeck(); assert(cardManager); cardManager->shuffle(cards.begin(), cards.end()); dereference(peerCommandSender).sendCommand( JsonSerializer {}, DEAL_COMMAND, std::pair {GAME_COMMAND, gameUuid}, std::pair {CARDS_COMMAND, std::move(cards)}); } else { log(LogLevel::DEBUG, "Simple card protocol: Expecting deck"); expectingCards = true; } } } bool SimpleCardProtocol::Impl::acceptPeer( const Identity& identity, const PositionVector& positions) { if (std::find(positions.begin(), positions.end(), Positions::NORTH) != positions.end()) { leaderIdentity = identity; } return true; } Reply<> SimpleCardProtocol::Impl::deal( const Identity& identity, const CardVector& cards) { log(LogLevel::DEBUG, "Deal command from %s", identity); if (expectingCards && leaderIdentity == identity) { cardManager->shuffle(cards.begin(), cards.end()); expectingCards = false; return success(); } return failure(); } SimpleCardProtocol::SimpleCardProtocol( const Uuid& gameUuid, std::shared_ptr<PeerCommandSender> peerCommandSender) : impl { std::make_shared<Impl>(gameUuid, std::move(peerCommandSender))} { assert(impl->cardManager); impl->cardManager->subscribe(impl); } bool SimpleCardProtocol::handleAcceptPeer( const Identity& identity, const PositionVector& positions, const OptionalArgs&) { assert(impl); return impl->acceptPeer(identity, positions); } void SimpleCardProtocol::handleInitialize() { } std::shared_ptr<Messaging::MessageHandler> SimpleCardProtocol::handleGetDealMessageHandler() { return Messaging::makeMessageHandler( *impl, &Impl::deal, JsonSerializer {}, std::tuple {CARDS_COMMAND}); } SimpleCardProtocol::SocketVector SimpleCardProtocol::handleGetSockets() { return {}; } std::shared_ptr<CardManager> SimpleCardProtocol::handleGetCardManager() { assert(impl); return impl->cardManager; } } }
jasujm/bridge
src/main/SimpleCardProtocol.cc
C++
gpl-3.0
4,231
#define BOOST_TEST_MODULE sugar_integration_tests #include <boost/test/included/unit_test.hpp>
vancleve/fwdpp
testsuite/integration/sugar_integration_tests.cc
C++
gpl-3.0
95
// Mantid Repository : https://github.com/mantidproject/mantid // // Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, // NScD Oak Ridge National Laboratory, European Spallation Source // & Institut Laue - Langevin // SPDX - License - Identifier: GPL - 3.0 + //---------------------------------------------------------------------- // Includes //---------------------------------------------------------------------- #include "MantidDataHandling/RemoveLogs.h" #include "MantidAPI/FileProperty.h" #include "MantidDataObjects/Workspace2D.h" #include "MantidKernel/ArrayProperty.h" #include "MantidKernel/Glob.h" #include "MantidKernel/PropertyWithValue.h" #include "MantidKernel/Strings.h" #include "MantidKernel/TimeSeriesProperty.h" #include <Poco/DateTimeFormat.h> #include <Poco/DateTimeParser.h> #include <Poco/DirectoryIterator.h> #include <Poco/File.h> #include <Poco/Path.h> #include <boost/algorithm/string.hpp> #include <algorithm> #include <fstream> // used to get ifstream #include <sstream> namespace Mantid { namespace DataHandling { // Register the algorithm into the algorithm factory DECLARE_ALGORITHM(RemoveLogs) using namespace Kernel; using namespace API; using DataObjects::Workspace2D_sptr; /// Empty default constructor RemoveLogs::RemoveLogs() {} /// Initialisation method. void RemoveLogs::init() { // When used as a Child Algorithm the workspace name is not used - hence the // "Anonymous" to satisfy the validator declareProperty( make_unique<WorkspaceProperty<MatrixWorkspace>>("Workspace", "Anonymous", Direction::InOut), "The name of the workspace to which the log data will be removed"); declareProperty( make_unique<ArrayProperty<std::string>>("KeepLogs", Direction::Input), "List(comma separated) of logs to be kept"); } /** Executes the algorithm. Reading in log file(s) * * @throw Mantid::Kernel::Exception::FileError Thrown if file is not *recognised to be a raw datafile or log file * @throw std::runtime_error Thrown with Workspace problems */ void RemoveLogs::exec() { // Get the input workspace and retrieve run from workspace. // the log file(s) will be loaded into the run object of the workspace const MatrixWorkspace_sptr localWorkspace = getProperty("Workspace"); const std::vector<Mantid::Kernel::Property *> &logData = localWorkspace->run().getLogData(); std::vector<std::string> keepLogs = getProperty("KeepLogs"); std::vector<std::string> logNames; logNames.reserve(logData.size()); for (const auto property : logData) { logNames.push_back(property->name()); } for (const auto &name : logNames) { auto location = std::find(keepLogs.cbegin(), keepLogs.cend(), name); if (location == keepLogs.cend()) { localWorkspace->mutableRun().removeLogData(name); } } // operation was a success and ended normally return; } } // namespace DataHandling } // namespace Mantid
mganeva/mantid
Framework/DataHandling/src/RemoveLogs.cpp
C++
gpl-3.0
2,988
/** * file mirror/doc/factory_generator.hpp * Documentation only header * * @author Matus Chochlik * * Copyright 2008-2010 Matus Chochlik. Distributed under the Boost * Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef MIRROR_DOC_FACTORY_GENERATOR_1011291729_HPP #define MIRROR_DOC_FACTORY_GENERATOR_1011291729_HPP #ifdef MIRROR_DOCUMENTATION_ONLY #include <mirror/config.hpp> MIRROR_NAMESPACE_BEGIN /** @page mirror_factory_generator_utility Factory generator utility * * @section mirror_factory_generator_intro Introduction * * The factory generator utility allows to easily create implementations * of object factories at compile-time by using the meta-data provided * by Mirror. * By object factories we mean here classes, which can create * instances of various types (@c Products), but do not require that the caller * supplies the parameters for the construction directly. * Factories pick or let the application user pick the @c Product 's most * appropriate constructor, they gather the necessary parameters in * a generic, application-specific way and use the selected constructor * to create an instance of the @c Product. * * Obviously the most interesting feature of these factories is, that * they separate the caller (who just needs to get an instance of the * specified type) from the actual method of creation which involves * choosing of right constructor and supplying the * required parameters, which in turn can also be constructed or supplied * in some other way (for example from a pool of existing objects). * * This is useful when we need to create instances of (possibly different) * types having multiple constructors from a single point in code and we want * the method of construction to be determined by parameters available only * at run-time. * * Here follows a brief list of examples: * - Creation of objects based on user input from a GUI: The factory object * creates a GUI component (a dialog for example) having the necessary * controls for selecting one of the constructors of the constructed type * and for the input of the values of all parameters for the selected * constructor. * - Creation of objects from a database dataset: The factory can go through * the list of constructors and find the one whose parameters are matching * to the columns in a database dataset. Then it calls this constructor * and passes the values of the matching columns as the parameters, doing * the appropriate type conversions where necessary. By doing this repeatedly * we can create multiple objects, each representing a different row in * the dataset. * - Creation of objects from other external representations: Similar to * the option above one can create instances from other file or stream-based * data representations like (XML, JSON, XDR, etc.) * * The factories generated by this utility can then be used for example * for the implementation of the Abstract factory design pattern, where * even the exact type of the created object is not known. * * Because the factory classes are created by a generic meta-program * at compile-time a good optimizing compiler can generate source * code, which is as efficient as if the factories were hand-coded. * This however depends on the implementation of the application-specific * parts that are supplied to the factory generator. * * @section mirror_factory_generator_principles Principles * * As we mentioned in the introduction, the factory must handle two important * tasks during the construction of an instance: * - Choose the constructor (default, copy, custom). * - Supply the parameters to the constructor if necessary. * * The implementation of these tasks is also the most distinctive thing * about a particular factory. The rest of the process is the same regardless * of the @c Product type. This is why the factory generator utility provides * all the common boilerplate code and the application only specifies how * a constuctor is selected and how the arguments are supplied to it. * * Furthermore there are two basic ways how to supply a parameter value: * - Create one from scratch by using the same factory with a different * @c Product type recursivelly. * - Use an existing instance which can be acquired from a pool of instances, * or be a result of a functor call. * * In order to create a factory, the application needs to supply the factory * generator with two template classes with the following signature: * * @code * template <class Product, class SourceTraits> * class constructor_parameter_source; * @endcode * * The first one is referred to as a @c Manufacturer and is responsible * for the creation of new parameter values. The second template is * referred to as @c Suppliers and is responsible for returning of an existing * value. * * One of the specializations of the @c Manufacturer template, namely the one * having the @c void type as @c Product is referred to as @c Manager. * This @c Manager is responsible for the selecting of the constructor that * to be used. * * Both of these templates have the following parameters: * - @c Product is the type produced by the source. A @c Manufacturer creates * a new instance of @c Product and @c Suppliers return an * existing instance of @c Product (one of possibly multiple candidates) * - @c SourceTraits is an optional type parameter used by some factory * implementations for the configuration and fine tuning of the factory's * behavior and appearance. * * Whether these sources (@c Manufacturer or @c Suppliers) are going to be used * for the supplying of a constructor parameter and if so, which of them, * depends on the selected constructor: * - If the @c Product 's default constructor is selected, then no parameters * are required and neither the @c Manufacturer nor the @c Suppliers are used. * - If the copy constructor is selected then the @c Suppliers template * (which returns existing instances of the same type) is used. * - If another constructor was picked, then the @c Manufacturer template is used * to create the individual parameters. * * @subsection mirror_factory_generator_manufacturer The Manufacturer * * The application-defined @c Manufacturer template should have several * distinct specializations, which serve for different purposes. * * As mentioned before, a @c Manufacturer with the @c void type as @c Product * serves as a manager which is responsible for choosing the constructor * that is ultimately to be used for the construction of an instance * of the @c Product. This means that besides the regular @c Manufacturer * which in fact creates the instances, there is one instance of the @c Manager * for every @c Product in the generated factory. The @c Manager has also * a different interface then the other @c Manufacturers. * * Other specializations of the @c Manufacturer should handle the creation of * values of some special types (like the native C++ types; boolean, integers, * floating points, strings, etc), considered atomic (i.e. not eleborated) * by the factory. Values of such types can be input directly by the user * into some kind of UI, they can be converted from some external representation * like the value of row/column in a database dataset, or a value of an XML * attribute, etc. * * The default implementation of the @c Manufacturer is for elaborated types and it * uses a generated factory to recursively create instances of the constructor * parameters. * * @subsection mirror_factory_generator_suppliers The Suppliers * * The @c Suppliers template is responsible for returning existing instances * of the type passed as the @c Product parameter. Depending on the specific * factory and the @c Product, the suppliers may or may not have means * to get instances of that particular @c Product type and should be implemented * accordingly. If there are multiple possible sources of values of a type * then the specialization of @c Suppliers must provide some means how to * select which of the external sources is to be used. * * @subsection mirror_factory_generator_source_traits The parameter source traits * * For additional flexibility both the @c Manufacturer and the @c Suppliers * template have (besides the @c Product type they create) an aditional template * type parameter called @c SourceTraits. This type is usually defined together * with the @c Manufacturer and @c Suppliers and is passed to the instantiations * of these templates by the factory generator when a new factory is created. * The factory generator treats this type as opaque. * If a concrete implementation of the parameter sources (@c Manufacturer and * @c Suppliers) has no use for this additional parameter, the void type * can be passed to the factory generator. * * @subsection mirror_factory_generator_factory_maker Factory and Factory Maker * * The @c Manufacturers, the @c Suppliers, the @c SourceTraits and * the boilerplate code common to all factories is tied together by * the @c mirror::factory template, with the following definition: * * @code * template < * template <class, class> class Manufacturer, * template <class, class> class Suppliers, * class SourceTraits, * typename Product * > class factory * { * public: * Product operator()(void); * Product* new_(void); * }; * @endcode * * Perhaps a more convenient way how to create factories, especially when * one wants to create multiple factories of the same kind (with the same * @c Manufacturers, @c Suppliers and @c SourceTraits) for constructing * different @c Product types is to use the @c mirror::factory_maker template * class defined as follows: * * @code * template < * template <class, class> class Manufacturer, * template <class, class> class Suppliers, * class SourceTraits * > struct factory_maker * { * template <typename Product> * struct factory * { * typedef factory<Manufacturer, Suppliers, SourceTraits, Product> type; * }; * }; * @endcode * * @section mirror_factory_generator_usage Usage * * The basic usage of the factory generator utility should be obvious from the above; * It is necessary to implement the @c Manufacturer and the @c Suppliers * templates (and possibly also the @c SourceTraits) and then use either the * @c mirror::factory template directly or the @c mirror::factory_maker 's factory * nested template to create an instantiation of a factory constructing instances * of a @c Product type: * * @code * // use the factory directly ... * mirror::factory<my_manuf, my_suppl, my_traits, my_product_1> f1; * my_product_1 x1(f1()); * my_product_1* px1(f1.new_()); * * // ... * // or use the factory_maker * typedef mirror::factory_maker<my_manuf, my_suppl, my_traits> my_fact_maker; * my_fact_maker::factory<my_product_1>::type f1; * my_fact_maker::factory<my_product_2>::type f2; * my_fact_maker::factory<my_product_3>::type f2; * // * my_product_1 x1(f1()); * my_product_1* px1(f1.new_()); * my_product_2 x2(f2()); * my_product_3* px3(f3.new_()); * @endcode * * @subsection mirror_factory_generator_tutorials Tutorials and other resources * * Here follows a list of references to other pages dealing with the factory * generator utility in depth and also tutorials showing how to write * the plugins (the Managers, Manufacturers and Suppliers) for the factory * generator: * * - @subpage mirror_fact_gen_in_depth * - @subpage mirror_sql_fact_gen_tutorial * * @section mirror_factory_generator_existing_templates Existing Manufacturers and Suppliers * * The Mirror library provides several working sample implementations * of the @c Manufacturer and @c Suppliers templates. * The following example shows the usage of the @c wx_gui_factory template * with the factory generator utility in a simple wxWidgets-based application. * The generated factory creates a wxDialog containing all necessary widgets * for the selection of the constructor to be used and for the input of all * parameters required by the selected constructor. Screenshots of dialogs * generated by this implementation can be found * @link mirror_wx_gui_fact_examples here@endlink. */ MIRROR_NAMESPACE_END #endif // DOCUMENTATION_ONLY #endif //include guard
firestarter/firestarter
redist/mirror-lib/mirror/doc/factory_generator.hpp
C++
gpl-3.0
12,717
#sidebar { display: none; } #sidebar * { border-radius: 0 !important; } #sidebar > nav { background-color: #222222; } @media (min-width: 768px) { #sidebar { position: fixed; top: 0; bottom: 0; left: 0; z-index: 1000; display: block; padding: 0; overflow-x: hidden; overflow-y: auto; background-color: #222222; border-right: 1px solid #111111; } } li.brand {background-color: #000;} .brand a.brand { padding: 0; width: 100%; height: 50px; margin: 0; display: block; background-image: url(../img/logo-light.png); background-position: center; background-size: 90%; background-repeat: no-repeat; } #sidebar .nav.nav-sidebar { border-bottom: 1px solid #ccc; } #sidebar .nav.nav-sidebar:last-child { border-bottom: 0; } #sidebar ul, #sidebar li, #sidebar li a { display: block; width: 100%; } #sidebar a.gradient > i { width: 24px; font-size: 16px; text-align: left; } #sidebar a.gradient { border-right: 5px solid transparent; } #sidebar a.gradient:hover, #sidebar a.gradient:active, #sidebar a.gradient:focus { border-right: 5px solid #00BCD4; } #sidebar li.active a.gradient, #sidebar a.gradient.active { border-right: 5px solid #ff0000; } #sidebar li.dropdown ul li.normal.by-0:not(:last-child) { border-bottom: 1px solid #3e3e3e !important; } .child-bg { background-color: #111; } #sidebar li.dropdown a span.caret { position: absolute; right: 15px; top: calc(50% - 1px); } #sidebar .activated { border-left: 3px solid #f43000; } #sidebar li.dropdown ul li a { padding-top: 8px; padding-bottom: 8px; } #sidebar li.dropdown ul li a:hover, #sidebar li.dropdown ul li a:active, #sidebar li.dropdown ul li a:focus { color: #848484; background-color: #0d0d0d; }
jmmendozamix/reelance
public/static-v5/css/sidebar.css
CSS
gpl-3.0
1,711
namespace GemsCraft.Entities.Metadata.Flags { public enum TameableFlags: byte { IsSitting = 0x01, /// <summary> /// Only used with wolves /// </summary> IsAngry = 0x02, IsTamed = 0x04 } }
apotter96/GemsCraft
GemsCraft/Entities/Metadata/Flags/TameableFlags.cs
C#
gpl-3.0
251
import React from 'react'; import { connect } from 'react-redux'; import { View, Text, FlatList } from 'react-native'; import sb from 'react-native-style-block'; import dateHelper from '@shared/utils/date-helper'; import appConfig from '../config.app'; import ConvItem from '../components/ConvItem'; import { reloadConverseList } from '@shared/redux/actions/chat'; import styled from 'styled-components/native'; import TRefreshControl from '../components/TComponent/TRefreshControl'; import { ChatType } from '../types/params'; import type { TRPGState, TRPGDispatchProp } from '@redux/types/__all__'; import _get from 'lodash/get'; import _values from 'lodash/values'; import _sortBy from 'lodash/sortBy'; import _size from 'lodash/size'; import { TMemo } from '@shared/components/TMemo'; import { useSpring, animated } from 'react-spring/native'; import { useTRPGSelector } from '@shared/hooks/useTRPGSelector'; import { TRPGTabScreenProps } from '@app/router'; import { switchToChatScreen } from '@app/navigate'; const NetworkContainer = styled(animated.View as any)<{ isOnline: boolean; tryReconnect: boolean; }>` position: absolute; top: -26px; left: 0; right: 0; height: 26px; background-color: ${({ isOnline, tryReconnect }) => isOnline ? '#2ecc71' : tryReconnect ? '#f39c12' : '#c0392b'}; color: white; align-items: center; justify-content: center; `; const NetworkText = styled.Text` color: white; `; const NetworkTip: React.FC = TMemo((props) => { const network = useTRPGSelector((state) => state.ui.network); const style = useSpring({ to: { top: network.isOnline ? -26 : 0, }, }); return ( <NetworkContainer style={style} isOnline={network.isOnline} tryReconnect={network.tryReconnect} > <NetworkText>{network.msg}</NetworkText> </NetworkContainer> ); }); NetworkTip.displayName = 'NetworkTip'; interface Props extends TRPGDispatchProp, TRPGTabScreenProps<'TRPG'> { converses: any; conversesDesc: any; groups: any; usercache: any; } class HomeScreen extends React.Component<Props> { state = { isRefreshing: false, }; getList() { if (_size(this.props.converses) > 0) { const arr: any[] = _sortBy( _values(this.props.converses), (item) => new Date(item.lastTime || 0) ) .reverse() .map((item, index) => { const uuid = item.uuid; const defaultIcon = uuid === 'trpgsystem' ? appConfig.defaultImg.trpgsystem : appConfig.defaultImg.user; let avatar: string; if (item.type === 'user') { avatar = _get(this.props.usercache, [uuid, 'avatar']); } else if (item.type === 'group') { const group = this.props.groups.find((g) => g.uuid === uuid); avatar = group ? group.avatar : ''; } return { icon: item.icon || avatar || defaultIcon, title: item.name, content: item.lastMsg, time: item.lastTime ? dateHelper.getShortDiff(item.lastTime) : '', uuid, unread: item.unread, onPress: () => { this.handleSelectConverse(uuid, item.type, item); }, }; }); return ( <FlatList refreshControl={ <TRefreshControl refreshing={this.state.isRefreshing} onRefresh={() => this.handleRefresh()} /> } keyExtractor={(item, index) => item.uuid} data={arr} renderItem={({ item }) => <ConvItem {...item} />} /> ); } else { return <Text style={styles.tipText}>{this.props.conversesDesc}</Text>; } } handleRefresh() { this.setState({ isRefreshing: true }); const timer = setTimeout(() => { this.setState({ isRefreshing: false }); }, 10000); // 10秒后自动取消 this.props.dispatch( reloadConverseList(() => { this.setState({ isRefreshing: false }); clearTimeout(timer); }) ); } handleSelectConverse(uuid: string, type: ChatType, info) { switchToChatScreen( this.props.navigation.dangerouslyGetParent(), uuid, type, info.name ); } render() { return ( <View style={styles.container}> {this.getList()} <NetworkTip /> </View> ); } } const styles = { container: [sb.flex()], tipText: [sb.textAlign('center'), sb.margin(80, 0, 0, 0), sb.color('#999')], }; export default connect((state: TRPGState) => ({ converses: state.chat.converses, conversesDesc: state.chat.conversesDesc, groups: state.group.groups, usercache: state.cache.user, }))(HomeScreen);
TRPGEngine/Client
src/app/src/screens/HomeScreen.tsx
TypeScript
gpl-3.0
4,755
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.4927 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ public partial class CMSModules_Groups_Tools_Polls_Polls_New { /// <summary> /// PollNew control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::CMSModules_Polls_Controls_PollNew PollNew; }
CCChapel/ccchapel.com
CMS/CMSModules/Groups/Tools/Polls/Polls_New.aspx.designer.cs
C#
gpl-3.0
746
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class ReadSavedData { public static void StartRead() throws IOException { FileReader file = new FileReader("C:/Users/Public/Documents/SavedData.txt"); BufferedReader reader = new BufferedReader(file); String text = ""; String line = reader.readLine(); while (line != null) { text += line; line = reader.readLine(); } reader.close(); System.out.println(text); } }
uSirPatrick/IPCalcGUI
IPCalc2/src/ReadSavedData.java
Java
gpl-3.0
556
enum MessageType { TYPE_CHAT_MESSAGE = 2000 }; enum PropertyType { PR_CHAT_NICK = 3000, PR_CHAT_TEXT };
ropez/pieces
src/examples/qchat/global.h
C
gpl-3.0
121
.block { background:yellow; /*max-height:50px;*/ border:5px; border-color:red; max-width:300px; -moz-border-radius: 15px; padding-left:5px; padding-right:10px; z-index:11; } .block:not(.block-inlist):last-of-type,.block-inlist{ border-bottom-right-radius: 10px; } .block-instack { list-style-position:inside; position:relative; left:-20px; z-index:11; } .stack { list-style-type:none; list-style-position:inside; padding: 0; padding-bottom:10px; margin-left: 0; position:absolute; background:green; overflow:visible; max-height:100%; /*max-width:500px;*/ min-width:100px; min-height:50px; background:green; z-index:-1; border-radius:5px; } #trash img { max-width:100px; max-height:100px; position:fixed; right:0px; bottom:0px; z-index:-1; } .createStack { background:green; max-height:50px; border:5px; max-width:300px; } .canvas { min-width:100%; min-height:100%; top:0px;left:0px; position:absolute; z-index:5; overflow:auto; } #objects li { border-style:solid; border-width:1px; border-color:orange; } custom-menu { list-style-type:none; list-style-position:inside; z-index:99; background:white; border-style:solid; border-width:1px; border-radius:5px; border-color:grey; min-width:100px; padding-left:-5px; margin-left:0px; font-size:14px; padding-right:500px; } custom-menu li, cmenu-item { width:100%; border-width:1px; border-color:white; border-style:solid; border-top-color:black; border-left-color:black; font-size:14px; position:relative; left:-3px; top:-3px; padding:0px; margin:0px; padding-right:5px; } custom-menu li:last-child, custom-menu cmenu-item:last-child { border-bottom-left-radius:5px; border-bottom-right-radius:5px; margin-bottom:-6px; border-bottom-color:grey; } custom-menu li:first-child, custom-menu cmenu-item:first-child { border-top-left-radius:5px; border-top-right-radius:5px; } custom-menu li:hover, custom-menu cmenu-item:hover { border-color:black; border-radius:5px; } cmenu-item { display:list-item; } .block-type-variable { background-color:#F000FC; } .data { border-radius:10px; background-color:#00FFFF; padding-left:5px; } .block-type-camera, .camera { background-color:#FF0040; } #webcam-ask { z-index: 1000; } #webcam-hide { opacity:0.0; filter:alpha(opacity=0); } #webcam-dialog { background-color:#DDDDDD; min-width:100px; min-height:100px; z-index:999; } .hide { z-index:9999; opacity:0; } #window { x-index:9999; opacity:1; width:300px; height:300px; border-width: 1px; border-color: black; border-radius: 5px; }
mailmindlin/teach-oop
main.css
CSS
gpl-3.0
2,561
/************************************************************************** * Karlyriceditor - a lyrics editor and CD+G / video export for Karaoke * * songs. * * Copyright (C) 2009-2013 George Yunaev, [email protected] * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * **************************************************************************/ #ifndef BACKGROUND_H #define BACKGROUND_H #include <QImage> #include "ffmpegvideodecoder.h" class Background { public: Background(); virtual ~Background(); // Actual draw function to implement. Should return time when the next // doDraw() should be called - for example, for videos it should only // be called when it is time to show the next frame; for static images // it should not be called at all. If 0 is returned, doDraw() will be called // again the next update. If -1 is returned, doDraw() will never be called // again, and the cached image will be used. virtual qint64 doDraw( QImage& image, qint64 timing ) = 0; // This function is called if timing went backward (user seek back), in which // case it will be called before doDraw() with a new time. Video players, for // example, may use it to seek back to zero. Default implementation does nothing. virtual void reset(); // Should return true if the event was created successfully virtual bool isValid() const = 0; }; class BackgroundImage : public Background { public: BackgroundImage( const QString& filename ); bool isValid() const; qint64 doDraw( QImage& image, qint64 timing ); private: QImage m_image; }; class BackgroundVideo : public Background { public: BackgroundVideo( const QString& arg ); bool isValid() const; qint64 doDraw( QImage& image, qint64 timing ); private: FFMpegVideoDecoder m_videoDecoder; bool m_valid; }; #endif // BACKGROUND_H
martin-steghoefer/debian-karlyriceditor
src/background.h
C
gpl-3.0
2,808
#!/bin/sh declare -x PATH_TO_SOURCE=`dirname $0`/.. cd $PATH_TO_SOURCE bsc -e "(module-compile-to-standalone \"ensanche-core\" 'main)"
alvatar/caad-research
__scripts/build.sh
Shell
gpl-3.0
137
class ApplicationController < ActionController::Base class ForbiddenException < StandardError; end protect_from_forgery before_filter :set_locale before_filter :authenticate_user! layout :get_layout def set_locale I18n.locale = params[:locale] || I18n.default_locale end def get_layout if !user_signed_in? get_layout = "logged_out" else get_layout = "application" end end def after_sign_out_path_for(resource) new_user_session_path end def administrator_only_access unless user_signed_in? && current_user.admin? raise ApplicationController::ForbiddenException end end end
autohome/autohome-web
app/controllers/application_controller.rb
Ruby
gpl-3.0
650
/** * Copyright 2010 David Froehlich <[email protected]>, * Samuel Kogler <[email protected]>, * Stephan Stiboller <[email protected]> * * This file is part of Codesearch. * * Codesearch is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Codesearch 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 Codesearch. If not, see <http://www.gnu.org/licenses/>. */ package com.uwyn.jhighlight.pcj.hash; /** * This interface represents hash functions from char values * to int values. The int value result is chosen to achieve * consistence with the common * {@link Object#hashCode() hashCode()} * method. The interface is provided to alter the hash functions used * by hashing data structures, like * {@link com.uwyn.rife.pcj.map.CharKeyIntChainedHashMap CharKeyIntChainedHashMap} * or * {@link com.uwyn.rife.pcj.set.CharChainedHashSet CharChainedHashSet}. * * @see DefaultCharHashFunction * * @author S&oslash;ren Bak * @version 1.0 2002/29/12 * @since 1.0 */ public interface CharHashFunction { /** * Returns a hash code for a specified char value. * * @param v * the value for which to return a hash code. * * @return a hash code for the specified value. */ int hash(char v); }
codesearch-github/codesearch
src/custom-libs/Codesearch-JHighlight/src/main/java/com/uwyn/jhighlight/pcj/hash/CharHashFunction.java
Java
gpl-3.0
1,832
using System; using System.Diagnostics; using System.Text; using System.Windows.Forms; using OpenDentBusiness; namespace OpenDental.Eclaims { /// <summary> /// Summary description for BCBSGA. /// </summary> public class BCBSGA{ /// <summary></summary> public static string ErrorMessage=""; public BCBSGA() { } ///<summary>Returns true if the communications were successful, and false if they failed. If they failed, a rollback will happen automatically by deleting the previously created X12 file. The batchnum is supplied for the possible rollback.</summary> public static bool Launch(Clearinghouse clearinghouseClin,int batchNum){ //called from Eclaims.cs. Clinic-level clearinghouse passed in. bool retVal=true; FormTerminal FormT=new FormTerminal(); try{ FormT.Show(); FormT.OpenConnection(clearinghouseClin.ModemPort); //1. Dial FormT.Dial("17065713158"); //2. Wait for connect, then pause 3 seconds FormT.WaitFor("CONNECT 9600",50000); FormT.Pause(3000); FormT.ClearRxBuff(); //3. Send Submitter login record string submitterLogin= //position,length indicated for each "/SLRON"//1,6 /SLRON=Submitter login +FormT.Sout(clearinghouseClin.LoginID,12,12)//7,12 Submitter ID +FormT.Sout(clearinghouseClin.Password,8,8)//19,8 submitter password +"NAT"//27,3 use NAT //30,8 suggested 8-BYTE CRC of the file for unique ID. No spaces. //But I used the batch number instead +batchNum.ToString().PadLeft(8,'0') +"ANSI837D 1 "//38,15 "ANSI837D 1 "=Dental claims +"X"//53,1 X=Xmodem, or Y for transmission protocol +"ANSI"//54,4 use ANSI +"BCS"//58,3 BCS=BlueCrossBlueShield +"00";//61,2 use 00 for filler FormT.Send(submitterLogin); //4. Receive Y, indicating login accepted if(FormT.WaitFor("Y","N",20000)=="Y"){ //5. Wait 1 second. FormT.Pause(1000); } else{ //6. If login rejected, receive an N, //followed by Transmission acknowledgement explaining throw new Exception(FormT.Receive(5000)); } //7. Send file using X-modem or Z-modem //slash not handled properly if missing: FormT.UploadXmodem(clearinghouseClin.ExportPath+"claims"+batchNum.ToString()+".txt"); //8. After transmitting, pause for 1 second. FormT.Pause(1000); FormT.ClearRxBuff(); //9. Send submitter logout record string submitterLogout= "/SLROFF"//1,7 /SLROFF=Submitter logout +FormT.Sout(clearinghouseClin.LoginID,12,12)//8,12 Submitter ID +batchNum.ToString().PadLeft(8,'0')//20,8 matches field in submitter Login +"!"//28,1 use ! to retrieve transmission acknowledgement record +"\r\n"; FormT.Send(submitterLogout); //10. Prepare to receive the Transmission acknowledgement. This is a receipt. FormT.Receive(5000);//this is displayed in the progress box so user can see. } catch(Exception ex){ ErrorMessage=ex.Message; x837Controller.Rollback(clearinghouseClin,batchNum); retVal=false; } finally{ FormT.CloseConnection(); } return retVal; } ///<summary>Retrieves any waiting reports from this clearinghouse. Returns true if the communications were successful, and false if they failed.</summary> public static bool Retrieve(Clearinghouse clearinghouseClin) { //Called from FormClaimReports. Clinic-level Clearinghouse passed in. bool retVal=true; FormTerminal FormT=new FormTerminal(); try{ FormT.Show(); FormT.OpenConnection(clearinghouseClin.ModemPort); FormT.Dial("17065713158"); //2. Wait for connect, then pause 3 seconds FormT.WaitFor("CONNECT 9600",50000); FormT.Pause(3000); FormT.ClearRxBuff(); //1. Send submitter login record string submitterLogin= "/SLRON"//1,6 /SLRON=Submitter login +FormT.Sout(clearinghouseClin.LoginID,12,12)//7,12 Submitter ID +FormT.Sout(clearinghouseClin.Password,8,8)//19,8 submitter password +" "//27,3 use 3 spaces //Possible issue with Trans ID +"12345678"//30,8. they did not explain this field very well in documentation +"* "//38,15 " * "=All available. spacing ok? +"X"//53,1 X=Xmodem, or Y for transmission protocol +"MDD "//54,4 use 'MDD ' +"VND"//58,3 Vendor ID is yet to be assigned by BCBS +"00";//61,2 Software version not important byte response=(byte)'Y'; string retrieveFile=""; while(response==(byte)'Y'){ FormT.ClearRxBuff(); FormT.Send(submitterLogin); response=0; while(response!=(byte)'N' && response!=(byte)'Y' && response!=(byte)'Z') { response=FormT.GetOneByte(20000); FormT.ClearRxBuff(); Application.DoEvents(); } //2. If not accepted, N is returned //3. and must receive transmission acknowledgement if(response==(byte)'N'){ MessageBox.Show(FormT.Receive(10000)); break; } //4. If login accepted, but no records, Z is returned. Hang up. if(response==(byte)'Z'){ MessageBox.Show("No reports to retrieve"); break; } //5. If record(s) available, Y is returned, followed by dos filename and 32 char subj. //less than one second since all text is supposed to immediately follow the Y retrieveFile=FormT.Receive(800).Substring(0,12);//12 char in dos filename FormT.ClearRxBuff(); //6. Pause for 1 second. (already mostly handled); FormT.Pause(200); //7. Receive file using Xmodem //path must include trailing slash for now. FormT.DownloadXmodem(clearinghouseClin.ResponsePath+retrieveFile); //8. Pause for 5 seconds. FormT.Pause(5000); //9. Repeat all steps including login until a Z is returned. } } catch(Exception ex){ ErrorMessage=ex.Message; //FormT.Close();//Also closes connection retVal=false; } finally{ FormT.CloseConnection(); } return retVal; } } }
eae/opendental
OpenDental/Eclaims/BCBSGA.cs
C#
gpl-3.0
5,973
-- -- Copyright (c) 1997-2013, www.tinygroup.org ([email protected]). -- -- Licensed under the GPL, Version 3.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.gnu.org/licenses/gpl.html -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- select * from dual t1, dual t2 join dual t3 using(dummy) left outer join dual t4 using(dummy) left outer join dual t5 using(dummy)
TinyGroup/tiny
db/org.tinygroup.jsqlparser/src/test/resources/org/tinygroup/jsqlparser/test/oracle-tests/join16.sql
SQL
gpl-3.0
771
/** ****************************************************************************** * @file I2C/I2C_TwoBoards_ComPolling/Src/stm32f4xx_it.c * @author MCD Application Team * @version V1.2.7 * @date 17-February-2017 * @brief Main Interrupt Service Routines. * This file provides template for all exceptions handler and * peripherals interrupt service routine. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "stm32f4xx_it.h" /** @addtogroup STM32F4xx_HAL_Examples * @{ */ /** @addtogroup I2C_TwoBoards_ComPolling * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* I2C handler declared in "main.c" file */ extern I2C_HandleTypeDef hi2c; /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /******************************************************************************/ /* Cortex-M4 Processor Exceptions Handlers */ /******************************************************************************/ /** * @brief This function handles NMI exception. * @param None * @retval None */ void NMI_Handler(void) { } /** * @brief This function handles Hard Fault exception. * @param None * @retval None */ void HardFault_Handler(void) { /* Go to infinite loop when Hard Fault exception occurs */ while (1) { } } /** * @brief This function handles Memory Manage exception. * @param None * @retval None */ void MemManage_Handler(void) { /* Go to infinite loop when Memory Manage exception occurs */ while (1) { } } /** * @brief This function handles Bus Fault exception. * @param None * @retval None */ void BusFault_Handler(void) { /* Go to infinite loop when Bus Fault exception occurs */ while (1) { } } /** * @brief This function handles Usage Fault exception. * @param None * @retval None */ void UsageFault_Handler(void) { /* Go to infinite loop when Usage Fault exception occurs */ while (1) { } } /** * @brief This function handles SVCall exception. * @param None * @retval None */ void SVC_Handler(void) { } /** * @brief This function handles Debug Monitor exception. * @param None * @retval None */ void DebugMon_Handler(void) { } /** * @brief This function handles PendSVC exception. * @param None * @retval None */ void PendSV_Handler(void) { } /** * @brief This function handles SysTick Handler. * @param None * @retval None */ void SysTick_Handler(void) { HAL_IncTick(); } /******************************************************************************/ /* STM32F4xx Peripherals Interrupt Handlers */ /* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */ /* available peripheral interrupt handler's name please refer to the startup */ /* file (startup_stm32f4xx.s). */ /******************************************************************************/ /** * @brief This function handles PPP interrupt request. * @param None * @retval None */ /*void PPP_IRQHandler(void) { }*/ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
TRothfelder/Multicopter
libs/STM32Cube_FW_F4_V1.16.0/Projects/STM32F4-Discovery/Examples/I2C/I2C_TwoBoards_ComPolling/Src/stm32f4xx_it.c
C
gpl-3.0
5,686
all: ocp-build init ocp-build opam-deps: opam install ocp-build
OCamlPro/Dessiner
Makefile
Makefile
gpl-3.0
68
#include "inventorypage.h" #include "ui_inventorypage.h" #include "fak.h" #include "inventorypage.h" #include <QtDebug> #include "QtDebug" #include <QSqlQuery> #include <QSqlError> #include <QSqlRecord> static const QString path = "C:/Sr.GUI/FAKKIT/db/fakdb4.db"; InventoryPage::InventoryPage(QWidget *parent) : QDialog(parent), ui(new Ui::InventoryPage) { ui->setupUi(this); this->setStyleSheet("background-color:#626065;"); DbManager db(path); qDebug() << "Stuff in db:"; QSqlQuery query; query.exec("SELECT * FROM codes"); int idName = query.record().indexOf("name"); while (query.next()) { QString name = query.value(idName).toString(); qDebug() << "===" << name; //ui->dbOutput->setPlainText(name); ui->dbOutput->append(name); } } DbManager::DbManager(const QString &path) { m_db = QSqlDatabase::addDatabase("QSQLITE"); m_db.setDatabaseName(path); if (!m_db.open()) { qDebug() << "Error: connection with database fail"; } else { qDebug() << "Database: connection ok"; } } InventoryPage::~InventoryPage() { delete ui; } void InventoryPage::on_HomeButton_clicked() { }
r0ug3-Mary/Sr.GUI
FAKKITpics/inventorypage.cpp
C++
gpl-3.0
1,227
var gulp = require('gulp'); var browserSync = require('browser-sync'); var jshint = require('gulp-jshint'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); // 静态服务器 gulp.task('browser-sync', function() { browserSync.init({ files: "src/**", server: { baseDir: "src/" } }); }); // js语法检查 gulp.task('jshint', function() { return gulp.src('src/js/*.js') .on('error') .pipe(jshint()) .pipe(jshint.reporter('default')); }); // js文件合并及压缩 gulp.task('minifyjs', function() { return gulp.src('src/js/*.js') .pipe(concat('all.js')) .pipe(gulp.dest('dist/js')) .pipe(uglify()) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('dist/js')); }); // 事件监听 gulp.task('watch', function() { gulp.watch('src/js/*.js', ['jshint','minifyjs']); }); gulp.task('default',['browser-sync','watch']);
bdSpring/zhou-task02
26/gulpfile.js
JavaScript
gpl-3.0
946
#ifndef __CLOCK_ROM_H__ #define __CLOCK_ROM_H__ #define ROM_ALARM0_DAY_MASK 0 #define ROM_ALARM0_HOUR 1 #define ROM_ALARM0_MIN 2 #define ROM_ALARM0_DUR 3 #define ROM_ALARM1_ENABLE 4 #define ROM_TIME_IS12 10 #define ROM_BEEPER_MUSIC_INDEX 11 #define ROM_BEEPER_ENABLE 12 #define ROM_POWERSAVE_TO 13 #define ROM_REMOTE_ONOFF 14 #define ROM_AUTO_LIGHT_ONOFF 15 #define ROM_FUSE_HG_ONOFF 20 #define ROM_FUSE_MPU 21 #define ROM_FUSE_THERMO_HI 22 #define ROM_FUSE_THERMO_LO 23 #define ROM_FUSE_REMOTE_ONOFF 24 #define ROM_FUSE_PASSWORD 25 // 6字节是password #define ROM_LT_TIMER_YEAR 40 #define ROM_LT_TIMER_MONTH 41 #define ROM_LT_TIMER_DATE 42 #define ROM_LT_TIMER_HOUR 43 #define ROM_LT_TIMER_MIN 44 #define ROM_LT_TIMER_SEC 45 #define ROM_RADIO_FREQ_HI 50 #define ROM_RADIO_FREQ_LO 51 #define ROM_RADIO_VOLUME 52 #define ROM_RADIO_HLSI 53 #define ROM_RADIO_MS 54 #define ROM_RADIO_BL 55 #define ROM_RADIO_HCC 56 #define ROM_RADIO_SNC 57 #define ROM_RADIO_DTC 58 unsigned char rom_read(unsigned char addr); void rom_write(unsigned char addr, unsigned char val); void rom_initialize(void); bit rom_is_factory_reset(void); #endif
sTeeLM/clock
src/rom.h
C
gpl-3.0
1,192
/* Copyright (C) 2010 Erik Hjortsberg <[email protected]> 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef SERIALTASK_H_ #define SERIALTASK_H_ #include "TemplateNamedTask.h" #include <vector> namespace Ember { namespace Tasks { /** * @author Erik Hjortsberg <[email protected]> * @brief A task which wraps two or more other tasks, which will be executed in order. * This is useful if you want to make sure that a certain task is executed after another task. */ class SerialTask: public TemplateNamedTask<SerialTask> { public: typedef std::vector<ITask*> TaskStore; /** * @brief Ctor. * @param subTasks The tasks to execute, in order. */ SerialTask(const TaskStore& subTasks); /** * @brief Ctor. * This is a convenience constructor which allows you to specify the tasks directly without having to first create a vector instance. * @param firstTask The first task to execute. * @param secondTask The second task to execute. * @param thirdTask The third task to execute. * @param firstTask The fourth task to execute. */ SerialTask(ITask* firstTask, ITask* secondTask, ITask* thirdTask = 0, ITask* fourthTask = 0); virtual ~SerialTask(); virtual void executeTaskInBackgroundThread(TaskExecutionContext& context); private: TaskStore mSubTasks; }; } } #endif /* SERIALTASK_H_ */
junrw/ember-gsoc2012
src/framework/tasks/SerialTask.h
C
gpl-3.0
1,988
\hypertarget{_coloring_8java}{}\doxysection{src/ch/innovazion/arionide/menu/structure/\+Coloring.java File Reference} \label{_coloring_8java}\index{src/ch/innovazion/arionide/menu/structure/Coloring.java@{src/ch/innovazion/arionide/menu/structure/Coloring.java}} \doxysubsection*{Classes} \begin{DoxyCompactItemize} \item class \mbox{\hyperlink{classch_1_1innovazion_1_1arionide_1_1menu_1_1structure_1_1_coloring}{ch.\+innovazion.\+arionide.\+menu.\+structure.\+Coloring}} \end{DoxyCompactItemize} \doxysubsection*{Packages} \begin{DoxyCompactItemize} \item package \mbox{\hyperlink{namespacech_1_1innovazion_1_1arionide_1_1menu_1_1structure}{ch.\+innovazion.\+arionide.\+menu.\+structure}} \end{DoxyCompactItemize}
thedreamer979/Arionide
doc/latex/_coloring_8java.tex
TeX
gpl-3.0
718
/*****************************************************************/ /* Source Of Evil Engine */ /* */ /* Copyright (C) 2000-2001 Andreas Zahnleiter GreenByte Studios */ /* */ /*****************************************************************/ /* Dynamic object list */ class C4ObjectLink { public: C4Object *Obj; C4ObjectLink *Prev,*Next; }; class C4ObjectList { public: C4ObjectList(); ~C4ObjectList(); public: C4ObjectLink *First,*Last; int Mass; char *szEnumerated; public: void SortByCategory(); void Default(); void Clear(); void Sort(); void Enumerate(); void Denumerate(); void Copy(C4ObjectList &rList); void Draw(C4FacetEx &cgo); void DrawList(C4Facet &cgo, int iSelection=-1, DWORD dwCategory=C4D_All); void DrawIDList(C4Facet &cgo, int iSelection, C4DefList &rDefs, DWORD dwCategory, C4RegionList *pRegions=NULL, int iRegionCom=COM_None, BOOL fDrawOneCounts=TRUE); void DrawSelectMark(C4FacetEx &cgo); void CloseMenus(); void UpdateFaces(); void SyncClearance(); void ResetAudibility(); void UpdateTransferZones(); void SetOCF(); void GetIDList(C4IDList &rList, DWORD dwCategory=C4D_All); void ClearInfo(C4ObjectInfo *pInfo); void PutSolidMasks(); void RemoveSolidMasks(BOOL fCauseInstability=TRUE); BOOL Add(C4Object *nObj, BOOL fSorted=TRUE); BOOL Remove(C4Object *pObj); BOOL Save(const char *szFilename, BOOL fSaveGame); BOOL Save(C4Group &hGroup, BOOL fSaveGame); BOOL AssignInfo(); BOOL ValidateOwners(); BOOL WriteNameList(char *szTarget, C4DefList &rDefs, DWORD dwCategory=C4D_All); BOOL IsClear(); BOOL ReadEnumerated(const char *szSource); BOOL DenumerateRead(); BOOL Write(char *szTarget); int Load(C4Group &hGroup); int ObjectNumber(C4Object *pObj); int ClearPointers(C4Object *pObj); int ObjectCount(C4ID id=C4ID_None, DWORD dwCategory=C4D_All); int MassCount(); int ListIDCount(DWORD dwCategory); C4Object* Denumerated(C4Object *pObj); C4Object* Enumerated(C4Object *pObj); C4Object* ObjectPointer(int iNumber); C4Object* GetObject(int Index=0); C4Object* Find(C4ID id, int iOwner=ANY_OWNER); C4Object* FindOther(C4ID id, int iOwner=ANY_OWNER); C4ObjectLink* GetLink(C4Object *pObj); C4ID GetListID(DWORD dwCategory, int Index); protected: void InsertLink(C4ObjectLink *pLink, C4ObjectLink *pAfter); void RemoveLink(C4ObjectLink *pLnk); };
MrCerealGuy/Source-Of-Evil
SoE Engine/inc/C4ObjectList.h
C
gpl-3.0
2,628
using UnityEngine; using System.Collections; public class TimeScaleManager : MonoBehaviour { public static TimeScaleManager instance; public delegate void OnTimeScaleChangeCallback(); public event OnTimeScaleChangeCallback TimeScaleChange; public bool isPlaying; public bool IsPaused { get { return !isPlaying; } } public enum TimeScale{ ONE, TWO, THREE } public TimeScale timeScale; void Awake(){ instance = this; timeScale = TimeScale.ONE; Time.timeScale = 0f; isPlaying = false; } public void SelectNextTimeScale(){ switch(timeScale){ case TimeScale.ONE: timeScale = TimeScale.TWO; if (isPlaying) { Time.timeScale = 2f; } if (TimeScaleChange != null){ TimeScaleChange(); } break; case TimeScale.TWO: timeScale = TimeScale.THREE; if (isPlaying) { Time.timeScale = 3f; } if (TimeScaleChange != null){ TimeScaleChange(); } break; case TimeScale.THREE: timeScale = TimeScale.ONE; if (isPlaying) { Time.timeScale = 1f; } if (TimeScaleChange != null){ TimeScaleChange(); } break; } } public string GetCurrentTimeScaleLabel(){ switch(timeScale){ case TimeScale.ONE: return "1"; case TimeScale.TWO: return "2"; case TimeScale.THREE: return "3"; default: return "error"; } } }
Michael-Dawkins/GeometricDefense
Assets/Scripts/Services/TimeScaleManager.cs
C#
gpl-3.0
1,551
#ifndef __ASSIGN_SPRITES_H #define __ASSIGN_SPRITES_H void AssignSprites(void); #endif
isage/nxengine-evo
src/autogen/AssignSprites.h
C
gpl-3.0
87
# Dockerfile "Big" Intended for a big webapplications which expects the following tools: - texlive (pdflatex)
GeraldWodni/kern.js
docker/big/ReadMe.md
Markdown
gpl-3.0
110
package org.amse.marinaSokol.model.interfaces.object.net; public interface IActivationFunctor { /** * Ôóíêöèÿ àêòèâàöèè * @param x - ÷èñëî, ïîäàííîå íà ôóíêöèþ àêòèâàöèè * @return âûõîä íåéðîíà * */ double getFunction(double x); /** * ïðîèçâîäíàÿ ôóíêöèè àêòèâàöèè * @param x - ÷èñëî, ïîäàííîå íà ôóíêöèþ * @return âûõîä * */ double getDerivation(double x); /** * Èìÿ ôóíêöèè àêòèâàöèè * @return èìÿ ôóíêöèè àêòèâàöèè * */ String getNameFunction(); }
sokolm/NeuroNet
src/org/amse/marinaSokol/model/interfaces/object/net/IActivationFunctor.java
Java
gpl-3.0
558
/* SPDX-FileCopyrightText: 2007 Jean-Baptiste Mardelle <[email protected]> SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL */ #include "definitions.h" #include <klocalizedstring.h> #include <QColor> #include <utility> #ifdef CRASH_AUTO_TEST #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wsign-conversion" #pragma GCC diagnostic ignored "-Wfloat-equal" #pragma GCC diagnostic ignored "-Wshadow" #pragma GCC diagnostic ignored "-Wpedantic" #include <rttr/registration> #pragma GCC diagnostic pop RTTR_REGISTRATION { using namespace rttr; // clang-format off registration::enumeration<GroupType>("GroupType")( value("Normal", GroupType::Normal), value("Selection", GroupType::Selection), value("AVSplit", GroupType::AVSplit), value("Leaf", GroupType::Leaf) ); registration::enumeration<PlaylistState::ClipState>("PlaylistState")( value("VideoOnly", PlaylistState::VideoOnly), value("AudioOnly", PlaylistState::AudioOnly), value("Disabled", PlaylistState::Disabled) ); // clang-format on } #endif QDebug operator<<(QDebug qd, const ItemInfo &info) { qd << "ItemInfo " << &info; qd << "\tTrack" << info.track; qd << "\tStart pos: " << info.startPos.toString(); qd << "\tEnd pos: " << info.endPos.toString(); qd << "\tCrop start: " << info.cropStart.toString(); qd << "\tCrop duration: " << info.cropDuration.toString(); return qd.maybeSpace(); } CommentedTime::CommentedTime() : m_time(GenTime(0)) { } CommentedTime::CommentedTime(const GenTime &time, QString comment, int markerType) : m_time(time) , m_comment(std::move(comment)) , m_type(markerType) { } CommentedTime::CommentedTime(const QString &hash, const GenTime &time) : m_time(time) , m_comment(hash.section(QLatin1Char(':'), 1)) , m_type(hash.section(QLatin1Char(':'), 0, 0).toInt()) { } QString CommentedTime::comment() const { return (m_comment.isEmpty() ? i18n("Marker") : m_comment); } GenTime CommentedTime::time() const { return m_time; } void CommentedTime::setComment(const QString &comm) { m_comment = comm; } void CommentedTime::setTime(const GenTime &t) { m_time = t; } void CommentedTime::setMarkerType(int newtype) { m_type = newtype; } QString CommentedTime::hash() const { return QString::number(m_type) + QLatin1Char(':') + (m_comment.isEmpty() ? i18n("Marker") : m_comment); } int CommentedTime::markerType() const { return m_type; } bool CommentedTime::operator>(const CommentedTime &op) const { return m_time > op.time(); } bool CommentedTime::operator<(const CommentedTime &op) const { return m_time < op.time(); } bool CommentedTime::operator>=(const CommentedTime &op) const { return m_time >= op.time(); } bool CommentedTime::operator<=(const CommentedTime &op) const { return m_time <= op.time(); } bool CommentedTime::operator==(const CommentedTime &op) const { return m_time == op.time(); } bool CommentedTime::operator!=(const CommentedTime &op) const { return m_time != op.time(); } const QString groupTypeToStr(GroupType t) { switch (t) { case GroupType::Normal: return QStringLiteral("Normal"); case GroupType::Selection: return QStringLiteral("Selection"); case GroupType::AVSplit: return QStringLiteral("AVSplit"); case GroupType::Leaf: return QStringLiteral("Leaf"); } Q_ASSERT(false); return QString(); } GroupType groupTypeFromStr(const QString &s) { std::vector<GroupType> types{GroupType::Selection, GroupType::Normal, GroupType::AVSplit, GroupType::Leaf}; for (const auto &t : types) { if (s == groupTypeToStr(t)) { return t; } } Q_ASSERT(false); return GroupType::Normal; } std::pair<bool, bool> stateToBool(PlaylistState::ClipState state) { return {state == PlaylistState::VideoOnly, state == PlaylistState::AudioOnly}; } PlaylistState::ClipState stateFromBool(std::pair<bool, bool> av) { Q_ASSERT(!av.first || !av.second); if (av.first) { return PlaylistState::VideoOnly; } else if (av.second) { return PlaylistState::AudioOnly; } else { return PlaylistState::Disabled; } } SubtitledTime::SubtitledTime() : m_starttime(0) , m_endtime(0) { } SubtitledTime::SubtitledTime(const GenTime &start, QString sub, const GenTime &end) : m_starttime(start) , m_subtitle(std::move(sub)) , m_endtime(end) { } QString SubtitledTime::subtitle() const { return m_subtitle; } GenTime SubtitledTime::start() const { return m_starttime; } GenTime SubtitledTime::end() const { return m_endtime; } void SubtitledTime::setSubtitle(const QString& sub) { m_subtitle = sub; } void SubtitledTime::setEndTime(const GenTime& end) { m_endtime = end; } bool SubtitledTime::operator>(const SubtitledTime& op) const { return(m_starttime > op.m_starttime && m_endtime > op.m_endtime && m_starttime > op.m_endtime); } bool SubtitledTime::operator<(const SubtitledTime& op) const { return(m_starttime < op.m_starttime && m_endtime < op.m_endtime && m_endtime < op.m_starttime); } bool SubtitledTime::operator==(const SubtitledTime& op) const { return(m_starttime == op.m_starttime && m_endtime == op.m_endtime); } bool SubtitledTime::operator!=(const SubtitledTime& op) const { return(m_starttime != op.m_starttime && m_endtime != op.m_endtime); }
KDE/kdenlive
src/definitions.cpp
C++
gpl-3.0
5,551
// ------------------------------------------------------------------------------------------ // Licensed by Interprise Solutions. // http://www.InterpriseSolutions.com // For details on this license please visit the product homepage at the URL above. // THE ABOVE NOTICE MUST REMAIN INTACT. // ------------------------------------------------------------------------------------------ using System; using InterpriseSuiteEcommerceCommon; using InterpriseSuiteEcommerceCommon.InterpriseIntegration; namespace InterpriseSuiteEcommerce { /// <summary> /// Summary description for tableorder_process. /// </summary> public partial class tableorder_process : System.Web.UI.Page { protected void Page_Load(object sender, System.EventArgs e) { Response.CacheControl = "private"; Response.Expires = 0; Response.AddHeader("pragma", "no-cache"); Customer ThisCustomer = ((InterpriseSuiteEcommercePrincipal)Context.User).ThisCustomer; ThisCustomer.RequireCustomerRecord(); InterpriseShoppingCart cart = new InterpriseShoppingCart(null, 1, ThisCustomer, CartTypeEnum.ShoppingCart, String.Empty, false,true); bool redirectToWishList = false; foreach (string key in Request.Form.AllKeys) { try { if (!key.StartsWith("ProductID")) { continue; } // retrieve the item counter // This may look obvious 4 but we want to make it expressive string itemCounterValue = Request.Form[key]; string quantityOrderedValue = Request.Form["Quantity"]; if (string.IsNullOrEmpty(quantityOrderedValue)) { quantityOrderedValue = Request.Form["Quantity_" + itemCounterValue]; if (!string.IsNullOrEmpty(quantityOrderedValue)) { quantityOrderedValue = quantityOrderedValue.Split(',')[0]; } } int counter = 0; int quantityOrdered = 0; if (!string.IsNullOrEmpty(itemCounterValue) && int.TryParse(itemCounterValue, out counter) && !string.IsNullOrEmpty(quantityOrderedValue) && int.TryParse(quantityOrderedValue, out quantityOrdered) && quantityOrdered > 0) { string unitMeasureFieldKey = "UnitMeasureCode_" + counter.ToString(); bool useDefaultUnitMeasure = string.IsNullOrEmpty(Request.Form[unitMeasureFieldKey]); string isWishListFieldKey = "IsWishList_" + counter.ToString(); bool isWishList = !string.IsNullOrEmpty(Request.Form[isWishListFieldKey]); redirectToWishList = isWishList; // we've got a valid counter string itemCode = string.Empty; using (var con = DB.NewSqlConnection()) { con.Open(); using (var reader = DB.GetRSFormat(con, "SELECT ItemCode FROM InventoryItem with (NOLOCK) WHERE Counter = {0}", counter)) { if (reader.Read()) { itemCode = DB.RSField(reader, "ItemCode"); } } } if(!string.IsNullOrEmpty(itemCode)) { UnitMeasureInfo? umInfo = null; if(!useDefaultUnitMeasure) { umInfo = InterpriseHelper.GetItemUnitMeasure(itemCode, Request.Form[unitMeasureFieldKey]); } if(null == umInfo && useDefaultUnitMeasure) { umInfo = InterpriseHelper.GetItemDefaultUnitMeasure(itemCode); } if (null != umInfo && umInfo.HasValue) { if (isWishList) { cart.CartType = CartTypeEnum.WishCart; } cart.AddItem(ThisCustomer, ThisCustomer.PrimaryShippingAddressID, itemCode, counter, quantityOrdered, umInfo.Value.Code, CartTypeEnum.ShoppingCart); //, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, CartTypeEnum.ShoppingCart, false, false, string.Empty, decimal.Zero); } } } } catch { // do nothing, add the items that we can } } if (redirectToWishList) { Response.Redirect("WishList.aspx"); } else { Response.Redirect("ShoppingCart.aspx?add=true"); } } } }
bhassett/Expressions-CB13
tableorder_process.aspx.cs
C#
gpl-3.0
5,729
<?php /** * WooCommerce Admin Webhooks Class * * @author WooThemes * @category Admin * @package WooCommerce/Admin * @version 2.4.0 */ if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * WC_Admin_Webhooks. */ class WC_Admin_Webhooks { /** * Initialize the webhooks admin actions. */ public function __construct() { add_action( 'admin_init', array( $this, 'actions' ) ); } /** * Check if is webhook settings page. * * @return bool */ private function is_webhook_settings_page() { return isset( $_GET['page'] ) && 'wc-settings' == $_GET['page'] && isset( $_GET['tab'] ) && 'api' == $_GET['tab'] && isset( $_GET['section'] ) && 'webhooks' == isset( $_GET['section'] ); } /** * Updated the Webhook name. * * @param int $webhook_id */ private function update_name( $webhook_id ) { global $wpdb; // @codingStandardsIgnoreStart $name = ! empty( $_POST['webhook_name'] ) ? $_POST['webhook_name'] : sprintf( __( 'Webhook created on %s', 'woocommerce' ), strftime( _x( '%b %d, %Y @ %I:%M %p', 'Webhook created on date parsed by strftime', 'woocommerce' ) ) ); // @codingStandardsIgnoreEnd $wpdb->update( $wpdb->posts, array( 'post_title' => $name ), array( 'ID' => $webhook_id ) ); } /** * Updated the Webhook status. * * @param WC_Webhook $webhook */ private function update_status( $webhook ) { $status = ! empty( $_POST['webhook_status'] ) ? wc_clean( $_POST['webhook_status'] ) : ''; $webhook->update_status( $status ); } /** * Updated the Webhook delivery URL. * * @param WC_Webhook $webhook */ private function update_delivery_url( $webhook ) { $delivery_url = ! empty( $_POST['webhook_delivery_url'] ) ? $_POST['webhook_delivery_url'] : ''; if ( wc_is_valid_url( $delivery_url ) ) { $webhook->set_delivery_url( $delivery_url ); } } /** * Updated the Webhook secret. * * @param WC_Webhook $webhook */ private function update_secret( $webhook ) { $secret = ! empty( $_POST['webhook_secret'] ) ? $_POST['webhook_secret'] : wp_generate_password( 50, true, true ); $webhook->set_secret( $secret ); } /** * Updated the Webhook topic. * * @param WC_Webhook $webhook */ private function update_topic( $webhook ) { if ( ! empty( $_POST['webhook_topic'] ) ) { $resource = ''; $event = ''; switch ( $_POST['webhook_topic'] ) { case 'custom' : if ( ! empty( $_POST['webhook_custom_topic'] ) ) { list( $resource, $event ) = explode( '.', wc_clean( $_POST['webhook_custom_topic'] ) ); } break; case 'action' : $resource = 'action'; $event = ! empty( $_POST['webhook_action_event'] ) ? wc_clean( $_POST['webhook_action_event'] ) : ''; break; default : list( $resource, $event ) = explode( '.', wc_clean( $_POST['webhook_topic'] ) ); break; } $topic = $resource . '.' . $event; if ( wc_is_webhook_valid_topic( $topic ) ) { $webhook->set_topic( $topic ); } } } /** * Save method. */ private function save() { if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'woocommerce-settings' ) ) { wp_die( __( 'Action failed. Please refresh the page and retry.', 'woocommerce' ) ); } $webhook_id = absint( $_POST['webhook_id'] ); if ( ! current_user_can( 'edit_shop_webhook', $webhook_id ) ) { return; } $webhook = new WC_Webhook( $webhook_id ); // Name $this->update_name( $webhook->id ); // Status $this->update_status( $webhook ); // Delivery URL $this->update_delivery_url( $webhook ); // Secret $this->update_secret( $webhook ); // Topic $this->update_topic( $webhook ); // Update date. wp_update_post( array( 'ID' => $webhook->id, 'post_modified' => current_time( 'mysql' ) ) ); // Run actions do_action( 'woocommerce_webhook_options_save', $webhook->id ); delete_transient( 'woocommerce_webhook_ids' ); // Ping the webhook at the first time that is activated $pending_delivery = get_post_meta( $webhook->id, '_webhook_pending_delivery', true ); if ( isset( $_POST['webhook_status'] ) && 'active' === $_POST['webhook_status'] && $pending_delivery ) { $result = $webhook->deliver_ping(); if ( is_wp_error( $result ) ) { // Redirect to webhook edit page to avoid settings save actions wp_safe_redirect( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&edit-webhook=' . $webhook->id . '&error=' . urlencode( $result->get_error_message() ) ) ); exit(); } } // Redirect to webhook edit page to avoid settings save actions wp_safe_redirect( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&edit-webhook=' . $webhook->id . '&updated=1' ) ); exit(); } /** * Create Webhook. */ private function create() { if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'create-webhook' ) ) { wp_die( __( 'Action failed. Please refresh the page and retry.', 'woocommerce' ) ); } if ( ! current_user_can( 'publish_shop_webhooks' ) ) { wp_die( __( 'You don\'t have permissions to create Webhooks!', 'woocommerce' ) ); } $webhook_id = wp_insert_post( array( 'post_type' => 'shop_webhook', 'post_status' => 'pending', 'ping_status' => 'closed', 'post_author' => get_current_user_id(), 'post_password' => strlen( ( $password = uniqid( 'webhook_' ) ) ) > 20 ? substr( $password, 0, 20 ) : $password, // @codingStandardsIgnoreStart 'post_title' => sprintf( __( 'Webhook created on %s', 'woocommerce' ), strftime( _x( '%b %d, %Y @ %I:%M %p', 'Webhook created on date parsed by strftime', 'woocommerce' ) ) ), // @codingStandardsIgnoreEnd 'comment_status' => 'open', ) ); if ( is_wp_error( $webhook_id ) ) { wp_die( $webhook_id->get_error_messages() ); } update_post_meta( $webhook_id, '_webhook_pending_delivery', true ); delete_transient( 'woocommerce_webhook_ids' ); // Redirect to edit page wp_redirect( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&edit-webhook=' . $webhook_id . '&created=1' ) ); exit(); } /** * Bulk trash/delete. * * @param array $webhooks * @param bool $delete */ private function bulk_trash( $webhooks, $delete = false ) { foreach ( $webhooks as $webhook_id ) { if ( $delete ) { wp_delete_post( $webhook_id, true ); } else { wp_trash_post( $webhook_id ); } } $type = ! EMPTY_TRASH_DAYS || $delete ? 'deleted' : 'trashed'; $qty = count( $webhooks ); $status = isset( $_GET['status'] ) ? '&status=' . sanitize_text_field( $_GET['status'] ) : ''; delete_transient( 'woocommerce_webhook_ids' ); // Redirect to webhooks page wp_redirect( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks' . $status . '&' . $type . '=' . $qty ) ); exit(); } /** * Bulk untrash. * * @param array $webhooks */ private function bulk_untrash( $webhooks ) { foreach ( $webhooks as $webhook_id ) { wp_untrash_post( $webhook_id ); } $qty = count( $webhooks ); delete_transient( 'woocommerce_webhook_ids' ); // Redirect to webhooks page wp_redirect( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&status=trash&untrashed=' . $qty ) ); exit(); } /** * Bulk actions. */ private function bulk_actions() { if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'woocommerce-settings' ) ) { wp_die( __( 'Action failed. Please refresh the page and retry.', 'woocommerce' ) ); } if ( ! current_user_can( 'edit_shop_webhooks' ) ) { wp_die( __( 'You don\'t have permissions to edit Webhooks!', 'woocommerce' ) ); } $webhooks = array_map( 'absint', (array) $_GET['webhook'] ); switch ( $_GET['action'] ) { case 'trash' : $this->bulk_trash( $webhooks ); break; case 'untrash' : $this->bulk_untrash( $webhooks ); break; case 'delete' : $this->bulk_trash( $webhooks, true ); break; default : break; } } /** * Empty Trash. */ private function empty_trash() { if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'empty_trash' ) ) { wp_die( __( 'Action failed. Please refresh the page and retry.', 'woocommerce' ) ); } if ( ! current_user_can( 'delete_shop_webhooks' ) ) { wp_die( __( 'You don\'t have permissions to delete Webhooks!', 'woocommerce' ) ); } $webhooks = get_posts( array( 'post_type' => 'shop_webhook', 'ignore_sticky_posts' => true, 'nopaging' => true, 'post_status' => 'trash', 'fields' => 'ids', ) ); foreach ( $webhooks as $webhook_id ) { wp_delete_post( $webhook_id, true ); } $qty = count( $webhooks ); // Redirect to webhooks page wp_redirect( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&deleted=' . $qty ) ); exit(); } /** * Webhooks admin actions. */ public function actions() { if ( $this->is_webhook_settings_page() ) { // Save if ( isset( $_POST['save'] ) && isset( $_POST['webhook_id'] ) ) { $this->save(); } // Create if ( isset( $_GET['create-webhook'] ) ) { $this->create(); } // Bulk actions if ( isset( $_GET['action'] ) && isset( $_GET['webhook'] ) ) { $this->bulk_actions(); } // Empty trash if ( isset( $_GET['empty_trash'] ) ) { $this->empty_trash(); } } } /** * Page output. */ public static function page_output() { // Hide the save button $GLOBALS['hide_save_button'] = true; if ( isset( $_GET['edit-webhook'] ) ) { $webhook_id = absint( $_GET['edit-webhook'] ); $webhook = new WC_Webhook( $webhook_id ); if ( 'trash' != $webhook->post_data->post_status ) { include( 'settings/views/html-webhooks-edit.php' ); return; } } self::table_list_output(); } /** * Notices. */ public static function notices() { if ( isset( $_GET['trashed'] ) ) { $trashed = absint( $_GET['trashed'] ); WC_Admin_Settings::add_message( sprintf( _n( '1 webhook moved to the Trash.', '%d webhooks moved to the Trash.', $trashed, 'woocommerce' ), $trashed ) ); } if ( isset( $_GET['untrashed'] ) ) { $untrashed = absint( $_GET['untrashed'] ); WC_Admin_Settings::add_message( sprintf( _n( '1 webhook restored from the Trash.', '%d webhooks restored from the Trash.', $untrashed, 'woocommerce' ), $untrashed ) ); } if ( isset( $_GET['deleted'] ) ) { $deleted = absint( $_GET['deleted'] ); WC_Admin_Settings::add_message( sprintf( _n( '1 webhook permanently deleted.', '%d webhooks permanently deleted.', $deleted, 'woocommerce' ), $deleted ) ); } if ( isset( $_GET['updated'] ) ) { WC_Admin_Settings::add_message( __( 'Webhook updated successfully.', 'woocommerce' ) ); } if ( isset( $_GET['created'] ) ) { WC_Admin_Settings::add_message( __( 'Webhook created successfully.', 'woocommerce' ) ); } if ( isset( $_GET['error'] ) ) { WC_Admin_Settings::add_error( wc_clean( $_GET['error'] ) ); } } /** * Table list output. */ private static function table_list_output() { echo '<h2>' . __( 'Webhooks', 'woocommerce' ) . ' <a href="' . esc_url( wp_nonce_url( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&create-webhook=1' ), 'create-webhook' ) ) . '" class="add-new-h2">' . __( 'Add webhook', 'woocommerce' ) . '</a></h2>'; $webhooks_table_list = new WC_Admin_Webhooks_Table_List(); $webhooks_table_list->prepare_items(); echo '<input type="hidden" name="page" value="wc-settings" />'; echo '<input type="hidden" name="tab" value="api" />'; echo '<input type="hidden" name="section" value="webhooks" />'; $webhooks_table_list->views(); $webhooks_table_list->search_box( __( 'Search webhooks', 'woocommerce' ), 'webhook' ); $webhooks_table_list->display(); } /** * Logs output. * * @param WC_Webhook $webhook */ public static function logs_output( $webhook ) { $current = isset( $_GET['log_page'] ) ? absint( $_GET['log_page'] ) : 1; $args = array( 'post_id' => $webhook->id, 'status' => 'approve', 'type' => 'webhook_delivery', 'number' => 10, ); if ( 1 < $current ) { $args['offset'] = ( $current - 1 ) * 10; } remove_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_webhook_comments' ), 10, 1 ); $logs = get_comments( $args ); add_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_webhook_comments' ), 10, 1 ); if ( $logs ) { include_once( dirname( __FILE__ ) . '/settings/views/html-webhook-logs.php' ); } else { echo '<p>' . __( 'This Webhook has no log yet.', 'woocommerce' ) . '</p>'; } } /** * Get the webhook topic data. * * @return array */ public static function get_topic_data( $webhook ) { $topic = $webhook->get_topic(); $event = ''; $resource = ''; if ( $topic ) { list( $resource, $event ) = explode( '.', $topic ); if ( 'action' === $resource ) { $topic = 'action'; } elseif ( ! in_array( $resource, array( 'coupon', 'customer', 'order', 'product' ) ) ) { $topic = 'custom'; } } return array( 'topic' => $topic, 'event' => $event, 'resource' => $resource, ); } /** * Get the logs navigation. * * @param int $total * * @return string */ public static function get_logs_navigation( $total, $webhook ) { $pages = ceil( $total / 10 ); $current = isset( $_GET['log_page'] ) ? absint( $_GET['log_page'] ) : 1; $html = '<div class="webhook-logs-navigation">'; $html .= '<p class="info" style="float: left;"><strong>'; $html .= sprintf( '%s &ndash; Page %d of %d', _n( '1 item', sprintf( '%d items', $total ), $total, 'woocommerce' ), $current, $pages ); $html .= '</strong></p>'; if ( 1 < $pages ) { $html .= '<p class="tools" style="float: right;">'; if ( 1 == $current ) { $html .= '<button class="button-primary" disabled="disabled">' . __( '&lsaquo; Previous', 'woocommerce' ) . '</button> '; } else { $html .= '<a class="button-primary" href="' . admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&edit-webhook=' . $webhook->id . '&log_page=' . ( $current - 1 ) ) . '#webhook-logs">' . __( '&lsaquo; Previous', 'woocommerce' ) . '</a> '; } if ( $pages == $current ) { $html .= '<button class="button-primary" disabled="disabled">' . __( 'Next &rsaquo;', 'woocommerce' ) . '</button>'; } else { $html .= '<a class="button-primary" href="' . admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&edit-webhook=' . $webhook->id . '&log_page=' . ( $current + 1 ) ) . '#webhook-logs">' . __( 'Next &rsaquo;', 'woocommerce' ) . '</a>'; } $html .= '</p>'; } $html .= '<div class="clear"></div></div>'; return $html; } } new WC_Admin_Webhooks();
bryceadams/woocommerce
includes/admin/class-wc-admin-webhooks.php
PHP
gpl-3.0
14,839
/** * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved. * * 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. */ package net.sareweb.emg.service; import com.liferay.portal.kernel.bean.PortletBeanLocatorUtil; import com.liferay.portal.kernel.util.ReferenceRegistry; import com.liferay.portal.service.InvokableService; /** * Provides the remote service utility for Draw. This utility wraps * {@link net.sareweb.emg.service.impl.DrawServiceImpl} and is the * primary access point for service operations in application layer code running * on a remote server. Methods of this service are expected to have security * checks based on the propagated JAAS credentials because this service can be * accessed remotely. * * @author A.Galdos * @see DrawService * @see net.sareweb.emg.service.base.DrawServiceBaseImpl * @see net.sareweb.emg.service.impl.DrawServiceImpl * @generated */ public class DrawServiceUtil { /* * NOTE FOR DEVELOPERS: * * Never modify this class directly. Add custom service methods to {@link net.sareweb.emg.service.impl.DrawServiceImpl} and rerun ServiceBuilder to regenerate this class. */ /** * Returns the Spring bean ID for this bean. * * @return the Spring bean ID for this bean */ public static java.lang.String getBeanIdentifier() { return getService().getBeanIdentifier(); } /** * Sets the Spring bean ID for this bean. * * @param beanIdentifier the Spring bean ID for this bean */ public static void setBeanIdentifier(java.lang.String beanIdentifier) { getService().setBeanIdentifier(beanIdentifier); } public static java.lang.Object invokeMethod(java.lang.String name, java.lang.String[] parameterTypes, java.lang.Object[] arguments) throws java.lang.Throwable { return getService().invokeMethod(name, parameterTypes, arguments); } public static java.util.List<net.sareweb.emg.model.Draw> getDrawsNewerThanDate( long date) throws com.liferay.portal.kernel.exception.SystemException { return getService().getDrawsNewerThanDate(date); } public static void clearService() { _service = null; } public static DrawService getService() { if (_service == null) { InvokableService invokableService = (InvokableService)PortletBeanLocatorUtil.locate(ClpSerializer.getServletContextName(), DrawService.class.getName()); if (invokableService instanceof DrawService) { _service = (DrawService)invokableService; } else { _service = new DrawServiceClp(invokableService); } ReferenceRegistry.registerReference(DrawServiceUtil.class, "_service"); } return _service; } /** * @deprecated As of 6.2.0 */ public void setService(DrawService service) { } private static DrawService _service; }
aritzg/EuroMillionGame-portlet
docroot/WEB-INF/service/net/sareweb/emg/service/DrawServiceUtil.java
Java
gpl-3.0
3,192
#define ICON_SIZE QSize(48,48) #define EXPANDED_HEIGHT 413 #define UNEXPANDED_HEIGHT 137 #include "mainpage.h" #include "ui_options.h" #include <QWidget> #include <QComboBox> #include <QHBoxLayout> #include <QVBoxLayout> #include <QGroupBox> #include <QCheckBox> #include <QLineEdit> #include <QMimeData> #include <QLabel> #include <QToolBar> #include <QAction> #include <QToolButton> #include <QFileDialog> #include <QUrl> #include <SMasterIcons> #include <SDeviceList> #include <SComboBox> #include <SDialogTools> class MainPagePrivate { public: QVBoxLayout *layout; QHBoxLayout *image_layout; QToolButton *open_btn; QLineEdit *src_line; SComboBox *dst_combo; QLabel *label; QToolBar *toolbar; QAction *go_action; QAction *more_action; SDeviceList *device_list; Ui::OptionsUi *options_ui; QWidget *options_widget; QList<SDeviceItem> devices; }; MainPage::MainPage( SApplication *parent ) : SPage( tr("Image Burner") , parent , SPage::WindowedPage ) { p = new MainPagePrivate; p->device_list = new SDeviceList( this ); p->src_line = new QLineEdit(); p->src_line->setReadOnly( true ); p->src_line->setFixedHeight( 28 ); p->src_line->setPlaceholderText( tr("Please select a Disc Image") ); p->src_line->setFocusPolicy( Qt::NoFocus ); p->open_btn = new QToolButton(); p->open_btn->setIcon( SMasterIcons::icon( ICON_SIZE , "document-open.png" ) ); p->open_btn->setFixedSize( 28 , 28 ); p->image_layout = new QHBoxLayout(); p->image_layout->addWidget( p->src_line ); p->image_layout->addWidget( p->open_btn ); p->dst_combo = new SComboBox(); p->dst_combo->setIconSize( QSize(22,22) ); p->label = new QLabel(); p->label->setText( tr("To") ); p->toolbar = new QToolBar(); p->toolbar->setToolButtonStyle( Qt::ToolButtonTextBesideIcon ); p->toolbar->setStyleSheet( "QToolBar{ border-style:solid ; margin:0px }" ); p->options_widget = new QWidget(); p->options_ui = new Ui::OptionsUi; p->options_ui->setupUi( p->options_widget ); p->layout = new QVBoxLayout( this ); p->layout->addLayout( p->image_layout ); p->layout->addWidget( p->label ); p->layout->addWidget( p->dst_combo ); p->layout->addWidget( p->options_widget ); p->layout->addWidget( p->toolbar ); p->layout->setContentsMargins( 10 , 10 , 10 , 10 ); setFixedWidth( 413 ); setFixedHeight( EXPANDED_HEIGHT ); p->dst_combo->setCurrentIndex( 0 ); connect( p->device_list , SIGNAL(deviceDetected(SDeviceItem)) , SLOT(deviceDetected(SDeviceItem)) ); connect( p->open_btn , SIGNAL(clicked()) , SLOT(select_src_image()) ); connect( p->dst_combo , SIGNAL(currentIndexChanged(int)) , SLOT(device_index_changed(int)) ); connect( p->options_ui->scan_check , SIGNAL(toggled(bool)) , p->options_ui->scan_widget , SLOT(setVisible(bool)) ); p->options_ui->scan_check->setChecked( false ); p->device_list->refresh(); init_actions(); more_prev(); setAcceptDrops( true ); } void MainPage::init_actions() { QWidget *spr1 = new QWidget(); spr1->setSizePolicy( QSizePolicy::Expanding , QSizePolicy::Minimum ); p->go_action = new QAction( SMasterIcons::icon(ICON_SIZE,"tools-media-optical-burn.png") , tr("Go") , this ); p->more_action = new QAction( SMasterIcons::icon(ICON_SIZE,"edit-rename.png") , tr("More") , this ); p->toolbar->addAction( p->more_action ); p->toolbar->addWidget( spr1 ); p->toolbar->addAction( p->go_action ); connect( p->go_action , SIGNAL(triggered()) , SLOT(go_prev()) ); connect( p->more_action , SIGNAL(triggered()) , SLOT(more_prev()) ); } void MainPage::deviceDetected( const SDeviceItem & device ) { if( !p->devices.contains(device) ) { p->devices << device; p->dst_combo->insertItem( p->devices.count()-1 , SMasterIcons::icon(ICON_SIZE,"drive-optical.png") , device.name() ); } else { int index = p->devices.indexOf( device ); p->devices.removeAt( index ); p->devices.insert( index , device ); p->dst_combo->setItemText( index , device.name() ); device_index_changed( p->dst_combo->currentIndex() ); } } void MainPage::device_index_changed( int index ) { if( index < 0 ) return ; const SDeviceItem & device = p->devices.at( index ); const SDiscFeatures & disc = device.currentDiscFeatures(); QList<int> list; if( disc.volume_disc_type_str.contains("blu",Qt::CaseInsensitive) ) list = device.deviceFeatures().bluray_speed_list; else if( disc.volume_disc_type_str.contains("dvd",Qt::CaseInsensitive) ) list = device.deviceFeatures().dvd_speed_list; else list = device.deviceFeatures().cd_speed_list; if( list.isEmpty() ) list << 2 << 1; p->options_ui->speed_combo->clear(); for( int i=0 ; i<list.count() ; i++ ) p->options_ui->speed_combo->addItem( QString::number(list.at(i)) ); } QString MainPage::sourceImage() const { return p->src_line->text(); } const SDeviceItem & MainPage::destinationDevice() const { return p->devices.at( p->dst_combo->currentIndex() ); } void MainPage::go_prev() { SDialogTools::getTimer( this , tr("Your Request will be starting after count down.") , 7000 , this , SIGNAL(go()) ); } void MainPage::more_prev() { if( height() == UNEXPANDED_HEIGHT ) { setFixedHeight( EXPANDED_HEIGHT ); p->options_widget->show(); p->more_action->setText( tr("Less") ); } else { setFixedHeight( UNEXPANDED_HEIGHT ); p->options_widget->hide(); p->more_action->setText( tr("More") ); } setDefaultOptions(); } void MainPage::setDefaultOptions() { int index = p->dst_combo->currentIndex(); if( index < 0 ) return ; const SDeviceItem & device = p->devices.at(index); const SDiscFeatures & disc = device.currentDiscFeatures(); /*! -------------------- Scanner Options -------------------------*/ p->options_ui->scan_line->setText( disc.volume_label_str ); } bool MainPage::scan() const { return p->options_ui->scan_check->isChecked(); } int MainPage::copiesNumber() const { return p->options_ui->copies_spin->value(); } int MainPage::speed() const { return p->options_ui->speed_combo->currentText().toInt(); } bool MainPage::eject() const { return p->options_ui->eject_check->isChecked(); } bool MainPage::dummy() const { return p->options_ui->dummy_check->isChecked(); } bool MainPage::remove() const { return p->options_ui->remove_check->isChecked(); } QString MainPage::scanName() const { return p->options_ui->scan_line->text(); } void MainPage::setSourceImage( const QString & file ) { p->src_line->setText( file ); } void MainPage::select_src_image() { SDialogTools::getOpenFileName( this , this , SLOT(setSourceImage(QString)) ); } void MainPage::setDestinationDevice( const QString & bus_len_id ) { for( int i=0 ; i<p->devices.count() ; i++ ) if( p->devices.at(i).toQString() == bus_len_id ) { p->dst_combo->setCurrentIndex( i ); return ; } } void MainPage::setScan( const QString & str ) { p->options_ui->scan_check->setChecked( !str.isEmpty() ); p->options_ui->scan_line->setText( str ); } void MainPage::setCopiesNumber( int value ) { p->options_ui->copies_spin->setValue( value ); } void MainPage::setSpeed( int speed ) { p->options_ui->speed_combo->setEditText( QString::number(speed) ); } void MainPage::setEject( bool stt ) { p->options_ui->eject_check->setChecked( stt ); } void MainPage::setDummy( bool stt ) { p->options_ui->dummy_check->setChecked( stt ); } void MainPage::setRemove( bool stt ) { p->options_ui->remove_check->setChecked( stt ); } void MainPage::dropEvent( QDropEvent *event ) { QList<QUrl> list = event->mimeData()->urls(); QString url_path = list.first().path(); #ifdef Q_OS_WIN32 if( url_path[0] == '/' ) url_path.remove( 0 , 1 ); #endif setSourceImage( url_path ); event->acceptProposedAction(); QWidget::dropEvent( event ); } void MainPage::dragEnterEvent( QDragEnterEvent *event ) { if( !event->mimeData()->hasUrls() ) return; QList<QUrl> list = event->mimeData()->urls(); if( list.count() != 1 ) event->ignore(); else event->acceptProposedAction(); QWidget::dragEnterEvent( event ); } MainPage::~MainPage() { delete p->options_ui; delete p; }
realbardia/silicon
SApplications/ImageBurner/mainpage.cpp
C++
gpl-3.0
8,814
# Makefile.in generated by automake 1.13.2 from Makefile.am. # monte/Makefile. Generated from Makefile.in by configure. # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/gsl pkgincludedir = $(includedir)/gsl pkglibdir = $(libdir)/gsl pkglibexecdir = $(libexecdir)/gsl am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = x86_64-unknown-linux-gnu host_triplet = x86_64-unknown-linux-gnu check_PROGRAMS = test$(EXEEXT) subdir = monte DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/mkinstalldirs $(top_srcdir)/depcomp \ $(noinst_HEADERS) $(pkginclude_HEADERS) \ $(top_srcdir)/test-driver ChangeLog README TODO ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libgslmonte_la_LIBADD = am_libgslmonte_la_OBJECTS = miser.lo plain.lo vegas.lo libgslmonte_la_OBJECTS = $(am_libgslmonte_la_OBJECTS) AM_V_lt = $(am__v_lt_$(V)) am__v_lt_ = $(am__v_lt_$(AM_DEFAULT_VERBOSITY)) am__v_lt_0 = --silent am__v_lt_1 = am_test_OBJECTS = test.$(OBJEXT) test_OBJECTS = $(am_test_OBJECTS) test_DEPENDENCIES = libgslmonte.la ../rng/libgslrng.la \ ../ieee-utils/libgslieeeutils.la ../err/libgslerr.la \ ../test/libgsltest.la ../sys/libgslsys.la ../utils/libutils.la AM_V_P = $(am__v_P_$(V)) am__v_P_ = $(am__v_P_$(AM_DEFAULT_VERBOSITY)) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_$(V)) am__v_GEN_ = $(am__v_GEN_$(AM_DEFAULT_VERBOSITY)) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_$(V)) am__v_at_ = $(am__v_at_$(AM_DEFAULT_VERBOSITY)) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I. -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_$(V)) am__v_CC_ = $(am__v_CC_$(AM_DEFAULT_VERBOSITY)) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_$(V)) am__v_CCLD_ = $(am__v_CCLD_$(AM_DEFAULT_VERBOSITY)) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libgslmonte_la_SOURCES) $(test_SOURCES) DIST_SOURCES = $(libgslmonte_la_SOURCES) $(test_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(pkgincludedir)" HEADERS = $(noinst_HEADERS) $(pkginclude_HEADERS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` RECHECK_LOGS = $(TEST_LOGS) AM_RECURSIVE_TARGETS = check recheck TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = .test LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = ${SHELL} /home/arne/src/github.com/barnex/gsl/gsl-1.16/missing aclocal-1.13 AMTAR = $${TAR-tar} AM_DEFAULT_VERBOSITY = 1 AR = ar AUTOCONF = ${SHELL} /home/arne/src/github.com/barnex/gsl/gsl-1.16/missing autoconf AUTOHEADER = ${SHELL} /home/arne/src/github.com/barnex/gsl/gsl-1.16/missing autoheader AUTOMAKE = ${SHELL} /home/arne/src/github.com/barnex/gsl/gsl-1.16/missing automake-1.13 AWK = mawk CC = gcc CCDEPMODE = depmode=gcc3 CFLAGS = -g -O2 CPP = gcc -E CPPFLAGS = CYGPATH_W = echo DEFS = -DHAVE_CONFIG_H DEPDIR = .deps DLLTOOL = false DSYMUTIL = DUMPBIN = ECHO_C = ECHO_N = -n ECHO_T = EGREP = /bin/grep -E EXEEXT = FGREP = /bin/grep -F GREP = /bin/grep GSL_CFLAGS = -I${prefix}/include GSL_LIBM = -lm GSL_LIBS = -L${exec_prefix}/lib -lgsl GSL_LT_CBLAS_VERSION = 0:0:0 GSL_LT_VERSION = 17:0:17 GSL_MAJOR_VERSION = 1 GSL_MINOR_VERSION = 16 HAVE_AIX_IEEE_INTERFACE = HAVE_DARWIN86_IEEE_INTERFACE = HAVE_DARWIN_IEEE_INTERFACE = HAVE_FREEBSD_IEEE_INTERFACE = HAVE_GNUM68K_IEEE_INTERFACE = HAVE_GNUPPC_IEEE_INTERFACE = HAVE_GNUSPARC_IEEE_INTERFACE = HAVE_GNUX86_IEEE_INTERFACE = HAVE_HPUX11_IEEE_INTERFACE = HAVE_HPUX_IEEE_INTERFACE = HAVE_IRIX_IEEE_INTERFACE = HAVE_NETBSD_IEEE_INTERFACE = HAVE_OPENBSD_IEEE_INTERFACE = HAVE_OS2EMX_IEEE_INTERFACE = HAVE_SOLARIS_IEEE_INTERFACE = HAVE_SUNOS4_IEEE_INTERFACE = HAVE_TRU64_IEEE_INTERFACE = INSTALL = /usr/bin/install -c INSTALL_DATA = ${INSTALL} -m 644 INSTALL_PROGRAM = ${INSTALL} INSTALL_SCRIPT = ${INSTALL} INSTALL_STRIP_PROGRAM = $(install_sh) -c -s LD = /usr/bin/ld -m elf_x86_64 LDFLAGS = LIBM = -lm LIBOBJS = LIBS = -lm LIBTOOL = $(SHELL) $(top_builddir)/libtool LIPO = LN_S = ln -s LTLIBOBJS = MAINT = # MAKEINFO = ${SHELL} /home/arne/src/github.com/barnex/gsl/gsl-1.16/missing makeinfo MANIFEST_TOOL = : MKDIR_P = /bin/mkdir -p NM = /usr/bin/nm -B NMEDIT = OBJDUMP = objdump OBJEXT = o OTOOL = OTOOL64 = PACKAGE = gsl PACKAGE_BUGREPORT = PACKAGE_NAME = gsl PACKAGE_STRING = gsl 1.16 PACKAGE_TARNAME = gsl PACKAGE_URL = PACKAGE_VERSION = 1.16 PATH_SEPARATOR = : RANLIB = ranlib SED = /bin/sed SET_MAKE = SHELL = /bin/bash STRIP = strip VERSION = 1.16 abs_builddir = /home/arne/src/github.com/barnex/gsl/gsl-1.16/monte abs_srcdir = /home/arne/src/github.com/barnex/gsl/gsl-1.16/monte abs_top_builddir = /home/arne/src/github.com/barnex/gsl/gsl-1.16 abs_top_srcdir = /home/arne/src/github.com/barnex/gsl/gsl-1.16 ac_ct_AR = ar ac_ct_CC = gcc ac_ct_DUMPBIN = am__include = include am__leading_dot = . am__quote = am__tar = $${TAR-tar} chof - "$$tardir" am__untar = $${TAR-tar} xf - bindir = ${exec_prefix}/bin build = x86_64-unknown-linux-gnu build_alias = build_cpu = x86_64 build_os = linux-gnu build_vendor = unknown builddir = . datadir = ${datarootdir} datarootdir = ${prefix}/share docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} dvidir = ${docdir} exec_prefix = ${prefix} host = x86_64-unknown-linux-gnu host_alias = host_cpu = x86_64 host_os = linux-gnu host_vendor = unknown htmldir = ${docdir} includedir = ${prefix}/include infodir = ${datarootdir}/info install_sh = ${SHELL} /home/arne/src/github.com/barnex/gsl/gsl-1.16/install-sh libdir = ${exec_prefix}/lib libexecdir = ${exec_prefix}/libexec localedir = ${datarootdir}/locale localstatedir = ${prefix}/var mandir = ${datarootdir}/man mkdir_p = $(MKDIR_P) oldincludedir = /usr/include pdfdir = ${docdir} prefix = /usr/local program_transform_name = s,x,x, psdir = ${docdir} sbindir = ${exec_prefix}/sbin sharedstatedir = ${prefix}/com srcdir = . sysconfdir = ${prefix}/etc target_alias = top_build_prefix = ../ top_builddir = .. top_srcdir = .. noinst_LTLIBRARIES = libgslmonte.la libgslmonte_la_SOURCES = miser.c plain.c gsl_monte_vegas.h gsl_monte_miser.h gsl_monte_plain.h gsl_monte.h vegas.c pkginclude_HEADERS = gsl_monte.h gsl_monte_vegas.h gsl_monte_miser.h gsl_monte_plain.h INCLUDES = -I$(top_srcdir) TESTS = $(check_PROGRAMS) test_SOURCES = test.c test_LDADD = libgslmonte.la ../rng/libgslrng.la ../ieee-utils/libgslieeeutils.la ../err/libgslerr.la ../test/libgsltest.la ../sys/libgslsys.la ../utils/libutils.la noinst_HEADERS = test_main.c all: all-am .SUFFIXES: .SUFFIXES: .c .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: # $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu monte/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu monte/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: # $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): # $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libgslmonte.la: $(libgslmonte_la_OBJECTS) $(libgslmonte_la_DEPENDENCIES) $(EXTRA_libgslmonte_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(libgslmonte_la_OBJECTS) $(libgslmonte_la_LIBADD) $(LIBS) clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list test$(EXEEXT): $(test_OBJECTS) $(test_DEPENDENCIES) $(EXTRA_test_DEPENDENCIES) @rm -f test$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_OBJECTS) $(test_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c include ./$(DEPDIR)/miser.Plo include ./$(DEPDIR)/plain.Plo include ./$(DEPDIR)/test.Po include ./$(DEPDIR)/vegas.Plo .c.o: $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po # $(AM_V_CC)source='$<' object='$@' libtool=no \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(COMPILE) -c $< .c.obj: $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po # $(AM_V_CC)source='$<' object='$@' libtool=no \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(COMPILE) -c `$(CYGPATH_W) '$<'` .c.lo: $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo # $(AM_V_CC)source='$<' object='$@' libtool=yes \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-pkgincludeHEADERS: $(pkginclude_HEADERS) @$(NORMAL_INSTALL) @list='$(pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(pkgincludedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(pkgincludedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(pkgincludedir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(pkgincludedir)" || exit $$?; \ done uninstall-pkgincludeHEADERS: @$(NORMAL_UNINSTALL) @list='$(pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(pkgincludedir)'; $(am__uninstall_files_from_dir) ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ else \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? test.log: test$(EXEEXT) @p='test$(EXEEXT)'; \ b='test'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) #.test$(EXEEXT).log: # @p='$<'; \ # $(am__set_b); \ # $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ # --log-file $$b.log --trs-file $$b.trs \ # $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ # "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-am all-am: Makefile $(LTLIBRARIES) $(HEADERS) installdirs: for dir in "$(DESTDIR)$(pkgincludedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-checkPROGRAMS clean-generic clean-libtool \ clean-noinstLTLIBRARIES mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-pkgincludeHEADERS install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-pkgincludeHEADERS .MAKE: check-am install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-TESTS check-am clean \ clean-checkPROGRAMS clean-generic clean-libtool \ clean-noinstLTLIBRARIES cscopelist-am ctags ctags-am distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-pkgincludeHEADERS \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am \ uninstall-pkgincludeHEADERS #demo_SOURCES= demo.c #demo_LDADD = libgslmonte.la ../rng/libgslrng.la ../ieee-utils/libgslieeeutils.la ../err/libgslerr.la ../test/libgsltest.la ../utils/libutils.la # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT:
barnex/gsl
gsl-1.16/monte/Makefile
Makefile
gpl-3.0
33,931
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.javascript.optimizer; import org.mozilla.javascript.ArrowFunction; import org.mozilla.javascript.Callable; import org.mozilla.javascript.ConsString; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.ES6Generator; import org.mozilla.javascript.Function; import org.mozilla.javascript.JavaScriptException; import org.mozilla.javascript.NativeFunction; import org.mozilla.javascript.NativeGenerator; import org.mozilla.javascript.NativeIterator; import org.mozilla.javascript.Script; import org.mozilla.javascript.ScriptRuntime; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.Undefined; /** * <p>OptRuntime class.</p> * * * */ public final class OptRuntime extends ScriptRuntime { /** Constant <code>oneObj</code> */ public static final Double oneObj = Double.valueOf(1.0); /** Constant <code>minusOneObj</code> */ public static final Double minusOneObj = Double.valueOf(-1.0); /** * Implement ....() call shrinking optimizer code. * * @param fun a {@link org.mozilla.javascript.Callable} object. * @param thisObj a {@link org.mozilla.javascript.Scriptable} object. * @param cx a {@link org.mozilla.javascript.Context} object. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @return a {@link java.lang.Object} object. */ public static Object call0(Callable fun, Scriptable thisObj, Context cx, Scriptable scope) { return fun.call(cx, scope, thisObj, ScriptRuntime.emptyArgs); } /** * Implement ....(arg) call shrinking optimizer code. * * @param fun a {@link org.mozilla.javascript.Callable} object. * @param thisObj a {@link org.mozilla.javascript.Scriptable} object. * @param arg0 a {@link java.lang.Object} object. * @param cx a {@link org.mozilla.javascript.Context} object. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @return a {@link java.lang.Object} object. */ public static Object call1(Callable fun, Scriptable thisObj, Object arg0, Context cx, Scriptable scope) { return fun.call(cx, scope, thisObj, new Object[] { arg0 } ); } /** * Implement ....(arg0, arg1) call shrinking optimizer code. * * @param fun a {@link org.mozilla.javascript.Callable} object. * @param thisObj a {@link org.mozilla.javascript.Scriptable} object. * @param arg0 a {@link java.lang.Object} object. * @param arg1 a {@link java.lang.Object} object. * @param cx a {@link org.mozilla.javascript.Context} object. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @return a {@link java.lang.Object} object. */ public static Object call2(Callable fun, Scriptable thisObj, Object arg0, Object arg1, Context cx, Scriptable scope) { return fun.call(cx, scope, thisObj, new Object[] { arg0, arg1 }); } /** * Implement ....(arg0, arg1, ...) call shrinking optimizer code. * * @param fun a {@link org.mozilla.javascript.Callable} object. * @param thisObj a {@link org.mozilla.javascript.Scriptable} object. * @param args an array of {@link java.lang.Object} objects. * @param cx a {@link org.mozilla.javascript.Context} object. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @return a {@link java.lang.Object} object. */ public static Object callN(Callable fun, Scriptable thisObj, Object[] args, Context cx, Scriptable scope) { return fun.call(cx, scope, thisObj, args); } /** * Implement name(args) call shrinking optimizer code. * * @param args an array of {@link java.lang.Object} objects. * @param name a {@link java.lang.String} object. * @param cx a {@link org.mozilla.javascript.Context} object. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @return a {@link java.lang.Object} object. */ public static Object callName(Object[] args, String name, Context cx, Scriptable scope) { Callable f = getNameFunctionAndThis(name, cx, scope); Scriptable thisObj = lastStoredScriptable(cx); return f.call(cx, scope, thisObj, args); } /** * Implement name() call shrinking optimizer code. * * @param name a {@link java.lang.String} object. * @param cx a {@link org.mozilla.javascript.Context} object. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @return a {@link java.lang.Object} object. */ public static Object callName0(String name, Context cx, Scriptable scope) { Callable f = getNameFunctionAndThis(name, cx, scope); Scriptable thisObj = lastStoredScriptable(cx); return f.call(cx, scope, thisObj, ScriptRuntime.emptyArgs); } /** * Implement x.property() call shrinking optimizer code. * * @param value a {@link java.lang.Object} object. * @param property a {@link java.lang.String} object. * @param cx a {@link org.mozilla.javascript.Context} object. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @return a {@link java.lang.Object} object. */ public static Object callProp0(Object value, String property, Context cx, Scriptable scope) { Callable f = getPropFunctionAndThis(value, property, cx, scope); Scriptable thisObj = lastStoredScriptable(cx); return f.call(cx, scope, thisObj, ScriptRuntime.emptyArgs); } /** * <p>add.</p> * * @param val1 a {@link java.lang.Object} object. * @param val2 a double. * @return a {@link java.lang.Object} object. */ public static Object add(Object val1, double val2) { if (val1 instanceof Scriptable) val1 = ((Scriptable) val1).getDefaultValue(null); if (!(val1 instanceof CharSequence)) return wrapDouble(toNumber(val1) + val2); return new ConsString((CharSequence)val1, toString(val2)); } /** {@inheritDoc} */ public static Object add(double val1, Object val2) { if (val2 instanceof Scriptable) val2 = ((Scriptable) val2).getDefaultValue(null); if (!(val2 instanceof CharSequence)) return wrapDouble(toNumber(val2) + val1); return new ConsString(toString(val1), (CharSequence)val2); } /** {@inheritDoc} */ @Deprecated public static Object elemIncrDecr(Object obj, double index, Context cx, int incrDecrMask) { return elemIncrDecr(obj, index, cx, getTopCallScope(cx), incrDecrMask); } /** {@inheritDoc} */ public static Object elemIncrDecr(Object obj, double index, Context cx, Scriptable scope, int incrDecrMask) { return ScriptRuntime.elemIncrDecr(obj, Double.valueOf(index), cx, scope, incrDecrMask); } /** * <p>padStart.</p> * * @param currentArgs an array of {@link java.lang.Object} objects. * @param count a int. * @return an array of {@link java.lang.Object} objects. */ public static Object[] padStart(Object[] currentArgs, int count) { Object[] result = new Object[currentArgs.length + count]; System.arraycopy(currentArgs, 0, result, count, currentArgs.length); return result; } /** * <p>initFunction.</p> * * @param fn a {@link org.mozilla.javascript.NativeFunction} object. * @param functionType a int. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @param cx a {@link org.mozilla.javascript.Context} object. */ public static void initFunction(NativeFunction fn, int functionType, Scriptable scope, Context cx) { ScriptRuntime.initFunction(cx, scope, fn, functionType, false); } /** * <p>bindThis.</p> * * @param fn a {@link org.mozilla.javascript.NativeFunction} object. * @param cx a {@link org.mozilla.javascript.Context} object. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @param thisObj a {@link org.mozilla.javascript.Scriptable} object. * @return a {@link org.mozilla.javascript.Function} object. */ public static Function bindThis(NativeFunction fn, Context cx, Scriptable scope, Scriptable thisObj) { return new ArrowFunction(cx, scope, fn, thisObj); } /** {@inheritDoc} */ public static Object callSpecial(Context cx, Callable fun, Scriptable thisObj, Object[] args, Scriptable scope, Scriptable callerThis, int callType, String fileName, int lineNumber) { return ScriptRuntime.callSpecial(cx, fun, thisObj, args, scope, callerThis, callType, fileName, lineNumber); } /** * <p>newObjectSpecial.</p> * * @param cx a {@link org.mozilla.javascript.Context} object. * @param fun a {@link java.lang.Object} object. * @param args an array of {@link java.lang.Object} objects. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @param callerThis a {@link org.mozilla.javascript.Scriptable} object. * @param callType a int. * @return a {@link java.lang.Object} object. */ public static Object newObjectSpecial(Context cx, Object fun, Object[] args, Scriptable scope, Scriptable callerThis, int callType) { return ScriptRuntime.newSpecial(cx, fun, args, scope, callType); } /** * <p>wrapDouble.</p> * * @param num a double. * @return a {@link java.lang.Double} object. */ public static Double wrapDouble(double num) { if (num == 0.0) { if (1 / num > 0) { // +0.0 return zeroObj; } } else if (num == 1.0) { return oneObj; } else if (num == -1.0) { return minusOneObj; } else if (Double.isNaN(num)) { return NaNobj; } return Double.valueOf(num); } static String encodeIntArray(int[] array) { // XXX: this extremely inefficient for small integers if (array == null) { return null; } int n = array.length; char[] buffer = new char[1 + n * 2]; buffer[0] = 1; for (int i = 0; i != n; ++i) { int value = array[i]; int shift = 1 + i * 2; buffer[shift] = (char)(value >>> 16); buffer[shift + 1] = (char)value; } return new String(buffer); } private static int[] decodeIntArray(String str, int arraySize) { // XXX: this extremely inefficient for small integers if (arraySize == 0) { if (str != null) throw new IllegalArgumentException(); return null; } if (str.length() != 1 + arraySize * 2 && str.charAt(0) != 1) { throw new IllegalArgumentException(); } int[] array = new int[arraySize]; for (int i = 0; i != arraySize; ++i) { int shift = 1 + i * 2; array[i] = (str.charAt(shift) << 16) | str.charAt(shift + 1); } return array; } /** * <p>newArrayLiteral.</p> * * @param objects an array of {@link java.lang.Object} objects. * @param encodedInts a {@link java.lang.String} object. * @param skipCount a int. * @param cx a {@link org.mozilla.javascript.Context} object. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @return a {@link org.mozilla.javascript.Scriptable} object. */ public static Scriptable newArrayLiteral(Object[] objects, String encodedInts, int skipCount, Context cx, Scriptable scope) { int[] skipIndexces = decodeIntArray(encodedInts, skipCount); return newArrayLiteral(objects, skipIndexces, cx, scope); } /** * <p>main.</p> * * @param script a {@link org.mozilla.javascript.Script} object. * @param args an array of {@link java.lang.String} objects. */ public static void main(final Script script, final String[] args) { ContextFactory.getGlobal().call(cx -> { ScriptableObject global = getGlobal(cx); // get the command line arguments and define "arguments" // array in the top-level object Object[] argsCopy = new Object[args.length]; System.arraycopy(args, 0, argsCopy, 0, args.length); Scriptable argsObj = cx.newArray(global, argsCopy); global.defineProperty("arguments", argsObj, ScriptableObject.DONTENUM); script.exec(cx, global); return null; }); } /** * <p>throwStopIteration.</p> * * @param scope a {@link java.lang.Object} object. * @param genState a {@link java.lang.Object} object. */ public static void throwStopIteration(Object scope, Object genState) { Object value = getGeneratorReturnValue(genState); Object si = (value == Undefined.instance) ? NativeIterator.getStopIterationObject((Scriptable)scope) : new NativeIterator.StopIteration(value); throw new JavaScriptException(si, "", 0); } /** * <p>createNativeGenerator.</p> * * @param funObj a {@link org.mozilla.javascript.NativeFunction} object. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @param thisObj a {@link org.mozilla.javascript.Scriptable} object. * @param maxLocals a int. * @param maxStack a int. * @return a {@link org.mozilla.javascript.Scriptable} object. */ public static Scriptable createNativeGenerator(NativeFunction funObj, Scriptable scope, Scriptable thisObj, int maxLocals, int maxStack) { GeneratorState gs = new GeneratorState(thisObj, maxLocals, maxStack); if (Context.getCurrentContext().getLanguageVersion() >= Context.VERSION_ES6) { return new ES6Generator(scope, funObj, gs); } else { return new NativeGenerator(scope, funObj, gs); } } /** * <p>getGeneratorStackState.</p> * * @param obj a {@link java.lang.Object} object. * @return an array of {@link java.lang.Object} objects. */ public static Object[] getGeneratorStackState(Object obj) { GeneratorState rgs = (GeneratorState) obj; if (rgs.stackState == null) rgs.stackState = new Object[rgs.maxStack]; return rgs.stackState; } /** * <p>getGeneratorLocalsState.</p> * * @param obj a {@link java.lang.Object} object. * @return an array of {@link java.lang.Object} objects. */ public static Object[] getGeneratorLocalsState(Object obj) { GeneratorState rgs = (GeneratorState) obj; if (rgs.localsState == null) rgs.localsState = new Object[rgs.maxLocals]; return rgs.localsState; } /** * <p>setGeneratorReturnValue.</p> * * @param obj a {@link java.lang.Object} object. * @param val a {@link java.lang.Object} object. */ public static void setGeneratorReturnValue(Object obj, Object val) { GeneratorState rgs = (GeneratorState) obj; rgs.returnValue = val; } /** * <p>getGeneratorReturnValue.</p> * * @param obj a {@link java.lang.Object} object. * @return a {@link java.lang.Object} object. */ public static Object getGeneratorReturnValue(Object obj) { GeneratorState rgs = (GeneratorState) obj; return (rgs.returnValue == null ? Undefined.instance : rgs.returnValue); } public static class GeneratorState { static final String CLASS_NAME = "org/mozilla/javascript/optimizer/OptRuntime$GeneratorState"; @SuppressWarnings("unused") public int resumptionPoint; static final String resumptionPoint_NAME = "resumptionPoint"; static final String resumptionPoint_TYPE = "I"; @SuppressWarnings("unused") public Scriptable thisObj; static final String thisObj_NAME = "thisObj"; static final String thisObj_TYPE = "Lorg/mozilla/javascript/Scriptable;"; Object[] stackState; Object[] localsState; int maxLocals; int maxStack; Object returnValue; GeneratorState(Scriptable thisObj, int maxLocals, int maxStack) { this.thisObj = thisObj; this.maxLocals = maxLocals; this.maxStack = maxStack; } } }
oswetto/LoboEvolution
LoboParser/src/main/java/org/mozilla/javascript/optimizer/OptRuntime.java
Java
gpl-3.0
18,041
#include "relativelayout.h" #include <QDebug> RelativeLayout::RelativeLayout(View *parent) : View(parent) { // By default, QQuickItem does not draw anything. If you subclass // QQuickItem to create a visual item, you will need to uncomment the // following line and re-implement updatePaintNode() // setFlag(ItemHasContents, true); } RelativeLayout::~RelativeLayout() { } void RelativeLayout::inflate() { View::inflate(); qDebug() << "Start rellayout inflate"; if (m_context != NULL && m_context->isValid()) { m_object = new QAndroidJniObject("android/widget/RelativeLayout", "(Landroid/content/Context;)V", m_context->object()); qDebug() << m_object->isValid(); qDebug() << m_object->toString(); foreach (QObject *child, m_children) { qDebug() << "add children to layout"; if (child != NULL) { qDebug() << child->metaObject()->className(); child->dumpObjectInfo(); if (child->inherits("View")) m_object->callMethod<void>("addView", "(Landroid/view/View;)V", qobject_cast<View*>(child)->object()->object()); } } } else qDebug() << "No context, cannot inflate!"; }
achipa/outqross_blog
2_OutQross.Android_components/relativelayout.cpp
C++
gpl-3.0
1,257
.nav-tabs { border-bottom: 1px solid #151313 !important; background-color: rgba(0, 0, 0, 0.33); padding: 5px; } li.btn { height: 44px; } * { margin:0; padding:0; border-radius: 0px; } .table-hover>tbody>tr:hover { background-color: #8387F1; border-radius: 0px ; } .table-hover>tbody>tr>td { border-radius: 0px ; } .btn{ box-shadow: 1px 2px 5px #000000; } #tituloBarra{ font-style: oblique; font-weight: bold; cursor: pointer; float: right; background-color: #5bc0de; border-radius: 4px; border: 1px; padding: 4px; } .fotoGrilla { width: 40px; height: 40px; } .fotoform { max-width: 200px; max-height: 200px; } .container { margin-top: 12px; } #header { position: fixed; top: 0; width: 100%; height: 50px; background-color: #333; color: #FFFFFF; padding: 10px; z-index: 1; } .centrar { text-align:center; } body { margin: 0 auto; color:#333; padding-top: 40px; background: linear-gradient(to right ,rgba(41, 137, 216, 0.39), #dff0d8, #999); /* Standard syntax */ /*background:rgba(85, 85, 85, 0.72);*/ font-family:'Open Sans',sans-serif; } caption { font-size: 1.6em; font-weight: 400; padding: 10px 0; } footer { height: 60px; /*background-color: #C2C2C2;*/ background: linear-gradient(to right ,rgba(41, 137, 216, 0.39), #dff0d8, #999); } h1 { margin: 0px; border: black; } .imgLogin { width:325px; height:377px; } .CajaUno { max-width: 30%; width:400px; margin:0 auto; margin-top:8px; margin-bottom:2%; transition:opacity 1s; -webkit-transition:opacity 1s; } .CajaInicio { width:750px; margin:0 auto; margin-top:8px; margin-bottom:2%; transition:opacity 1s; -webkit-transition:opacity 1s; } .CajaEnunciado { max-width: 30%; border: dashed; position: fixed; background: royalblue; top: 0px; width: 400px; margin: 0; padding: 10px; margin-bottom: 2%; transition: opacity 1s; -webkit-transition: opacity 1s; border-radius: 15px; -webkit-border-radius: 15px; } .CajaInicio h1{ background:#010101 /*rgb(14, 26, 112);*/; padding:20px 0; font-size:140%; font-weight:300; text-align:center; color:#fff; } .CajaAbajo { margin-top: 100px; width:400px; top:0px; left:0px; transition:opacity 1s; -webkit-transition:opacity 1s; } .CajaArriva { margin-top: 20px; width:400px; top:0px; left:0px; transition:opacity 1s; -webkit-transition:opacity 1s; } #FormIngreso { background:#f0f0f0; padding:7% 5%; } input[type="text"],input[type="file"],input[type="search"]{ width:100%; background:#fff; margin-bottom:2%; border:1px solid #ccc; padding:2%; font-family:'Open Sans',sans-serif; font-size:140%; font-weight: 800; color:#555; } select{ width:100%; background:#fff; margin-bottom:2%; border:1px solid #ccc; padding:2%; font-family:'Open Sans',sans-serif; font-size:95%; color:#555; } .MiBotonUTN { display:block; text-transform: capitalize; border:hidden; width:100%; background:#f50056; margin:0 auto; margin-top:1%; padding:10px; text-align:center; text-decoration:none; color:#fff; cursor:pointer; -moz-border-radius:7px; -webkit-border-radius:7px; border-radius:7px; transition:background .3s; -webkit-transition:background .3s; } .MiBotonUTN:hover{ background:#1BA045; } /* .MiBotonUTNJuego { text-transform: capitalize; border:hidden; width:32%; background:#f50056; margin:0 auto; margin-top:1%; padding:10px; text-align:center; text-decoration:none; color:#fff; cursor:pointer; -moz-border-radius:7px; -webkit-border-radius:7px; border-radius:7px; transition:background .3s; -webkit-transition:background .3s; } */ .MiBotonUTNMenu { display:block; text-transform: capitalize; border:hidden; width:100px; background:#f50056; margin-top:1%; padding:6px; text-align:center; text-decoration:none; color:#fff; cursor:pointer; -moz-border-radius:7px; -webkit-border-radius:7px; border-radius:7px; transition:background .3s; -webkit-transition:background .3s; } .MiBotonUTNMenu:hover{ background: #1e5799; /* Old browsers */ background: -moz-linear-gradient(45deg, #1e5799 0%, #2989d8 16%, #2989d8 16%, #ffffff 36%, #ffffff 43%, #ebf709 48%, #ffffff 52%, #ffffff 61%, #207cca 82%, #207cca 99%, #207cca 99%, #7db9e8 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left bottom, right top, color-stop(0%,#1e5799), color-stop(16%,#2989d8), color-stop(16%,#2989d8), color-stop(36%,#ffffff), color-stop(43%,#ffffff), color-stop(48%,#ebf709), color-stop(52%,#ffffff), color-stop(61%,#ffffff), color-stop(82%,#207cca), color-stop(99%,#207cca), color-stop(99%,#207cca), color-stop(100%,#7db9e8)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(45deg, #1e5799 0%,#2989d8 16%,#2989d8 16%,#ffffff 36%,#ffffff 43%,#ebf709 48%,#ffffff 52%,#ffffff 61%,#207cca 82%,#207cca 99%,#207cca 99%,#7db9e8 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(45deg, #1e5799 0%,#2989d8 16%,#2989d8 16%,#ffffff 36%,#ffffff 43%,#ebf709 48%,#ffffff 52%,#ffffff 61%,#207cca 82%,#207cca 99%,#207cca 99%,#7db9e8 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(45deg, #1e5799 0%,#2989d8 16%,#2989d8 16%,#ffffff 36%,#ffffff 43%,#ebf709 48%,#ffffff 52%,#ffffff 61%,#207cca 82%,#207cca 99%,#207cca 99%,#7db9e8 100%); /* IE10+ */ background: linear-gradient(45deg, #1e5799 0%,#2989d8 16%,#2989d8 16%,#ffffff 36%,#ffffff 43%,#ebf709 48%,#ffffff 52%,#ffffff 61%,#207cca 82%,#207cca 99%,#207cca 99%,#7db9e8 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#1e5799', endColorstr='#7db9e8',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */ color:black; } /* .MiBotonUTNLinea{ max-width: 150px; position: absolute; text-transform: capitalize; border:hidden; width:100%; background:#00A1F5; margin:0 auto; margin-top:30%; padding:10px; text-align:center; text-decoration:none; color:#fff; cursor:pointer; -moz-border-radius:7px; -webkit-border-radius:7px; border-radius:7px; transition:background .3s; -webkit-transition:background .3s; } .MiBotonUTNLinea:hover{ background:red; } */ .MiBotonUTNMenuInicio { display:block; border:hidden; //width:150px; background:Blue; margin-top:1%; padding:6px; text-align:center; text-decoration:none; color:#fff; cursor:pointer; -moz-border-radius:7px; -webkit-border-radius:7px; border-radius:7px; transition:background .3s; -webkit-transition:background .3s; } .MiBotonUTNMenuInicio:hover{ background:red; } /* .CajaUno h1{ background:#f50056; padding:20px 0; font-size:140%; font-weight:300; text-align:center; color:#fff; } .CajaUno a:hover { color:#f50056; } */ /* .CajaUno a { color:#DDDDDD; } */ /* .PiedraPapelTijera { width: 100px; height: 100px; padding: 10px; }*/
Leandro1391/TP_MysteryShopper
css/estilo.css
CSS
gpl-3.0
6,948
/* Copyright 2012 SINTEF ICT, Applied Mathematics. This file is part of the Open Porous Media project (OPM). OPM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OPM 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 OPM. If not, see <http://www.gnu.org/licenses/>. */ #ifndef OPM_INCOMPTPFA_HEADER_INCLUDED #define OPM_INCOMPTPFA_HEADER_INCLUDED #include <opm/core/simulator/SimulatorState.hpp> #include <opm/core/pressure/tpfa/ifs_tpfa.h> #include <vector> struct UnstructuredGrid; struct Wells; struct FlowBoundaryConditions; namespace Opm { class IncompPropertiesInterface; class RockCompressibility; class LinearSolverInterface; class WellState; class SimulatoreState; /// Encapsulating a tpfa pressure solver for the incompressible-fluid case. /// Supports gravity, wells controlled by bhp or reservoir rates, /// boundary conditions and simple sources as driving forces. /// Rock compressibility can be included, and necessary nonlinear /// iterations are handled. /// Below we use the shortcuts D for the number of dimensions, N /// for the number of cells and F for the number of faces. class IncompTpfa { public: /// Construct solver for incompressible case. /// \param[in] grid A 2d or 3d grid. /// \param[in] props Rock and fluid properties. /// \param[in] linsolver Linear solver to use. /// \param[in] gravity Gravity vector. If non-null, the array should /// have D elements. /// \param[in] wells The wells argument. Will be used in solution, /// is ignored if NULL. /// Note: this class observes the well object, and /// makes the assumption that the well topology /// and completions does not change during the /// run. However, controls (only) are allowed /// to change. /// \param[in] src Source terms. May be empty(). /// \param[in] bcs Boundary conditions, treat as all noflow if null. IncompTpfa(const UnstructuredGrid& grid, const IncompPropertiesInterface& props, LinearSolverInterface& linsolver, const double* gravity, const Wells* wells, const std::vector<double>& src, const FlowBoundaryConditions* bcs); /// Construct solver, possibly with rock compressibility. /// \param[in] grid A 2d or 3d grid. /// \param[in] props Rock and fluid properties. /// \param[in] rock_comp_props Rock compressibility properties. May be null. /// \param[in] linsolver Linear solver to use. /// \param[in] residual_tol Solution accepted if inf-norm of residual is smaller. /// \param[in] change_tol Solution accepted if inf-norm of change in pressure is smaller. /// \param[in] maxiter Maximum acceptable number of iterations. /// \param[in] gravity Gravity vector. If non-null, the array should /// have D elements. /// \param[in] wells The wells argument. Will be used in solution, /// is ignored if NULL. /// Note: this class observes the well object, and /// makes the assumption that the well topology /// and completions does not change during the /// run. However, controls (only) are allowed /// to change. /// \param[in] src Source terms. May be empty(). /// \param[in] bcs Boundary conditions, treat as all noflow if null. IncompTpfa(const UnstructuredGrid& grid, const IncompPropertiesInterface& props, const RockCompressibility* rock_comp_props, LinearSolverInterface& linsolver, const double residual_tol, const double change_tol, const int maxiter, const double* gravity, const Wells* wells, const std::vector<double>& src, const FlowBoundaryConditions* bcs); /// Destructor. virtual ~IncompTpfa(); /// Solve the pressure equation. If there is no pressure /// dependency introduced by rock compressibility effects, /// the equation is linear, and it is solved directly. /// Otherwise, the nonlinear equations ares solved by a /// Newton-Raphson scheme. /// May throw an exception if the number of iterations /// exceed maxiter (set in constructor). void solve(const double dt, SimulatorState& state, WellState& well_state); /// Expose read-only reference to internal half-transmissibility. const std::vector<double>& getHalfTrans() const { return htrans_; } protected: // Solve with no rock compressibility (linear eqn). void solveIncomp(const double dt, SimulatorState& state, WellState& well_state); // Solve with rock compressibility (nonlinear eqn). void solveRockComp(const double dt, SimulatorState& state, WellState& well_state); private: // Helper functions. void computeStaticData(); virtual void computePerSolveDynamicData(const double dt, const SimulatorState& state, const WellState& well_state); void computePerIterationDynamicData(const double dt, const SimulatorState& state, const WellState& well_state); void assemble(const double dt, const SimulatorState& state, const WellState& well_state); void solveIncrement(); double residualNorm() const; double incrementNorm() const; void computeResults(SimulatorState& state, WellState& well_state) const; protected: // ------ Data that will remain unmodified after construction. ------ const UnstructuredGrid& grid_; const IncompPropertiesInterface& props_; const RockCompressibility* rock_comp_props_; const LinearSolverInterface& linsolver_; const double residual_tol_; const double change_tol_; const int maxiter_; const double* gravity_; // May be NULL const Wells* wells_; // May be NULL, outside may modify controls (only) between calls to solve(). const std::vector<double>& src_; const FlowBoundaryConditions* bcs_; std::vector<double> htrans_; std::vector<double> gpress_; std::vector<int> allcells_; // ------ Data that will be modified for every solve. ------ std::vector<double> trans_ ; std::vector<double> wdp_; std::vector<double> totmob_; std::vector<double> omega_; std::vector<double> gpress_omegaweighted_; std::vector<double> initial_porevol_; struct ifs_tpfa_forces forces_; // ------ Data that will be modified for every solver iteration. ------ std::vector<double> porevol_; std::vector<double> rock_comp_; std::vector<double> pressures_; // ------ Internal data for the ifs_tpfa solver. ------ struct ifs_tpfa_data* h_; }; } // namespace Opm #endif // OPM_INCOMPTPFA_HEADER_INCLUDED
jokva/opm-core
opm/core/pressure/IncompTpfa.hpp
C++
gpl-3.0
8,431
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_65) on Thu Feb 05 20:10:13 EST 2015 --> <title>ModDiscoverer (Forge API)</title> <meta name="date" content="2015-02-05"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ModDiscoverer (Forge API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../cpw/mods/fml/common/discovery/ModCandidate.html" title="class in cpw.mods.fml.common.discovery"><span class="strong">Prev Class</span></a></li> <li>Next Class</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?cpw/mods/fml/common/discovery/ModDiscoverer.html" target="_top">Frames</a></li> <li><a href="ModDiscoverer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">cpw.mods.fml.common.discovery</div> <h2 title="Class ModDiscoverer" class="title">Class ModDiscoverer</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>cpw.mods.fml.common.discovery.ModDiscoverer</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="strong">ModDiscoverer</span> extends java.lang.Object</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../../cpw/mods/fml/common/discovery/ModDiscoverer.html#ModDiscoverer()">ModDiscoverer</a></strong>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../cpw/mods/fml/common/discovery/ModDiscoverer.html#findClasspathMods(cpw.mods.fml.common.ModClassLoader)">findClasspathMods</a></strong>(<a href="../../../../../cpw/mods/fml/common/ModClassLoader.html" title="class in cpw.mods.fml.common">ModClassLoader</a>&nbsp;modClassLoader)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../cpw/mods/fml/common/discovery/ModDiscoverer.html#findModDirMods(java.io.File)">findModDirMods</a></strong>(java.io.File&nbsp;modsDir)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../cpw/mods/fml/common/discovery/ASMDataTable.html" title="class in cpw.mods.fml.common.discovery">ASMDataTable</a></code></td> <td class="colLast"><code><strong><a href="../../../../../cpw/mods/fml/common/discovery/ModDiscoverer.html#getASMTable()">getASMTable</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.util.List&lt;java.io.File&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../../cpw/mods/fml/common/discovery/ModDiscoverer.html#getNonModLibs()">getNonModLibs</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.util.List&lt;<a href="../../../../../cpw/mods/fml/common/ModContainer.html" title="interface in cpw.mods.fml.common">ModContainer</a>&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../../cpw/mods/fml/common/discovery/ModDiscoverer.html#identifyMods()">identifyMods</a></strong>()</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="ModDiscoverer()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>ModDiscoverer</h4> <pre>public&nbsp;ModDiscoverer()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="findClasspathMods(cpw.mods.fml.common.ModClassLoader)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>findClasspathMods</h4> <pre>public&nbsp;void&nbsp;findClasspathMods(<a href="../../../../../cpw/mods/fml/common/ModClassLoader.html" title="class in cpw.mods.fml.common">ModClassLoader</a>&nbsp;modClassLoader)</pre> </li> </ul> <a name="findModDirMods(java.io.File)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>findModDirMods</h4> <pre>public&nbsp;void&nbsp;findModDirMods(java.io.File&nbsp;modsDir)</pre> </li> </ul> <a name="identifyMods()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>identifyMods</h4> <pre>public&nbsp;java.util.List&lt;<a href="../../../../../cpw/mods/fml/common/ModContainer.html" title="interface in cpw.mods.fml.common">ModContainer</a>&gt;&nbsp;identifyMods()</pre> </li> </ul> <a name="getASMTable()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getASMTable</h4> <pre>public&nbsp;<a href="../../../../../cpw/mods/fml/common/discovery/ASMDataTable.html" title="class in cpw.mods.fml.common.discovery">ASMDataTable</a>&nbsp;getASMTable()</pre> </li> </ul> <a name="getNonModLibs()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getNonModLibs</h4> <pre>public&nbsp;java.util.List&lt;java.io.File&gt;&nbsp;getNonModLibs()</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../cpw/mods/fml/common/discovery/ModCandidate.html" title="class in cpw.mods.fml.common.discovery"><span class="strong">Prev Class</span></a></li> <li>Next Class</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?cpw/mods/fml/common/discovery/ModDiscoverer.html" target="_top">Frames</a></li> <li><a href="ModDiscoverer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
Foghrye4/ihl
javadoc/cpw/mods/fml/common/discovery/ModDiscoverer.html
HTML
gpl-3.0
10,675
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. use zinc64_core::{Ram, Rom, Shared, SharedCell}; pub struct VicMemory { base_address: SharedCell<u16>, charset: Shared<Rom>, ram: Shared<Ram>, } impl VicMemory { pub fn new(base_address: SharedCell<u16>, charset: Shared<Rom>, ram: Shared<Ram>) -> VicMemory { VicMemory { base_address, charset, ram, } } pub fn read(&self, address: u16) -> u8 { let full_address = self.base_address.get() | address; let zone = full_address >> 12; match zone { 0x01 => self.charset.borrow().read(full_address - 0x1000), 0x09 => self.charset.borrow().read(full_address - 0x9000), _ => self.ram.borrow().read(full_address), } } }
digitalstreamio/zinc64
zinc64-emu/src/video/vic_memory.rs
Rust
gpl-3.0
953
# -*- coding: utf-8 -*- # # Stetl documentation build configuration file, created by # sphinx-quickstart on Sun Jun 2 11:01:36 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # indicate Sphinx is building (to replace @Config decorators) os.environ['SPHINX_BUILD'] = '1' # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) sys.path.insert(0, os.path.abspath('../')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Stetl' copyright = u'2013+, Just van den Broecke' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.2-dev' # The full version, including alpha/beta/rc tags. release = '1.2-dev' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Stetldoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'Stetl.tex', u'Stetl Documentation', u'Just van den Broecke', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'stetl', u'Stetl Documentation', [u'Just van den Broecke'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'Stetl', u'Stetl Documentation', u'Just van den Broecke', 'Stetl', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote'
justb4/stetl
docs/conf.py
Python
gpl-3.0
7,939
<html> <head> <title>Document Browser</title> <link rel='stylesheet' href='./scdoc.css' type='text/css' /> <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /> <script src="docmap.js" type="text/javascript"></script> <script src="scdoc.js" type="text/javascript"></script> <style> .browser { margin: 0em; border-collapse: collapse; margin-top: 1em; } .result { padding: 2px; } .browser td { vertical-align: top; border: none; } .result_doc { border-bottom: 1px solid #ddd; margin-top: 0.5em; } .result_summary { color: #444; font-size: 9pt; max-width: 18em; margin-bottom: 0.6em; } .category, .cat_selected { margin-bottom: 0.25em; border-bottom: 1px solid transparent; } .cat_selected { border-bottom: 1px solid #777; } .cat_header { border-bottom: 2px solid #999; color: #777; /* background: #aaa; color: white;*/ margin-bottom: 0.25em; padding: 2px; /* font-weight: bold;*/ } .category a { color: #555; font-weight: bold; } .cat_selected a { color: #000; font-weight: bold; } .cat_arrow { float: right; padding-left: 1ex; color: #555; } #search_checks { font-size: 9pt; color: #555; border-bottom: 1px solid #ddd; margin-top: 1em; padding-bottom: 1em; } .cat_count { color: #777; font-size: 9pt; } #total_count { font-size: 9pt; color: #777; } .doc_kind { color: #666; float: right; font-size: 8pt; padding: 0 2px; margin-left: 0.5ex; font-weight: bold; } </style> <noscript> <!--<meta http-equiv="refresh" content="3; URL=Overviews/Categories.html"> <p>JavaScript is not available, redirecting to <a href="Overviews/Categories.html">static category overview</a>...--> <p>The document browser needs JavaScript. </noscript> <script type="text/javascript"> var categorytree = null; var path = []; function GotoPath(p) { path = p.split(">"); var x = escape(p); if(window.location.hash != x) window.location.hash = x; updateTree(); } function updateTree() { var el = document.getElementById("browser"); var res = "<tr><td>"; var lev = 0; var tree = {entries:[],subcats:categorytree}; var p; var done = 0; var sel; var colors = { "Classes": "#7ab", "Reference": "#7b9", "Overviews": "#ca6", "Guides": "#b87", "Tutorials": "#b77", }; link = ""; while(1) { res += "<div class='result'>"; p=path[lev++]; var l = []; for(var k in tree.subcats) l.push(k); l = l.sort(); sel = ""; for(var i=0;i<l.length;i++) { var k = l[i]; if(k==p) { res += "<div class='cat_selected'>"; sel = k; } else res += "<div class='category'>"; res += "<a href='javascript:GotoPath(\""+link+k+"\")'>"+k+"</a>"; res += " <span class='cat_count'>("+tree.subcats[k].count+")</span>"; if(k==p) res += "<span class='cat_arrow'> &#9658;</span>"; res += "</div>"; } for(var i=0;i<tree.entries.length;i++) { var v = tree.entries[i]; var x = v.path.split("/"); res += "<div class='result_doc'><span class='doc_kind' "; var clr = colors[x[0]]; if(clr) { res += "style='color:"+clr+";'"; }; res += ">"; if(v.installed=="extension") res += "+"; else if(v.installed=="missing") res += "(not installed) "; var link = v.hasOwnProperty("oldhelp")?v.oldhelp:(v.path+".html"); res += x[0].toUpperCase()+"</span><a href='"+link+"'>"+v.title+"</a></div><div class='result_summary'>"+v.summary+"</div>"; } res += "</div>"; if(!p) break; tree = tree.subcats[p]; link += p+">"; res += "<td>"; res += "<div class='cat_header'>"+sel+"</div>"; if(!tree) { res += "<div class='result_summary'>&#9658; Category not found: "+p+"</div>"; break; } } el.innerHTML = res; } function countTree(t) { var x = 0; for(var k in t.subcats) x += countTree(t.subcats[k]); x += t.entries.length; return t.count = x; } function buildCategoryTree() { var cats = {}; for(var k in docmap) { var v = docmap[k]; if(v.installed=="extension" && !check_extensions.checked) continue; if(filter.value != "all" && v.path.split("/")[0].toLowerCase() != filter.value) continue; var c2 = v.categories.match(/[^, ]+[^,]*[^, ]+/g) || ["Uncategorized"]; for(var i=0;i<c2.length;i++) { var c = c2[i]; if(!cats[c]) cats[c]=[]; cats[c].push(v); } } var tree = {}; var p,l,e,a; for(var cat in cats) { var files = cats[cat]; p=tree; l=cat.split(">"); for(var i=0;i<l.length;i++) { var c = l[i]; if(!p[c]) { p[c]={}; p[c].subcats = {}; p[c].entries = []; p[c].count = 0; } e=p[c]; p=p[c].subcats; } for(var i=0;i<files.length;i++) e.entries.push(files[i]); e.entries = e.entries.sort(function(a,b) { a=a.title; b=b.title; if(a<b) return -1; else if(a>b) return +1; else return 0; }); } categorytree = tree; document.getElementById("total_count").innerHTML = countTree({subcats:tree,entries:[],count:0}) + " documents"; } var check_extensions; var filter; window.onload = function() { // restoreMenu(); helpRoot="."; fixTOC(); var onChange = function() { buildCategoryTree(); updateTree(); }; check_extensions = document.getElementById("check_extensions"); check_extensions.onchange = onChange; filter = document.getElementById("menu_filter"); filter.onchange = onChange; buildCategoryTree(); GotoPath(unescape(window.location.hash.slice(1))); } window.onhashchange = function() { GotoPath(unescape(window.location.hash.slice(1))); } </script> </head> <ul id="menubar"></ul> <body> <div class='contents'> <div class='header'> <div id='label'>SuperCollider</div> <h1>Document Browser</h1> <div id='summary'>Browse categories</div> </div> <div id="search_checks"> Filter: <select id="menu_filter"> <option SELECTED value="all">All documents</option> <option value="classes">Classes only</option> <option value="reference">Reference only</option> <option value="guides">Guides only</option> <option value="tutorials">Tutorials only</option> <option value="overviews">Overviews only</option> <option value="other">Other only</option> </select> <input type="checkbox" id="check_extensions" checked="true">Include extensions</input> </div> <div id="total_count"></div> <table class="browser" id="browser"></table> </div> </body> </html>
wdkk/iSuperColliderKit
HelpSource/Browse.html
HTML
gpl-3.0
7,242
<?php /** * Functions for building the page content for each codex page * * @since 1.0.0 * @package Codex_Creator */ /** * Get and format content output for summary section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_summary_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_summary', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_summary_content', $content, $post_id, $title); } /** * Get and format content output for description section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_description_content($post_id, $title) { $content = ''; //$meta_value = get_post_meta($post_id, 'cdxc_description', true); $meta_value = get_post_meta($post_id, 'cdxc_meta_docblock', true); if (!$meta_value) { return ''; } $phpdoc = new \phpDocumentor\Reflection\DocBlock($meta_value); $line_arr = explode(PHP_EOL, $phpdoc->getLongDescription()->getContents()); $line_arr = array_values(array_filter($line_arr)); if (empty($line_arr)) { return ''; } $sample_open = false; $sample_close = false; foreach ($line_arr as $key=>$line) { //check for code sample opening if($line=='' && substr($line_arr[$key+1], 0, 3) === ' '){// we have found a opening code sample $sample_open = $key+1; } //check for code sample closing if($sample_open && substr($line_arr[$key], 0, 3) === ' '){// we have found a closing code sample $sample_close = $key; } } if ($sample_open && $sample_close) { $line_arr[$sample_open] = CDXC_SAMPLE_OPEN.$line_arr[$sample_open]; $line_arr[$sample_open] = $line_arr[$sample_close].CDXC_SAMPLE_CLOSE; } $meta_value = implode(PHP_EOL, $line_arr); $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_description_content', $content, $post_id, $title); } /** * Get and format content output for usage section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_usage_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_usage', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_usage_content', $content, $post_id, $title); } /** * Get and format content output for access section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_access_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_access', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_access_content', $content, $post_id, $title); } /** * Get and format content output for deprecated section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_deprecated_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_deprecated', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_deprecated_content', $content, $post_id, $title); } /** * Get and format content output for global section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_global_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_global', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; if (is_array($meta_value)) { foreach ($meta_value as $value) { $value = cdxc_global_content_helper($value); $content .= CDXC_CONTENT_START . $value . CDXC_CONTENT_END; } } else { $meta_value = cdxc_global_content_helper($meta_value); $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; } /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_global_content', $content, $post_id, $title); } /** * Arrange a param value into a usable HTML output. * * @since 1.0.0 * @package Codex_Creator * @param string $param The param value to be used. * @return string Formatted HTML on success. */ function cdxc_global_content_helper($param) { if($param==''){return '';} $output = ''; $param_arr = explode(' ',$param); $param_arr = array_values(array_filter($param_arr)); //print_r($param_arr); $output .= '<dl>'; //variable if(!empty($param_arr[1])){ $var = $param_arr[1]; $output .= '<dt><b>'.$var.'</b></dt>'; unset($param_arr[1]); } $output .= '<dd>'; //datatype if(!empty($param_arr[0])){ $datatype = $param_arr[0]; $link_open = ''; $link_close = ''; if($datatype=='string' || $datatype=='String'){ $link_open = '<a href="http://codex.wordpress.org/How_to_Pass_Tag_Parameters#String" target="_blank">'; $link_close = '</a>'; } if($datatype=='int'){ $link_open = '<a href="http://codex.wordpress.org/How_to_Pass_Tag_Parameters#Integer" target="_blank">'; $link_close = '</a>'; } if($datatype=='bool'){ $link_open = '<a href="http://codex.wordpress.org/How_to_Pass_Tag_Parameters#Boolean" target="_blank">'; $link_close = '</a>'; } $output .= '('.$link_open.'<i>'.$datatype.'</i>'.$link_close.') '; unset($param_arr[0]); } //optional $optional = '(<i>'.__('required', CDXC_TEXTDOMAIN).'</i>)'; if(!empty($param_arr[2])){ $opt = $param_arr[2]; if($opt=='Optional.' || $opt=='optional.'){ $optional = '(<i>'.__('optional', CDXC_TEXTDOMAIN).'</i>)'; unset($param_arr[2]); } } $output .= $optional.' '; //we now split into descriptions. $param_str = implode(' ',$param_arr); $param_arr = explode('.',$param_str); $param_arr = array_filter($param_arr); //print_r($param_arr); //description/default $default = '<dl><dd>'.__('Default', CDXC_TEXTDOMAIN).': <i>'.__('None', CDXC_TEXTDOMAIN).'</i></dd></dl>'; foreach ($param_arr as $bit) { $bit = trim($bit); //echo '#'.$bit.'#'; if(substr( $bit, 0, 7) === 'Default'){ $bits = explode('Default',$bit); $default = '<dl><dd>'.__('Default', CDXC_TEXTDOMAIN).': <i>'.$bits[1].'</i></dd></dl>'; }else{ $output .= $bit.'. '; } } $output .= $default; $output .= '</dd>'; $output .= '</dl>'; return $output; } /** * Get and format content output for internal section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_internal_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_internal', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_internal_content', $content, $post_id, $title); } /** * Get and format content output for ignore section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_ignore_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_ignore', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_ignore_content', $content, $post_id, $title); } /** * Get and format content output for link section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_link_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_link', true); if (!$meta_value) { return; } /* * @todo add checking for parsing links */ $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START ."<a href='$meta_value' >".$meta_value . "</a>".CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_link_content', $content, $post_id, $title); } /** * Get and format content output for method section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_method_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_method', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_method_content', $content, $post_id, $title); } /** * Get and format content output for package section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_package_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_package', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_package_content', $content, $post_id, $title); } /** * Get and format content output for param section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_param_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_param', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; if (is_array($meta_value)) { foreach ($meta_value as $value) { $value = cdxc_param_content_helper($value); $content .= CDXC_CONTENT_START . $value . CDXC_CONTENT_END; } } else { $meta_value = cdxc_param_content_helper($meta_value); $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; } /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_param_content', $content, $post_id, $title); } /** * Arrange a param value into a usable HTML output. * * @since 1.0.0 * @package Codex_Creator * @param string $param The param value to be used. * @return string Formatted HTML on success. */ function cdxc_param_content_helper($param) { if($param==''){return '';} $output = ''; $param_arr = explode(' ',$param); $param_arr = array_values(array_filter($param_arr)); //print_r($param_arr); $output .= '<dl>'; //variable if(!empty($param_arr[1])){ $var = $param_arr[1]; $output .= '<dt><b>'.$var.'</b></dt>'; unset($param_arr[1]); } $output .= '<dd>'; //datatype if(!empty($param_arr[0])){ $datatype = $param_arr[0]; $link_open = ''; $link_close = ''; if($datatype=='string' || $datatype=='String'){ $link_open = '<a href="http://codex.wordpress.org/How_to_Pass_Tag_Parameters#String" target="_blank">'; $link_close = '</a>'; } if($datatype=='int'){ $link_open = '<a href="http://codex.wordpress.org/How_to_Pass_Tag_Parameters#Integer" target="_blank">'; $link_close = '</a>'; } if($datatype=='bool'){ $link_open = '<a href="http://codex.wordpress.org/How_to_Pass_Tag_Parameters#Boolean" target="_blank">'; $link_close = '</a>'; } $output .= '('.$link_open.'<i>'.$datatype.'</i>'.$link_close.') '; unset($param_arr[0]); } //optional $optional = '(<i>'.__('required', CDXC_TEXTDOMAIN).'</i>)'; if(!empty($param_arr[2])){ $opt = $param_arr[2]; if($opt=='Optional.' || $opt=='optional.'){ $optional = '(<i>'.__('optional', CDXC_TEXTDOMAIN).'</i>)'; unset($param_arr[2]); } } $output .= $optional.' '; //we now split into descriptions. $param_str = implode(' ',$param_arr); $param_arr = explode('.',$param_str); $param_arr = array_filter($param_arr); //print_r($param_arr); //description/default $default = '<dl><dd>'.__('Default', CDXC_TEXTDOMAIN).': <i>'.__('None', CDXC_TEXTDOMAIN).'</i></dd></dl>'; foreach ($param_arr as $bit) { $bit = trim($bit); //echo '#'.$bit.'#'; if(substr( $bit, 0, 7) === 'Default'){ $bits = explode('Default',$bit); $default = '<dl><dd>'.__('Default', CDXC_TEXTDOMAIN).': <i>'.$bits[1].'</i></dd></dl>'; }else{ $output .= $bit.'. '; } } $output .= $default; $output .= '</dd>'; $output .= '</dl>'; return $output; } /** * Get and format content output for example section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_example_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_example', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_example_content', $content, $post_id, $title); } /** * Get and format content output for return section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_return_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_return', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $meta_value = cdxc_return_content_helper($meta_value); $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_return_content', $content, $post_id, $title); } /** * Arrange a return value into a usable HTML output. * * @since 1.0.0 * @package Codex_Creator * @param string $value The string value to be used. * @return string Formatted HTML on success. */ function cdxc_return_content_helper($value) { if($value==''){return '';} $output = ''; $param_arr = explode(' ',$value); $param_arr = array_values(array_filter($param_arr)); //print_r($param_arr); $output .= '<dl>'; //datatype if(!empty($param_arr[0])){ $datatype = $param_arr[0]; $link_open = ''; $link_close = ''; if($datatype=='string' || $datatype=='String'){ $link_open = '<a href="http://codex.wordpress.org/How_to_Pass_Tag_Parameters#String" target="_blank">'; $link_close = '</a>'; } if($datatype=='int'){ $link_open = '<a href="http://codex.wordpress.org/How_to_Pass_Tag_Parameters#Integer" target="_blank">'; $link_close = '</a>'; } if($datatype=='bool'){ $link_open = '<a href="http://codex.wordpress.org/How_to_Pass_Tag_Parameters#Boolean" target="_blank">'; $link_close = '</a>'; } $output .= '<dt><b>('.$link_open.'<i>'.$datatype.'</i>'.$link_close.')</b></dt>'; unset($param_arr[0]); } $output .= '<ul>'; //we now split into descriptions. $param_str = implode(' ',$param_arr); $param_arr = explode('.',$param_str); $param_arr = array_filter($param_arr); //print_r($param_arr); //description/default foreach ($param_arr as $bit) { $bit = trim($bit); $output .= '<li>'.$bit.'. </li>'; } $output .= '</ul>'; $output .= '</dl>'; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return $output; } /** * Get and format content output for see section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_see_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_see', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; if (is_array($meta_value)) { foreach ($meta_value as $value) { $value = cdxc_see_content_helper($value); $content .= CDXC_CONTENT_START . $value . CDXC_CONTENT_END; } } else { $meta_value = cdxc_see_content_helper($meta_value); $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; } /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_see_content', $content, $post_id, $title); } /** * Arrange a see value into a usable HTML output. * * @since 1.0.0 * @package Codex_Creator * @param string $value The string value to be used. * @return string Formatted HTML on success. * @todo make this format URL's. */ function cdxc_see_content_helper($text) { if ($text == '') { return ''; } if (strpos($text,'"') !== false || strpos($text,"'") !== false) {// we have a hook $new_text = str_replace(array('"',"'"),'',$text); $page = get_page_by_title($new_text, OBJECT, 'codex_creator'); if($page) { $link = get_permalink($page->ID); $text = "<a href='$link' >$text</a>"; } }elseif(strpos($text,'()') !== false){ $new_text = str_replace('()','',$text); $page = get_page_by_title($new_text, OBJECT, 'codex_creator'); if($page) { $link = get_permalink($page->ID); $text = "<a href='$link' >$text</a>"; } } return $text; } /** * Get and format content output for since section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_since_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_since', true); if (!$meta_value) { return; } if (is_array($meta_value) && empty($meta_value)) { return false; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $tags = array(); if (is_array($meta_value)) { $i=0; foreach ($meta_value as $value) { if($i==0){$since = __('Since', CDXC_TEXTDOMAIN).': ';}else{$since='';} if ($pieces = explode(" ", $value)) { $ver = $pieces[0]; unset($pieces[0]); $text = join(' ', $pieces); $content .= CDXC_CONTENT_START .$since. '<a href="%' . $ver . '%">' . $ver . '</a>' . ' ' . $text . CDXC_CONTENT_END; $tags[] = $ver; } else { $content .= CDXC_CONTENT_START . '<a href="%' . $value . '%">' . $value . '</a>' . CDXC_CONTENT_END; $tags[] = $value; } $i++; } } else { $content .= CDXC_CONTENT_START .__('Since', CDXC_TEXTDOMAIN). ': <a href="%' . $meta_value . '%">' . $meta_value . '</a>' . CDXC_CONTENT_END; $tags[] = $meta_value; } // get the project slug $project_slug = 'project-not-found'; $project_terms = wp_get_object_terms($post_id, 'codex_project'); if (!is_wp_error($project_terms) && !empty($project_terms) && is_object($project_terms[0])) { foreach ($project_terms as $p_term) { if ($p_term->parent == '0') { $project_slug = $p_term->slug; } } } //set all tags to have prefix of the project $alt_tags = array(); foreach ($tags as $temp_tag) { $alt_tags[] = $project_slug . '_' . $temp_tag; } $tags = $alt_tags; $tags_arr = wp_set_post_terms($post_id, $tags, 'codex_tags', false); //print_r($tags_arr);//exit; if (is_array($tags_arr)) { foreach ($tags_arr as $key => $tag_id) { //$term = get_term($tag_id, 'codex_tags'); $term = get_term_by('term_taxonomy_id', $tag_id, 'codex_tags'); $tag_link = get_term_link($term, 'codex_tags'); $orig_ver = str_replace($project_slug . '_', '', $tags[$key]); $content = str_replace('%' . $orig_ver . '%', $tag_link, $content); } } // print_r($tags_arr);exit; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_since_content', $content, $post_id, $title); } /** * Get and format content output for subpackage section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_subpackage_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_subpackage', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_subpackage_content', $content, $post_id, $title); } /** * Get and format content output for todo section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_todo_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_todo', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_todo_content', $content, $post_id, $title); } /** * Get and format content output for type section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_type_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_type', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_type_content', $content, $post_id, $title); } /** * Get and format content output for uses section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_uses_content($post_id, $title) { return;// @todo make this work with arrays. $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_uses', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_uses_content', $content, $post_id, $title); } /** * Get and format content output for var section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_var_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_var', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_var_content', $content, $post_id, $title); } /** * Get and format content output for functions section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_functions_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_meta_functions', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; //$content .= CDXC_CONTENT_START.$meta_value.CDXC_CONTENT_END; if (is_array($meta_value)) { foreach ($meta_value as $func) { $func_arr = get_page_by_title($func[1], OBJECT, 'codex_creator'); // print_r($func_arr);exit; if (is_object($func_arr)) { $link = get_permalink($func_arr->ID); $content .= CDXC_CONTENT_START . '<a href="' . $link . '">' . $func[1] . '()</a> [' . __('Line', CDXC_TEXTDOMAIN) . ': ' . $func[2] . ']' . CDXC_CONTENT_END; } else { $content .= CDXC_CONTENT_START . $func[1] . '() [' . __('Line', CDXC_TEXTDOMAIN) . ': ' . $func[2] . ']' . CDXC_CONTENT_END; } } } //$content .= CDXC_CONTENT_START.print_r($meta_value,true).CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_functions_content', $content, $post_id, $title); } /** * Get and format content output for actions section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_actions_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_meta_actions', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; if (is_array($meta_value)) { foreach ($meta_value as $func) { $func_arr = get_page_by_title($func[1], OBJECT, 'codex_creator'); //print_r($func_arr);exit; $name = "'".$func[1]."'"; if (is_object($func_arr)) { $link = get_permalink($func_arr->ID); $content .= CDXC_CONTENT_START . '<a href="' . $link . '">' . $name . ' </a> [' . __('Line', CDXC_TEXTDOMAIN) . ': ' . $func[2] . ']' . CDXC_CONTENT_END; } else { $content .= CDXC_CONTENT_START . $name . ' [' . __('Line', CDXC_TEXTDOMAIN) . ': ' . $func[2] . ']' . CDXC_CONTENT_END; } } } //$content .= CDXC_CONTENT_START.print_r($meta_value,true).CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_actions_content', $content, $post_id, $title); } /** * Get and format content output for filters section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_filters_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_meta_filters', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; if (is_array($meta_value)) { foreach ($meta_value as $func) { $func_arr = get_page_by_title($func[1], OBJECT, 'codex_creator'); // print_r($func_arr);exit; $name = "'".$func[1]."'"; if (is_object($func_arr)) { $link = get_permalink($func_arr->ID); $content .= CDXC_CONTENT_START . '<a href="' . $link . '">' . $name . ' </a> [' . __('Line', CDXC_TEXTDOMAIN) . ': ' . $func[2] . ']' . CDXC_CONTENT_END; } else { $content .= CDXC_CONTENT_START . $name . ' [' . __('Line', CDXC_TEXTDOMAIN) . ': ' . $func[2] . ']' . CDXC_CONTENT_END; } } } //$content .= CDXC_CONTENT_START.print_r($meta_value,true).CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_filters_content', $content, $post_id, $title); } /** * Get and format content output for location section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_location_content($post_id, $title) { $content = ''; $meta_type = get_post_meta($post_id, 'cdxc_meta_type', true); if ($meta_type == 'file' || $meta_type == 'action' || $meta_type == 'filter') { return false; } $meta_value = get_post_meta($post_id, 'cdxc_meta_path', true); if (!$meta_value) { return; } $line = get_post_meta($post_id, 'cdxc_meta_line', true); $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $file_name = basename($meta_value); $func_arr = get_post($post_id); $func_name = $func_arr->post_title; if($meta_type=='function'){ $func_name_n = $func_name. '() '; }else{ $func_name_n = "'".$func_name. "' "; } $file_arr = get_page_by_title($file_name, OBJECT, 'codex_creator'); if (is_object($file_arr)) { $link = get_permalink($file_arr->ID); $content .= CDXC_CONTENT_START .$func_name_n . __('is located in', CDXC_TEXTDOMAIN) . ' <a href="' . $link . '">' . $meta_value . '</a> [' . __('Line', CDXC_TEXTDOMAIN) . ': ' . $line . ']' . CDXC_CONTENT_END; } else { $content .= CDXC_CONTENT_START . $func_name_n . __('is located in', CDXC_TEXTDOMAIN) . ' ' . $meta_value . ' [' . __('Line', CDXC_TEXTDOMAIN) . ': ' . $line . ']' . CDXC_CONTENT_END; } /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_location_content', $content, $post_id, $title); } /** * Get and format content output for source code section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_code_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_meta_code', true); if (!$meta_value) { return; } $meta_value = "%%CDXC_SRC_CODE%%"; $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; //$content .= CDXC_PHP_CODE_START . $meta_value . CDXC_PHP_CODE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_code_content', $content, $post_id, $title); } /** * Get and format content output for filters section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_used_by_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_meta_used_by', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; if (is_array($meta_value)) { foreach ($meta_value as $func) { $func_arr = get_page_by_title($func['function_name'], OBJECT, 'codex_creator'); // print_r($func_arr);exit; $name = ''; if($func['function_name']){ $name = "".$func['function_name']."()"; } if (is_object($func_arr)) { $link = get_permalink($func_arr->ID); $content .= CDXC_CONTENT_START . $func['file_path'].': <a href="' . $link . '">' . $name . ' </a> [' . __('Line', CDXC_TEXTDOMAIN) . ': ' . $func['hook_line'] . ']' . CDXC_CONTENT_END; } else { $content .= CDXC_CONTENT_START .$func['file_path'].': '. $name . ' [' . __('Line', CDXC_TEXTDOMAIN) . ': ' . $func['hook_line'] . ']' . CDXC_CONTENT_END; } } } //$content .= CDXC_CONTENT_START.print_r($meta_value,true).CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_used_by_content', $content, $post_id, $title); }
NomadDevs/codex_creator
lib/content_output_functions.php
PHP
gpl-3.0
41,482
/******************************************************************************* * Copyright 2010 Olaf Sebelin * * This file is part of Verdandi. * * Verdandi is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Verdandi 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 Verdandi. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package verdandi; /** * * @ */ public class InvalidIntervalException extends Exception { /** * */ private static final long serialVersionUID = 1L; /** * */ public InvalidIntervalException() { super(); } /** * @param message */ public InvalidIntervalException(String message) { super(message); } }
osebelin/verdandi
src/main/java/verdandi/InvalidIntervalException.java
Java
gpl-3.0
1,220
/* * sound/oss/ad1848.c * * The low level driver for the AD1848/CS4248 codec chip which * is used for example in the MS Sound System. * * The CS4231 which is used in the GUS MAX and some other cards is * upwards compatible with AD1848 and this driver is able to drive it. * * CS4231A and AD1845 are upward compatible with CS4231. However * the new features of these chips are different. * * CS4232 is a PnP audio chip which contains a CS4231A (and SB, MPU). * CS4232A is an improved version of CS4232. * * * * Copyright (C) by Hannu Savolainen 1993-1997 * * OSS/Free for Linux is distributed under the GNU GENERAL PUBLIC LICENSE (GPL) * Version 2 (June 1991). See the "COPYING" file distributed with this software * for more info. * * * Thomas Sailer : ioctl code reworked (vmalloc/vfree removed) * general sleep/wakeup clean up. * Alan Cox : reformatted. Fixed SMP bugs. Moved to kernel alloc/free * of irqs. Use dev_id. * Christoph Hellwig : adapted to module_init/module_exit * Aki Laukkanen : added power management support * Arnaldo C. de Melo : added missing restore_flags in ad1848_resume * Miguel Freitas : added ISA PnP support * Alan Cox : Added CS4236->4239 identification * Daniel T. Cobra : Alernate config/mixer for later chips * Alan Cox : Merged chip idents and config code * * TODO * APM save restore assist code on IBM thinkpad * * Status: * Tested. Believed fully functional. */ #include <linux/init.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/stddef.h> #include <linux/slab.h> #include <linux/isapnp.h> #include <linux/pnp.h> #include <linux/spinlock.h> #include "sound_config.h" #include "ad1848.h" #include "ad1848_mixer.h" typedef struct { spinlock_t lock; int base; int irq; int dma1, dma2; int dual_dma; /* 1, when two DMA channels allocated */ int subtype; unsigned char MCE_bit; unsigned char saved_regs[64]; /* Includes extended register space */ int debug_flag; int audio_flags; int record_dev, playback_dev; int xfer_count; int audio_mode; int open_mode; int intr_active; char *chip_name, *name; int model; #define MD_1848 1 #define MD_4231 2 #define MD_4231A 3 #define MD_1845 4 #define MD_4232 5 #define MD_C930 6 #define MD_IWAVE 7 #define MD_4235 8 /* Crystal Audio CS4235 */ #define MD_1845_SSCAPE 9 /* Ensoniq Soundscape PNP*/ #define MD_4236 10 /* 4236 and higher */ #define MD_42xB 11 /* CS 42xB */ #define MD_4239 12 /* CS4239 */ /* Mixer parameters */ int recmask; int supported_devices, orig_devices; int supported_rec_devices, orig_rec_devices; int *levels; short mixer_reroute[32]; int dev_no; volatile unsigned long timer_ticks; int timer_running; int irq_ok; mixer_ents *mix_devices; int mixer_output_port; } ad1848_info; typedef struct ad1848_port_info { int open_mode; int speed; unsigned char speed_bits; int channels; int audio_format; unsigned char format_bits; } ad1848_port_info; static struct address_info cfg; static int nr_ad1848_devs; static bool deskpro_xl; static bool deskpro_m; static bool soundpro; static volatile signed char irq2dev[17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; #ifndef EXCLUDE_TIMERS static int timer_installed = -1; #endif static int loaded; static int ad_format_mask[13 /*devc->model */ ] = { 0, AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW, AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM, AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM, AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW, /* AD1845 */ AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM, AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM, AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM, AFMT_U8 | AFMT_S16_LE /* CS4235 */, AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW /* Ensoniq Soundscape*/, AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM, AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM, AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM }; static ad1848_info adev_info[MAX_AUDIO_DEV]; #define io_Index_Addr(d) ((d)->base) #define io_Indexed_Data(d) ((d)->base+1) #define io_Status(d) ((d)->base+2) #define io_Polled_IO(d) ((d)->base+3) static struct { unsigned char flags; #define CAP_F_TIMER 0x01 } capabilities [10 /*devc->model */ ] = { {0} , {0} /* MD_1848 */ , {CAP_F_TIMER} /* MD_4231 */ , {CAP_F_TIMER} /* MD_4231A */ , {CAP_F_TIMER} /* MD_1845 */ , {CAP_F_TIMER} /* MD_4232 */ , {0} /* MD_C930 */ , {CAP_F_TIMER} /* MD_IWAVE */ , {0} /* MD_4235 */ , {CAP_F_TIMER} /* MD_1845_SSCAPE */ }; #ifdef CONFIG_PNP static int isapnp = 1; static int isapnpjump; static bool reverse; static int audio_activated; #else static int isapnp; #endif static int ad1848_open(int dev, int mode); static void ad1848_close(int dev); static void ad1848_output_block(int dev, unsigned long buf, int count, int intrflag); static void ad1848_start_input(int dev, unsigned long buf, int count, int intrflag); static int ad1848_prepare_for_output(int dev, int bsize, int bcount); static int ad1848_prepare_for_input(int dev, int bsize, int bcount); static void ad1848_halt(int dev); static void ad1848_halt_input(int dev); static void ad1848_halt_output(int dev); static void ad1848_trigger(int dev, int bits); static irqreturn_t adintr(int irq, void *dev_id); #ifndef EXCLUDE_TIMERS static int ad1848_tmr_install(int dev); static void ad1848_tmr_reprogram(int dev); #endif static int ad_read(ad1848_info *devc, int reg) { int x; int timeout = 900000; while (timeout > 0 && inb(devc->base) == 0x80) /*Are we initializing */ { timeout--; } if (reg < 32) { outb(((unsigned char) (reg & 0xff) | devc->MCE_bit), io_Index_Addr(devc)); x = inb(io_Indexed_Data(devc)); } else { int xreg, xra; xreg = (reg & 0xff) - 32; xra = (((xreg & 0x0f) << 4) & 0xf0) | 0x08 | ((xreg & 0x10) >> 2); outb(((unsigned char) (23 & 0xff) | devc->MCE_bit), io_Index_Addr(devc)); outb(((unsigned char) (xra & 0xff)), io_Indexed_Data(devc)); x = inb(io_Indexed_Data(devc)); } return x; } static void ad_write(ad1848_info *devc, int reg, int data) { int timeout = 900000; while (timeout > 0 && inb(devc->base) == 0x80) /* Are we initializing */ { timeout--; } if (reg < 32) { outb(((unsigned char) (reg & 0xff) | devc->MCE_bit), io_Index_Addr(devc)); outb(((unsigned char) (data & 0xff)), io_Indexed_Data(devc)); } else { int xreg, xra; xreg = (reg & 0xff) - 32; xra = (((xreg & 0x0f) << 4) & 0xf0) | 0x08 | ((xreg & 0x10) >> 2); outb(((unsigned char) (23 & 0xff) | devc->MCE_bit), io_Index_Addr(devc)); outb(((unsigned char) (xra & 0xff)), io_Indexed_Data(devc)); outb((unsigned char) (data & 0xff), io_Indexed_Data(devc)); } } static void wait_for_calibration(ad1848_info *devc) { int timeout; /* * Wait until the auto calibration process has finished. * * 1) Wait until the chip becomes ready (reads don't return 0x80). * 2) Wait until the ACI bit of I11 gets on and then off. */ timeout = 100000; while (timeout > 0 && inb(devc->base) == 0x80) { timeout--; } if (inb(devc->base) & 0x80) { printk(KERN_WARNING "ad1848: Auto calibration timed out(1).\n"); } timeout = 100; while (timeout > 0 && !(ad_read(devc, 11) & 0x20)) { timeout--; } if (!(ad_read(devc, 11) & 0x20)) { return; } timeout = 80000; while (timeout > 0 && (ad_read(devc, 11) & 0x20)) { timeout--; } if (ad_read(devc, 11) & 0x20) if ((devc->model != MD_1845) && (devc->model != MD_1845_SSCAPE)) { printk(KERN_WARNING "ad1848: Auto calibration timed out(3).\n"); } } static void ad_mute(ad1848_info *devc) { int i; unsigned char prev; /* * Save old register settings and mute output channels */ for (i = 6; i < 8; i++) { prev = devc->saved_regs[i] = ad_read(devc, i); } } static void ad_unmute(ad1848_info *devc) { } static void ad_enter_MCE(ad1848_info *devc) { int timeout = 1000; unsigned short prev; while (timeout > 0 && inb(devc->base) == 0x80) /*Are we initializing */ { timeout--; } devc->MCE_bit = 0x40; prev = inb(io_Index_Addr(devc)); if (prev & 0x40) { return; } outb((devc->MCE_bit), io_Index_Addr(devc)); } static void ad_leave_MCE(ad1848_info *devc) { unsigned char prev, acal; int timeout = 1000; while (timeout > 0 && inb(devc->base) == 0x80) /*Are we initializing */ { timeout--; } acal = ad_read(devc, 9); devc->MCE_bit = 0x00; prev = inb(io_Index_Addr(devc)); outb((0x00), io_Index_Addr(devc)); /* Clear the MCE bit */ if ((prev & 0x40) == 0) /* Not in MCE mode */ { return; } outb((0x00), io_Index_Addr(devc)); /* Clear the MCE bit */ if (acal & 0x08) /* Auto calibration is enabled */ { wait_for_calibration(devc); } } static int ad1848_set_recmask(ad1848_info *devc, int mask) { unsigned char recdev; int i, n; unsigned long flags; mask &= devc->supported_rec_devices; /* Rename the mixer bits if necessary */ for (i = 0; i < 32; i++) { if (devc->mixer_reroute[i] != i) { if (mask & (1 << i)) { mask &= ~(1 << i); mask |= (1 << devc->mixer_reroute[i]); } } } n = 0; for (i = 0; i < 32; i++) /* Count selected device bits */ if (mask & (1 << i)) { n++; } spin_lock_irqsave(&devc->lock, flags); if (!soundpro) { if (n == 0) { mask = SOUND_MASK_MIC; } else if (n != 1) /* Too many devices selected */ { mask &= ~devc->recmask; /* Filter out active settings */ n = 0; for (i = 0; i < 32; i++) /* Count selected device bits */ if (mask & (1 << i)) { n++; } if (n != 1) { mask = SOUND_MASK_MIC; } } switch (mask) { case SOUND_MASK_MIC: recdev = 2; break; case SOUND_MASK_LINE: case SOUND_MASK_LINE3: recdev = 0; break; case SOUND_MASK_CD: case SOUND_MASK_LINE1: recdev = 1; break; case SOUND_MASK_IMIX: recdev = 3; break; default: mask = SOUND_MASK_MIC; recdev = 2; } recdev <<= 6; ad_write(devc, 0, (ad_read(devc, 0) & 0x3f) | recdev); ad_write(devc, 1, (ad_read(devc, 1) & 0x3f) | recdev); } else /* soundpro */ { unsigned char val; int set_rec_bit; int j; for (i = 0; i < 32; i++) /* For each bit */ { if ((devc->supported_rec_devices & (1 << i)) == 0) { continue; /* Device not supported */ } for (j = LEFT_CHN; j <= RIGHT_CHN; j++) { if (devc->mix_devices[i][j].nbits == 0) /* Inexistent channel */ { continue; } /* * This is tricky: * set_rec_bit becomes 1 if the corresponding bit in mask is set * then it gets flipped if the polarity is inverse */ set_rec_bit = ((mask & (1 << i)) != 0) ^ devc->mix_devices[i][j].recpol; val = ad_read(devc, devc->mix_devices[i][j].recreg); val &= ~(1 << devc->mix_devices[i][j].recpos); val |= (set_rec_bit << devc->mix_devices[i][j].recpos); ad_write(devc, devc->mix_devices[i][j].recreg, val); } } } spin_unlock_irqrestore(&devc->lock, flags); /* Rename the mixer bits back if necessary */ for (i = 0; i < 32; i++) { if (devc->mixer_reroute[i] != i) { if (mask & (1 << devc->mixer_reroute[i])) { mask &= ~(1 << devc->mixer_reroute[i]); mask |= (1 << i); } } } devc->recmask = mask; return mask; } static void oss_change_bits(ad1848_info *devc, unsigned char *regval, unsigned char *muteval, int dev, int chn, int newval) { unsigned char mask; int shift; int mute; int mutemask; int set_mute_bit; set_mute_bit = (newval == 0) ^ devc->mix_devices[dev][chn].mutepol; if (devc->mix_devices[dev][chn].polarity == 1) /* Reverse */ { newval = 100 - newval; } mask = (1 << devc->mix_devices[dev][chn].nbits) - 1; shift = devc->mix_devices[dev][chn].bitpos; if (devc->mix_devices[dev][chn].mutepos == 8) { /* if there is no mute bit */ mute = 0; /* No mute bit; do nothing special */ mutemask = ~0; /* No mute bit; do nothing special */ } else { mute = (set_mute_bit << devc->mix_devices[dev][chn].mutepos); mutemask = ~(1 << devc->mix_devices[dev][chn].mutepos); } newval = (int) ((newval * mask) + 50) / 100; /* Scale it */ *regval &= ~(mask << shift); /* Clear bits */ *regval |= (newval & mask) << shift; /* Set new value */ *muteval &= mutemask; *muteval |= mute; } static int ad1848_mixer_get(ad1848_info *devc, int dev) { if (!((1 << dev) & devc->supported_devices)) { return -EINVAL; } dev = devc->mixer_reroute[dev]; return devc->levels[dev]; } static void ad1848_mixer_set_channel(ad1848_info *devc, int dev, int value, int channel) { int regoffs, muteregoffs; unsigned char val, muteval; unsigned long flags; regoffs = devc->mix_devices[dev][channel].regno; muteregoffs = devc->mix_devices[dev][channel].mutereg; val = ad_read(devc, regoffs); if (muteregoffs != regoffs) { muteval = ad_read(devc, muteregoffs); oss_change_bits(devc, &val, &muteval, dev, channel, value); } else { oss_change_bits(devc, &val, &val, dev, channel, value); } spin_lock_irqsave(&devc->lock, flags); ad_write(devc, regoffs, val); devc->saved_regs[regoffs] = val; if (muteregoffs != regoffs) { ad_write(devc, muteregoffs, muteval); devc->saved_regs[muteregoffs] = muteval; } spin_unlock_irqrestore(&devc->lock, flags); } static int ad1848_mixer_set(ad1848_info *devc, int dev, int value) { int left = value & 0x000000ff; int right = (value & 0x0000ff00) >> 8; int retvol; if (dev > 31) { return -EINVAL; } if (!(devc->supported_devices & (1 << dev))) { return -EINVAL; } dev = devc->mixer_reroute[dev]; if (devc->mix_devices[dev][LEFT_CHN].nbits == 0) { return -EINVAL; } if (left > 100) { left = 100; } if (right > 100) { right = 100; } if (devc->mix_devices[dev][RIGHT_CHN].nbits == 0) /* Mono control */ { right = left; } retvol = left | (right << 8); /* Scale volumes */ left = mix_cvt[left]; right = mix_cvt[right]; devc->levels[dev] = retvol; /* * Set the left channel */ ad1848_mixer_set_channel(devc, dev, left, LEFT_CHN); /* * Set the right channel */ if (devc->mix_devices[dev][RIGHT_CHN].nbits == 0) { goto out; } ad1848_mixer_set_channel(devc, dev, right, RIGHT_CHN); out: return retvol; } static void ad1848_mixer_reset(ad1848_info *devc) { int i; char name[32]; unsigned long flags; devc->mix_devices = &(ad1848_mix_devices[0]); sprintf(name, "%s_%d", devc->chip_name, nr_ad1848_devs); for (i = 0; i < 32; i++) { devc->mixer_reroute[i] = i; } devc->supported_rec_devices = MODE1_REC_DEVICES; switch (devc->model) { case MD_4231: case MD_4231A: case MD_1845: case MD_1845_SSCAPE: devc->supported_devices = MODE2_MIXER_DEVICES; break; case MD_C930: devc->supported_devices = C930_MIXER_DEVICES; devc->mix_devices = &(c930_mix_devices[0]); break; case MD_IWAVE: devc->supported_devices = MODE3_MIXER_DEVICES; devc->mix_devices = &(iwave_mix_devices[0]); break; case MD_42xB: case MD_4239: devc->mix_devices = &(cs42xb_mix_devices[0]); devc->supported_devices = MODE3_MIXER_DEVICES; break; case MD_4232: case MD_4235: case MD_4236: devc->supported_devices = MODE3_MIXER_DEVICES; break; case MD_1848: if (soundpro) { devc->supported_devices = SPRO_MIXER_DEVICES; devc->supported_rec_devices = SPRO_REC_DEVICES; devc->mix_devices = &(spro_mix_devices[0]); break; } default: devc->supported_devices = MODE1_MIXER_DEVICES; } devc->orig_devices = devc->supported_devices; devc->orig_rec_devices = devc->supported_rec_devices; devc->levels = load_mixer_volumes(name, default_mixer_levels, 1); for (i = 0; i < SOUND_MIXER_NRDEVICES; i++) { if (devc->supported_devices & (1 << i)) { ad1848_mixer_set(devc, i, devc->levels[i]); } } ad1848_set_recmask(devc, SOUND_MASK_MIC); devc->mixer_output_port = devc->levels[31] | AUDIO_HEADPHONE | AUDIO_LINE_OUT; spin_lock_irqsave(&devc->lock, flags); if (!soundpro) { if (devc->mixer_output_port & AUDIO_SPEAKER) { ad_write(devc, 26, ad_read(devc, 26) & ~0x40); /* Unmute mono out */ } else { ad_write(devc, 26, ad_read(devc, 26) | 0x40); /* Mute mono out */ } } else { /* * From the "wouldn't it be nice if the mixer API had (better) * support for custom stuff" category */ /* Enable surround mode and SB16 mixer */ ad_write(devc, 16, 0x60); } spin_unlock_irqrestore(&devc->lock, flags); } static int ad1848_mixer_ioctl(int dev, unsigned int cmd, void __user *arg) { ad1848_info *devc = mixer_devs[dev]->devc; int val; if (cmd == SOUND_MIXER_PRIVATE1) { if (get_user(val, (int __user *)arg)) { return -EFAULT; } if (val != 0xffff) { unsigned long flags; val &= (AUDIO_SPEAKER | AUDIO_HEADPHONE | AUDIO_LINE_OUT); devc->mixer_output_port = val; val |= AUDIO_HEADPHONE | AUDIO_LINE_OUT; /* Always on */ devc->mixer_output_port = val; spin_lock_irqsave(&devc->lock, flags); if (val & AUDIO_SPEAKER) { ad_write(devc, 26, ad_read(devc, 26) & ~0x40); /* Unmute mono out */ } else { ad_write(devc, 26, ad_read(devc, 26) | 0x40); /* Mute mono out */ } spin_unlock_irqrestore(&devc->lock, flags); } val = devc->mixer_output_port; return put_user(val, (int __user *)arg); } if (cmd == SOUND_MIXER_PRIVATE2) { if (get_user(val, (int __user *)arg)) { return -EFAULT; } return (ad1848_control(AD1848_MIXER_REROUTE, val)); } if (((cmd >> 8) & 0xff) == 'M') { if (_SIOC_DIR(cmd) & _SIOC_WRITE) { switch (cmd & 0xff) { case SOUND_MIXER_RECSRC: if (get_user(val, (int __user *)arg)) { return -EFAULT; } val = ad1848_set_recmask(devc, val); break; default: if (get_user(val, (int __user *)arg)) { return -EFAULT; } val = ad1848_mixer_set(devc, cmd & 0xff, val); break; } return put_user(val, (int __user *)arg); } else { switch (cmd & 0xff) { /* * Return parameters */ case SOUND_MIXER_RECSRC: val = devc->recmask; break; case SOUND_MIXER_DEVMASK: val = devc->supported_devices; break; case SOUND_MIXER_STEREODEVS: val = devc->supported_devices; if (devc->model != MD_C930) { val &= ~(SOUND_MASK_SPEAKER | SOUND_MASK_IMIX); } break; case SOUND_MIXER_RECMASK: val = devc->supported_rec_devices; break; case SOUND_MIXER_CAPS: val = SOUND_CAP_EXCL_INPUT; break; default: val = ad1848_mixer_get(devc, cmd & 0xff); break; } return put_user(val, (int __user *)arg); } } else { return -EINVAL; } } static int ad1848_set_speed(int dev, int arg) { ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc; /* * The sampling speed is encoded in the least significant nibble of I8. The * LSB selects the clock source (0=24.576 MHz, 1=16.9344 MHz) and other * three bits select the divisor (indirectly): * * The available speeds are in the following table. Keep the speeds in * the increasing order. */ typedef struct { int speed; unsigned char bits; } speed_struct; static speed_struct speed_table[] = { {5510, (0 << 1) | 1}, {5510, (0 << 1) | 1}, {6620, (7 << 1) | 1}, {8000, (0 << 1) | 0}, {9600, (7 << 1) | 0}, {11025, (1 << 1) | 1}, {16000, (1 << 1) | 0}, {18900, (2 << 1) | 1}, {22050, (3 << 1) | 1}, {27420, (2 << 1) | 0}, {32000, (3 << 1) | 0}, {33075, (6 << 1) | 1}, {37800, (4 << 1) | 1}, {44100, (5 << 1) | 1}, {48000, (6 << 1) | 0} }; int i, n, selected = -1; n = sizeof(speed_table) / sizeof(speed_struct); if (arg <= 0) { return portc->speed; } if (devc->model == MD_1845 || devc->model == MD_1845_SSCAPE) /* AD1845 has different timer than others */ { if (arg < 4000) { arg = 4000; } if (arg > 50000) { arg = 50000; } portc->speed = arg; portc->speed_bits = speed_table[3].bits; return portc->speed; } if (arg < speed_table[0].speed) { selected = 0; } if (arg > speed_table[n - 1].speed) { selected = n - 1; } for (i = 1 /*really */ ; selected == -1 && i < n; i++) { if (speed_table[i].speed == arg) { selected = i; } else if (speed_table[i].speed > arg) { int diff1, diff2; diff1 = arg - speed_table[i - 1].speed; diff2 = speed_table[i].speed - arg; if (diff1 < diff2) { selected = i - 1; } else { selected = i; } } } if (selected == -1) { printk(KERN_WARNING "ad1848: Can't find speed???\n"); selected = 3; } portc->speed = speed_table[selected].speed; portc->speed_bits = speed_table[selected].bits; return portc->speed; } static short ad1848_set_channels(int dev, short arg) { ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc; if (arg != 1 && arg != 2) { return portc->channels; } portc->channels = arg; return arg; } static unsigned int ad1848_set_bits(int dev, unsigned int arg) { ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc; static struct format_tbl { int format; unsigned char bits; } format2bits[] = { { 0, 0 } , { AFMT_MU_LAW, 1 } , { AFMT_A_LAW, 3 } , { AFMT_IMA_ADPCM, 5 } , { AFMT_U8, 0 } , { AFMT_S16_LE, 2 } , { AFMT_S16_BE, 6 } , { AFMT_S8, 0 } , { AFMT_U16_LE, 0 } , { AFMT_U16_BE, 0 } }; int i, n = sizeof(format2bits) / sizeof(struct format_tbl); if (arg == 0) { return portc->audio_format; } if (!(arg & ad_format_mask[devc->model])) { arg = AFMT_U8; } portc->audio_format = arg; for (i = 0; i < n; i++) if (format2bits[i].format == arg) { if ((portc->format_bits = format2bits[i].bits) == 0) { return portc->audio_format = AFMT_U8; /* Was not supported */ } return arg; } /* Still hanging here. Something must be terribly wrong */ portc->format_bits = 0; return portc->audio_format = AFMT_U8; } static struct audio_driver ad1848_audio_driver = { .owner = THIS_MODULE, .open = ad1848_open, .close = ad1848_close, .output_block = ad1848_output_block, .start_input = ad1848_start_input, .prepare_for_input = ad1848_prepare_for_input, .prepare_for_output = ad1848_prepare_for_output, .halt_io = ad1848_halt, .halt_input = ad1848_halt_input, .halt_output = ad1848_halt_output, .trigger = ad1848_trigger, .set_speed = ad1848_set_speed, .set_bits = ad1848_set_bits, .set_channels = ad1848_set_channels }; static struct mixer_operations ad1848_mixer_operations = { .owner = THIS_MODULE, .id = "SOUNDPORT", .name = "AD1848/CS4248/CS4231", .ioctl = ad1848_mixer_ioctl }; static int ad1848_open(int dev, int mode) { ad1848_info *devc; ad1848_port_info *portc; unsigned long flags; if (dev < 0 || dev >= num_audiodevs) { return -ENXIO; } devc = (ad1848_info *) audio_devs[dev]->devc; portc = (ad1848_port_info *) audio_devs[dev]->portc; /* here we don't have to protect against intr */ spin_lock(&devc->lock); if (portc->open_mode || (devc->open_mode & mode)) { spin_unlock(&devc->lock); return -EBUSY; } devc->dual_dma = 0; if (audio_devs[dev]->flags & DMA_DUPLEX) { devc->dual_dma = 1; } devc->intr_active = 0; devc->audio_mode = 0; devc->open_mode |= mode; portc->open_mode = mode; spin_unlock(&devc->lock); ad1848_trigger(dev, 0); if (mode & OPEN_READ) { devc->record_dev = dev; } if (mode & OPEN_WRITE) { devc->playback_dev = dev; } /* * Mute output until the playback really starts. This decreases clicking (hope so). */ spin_lock_irqsave(&devc->lock, flags); ad_mute(devc); spin_unlock_irqrestore(&devc->lock, flags); return 0; } static void ad1848_close(int dev) { unsigned long flags; ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc; devc->intr_active = 0; ad1848_halt(dev); spin_lock_irqsave(&devc->lock, flags); devc->audio_mode = 0; devc->open_mode &= ~portc->open_mode; portc->open_mode = 0; ad_unmute(devc); spin_unlock_irqrestore(&devc->lock, flags); } static void ad1848_output_block(int dev, unsigned long buf, int count, int intrflag) { unsigned long flags, cnt; ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc; cnt = count; if (portc->audio_format == AFMT_IMA_ADPCM) { cnt /= 4; } else { if (portc->audio_format & (AFMT_S16_LE | AFMT_S16_BE)) /* 16 bit data */ { cnt >>= 1; } } if (portc->channels > 1) { cnt >>= 1; } cnt--; if ((devc->audio_mode & PCM_ENABLE_OUTPUT) && (audio_devs[dev]->flags & DMA_AUTOMODE) && intrflag && cnt == devc->xfer_count) { devc->audio_mode |= PCM_ENABLE_OUTPUT; devc->intr_active = 1; return; /* * Auto DMA mode on. No need to react */ } spin_lock_irqsave(&devc->lock, flags); ad_write(devc, 15, (unsigned char) (cnt & 0xff)); ad_write(devc, 14, (unsigned char) ((cnt >> 8) & 0xff)); devc->xfer_count = cnt; devc->audio_mode |= PCM_ENABLE_OUTPUT; devc->intr_active = 1; spin_unlock_irqrestore(&devc->lock, flags); } static void ad1848_start_input(int dev, unsigned long buf, int count, int intrflag) { unsigned long flags, cnt; ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc; cnt = count; if (portc->audio_format == AFMT_IMA_ADPCM) { cnt /= 4; } else { if (portc->audio_format & (AFMT_S16_LE | AFMT_S16_BE)) /* 16 bit data */ { cnt >>= 1; } } if (portc->channels > 1) { cnt >>= 1; } cnt--; if ((devc->audio_mode & PCM_ENABLE_INPUT) && (audio_devs[dev]->flags & DMA_AUTOMODE) && intrflag && cnt == devc->xfer_count) { devc->audio_mode |= PCM_ENABLE_INPUT; devc->intr_active = 1; return; /* * Auto DMA mode on. No need to react */ } spin_lock_irqsave(&devc->lock, flags); if (devc->model == MD_1848) { ad_write(devc, 15, (unsigned char) (cnt & 0xff)); ad_write(devc, 14, (unsigned char) ((cnt >> 8) & 0xff)); } else { ad_write(devc, 31, (unsigned char) (cnt & 0xff)); ad_write(devc, 30, (unsigned char) ((cnt >> 8) & 0xff)); } ad_unmute(devc); devc->xfer_count = cnt; devc->audio_mode |= PCM_ENABLE_INPUT; devc->intr_active = 1; spin_unlock_irqrestore(&devc->lock, flags); } static int ad1848_prepare_for_output(int dev, int bsize, int bcount) { int timeout; unsigned char fs, old_fs, tmp = 0; unsigned long flags; ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc; ad_mute(devc); spin_lock_irqsave(&devc->lock, flags); fs = portc->speed_bits | (portc->format_bits << 5); if (portc->channels > 1) { fs |= 0x10; } ad_enter_MCE(devc); /* Enables changes to the format select reg */ if (devc->model == MD_1845 || devc->model == MD_1845_SSCAPE) /* Use alternate speed select registers */ { fs &= 0xf0; /* Mask off the rate select bits */ ad_write(devc, 22, (portc->speed >> 8) & 0xff); /* Speed MSB */ ad_write(devc, 23, portc->speed & 0xff); /* Speed LSB */ } old_fs = ad_read(devc, 8); if (devc->model == MD_4232 || devc->model >= MD_4236) { tmp = ad_read(devc, 16); ad_write(devc, 16, tmp | 0x30); } if (devc->model == MD_IWAVE) { ad_write(devc, 17, 0xc2); /* Disable variable frequency select */ } ad_write(devc, 8, fs); /* * Write to I8 starts resynchronization. Wait until it completes. */ timeout = 0; while (timeout < 100 && inb(devc->base) != 0x80) { timeout++; } timeout = 0; while (timeout < 10000 && inb(devc->base) == 0x80) { timeout++; } if (devc->model >= MD_4232) { ad_write(devc, 16, tmp & ~0x30); } ad_leave_MCE(devc); /* * Starts the calibration process. */ spin_unlock_irqrestore(&devc->lock, flags); devc->xfer_count = 0; #ifndef EXCLUDE_TIMERS if (dev == timer_installed && devc->timer_running) if ((fs & 0x01) != (old_fs & 0x01)) { ad1848_tmr_reprogram(dev); } #endif ad1848_halt_output(dev); return 0; } static int ad1848_prepare_for_input(int dev, int bsize, int bcount) { int timeout; unsigned char fs, old_fs, tmp = 0; unsigned long flags; ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc; if (devc->audio_mode) { return 0; } spin_lock_irqsave(&devc->lock, flags); fs = portc->speed_bits | (portc->format_bits << 5); if (portc->channels > 1) { fs |= 0x10; } ad_enter_MCE(devc); /* Enables changes to the format select reg */ if ((devc->model == MD_1845) || (devc->model == MD_1845_SSCAPE)) /* Use alternate speed select registers */ { fs &= 0xf0; /* Mask off the rate select bits */ ad_write(devc, 22, (portc->speed >> 8) & 0xff); /* Speed MSB */ ad_write(devc, 23, portc->speed & 0xff); /* Speed LSB */ } if (devc->model == MD_4232) { tmp = ad_read(devc, 16); ad_write(devc, 16, tmp | 0x30); } if (devc->model == MD_IWAVE) { ad_write(devc, 17, 0xc2); /* Disable variable frequency select */ } /* * If mode >= 2 (CS4231), set I28. It's the capture format register. */ if (devc->model != MD_1848) { old_fs = ad_read(devc, 28); ad_write(devc, 28, fs); /* * Write to I28 starts resynchronization. Wait until it completes. */ timeout = 0; while (timeout < 100 && inb(devc->base) != 0x80) { timeout++; } timeout = 0; while (timeout < 10000 && inb(devc->base) == 0x80) { timeout++; } if (devc->model != MD_1848 && devc->model != MD_1845 && devc->model != MD_1845_SSCAPE) { /* * CS4231 compatible devices don't have separate sampling rate selection * register for recording an playback. The I8 register is shared so we have to * set the speed encoding bits of it too. */ unsigned char tmp = portc->speed_bits | (ad_read(devc, 8) & 0xf0); ad_write(devc, 8, tmp); /* * Write to I8 starts resynchronization. Wait until it completes. */ timeout = 0; while (timeout < 100 && inb(devc->base) != 0x80) { timeout++; } timeout = 0; while (timeout < 10000 && inb(devc->base) == 0x80) { timeout++; } } } else { /* For AD1848 set I8. */ old_fs = ad_read(devc, 8); ad_write(devc, 8, fs); /* * Write to I8 starts resynchronization. Wait until it completes. */ timeout = 0; while (timeout < 100 && inb(devc->base) != 0x80) { timeout++; } timeout = 0; while (timeout < 10000 && inb(devc->base) == 0x80) { timeout++; } } if (devc->model == MD_4232) { ad_write(devc, 16, tmp & ~0x30); } ad_leave_MCE(devc); /* * Starts the calibration process. */ spin_unlock_irqrestore(&devc->lock, flags); devc->xfer_count = 0; #ifndef EXCLUDE_TIMERS if (dev == timer_installed && devc->timer_running) { if ((fs & 0x01) != (old_fs & 0x01)) { ad1848_tmr_reprogram(dev); } } #endif ad1848_halt_input(dev); return 0; } static void ad1848_halt(int dev) { ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc; unsigned char bits = ad_read(devc, 9); if (bits & 0x01 && (portc->open_mode & OPEN_WRITE)) { ad1848_halt_output(dev); } if (bits & 0x02 && (portc->open_mode & OPEN_READ)) { ad1848_halt_input(dev); } devc->audio_mode = 0; } static void ad1848_halt_input(int dev) { ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; unsigned long flags; if (!(ad_read(devc, 9) & 0x02)) { return; /* Capture not enabled */ } spin_lock_irqsave(&devc->lock, flags); ad_mute(devc); { int tmout; if (!isa_dma_bridge_buggy) { disable_dma(audio_devs[dev]->dmap_in->dma); } for (tmout = 0; tmout < 100000; tmout++) if (ad_read(devc, 11) & 0x10) { break; } ad_write(devc, 9, ad_read(devc, 9) & ~0x02); /* Stop capture */ if (!isa_dma_bridge_buggy) { enable_dma(audio_devs[dev]->dmap_in->dma); } devc->audio_mode &= ~PCM_ENABLE_INPUT; } outb(0, io_Status(devc)); /* Clear interrupt status */ outb(0, io_Status(devc)); /* Clear interrupt status */ devc->audio_mode &= ~PCM_ENABLE_INPUT; spin_unlock_irqrestore(&devc->lock, flags); } static void ad1848_halt_output(int dev) { ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; unsigned long flags; if (!(ad_read(devc, 9) & 0x01)) { return; /* Playback not enabled */ } spin_lock_irqsave(&devc->lock, flags); ad_mute(devc); { int tmout; if (!isa_dma_bridge_buggy) { disable_dma(audio_devs[dev]->dmap_out->dma); } for (tmout = 0; tmout < 100000; tmout++) if (ad_read(devc, 11) & 0x10) { break; } ad_write(devc, 9, ad_read(devc, 9) & ~0x01); /* Stop playback */ if (!isa_dma_bridge_buggy) { enable_dma(audio_devs[dev]->dmap_out->dma); } devc->audio_mode &= ~PCM_ENABLE_OUTPUT; } outb((0), io_Status(devc)); /* Clear interrupt status */ outb((0), io_Status(devc)); /* Clear interrupt status */ devc->audio_mode &= ~PCM_ENABLE_OUTPUT; spin_unlock_irqrestore(&devc->lock, flags); } static void ad1848_trigger(int dev, int state) { ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc; unsigned long flags; unsigned char tmp, old; spin_lock_irqsave(&devc->lock, flags); state &= devc->audio_mode; tmp = old = ad_read(devc, 9); if (portc->open_mode & OPEN_READ) { if (state & PCM_ENABLE_INPUT) { tmp |= 0x02; } else { tmp &= ~0x02; } } if (portc->open_mode & OPEN_WRITE) { if (state & PCM_ENABLE_OUTPUT) { tmp |= 0x01; } else { tmp &= ~0x01; } } /* ad_mute(devc); */ if (tmp != old) { ad_write(devc, 9, tmp); ad_unmute(devc); } spin_unlock_irqrestore(&devc->lock, flags); } static void ad1848_init_hw(ad1848_info *devc) { int i; int *init_values; /* * Initial values for the indirect registers of CS4248/AD1848. */ static int init_values_a[] = { 0xa8, 0xa8, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00, 0x00, 0x0c, 0x02, 0x00, 0x8a, 0x01, 0x00, 0x00, /* Positions 16 to 31 just for CS4231/2 and ad1845 */ 0x80, 0x00, 0x10, 0x10, 0x00, 0x00, 0x1f, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; static int init_values_b[] = { /* Values for the newer chips Some of the register initialization values were changed. In order to get rid of the click that preceded PCM playback, calibration was disabled on the 10th byte. On that same byte, dual DMA was enabled; on the 11th byte, ADC dithering was enabled, since that is theoretically desirable; on the 13th byte, Mode 3 was selected, to enable access to extended registers. */ 0xa8, 0xa8, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0xe0, 0x01, 0x00, 0x00, 0x80, 0x00, 0x10, 0x10, 0x00, 0x00, 0x1f, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; /* * Select initialisation data */ init_values = init_values_a; if (devc->model >= MD_4236) { init_values = init_values_b; } for (i = 0; i < 16; i++) { ad_write(devc, i, init_values[i]); } ad_mute(devc); /* Initialize some variables */ ad_unmute(devc); /* Leave it unmuted now */ if (devc->model > MD_1848) { if (devc->model == MD_1845_SSCAPE) { ad_write(devc, 12, ad_read(devc, 12) | 0x50); } else { ad_write(devc, 12, ad_read(devc, 12) | 0x40); /* Mode2 = enabled */ } if (devc->model == MD_IWAVE) { ad_write(devc, 12, 0x6c); /* Select codec mode 3 */ } if (devc->model != MD_1845_SSCAPE) for (i = 16; i < 32; i++) { ad_write(devc, i, init_values[i]); } if (devc->model == MD_IWAVE) { ad_write(devc, 16, 0x30); /* Playback and capture counters enabled */ } } if (devc->model > MD_1848) { if (devc->audio_flags & DMA_DUPLEX) { ad_write(devc, 9, ad_read(devc, 9) & ~0x04); /* Dual DMA mode */ } else { ad_write(devc, 9, ad_read(devc, 9) | 0x04); /* Single DMA mode */ } if (devc->model == MD_1845 || devc->model == MD_1845_SSCAPE) { ad_write(devc, 27, ad_read(devc, 27) | 0x08); /* Alternate freq select enabled */ } if (devc->model == MD_IWAVE) { /* Some magic Interwave specific initialization */ ad_write(devc, 12, 0x6c); /* Select codec mode 3 */ ad_write(devc, 16, 0x30); /* Playback and capture counters enabled */ ad_write(devc, 17, 0xc2); /* Alternate feature enable */ } } else { devc->audio_flags &= ~DMA_DUPLEX; ad_write(devc, 9, ad_read(devc, 9) | 0x04); /* Single DMA mode */ if (soundpro) { ad_write(devc, 12, ad_read(devc, 12) | 0x40); /* Mode2 = enabled */ } } outb((0), io_Status(devc)); /* Clear pending interrupts */ /* * Toggle the MCE bit. It completes the initialization phase. */ ad_enter_MCE(devc); /* In case the bit was off */ ad_leave_MCE(devc); ad1848_mixer_reset(devc); } int ad1848_detect(struct resource *ports, int *ad_flags, int *osp) { unsigned char tmp; ad1848_info *devc = &adev_info[nr_ad1848_devs]; unsigned char tmp1 = 0xff, tmp2 = 0xff; int optiC930 = 0; /* OPTi 82C930 flag */ int interwave = 0; int ad1847_flag = 0; int cs4248_flag = 0; int sscape_flag = 0; int io_base = ports->start; int i; DDB(printk("ad1848_detect(%x)\n", io_base)); if (ad_flags) { if (*ad_flags == 0x12345678) { interwave = 1; *ad_flags = 0; } if (*ad_flags == 0x87654321) { sscape_flag = 1; *ad_flags = 0; } if (*ad_flags == 0x12345677) { cs4248_flag = 1; *ad_flags = 0; } } if (nr_ad1848_devs >= MAX_AUDIO_DEV) { printk(KERN_ERR "ad1848 - Too many audio devices\n"); return 0; } spin_lock_init(&devc->lock); devc->base = io_base; devc->irq_ok = 0; devc->timer_running = 0; devc->MCE_bit = 0x40; devc->irq = 0; devc->open_mode = 0; devc->chip_name = devc->name = "AD1848"; devc->model = MD_1848; /* AD1848 or CS4248 */ devc->levels = NULL; devc->debug_flag = 0; /* * Check that the I/O address is in use. * * The bit 0x80 of the base I/O port is known to be 0 after the * chip has performed its power on initialization. Just assume * this has happened before the OS is starting. * * If the I/O address is unused, it typically returns 0xff. */ if (inb(devc->base) == 0xff) { DDB(printk("ad1848_detect: The base I/O address appears to be dead\n")); } /* * Wait for the device to stop initialization */ DDB(printk("ad1848_detect() - step 0\n")); for (i = 0; i < 10000000; i++) { unsigned char x = inb(devc->base); if (x == 0xff || !(x & 0x80)) { break; } } DDB(printk("ad1848_detect() - step A\n")); if (inb(devc->base) == 0x80) /* Not ready. Let's wait */ { ad_leave_MCE(devc); } if ((inb(devc->base) & 0x80) != 0x00) /* Not a AD1848 */ { DDB(printk("ad1848 detect error - step A (%02x)\n", (int) inb(devc->base))); return 0; } /* * Test if it's possible to change contents of the indirect registers. * Registers 0 and 1 are ADC volume registers. The bit 0x10 is read only * so try to avoid using it. */ DDB(printk("ad1848_detect() - step B\n")); ad_write(devc, 0, 0xaa); ad_write(devc, 1, 0x45); /* 0x55 with bit 0x10 clear */ if ((tmp1 = ad_read(devc, 0)) != 0xaa || (tmp2 = ad_read(devc, 1)) != 0x45) { if (tmp2 == 0x65) /* AD1847 has couple of bits hardcoded to 1 */ { ad1847_flag = 1; } else { DDB(printk("ad1848 detect error - step B (%x/%x)\n", tmp1, tmp2)); return 0; } } DDB(printk("ad1848_detect() - step C\n")); ad_write(devc, 0, 0x45); ad_write(devc, 1, 0xaa); if ((tmp1 = ad_read(devc, 0)) != 0x45 || (tmp2 = ad_read(devc, 1)) != 0xaa) { if (tmp2 == 0x8a) /* AD1847 has few bits hardcoded to 1 */ { ad1847_flag = 1; } else { DDB(printk("ad1848 detect error - step C (%x/%x)\n", tmp1, tmp2)); return 0; } } /* * The indirect register I12 has some read only bits. Let's * try to change them. */ DDB(printk("ad1848_detect() - step D\n")); tmp = ad_read(devc, 12); ad_write(devc, 12, (~tmp) & 0x0f); if ((tmp & 0x0f) != ((tmp1 = ad_read(devc, 12)) & 0x0f)) { DDB(printk("ad1848 detect error - step D (%x)\n", tmp1)); return 0; } /* * NOTE! Last 4 bits of the reg I12 tell the chip revision. * 0x01=RevB and 0x0A=RevC. */ /* * The original AD1848/CS4248 has just 15 indirect registers. This means * that I0 and I16 should return the same value (etc.). * However this doesn't work with CS4248. Actually it seems to be impossible * to detect if the chip is a CS4231 or CS4248. * Ensure that the Mode2 enable bit of I12 is 0. Otherwise this test fails * with CS4231. */ /* * OPTi 82C930 has mode2 control bit in another place. This test will fail * with it. Accept this situation as a possible indication of this chip. */ DDB(printk("ad1848_detect() - step F\n")); ad_write(devc, 12, 0); /* Mode2=disabled */ for (i = 0; i < 16; i++) { if ((tmp1 = ad_read(devc, i)) != (tmp2 = ad_read(devc, i + 16))) { DDB(printk("ad1848 detect step F(%d/%x/%x) - OPTi chip???\n", i, tmp1, tmp2)); if (!ad1847_flag) { optiC930 = 1; } break; } } /* * Try to switch the chip to mode2 (CS4231) by setting the MODE2 bit (0x40). * The bit 0x80 is always 1 in CS4248 and CS4231. */ DDB(printk("ad1848_detect() - step G\n")); if (ad_flags && *ad_flags == 400) { *ad_flags = 0; } else { ad_write(devc, 12, 0x40); /* Set mode2, clear 0x80 */ } if (ad_flags) { *ad_flags = 0; } tmp1 = ad_read(devc, 12); if (tmp1 & 0x80) { if (ad_flags) { *ad_flags |= AD_F_CS4248; } devc->chip_name = "CS4248"; /* Our best knowledge just now */ } if (optiC930 || (tmp1 & 0xc0) == (0x80 | 0x40)) { /* * CS4231 detected - is it? * * Verify that setting I0 doesn't change I16. */ DDB(printk("ad1848_detect() - step H\n")); ad_write(devc, 16, 0); /* Set I16 to known value */ ad_write(devc, 0, 0x45); if ((tmp1 = ad_read(devc, 16)) != 0x45) /* No change -> CS4231? */ { ad_write(devc, 0, 0xaa); if ((tmp1 = ad_read(devc, 16)) == 0xaa) /* Rotten bits? */ { DDB(printk("ad1848 detect error - step H(%x)\n", tmp1)); return 0; } /* * Verify that some bits of I25 are read only. */ DDB(printk("ad1848_detect() - step I\n")); tmp1 = ad_read(devc, 25); /* Original bits */ ad_write(devc, 25, ~tmp1); /* Invert all bits */ if ((ad_read(devc, 25) & 0xe7) == (tmp1 & 0xe7)) { int id; /* * It's at least CS4231 */ devc->chip_name = "CS4231"; devc->model = MD_4231; /* * It could be an AD1845 or CS4231A as well. * CS4231 and AD1845 report the same revision info in I25 * while the CS4231A reports different. */ id = ad_read(devc, 25); if ((id & 0xe7) == 0x80) /* Device busy??? */ { id = ad_read(devc, 25); } if ((id & 0xe7) == 0x80) /* Device still busy??? */ { id = ad_read(devc, 25); } DDB(printk("ad1848_detect() - step J (%02x/%02x)\n", id, ad_read(devc, 25))); if ((id & 0xe7) == 0x80) { /* * It must be a CS4231 or AD1845. The register I23 of * CS4231 is undefined and it appears to be read only. * AD1845 uses I23 for setting sample rate. Assume * the chip is AD1845 if I23 is changeable. */ unsigned char tmp = ad_read(devc, 23); ad_write(devc, 23, ~tmp); if (interwave) { devc->model = MD_IWAVE; devc->chip_name = "IWave"; } else if (ad_read(devc, 23) != tmp) /* AD1845 ? */ { devc->chip_name = "AD1845"; devc->model = MD_1845; } else if (cs4248_flag) { if (ad_flags) { *ad_flags |= AD_F_CS4248; } devc->chip_name = "CS4248"; devc->model = MD_1848; ad_write(devc, 12, ad_read(devc, 12) & ~0x40); /* Mode2 off */ } ad_write(devc, 23, tmp); /* Restore */ } else { switch (id & 0x1f) { case 3: /* CS4236/CS4235/CS42xB/CS4239 */ { int xid; ad_write(devc, 12, ad_read(devc, 12) | 0x60); /* switch to mode 3 */ ad_write(devc, 23, 0x9c); /* select extended register 25 */ xid = inb(io_Indexed_Data(devc)); ad_write(devc, 12, ad_read(devc, 12) & ~0x60); /* back to mode 0 */ switch (xid & 0x1f) { case 0x00: devc->chip_name = "CS4237B(B)"; devc->model = MD_42xB; break; case 0x08: /* Seems to be a 4238 ?? */ devc->chip_name = "CS4238"; devc->model = MD_42xB; break; case 0x09: devc->chip_name = "CS4238B"; devc->model = MD_42xB; break; case 0x0b: devc->chip_name = "CS4236B"; devc->model = MD_4236; break; case 0x10: devc->chip_name = "CS4237B"; devc->model = MD_42xB; break; case 0x1d: devc->chip_name = "CS4235"; devc->model = MD_4235; break; case 0x1e: devc->chip_name = "CS4239"; devc->model = MD_4239; break; default: printk("Chip ident is %X.\n", xid & 0x1F); devc->chip_name = "CS42xx"; devc->model = MD_4232; break; } } break; case 2: /* CS4232/CS4232A */ devc->chip_name = "CS4232"; devc->model = MD_4232; break; case 0: if ((id & 0xe0) == 0xa0) { devc->chip_name = "CS4231A"; devc->model = MD_4231A; } else { devc->chip_name = "CS4321"; devc->model = MD_4231; } break; default: /* maybe */ DDB(printk("ad1848: I25 = %02x/%02x\n", ad_read(devc, 25), ad_read(devc, 25) & 0xe7)); if (optiC930) { devc->chip_name = "82C930"; devc->model = MD_C930; } else { devc->chip_name = "CS4231"; devc->model = MD_4231; } } } } ad_write(devc, 25, tmp1); /* Restore bits */ DDB(printk("ad1848_detect() - step K\n")); } } else if (tmp1 == 0x0a) { /* * Is it perhaps a SoundPro CMI8330? * If so, then we should be able to change indirect registers * greater than I15 after activating MODE2, even though reading * back I12 does not show it. */ /* * Let's try comparing register values */ for (i = 0; i < 16; i++) { if ((tmp1 = ad_read(devc, i)) != (tmp2 = ad_read(devc, i + 16))) { DDB(printk("ad1848 detect step H(%d/%x/%x) - SoundPro chip?\n", i, tmp1, tmp2)); soundpro = 1; devc->chip_name = "SoundPro CMI 8330"; break; } } } DDB(printk("ad1848_detect() - step L\n")); if (ad_flags) { if (devc->model != MD_1848) { *ad_flags |= AD_F_CS4231; } } DDB(printk("ad1848_detect() - Detected OK\n")); if (devc->model == MD_1848 && ad1847_flag) { devc->chip_name = "AD1847"; } if (sscape_flag == 1) { devc->model = MD_1845_SSCAPE; } return 1; } int ad1848_init (char *name, struct resource *ports, int irq, int dma_playback, int dma_capture, int share_dma, int *osp, struct module *owner) { /* * NOTE! If irq < 0, there is another driver which has allocated the IRQ * so that this driver doesn't need to allocate/deallocate it. * The actually used IRQ is ABS(irq). */ int my_dev; char dev_name[100]; int e; ad1848_info *devc = &adev_info[nr_ad1848_devs]; ad1848_port_info *portc = NULL; devc->irq = (irq > 0) ? irq : 0; devc->open_mode = 0; devc->timer_ticks = 0; devc->dma1 = dma_playback; devc->dma2 = dma_capture; devc->subtype = cfg.card_subtype; devc->audio_flags = DMA_AUTOMODE; devc->playback_dev = devc->record_dev = 0; if (name != NULL) { devc->name = name; } if (name != NULL && name[0] != 0) sprintf(dev_name, "%s (%s)", name, devc->chip_name); else sprintf(dev_name, "Generic audio codec (%s)", devc->chip_name); rename_region(ports, devc->name); conf_printf2(dev_name, devc->base, devc->irq, dma_playback, dma_capture); if (devc->model == MD_1848 || devc->model == MD_C930) { devc->audio_flags |= DMA_HARDSTOP; } if (devc->model > MD_1848) { if (devc->dma1 == devc->dma2 || devc->dma2 == -1 || devc->dma1 == -1) { devc->audio_flags &= ~DMA_DUPLEX; } else { devc->audio_flags |= DMA_DUPLEX; } } portc = kmalloc(sizeof(ad1848_port_info), GFP_KERNEL); if (portc == NULL) { release_region(devc->base, 4); return -1; } if ((my_dev = sound_install_audiodrv(AUDIO_DRIVER_VERSION, dev_name, &ad1848_audio_driver, sizeof(struct audio_driver), devc->audio_flags, ad_format_mask[devc->model], devc, dma_playback, dma_capture)) < 0) { release_region(devc->base, 4); kfree(portc); return -1; } audio_devs[my_dev]->portc = portc; audio_devs[my_dev]->mixer_dev = -1; if (owner) { audio_devs[my_dev]->d->owner = owner; } memset((char *) portc, 0, sizeof(*portc)); nr_ad1848_devs++; ad1848_init_hw(devc); if (irq > 0) { devc->dev_no = my_dev; if (request_irq(devc->irq, adintr, 0, devc->name, (void *)(long)my_dev) < 0) { printk(KERN_WARNING "ad1848: Unable to allocate IRQ\n"); /* Don't free it either then.. */ devc->irq = 0; } if (capabilities[devc->model].flags & CAP_F_TIMER) { #ifndef CONFIG_SMP int x; unsigned char tmp = ad_read(devc, 16); #endif devc->timer_ticks = 0; ad_write(devc, 21, 0x00); /* Timer MSB */ ad_write(devc, 20, 0x10); /* Timer LSB */ #ifndef CONFIG_SMP ad_write(devc, 16, tmp | 0x40); /* Enable timer */ for (x = 0; x < 100000 && devc->timer_ticks == 0; x++); ad_write(devc, 16, tmp & ~0x40); /* Disable timer */ if (devc->timer_ticks == 0) { printk(KERN_WARNING "ad1848: Interrupt test failed (IRQ%d)\n", irq); } else { DDB(printk("Interrupt test OK\n")); devc->irq_ok = 1; } #else devc->irq_ok = 1; #endif } else { devc->irq_ok = 1; /* Couldn't test. assume it's OK */ } } else if (irq < 0) { irq2dev[-irq] = devc->dev_no = my_dev; } #ifndef EXCLUDE_TIMERS if ((capabilities[devc->model].flags & CAP_F_TIMER) && devc->irq_ok) { ad1848_tmr_install(my_dev); } #endif if (!share_dma) { if (sound_alloc_dma(dma_playback, devc->name)) { printk(KERN_WARNING "ad1848.c: Can't allocate DMA%d\n", dma_playback); } if (dma_capture != dma_playback) if (sound_alloc_dma(dma_capture, devc->name)) { printk(KERN_WARNING "ad1848.c: Can't allocate DMA%d\n", dma_capture); } } if ((e = sound_install_mixer(MIXER_DRIVER_VERSION, dev_name, &ad1848_mixer_operations, sizeof(struct mixer_operations), devc)) >= 0) { audio_devs[my_dev]->mixer_dev = e; if (owner) { mixer_devs[e]->owner = owner; } } return my_dev; } int ad1848_control(int cmd, int arg) { ad1848_info *devc; unsigned long flags; if (nr_ad1848_devs < 1) { return -ENODEV; } devc = &adev_info[nr_ad1848_devs - 1]; switch (cmd) { case AD1848_SET_XTAL: /* Change clock frequency of AD1845 (only ) */ if (devc->model != MD_1845 && devc->model != MD_1845_SSCAPE) { return -EINVAL; } spin_lock_irqsave(&devc->lock, flags); ad_enter_MCE(devc); ad_write(devc, 29, (ad_read(devc, 29) & 0x1f) | (arg << 5)); ad_leave_MCE(devc); spin_unlock_irqrestore(&devc->lock, flags); break; case AD1848_MIXER_REROUTE: { int o = (arg >> 8) & 0xff; int n = arg & 0xff; if (o < 0 || o >= SOUND_MIXER_NRDEVICES) { return -EINVAL; } if (!(devc->supported_devices & (1 << o)) && !(devc->supported_rec_devices & (1 << o))) { return -EINVAL; } if (n == SOUND_MIXER_NONE) { /* Just hide this control */ ad1848_mixer_set(devc, o, 0); /* Shut up it */ devc->supported_devices &= ~(1 << o); devc->supported_rec_devices &= ~(1 << o); break; } /* Make the mixer control identified by o to appear as n */ if (n < 0 || n >= SOUND_MIXER_NRDEVICES) { return -EINVAL; } devc->mixer_reroute[n] = o; /* Rename the control */ if (devc->supported_devices & (1 << o)) { devc->supported_devices |= (1 << n); } if (devc->supported_rec_devices & (1 << o)) { devc->supported_rec_devices |= (1 << n); } devc->supported_devices &= ~(1 << o); devc->supported_rec_devices &= ~(1 << o); } break; } return 0; } void ad1848_unload(int io_base, int irq, int dma_playback, int dma_capture, int share_dma) { int i, mixer, dev = 0; ad1848_info *devc = NULL; for (i = 0; devc == NULL && i < nr_ad1848_devs; i++) { if (adev_info[i].base == io_base) { devc = &adev_info[i]; dev = devc->dev_no; } } if (devc != NULL) { kfree(audio_devs[dev]->portc); release_region(devc->base, 4); if (!share_dma) { if (devc->irq > 0) /* There is no point in freeing irq, if it wasn't allocated */ { free_irq(devc->irq, (void *)(long)devc->dev_no); } sound_free_dma(dma_playback); if (dma_playback != dma_capture) { sound_free_dma(dma_capture); } } mixer = audio_devs[devc->dev_no]->mixer_dev; if (mixer >= 0) { sound_unload_mixerdev(mixer); } nr_ad1848_devs--; for ( ; i < nr_ad1848_devs ; i++) { adev_info[i] = adev_info[i + 1]; } } else { printk(KERN_ERR "ad1848: Can't find device to be unloaded. Base=%x\n", io_base); } } static irqreturn_t adintr(int irq, void *dev_id) { unsigned char status; ad1848_info *devc; int dev; int alt_stat = 0xff; unsigned char c930_stat = 0; int cnt = 0; dev = (long)dev_id; devc = (ad1848_info *) audio_devs[dev]->devc; interrupt_again: /* Jump back here if int status doesn't reset */ status = inb(io_Status(devc)); if (status == 0x80) { printk(KERN_DEBUG "adintr: Why?\n"); } if (devc->model == MD_1848) { outb((0), io_Status(devc)); /* Clear interrupt status */ } if (status & 0x01) { if (devc->model == MD_C930) { /* 82C930 has interrupt status register in MAD16 register MC11 */ spin_lock(&devc->lock); /* 0xe0e is C930 address port * 0xe0f is C930 data port */ outb(11, 0xe0e); c930_stat = inb(0xe0f); outb((~c930_stat), 0xe0f); spin_unlock(&devc->lock); alt_stat = (c930_stat << 2) & 0x30; } else if (devc->model != MD_1848) { spin_lock(&devc->lock); alt_stat = ad_read(devc, 24); ad_write(devc, 24, ad_read(devc, 24) & ~alt_stat); /* Selective ack */ spin_unlock(&devc->lock); } if ((devc->open_mode & OPEN_READ) && (devc->audio_mode & PCM_ENABLE_INPUT) && (alt_stat & 0x20)) { DMAbuf_inputintr(devc->record_dev); } if ((devc->open_mode & OPEN_WRITE) && (devc->audio_mode & PCM_ENABLE_OUTPUT) && (alt_stat & 0x10)) { DMAbuf_outputintr(devc->playback_dev, 1); } if (devc->model != MD_1848 && (alt_stat & 0x40)) /* Timer interrupt */ { devc->timer_ticks++; #ifndef EXCLUDE_TIMERS if (timer_installed == dev && devc->timer_running) { sound_timer_interrupt(); } #endif } } /* * Sometimes playback or capture interrupts occur while a timer interrupt * is being handled. The interrupt will not be retriggered if we don't * handle it now. Check if an interrupt is still pending and restart * the handler in this case. */ if (inb(io_Status(devc)) & 0x01 && cnt++ < 4) { goto interrupt_again; } return IRQ_HANDLED; } /* * Experimental initialization sequence for the integrated sound system * of the Compaq Deskpro M. */ static int init_deskpro_m(struct address_info *hw_config) { unsigned char tmp; if ((tmp = inb(0xc44)) == 0xff) { DDB(printk("init_deskpro_m: Dead port 0xc44\n")); return 0; } outb(0x10, 0xc44); outb(0x40, 0xc45); outb(0x00, 0xc46); outb(0xe8, 0xc47); outb(0x14, 0xc44); outb(0x40, 0xc45); outb(0x00, 0xc46); outb(0xe8, 0xc47); outb(0x10, 0xc44); return 1; } /* * Experimental initialization sequence for the integrated sound system * of Compaq Deskpro XL. */ static int init_deskpro(struct address_info *hw_config) { unsigned char tmp; if ((tmp = inb(0xc44)) == 0xff) { DDB(printk("init_deskpro: Dead port 0xc44\n")); return 0; } outb((tmp | 0x04), 0xc44); /* Select bank 1 */ if (inb(0xc44) != 0x04) { DDB(printk("init_deskpro: Invalid bank1 signature in port 0xc44\n")); return 0; } /* * OK. It looks like a Deskpro so let's proceed. */ /* * I/O port 0xc44 Audio configuration register. * * bits 0xc0: Audio revision bits * 0x00 = Compaq Business Audio * 0x40 = MS Sound System Compatible (reset default) * 0x80 = Reserved * 0xc0 = Reserved * bit 0x20: No Wait State Enable * 0x00 = Disabled (reset default, DMA mode) * 0x20 = Enabled (programmed I/O mode) * bit 0x10: MS Sound System Decode Enable * 0x00 = Decoding disabled (reset default) * 0x10 = Decoding enabled * bit 0x08: FM Synthesis Decode Enable * 0x00 = Decoding Disabled (reset default) * 0x08 = Decoding enabled * bit 0x04 Bank select * 0x00 = Bank 0 * 0x04 = Bank 1 * bits 0x03 MSS Base address * 0x00 = 0x530 (reset default) * 0x01 = 0x604 * 0x02 = 0xf40 * 0x03 = 0xe80 */ #ifdef DEBUGXL /* Debug printing */ printk("Port 0xc44 (before): "); outb((tmp & ~0x04), 0xc44); printk("%02x ", inb(0xc44)); outb((tmp | 0x04), 0xc44); printk("%02x\n", inb(0xc44)); #endif /* Set bank 1 of the register */ tmp = 0x58; /* MSS Mode, MSS&FM decode enabled */ switch (hw_config->io_base) { case 0x530: tmp |= 0x00; break; case 0x604: tmp |= 0x01; break; case 0xf40: tmp |= 0x02; break; case 0xe80: tmp |= 0x03; break; default: DDB(printk("init_deskpro: Invalid MSS port %x\n", hw_config->io_base)); return 0; } outb((tmp & ~0x04), 0xc44); /* Write to bank=0 */ #ifdef DEBUGXL /* Debug printing */ printk("Port 0xc44 (after): "); outb((tmp & ~0x04), 0xc44); /* Select bank=0 */ printk("%02x ", inb(0xc44)); outb((tmp | 0x04), 0xc44); /* Select bank=1 */ printk("%02x\n", inb(0xc44)); #endif /* * I/O port 0xc45 FM Address Decode/MSS ID Register. * * bank=0, bits 0xfe: FM synthesis Decode Compare bits 7:1 (default=0x88) * bank=0, bit 0x01: SBIC Power Control Bit * 0x00 = Powered up * 0x01 = Powered down * bank=1, bits 0xfc: MSS ID (default=0x40) */ #ifdef DEBUGXL /* Debug printing */ printk("Port 0xc45 (before): "); outb((tmp & ~0x04), 0xc44); /* Select bank=0 */ printk("%02x ", inb(0xc45)); outb((tmp | 0x04), 0xc44); /* Select bank=1 */ printk("%02x\n", inb(0xc45)); #endif outb((tmp & ~0x04), 0xc44); /* Select bank=0 */ outb((0x88), 0xc45); /* FM base 7:0 = 0x88 */ outb((tmp | 0x04), 0xc44); /* Select bank=1 */ outb((0x10), 0xc45); /* MSS ID = 0x10 (MSS port returns 0x04) */ #ifdef DEBUGXL /* Debug printing */ printk("Port 0xc45 (after): "); outb((tmp & ~0x04), 0xc44); /* Select bank=0 */ printk("%02x ", inb(0xc45)); outb((tmp | 0x04), 0xc44); /* Select bank=1 */ printk("%02x\n", inb(0xc45)); #endif /* * I/O port 0xc46 FM Address Decode/Address ASIC Revision Register. * * bank=0, bits 0xff: FM synthesis Decode Compare bits 15:8 (default=0x03) * bank=1, bits 0xff: Audio addressing ASIC id */ #ifdef DEBUGXL /* Debug printing */ printk("Port 0xc46 (before): "); outb((tmp & ~0x04), 0xc44); /* Select bank=0 */ printk("%02x ", inb(0xc46)); outb((tmp | 0x04), 0xc44); /* Select bank=1 */ printk("%02x\n", inb(0xc46)); #endif outb((tmp & ~0x04), 0xc44); /* Select bank=0 */ outb((0x03), 0xc46); /* FM base 15:8 = 0x03 */ outb((tmp | 0x04), 0xc44); /* Select bank=1 */ outb((0x11), 0xc46); /* ASIC ID = 0x11 */ #ifdef DEBUGXL /* Debug printing */ printk("Port 0xc46 (after): "); outb((tmp & ~0x04), 0xc44); /* Select bank=0 */ printk("%02x ", inb(0xc46)); outb((tmp | 0x04), 0xc44); /* Select bank=1 */ printk("%02x\n", inb(0xc46)); #endif /* * I/O port 0xc47 FM Address Decode Register. * * bank=0, bits 0xff: Decode enable selection for various FM address bits * bank=1, bits 0xff: Reserved */ #ifdef DEBUGXL /* Debug printing */ printk("Port 0xc47 (before): "); outb((tmp & ~0x04), 0xc44); /* Select bank=0 */ printk("%02x ", inb(0xc47)); outb((tmp | 0x04), 0xc44); /* Select bank=1 */ printk("%02x\n", inb(0xc47)); #endif outb((tmp & ~0x04), 0xc44); /* Select bank=0 */ outb((0x7c), 0xc47); /* FM decode enable bits = 0x7c */ outb((tmp | 0x04), 0xc44); /* Select bank=1 */ outb((0x00), 0xc47); /* Reserved bank1 = 0x00 */ #ifdef DEBUGXL /* Debug printing */ printk("Port 0xc47 (after): "); outb((tmp & ~0x04), 0xc44); /* Select bank=0 */ printk("%02x ", inb(0xc47)); outb((tmp | 0x04), 0xc44); /* Select bank=1 */ printk("%02x\n", inb(0xc47)); #endif /* * I/O port 0xc6f = Audio Disable Function Register */ #ifdef DEBUGXL printk("Port 0xc6f (before) = %02x\n", inb(0xc6f)); #endif outb((0x80), 0xc6f); #ifdef DEBUGXL printk("Port 0xc6f (after) = %02x\n", inb(0xc6f)); #endif return 1; } int probe_ms_sound(struct address_info *hw_config, struct resource *ports) { unsigned char tmp; DDB(printk("Entered probe_ms_sound(%x, %d)\n", hw_config->io_base, hw_config->card_subtype)); if (hw_config->card_subtype == 1) /* Has no IRQ/DMA registers */ { /* check_opl3(0x388, hw_config); */ return ad1848_detect(ports, NULL, hw_config->osp); } if (deskpro_xl && hw_config->card_subtype == 2) /* Compaq Deskpro XL */ { if (!init_deskpro(hw_config)) { return 0; } } if (deskpro_m) /* Compaq Deskpro M */ { if (!init_deskpro_m(hw_config)) { return 0; } } /* * Check if the IO port returns valid signature. The original MS Sound * system returns 0x04 while some cards (AudioTrix Pro for example) * return 0x00 or 0x0f. */ if ((tmp = inb(hw_config->io_base + 3)) == 0xff) /* Bus float */ { int ret; DDB(printk("I/O address is inactive (%x)\n", tmp)); if (!(ret = ad1848_detect(ports, NULL, hw_config->osp))) { return 0; } return 1; } DDB(printk("MSS signature = %x\n", tmp & 0x3f)); if ((tmp & 0x3f) != 0x04 && (tmp & 0x3f) != 0x0f && (tmp & 0x3f) != 0x00) { int ret; MDB(printk(KERN_ERR "No MSS signature detected on port 0x%x (0x%x)\n", hw_config->io_base, (int) inb(hw_config->io_base + 3))); DDB(printk("Trying to detect codec anyway but IRQ/DMA may not work\n")); if (!(ret = ad1848_detect(ports, NULL, hw_config->osp))) { return 0; } hw_config->card_subtype = 1; return 1; } if ((hw_config->irq != 5) && (hw_config->irq != 7) && (hw_config->irq != 9) && (hw_config->irq != 10) && (hw_config->irq != 11) && (hw_config->irq != 12)) { printk(KERN_ERR "MSS: Bad IRQ %d\n", hw_config->irq); return 0; } if (hw_config->dma != 0 && hw_config->dma != 1 && hw_config->dma != 3) { printk(KERN_ERR "MSS: Bad DMA %d\n", hw_config->dma); return 0; } /* * Check that DMA0 is not in use with a 8 bit board. */ if (hw_config->dma == 0 && inb(hw_config->io_base + 3) & 0x80) { printk(KERN_ERR "MSS: Can't use DMA0 with a 8 bit card/slot\n"); return 0; } if (hw_config->irq > 7 && hw_config->irq != 9 && inb(hw_config->io_base + 3) & 0x80) { printk(KERN_ERR "MSS: Can't use IRQ%d with a 8 bit card/slot\n", hw_config->irq); return 0; } return ad1848_detect(ports, NULL, hw_config->osp); } void attach_ms_sound(struct address_info *hw_config, struct resource *ports, struct module *owner) { static signed char interrupt_bits[12] = { -1, -1, -1, -1, -1, 0x00, -1, 0x08, -1, 0x10, 0x18, 0x20 }; signed char bits; char dma2_bit = 0; static char dma_bits[4] = { 1, 2, 0, 3 }; int config_port = hw_config->io_base + 0; int version_port = hw_config->io_base + 3; int dma = hw_config->dma; int dma2 = hw_config->dma2; if (hw_config->card_subtype == 1) /* Has no IRQ/DMA registers */ { hw_config->slots[0] = ad1848_init("MS Sound System", ports, hw_config->irq, hw_config->dma, hw_config->dma2, 0, hw_config->osp, owner); return; } /* * Set the IRQ and DMA addresses. */ bits = interrupt_bits[hw_config->irq]; if (bits == -1) { printk(KERN_ERR "MSS: Bad IRQ %d\n", hw_config->irq); release_region(ports->start, 4); release_region(ports->start - 4, 4); return; } outb((bits | 0x40), config_port); if ((inb(version_port) & 0x40) == 0) { printk(KERN_ERR "[MSS: IRQ Conflict?]\n"); } /* * Handle the capture DMA channel */ if (dma2 != -1 && dma2 != dma) { if (!((dma == 0 && dma2 == 1) || (dma == 1 && dma2 == 0) || (dma == 3 && dma2 == 0))) { /* Unsupported combination. Try to swap channels */ int tmp = dma; dma = dma2; dma2 = tmp; } if ((dma == 0 && dma2 == 1) || (dma == 1 && dma2 == 0) || (dma == 3 && dma2 == 0)) { dma2_bit = 0x04; /* Enable capture DMA */ } else { printk(KERN_WARNING "MSS: Invalid capture DMA\n"); dma2 = dma; } } else { dma2 = dma; } hw_config->dma = dma; hw_config->dma2 = dma2; outb((bits | dma_bits[dma] | dma2_bit), config_port); /* Write IRQ+DMA setup */ hw_config->slots[0] = ad1848_init("MS Sound System", ports, hw_config->irq, dma, dma2, 0, hw_config->osp, THIS_MODULE); } void unload_ms_sound(struct address_info *hw_config) { ad1848_unload(hw_config->io_base + 4, hw_config->irq, hw_config->dma, hw_config->dma2, 0); sound_unload_audiodev(hw_config->slots[0]); release_region(hw_config->io_base, 4); } #ifndef EXCLUDE_TIMERS /* * Timer stuff (for /dev/music). */ static unsigned int current_interval; static unsigned int ad1848_tmr_start(int dev, unsigned int usecs) { unsigned long flags; ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; unsigned long xtal_nsecs; /* nanoseconds per xtal oscillator tick */ unsigned long divider; spin_lock_irqsave(&devc->lock, flags); /* * Length of the timer interval (in nanoseconds) depends on the * selected crystal oscillator. Check this from bit 0x01 of I8. * * AD1845 has just one oscillator which has cycle time of 10.050 us * (when a 24.576 MHz xtal oscillator is used). * * Convert requested interval to nanoseconds before computing * the timer divider. */ if (devc->model == MD_1845 || devc->model == MD_1845_SSCAPE) { xtal_nsecs = 10050; } else if (ad_read(devc, 8) & 0x01) { xtal_nsecs = 9920; } else { xtal_nsecs = 9969; } divider = (usecs * 1000 + xtal_nsecs / 2) / xtal_nsecs; if (divider < 100) /* Don't allow shorter intervals than about 1ms */ { divider = 100; } if (divider > 65535) /* Overflow check */ { divider = 65535; } ad_write(devc, 21, (divider >> 8) & 0xff); /* Set upper bits */ ad_write(devc, 20, divider & 0xff); /* Set lower bits */ ad_write(devc, 16, ad_read(devc, 16) | 0x40); /* Start the timer */ devc->timer_running = 1; spin_unlock_irqrestore(&devc->lock, flags); return current_interval = (divider * xtal_nsecs + 500) / 1000; } static void ad1848_tmr_reprogram(int dev) { /* * Audio driver has changed sampling rate so that a different xtal * oscillator was selected. We have to reprogram the timer rate. */ ad1848_tmr_start(dev, current_interval); sound_timer_syncinterval(current_interval); } static void ad1848_tmr_disable(int dev) { unsigned long flags; ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; spin_lock_irqsave(&devc->lock, flags); ad_write(devc, 16, ad_read(devc, 16) & ~0x40); devc->timer_running = 0; spin_unlock_irqrestore(&devc->lock, flags); } static void ad1848_tmr_restart(int dev) { unsigned long flags; ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc; if (current_interval == 0) { return; } spin_lock_irqsave(&devc->lock, flags); ad_write(devc, 16, ad_read(devc, 16) | 0x40); devc->timer_running = 1; spin_unlock_irqrestore(&devc->lock, flags); } static struct sound_lowlev_timer ad1848_tmr = { 0, 2, ad1848_tmr_start, ad1848_tmr_disable, ad1848_tmr_restart }; static int ad1848_tmr_install(int dev) { if (timer_installed != -1) { return 0; /* Don't install another timer */ } timer_installed = ad1848_tmr.dev = dev; sound_timer_init(&ad1848_tmr, audio_devs[dev]->name); return 1; } #endif /* EXCLUDE_TIMERS */ EXPORT_SYMBOL(ad1848_detect); EXPORT_SYMBOL(ad1848_init); EXPORT_SYMBOL(ad1848_unload); EXPORT_SYMBOL(ad1848_control); EXPORT_SYMBOL(probe_ms_sound); EXPORT_SYMBOL(attach_ms_sound); EXPORT_SYMBOL(unload_ms_sound); static int __initdata io = -1; static int __initdata irq = -1; static int __initdata dma = -1; static int __initdata dma2 = -1; static int __initdata type = 0; module_param(io, int, 0); /* I/O for a raw AD1848 card */ module_param(irq, int, 0); /* IRQ to use */ module_param(dma, int, 0); /* First DMA channel */ module_param(dma2, int, 0); /* Second DMA channel */ module_param(type, int, 0); /* Card type */ module_param(deskpro_xl, bool, 0); /* Special magic for Deskpro XL boxen */ module_param(deskpro_m, bool, 0); /* Special magic for Deskpro M box */ module_param(soundpro, bool, 0); /* More special magic for SoundPro chips */ #ifdef CONFIG_PNP module_param(isapnp, int, 0); module_param(isapnpjump, int, 0); module_param(reverse, bool, 0); MODULE_PARM_DESC(isapnp, "When set to 0, Plug & Play support will be disabled"); MODULE_PARM_DESC(isapnpjump, "Jumps to a specific slot in the driver's PnP table. Use the source, Luke."); MODULE_PARM_DESC(reverse, "When set to 1, will reverse ISAPnP search order"); static struct pnp_dev *ad1848_dev = NULL; /* Please add new entries at the end of the table */ static struct { char *name; unsigned short card_vendor, card_device, vendor, function; short mss_io, irq, dma, dma2; /* index into isapnp table */ int type; } ad1848_isapnp_list[] __initdata = { { "CMI 8330 SoundPRO", ISAPNP_VENDOR('C', 'M', 'I'), ISAPNP_DEVICE(0x0001), ISAPNP_VENDOR('@', '@', '@'), ISAPNP_FUNCTION(0x0001), 0, 0, 0, -1, 0 }, { "CS4232 based card", ISAPNP_ANY_ID, ISAPNP_ANY_ID, ISAPNP_VENDOR('C', 'S', 'C'), ISAPNP_FUNCTION(0x0000), 0, 0, 0, 1, 0 }, { "CS4232 based card", ISAPNP_ANY_ID, ISAPNP_ANY_ID, ISAPNP_VENDOR('C', 'S', 'C'), ISAPNP_FUNCTION(0x0100), 0, 0, 0, 1, 0 }, { "OPL3-SA2 WSS mode", ISAPNP_ANY_ID, ISAPNP_ANY_ID, ISAPNP_VENDOR('Y', 'M', 'H'), ISAPNP_FUNCTION(0x0021), 1, 0, 0, 1, 1 }, { "Advanced Gravis InterWave Audio", ISAPNP_VENDOR('G', 'R', 'V'), ISAPNP_DEVICE(0x0001), ISAPNP_VENDOR('G', 'R', 'V'), ISAPNP_FUNCTION(0x0000), 0, 0, 0, 1, 0 }, {NULL} }; #ifdef MODULE static struct isapnp_device_id id_table[] = { { ISAPNP_VENDOR('C', 'M', 'I'), ISAPNP_DEVICE(0x0001), ISAPNP_VENDOR('@', '@', '@'), ISAPNP_FUNCTION(0x0001), 0 }, { ISAPNP_ANY_ID, ISAPNP_ANY_ID, ISAPNP_VENDOR('C', 'S', 'C'), ISAPNP_FUNCTION(0x0000), 0 }, { ISAPNP_ANY_ID, ISAPNP_ANY_ID, ISAPNP_VENDOR('C', 'S', 'C'), ISAPNP_FUNCTION(0x0100), 0 }, /* The main driver for this card is opl3sa2 { ISAPNP_ANY_ID, ISAPNP_ANY_ID, ISAPNP_VENDOR('Y','M','H'), ISAPNP_FUNCTION(0x0021), 0 }, */ { ISAPNP_VENDOR('G', 'R', 'V'), ISAPNP_DEVICE(0x0001), ISAPNP_VENDOR('G', 'R', 'V'), ISAPNP_FUNCTION(0x0000), 0 }, {0} }; MODULE_DEVICE_TABLE(isapnp, id_table); #endif static struct pnp_dev *activate_dev(char *devname, char *resname, struct pnp_dev *dev) { int err; err = pnp_device_attach(dev); if (err < 0) { return (NULL); } if ((err = pnp_activate_dev(dev)) < 0) { printk(KERN_ERR "ad1848: %s %s config failed (out of resources?)[%d]\n", devname, resname, err); pnp_device_detach(dev); return (NULL); } audio_activated = 1; return (dev); } static struct pnp_dev __init *ad1848_init_generic(struct pnp_card *bus, struct address_info *hw_config, int slot) { /* Configure Audio device */ if ((ad1848_dev = pnp_find_dev(bus, ad1848_isapnp_list[slot].vendor, ad1848_isapnp_list[slot].function, NULL))) { if ((ad1848_dev = activate_dev(ad1848_isapnp_list[slot].name, "ad1848", ad1848_dev))) { hw_config->io_base = pnp_port_start(ad1848_dev, ad1848_isapnp_list[slot].mss_io); hw_config->irq = pnp_irq(ad1848_dev, ad1848_isapnp_list[slot].irq); hw_config->dma = pnp_dma(ad1848_dev, ad1848_isapnp_list[slot].dma); if (ad1848_isapnp_list[slot].dma2 != -1) { hw_config->dma2 = pnp_dma(ad1848_dev, ad1848_isapnp_list[slot].dma2); } else { hw_config->dma2 = -1; } hw_config->card_subtype = ad1848_isapnp_list[slot].type; } else { return (NULL); } } else { return (NULL); } return (ad1848_dev); } static int __init ad1848_isapnp_init(struct address_info *hw_config, struct pnp_card *bus, int slot) { char *busname = bus->name[0] ? bus->name : ad1848_isapnp_list[slot].name; /* Initialize this baby. */ if (ad1848_init_generic(bus, hw_config, slot)) { /* We got it. */ printk(KERN_NOTICE "ad1848: PnP reports '%s' at i/o %#x, irq %d, dma %d, %d\n", busname, hw_config->io_base, hw_config->irq, hw_config->dma, hw_config->dma2); return 1; } return 0; } static int __init ad1848_isapnp_probe(struct address_info *hw_config) { static int first = 1; int i; /* Count entries in sb_isapnp_list */ for (i = 0; ad1848_isapnp_list[i].card_vendor != 0; i++); i--; /* Check and adjust isapnpjump */ if ( isapnpjump < 0 || isapnpjump > i) { isapnpjump = reverse ? i : 0; printk(KERN_ERR "ad1848: Valid range for isapnpjump is 0-%d. Adjusted to %d.\n", i, isapnpjump); } if (!first || !reverse) { i = isapnpjump; } first = 0; while (ad1848_isapnp_list[i].card_vendor != 0) { static struct pnp_card *bus = NULL; while ((bus = pnp_find_card( ad1848_isapnp_list[i].card_vendor, ad1848_isapnp_list[i].card_device, bus))) { if (ad1848_isapnp_init(hw_config, bus, i)) { isapnpjump = i; /* start next search from here */ return 0; } } i += reverse ? -1 : 1; } return -ENODEV; } #endif static int __init init_ad1848(void) { printk(KERN_INFO "ad1848/cs4248 codec driver Copyright (C) by Hannu Savolainen 1993-1996\n"); #ifdef CONFIG_PNP if (isapnp && (ad1848_isapnp_probe(&cfg) < 0) ) { printk(KERN_NOTICE "ad1848: No ISAPnP cards found, trying standard ones...\n"); isapnp = 0; } #endif if (io != -1) { struct resource *ports; if ( isapnp == 0 ) { if (irq == -1 || dma == -1) { printk(KERN_WARNING "ad1848: must give I/O , IRQ and DMA.\n"); return -EINVAL; } cfg.irq = irq; cfg.io_base = io; cfg.dma = dma; cfg.dma2 = dma2; cfg.card_subtype = type; } ports = request_region(io + 4, 4, "ad1848"); if (!ports) { return -EBUSY; } if (!request_region(io, 4, "WSS config")) { release_region(io + 4, 4); return -EBUSY; } if (!probe_ms_sound(&cfg, ports)) { release_region(io + 4, 4); release_region(io, 4); return -ENODEV; } attach_ms_sound(&cfg, ports, THIS_MODULE); loaded = 1; } return 0; } static void __exit cleanup_ad1848(void) { if (loaded) { unload_ms_sound(&cfg); } #ifdef CONFIG_PNP if (ad1848_dev) { if (audio_activated) { pnp_device_detach(ad1848_dev); } } #endif } module_init(init_ad1848); module_exit(cleanup_ad1848); #ifndef MODULE static int __init setup_ad1848(char *str) { /* io, irq, dma, dma2, type */ int ints[6]; str = get_options(str, ARRAY_SIZE(ints), ints); io = ints[1]; irq = ints[2]; dma = ints[3]; dma2 = ints[4]; type = ints[5]; return 1; } __setup("ad1848=", setup_ad1848); #endif MODULE_LICENSE("GPL");
williamfdevine/PrettyLinux
sound/oss/ad1848.c
C
gpl-3.0
77,160
/* * SPDX-License-Identifier: GPL-3.0 * * * (J)ava (M)iscellaneous (U)tilities (L)ibrary * * JMUL is a central repository for utilities which are used in my * other public and private repositories. * * Copyright (C) 2016 Kristian Kutin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * e-mail: [email protected] */ /* * This section contains meta informations. * * $Id$ */ package jmul.web.page; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import jmul.io.NestedStreams; import jmul.io.NestedStreamsImpl; import jmul.misc.exceptions.MultipleCausesException; import static jmul.string.Constants.FILE_SEPARATOR; import static jmul.string.Constants.SLASH; /** * This class represents an entity which loads web content from the file * system. * * @author Kristian Kutin */ public class PageLoader { /** * The base directory of the web content. */ private final File baseDirectory; /** * The file with the page content. */ private final File file; /** * Creates a new instance of a content loader. * * @param aBaseDirectory * a base directory * @param aFile * a file (i.e. file path) */ public PageLoader(File aBaseDirectory, File aFile) { baseDirectory = aBaseDirectory; file = aFile; } /** * Loads the web content. * * @return web content */ public PublishedPage loadContent() { String path = getPath(); NestedStreams nestedStreams = null; try { nestedStreams = openStreams(file); } catch (FileNotFoundException e) { String message = "Unable to load the web content (\"" + file + "\")!"; throw new PageLoaderException(message, e); } byte[] content = null; try { content = loadContent(nestedStreams); } catch (IOException e) { Throwable followupError = null; try { nestedStreams.close(); } catch (IOException f) { followupError = f; } String message = "Error while reading from file (\"" + file + "\")!"; if (followupError != null) { throw new PageLoaderException(message, new MultipleCausesException(e, followupError)); } else { throw new PageLoaderException(message, followupError); } } return new PublishedPage(path, content); } /** * Determines the web path for this file relative to the base directory. * * @param aBaseDirectory * @param aFile * * @return a path * * @throws IOException * is thrown if the specified directory or file cannot be resolved to * absolute paths */ private static String determinePath(File aBaseDirectory, File aFile) throws IOException { String directory = aBaseDirectory.getCanonicalPath(); String fileName = aFile.getCanonicalPath(); String path = fileName.replace(directory, ""); path = path.replace(FILE_SEPARATOR, SLASH); return path; } /** * Opens a stream to read from the specified file. * * @param aFile * * @return an input stream * * @throws FileNotFoundException * is thrown if the specified file doesn't exist */ private static NestedStreams openStreams(File aFile) throws FileNotFoundException { InputStream reader = new FileInputStream(aFile); return new NestedStreamsImpl(reader); } /** * Tries to load the web content from the specified file. * * @param someNestedStreams * * @return some web content * * @throws IOException * is thrown if an error occurred while reading from the file */ private static byte[] loadContent(NestedStreams someNestedStreams) throws IOException { InputStream reader = (InputStream) someNestedStreams.getOuterStream(); List<Byte> buffer = new ArrayList<>(); while (true) { int next = reader.read(); if (next == -1) { break; } buffer.add((byte) next); } int size = buffer.size(); byte[] bytes = new byte[size]; for (int a = 0; a < size; a++) { Byte b = buffer.get(a); bytes[a] = b; } return bytes; } /** * Returns the path of the web page. * * @return a path */ public String getPath() { String path = null; try { path = determinePath(baseDirectory, file); } catch (IOException e) { String message = "Unable to resolve paths (\"" + baseDirectory + "\" & \"" + file + "\")!"; throw new PageLoaderException(message, e); } return path; } }
gammalgris/jmul
Utilities/Web/src/jmul/web/page/PageLoader.java
Java
gpl-3.0
5,731
/** * @file gensvm_debug.c * @author G.J.J. van den Burg * @date 2016-05-01 * @brief Functions facilitating debugging * * @details * Defines functions useful for debugging matrices. * * @copyright Copyright 2016, G.J.J. van den Burg. This file is part of GenSVM. GenSVM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. GenSVM 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 GenSVM. If not, see <http://www.gnu.org/licenses/>. */ #include "gensvm_debug.h" /** * @brief Print a dense matrix * * @details * Debug function to print a matrix * * @param[in] M matrix * @param[in] rows number of rows of M * @param[in] cols number of columns of M */ void gensvm_print_matrix(double *M, long rows, long cols) { long i, j; for (i=0; i<rows; i++) { for (j=0; j<cols; j++) { if (j > 0) note(" "); note("%+6.6f", matrix_get(M, cols, i, j)); } note("\n"); } note("\n"); } /** * @brief Print a sparse matrix * * @details * Debug function to print a GenSparse sparse matrix * * @param[in] A a GenSparse matrix to print * */ void gensvm_print_sparse(struct GenSparse *A) { long i; // print matrix dimensions note("Sparse Matrix:\n"); note("\tnnz = %li, rows = %li, cols = %li\n", A->nnz, A->n_row, A->n_col); // print nonzero values note("\tvalues = [ "); for (i=0; i<A->nnz; i++) { if (i != 0) note(", "); note("%f", A->values[i]); } note(" ]\n"); // print row indices note("\tIA = [ "); for (i=0; i<A->n_row+1; i++) { if (i != 0) note(", "); note("%i", A->ia[i]); } note(" ]\n"); // print column indices note("\tJA = [ "); for (i=0; i<A->nnz; i++) { if (i != 0) note(", "); note("%i", A->ja[i]); } note(" ]\n"); }
GjjvdBurg/GenSVM
src/gensvm_debug.c
C
gpl-3.0
2,141
/******************************************************************************* * Australian National University Data Commons * Copyright (C) 2013 The Australian National University * * This file is part of Australian National University Data Commons. * * Australian National University Data Commons is free software: you * can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package au.edu.anu.datacommons.doi; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.StringWriter; import java.net.URI; import javax.ws.rs.core.UriBuilder; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.datacite.schema.kernel_4.Resource; import org.datacite.schema.kernel_4.Resource.Creators; import org.datacite.schema.kernel_4.Resource.Creators.Creator; import org.datacite.schema.kernel_4.Resource.Creators.Creator.CreatorName; import org.datacite.schema.kernel_4.Resource.Identifier; import org.datacite.schema.kernel_4.Resource.Titles; import org.datacite.schema.kernel_4.Resource.Titles.Title; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sun.jersey.test.framework.JerseyTest; public class DoiClientTest extends JerseyTest { private static final Logger LOGGER = LoggerFactory.getLogger(DoiClientTest.class); private DoiClient doiClient; private String sampleDoi = "10.5072/13/50639BFE25F18"; private static JAXBContext context; private Marshaller marshaller; private Unmarshaller unmarshaller; public DoiClientTest() { super("au.edu.anu.datacommons.doi"); // LOGGER.trace("In Constructor"); // WebResource webResource = resource(); // DoiConfig doiConfig = new DoiConfigImpl(webResource.getURI().toString(), appId); // doiClient = new DoiClient(doiConfig); doiClient = new DoiClient(); } @BeforeClass public static void setUpBeforeClass() throws Exception { context = JAXBContext.newInstance(Resource.class); } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { super.setUp(); marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://datacite.org/schema/kernel-2.2 http://schema.datacite.org/meta/kernel-2.2/metadata.xsd"); } @After public void tearDown() throws Exception { super.tearDown(); } @Ignore public void testMint() { try { doiClient.mint("https://datacommons.anu.edu.au:8443/DataCommons/item/anudc:3320", generateSampleResource()); String respStr = doiClient.getDoiResponseAsString(); LOGGER.trace(respStr); } catch (Exception e) { failOnException(e); } } @Ignore public void testUpdate() { try { Resource res = new Resource(); Creators creators = new Creators(); Creator creator = new Creator(); CreatorName creatorName = new CreatorName(); creatorName.setValue("Creator 1"); creator.setCreatorName(creatorName); creators.getCreator().add(creator); res.setCreators(creators); Titles titles = new Titles(); Title title = new Title(); title.setValue("Title 1"); titles.getTitle().add(title); res.setTitles(titles); res.setPublisher("Publisher 1"); res.setPublicationYear("1987"); Identifier id = new Identifier(); id.setValue(sampleDoi); id.setIdentifierType("DOI"); res.setIdentifier(id); doiClient.update(sampleDoi, null, res); Resource newRes = doiClient.getMetadata(sampleDoi); String resAsStr = getResourceAsString(newRes); LOGGER.trace(resAsStr); } catch (Exception e) { failOnException(e); } } @Ignore public void testDeactivate() { try { doiClient.deactivate(sampleDoi); assertTrue(doiClient.getDoiResponseAsString().indexOf("AbsolutePath:" + resource().getURI().toString() + "deactivate.xml/") != -1); // assertTrue(doiClient.getDoiResponseAsString().indexOf("QueryParam:app_id=TEST" + appId) != -1); assertTrue(doiClient.getDoiResponseAsString().indexOf("QueryParam:doi=" + sampleDoi) != -1); } catch (Exception e) { failOnException(e); } } @Ignore public void testActivate() { try { doiClient.activate(sampleDoi); assertTrue(doiClient.getDoiResponseAsString().indexOf("AbsolutePath:" + resource().getURI().toString() + "activate.xml/") != -1); // assertTrue(doiClient.getDoiResponseAsString().indexOf("QueryParam:app_id=TEST" + appId) != -1); assertTrue(doiClient.getDoiResponseAsString().indexOf("QueryParam:doi=" + sampleDoi) != -1); } catch (Exception e) { failOnException(e); } } @Test public void testGetDoiMetaData() { try { Resource res = doiClient.getMetadata(sampleDoi); StringWriter strW = new StringWriter(); marshaller.marshal(res, strW); // assertTrue(doiClient.getDoiResponseAsString().indexOf("AbsolutePath:" + resource().getURI().toString() + "xml.xml/") != -1); // assertTrue(doiClient.getDoiResponseAsString().indexOf("QueryParam:doi=" + sampleDoi) != -1); } catch (Exception e) { failOnException(e); } } private Resource generateSampleResource() { Resource metadata = new Resource(); Titles titles = new Titles(); Title title1 = new Title(); title1.setValue("Some title without a type"); titles.getTitle().add(title1); metadata.setTitles(titles); Creators creators = new Creators(); metadata.setCreators(creators); Creator creator = new Creator(); CreatorName creatorName = new CreatorName(); creatorName.setValue("Smith, John"); creator.setCreatorName(creatorName); metadata.getCreators().getCreator().add(creator); metadata.setPublisher("Some random publisher"); metadata.setPublicationYear("2010"); return metadata; } private String getResourceAsString(Resource res) throws JAXBException { StringWriter strW = new StringWriter(); marshaller.marshal(res, strW); return strW.toString(); } private void failOnException(Throwable e) { LOGGER.error(e.getMessage(), e); fail(e.getMessage()); } }
anu-doi/anudc
DataCommons/src/test/java/au/edu/anu/datacommons/doi/DoiClientTest.java
Java
gpl-3.0
6,942
/* Report an error and exit. Copyright (C) 2017-2019 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ /* Borrowed from coreutils. */ #ifndef DIE_H # define DIE_H # include <error.h> # include <stdbool.h> # include <verify.h> /* Like 'error (STATUS, ...)', except STATUS must be a nonzero constant. This may pacify the compiler or help it generate better code. */ # define die(status, ...) \ verify_expr (status, (error (status, __VA_ARGS__), assume (false))) #endif /* DIE_H */
pexip/os-findutils
lib/die.h
C
gpl-3.0
1,182
/* =========================================================================== Shadow of Dust GPL Source Code Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. This file is part of the Shadow of Dust GPL Source Code ("Shadow of Dust Source Code"). Shadow of Dust 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 3 of the License, or (at your option) any later version. Shadow of Dust 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 Shadow of Dust Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Shadow of Dust Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Shadow of Dust Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #pragma once // DialogAFView dialog class DialogAFView : public CDialog { DECLARE_DYNAMIC(DialogAFView) public: DialogAFView(CWnd* pParent = NULL); // standard constructor virtual ~DialogAFView(); enum { IDD = IDD_DIALOG_AF_VIEW }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support virtual int OnToolHitTest( CPoint point, TOOLINFO* pTI ) const; afx_msg BOOL OnToolTipNotify( UINT id, NMHDR *pNMHDR, LRESULT *pResult ); afx_msg void OnBnClickedCheckViewBodies(); afx_msg void OnBnClickedCheckViewBodynames(); afx_msg void OnBnClickedCheckViewBodyMass(); afx_msg void OnBnClickedCheckViewTotalMass(); afx_msg void OnBnClickedCheckViewInertiatensor(); afx_msg void OnBnClickedCheckViewVelocity(); afx_msg void OnBnClickedCheckViewConstraints(); afx_msg void OnBnClickedCheckViewConstraintnames(); afx_msg void OnBnClickedCheckViewPrimaryonly(); afx_msg void OnBnClickedCheckViewLimits(); afx_msg void OnBnClickedCheckViewConstrainedBodies(); afx_msg void OnBnClickedCheckViewTrees(); afx_msg void OnBnClickedCheckMd5Skeleton(); afx_msg void OnBnClickedCheckMd5Skeletononly(); afx_msg void OnBnClickedCheckLinesDepthtest(); afx_msg void OnBnClickedCheckLinesUsearrows(); afx_msg void OnBnClickedCheckPhysicsNofriction(); afx_msg void OnBnClickedCheckPhysicsNolimits(); afx_msg void OnBnClickedCheckPhysicsNogravity(); afx_msg void OnBnClickedCheckPhysicsNoselfcollision(); afx_msg void OnBnClickedCheckPhysicsTiming(); afx_msg void OnBnClickedCheckPhysicsDragEntities(); afx_msg void OnBnClickedCheckPhysicsShowDragSelection(); DECLARE_MESSAGE_MAP() private: //{{AFX_DATA(DialogAFView) BOOL m_showBodies; BOOL m_showBodyNames; BOOL m_showMass; BOOL m_showTotalMass; BOOL m_showInertia; BOOL m_showVelocity; BOOL m_showConstraints; BOOL m_showConstraintNames; BOOL m_showPrimaryOnly; BOOL m_showLimits; BOOL m_showConstrainedBodies; BOOL m_showTrees; BOOL m_showSkeleton; BOOL m_showSkeletonOnly; BOOL m_debugLineDepthTest; BOOL m_debugLineUseArrows; BOOL m_noFriction; BOOL m_noLimits; BOOL m_noGravity; BOOL m_noSelfCollision; BOOL m_showTimings; BOOL m_dragEntity; BOOL m_dragShowSelection; //}}AFX_DATA float m_gravity; static toolTip_t toolTips[]; };
Salamek/Shadow-of-Dust
neo/tools/af/DialogAFView.h
C
gpl-3.0
3,918
// Copyright 2016, Durachenko Aleksey V. <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include "version.h" #define STR_HELPER(x) #x #define STR(x) STR_HELPER(x) #ifndef APP_NAME #define APP_NAME "target" #endif #ifndef APP_MAJOR #define APP_MAJOR 0 #endif #ifndef APP_MINOR #define APP_MINOR 0 #endif #ifndef APP_PATCH #define APP_PATCH 0 #endif #ifndef APP_VERSION #define APP_VERSION STR(APP_MAJOR) "." STR(APP_MINOR) "." STR(APP_PATCH) #endif const char *appName() { return STR(APP_NAME); } const char *appShortName() { return STR(APP_NAME); } const char *appFullName() { return STR(APP_NAME); } const char *appVersion() { return STR(APP_VERSION); } const char *appBuildNumber() { #ifdef APP_BUILD_NUMBER return STR(APP_BUILD_NUMBER); #else return "0"; #endif } const char *appBuildDate() { #ifdef APP_BUILD_DATE return STR(APP_BUILD_DATE); #else return "0000-00-00T00:00:00+0000"; #endif } const char *appRevision() { #ifdef APP_REVISION return STR(APP_REVISION); #else return "0"; #endif } const char *appSources() { #ifdef APP_SOURCES return STR(APP_SOURCES); #else return ""; #endif }
AlekseyDurachenko/vkOAuth
src/version.cpp
C++
gpl-3.0
1,812
import { Model } from "chomex"; import catalog from "./catalog"; export interface DeckCaptureLike { _id: any; title: string; row: number; col: number; page: number; cell: { x: number; y: number; w: number, h: number; }; protected?: boolean; } /** * 編成キャプチャの設定を保存する用のモデル。 * ふつうの1艦隊編成もあれば、連合艦隊、航空基地編成などもある。 */ export default class DeckCapture extends Model { static __ns = "DeckCapture"; static default = { normal: { title: "編成キャプチャ", row: 3, col: 2, cell: catalog.fleet, protected: true, }, combined: { title: "連合編成キャプチャ", row: 3, col: 2, cell: catalog.fleet, protected: true, page: 2, pagelabel: ["第一艦隊", "第二艦隊"], }, aviation: { title: "基地航空隊", row: 1, col: 3, cell: catalog.aviation, protected: true, }, }; title: string; // この編成キャプチャ設定の名前 row: number; // 列数 col: number; // 行数 cell: { // 1セルの定義 x: number; // スタート座標X (ゲーム幅を1に対して) y: number; // スタート座標Y (ゲーム高を1に対して) w: number; // セル幅 (ゲーム幅を1に対して) h: number; // セル高 (ゲーム高を1に対して) }; protected = false; // 削除禁止 page = 1; // 繰り返しページ数 pagelabel: string[] = []; // ページごとのラベル obj(): DeckCaptureLike { return { _id: this._id, title: this.title, row: this.row, col: this.col, page: this.page, cell: {...this.cell}, protected: this.protected, }; } static listObj(): DeckCaptureLike[] { return this.list<DeckCapture>().map(d => d.obj()); } }
otiai10/kanColleWidget
src/js/Applications/Models/DeckCapture/index.ts
TypeScript
gpl-3.0
1,889
/******************************************************************************* MPhoto - Photo viewer for multi-touch devices Copyright (C) 2010 Mihai Paslariu This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ #include "ImageLoadQueue.h" // synchronized against all other methods ImageLoadItem ImageLoadQueue::pop ( void ) { ImageLoadItem x; _sem.acquire(); _mutex.lock(); x = QQueue<ImageLoadItem>::front(); QQueue<ImageLoadItem>::pop_front(); _mutex.unlock(); return x; } // synchronized against all other methods ImageLoadItem ImageLoadQueue::popWithPriority ( void ) { ImageLoadItem x; _sem.acquire(); _mutex.lock(); QQueue<ImageLoadItem>::Iterator it; QQueue<ImageLoadItem>::Iterator it_max; int max_prio = -1; for ( it = this->begin(); it != this->end(); it++ ) { if ( it->priority > max_prio ) { max_prio = it->priority; it_max = it; } } x = *it_max; this->erase( it_max ); _mutex.unlock(); return x; } // synchronized only against pop void ImageLoadQueue::push ( const ImageLoadItem &x ) { _mutex.lock(); QQueue<ImageLoadItem>::push_back(x); _sem.release(); _mutex.unlock(); } // synchronized only against pop QList<ImageLoadItem> ImageLoadQueue::clear( void ) { QList<ImageLoadItem> cleared_items = QList<ImageLoadItem>(); while ( _sem.tryAcquire() ) { ImageLoadItem x; _mutex.lock(); x = QQueue<ImageLoadItem>::front(); QQueue<ImageLoadItem>::pop_front(); _mutex.unlock(); cleared_items.append( x ); } return cleared_items; } void ImageLoadQueue::clearPriorities( void ) { _mutex.lock(); QQueue<ImageLoadItem>::Iterator it; for ( it = this->begin(); it != this->end(); it++ ) { it->priority = 0; } _mutex.unlock(); } void ImageLoadQueue::updatePriority( QImage ** dest, int priority ) { _mutex.lock(); QQueue<ImageLoadItem>::Iterator it; for ( it = this->begin(); it != this->end(); it++ ) { if ( it->destination == dest ) it->priority = priority; } _mutex.unlock(); }
miabrahams/MPhoto
dev/ImageLoadQueue.cpp
C++
gpl-3.0
2,610
/* * Copyright (C) 2007-2009 Daniel Prevost <[email protected]> * * This file is part of Photon (photonsoftware.org). * * This file may be distributed and/or modified under the terms of the * GNU General Public License version 2 or version 3 as published by the * Free Software Foundation and appearing in the file COPYING.GPL2 and * COPYING.GPL3 included in the packaging of this software. * * Licensees holding a valid Photon Commercial license can use this file * in accordance with the terms of their license. * * This software 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. */ /* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ #include "Nucleus/Hash.h" #include "Nucleus/Tests/Hash/HashTest.h" const bool expectedToPass = true; /* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ int main() { psonSessionContext context; psonHash* pHash; enum psoErrors errcode; char* key1 = "My Key 1"; char* key2 = "My Key 2"; char* data1 = "My Data 1"; char* data2 = "My Data 2"; psonHashItem * pHashItem; pHash = initHashTest( expectedToPass, &context ); errcode = psonHashInit( pHash, g_memObjOffset, 100, &context ); if ( errcode != PSO_OK ) { ERROR_EXIT( expectedToPass, &context.errorHandler, ; ); } errcode = psonHashInsert( pHash, (unsigned char*)key1, strlen(key1), data1, strlen(data1), &pHashItem, &context ); if ( errcode != PSO_OK ) { ERROR_EXIT( expectedToPass, &context.errorHandler, ; ); } /* A duplicate - not allowed */ errcode = psonHashInsert( pHash, (unsigned char*)key1, strlen(key1), data2, strlen(data2), &pHashItem, &context ); if ( errcode != PSO_ITEM_ALREADY_PRESENT ) { ERROR_EXIT( expectedToPass, NULL, ; ); } errcode = psonHashInsert( pHash, (unsigned char*)key2, strlen(key2), data1, strlen(data1), &pHashItem, &context ); if ( errcode != PSO_OK ) { ERROR_EXIT( expectedToPass, &context.errorHandler, ; ); } return 0; } /* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */
dprevost/photon
src/Nucleus/Tests/Hash/InsertPass.c
C
gpl-3.0
2,772
#ifndef LIGHTNET_SUBSAMPLE_MODULE_H #define LIGHTNET_SUBSAMPLE_MODULE_H #include "module.h" using namespace std; using FeatureMap = vector<vector<Neuron*>>; FeatureMap* matrifyNeurons(vector<Neuron*>& v, int sizex, int sizey) { FeatureMap *fmap = new FeatureMap(); fmap->resize(sizex); int z = 0; for(unsigned int x = 0; x < fmap->size(); x++) { fmap->at(x).resize(sizey); for(unsigned int y = 0; y < fmap->at(x).size(); y++) { fmap->at(x).at(y) = v.at(z); z++; } } return fmap; } class SubsampleModule : public Module { private: int inputSize; double lowerWeightLimit,upperWeightLimit; int sizex, sizey, numFeatures, featureSize; vector<FeatureMap*> featureMaps; public: SubsampleModule(int numFeatures, int sizex, int sizey) { this->sizex = sizex; this->sizey = sizey; this->featureSize = sizex*sizey; this->numFeatures = numFeatures; for(int n = 0; n < featureSize*numFeatures/pow(2,2); n++) { neurons.push_back(new Neuron(0.25, 0.25)); } for(int f = 0; f < numFeatures; f++) { vector<Neuron*> v(neurons.begin()+(f*floor(sizex/2.0)*floor(sizey/2.0)),neurons.begin()+((f+1)*floor(sizex/2.0)*floor(sizey/2.0))); featureMaps.push_back(matrifyNeurons(v,floor(sizex/2.0),floor(sizey/2.0))); } } void connect(Module* prev) { int z = 0; for(int f = 0; f < numFeatures; f++) { vector<Neuron*> v(prev->getNeurons().begin()+(f*sizex*sizey),prev->getNeurons().begin()+((f+1)*sizex*sizey)); FeatureMap* fmap = matrifyNeurons(v,sizex,sizey); for(int fx = 0; fx < featureMaps[f]->size(); fx++) { for(int fy = 0; fy < featureMaps[f]->at(0).size(); fy++) { for(int ix = fx*2; ix < fx*2 + 2; ix++) { for(int iy = fy*2; iy < fy*2 + 2; iy++) { //cout << f << " connecting " << fx << "," << fy << " to " << ix << "," << iy << endl; featureMaps[f]->at(fx).at(fy)->connect(fmap->at(ix).at(iy),new Weight()); } } } } } //cout << "size " << neurons.size() << endl; } void gradientDescent(double learningRate) {} }; #endif
DariusBxsci/LightNet
include/modules/SubsampleModule.h
C
gpl-3.0
2,230
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WithoutPath.DAL { using System; using System.Collections.Generic; public partial class ShipType { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public ShipType() { this.Characters = new HashSet<Character>(); } public int Id { get; set; } public long EveID { get; set; } public string Name { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Character> Characters { get; set; } } }
AndreyPSmith/WithoutPath
WithoutPath.DAL/ShipType.cs
C#
gpl-3.0
1,144
<?php /************************* Coppermine Photo Gallery ************************ Copyright (c) 2003-2016 Coppermine Dev Team v1.0 originally written by Gregory Demar This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 3 as published by the Free Software Foundation. ******************************************** Coppermine version: 1.6.03 $HeadURL$ **********************************************/ $base = array( 0x00 => 'ruk', 'rut', 'rup', 'ruh', 'rweo', 'rweog', 'rweogg', 'rweogs', 'rweon', 'rweonj', 'rweonh', 'rweod', 'rweol', 'rweolg', 'rweolm', 'rweolb', 0x10 => 'rweols', 'rweolt', 'rweolp', 'rweolh', 'rweom', 'rweob', 'rweobs', 'rweos', 'rweoss', 'rweong', 'rweoj', 'rweoc', 'rweok', 'rweot', 'rweop', 'rweoh', 0x20 => 'rwe', 'rweg', 'rwegg', 'rwegs', 'rwen', 'rwenj', 'rwenh', 'rwed', 'rwel', 'rwelg', 'rwelm', 'rwelb', 'rwels', 'rwelt', 'rwelp', 'rwelh', 0x30 => 'rwem', 'rweb', 'rwebs', 'rwes', 'rwess', 'rweng', 'rwej', 'rwec', 'rwek', 'rwet', 'rwep', 'rweh', 'rwi', 'rwig', 'rwigg', 'rwigs', 0x40 => 'rwin', 'rwinj', 'rwinh', 'rwid', 'rwil', 'rwilg', 'rwilm', 'rwilb', 'rwils', 'rwilt', 'rwilp', 'rwilh', 'rwim', 'rwib', 'rwibs', 'rwis', 0x50 => 'rwiss', 'rwing', 'rwij', 'rwic', 'rwik', 'rwit', 'rwip', 'rwih', 'ryu', 'ryug', 'ryugg', 'ryugs', 'ryun', 'ryunj', 'ryunh', 'ryud', 0x60 => 'ryul', 'ryulg', 'ryulm', 'ryulb', 'ryuls', 'ryult', 'ryulp', 'ryulh', 'ryum', 'ryub', 'ryubs', 'ryus', 'ryuss', 'ryung', 'ryuj', 'ryuc', 0x70 => 'ryuk', 'ryut', 'ryup', 'ryuh', 'reu', 'reug', 'reugg', 'reugs', 'reun', 'reunj', 'reunh', 'reud', 'reul', 'reulg', 'reulm', 'reulb', 0x80 => 'reuls', 'reult', 'reulp', 'reulh', 'reum', 'reub', 'reubs', 'reus', 'reuss', 'reung', 'reuj', 'reuc', 'reuk', 'reut', 'reup', 'reuh', 0x90 => 'ryi', 'ryig', 'ryigg', 'ryigs', 'ryin', 'ryinj', 'ryinh', 'ryid', 'ryil', 'ryilg', 'ryilm', 'ryilb', 'ryils', 'ryilt', 'ryilp', 'ryilh', 0xA0 => 'ryim', 'ryib', 'ryibs', 'ryis', 'ryiss', 'rying', 'ryij', 'ryic', 'ryik', 'ryit', 'ryip', 'ryih', 'ri', 'rig', 'rigg', 'rigs', 0xB0 => 'rin', 'rinj', 'rinh', 'rid', 'ril', 'rilg', 'rilm', 'rilb', 'rils', 'rilt', 'rilp', 'rilh', 'rim', 'rib', 'ribs', 'ris', 0xC0 => 'riss', 'ring', 'rij', 'ric', 'rik', 'rit', 'rip', 'rih', 'ma', 'mag', 'magg', 'mags', 'man', 'manj', 'manh', 'mad', 0xD0 => 'mal', 'malg', 'malm', 'malb', 'mals', 'malt', 'malp', 'malh', 'mam', 'mab', 'mabs', 'mas', 'mass', 'mang', 'maj', 'mac', 0xE0 => 'mak', 'mat', 'map', 'mah', 'mae', 'maeg', 'maegg', 'maegs', 'maen', 'maenj', 'maenh', 'maed', 'mael', 'maelg', 'maelm', 'maelb', 0xF0 => 'maels', 'maelt', 'maelp', 'maelh', 'maem', 'maeb', 'maebs', 'maes', 'maess', 'maeng', 'maej', 'maec', 'maek', 'maet', 'maep', 'maeh', );
coppermine-gallery/cpg1.6.x
include/transliteration/xb9.php
PHP
gpl-3.0
2,810
package co.edu.udea.ingenieriaweb.admitravel.bl; import java.util.List; import co.edu.udea.ingenieriaweb.admitravel.dto.PaqueteDeViaje; import co.edu.udea.ingenieriaweb.admitravel.util.exception.IWBLException; import co.edu.udea.ingenieriaweb.admitravel.util.exception.IWDaoException; /** * Clase DestinoBL define la funcionalidad a implementar en el DestinoBLImp * * @author Yeferson Marín * */ public interface PaqueteDeViajeBL { /** * Método que permite almacenar un paquete de viaje en el sistema * @param idPaquete tipo de identificación del paquete de viaje * @param destinos nombre del destinos (Este parametro no debería ir) * @param transporte transporte en el que se hace el viaje * @param alimentacion alimentación que lleva el viaje * @param duracionViaje duración del viaje tomado * @throws IWDaoException ocurre cuando hay un error en la base de datos * @throws IWBLException ocurre cuando hay un error de lógica del negocio en los datos a guardar */ public void guardar(String idPaquete, String destinos, String transporte, String alimentacion, String duracionViaje) throws IWDaoException, IWBLException; public void actualizar(PaqueteDeViaje paqueteDeViaje, String idPaquete, String destinos, String transporte, String alimentacion, String duracionViaje)throws IWDaoException, IWBLException; PaqueteDeViaje obtener(String idPaquete) throws IWDaoException, IWBLException; }
yefry/AdmiTravelSpring
AdmiTravelSpring/src/co/edu/udea/ingenieriaweb/admitravel/bl/PaqueteDeViajeBL.java
Java
gpl-3.0
1,439
// mailer.js var nodemailer = require('nodemailer'); var smtpTransport = nodemailer.createTransport("SMTP", { service: "Mandrill", debug: true, auth: { user: "[email protected]", pass: "k-AdDVcsNJ9oj8QYATVNGQ" } }); exports.sendEmailConfirmation = function(emailaddress, username, firstname, expiremoment, token){ var mailOptions = { from: "[email protected]", // sender address to: emailaddress, // list of receivers subject: "Confirm email and start Ativinos", // Subject line text: 'Hi ' +firstname+ ', your account, ' +username+ ', will be enabled after you confirm your email. Your account will be deleted by ' + expiremoment + ' if you do not verify email before then. To verify your email, visit http://www.ativinos.com/emailverify?token=' + token + '&username=' + username, html: 'Hi ' +firstname+ ', your account, ' +username+ ', will be enabled after you confirm your email. Your account will be deleted by ' + expiremoment + ' if you do not verify email before then. To verify your email, visit <a href="http://www.ativinos.com/emailverify?token=' + token + '&username=' + username + '">http://www.ativinos.com/emailverify?token=' + token + '&username=' + username + '</a>', } smtpTransport.sendMail(mailOptions, function(error, response){ if(error){ console.log(error); } }) }
evrom/ativinos---deprecated
local_modules/mailer.js
JavaScript
gpl-3.0
1,602
$(function(){ $('#telefone').mask('(99)9999-9999'); $('.editar').on({ click : function(){ var url = URI+"sistema/editar/"+$(this).attr('data-item'); window.location.href = url; } }); $('.deletar').on({ click : function(){ var $selecionados = get_selecionados(); if($selecionados.length > 0) { var $url = URI+"sistema/remover/"; if (window.confirm("deseja apagar os ("+$selecionados.length+") itens selecionados? ")) { $.post($url, { 'selecionados': $selecionados}, function(data){ pop_up(data, setTimeout(function(){location.reload()}, 100)); }); } } else { pop_up('nenhum item selecionado'); } } }); $('#description').on('keyup',function(){ var alvo = $("#char-digitado"); var max = 140; var digitados = $(this).val().length; var restante = max - digitados; if(digitados > max) { var val = $(this).val(); $(this).val(val.substr(0, max)); restante = 0; } alvo.html(restante); }); });
Carlos-Claro/admin2_0
js/sistema.js
JavaScript
gpl-3.0
1,437
def plotHistory(plot_context, axes): """ @type axes: matplotlib.axes.Axes @type plot_config: PlotConfig """ plot_config = plot_context.plotConfig() if ( not plot_config.isHistoryEnabled() or plot_context.history_data is None or plot_context.history_data.empty ): return data = plot_context.history_data style = plot_config.historyStyle() lines = axes.plot_date( x=data.index.values, y=data, color=style.color, alpha=style.alpha, marker=style.marker, linestyle=style.line_style, linewidth=style.width, markersize=style.size, ) if len(lines) > 0 and style.isVisible(): plot_config.addLegendItem("History", lines[0])
joakim-hove/ert
ert_gui/plottery/plots/history.py
Python
gpl-3.0
771
# -*- coding: UTF-8 -*- """ Desc: django util. Note: --------------------------------------- # 2016/04/30 kangtian created """ from hashlib import md5 def gen_md5(content_str): m = md5() m.update(content_str) return m.hexdigest()
tiankangkan/paper_plane
k_util/hash_util.py
Python
gpl-3.0
257
/* Copyright (C) 2013 Edwin Velds This file is part of Polka 2. Polka 2 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Polka 2 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 Polka 2. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _POLKA_BITMAPCANVAS_H_ #define _POLKA_BITMAPCANVAS_H_ #include "Object.h" #include "ObjectManager.h" #include "icons/sketch.c" #include <glibmm/i18n.h> #include <cairomm/surface.h> namespace Polka { /* class Palette; class BitmapCanvas : public Polka::Object { public: BitmapCanvas( int depth ); ~BitmapCanvas(); enum Type { BP2, BP4, BP6, BRGB332, BRGB555 }; int width() const; int height() const; const Palette *getPalette( unsigned int slot = 0 ) const; Cairo::RefPtr<Cairo::ImageSurface> getImage() const; void setPalette( const Palette& palette, unsigned int slot = 0 ); protected: virtual void doUpdate(); private: Cairo::RefPtr<Cairo::ImageSurface> m_Image; std::vector<char*> m_Data; std::vector<const Palette *> m_Palettes; }; class Bitmap16CanvasFactory : public ObjectManager::ObjectFactory { public: BitmapCanvasFactory() : ObjectManager::ObjectFactory( _("16 Color Canvas"), _("Sketch canvasses"), 20, "BMP16CANVAS", "BITMAPCANVASEDIT", "PAL1,PAL2,PALG9K", sketch ) {} Object *create() const { return new BitmapCanvas( BitmapCanvas::BP4 ); } }; */ } // namespace Polka #endif // _POLKA_BITMAPCANVAS_H_
edwin-v/polka2
src/objects/BitmapCanvas.h
C
gpl-3.0
2,003
/* avr_libs Copyright (C) 2014 Edward Sargsyan avr_libs is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. avr_libs 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 avr_libs. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SD_CMD_H #define SD_SD_CMD_H /* CMD0: response R1 */ #define SD_CMD_GO_IDLE_STATE 0x00 /* CMD1: response R1 */ #define SD_CMD_SEND_OP_COND 0x01 /* CMD8: response R7 */ #define SD_CMD_SEND_IF_COND 0x08 /* CMD9: response R1 */ #define SD_CMD_SEND_CSD 0x09 /* CMD10: response R1 */ #define SD_CMD_SEND_CID 0x0a /* CMD12: response R1 */ #define SD_CMD_STOP_TRANSMISSION 0x0c /* CMD13: response R2 */ #define SD_CMD_SEND_STATUS 0x0d /* CMD16: arg0[31:0]: block length, response R1 */ #define SD_CMD_SET_BLOCKLEN 0x10 /* CMD17: arg0[31:0]: data address, response R1 */ #define SD_CMD_READ_SINGLE_BLOCK 0x11 /* CMD18: arg0[31:0]: data address, response R1 */ #define SD_CMD_READ_MULTIPLE_BLOCK 0x12 /* CMD24: arg0[31:0]: data address, response R1 */ #define SD_CMD_WRITE_SINGLE_BLOCK 0x18 /* CMD25: arg0[31:0]: data address, response R1 */ #define SD_CMD_WRITE_MULTIPLE_BLOCK 0x19 /* CMD27: response R1 */ #define SD_CMD_PROGRAM_CSD 0x1b /* CMD28: arg0[31:0]: data address, response R1b */ #define SD_CMD_SET_WRITE_PROT 0x1c /* CMD29: arg0[31:0]: data address, response R1b */ #define SD_CMD_CLR_WRITE_PROT 0x1d /* CMD30: arg0[31:0]: write protect data address, response R1 */ #define SD_CMD_SEND_WRITE_PROT 0x1e /* CMD32: arg0[31:0]: data address, response R1 */ #define SD_CMD_TAG_SECTOR_START 0x20 /* CMD33: arg0[31:0]: data address, response R1 */ #define SD_CMD_TAG_SECTOR_END 0x21 /* CMD34: arg0[31:0]: data address, response R1 */ #define SD_CMD_UNTAG_SECTOR 0x22 /* CMD35: arg0[31:0]: data address, response R1 */ #define SD_CMD_TAG_ERASE_GROUP_START 0x23 /* CMD36: arg0[31:0]: data address, response R1 */ #define SD_CMD_TAG_ERASE_GROUP_END 0x24 /* CMD37: arg0[31:0]: data address, response R1 */ #define SD_CMD_UNTAG_ERASE_GROUP 0x25 /* CMD38: arg0[31:0]: stuff bits, response R1b */ #define SD_CMD_ERASE 0x26 /* ACMD41: arg0[31:0]: OCR contents, response R1 */ #define SD_CMD_GET_OCR 0x29 /* CMD42: arg0[31:0]: stuff bits, response R1b */ #define SD_CMD_LOCK_UNLOCK 0x2a /* CMD55: arg0[31:0]: stuff bits, response R1 */ #define SD_CMD_APP 0x37 /* CMD58: arg0[31:0]: stuff bits, response R3 */ #define SD_CMD_READ_OCR 0x3a /* CMD59: arg0[31:1]: stuff bits, arg0[0:0]: crc option, response R1 */ #define SD_CMD_CRC_ON_OFF 0x3b /* command responses */ /* R1: size 1 byte */ #define SD_R1_IDLE_STATE 0 #define SD_R1_ERASE_RESET 1 #define SD_R1_ILLEGAL_COMMAND 2 #define SD_R1_COM_CRC_ERR 3 #define SD_R1_ERASE_SEQ_ERR 4 #define SD_R1_ADDR_ERR 5 #define SD_R1_PARAM_ERR 6 /* R1b: equals R1, additional busy bytes */ /* R2: size 2 bytes */ #define SD_R2_CARD_LOCKED 0 #define SD_R2_WP_ERASE_SKIP 1 #define SD_R2_ERR 2 #define SD_R2_CARD_ERR 3 #define SD_R2_CARD_ECC_FAIL 4 #define SD_R2_WP_VIOLATION 5 #define SD_R2_INVAL_ERASE 6 #define SD_R2_OUT_OF_RANGE 7 #define SD_R2_CSD_OVERWRITE 7 #define SD_R2_IDLE_STATE ( SD_R1_IDLE_STATE + 8) #define SD_R2_ERASE_RESET ( SD_R1_ERASE_RESET + 8) #define SD_R2_ILLEGAL_COMMAND ( SD_R1_ILLEGAL_COMMAND + 8) #define SD_R2_COM_CRC_ERR ( SD_R1_COM_CRC_ERR + 8) #define SD_R2_ERASE_SEQ_ERR ( SD_R1_ERASE_SEQ_ERR + 8) #define SD_R2_ADDR_ERR ( SD_R1_ADDR_ERR + 8) #define SD_R2_PARAM_ERR ( SD_R1_PARAM_ERR + 8) /* R3: size 5 bytes */ #define SD_R3_OCR_MASK (0xffffffffUL) #define SD_R3_IDLE_STATE ( SD_R1_IDLE_STATE + 32) #define SD_R3_ERASE_RESET ( SD_R1_ERASE_RESET + 32) #define SD_R3_ILLEGAL_COMMAND ( SD_R1_ILLEGAL_COMMAND + 32) #define SD_R3_COM_CRC_ERR ( SD_R1_COM_CRC_ERR + 32) #define SD_R3_ERASE_SEQ_ERR ( SD_R1_ERASE_SEQ_ERR + 32) #define SD_R3_ADDR_ERR ( SD_R1_ADDR_ERR + 32) #define SD_R3_PARAM_ERR ( SD_R1_PARAM_ERR + 32) /* Data Response: size 1 byte */ #define SD_DR_STATUS_MASK 0x0e #define SD_DR_STATUS_ACCEPTED 0x05 #define SD_DR_STATUS_CRC_ERR 0x0a #define SD_DR_STATUS_WRITE_ERR 0x0c #endif // SD_CMD_H
edwardoid/avr_libs
sd/sd_cmd.h
C
gpl-3.0
4,449
using System; namespace Server.Network { public delegate void OnPacketReceive( NetState state, PacketReader pvSrc ); public delegate bool ThrottlePacketCallback( NetState state ); public class PacketHandler { public PacketHandler( int packetID, int length, bool ingame, OnPacketReceive onReceive ) { PacketID = packetID; Length = length; Ingame = ingame; OnReceive = onReceive; } public int PacketID { get; } public int Length { get; } public OnPacketReceive OnReceive { get; } public ThrottlePacketCallback ThrottleCallback { get; set; } public bool Ingame { get; } } }
xrunuo/xrunuo
Server/Network/PacketHandler.cs
C#
gpl-3.0
640
package com.github.wglanzer.redmine; import java.util.function.Consumer; /** * Interface that is able to create background-tasks * * @author w.glanzer, 11.12.2016. */ public interface IRTaskCreator { /** * Executes a given task in background * * @param pTask Task that should be done in background * @return the given task */ <T extends ITask> T executeInBackground(T pTask); /** * Progress, that can be executed */ interface ITask extends Consumer<IProgressIndicator> { /** * @return the name of the current progress */ String getName(); } /** * Indicator-Interface to call back to UI */ interface IProgressIndicator { /** * Adds the given number to percentage * * @param pPercentage 0-100 */ void addPercentage(double pPercentage); } }
wglanzer/redmine-intellij-plugin
core/src/main/java/com/github/wglanzer/redmine/IRTaskCreator.java
Java
gpl-3.0
841
<?php $namespacetree = array( 'vector' => array( ), 'std' => array( 'vector' => array( 'inner' => array( ) ) ) ); $string = "while(!acceptable(a)) perform_random_actions(&a);";
nitro2010/moodle
blocks/formal_langs/parsertests/input/old/while.php
PHP
gpl-3.0
249
#ifndef VIDDEF_H #define VIDDEF_H #include <QObject> // FFmpeg is a pure C project, so to use the libraries within your C++ application you need // to explicitly state that you are using a C library by using extern "C"." extern "C" { #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libavformat/avio.h> #include <libswscale/swscale.h> #include <libavutil/avstring.h> #include <libavutil/time.h> #include <libavutil/mem.h> #include <libavutil/pixfmt.h> } #include <cmath> #define MAX_VIDEOQ_SIZE (5 * 256 * 1024) #define AV_SYNC_THRESHOLD 0.01 #define AV_NOSYNC_THRESHOLD 10.0 #define VIDEO_PICTURE_QUEUE_SIZE 1 // YUV_Overlay is similar to SDL_Overlay // A SDL_Overlay is similar to a SDL_Surface except it stores a YUV overlay. // Possible format: #define SDL_YV12_OVERLAY 0x32315659 /* Planar mode: Y + V + U */ #define SDL_IYUV_OVERLAY 0x56555949 /* Planar mode: Y + U + V */ #define SDL_YUY2_OVERLAY 0x32595559 /* Packed mode: Y0+U0+Y1+V0 */ #define SDL_UYVY_OVERLAY 0x59565955 /* Packed mode: U0+Y0+V0+Y1 */ #define SDL_YVYU_OVERLAY 0x55595659 /* Packed mode: Y0+V0+Y1+U0 */ typedef struct Overlay { quint32 format; int w, h; int planes; quint16 *pitches; quint8 **pixels; quint32 hw_overlay:1; } YUV_Overlay; typedef struct PacketQueue { AVPacketList *first_pkt, *last_pkt; int nb_packets; int size; } PacketQueue; typedef struct VideoPicture { YUV_Overlay *bmp; int width, height; /* source height & width */ int allocated; double pts; } VideoPicture; typedef struct VideoState { AVFormatContext *pFormatCtx; int videoStream; double frame_timer; double frame_last_pts; double frame_last_delay; double video_clock; ///<pts of last decoded frame / predicted pts of next decoded frame AVStream *video_st; PacketQueue videoq; VideoPicture pictq[VIDEO_PICTURE_QUEUE_SIZE]; int pictq_size, pictq_rindex, pictq_windex; int quit; AVIOContext *io_context; struct SwsContext *sws_ctx; } VideoState; #endif // VIDDEF_H
indarsugiarto/Graceful_ImagePro
gui/SpiNNvidStreamer/SpiNNvidStreamer/viddef.h
C
gpl-3.0
2,123
// ADOBE SYSTEMS INCORPORATED // Copyright 1993 - 2002 Adobe Systems Incorporated // All Rights Reserved // // NOTICE: Adobe permits you to use, modify, and distribute this // file in accordance with the terms of the Adobe license agreement // accompanying it. If you have received this file from a source // other than Adobe, then your use, modification, or distribution // of it requires the prior written permission of Adobe. //------------------------------------------------------------------- /* File: NearestBaseUIWin.c C source file for Windows specific code for Color Picker example. */ #include "NearestBase.h" #include "DialogUtilities.h" /*****************************************************************************/ DLLExport BOOL WINAPI PickerProc(HWND hDlg, UINT wMsg, WPARAM wParam, LPARAM lParam); // Win32 Change /*****************************************************************************/ void DoAbout (AboutRecordPtr about) { ShowAbout(about); } /*****************************************************************************/ DLLExport BOOL WINAPI PickerProc(HWND hDlg, UINT wMsg, WPARAM wParam, LPARAM lParam) // Win32 Change { int idd; // WIN32 Change static GPtr globals=NULL; /* need to be static */ long x = 0; switch (wMsg) { case WM_INITDIALOG: /* set up globals */ globals = (GPtr) lParam; CenterDialog(hDlg); /* fall into WM_PAINT */ case WM_PAINT: return FALSE; break; case WM_COMMAND: idd = COMMANDID (wParam); // WIN32 Change if (idd == x) // any radio groups ; // handle radios; else { switch (idd) { case OK: // assign to globals EndDialog(hDlg, idd); break; case CANCEL: gResult = userCanceledErr; EndDialog(hDlg, idd); // WIN32 change break; default: return FALSE; break; } } break; default: return FALSE; break; } return TRUE; } /*****************************************************************************/ Boolean DoParameters (GPtr globals) { INT_PTR nResult = noErr; PlatformData *platform; platform = (PlatformData *)((PickerRecordPtr) gStuff)->platformData; /* Query the user for parameters. */ nResult = DialogBoxParam(GetDLLInstance(), (LPSTR)"PICKERPARAM", (HWND)platform->hwnd, (DLGPROC)PickerProc, (LPARAM)globals); return (nResult == OK); // could be -1 } // NearestBaseUIWin.cpp
wholegroup/vector
external/Adobe Photoshop CS6 SDK/samplecode/colorpicker/nearestbase/win/NearestBaseUIWin.cpp
C++
gpl-3.0
2,478
# Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier
theguardian/LazyLibrarian_Old
lazylibrarian/notifiers/tweet.py
Python
gpl-3.0
5,477
--- date: "2015-10-07T00:00:00Z" link: http://musicemojis.tumblr.com/ remoteImage: true title: Music Emojis category: Inspiration --- _A showcase of musicians in the minimal style of emojis!_ By [Bruno Leo Ribeiro](http://www.brunoleoribeiro.com/#kauko-home)
tholman/inspiring-online
content/posts/2015-09-12-music-emojis.md
Markdown
gpl-3.0
261
/* * This file is part of Cleanflight. * * Cleanflight is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Cleanflight 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 Cleanflight. If not, see <http://www.gnu.org/licenses/>. */ /* * telemetry_hott.c * * Authors: * Konstantin Sharlaimov - HoTT code cleanup, proper state machine implementation, bi-directional serial port operation cleanup * Dominic Clifton - Hydra - Software Serial, Electronics, Hardware Integration and debugging, HoTT Code cleanup and fixes, general telemetry improvements. * Carsten Giesen - cGiesen - Baseflight port * Oliver Bayer - oBayer - MultiWii-HoTT, HoTT reverse engineering * Adam Majerczyk - HoTT-for-ardupilot from which some information and ideas are borrowed. * * https://github.com/obayer/MultiWii-HoTT * https://github.com/oBayer/MultiHoTT-Module * https://code.google.com/p/hott-for-ardupilot * * HoTT is implemented in Graupner equipment using a bi-directional protocol over a single wire. * * Generally the receiver sends a single request byte out using normal uart signals, then waits a short period for a * multiple byte response and checksum byte before it sends out the next request byte. * Each response byte must be send with a protocol specific delay between them. * * Serial ports use two wires but HoTT uses a single wire so some electronics are required so that * the signals don't get mixed up. When cleanflight transmits it should not receive it's own transmission. * * Connect as follows: * HoTT TX/RX -> Serial RX (connect directly) * Serial TX -> 1N4148 Diode -(| )-> HoTT TX/RX (connect via diode) * * The diode should be arranged to allow the data signals to flow the right way * -(| )- == Diode, | indicates cathode marker. * * As noticed by Skrebber the GR-12 (and probably GR-16/24, too) are based on a PIC 24FJ64GA-002, which has 5V tolerant digital pins. * * Note: The softserial ports are not listed as 5V tolerant in the STM32F103xx data sheet pinouts and pin description * section. Verify if you require a 5v/3.3v level shifters. The softserial port should not be inverted. * * There is a technical discussion (in German) about HoTT here * http://www.rc-network.de/forum/showthread.php/281496-Graupner-HoTT-Telemetrie-Sensoren-Eigenbau-DIY-Telemetrie-Protokoll-entschl%C3%BCsselt/page21 */ #include <stdbool.h> #include <stdint.h> #include <string.h> #include "platform.h" #if defined(TELEMETRY) && defined(TELEMETRY_HOTT) #include "build/build_config.h" #include "build/debug.h" #include "common/axis.h" #include "common/time.h" #include "drivers/time.h" #include "drivers/serial.h" #include "fc/runtime_config.h" #include "flight/pid.h" #include "io/serial.h" #include "io/gps.h" #include "navigation/navigation.h" #include "sensors/sensors.h" #include "sensors/battery.h" #include "telemetry/telemetry.h" #include "telemetry/hott.h" //#define HOTT_DEBUG typedef enum { HOTT_WAITING_FOR_REQUEST, HOTT_RECEIVING_REQUEST, HOTT_WAITING_FOR_TX_WINDOW, HOTT_TRANSMITTING, HOTT_ENDING_TRANSMISSION } hottState_e; #define HOTT_MESSAGE_PREPARATION_FREQUENCY_5_HZ ((1000 * 1000) / 5) #define HOTT_RX_SCHEDULE 4000 #define HOTT_TX_SCHEDULE 5000 #define HOTT_TX_DELAY_US 2000 #define MILLISECONDS_IN_A_SECOND 1000 static hottState_e hottState = HOTT_WAITING_FOR_REQUEST; static timeUs_t hottStateChangeUs = 0; static uint8_t *hottTxMsg = NULL; static uint8_t hottTxMsgSize; static uint8_t hottTxMsgCrc; #define HOTT_BAUDRATE 19200 #define HOTT_INITIAL_PORT_MODE MODE_RXTX static serialPort_t *hottPort = NULL; static serialPortConfig_t *portConfig; static bool hottTelemetryEnabled = false; static portSharing_e hottPortSharing; static HOTT_GPS_MSG_t hottGPSMessage; static HOTT_EAM_MSG_t hottEAMMessage; static void hottSwitchState(hottState_e newState, timeUs_t currentTimeUs) { if (hottState != newState) { hottState = newState; hottStateChangeUs = currentTimeUs; } } static void initialiseEAMMessage(HOTT_EAM_MSG_t *msg, size_t size) { memset(msg, 0, size); msg->start_byte = 0x7C; msg->eam_sensor_id = HOTT_TELEMETRY_EAM_SENSOR_ID; msg->sensor_id = HOTT_EAM_SENSOR_TEXT_ID; msg->stop_byte = 0x7D; } #ifdef GPS typedef enum { GPS_FIX_CHAR_NONE = '-', GPS_FIX_CHAR_2D = '2', GPS_FIX_CHAR_3D = '3', GPS_FIX_CHAR_DGPS = 'D', } gpsFixChar_e; static void initialiseGPSMessage(HOTT_GPS_MSG_t *msg, size_t size) { memset(msg, 0, size); msg->start_byte = 0x7C; msg->gps_sensor_id = HOTT_TELEMETRY_GPS_SENSOR_ID; msg->sensor_id = HOTT_GPS_SENSOR_TEXT_ID; msg->stop_byte = 0x7D; } #endif static void initialiseMessages(void) { initialiseEAMMessage(&hottEAMMessage, sizeof(hottEAMMessage)); #ifdef GPS initialiseGPSMessage(&hottGPSMessage, sizeof(hottGPSMessage)); #endif } #ifdef GPS void addGPSCoordinates(HOTT_GPS_MSG_t *hottGPSMessage, int32_t latitude, int32_t longitude) { int16_t deg = latitude / GPS_DEGREES_DIVIDER; int32_t sec = (latitude - (deg * GPS_DEGREES_DIVIDER)) * 6; int8_t min = sec / 1000000L; sec = (sec % 1000000L) / 100L; uint16_t degMin = (deg * 100L) + min; hottGPSMessage->pos_NS = (latitude < 0); hottGPSMessage->pos_NS_dm_L = degMin; hottGPSMessage->pos_NS_dm_H = degMin >> 8; hottGPSMessage->pos_NS_sec_L = sec; hottGPSMessage->pos_NS_sec_H = sec >> 8; deg = longitude / GPS_DEGREES_DIVIDER; sec = (longitude - (deg * GPS_DEGREES_DIVIDER)) * 6; min = sec / 1000000L; sec = (sec % 1000000L) / 100L; degMin = (deg * 100L) + min; hottGPSMessage->pos_EW = (longitude < 0); hottGPSMessage->pos_EW_dm_L = degMin; hottGPSMessage->pos_EW_dm_H = degMin >> 8; hottGPSMessage->pos_EW_sec_L = sec; hottGPSMessage->pos_EW_sec_H = sec >> 8; } void hottPrepareGPSResponse(HOTT_GPS_MSG_t *hottGPSMessage) { hottGPSMessage->gps_satelites = gpsSol.numSat; // Report climb rate regardless of GPS fix const int32_t climbrate = MAX(0, getEstimatedActualVelocity(Z) + 30000); hottGPSMessage->climbrate_L = climbrate & 0xFF; hottGPSMessage->climbrate_H = climbrate >> 8; const int32_t climbrate3s = MAX(0, 3.0f * getEstimatedActualVelocity(Z) / 100 + 120); hottGPSMessage->climbrate3s = climbrate3s & 0xFF; if (!STATE(GPS_FIX)) { hottGPSMessage->gps_fix_char = GPS_FIX_CHAR_NONE; return; } if (gpsSol.fixType == GPS_FIX_3D) { hottGPSMessage->gps_fix_char = GPS_FIX_CHAR_3D; } else { hottGPSMessage->gps_fix_char = GPS_FIX_CHAR_2D; } addGPSCoordinates(hottGPSMessage, gpsSol.llh.lat, gpsSol.llh.lon); // GPS Speed is returned in cm/s (from io/gps.c) and must be sent in km/h (Hott requirement) const uint16_t speed = (gpsSol.groundSpeed * 36) / 1000; hottGPSMessage->gps_speed_L = speed & 0x00FF; hottGPSMessage->gps_speed_H = speed >> 8; hottGPSMessage->home_distance_L = GPS_distanceToHome & 0x00FF; hottGPSMessage->home_distance_H = GPS_distanceToHome >> 8; const uint16_t hottGpsAltitude = (gpsSol.llh.alt / 100) + HOTT_GPS_ALTITUDE_OFFSET; // meters hottGPSMessage->altitude_L = hottGpsAltitude & 0x00FF; hottGPSMessage->altitude_H = hottGpsAltitude >> 8; hottGPSMessage->home_direction = GPS_directionToHome; } #endif static inline void updateAlarmBatteryStatus(HOTT_EAM_MSG_t *hottEAMMessage) { static uint32_t lastHottAlarmSoundTime = 0; if (((millis() - lastHottAlarmSoundTime) >= (telemetryConfig()->hottAlarmSoundInterval * MILLISECONDS_IN_A_SECOND))){ lastHottAlarmSoundTime = millis(); batteryState_e batteryState = getBatteryState(); if (batteryState == BATTERY_WARNING || batteryState == BATTERY_CRITICAL){ hottEAMMessage->warning_beeps = 0x10; hottEAMMessage->alarm_invers1 = HOTT_EAM_ALARM1_FLAG_BATTERY_1; } else { hottEAMMessage->warning_beeps = HOTT_EAM_ALARM1_FLAG_NONE; hottEAMMessage->alarm_invers1 = HOTT_EAM_ALARM1_FLAG_NONE; } } } static inline void hottEAMUpdateBattery(HOTT_EAM_MSG_t *hottEAMMessage) { hottEAMMessage->main_voltage_L = vbat & 0xFF; hottEAMMessage->main_voltage_H = vbat >> 8; hottEAMMessage->batt1_voltage_L = vbat & 0xFF; hottEAMMessage->batt1_voltage_H = vbat >> 8; updateAlarmBatteryStatus(hottEAMMessage); } static inline void hottEAMUpdateCurrentMeter(HOTT_EAM_MSG_t *hottEAMMessage) { const int32_t amp = amperage / 10; hottEAMMessage->current_L = amp & 0xFF; hottEAMMessage->current_H = amp >> 8; } static inline void hottEAMUpdateBatteryDrawnCapacity(HOTT_EAM_MSG_t *hottEAMMessage) { const int32_t mAh = mAhDrawn / 10; hottEAMMessage->batt_cap_L = mAh & 0xFF; hottEAMMessage->batt_cap_H = mAh >> 8; } static inline void hottEAMUpdateAltitudeAndClimbrate(HOTT_EAM_MSG_t *hottEAMMessage) { const int32_t alt = MAX(0, getEstimatedActualPosition(Z) / 100.0f + HOTT_GPS_ALTITUDE_OFFSET); // Value of 500 = 0m hottEAMMessage->altitude_L = alt & 0xFF; hottEAMMessage->altitude_H = alt >> 8; const int32_t climbrate = MAX(0, getEstimatedActualVelocity(Z) + 30000); hottEAMMessage->climbrate_L = climbrate & 0xFF; hottEAMMessage->climbrate_H = climbrate >> 8; const int32_t climbrate3s = MAX(0, 3.0f * getEstimatedActualVelocity(Z) / 100 + 120); hottEAMMessage->climbrate3s = climbrate3s & 0xFF; } void hottPrepareEAMResponse(HOTT_EAM_MSG_t *hottEAMMessage) { // Reset alarms hottEAMMessage->warning_beeps = 0x0; hottEAMMessage->alarm_invers1 = 0x0; hottEAMUpdateBattery(hottEAMMessage); hottEAMUpdateCurrentMeter(hottEAMMessage); hottEAMUpdateBatteryDrawnCapacity(hottEAMMessage); hottEAMUpdateAltitudeAndClimbrate(hottEAMMessage); } static void hottSerialWrite(uint8_t c) { static uint8_t serialWrites = 0; serialWrites++; serialWrite(hottPort, c); } void freeHoTTTelemetryPort(void) { closeSerialPort(hottPort); hottPort = NULL; hottTelemetryEnabled = false; } void initHoTTTelemetry(void) { portConfig = findSerialPortConfig(FUNCTION_TELEMETRY_HOTT); hottPortSharing = determinePortSharing(portConfig, FUNCTION_TELEMETRY_HOTT); initialiseMessages(); } void configureHoTTTelemetryPort(void) { if (!portConfig) { return; } hottPort = openSerialPort(portConfig->identifier, FUNCTION_TELEMETRY_HOTT, NULL, HOTT_BAUDRATE, HOTT_INITIAL_PORT_MODE, SERIAL_NOT_INVERTED); if (!hottPort) { return; } hottTelemetryEnabled = true; } static void hottQueueSendResponse(uint8_t *buffer, int length) { hottTxMsg = buffer; hottTxMsgSize = length; } static bool processBinaryModeRequest(uint8_t address) { switch (address) { #ifdef GPS case 0x8A: if (sensors(SENSOR_GPS)) { hottPrepareGPSResponse(&hottGPSMessage); hottQueueSendResponse((uint8_t *)&hottGPSMessage, sizeof(hottGPSMessage)); return true; } break; #endif case 0x8E: hottPrepareEAMResponse(&hottEAMMessage); hottQueueSendResponse((uint8_t *)&hottEAMMessage, sizeof(hottEAMMessage)); return true; } return false; } static void flushHottRxBuffer(void) { while (serialRxBytesWaiting(hottPort) > 0) { serialRead(hottPort); } } static bool hottSendTelemetryDataByte(timeUs_t currentTimeUs) { static timeUs_t byteSentTimeUs = 0; // Guard intra-byte interval if (currentTimeUs - byteSentTimeUs < HOTT_TX_DELAY_US) { return false; } if (hottTxMsgSize == 0) { // Send CRC byte hottSerialWrite(hottTxMsgCrc); return true; } else { // Send data byte hottTxMsgCrc += *hottTxMsg; hottSerialWrite(*hottTxMsg); hottTxMsg++; hottTxMsgSize--; return false; } } void checkHoTTTelemetryState(void) { bool newTelemetryEnabledValue = telemetryDetermineEnabledState(hottPortSharing); if (newTelemetryEnabledValue == hottTelemetryEnabled) { return; } if (newTelemetryEnabledValue) configureHoTTTelemetryPort(); else freeHoTTTelemetryPort(); } void handleHoTTTelemetry(timeUs_t currentTimeUs) { static uint8_t hottRequestBuffer[2]; static int hottRequestBufferPtr = 0; if (!hottTelemetryEnabled) return; bool reprocessState; do { reprocessState = false; switch (hottState) { case HOTT_WAITING_FOR_REQUEST: if (serialRxBytesWaiting(hottPort)) { hottRequestBufferPtr = 0; hottSwitchState(HOTT_RECEIVING_REQUEST, currentTimeUs); reprocessState = true; } break; case HOTT_RECEIVING_REQUEST: if ((currentTimeUs - hottStateChangeUs) >= HOTT_RX_SCHEDULE) { // Waiting for too long - resync flushHottRxBuffer(); hottSwitchState(HOTT_WAITING_FOR_REQUEST, currentTimeUs); } else { while (serialRxBytesWaiting(hottPort) && hottRequestBufferPtr < 2) { hottRequestBuffer[hottRequestBufferPtr++] = serialRead(hottPort); } if (hottRequestBufferPtr >= 2) { if ((hottRequestBuffer[0] == 0) || (hottRequestBuffer[0] == HOTT_BINARY_MODE_REQUEST_ID)) { /* * FIXME the first byte of the HoTT request frame is ONLY either 0x80 (binary mode) or 0x7F (text mode). * The binary mode is read as 0x00 (error reading the upper bit) while the text mode is correctly decoded. * The (requestId == 0) test is a workaround for detecting the binary mode with no ambiguity as there is only * one other valid value (0x7F) for text mode. * The error reading for the upper bit should nevertheless be fixed */ if (processBinaryModeRequest(hottRequestBuffer[1])) { hottSwitchState(HOTT_WAITING_FOR_TX_WINDOW, currentTimeUs); } else { hottSwitchState(HOTT_WAITING_FOR_REQUEST, currentTimeUs); } } else if (hottRequestBuffer[0] == HOTT_TEXT_MODE_REQUEST_ID) { // FIXME Text mode hottSwitchState(HOTT_WAITING_FOR_REQUEST, currentTimeUs); } else { // Received garbage - resync flushHottRxBuffer(); hottSwitchState(HOTT_WAITING_FOR_REQUEST, currentTimeUs); } reprocessState = true; } } break; case HOTT_WAITING_FOR_TX_WINDOW: if ((currentTimeUs - hottStateChangeUs) >= HOTT_TX_SCHEDULE) { hottTxMsgCrc = 0; hottSwitchState(HOTT_TRANSMITTING, currentTimeUs); } break; case HOTT_TRANSMITTING: if (hottSendTelemetryDataByte(currentTimeUs)) { hottSwitchState(HOTT_ENDING_TRANSMISSION, currentTimeUs); } break; case HOTT_ENDING_TRANSMISSION: if ((currentTimeUs - hottStateChangeUs) >= HOTT_TX_DELAY_US) { flushHottRxBuffer(); hottSwitchState(HOTT_WAITING_FOR_REQUEST, currentTimeUs); reprocessState = true; } break; }; } while (reprocessState); } #endif
rb1205/inav
src/main/telemetry/hott.c
C
gpl-3.0
16,523
/* This file is part of Clementine. Copyright 2010, David Sansome <[email protected]> Clementine is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clementine 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 Clementine. If not, see <http://www.gnu.org/licenses/>. */ #include <Python.h> #include "core/utilities.h" #include "playlist/songplaylistitem.h" #include "scripting/script.h" #include "scripting/scriptmanager.h" #include "scripting/python/pythonengine.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "testobjectdecorators.h" #include "test_utils.h" #include <QSettings> #include <QtDebug> #include <boost/noncopyable.hpp> class TemporaryScript : boost::noncopyable { public: TemporaryScript(const QString& code, const QString& directory_template = QString()) { directory_ = Utilities::MakeTempDir(directory_template); QSettings ini(directory_ + "/script.ini", QSettings::IniFormat); ini.beginGroup("Script"); ini.setValue("language", "python"); ini.setValue("script_file", "script.py"); QFile script(directory_ + "/script.py"); script.open(QIODevice::WriteOnly); script.write(code.toUtf8()); } ~TemporaryScript() { if (!directory_.isEmpty()) { Utilities::RemoveRecursive(directory_); } } QString directory_; }; class PythonTest : public ::testing::Test { protected: static void SetUpTestCase() { sManager = new ScriptManager; sEngine = qobject_cast<PythonEngine*>( sManager->EngineForLanguage(ScriptInfo::Language_Python)); sEngine->EnsureInitialised(); PythonQt::self()->addDecorators(new TestObjectDecorators()); } static void TearDownTestCase() { delete sManager; } static ScriptManager* sManager; static PythonEngine* sEngine; }; ScriptManager* PythonTest::sManager = NULL; PythonEngine* PythonTest::sEngine = NULL; TEST_F(PythonTest, HasPythonEngine) { ASSERT_TRUE(sEngine); } TEST_F(PythonTest, InitFromDirectory) { TemporaryScript script("pass"); ScriptInfo info; info.InitFromDirectory(sManager, script.directory_); EXPECT_TRUE(info.is_valid()); EXPECT_EQ(script.directory_, info.path()); EXPECT_EQ(ScriptInfo::Language_Python, info.language()); EXPECT_EQ(NULL, info.loaded()); } TEST_F(PythonTest, StdioIsRedirected) { TemporaryScript script( "import sys\n" "print 'text on stdout'\n" "print >>sys.stderr, 'text on stderr'\n"); ScriptInfo info; info.InitFromDirectory(sManager, script.directory_); sEngine->CreateScript(info); QString log = sManager->log_lines_plain().join("\n"); ASSERT_TRUE(log.contains("text on stdout")); ASSERT_TRUE(log.contains("text on stderr")); } TEST_F(PythonTest, CleanupModuleDict) { TemporaryScript script( "class Foo:\n" " def __init__(self):\n" " print 'constructor'\n" " def __del__(self):\n" " print 'destructor'\n" "f = Foo()\n"); ScriptInfo info; info.InitFromDirectory(sManager, script.directory_); Script* s = sEngine->CreateScript(info); ASSERT_TRUE(sManager->log_lines_plain().last().endsWith("constructor")); sEngine->DestroyScript(s); ASSERT_TRUE(sManager->log_lines_plain().last().endsWith("destructor")); } TEST_F(PythonTest, CleanupSignalConnections) { TemporaryScript script( "from PythonQt.QtCore import QCoreApplication\n" "class Foo:\n" " def __init__(self):\n" " QCoreApplication.instance().connect('aboutToQuit()', self.aslot)\n" " def __del__(self):\n" " print 'destructor'\n" " def aslot(self):\n" " pass\n" "f = Foo()\n"); ScriptInfo info; info.InitFromDirectory(sManager, script.directory_); sEngine->DestroyScript(sEngine->CreateScript(info)); ASSERT_TRUE(sManager->log_lines_plain().last().endsWith("destructor")); } TEST_F(PythonTest, ModuleConstants) { TemporaryScript script( "print type(__builtins__)\n" "print __file__\n" "print __name__\n" "print __package__\n" "print __path__\n" "print __script__\n"); ScriptInfo info; info.InitFromDirectory(sManager, script.directory_); sEngine->CreateScript(info); const QStringList log = sManager->log_lines_plain(); const int n = log.count(); ASSERT_GE(n, 6); EXPECT_TRUE(log.at(n-6).endsWith("<type 'dict'>")); // __builtins__ EXPECT_TRUE(log.at(n-5).endsWith(script.directory_ + "/script.py")); // __file__ EXPECT_TRUE(log.at(n-4).endsWith("clementinescripts." + info.id())); // __name__ EXPECT_TRUE(log.at(n-3).endsWith("None")); // __package__ EXPECT_TRUE(log.at(n-2).endsWith("['" + script.directory_ + "']")); // __path__ EXPECT_TRUE(log.at(n-1).contains("ScriptInterface (QObject ")); // __script__ } TEST_F(PythonTest, PythonQtAttrSetWrappedCPP) { // Tests 3rdparty/pythonqt/patches/call-slot-returnvalue.patch TemporaryScript script( "import PythonQt.QtGui\n" "PythonQt.QtGui.QStyleOption().version = 123\n" "PythonQt.QtGui.QStyleOption().version = 123\n" "PythonQt.QtGui.QStyleOption().version = 123\n"); ScriptInfo info; info.InitFromDirectory(sManager, script.directory_); EXPECT_TRUE(sEngine->CreateScript(info)); } TEST_F(PythonTest, PythonQtArgumentReferenceCount) { // Tests 3rdparty/pythonqt/patches/argument-reference-count.patch TemporaryScript script( "from PythonQt.QtCore import QFile, QObject\n" "class Foo(QFile):\n" " def Init(self, parent):\n" " QFile.__init__(self, parent)\n" "parent = QObject()\n" "Foo().Init(parent)\n" "assert parent\n"); ScriptInfo info; info.InitFromDirectory(sManager, script.directory_); EXPECT_TRUE(sEngine->CreateScript(info)); } TEST_F(PythonTest, PythonQtConversionStack) { // Tests 3rdparty/pythonqt/patches/conversion-stack.patch // This crash is triggered when a C++ thing calls a virtual method on a // python wrapper and that wrapper returns a QString, QByteArray or // QStringList. In this instance, initStyleOption() calls text() in Foo. TemporaryScript script( "from PythonQt.QtGui import QProgressBar, QStyleOptionProgressBar\n" "class Foo(QProgressBar):\n" " def text(self):\n" " return 'something'\n" "for _ in xrange(1000):\n" " Foo().initStyleOption(QStyleOptionProgressBar())\n"); ScriptInfo info; info.InitFromDirectory(sManager, script.directory_); EXPECT_TRUE(sEngine->CreateScript(info)); }
ximion/Clementine-LibDanceTag
tests/python_test.cpp
C++
gpl-3.0
7,034
<?php class ControllerCommonLanguage extends Controller { public function index() { $this->load->language('common/language'); $data['action'] = $this->url->link('common/language/language', '', $this->request->server['HTTPS']); $data['code'] = $this->session->data['language']; $this->load->model('localisation/language'); $data['languages'] = array(); $results = $this->model_localisation_language->getLanguages(); foreach ($results as $result) { if ($result['status']) { $data['languages'][] = array( 'layout' => 1, 'name' => $result['name'], 'code' => $result['code'] ); } } if (!isset($this->request->get['route'])) { $data['redirect'] = $this->url->link('common/home'); } else { $url_data = $this->request->get; unset($url_data['_route_']); $route = $url_data['route']; unset($url_data['route']); $url = ''; if ($url_data) { $url = '&' . urldecode(http_build_query($url_data, '', '&')); } $data['redirect'] = $this->url->link($route, $url, $this->request->server['HTTPS']); } return $this->load->view('common/language', $data); } public function language() { if (isset($this->request->post['code'])) { $this->session->data['language'] = $this->request->post['code']; } if (isset($this->request->post['redirect'])) { $this->response->redirect($this->request->post['redirect']); } else { $this->response->redirect($this->url->link('common/home')); } } }
vocxod/cintez
www/catalog/controller/common/language.php
PHP
gpl-3.0
1,477
/** * Copyright (C) 2008 Happy Fish / YuQing * * FastDFS may be copied only under the terms of the GNU General * Public License V3, which may be found in the FastDFS source kit. * Please visit the FastDFS Home Page http://www.csource.org/ for more detail. **/ //tracker_nio.h #ifndef _TRACKER_NIO_H #define _TRACKER_NIO_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include "fast_task_queue.h" #ifdef __cplusplus extern "C" { #endif /* * ÿ¸öÏ̵߳ĹܵÀpipe_fds[0]µÄREADʼþµÄ»Øµ÷º¯Êý * ÿ´Î¶Áȡһ¸öint±äÁ¿£¬ÊÇн¨Á¢Á¬½ÓµÄsocketÃèÊö·û£¬Ö®ºó¼ÓÈëµ½IOʼþ¼¯ºÏ * °´Í¨µÀ·Ö·¢µ½ÏàÓ¦¹¤×÷Ïß³ÌÖеȴý¿É¶Áʼþ´¥·¢ºóµ÷ÓÃclient_sock_readº¯Êý½øÐд¦Àí */ void recv_notify_read(int sock, short event, void *arg); /* ½«·¢Ëͱ¨ÎĵÄʼþ¼ÓÈëµ½IOʼþ¼¯ºÏÖÐ */ int send_add_event(struct fast_task_info *pTask); /* ÈÎÎñ½áÊøºóµÄÇåÀíº¯Êý */ void task_finish_clean_up(struct fast_task_info *pTask); #ifdef __cplusplus } #endif #endif
fatedier/studies
fastdfs-5.01/tracker/tracker_nio.h
C
gpl-3.0
937
using System; using System.Collections; using System.IO; namespace Server.Engines.Reports { public class StaffHistory : PersistableObject { #region Type Identification public static readonly PersistableType ThisTypeID = new PersistableType("stfhst", new ConstructCallback(Construct)); private static PersistableObject Construct() { return new StaffHistory(); } public override PersistableType TypeID { get { return ThisTypeID; } } #endregion private PageInfoCollection m_Pages; private QueueStatusCollection m_QueueStats; private Hashtable m_UserInfo; private Hashtable m_StaffInfo; public PageInfoCollection Pages { get { return this.m_Pages; } set { this.m_Pages = value; } } public QueueStatusCollection QueueStats { get { return this.m_QueueStats; } set { this.m_QueueStats = value; } } public Hashtable UserInfo { get { return this.m_UserInfo; } set { this.m_UserInfo = value; } } public Hashtable StaffInfo { get { return this.m_StaffInfo; } set { this.m_StaffInfo = value; } } public void AddPage(PageInfo info) { lock (SaveLock) this.m_Pages.Add(info); info.History = this; } public StaffHistory() { this.m_Pages = new PageInfoCollection(); this.m_QueueStats = new QueueStatusCollection(); this.m_UserInfo = new Hashtable(StringComparer.OrdinalIgnoreCase); this.m_StaffInfo = new Hashtable(StringComparer.OrdinalIgnoreCase); } public StaffInfo GetStaffInfo(string account) { lock (RenderLock) { if (account == null || account.Length == 0) return null; StaffInfo info = this.m_StaffInfo[account] as StaffInfo; if (info == null) this.m_StaffInfo[account] = info = new StaffInfo(account); return info; } } public UserInfo GetUserInfo(string account) { if (account == null || account.Length == 0) return null; UserInfo info = this.m_UserInfo[account] as UserInfo; if (info == null) this.m_UserInfo[account] = info = new UserInfo(account); return info; } public static readonly object RenderLock = new object(); public static readonly object SaveLock = new object(); public void Save() { lock (SaveLock) { if (!Directory.Exists("Output")) { Directory.CreateDirectory("Output"); } string path = Path.Combine(Core.BaseDirectory, "Output/staffHistory.xml"); PersistanceWriter pw = new XmlPersistanceWriter(path, "Staff"); pw.WriteDocument(this); pw.Close(); } } public void Load() { string path = Path.Combine(Core.BaseDirectory, "Output/staffHistory.xml"); if (!File.Exists(path)) return; PersistanceReader pr = new XmlPersistanceReader(path, "Staff"); pr.ReadDocument(this); pr.Close(); } public override void SerializeChildren(PersistanceWriter op) { for (int i = 0; i < this.m_Pages.Count; ++i) this.m_Pages[i].Serialize(op); for (int i = 0; i < this.m_QueueStats.Count; ++i) this.m_QueueStats[i].Serialize(op); } public override void DeserializeChildren(PersistanceReader ip) { DateTime min = DateTime.UtcNow - TimeSpan.FromDays(8.0); while (ip.HasChild) { PersistableObject obj = ip.GetChild(); if (obj is PageInfo) { PageInfo pageInfo = obj as PageInfo; pageInfo.UpdateResolver(); if (pageInfo.TimeSent >= min || pageInfo.TimeResolved >= min) { this.m_Pages.Add(pageInfo); pageInfo.History = this; } else { pageInfo.Sender = null; pageInfo.Resolver = null; } } else if (obj is QueueStatus) { QueueStatus queueStatus = obj as QueueStatus; if (queueStatus.TimeStamp >= min) this.m_QueueStats.Add(queueStatus); } } } public StaffInfo[] GetStaff() { StaffInfo[] staff = new StaffInfo[this.m_StaffInfo.Count]; int index = 0; foreach (StaffInfo staffInfo in this.m_StaffInfo.Values) staff[index++] = staffInfo; return staff; } public void Render(ObjectCollection objects) { lock (RenderLock) { objects.Add(this.GraphQueueStatus()); StaffInfo[] staff = this.GetStaff(); BaseInfo.SortRange = TimeSpan.FromDays(7.0); Array.Sort(staff); objects.Add(this.GraphHourlyPages(this.m_Pages, PageResolution.None, "New pages by hour", "graph_new_pages_hr")); objects.Add(this.GraphHourlyPages(this.m_Pages, PageResolution.Handled, "Handled pages by hour", "graph_handled_pages_hr")); objects.Add(this.GraphHourlyPages(this.m_Pages, PageResolution.Deleted, "Deleted pages by hour", "graph_deleted_pages_hr")); objects.Add(this.GraphHourlyPages(this.m_Pages, PageResolution.Canceled, "Canceled pages by hour", "graph_canceled_pages_hr")); objects.Add(this.GraphHourlyPages(this.m_Pages, PageResolution.Logged, "Logged-out pages by hour", "graph_logged_pages_hr")); BaseInfo.SortRange = TimeSpan.FromDays(1.0); Array.Sort(staff); objects.Add(this.ReportTotalPages(staff, TimeSpan.FromDays(1.0), "1 Day")); objects.AddRange((PersistableObject[])this.ChartTotalPages(staff, TimeSpan.FromDays(1.0), "1 Day", "graph_daily_pages")); BaseInfo.SortRange = TimeSpan.FromDays(7.0); Array.Sort(staff); objects.Add(this.ReportTotalPages(staff, TimeSpan.FromDays(7.0), "1 Week")); objects.AddRange((PersistableObject[])this.ChartTotalPages(staff, TimeSpan.FromDays(7.0), "1 Week", "graph_weekly_pages")); BaseInfo.SortRange = TimeSpan.FromDays(30.0); Array.Sort(staff); objects.Add(this.ReportTotalPages(staff, TimeSpan.FromDays(30.0), "1 Month")); objects.AddRange((PersistableObject[])this.ChartTotalPages(staff, TimeSpan.FromDays(30.0), "1 Month", "graph_monthly_pages")); for (int i = 0; i < staff.Length; ++i) objects.Add(this.GraphHourlyPages(staff[i])); } } public static int GetPageCount(StaffInfo staff, DateTime min, DateTime max) { return GetPageCount(staff.Pages, PageResolution.Handled, min, max); } public static int GetPageCount(PageInfoCollection pages, PageResolution res, DateTime min, DateTime max) { int count = 0; for (int i = 0; i < pages.Count; ++i) { if (res != PageResolution.None && pages[i].Resolution != res) continue; DateTime ts = pages[i].TimeResolved; if (ts >= min && ts < max) ++count; } return count; } private BarGraph GraphQueueStatus() { int[] totals = new int[24]; int[] counts = new int[24]; DateTime max = DateTime.UtcNow; DateTime min = max - TimeSpan.FromDays(7.0); for (int i = 0; i < this.m_QueueStats.Count; ++i) { DateTime ts = this.m_QueueStats[i].TimeStamp; if (ts >= min && ts < max) { DateTime date = ts.Date; TimeSpan time = ts.TimeOfDay; int hour = time.Hours; totals[hour] += this.m_QueueStats[i].Count; counts[hour]++; } } BarGraph barGraph = new BarGraph("Average pages in queue", "graph_pagequeue_avg", 10, "Time", "Pages", BarGraphRenderMode.Lines); barGraph.FontSize = 6; for (int i = 7; i <= totals.Length + 7; ++i) { int val; if (counts[i % totals.Length] == 0) val = 0; else val = (totals[i % totals.Length] + (counts[i % totals.Length] / 2)) / counts[i % totals.Length]; int realHours = i % totals.Length; int hours; if (realHours == 0) hours = 12; else if (realHours > 12) hours = realHours - 12; else hours = realHours; barGraph.Items.Add(hours + (realHours >= 12 ? " PM" : " AM"), val); } return barGraph; } private BarGraph GraphHourlyPages(StaffInfo staff) { return this.GraphHourlyPages(staff.Pages, PageResolution.Handled, "Average pages handled by " + staff.Display, "graphs_" + staff.Account.ToLower() + "_avg"); } private BarGraph GraphHourlyPages(PageInfoCollection pages, PageResolution res, string title, string fname) { int[] totals = new int[24]; int[] counts = new int[24]; DateTime[] dates = new DateTime[24]; DateTime max = DateTime.UtcNow; DateTime min = max - TimeSpan.FromDays(7.0); bool sentStamp = (res == PageResolution.None); for (int i = 0; i < pages.Count; ++i) { if (res != PageResolution.None && pages[i].Resolution != res) continue; DateTime ts = (sentStamp ? pages[i].TimeSent : pages[i].TimeResolved); if (ts >= min && ts < max) { DateTime date = ts.Date; TimeSpan time = ts.TimeOfDay; int hour = time.Hours; totals[hour]++; if (dates[hour] != date) { counts[hour]++; dates[hour] = date; } } } BarGraph barGraph = new BarGraph(title, fname, 10, "Time", "Pages", BarGraphRenderMode.Lines); barGraph.FontSize = 6; for (int i = 7; i <= totals.Length + 7; ++i) { int val; if (counts[i % totals.Length] == 0) val = 0; else val = (totals[i % totals.Length] + (counts[i % totals.Length] / 2)) / counts[i % totals.Length]; int realHours = i % totals.Length; int hours; if (realHours == 0) hours = 12; else if (realHours > 12) hours = realHours - 12; else hours = realHours; barGraph.Items.Add(hours + (realHours >= 12 ? " PM" : " AM"), val); } return barGraph; } private Report ReportTotalPages(StaffInfo[] staff, TimeSpan ts, string title) { DateTime max = DateTime.UtcNow; DateTime min = max - ts; Report report = new Report(title + " Staff Report", "400"); report.Columns.Add("65%", "left", "Staff Name"); report.Columns.Add("35%", "center", "Page Count"); for (int i = 0; i < staff.Length; ++i) report.Items.Add(staff[i].Display, GetPageCount(staff[i], min, max)); return report; } private PieChart[] ChartTotalPages(StaffInfo[] staff, TimeSpan ts, string title, string fname) { DateTime max = DateTime.UtcNow; DateTime min = max - ts; PieChart staffChart = new PieChart(title + " Staff Chart", fname + "_staff", true); int other = 0; for (int i = 0; i < staff.Length; ++i) { int count = GetPageCount(staff[i], min, max); if (i < 12 && count > 0) staffChart.Items.Add(staff[i].Display, count); else other += count; } if (other > 0) staffChart.Items.Add("Other", other); PieChart resChart = new PieChart(title + " Resolutions", fname + "_resol", true); int countTotal = GetPageCount(this.m_Pages, PageResolution.None, min, max); int countHandled = GetPageCount(this.m_Pages, PageResolution.Handled, min, max); int countDeleted = GetPageCount(this.m_Pages, PageResolution.Deleted, min, max); int countCanceled = GetPageCount(this.m_Pages, PageResolution.Canceled, min, max); int countLogged = GetPageCount(this.m_Pages, PageResolution.Logged, min, max); int countUnres = countTotal - (countHandled + countDeleted + countCanceled + countLogged); resChart.Items.Add("Handled", countHandled); resChart.Items.Add("Deleted", countDeleted); resChart.Items.Add("Canceled", countCanceled); resChart.Items.Add("Logged Out", countLogged); resChart.Items.Add("Unresolved", countUnres); return new PieChart[] { staffChart, resChart }; } } }
GenerationOfWorlds/GOW
Scripts/Systems/Management/Services/Web/Reports/Objects/Staffing/StaffHistory.cs
C#
gpl-3.0
14,679
/* * Copyright (C) 2018 Olzhas Rakhimov * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @file /// Text alignment common conventions. #pragma once #include <Qt> namespace scram::gui { /// Default alignment of numerical values in tables. const int ALIGN_NUMBER_IN_TABLE = Qt::AlignRight | Qt::AlignVCenter; } // namespace scram::gui
rakhimov/scram
gui/align.h
C
gpl-3.0
947
{% extends "layout.html" %} {% block body %} <div class="text_body"> <h2>Manage input variable groups</h2> <form> <h3>Create an input group</h3> <p> Input groups are used to select input variables for templates They are managed at the partner level, so that members of your group will only see the input groups that you manage. </p> <p> You can make your own copy of an input group that was created by another partner or leave the filters blank to create a new empty input group and add input variables below. </p> <dl> <div id="group_to_copy_select"> <dd>Copy default variable groups or from a selected partner</dd> <dt>{{ add_input_group_form.partner_to_copy }}</dt> <dd>Select the group to copy</dd> <dt>{{ add_input_group_form.group_to_copy }}</dt> </div> <div id="group_to_copy_div"> <div id = group_to_copy_members_div> <dd>Group members:</dd> <dt> <ul id="group_to_copy_members"> </ul> </dt> </div> <div id = group_to_copy_levels_div> <dd>Group available at levels:</dd> <dt> <ul id="group_to_copy_levels"> </ul> </dt> </div> </div> </dl> <dl> <dd>Enter a name to create a new group</dd> <dt>{{ add_input_group_form.input_group_name }} {{ add_input_group_form.submit_input_group_name }}</dt> {{ add_input_group_form.csrf_token }} </dl> <div id="manage_group_members_div"> <div> <h3>Manage group</h3> <p> Drag and drop between lists to add/remove items or within the list to arrange their order of appearance. Click commit to store these changes. </p> </div> <div id="group_inputs_div"> <h4>Manage selected group</h4> <dd>{{ manage_input_group_form.input_group_select }}</dd> <div id="group_inputs_list_div"> {{ manage_input_group_form.group_inputs }} </div> <h4>Select levels for this group</h4> <p> Note: This does not affect the availability of the groups input variables at each level. It only affects the visibility of the input group. </p> <dd>{{ manage_input_group_form.group_levels_select }}</dd> <dd>{{ manage_input_group_form.commit_group_changes }}</dd> {{ manage_input_group_form.csrf_token }} </div> <div id="all_inputs_div"> <h4>Find input variables</h4> <dd>Record type:{{ manage_input_group_form.record_type }} Item level:{{ manage_input_group_form.item_level }}</dd> <div id="all_inputs_list_div"> {{ manage_input_group_form.all_inputs }} </div> </div> </div> <div id="manage group visibility"> <h3> </h3> </div> </form> </div> <script src="{{ url_for('static', filename='jquery_1.8.3_min.js') }}"></script> <script src="{{ url_for('static', filename='jquery-ui-1.12.1.custom/jquery-ui.js') }}"></script> <script src="{{ url_for('static', filename='jquery_input_group_mgmt.js') }}"></script> {% endblock %}
marcusmchale/breedcafs
app/templates/input_group_management.html
HTML
gpl-3.0
4,102
# <img src="https://v20.imgup.net/oakdex_logfbad.png" alt="fixer" width=282> [![Build Status](https://travis-ci.org/jalyna/oakdex-pokedex.svg?branch=master)](https://travis-ci.org/jalyna/oakdex-pokedex) [![Code Climate](https://codeclimate.com/github/jalyna/oakdex-pokedex/badges/gpa.svg)](https://codeclimate.com/github/jalyna/oakdex-pokedex) [![Test Coverage](https://codeclimate.com/github/jalyna/oakdex-pokedex/badges/coverage.svg)](https://codeclimate.com/github/jalyna/oakdex-pokedex/coverage) [![Issue Count](https://codeclimate.com/github/jalyna/oakdex-pokedex/badges/issue_count.svg)](https://codeclimate.com/github/jalyna/oakdex-pokedex) ## Getting Started ### Ruby Add oakdex to your Gemfile and do `bundle install`: ```ruby gem 'oakdex-pokedex' ``` Then you can use the library: ```ruby require 'oakdex/pokedex' eevee = Oakdex::Pokedex::Pokemon.find('Eevee') # => #<Oakdex::Pokedex::Pokemon:0x007fe3dd6a88f8 @attributes={"names"=>{"fr"=>"Évoli", "de"=>"Evoli", "it"=>"Eevee", "en"=>"Eevee"}, "national_id"=>133 ...> bulbasaur = Oakdex::Pokedex::Pokemon.find(1) # => #<Oakdex::Pokedex::Pokemon:0x007fe3dc55da80 @attributes={"names"=>{"fr"=>"Bulbizarre", "de"=>"Bisasam", ...> bulbasaur.name # => "Bulbasaur" bulbasaur.name('de') # => "Bisasam" bulbasaur.types # => ["Grass", "Poison"] bulbasaur.attributes # => {"names"=>{"fr"=>"Bulbizarre", "de"=>"Bisasam", "it"=>"Bulbasaur", "en"=>"Bulbasaur"}, "national_id"=>1, "types"=>["Grass", "Poison"], "abilities"=>[{"name"=>"Overgrow"}, {"name"=>"Chlorophyll", "hidden"=>true}], "gender_ratios"=>{"male"=>87.5, "female"=>12.5}, "catch_rate"=>45, "egg_groups"=...} tackle = Oakdex::Pokedex::Move.find('Tackle') # => #<Oakdex::Pokedex::Move:0x007fbc9a10cda0 @attributes={"index_number"=>33, "pp"=>35, "max_pp"=>56, "power"=>50, "accuracy"=>100, "category"=>"physical", "priority"=>0, "target"=>"target", ...> contrary = Oakdex::Pokedex::Ability.find('Contrary') # => #<Oakdex::Pokedex::Ability:0x007fbc9b033540 @attributes={"index_number"=>126, "names"=>{"fr"=>"Contestation", "de"=>"Umkehrung", "it"=>"Inversione", "en"=>"Contrary"}, "descriptions"=>{"en"=>"Inverts stat modifiers.", "de"=>"Attacken, die einen Statuswert des Pokémon erhöhen würden, senken ihn und umgekehrt."}}> fairy = Oakdex::Pokedex::Type.find('Fairy') # => #<Oakdex::Pokedex::Type:0x007fbc9a943c30 @attributes={"names"=>{"de"=>"Fee", "gr"=>"νεράιδα Neraida", "it"=>"Folletto", "pl"=>"Baśniowy (XY13) Bajkowy (XY46)", "en"=>"Fairy"}, "effectivness"=>{"Normal"=>1.0, "Fighting"=>2.0, "Flying"=>1.0, "Poison"=>0.5, "Ground"=>1.0, "Rock"=>1.0, "Bug"=>1.0, "Ghost"=>1.0, "Steel"=>0.5, "Fire"=>0.5, "Water"=>1.0, "Grass"=>1.0, "Electric"=>1.0, "Psychic"=>1.0, "Ice"=>1.0, "Dragon"=>2.0, "Dark"=>2.0, "Fairy"=>1.0}, "color"=>"#D685AD"}> fairy.effectivness_for('Dark') # => 2.0 water1 = Oakdex::Pokedex::EggGroup.find('Water 1') # => #<Oakdex::Pokedex::EggGroup:0x007fbc9a853398 @attributes={"names"=>{"en"=>"Water 1", "jp"=>"すいちゅう1 (水中1) Suichū1", "fr"=>"Eau 1", "de"=>"Wasser 1", "it"=>"Acqua 1", "es"=>"Agua 1"}}> generation6 = Oakdex::Pokedex::Generation.find('Generation VI') # => #<Oakdex::Pokedex::Generation:0x007fbc9b0382c0 @attributes={"number"=>6, "dex_name"=>"kalos_id", "names"=>{"en"=>"Generation VI", "de"=>"Generation VI"}, "games"=>[{"en"=>"X", "de"=>"X"}, {"en"=>"Y", "de"=>"Y"}, {"en"=>"Omega Ruby", "de"=>"Omega Rubin"}, {"en"=>"Alpha Sapphire", "de"=>"Alpha Saphir"}]}> bold = Oakdex::Pokedex::Nature.find('Bold') # => #<Oakdex::Pokedex::Nature:0x007fbc9a92b2c0 @attributes={"names"=>{"en"=>"Bold", "de"=>"Kühn"}, "increased_stat"=>"def", "decreased_stat"=>"atk", "favorite_flavor"=>"Sour", "disliked_flavor"=>"Spicy"}> Oakdex::Pokedex::Pokemon.all.size # => 802 Oakdex::Pokedex::Pokemon.where(type: 'Dark').size # => 46 Oakdex::Pokedex::Pokemon.where(egg_group: 'Human-Like').size # => 52 Oakdex::Pokedex::Pokemon.where(dex: 'alola').size # => 302 Oakdex::Pokedex::Pokemon.where(alola_id: 1) # => [#<Oakdex::Pokedex::Pokemon:0x007fbc9e542510 @attributes={"names"=>{"en"=>"Rowlet", "jp"=>"モクロー Mokuroh", "fr"=>"Brindibou", "es"=>"Rowlet", "de"=>"Bauz", "it"=>"Rowlet"}, "national_id"=>722, "alola_id"=>1, ...>] Oakdex::Pokedex::Move.where(type: 'Ground').size # => 26 ``` ### Javascript Install the package: ``` $ npm install oakdex-pokedex --save ``` Then you can use the library: ```js oakdexPokedex = require('oakdex-pokedex'); oakdexPokedex.findPokemon('Eevee', function(p) { // returns data/pokemon/eevee.json console.log(p.names.en); // Eeevee }); oakdexPokedex.findPokemon(4, function(p) { // returns data/pokemon/charmander.json console.log(p.names.en); // Charmander }); oakdexPokedex.findMove('Tackle', function(m) { // returns data/move/tackle.json console.log(m.names.en); // Tackle }); oakdexPokedex.findAbility('Contrary', function(a) { // returns data/ability/contrary.json console.log(a.names.en); // Contrary }); oakdexPokedex.findType('Fairy', function(t) { // returns data/type/fairy.json console.log(t.names.en); // Fairy }); oakdexPokedex.findEggGroup('Water 1', function(e) { // returns data/egg_group/water_1.json console.log(e.names.en); // Water 1 }); oakdexPokedex.findGeneration('Generation VI', function(g) { // returns data/generation/6.json console.log(g.names.en); // Generation VI }); oakdexPokedex.findNature('Bold', function(n) { // returns data/nature/bold.json console.log(n.names.en); // Bold }); oakdexPokedex.allPokemon(function(pokemon) { console.log(pokemon.length); // 802 }); oakdexPokedex.allPokemon({ type: 'Dark' }, function(pokemon) { console.log(pokemon.length); // 46 }); oakdexPokedex.allPokemon({ egg_group: 'Human-Like' }, function(pokemon) { console.log(pokemon.length); // 52 }); oakdexPokedex.allPokemon({ dex: 'alola' }, function(pokemon) { console.log(pokemon.length); // 302 }); oakdexPokedex.allMoves({ type: 'Ground' }, function(moves) { console.log(moves.length); // 26 }); ``` ### Schemas If you want to know what the structure of the given data is, checkout the following documentations: - [Pokemon](doc/pokemon.md) - [Move](doc/move.md) - [Ability](doc/ability.md) - [Type](doc/type.md) - [Egg Group](doc/egg_group.md) - [Nature](doc/nature.md) - [Generation](doc/generation.md) ### Sprites If you want also to include sprites in your pokedex, check out [oakdex-pokedex-sprites](https://github.com/jalyna/oakdex-pokedex-sprites). ## Contributing I would be happy if you want to add your contribution to the project. In order to contribute, you just have to fork this repository. ## License MIT License. See the included MIT-LICENSE file. ## Credits Logo Icon by [Roundicons Freebies](http://www.flaticon.com/authors/roundicons-freebies).
SrNativee/BotDeUmBot
node_modules/oakdex-pokedex/README.md
Markdown
gpl-3.0
6,776
import numpy as np import laspy as las # Determine if a point is inside a given polygon or not # Polygon is a list of (x,y) pairs. This function # returns True or False. The algorithm is called # the "Ray Casting Method". # the point_in_poly algorithm was found here: # http://geospatialpython.com/2011/01/point-in-polygon.html def point_in_poly(x,y,poly): n = len(poly) inside = False p1x,p1y = poly[0] for i in range(n+1): p2x,p2y = poly[i % n] if y > min(p1y,p2y): if y <= max(p1y,p2y): if x <= max(p1x,p2x): if p1y != p2y: xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x if p1x == p2x or x <= xints: inside = not inside p1x,p1y = p2x,p2y return inside # This one is my own version of the ray-trace algorithm which utilises the numpy arrays so that a list of x and y coordinates can be processed in one call and only points inside polygon are returned alongside the indices in case required for future referencing. This saves a fair bit of looping. def points_in_poly(x,y,poly): n = len(poly) inside=np.zeros(x.size,dtype=bool) xints=np.zeros(x.size) p1x,p1y = poly[0] for i in range(n+1): p2x,p2y=poly[i % n] if p1y!=p2y: xints[np.all([y>min(p1y,p2y), y<=max(p1y,p2y), x<=max(p1x,p2x)],axis=0)] = (y[np.all([y>min(p1y,p2y), y<=max(p1y,p2y), x<=max(p1x,p2x)],axis=0)]-p1y)*(p2x-p1x)/(p2y-p1y)+p1x if p1x==p2x: inside[np.all([y>min(p1y,p2y), y<=max(p1y,p2y), x<=max(p1x,p2x)],axis=0)] = np.invert(inside[np.all([y>min(p1y,p2y), y<=max(p1y,p2y), x<=max(p1x,p2x)],axis=0)]) else: inside[np.all([y>min(p1y,p2y), y<=max(p1y,p2y), x<=max(p1x,p2x),x<=xints],axis=0)] = np.invert(inside[np.all([y>min(p1y,p2y), y<=max(p1y,p2y), x<=max(p1x,p2x),x<=xints],axis=0)]) p1x,p1y = p2x,p2y return x[inside],y[inside], inside # This retrieves all points within circular neighbourhood, Terget point is the location around which the neighbourhood search is conducted, for a specified search radius. x and y are vectors with the x and y coordinates of the test points def points_in_radius(x,y,target_x, target_y,radius): inside=np.zeros(x.size,dtype=bool) d2=(x-target_x)**2+(y-target_y)**2 inside = d2<=radius**2 return x[inside],y[inside], inside # filter lidar wth polygon # This function has been updated to include an option to filter by first return location. # The reason for this is so full collections of returns associated with each LiDAR pulse # can be retrieved, which can be an issue at edges in multi-return analyses def filter_lidar_data_by_polygon(in_pts,polygon,filter_by_first_return_location = False): pts = np.zeros((0,in_pts.shape[1])) if in_pts.shape[0]>0: if filter_by_first_return_location: # find first returns mask = in_pts[:,3]==1 x_temp, y_temp, inside_temp = points_in_poly(in_pts[mask,0],in_pts[mask,1],polygon) shots = np.unique(in_pts[mask,6][inside_temp]) # index 6 refers to GPS time inside = np.in1d(in_pts[:,6],shots) # this function retrieves all points corresponding to this GPS time x = in_pts[inside,0] y = in_pts[inside,1] x_temp=None y_temp=None inside_temp=None else: x,y,inside = points_in_poly(in_pts[:,0],in_pts[:,1],polygon) pts = in_pts[inside,:] else: print("\t\t\t no points in polygon") return pts # filter lidar by circular neighbourhood def filter_lidar_data_by_neighbourhood(in_pts,target_xy,radius): pts = np.zeros((0,in_pts.shape[1])) if in_pts.shape[0]>0: x,y,inside = points_in_radius(in_pts[:,0],in_pts[:,1],target_xy[0],target_xy[1],radius) pts = in_pts[inside,:] else: print( "\t\t\t no points in neighbourhood") return pts
DTMilodowski/LiDAR_canopy
src/LiDAR_tools.py
Python
gpl-3.0
3,971
/* File: deref.h ** Author(s): Jiyang Xu, Terrance Swift, Kostis Sagonas ** Contact: [email protected] ** ** Copyright (C) The Research Foundation of SUNY, 1986, 1993-1998 ** Copyright (C) ECRC, Germany, 1990 ** ** XSB 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. ** ** XSB 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 XSB; if not, write to the Free Software Foundation, ** Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ** ** $Id: deref.h,v 1.13 2010-08-19 15:03:36 spyrosh Exp $ ** */ #ifndef __DEREF_H__ #define __DEREF_H__ /* TLS: Bao changed these derefs to handle attributed variables, since * a reference chain can, in principle, have a chain of var pointers * followed by a chain of attv pointers, ending in a free variable. * Actually, the code here is somewhat more general, and allows more * intermixture of attv and var pointers. So I may be wrong or the * code may be a little more general than it needs to be. * * XSB_Deref(op) is the same as XSB_CptrDeref(op) except that * XSB_CptrDeref(op) performs an explicit cast of op to a CPtr. */ #define XSB_Deref(op) XSB_Deref2(op,break) /* XSB_Deref2 is changed to consider attributed variables */ #define XSB_Deref2(op, stat) { \ while (isref(op)) { \ if (op == follow(op)) \ stat; \ op = follow(op); \ } \ while (isattv(op)) { \ if (cell((CPtr) dec_addr(op)) == dec_addr(op)) \ break; /* end of an attv */ \ else { \ op = cell((CPtr) dec_addr(op)); \ while (isref(op)) { \ if (op == follow(op)) \ stat; \ op = follow(op); \ } \ } \ } \ } #define XSB_CptrDeref(op) { \ while (isref(op)) { \ if (op == (CPtr) cell(op)) break; \ op = (CPtr) cell(op); \ } \ while (isattv(op)) { \ if (cell((CPtr) dec_addr(op)) == dec_addr(op)) \ break; \ else { \ op = (CPtr) cell((CPtr) dec_addr(op)); \ while (isref(op)) { \ if (op == (CPtr) cell(op)) break; \ op = (CPtr) cell(op); \ } \ } \ } \ } #define printderef(op) while (isref(op) && op > 0) { \ if (op==follow(op)) \ break; \ op=follow(op); } #endif /* __DEREF_H__ */
KULeuven-KRR/IDP
lib/XSB/emu/deref.h
C
gpl-3.0
2,786