code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* * Some of the filter code was taken from Glumpy: * # Copyright (c) 2009-2016 Nicolas P. Rougier. All rights reserved. * # Distributed under the (new) BSD License. * (https://github.com/glumpy/glumpy/blob/master/glumpy/library/build-spatial-filters.py) * * Also see: * - http://vector-agg.cvs.sourceforge.net/viewvc/vector-agg/agg-2.5/include/agg_image_filters.h * - Vapoursynth plugin fmtconv (WTFPL Licensed), which is based on * dither plugin for avisynth from the same author: * https://github.com/vapoursynth/fmtconv/tree/master/src/fmtc * - Paul Heckbert's "zoom" * - XBMC: ConvolutionKernels.cpp etc. * * This file is part of mpv. * * This file can be distributed under the 3-clause license ("New BSD License"). * * You can alternatively redistribute the non-Glumpy parts of this file 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. */ #include <stddef.h> #include <string.h> #include <math.h> #include <assert.h> #include "filter_kernels.h" // NOTE: all filters are designed for discrete convolution const struct filter_window *mp_find_filter_window(const char *name) { if (!name) return NULL; for (const struct filter_window *w = mp_filter_windows; w->name; w++) { if (strcmp(w->name, name) == 0) return w; } return NULL; } const struct filter_kernel *mp_find_filter_kernel(const char *name) { if (!name) return NULL; for (const struct filter_kernel *k = mp_filter_kernels; k->f.name; k++) { if (strcmp(k->f.name, name) == 0) return k; } return NULL; } // sizes = sorted list of available filter sizes, terminated with size 0 // inv_scale = source_size / dest_size bool mp_init_filter(struct filter_kernel *filter, const int *sizes, double inv_scale) { assert(filter->f.radius > 0); // Only downscaling requires widening the filter filter->inv_scale = inv_scale >= 1.0 ? inv_scale : 1.0; filter->f.radius *= filter->inv_scale; // Polar filters are dependent solely on the radius if (filter->polar) { filter->size = 1; // Safety precaution to avoid generating a gigantic shader if (filter->f.radius > 16.0) { filter->f.radius = 16.0; return false; } return true; } int size = ceil(2.0 * filter->f.radius); // round up to smallest available size that's still large enough if (size < sizes[0]) size = sizes[0]; const int *cursize = sizes; while (size > *cursize && *cursize) cursize++; if (*cursize) { filter->size = *cursize; return true; } else { // The filter doesn't fit - instead of failing completely, use the // largest filter available. This is incorrect, but better than refusing // to do anything. filter->size = cursize[-1]; filter->inv_scale *= (filter->size/2.0) / filter->f.radius; return false; } } // Sample from the blurred, windowed kernel. Note: The window is always // stretched to the true radius, regardless of the filter blur/scale. static double sample_filter(struct filter_kernel *filter, struct filter_window *window, double x) { double bk = filter->f.blur > 0.0 ? filter->f.blur : 1.0; double bw = window->blur > 0.0 ? window->blur : 1.0; double c = fabs(x) / (filter->inv_scale * bk); double w = window->weight ? window->weight(window, x/bw * window->radius / filter->f.radius) : 1.0; double v = c < filter->f.radius ? w * filter->f.weight(&filter->f, c) : 0.0; return filter->clamp ? fmax(0.0, fmin(1.0, v)) : v; } // Calculate the 1D filtering kernel for N sample points. // N = number of samples, which is filter->size // The weights will be stored in out_w[0] to out_w[N - 1] // f = x0 - abs(x0), subpixel position in the range [0,1) or [0,1]. static void mp_compute_weights(struct filter_kernel *filter, struct filter_window *window, double f, float *out_w) { assert(filter->size > 0); double sum = 0; for (int n = 0; n < filter->size; n++) { double x = f - (n - filter->size / 2 + 1); double w = sample_filter(filter, window, x); out_w[n] = w; sum += w; } // Normalize to preserve energy for (int n = 0; n < filter->size; n++) out_w[n] /= sum; } // Fill the given array with weights for the range [0.0, 1.0]. The array is // interpreted as rectangular array of count * filter->size items. // // There will be slight sampling error if these weights are used in a OpenGL // texture as LUT directly. The sampling point of a texel is located at its // center, so out_array[0] will end up at 0.5 / count instead of 0.0. // Correct lookup requires a linear coordinate mapping from [0.0, 1.0] to // [0.5 / count, 1.0 - 0.5 / count]. void mp_compute_lut(struct filter_kernel *filter, int count, float *out_array) { struct filter_window *window = &filter->w; if (filter->polar) { // Compute a 1D array indexed by radius for (int x = 0; x < count; x++) { double r = x * filter->f.radius / (count - 1); out_array[x] = sample_filter(filter, window, r); } } else { // Compute a 2D array indexed by subpixel position for (int n = 0; n < count; n++) { mp_compute_weights(filter, window, n / (double)(count - 1), out_array + filter->size * n); } } } typedef struct filter_window params; static double box(params *p, double x) { // This is mathematically 1.0 everywhere, the clipping is done implicitly // based on the radius. return 1.0; } static double triangle(params *p, double x) { return fmax(0.0, 1.0 - fabs(x / p->radius)); } static double hanning(params *p, double x) { return 0.5 + 0.5 * cos(M_PI * x); } static double hamming(params *p, double x) { return 0.54 + 0.46 * cos(M_PI * x); } // Generalization of raised-power cosine windows to arbitrary exponents static double petsu(params *p, double x) { return powf(cos(M_PI/2 * x), p->params[0]); } static double quadric(params *p, double x) { if (x < 0.75) { return 0.75 - x * x; } else if (x < 1.5) { double t = x - 1.5; return 0.5 * t * t; } return 0.0; } #define POW3(x) ((x) <= 0 ? 0 : (x) * (x) * (x)) static double bicubic(params *p, double x) { return (1.0/6.0) * ( POW3(x + 2) - 4 * POW3(x + 1) + 6 * POW3(x) - 4 * POW3(x - 1)); } static double bessel_i0(double x) { double s = 1.0; double y = x * x / 4.0; double t = y; int i = 2; while (t > 1e-12) { s += t; t *= y / (i * i); i += 1; } return s; } static double kaiser(params *p, double x) { if (x > 1) return 0; double i0a = 1.0 / bessel_i0(p->params[1]); return bessel_i0(p->params[0] * sqrt(1.0 - x * x)) * i0a; } static double blackman(params *p, double x) { double a = p->params[0]; double a0 = (1-a)/2.0, a1 = 1/2.0, a2 = a/2.0; double pix = M_PI * x; return a0 + a1*cos(pix) + a2*cos(2 * pix); } static double welch(params *p, double x) { return 1.0 - x*x; } // Family of cubic B/C splines static double cubic_bc(params *p, double x) { double b = p->params[0], c = p->params[1]; double p0 = (6.0 - 2.0 * b) / 6.0, p2 = (-18.0 + 12.0 * b + 6.0 * c) / 6.0, p3 = (12.0 - 9.0 * b - 6.0 * c) / 6.0, q0 = (8.0 * b + 24.0 * c) / 6.0, q1 = (-12.0 * b - 48.0 * c) / 6.0, q2 = (6.0 * b + 30.0 * c) / 6.0, q3 = (-b - 6.0 * c) / 6.0; if (x < 1.0) { return p0 + x * x * (p2 + x * p3); } else if (x < 2.0) { return q0 + x * (q1 + x * (q2 + x * q3)); } return 0.0; } static double spline16(params *p, double x) { if (x < 1.0) { return ((x - 9.0/5.0 ) * x - 1.0/5.0 ) * x + 1.0; } else { return ((-1.0/3.0 * (x-1) + 4.0/5.0) * (x-1) - 7.0/15.0 ) * (x-1); } } static double spline36(params *p, double x) { if (x < 1.0) { return ((13.0/11.0 * x - 453.0/209.0) * x - 3.0/209.0) * x + 1.0; } else if (x < 2.0) { return ((-6.0/11.0 * (x-1) + 270.0/209.0) * (x-1) - 156.0/ 209.0) * (x-1); } else { return ((1.0/11.0 * (x-2) - 45.0/209.0) * (x-2) + 26.0/209.0) * (x-2); } } static double spline64(params *p, double x) { if (x < 1.0) { return ((49.0/41.0 * x - 6387.0/2911.0) * x - 3.0/911.0) * x + 1.0; } else if (x < 2.0) { return ((-24.0/42.0 * (x-1) + 4032.0/2911.0) * (x-1) - 2328.0/ 2911.0) * (x-1); } else if (x < 3.0) { return ((6.0/41.0 * (x-2) - 1008.0/2911.0) * (x-2) + 582.0/2911.0) * (x-2); } else { return ((-1.0/41.0 * (x-3) - 168.0/2911.0) * (x-3) + 97.0/2911.0) * (x-3); } } static double gaussian(params *p, double x) { return exp(-2.0 * x * x / p->params[0]); } static double sinc(params *p, double x) { if (fabs(x) < 1e-8) return 1.0; x *= M_PI; return sin(x) / x; } static double jinc(params *p, double x) { if (fabs(x) < 1e-8) return 1.0; x *= M_PI; return 2.0 * j1(x) / x; } static double sphinx(params *p, double x) { if (fabs(x) < 1e-8) return 1.0; x *= M_PI; return 3.0 * (sin(x) - x * cos(x)) / (x * x * x); } const struct filter_window mp_filter_windows[] = { {"box", 1, box}, {"triangle", 1, triangle}, {"bartlett", 1, triangle}, {"hanning", 1, hanning}, {"hamming", 1, hamming}, {"petsu", 1, petsu, .params = {1.5, NAN} }, {"quadric", 1.5, quadric}, {"welch", 1, welch}, {"kaiser", 1, kaiser, .params = {6.33, NAN} }, {"blackman", 1, blackman, .params = {0.16, NAN} }, {"gaussian", 2, gaussian, .params = {1.00, NAN} }, {"sinc", 1, sinc}, {"jinc", 1.2196698912665045, jinc}, {"sphinx", 1.4302966531242027, sphinx}, {0} }; const struct filter_kernel mp_filter_kernels[] = { // Spline filters {{"spline16", 2, spline16}}, {{"spline36", 3, spline36}}, {{"spline64", 4, spline64}}, // Sinc filters {{"sinc", 2, sinc, .resizable = true}}, {{"lanczos", 3, sinc, .resizable = true}, .window = "sinc"}, {{"ginseng", 3, sinc, .resizable = true}, .window = "jinc"}, // Jinc filters {{"jinc", 3, jinc, .resizable = true}, .polar = true}, {{"ewa_lanczos", 3, jinc, .resizable = true}, .polar = true, .window = "jinc"}, {{"ewa_hanning", 3, jinc, .resizable = true}, .polar = true, .window = "hanning" }, {{"ewa_ginseng", 3, jinc, .resizable = true}, .polar = true, .window = "sinc"}, // Radius is based on the true jinc radius, slightly sharpened as per // calculations by Nicolas Robidoux. Source: Imagemagick's magick/resize.c {{"ewa_lanczossharp", 3.2383154841662362, jinc, .blur = 0.9812505644269356, .resizable = true}, .polar = true, .window = "jinc"}, // Similar to the above, but softened instead. This one makes hash patterns // disappear completely. Blur determined by trial and error. {{"ewa_lanczossoft", 3.2383154841662362, jinc, .blur = 1.015, .resizable = true}, .polar = true, .window = "jinc"}, // Very soft (blurred) hanning-windowed jinc; removes almost all aliasing. // Blur paramater picked to match orthogonal and diagonal contributions {{"haasnsoft", 3.2383154841662362, jinc, .blur = 1.11, .resizable = true}, .polar = true, .window = "hanning"}, // Cubic filters {{"bicubic", 2, bicubic}}, {{"bcspline", 2, cubic_bc, .params = {0.5, 0.5} }}, {{"catmull_rom", 2, cubic_bc, .params = {0.0, 0.5} }}, {{"mitchell", 2, cubic_bc, .params = {1.0/3.0, 1.0/3.0} }}, {{"robidoux", 2, cubic_bc, .params = {12 / (19 + 9 * M_SQRT2), 113 / (58 + 216 * M_SQRT2)} }}, {{"robidouxsharp", 2, cubic_bc, .params = {6 / (13 + 7 * M_SQRT2), 7 / (2 + 12 * M_SQRT2)} }}, {{"ewa_robidoux", 2, cubic_bc, .params = {12 / (19 + 9 * M_SQRT2), 113 / (58 + 216 * M_SQRT2)}}, .polar = true}, {{"ewa_robidouxsharp", 2,cubic_bc, .params = {6 / (13 + 7 * M_SQRT2), 7 / (2 + 12 * M_SQRT2)}}, .polar = true}, // Miscellaneous filters {{"box", 1, box, .resizable = true}}, {{"nearest", 0.5, box}}, {{"triangle", 1, triangle, .resizable = true}}, {{"gaussian", 2, gaussian, .params = {1.0, NAN}, .resizable = true}}, {{0}} };
haasn/mpvhq
video/out/filter_kernels.c
C
gpl-2.0
13,281
/* * arch/sh/kernel/cpu/sh3/clock-sh7712.c * * SH7712 support for the clock framework * * Copyright (C) 2007 Andrew Murray <amurray@mpc-data.co.uk> * * Based on arch/sh/kernel/cpu/sh3/clock-sh3.c * Copyright (C) 2005 Paul Mundt * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #include <linux/init.h> #include <linux/kernel.h> #include <asm/clock.h> #include <asm/freq.h> #include <asm/io.h> static int multipliers[] = { 1, 2, 3 }; static int divisors[] = { 1, 2, 3, 4, 6 }; static void master_clk_init(struct clk *clk) { int frqcr = __raw_readw(FRQCR); int idx = (frqcr & 0x0300) >> 8; clk->rate *= multipliers[idx]; } static struct sh_clk_ops sh7712_master_clk_ops = { .init = master_clk_init, }; static unsigned long module_clk_recalc(struct clk *clk) { int frqcr = __raw_readw(FRQCR); int idx = frqcr & 0x0007; return clk->parent->rate / divisors[idx]; } static struct sh_clk_ops sh7712_module_clk_ops = { .recalc = module_clk_recalc, }; static unsigned long cpu_clk_recalc(struct clk *clk) { int frqcr = __raw_readw(FRQCR); int idx = (frqcr & 0x0030) >> 4; return clk->parent->rate / divisors[idx]; } static struct sh_clk_ops sh7712_cpu_clk_ops = { .recalc = cpu_clk_recalc, }; static struct sh_clk_ops *sh7712_clk_ops[] = { &sh7712_master_clk_ops, &sh7712_module_clk_ops, &sh7712_cpu_clk_ops, }; void __init arch_init_clk_ops(struct sh_clk_ops **ops, int idx) { if (idx < ARRAY_SIZE(sh7712_clk_ops)) *ops = sh7712_clk_ops[idx]; }
Jackeagle/android_kernel_sony_c2305
arch/sh/kernel/cpu/sh3/clock-sh7712.c
C
gpl-2.0
1,687
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sdb.cmd; import com.hp.hpl.jena.sdb.Store; import arq.cmdline.*; public class ModConfig extends ModBase { protected final ArgDecl argDeclFormat = new ArgDecl(ArgDecl.NoValue, "format") ; protected final ArgDecl argDeclCreate = new ArgDecl(ArgDecl.NoValue, "create") ; protected final ArgDecl argDeclDropIndexes = new ArgDecl(ArgDecl.NoValue, "dropIndexes", "drop") ; protected final ArgDecl argDeclIndexes = new ArgDecl(ArgDecl.NoValue, "addIndexes", "indexes", "index") ; private boolean format = false ; private boolean createStore = false ; private boolean dropIndexes = false ; private boolean createIndexes = false ; public ModConfig() {} @Override public void registerWith(CmdGeneral cmdLine) { cmdLine.add(argDeclCreate, "--create", "Format a database and add indexes") ; cmdLine.add(argDeclFormat, "--format", "Format a database (no indexes)") ; cmdLine.add(argDeclDropIndexes, "--drop", "Drop indexes") ; cmdLine.add(argDeclIndexes, "--indexes", "Add indexes") ; } @Override public void processArgs(CmdArgModule cmdLine) { format = cmdLine.contains(argDeclFormat) ; createStore = cmdLine.contains(argDeclCreate) ; dropIndexes = cmdLine.contains(argDeclDropIndexes) ; createIndexes = cmdLine.contains(argDeclIndexes) ; } public boolean addIndexes() { return createIndexes ; } public boolean dropIndexes() { return dropIndexes ; } public boolean format() { return format ; } public boolean createStore() { return createStore ; } public void enact(Store store) { enact(store, null) ; } public void enact(Store store, ModTime timer) { // "create" = format + build indexes. if ( createStore() ) { if ( timer != null ) timer.startTimer() ; store.getTableFormatter().create() ; if ( timer != null ) { long time = timer.endTimer() ; printTime("create", time) ; } } if ( format() && ! createStore() ) { if ( timer != null ) timer.startTimer() ; store.getTableFormatter().format() ; if ( timer != null ) { long time = timer.endTimer() ; printTime("format", time) ; } } if ( dropIndexes() ) { if ( timer != null ) timer.startTimer() ; store.getTableFormatter().dropIndexes() ; if ( timer != null ) { long time = timer.endTimer() ; printTime("drop indexes", time) ; } } if ( addIndexes() ) { if ( timer != null ) timer.startTimer() ; store.getTableFormatter().addIndexes() ; if ( timer != null ) { long time = timer.endTimer() ; printTime("add indexes", time) ; } } } private void printTime(String string, long timeMilli) { System.out.printf("Operation: %s: Time %.3f seconds\n", string, timeMilli/1000.0) ; } }
hdadler/sensetrace-src
com.ipv.sensetrace.RDFDatamanager/jena-2.11.0/jena-sdb/src/main/java/sdb/cmd/ModConfig.java
Java
gpl-2.0
4,248
/* BlueZ - Bluetooth protocol stack for Linux Copyright (c) 2000-2001, 2010-2012, Code Aurora Forum. All rights reserved. Written 2000,2001 by Maxim Krasnyansky <maxk@qualcomm.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. */ #ifndef __HCI_CORE_H #define __HCI_CORE_H #include <net/bluetooth/hci.h> /* HCI upper protocols */ #define HCI_PROTO_L2CAP 0 #define HCI_PROTO_SCO 1 /* HCI Core structures */ struct inquiry_data { bdaddr_t bdaddr; __u8 pscan_rep_mode; __u8 pscan_period_mode; __u8 pscan_mode; __u8 dev_class[3]; __le16 clock_offset; __s8 rssi; __u8 ssp_mode; }; struct inquiry_entry { struct inquiry_entry *next; __u32 timestamp; struct inquiry_data data; }; struct inquiry_cache { spinlock_t lock; __u32 timestamp; struct inquiry_entry *list; }; struct hci_conn_hash { struct list_head list; spinlock_t lock; unsigned int acl_num; unsigned int sco_num; unsigned int le_num; }; struct hci_chan_list { struct list_head list; spinlock_t lock; }; struct bdaddr_list { struct list_head list; bdaddr_t bdaddr; }; struct bt_uuid { struct list_head list; u8 uuid[16]; u8 svc_hint; }; struct key_master_id { __le16 ediv; u8 rand[8]; } __packed; #define KEY_TYPE_LE_BASE 0x11 #define KEY_TYPE_LTK 0x11 #define KEY_TYPE_IRK 0x12 #define KEY_TYPE_CSRK 0x13 struct link_key_data { bdaddr_t bdaddr; u8 addr_type; u8 key_type; u8 val[16]; u8 pin_len; u8 auth; u8 dlen; u8 data[0]; } __packed; struct link_key { struct list_head list; bdaddr_t bdaddr; u8 addr_type; u8 key_type; u8 val[16]; u8 pin_len; u8 auth; u8 dlen; u8 data[0]; }; struct oob_data { struct list_head list; bdaddr_t bdaddr; u8 hash[16]; u8 randomizer[16]; }; struct adv_entry { struct list_head list; bdaddr_t bdaddr; u8 bdaddr_type; u8 flags; }; #define NUM_REASSEMBLY 4 struct hci_dev { struct list_head list; spinlock_t lock; atomic_t refcnt; char name[8]; unsigned long flags; __u16 id; __u8 bus; __u8 dev_type; bdaddr_t bdaddr; __u8 dev_name[HCI_MAX_NAME_LENGTH]; __u8 eir[HCI_MAX_EIR_LENGTH]; __u8 dev_class[3]; __u8 major_class; __u8 minor_class; __u8 features[8]; __u8 commands[64]; __u8 ssp_mode; __u8 hci_ver; __u16 hci_rev; __u8 lmp_ver; __u16 manufacturer; __le16 lmp_subver; __u16 voice_setting; __u8 io_capability; __u16 pkt_type; __u16 esco_type; __u16 link_policy; __u16 link_mode; __u32 idle_timeout; __u16 sniff_min_interval; __u16 sniff_max_interval; __u8 amp_status; __u32 amp_total_bw; __u32 amp_max_bw; __u32 amp_min_latency; __u32 amp_max_pdu; __u8 amp_type; __u16 amp_pal_cap; __u16 amp_assoc_size; __u32 amp_max_flush_to; __u32 amp_be_flush_to; __s8 is_wbs; unsigned long quirks; atomic_t cmd_cnt; unsigned int acl_cnt; unsigned int sco_cnt; unsigned int le_cnt; __u8 flow_ctl_mode; unsigned int acl_mtu; unsigned int sco_mtu; unsigned int le_mtu; unsigned int acl_pkts; unsigned int sco_pkts; unsigned int le_pkts; unsigned int data_block_len; unsigned long acl_last_tx; unsigned long sco_last_tx; unsigned long le_last_tx; struct workqueue_struct *workqueue; struct work_struct power_on; struct work_struct power_off; struct timer_list off_timer; struct timer_list cmd_timer; struct tasklet_struct cmd_task; struct tasklet_struct rx_task; struct tasklet_struct tx_task; struct sk_buff_head rx_q; struct sk_buff_head raw_q; struct sk_buff_head cmd_q; struct sk_buff *sent_cmd; struct sk_buff *reassembly[NUM_REASSEMBLY]; struct mutex req_lock; wait_queue_head_t req_wait_q; __u32 req_status; __u32 req_result; __u16 init_last_cmd; struct crypto_blkcipher *tfm; struct inquiry_cache inq_cache; struct hci_conn_hash conn_hash; struct hci_chan_list chan_list; struct list_head blacklist; struct list_head uuids; struct list_head link_keys; struct list_head remote_oob_data; struct list_head adv_entries; rwlock_t adv_entries_lock; struct timer_list adv_timer; struct timer_list disco_timer; struct timer_list disco_le_timer; __u8 disco_state; int disco_int_phase; int disco_int_count; struct hci_dev_stats stat; struct sk_buff_head driver_init; void *driver_data; void *core_data; atomic_t promisc; struct dentry *debugfs; struct device *parent; struct device dev; struct rfkill *rfkill; struct module *owner; int (*open)(struct hci_dev *hdev); int (*close)(struct hci_dev *hdev); int (*flush)(struct hci_dev *hdev); int (*send)(struct sk_buff *skb); void (*destruct)(struct hci_dev *hdev); void (*notify)(struct hci_dev *hdev, unsigned int evt); int (*ioctl)(struct hci_dev *hdev, unsigned int cmd, unsigned long arg); }; struct hci_conn { struct list_head list; atomic_t refcnt; spinlock_t lock; bdaddr_t dst; __u8 dst_id; __u8 dst_type; __u16 handle; __u16 state; __u8 mode; __u8 type; __u8 out; __u8 attempt; __u8 dev_class[3]; __u8 features[8]; __u8 ssp_mode; __u16 interval; __u16 pkt_type; __u16 link_policy; __u32 link_mode; __u8 auth_type; __u8 sec_level; __u8 pending_sec_level; __u8 pin_length; __u8 enc_key_size; __u8 io_capability; __u8 auth_initiator; __u8 power_save; __u16 disc_timeout; unsigned long pend; __u8 remote_cap; __u8 remote_oob; __u8 remote_auth; unsigned int sent; struct sk_buff_head data_q; struct timer_list disc_timer; struct timer_list idle_timer; struct work_struct work_add; struct work_struct work_del; struct device dev; atomic_t devref; struct hci_dev *hdev; void *l2cap_data; void *sco_data; void *priv; __u8 link_key[16]; __u8 key_type; struct hci_conn *link; /* Low Energy SMP pairing data */ __u8 oob; /* OOB pairing supported */ __u8 tk_valid; /* TK value is valid */ __u8 cfm_pending; /* CONFIRM cmd may be sent */ __u8 preq[7]; /* Pairing Request */ __u8 prsp[7]; /* Pairing Response */ __u8 prnd[16]; /* Pairing Random */ __u8 pcnf[16]; /* Pairing Confirm */ __u8 tk[16]; /* Temporary Key */ __u8 smp_key_size; __u8 sec_req; __u8 auth; void *smp_conn; struct timer_list smp_timer; void (*connect_cfm_cb) (struct hci_conn *conn, u8 status); void (*security_cfm_cb) (struct hci_conn *conn, u8 status); void (*disconn_cfm_cb) (struct hci_conn *conn, u8 reason); }; struct hci_chan { struct list_head list; struct hci_dev *hdev; __u16 state; atomic_t refcnt; __u16 ll_handle; struct hci_ext_fs tx_fs; struct hci_ext_fs rx_fs; struct hci_conn *conn; void *l2cap_sk; }; extern struct hci_proto *hci_proto[]; extern struct list_head hci_dev_list; extern struct list_head hci_cb_list; extern rwlock_t hci_dev_list_lock; extern rwlock_t hci_cb_list_lock; /* ----- Inquiry cache ----- */ #define INQUIRY_CACHE_AGE_MAX (HZ*30) /* 30 seconds */ #define INQUIRY_ENTRY_AGE_MAX (HZ*60) /* 60 seconds */ #define inquiry_cache_lock(c) spin_lock(&c->lock) #define inquiry_cache_unlock(c) spin_unlock(&c->lock) #define inquiry_cache_lock_bh(c) spin_lock_bh(&c->lock) #define inquiry_cache_unlock_bh(c) spin_unlock_bh(&c->lock) static inline void inquiry_cache_init(struct hci_dev *hdev) { struct inquiry_cache *c = &hdev->inq_cache; spin_lock_init(&c->lock); c->list = NULL; } static inline int inquiry_cache_empty(struct hci_dev *hdev) { struct inquiry_cache *c = &hdev->inq_cache; return c->list == NULL; } static inline long inquiry_cache_age(struct hci_dev *hdev) { struct inquiry_cache *c = &hdev->inq_cache; return jiffies - c->timestamp; } static inline long inquiry_entry_age(struct inquiry_entry *e) { return jiffies - e->timestamp; } struct inquiry_entry *hci_inquiry_cache_lookup(struct hci_dev *hdev, bdaddr_t *bdaddr); void hci_inquiry_cache_update(struct hci_dev *hdev, struct inquiry_data *data); /* ----- HCI Connections ----- */ enum { HCI_CONN_AUTH_PEND, HCI_CONN_ENCRYPT_PEND, HCI_CONN_RSWITCH_PEND, HCI_CONN_MODE_CHANGE_PEND, HCI_CONN_SCO_SETUP_PEND, }; static inline void hci_conn_hash_init(struct hci_dev *hdev) { struct hci_conn_hash *h = &hdev->conn_hash; INIT_LIST_HEAD(&h->list); spin_lock_init(&h->lock); h->acl_num = 0; h->sco_num = 0; } static inline void hci_conn_hash_add(struct hci_dev *hdev, struct hci_conn *c) { struct hci_conn_hash *h = &hdev->conn_hash; list_add(&c->list, &h->list); switch (c->type) { case ACL_LINK: h->acl_num++; break; case LE_LINK: h->le_num++; break; case SCO_LINK: case ESCO_LINK: h->sco_num++; break; } } static inline void hci_conn_hash_del(struct hci_dev *hdev, struct hci_conn *c) { struct hci_conn_hash *h = &hdev->conn_hash; list_del(&c->list); switch (c->type) { case ACL_LINK: h->acl_num--; break; case LE_LINK: h->le_num--; break; case SCO_LINK: case ESCO_LINK: h->sco_num--; break; } } static inline struct hci_conn *hci_conn_hash_lookup_handle(struct hci_dev *hdev, __u16 handle) { struct hci_conn_hash *h = &hdev->conn_hash; struct list_head *p; struct hci_conn *c; list_for_each(p, &h->list) { c = list_entry(p, struct hci_conn, list); if (c->handle == handle) return c; } return NULL; } static inline void hci_chan_list_init(struct hci_dev *hdev) { struct hci_chan_list *h = &hdev->chan_list; INIT_LIST_HEAD(&h->list); spin_lock_init(&h->lock); } static inline struct hci_conn *hci_conn_hash_lookup_ba(struct hci_dev *hdev, __u8 type, bdaddr_t *ba) { struct hci_conn_hash *h = &hdev->conn_hash; struct list_head *p; struct hci_conn *c; list_for_each(p, &h->list) { c = list_entry(p, struct hci_conn, list); if (c->type == type && !bacmp(&c->dst, ba)) return c; } return NULL; } static inline struct hci_conn *hci_conn_hash_lookup_id(struct hci_dev *hdev, bdaddr_t *ba, __u8 id) { struct hci_conn_hash *h = &hdev->conn_hash; struct list_head *p; struct hci_conn *c; list_for_each(p, &h->list) { c = list_entry(p, struct hci_conn, list); if (!bacmp(&c->dst, ba) && (c->dst_id == id)) return c; } return NULL; } static inline struct hci_conn *hci_conn_hash_lookup_state(struct hci_dev *hdev, __u8 type, __u16 state) { struct hci_conn_hash *h = &hdev->conn_hash; struct list_head *p; struct hci_conn *c; list_for_each(p, &h->list) { c = list_entry(p, struct hci_conn, list); if (c->type == type && c->state == state) return c; } return NULL; } static inline struct hci_chan *hci_chan_list_lookup_handle(struct hci_dev *hdev, __u16 handle) { struct hci_chan_list *l = &hdev->chan_list; struct list_head *p; struct hci_chan *c; list_for_each(p, &l->list) { c = list_entry(p, struct hci_chan, list); if (c->ll_handle == handle) return c; } return NULL; } static inline struct hci_chan *hci_chan_list_lookup_id(struct hci_dev *hdev, __u8 handle) { struct hci_chan_list *l = &hdev->chan_list; struct list_head *p; struct hci_chan *c; list_for_each(p, &l->list) { c = list_entry(p, struct hci_chan, list); if (c->conn->handle == handle) return c; } return NULL; } void hci_acl_connect(struct hci_conn *conn); void hci_acl_disconn(struct hci_conn *conn, __u8 reason); void hci_add_sco(struct hci_conn *conn, __u16 handle); void hci_setup_sync(struct hci_conn *conn, __u16 handle); void hci_sco_setup(struct hci_conn *conn, __u8 status); struct hci_conn *hci_conn_add(struct hci_dev *hdev, int type, __u16 pkt_type, bdaddr_t *dst); struct hci_conn *hci_le_conn_add(struct hci_dev *hdev, bdaddr_t *dst, __u8 addr_type); int hci_conn_del(struct hci_conn *conn); void hci_conn_hash_flush(struct hci_dev *hdev); void hci_conn_check_pending(struct hci_dev *hdev); struct hci_chan *hci_chan_add(struct hci_dev *hdev); int hci_chan_del(struct hci_chan *chan); static inline void hci_chan_hold(struct hci_chan *chan) { atomic_inc(&chan->refcnt); } int hci_chan_put(struct hci_chan *chan); struct hci_chan *hci_chan_accept(struct hci_conn *hcon, struct hci_ext_fs *tx_fs, struct hci_ext_fs *rx_fs); struct hci_chan *hci_chan_create(struct hci_conn *hcon, struct hci_ext_fs *tx_fs, struct hci_ext_fs *rx_fs); void hci_chan_modify(struct hci_chan *chan, struct hci_ext_fs *tx_fs, struct hci_ext_fs *rx_fs); struct hci_conn *hci_connect(struct hci_dev *hdev, int type, __u16 pkt_type, bdaddr_t *dst, __u8 sec_level, __u8 auth_type); int hci_conn_check_link_mode(struct hci_conn *conn); int hci_conn_security(struct hci_conn *conn, __u8 sec_level, __u8 auth_type); int hci_conn_change_link_key(struct hci_conn *conn); int hci_conn_switch_role(struct hci_conn *conn, __u8 role); void hci_disconnect(struct hci_conn *conn, __u8 reason); void hci_disconnect_amp(struct hci_conn *conn, __u8 reason); void hci_conn_enter_active_mode(struct hci_conn *conn, __u8 force_active); void hci_conn_enter_sniff_mode(struct hci_conn *conn); void hci_conn_hold_device(struct hci_conn *conn); void hci_conn_put_device(struct hci_conn *conn); static inline void hci_conn_hold(struct hci_conn *conn) { atomic_inc(&conn->refcnt); del_timer(&conn->disc_timer); } static inline void hci_conn_put(struct hci_conn *conn) { if (atomic_dec_and_test(&conn->refcnt)) { unsigned long timeo; if (conn->type == ACL_LINK || conn->type == LE_LINK) { del_timer(&conn->idle_timer); if (conn->state == BT_CONNECTED) { timeo = msecs_to_jiffies(conn->disc_timeout); if (!conn->out) timeo *= 20; } else timeo = msecs_to_jiffies(10); } else timeo = msecs_to_jiffies(10); mod_timer(&conn->disc_timer, jiffies + timeo); } } /* ----- HCI Devices ----- */ static inline void __hci_dev_put(struct hci_dev *d) { if (atomic_dec_and_test(&d->refcnt)) d->destruct(d); } static inline void hci_dev_put(struct hci_dev *d) { __hci_dev_put(d); module_put(d->owner); } static inline struct hci_dev *__hci_dev_hold(struct hci_dev *d) { atomic_inc(&d->refcnt); return d; } static inline struct hci_dev *hci_dev_hold(struct hci_dev *d) { if (try_module_get(d->owner)) return __hci_dev_hold(d); return NULL; } #define hci_dev_lock(d) spin_lock(&d->lock) #define hci_dev_unlock(d) spin_unlock(&d->lock) #define hci_dev_lock_bh(d) spin_lock_bh(&d->lock) #define hci_dev_unlock_bh(d) spin_unlock_bh(&d->lock) struct hci_dev *hci_dev_get(int index); struct hci_dev *hci_get_route(bdaddr_t *src, bdaddr_t *dst); struct hci_dev *hci_dev_get_type(__u8 amp_type); struct hci_dev *hci_alloc_dev(void); void hci_free_dev(struct hci_dev *hdev); int hci_register_dev(struct hci_dev *hdev); int hci_unregister_dev(struct hci_dev *hdev); int hci_suspend_dev(struct hci_dev *hdev); int hci_resume_dev(struct hci_dev *hdev); int hci_dev_open(__u16 dev); int hci_dev_close(__u16 dev); int hci_dev_reset(__u16 dev); int hci_dev_reset_stat(__u16 dev); int hci_dev_cmd(unsigned int cmd, void __user *arg); int hci_get_dev_list(void __user *arg); int hci_get_dev_info(void __user *arg); int hci_get_conn_list(void __user *arg); int hci_get_conn_info(struct hci_dev *hdev, void __user *arg); int hci_get_auth_info(struct hci_dev *hdev, void __user *arg); int hci_set_auth_info(struct hci_dev *hdev, void __user *arg); int hci_inquiry(void __user *arg); struct bdaddr_list *hci_blacklist_lookup(struct hci_dev *hdev, bdaddr_t *bdaddr); int hci_blacklist_clear(struct hci_dev *hdev); int hci_uuids_clear(struct hci_dev *hdev); int hci_link_keys_clear(struct hci_dev *hdev); struct link_key *hci_find_link_key(struct hci_dev *hdev, bdaddr_t *bdaddr); int hci_add_link_key(struct hci_dev *hdev, int new_key, bdaddr_t *bdaddr, u8 *key, u8 type, u8 pin_len); struct link_key *hci_find_ltk(struct hci_dev *hdev, __le16 ediv, u8 rand[8]); struct link_key *hci_find_link_key_type(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 type); int hci_add_ltk(struct hci_dev *hdev, int new_key, bdaddr_t *bdaddr, u8 type, u8 auth, u8 key_size, __le16 ediv, u8 rand[8], u8 ltk[16]); int hci_remove_link_key(struct hci_dev *hdev, bdaddr_t *bdaddr); int hci_remote_oob_data_clear(struct hci_dev *hdev); struct oob_data *hci_find_remote_oob_data(struct hci_dev *hdev, bdaddr_t *bdaddr); int hci_add_remote_oob_data(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 *hash, u8 *randomizer); int hci_remove_remote_oob_data(struct hci_dev *hdev, bdaddr_t *bdaddr); #define ADV_CLEAR_TIMEOUT (3*60*HZ) /* Three minutes */ int hci_adv_entries_clear(struct hci_dev *hdev); struct adv_entry *hci_find_adv_entry(struct hci_dev *hdev, bdaddr_t *bdaddr); int hci_add_adv_entry(struct hci_dev *hdev, struct hci_ev_le_advertising_info *ev); void hci_del_off_timer(struct hci_dev *hdev); void hci_event_packet(struct hci_dev *hdev, struct sk_buff *skb); int hci_recv_frame(struct sk_buff *skb); int hci_recv_fragment(struct hci_dev *hdev, int type, void *data, int count); int hci_recv_stream_fragment(struct hci_dev *hdev, void *data, int count); int hci_register_sysfs(struct hci_dev *hdev); void hci_unregister_sysfs(struct hci_dev *hdev); void hci_conn_init_sysfs(struct hci_conn *conn); void hci_conn_add_sysfs(struct hci_conn *conn); void hci_conn_del_sysfs(struct hci_conn *conn); #define SET_HCIDEV_DEV(hdev, pdev) ((hdev)->parent = (pdev)) /* ----- LMP capabilities ----- */ #define lmp_rswitch_capable(dev) ((dev)->features[0] & LMP_RSWITCH) #define lmp_encrypt_capable(dev) ((dev)->features[0] & LMP_ENCRYPT) #define lmp_sniff_capable(dev) ((dev)->features[0] & LMP_SNIFF) #define lmp_sniffsubr_capable(dev) ((dev)->features[5] & LMP_SNIFF_SUBR) #define lmp_esco_capable(dev) ((dev)->features[3] & LMP_ESCO) #define lmp_ssp_capable(dev) ((dev)->features[6] & LMP_SIMPLE_PAIR) #define lmp_no_flush_capable(dev) ((dev)->features[6] & LMP_NO_FLUSH) #define lmp_le_capable(dev) ((dev)->features[4] & LMP_LE) /* ----- HCI protocols ----- */ struct hci_proto { char *name; unsigned int id; unsigned long flags; void *priv; int (*connect_ind) (struct hci_dev *hdev, bdaddr_t *bdaddr, __u8 type); int (*connect_cfm) (struct hci_conn *conn, __u8 status); int (*disconn_ind) (struct hci_conn *conn); int (*disconn_cfm) (struct hci_conn *conn, __u8 reason); int (*recv_acldata) (struct hci_conn *conn, struct sk_buff *skb, __u16 flags); int (*recv_scodata) (struct hci_conn *conn, struct sk_buff *skb); int (*security_cfm) (struct hci_conn *conn, __u8 status, __u8 encrypt); int (*create_cfm) (struct hci_chan *chan, __u8 status); int (*modify_cfm) (struct hci_chan *chan, __u8 status); int (*destroy_cfm) (struct hci_chan *chan, __u8 status); }; static inline int hci_proto_connect_ind(struct hci_dev *hdev, bdaddr_t *bdaddr, __u8 type) { register struct hci_proto *hp; int mask = 0; hp = hci_proto[HCI_PROTO_L2CAP]; if (hp && hp->connect_ind) mask |= hp->connect_ind(hdev, bdaddr, type); hp = hci_proto[HCI_PROTO_SCO]; if (hp && hp->connect_ind) mask |= hp->connect_ind(hdev, bdaddr, type); return mask; } static inline void hci_proto_connect_cfm(struct hci_conn *conn, __u8 status) { register struct hci_proto *hp; hp = hci_proto[HCI_PROTO_L2CAP]; if (hp && hp->connect_cfm) hp->connect_cfm(conn, status); hp = hci_proto[HCI_PROTO_SCO]; if (hp && hp->connect_cfm) hp->connect_cfm(conn, status); if (conn->connect_cfm_cb) conn->connect_cfm_cb(conn, status); } static inline int hci_proto_disconn_ind(struct hci_conn *conn) { register struct hci_proto *hp; int reason = 0x13; hp = hci_proto[HCI_PROTO_L2CAP]; if (hp && hp->disconn_ind) reason = hp->disconn_ind(conn); hp = hci_proto[HCI_PROTO_SCO]; if (hp && hp->disconn_ind) reason = hp->disconn_ind(conn); return reason; } static inline void hci_proto_disconn_cfm(struct hci_conn *conn, __u8 reason) { register struct hci_proto *hp; hp = hci_proto[HCI_PROTO_L2CAP]; if (hp && hp->disconn_cfm) hp->disconn_cfm(conn, reason); hp = hci_proto[HCI_PROTO_SCO]; if (hp && hp->disconn_cfm) hp->disconn_cfm(conn, reason); if (conn->disconn_cfm_cb) conn->disconn_cfm_cb(conn, reason); } static inline void hci_proto_auth_cfm(struct hci_conn *conn, __u8 status) { register struct hci_proto *hp; __u8 encrypt; if (test_bit(HCI_CONN_ENCRYPT_PEND, &conn->pend)) return; encrypt = (conn->link_mode & HCI_LM_ENCRYPT) ? 0x01 : 0x00; hp = hci_proto[HCI_PROTO_L2CAP]; if (hp && hp->security_cfm) hp->security_cfm(conn, status, encrypt); hp = hci_proto[HCI_PROTO_SCO]; if (hp && hp->security_cfm) hp->security_cfm(conn, status, encrypt); if (conn->security_cfm_cb) conn->security_cfm_cb(conn, status); } static inline void hci_proto_encrypt_cfm(struct hci_conn *conn, __u8 status, __u8 encrypt) { register struct hci_proto *hp; hp = hci_proto[HCI_PROTO_L2CAP]; if (hp && hp->security_cfm) hp->security_cfm(conn, status, encrypt); hp = hci_proto[HCI_PROTO_SCO]; if (hp && hp->security_cfm) hp->security_cfm(conn, status, encrypt); if (conn->security_cfm_cb) conn->security_cfm_cb(conn, status); } static inline void hci_proto_create_cfm(struct hci_chan *chan, __u8 status) { register struct hci_proto *hp; hp = hci_proto[HCI_PROTO_L2CAP]; if (hp && hp->create_cfm) hp->create_cfm(chan, status); } static inline void hci_proto_modify_cfm(struct hci_chan *chan, __u8 status) { register struct hci_proto *hp; hp = hci_proto[HCI_PROTO_L2CAP]; if (hp && hp->modify_cfm) hp->modify_cfm(chan, status); } static inline void hci_proto_destroy_cfm(struct hci_chan *chan, __u8 status) { register struct hci_proto *hp; hp = hci_proto[HCI_PROTO_L2CAP]; if (hp && hp->destroy_cfm) hp->destroy_cfm(chan, status); } int hci_register_proto(struct hci_proto *hproto); int hci_unregister_proto(struct hci_proto *hproto); /* ----- HCI callbacks ----- */ struct hci_cb { struct list_head list; char *name; void (*security_cfm) (struct hci_conn *conn, __u8 status, __u8 encrypt); void (*key_change_cfm) (struct hci_conn *conn, __u8 status); void (*role_switch_cfm) (struct hci_conn *conn, __u8 status, __u8 role); }; static inline void hci_auth_cfm(struct hci_conn *conn, __u8 status) { struct list_head *p; __u8 encrypt; hci_proto_auth_cfm(conn, status); if (test_bit(HCI_CONN_ENCRYPT_PEND, &conn->pend)) return; encrypt = (conn->link_mode & HCI_LM_ENCRYPT) ? 0x01 : 0x00; read_lock_bh(&hci_cb_list_lock); list_for_each(p, &hci_cb_list) { struct hci_cb *cb = list_entry(p, struct hci_cb, list); if (cb->security_cfm) cb->security_cfm(conn, status, encrypt); } read_unlock_bh(&hci_cb_list_lock); } static inline void hci_encrypt_cfm(struct hci_conn *conn, __u8 status, __u8 encrypt) { struct list_head *p; if (conn->sec_level == BT_SECURITY_SDP) conn->sec_level = BT_SECURITY_LOW; if (!status && encrypt && conn->pending_sec_level > conn->sec_level) conn->sec_level = conn->pending_sec_level; hci_proto_encrypt_cfm(conn, status, encrypt); read_lock_bh(&hci_cb_list_lock); list_for_each(p, &hci_cb_list) { struct hci_cb *cb = list_entry(p, struct hci_cb, list); if (cb->security_cfm) cb->security_cfm(conn, status, encrypt); } read_unlock_bh(&hci_cb_list_lock); } static inline void hci_key_change_cfm(struct hci_conn *conn, __u8 status) { struct list_head *p; read_lock_bh(&hci_cb_list_lock); list_for_each(p, &hci_cb_list) { struct hci_cb *cb = list_entry(p, struct hci_cb, list); if (cb->key_change_cfm) cb->key_change_cfm(conn, status); } read_unlock_bh(&hci_cb_list_lock); } static inline void hci_role_switch_cfm(struct hci_conn *conn, __u8 status, __u8 role) { struct list_head *p; read_lock_bh(&hci_cb_list_lock); list_for_each(p, &hci_cb_list) { struct hci_cb *cb = list_entry(p, struct hci_cb, list); if (cb->role_switch_cfm) cb->role_switch_cfm(conn, status, role); } read_unlock_bh(&hci_cb_list_lock); } int hci_register_cb(struct hci_cb *hcb); int hci_unregister_cb(struct hci_cb *hcb); int hci_register_notifier(struct notifier_block *nb); int hci_unregister_notifier(struct notifier_block *nb); /* AMP Manager event callbacks */ struct amp_mgr_cb { struct list_head list; void (*amp_cmd_complete_event) (struct hci_dev *hdev, __u16 opcode, struct sk_buff *skb); void (*amp_cmd_status_event) (struct hci_dev *hdev, __u16 opcode, __u8 status); void (*amp_event) (struct hci_dev *hdev, __u8 ev_code, struct sk_buff *skb); }; void hci_amp_cmd_complete(struct hci_dev *hdev, __u16 opcode, struct sk_buff *skb); void hci_amp_cmd_status(struct hci_dev *hdev, __u16 opcode, __u8 status); void hci_amp_event_packet(struct hci_dev *hdev, __u8 ev_code, struct sk_buff *skb); int hci_register_amp(struct amp_mgr_cb *acb); int hci_unregister_amp(struct amp_mgr_cb *acb); int hci_send_cmd(struct hci_dev *hdev, __u16 opcode, __u32 plen, void *param); void hci_send_acl(struct hci_conn *conn, struct hci_chan *chan, struct sk_buff *skb, __u16 flags); void hci_send_sco(struct hci_conn *conn, struct sk_buff *skb); void *hci_sent_cmd_data(struct hci_dev *hdev, __u16 opcode); void hci_si_event(struct hci_dev *hdev, int type, int dlen, void *data); /* ----- HCI Sockets ----- */ void hci_send_to_sock(struct hci_dev *hdev, struct sk_buff *skb, struct sock *skip_sk); /* Management interface */ int mgmt_control(struct sock *sk, struct msghdr *msg, size_t len); int mgmt_index_added(u16 index); int mgmt_index_removed(u16 index); int mgmt_powered(u16 index, u8 powered); int mgmt_discoverable(u16 index, u8 discoverable); int mgmt_connectable(u16 index, u8 connectable); int mgmt_new_key(u16 index, struct link_key *key, u8 bonded); int mgmt_connected(u16 index, bdaddr_t *bdaddr, u8 le); int mgmt_disconnected(u16 index, bdaddr_t *bdaddr); int mgmt_disconnect_failed(u16 index); int mgmt_connect_failed(u16 index, bdaddr_t *bdaddr, u8 status); int mgmt_pin_code_request(u16 index, bdaddr_t *bdaddr); int mgmt_pin_code_reply_complete(u16 index, bdaddr_t *bdaddr, u8 status); int mgmt_pin_code_neg_reply_complete(u16 index, bdaddr_t *bdaddr, u8 status); int mgmt_user_confirm_request(u16 index, u8 event, bdaddr_t *bdaddr, __le32 value); int mgmt_user_oob_request(u16 index, bdaddr_t *bdaddr); int mgmt_user_confirm_reply_complete(u16 index, bdaddr_t *bdaddr, u8 status); int mgmt_user_confirm_neg_reply_complete(u16 index, bdaddr_t *bdaddr, u8 status); int mgmt_auth_failed(u16 index, bdaddr_t *bdaddr, u8 status); int mgmt_set_local_name_complete(u16 index, u8 *name, u8 status); int mgmt_read_local_oob_data_reply_complete(u16 index, u8 *hash, u8 *randomizer, u8 status); int mgmt_device_found(u16 index, bdaddr_t *bdaddr, u8 link_type, u8 addr_type, u8 le, u8 *dev_class, s8 rssi, u8 eir_len, u8 *eir); int mgmt_remote_name(u16 index, bdaddr_t *bdaddr, u8 status, u8 *name); void mgmt_inquiry_started(u16 index); void mgmt_inquiry_complete_evt(u16 index, u8 status); void mgmt_disco_timeout(unsigned long data); void mgmt_disco_le_timeout(unsigned long data); int mgmt_encrypt_change(u16 index, bdaddr_t *bdaddr, u8 status); /* LE SMP Management interface */ int le_user_confirm_reply(struct hci_conn *conn, u16 mgmt_op, void *cp); int mgmt_remote_class(u16 index, bdaddr_t *bdaddr, u8 dev_class[3]); int mgmt_remote_version(u16 index, bdaddr_t *bdaddr, u8 ver, u16 mnf, u16 sub_ver); int mgmt_remote_features(u16 index, bdaddr_t *bdaddr, u8 features[8]); /* HCI info for socket */ #define hci_pi(sk) ((struct hci_pinfo *) sk) struct hci_pinfo { struct bt_sock bt; struct hci_dev *hdev; struct hci_filter filter; __u32 cmsg_mask; unsigned short channel; }; /* HCI security filter */ #define HCI_SFLT_MAX_OGF 5 struct hci_sec_filter { __u32 type_mask; __u32 event_mask[2]; __u32 ocf_mask[HCI_SFLT_MAX_OGF + 1][4]; }; /* ----- HCI requests ----- */ #define HCI_REQ_DONE 0 #define HCI_REQ_PEND 1 #define HCI_REQ_CANCELED 2 #define hci_req_lock(d) mutex_lock(&d->req_lock) #define hci_req_unlock(d) mutex_unlock(&d->req_lock) void hci_req_complete(struct hci_dev *hdev, __u16 cmd, int result); void hci_le_conn_update(struct hci_conn *conn, u16 min, u16 max, u16 latency, u16 to_multiplier); void hci_le_start_enc(struct hci_conn *conn, __le16 ediv, __u8 rand[8], __u8 ltk[16]); void hci_le_ltk_reply(struct hci_conn *conn, u8 ltk[16]); void hci_le_ltk_neg_reply(struct hci_conn *conn); #endif /* __HCI_CORE_H */
A2ronLil/android_kernel_motorola_fleming
include/net/bluetooth/hci_core.h
C
gpl-2.0
29,124
/* ========================================================================== Scott Pedder's custom styles www.scott-pedder.co.nz ========================================================================== */ @font-face { font-family: 'brandon_grotesquemedium'; src: url('fonts/brandongrotesque-medium.eot'); src: url('fonts/brandongrotesque-medium.eot?#iefix') format('embedded-opentype'), url('fonts/brandongrotesque-medium.woff') format('woff'), url('fonts/brandongrotesque-medium.ttf') format('truetype'), url('fonts/brandongrotesque-medium.svg#brandon_grotesquemedium') format('svg'); font-weight: normal; font-style: normal; } @font-face{ font-family: 'brandon_grotesqueMdIt'; src: url('fonts/brandongrotesque-mediumitalic-webfont.eot'); src: url('fonts/brandongrotesque-mediumitalic-webfont.eot?#iefix') format('embedded-opentype'), url('fonts/brandongrotesque-mediumitalic-webfont.woff') format('woff'), url('fonts/brandongrotesque-mediumitalic-webfont.ttf') format('truetype'), url('fonts/brandongrotesque-mediumitalic-webfont.svg#brandon_grotesqueMdIt') format('svg'); font-weight: normal; font-style: normal; } h1, h2, h3, h4{ font-family: 'brandon_grotesquemedium'; color:#63a4d9; } a:hover{ text-decoration:none;} .callus{ text-align:right; font-size:22px; margin-top:15px; } .red{ background:#F00 } .purple{ background:#63C; } .green{ background:#090} .blue{ color:#367eb6} .white{ background:#fff; } .gray{ background:#fafafa; } .ital{ font-family: 'brandon_grotesqueMdIt'; } .black{ background:#212121; } .cont{ width:100%; padding:10px 0 0 0; } .repair{ padding-top:60px; } .repair img{ border: #ccc solid 1px; padding:5px; } .social{ padding-top:10px; } .slid-cont{ width:100%; background:#eaeaea url(img/slider/border.jpg) repeat-x; } .bor{ background: url(img/slider/border.jpg) repeat-x; } .testimonial p{ font-family: 'brandon_grotesqueMdIt'; font-size:32px; text-align:right; line-height:24px; margin-top:20px; color:#666; } .container-fluid, .slider-fluid{ max-width:1200px; margin:0 auto; } span.dan{ font-family: 'brandon_grotesquemedium'; font-size:15px; line-height:18px; text-align:right; float:right; } .icons img{ float:left; padding:30px 7.5%; width:10%; } .why{ float:left; } .some{ float:right;} .why ul li{ list-style:url(img/tick.jpg); font-size:20px; padding:5px 0; color:#666; } .wel{ padding-top:20px; } .some img{ padding:5px; border:#CCC solid 1px; float:left; margin:0 10px 10px 0; } .contact{ float:left; } .contact label{ width:100px; } .contact p{ float:left; display:block; width:100%; } .form-left{ width:45%; float:left; } .form-right{ float:right; width:45%; } .contact input[type=text], .contact input[type=email]{ background:#d7d7d7; float:left; width:100%; border:none; border-radius:4px; } .contact textarea[type=textarea]{ background:#d7d7d7; float:right; width:100%; height:166px; border-radius:4px; } .form-right button[type=submit]{ float:right; background:#666; margin:10px 0; color:#fff; padding:3px 10px; border-radius:4px; } .address{ float:right; } .address ul{ margin:0; } .address ul li{ list-style:none; } .footer p{ color:#FFF; font-size:11px; line-height:28px; } ul.nav{ padding:0;} ul.nav li a{ font-size:18px; font-family: 'brandon_grotesquemedium'; } li{ line-height:20px;} div.navbar-inner{ border:none; background:none; float:right; margin:0; padding:0; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; } .navbar .nav>.active>a, .navbar .nav>.active>a:hover, .navbar .nav>.active>a:focus { color: #367eb6; text-decoration: none; background-color:#fafafa; -webkit-box-shadow: none; -moz-box-shadow:none; box-shadow: none; } .navbar .nav { position: relative; left: 0; display: block; float: left; margin: 0 0px 0 0; } .ser h1{ padding-bottom:15px; margin-top:-10px; } .top-footer{ background:#eaeaea url(img/slider/border.jpg) repeat-x;} .page-wrap{ background:#63a4d9; height:90px; } .page-title{ color:#fff; font-family: 'brandon_grotesquemedium'; font-size: 36px; padding: 30px 0 0 0; } .hero img{ margin:30px 0; border-radius:10px; } div.clients ul{ margin-top:30px; } div.clients ul li{ float:left; list-style:none; width:24.8%; text-align:center; padding:1% 0; } div.clients ul li:first-child{ border-left:#dbdcdc solid 1px } div.clients ul li{ border-right:#dbdcdc solid 1px } div.clients ul li img{ -moz-transition:all 0.6s ease; -webkit-transition:all 0.6s ease; -ms-transition:all 0.6s ease; -o-transition:all 0.6s ease; transition:all 0.6s ease; -webkit-filter:grayscale(1); } div.clients ul li img:hover{ z-index:2; -webkit-filter:grayscale(0); } .test{ margin:30px 0; } ul.test-slide{ border-radius:8px; background:#f3f3f3; margin-top:30px; padding:20px; color:#777; } ul.test-slide li p{ font-style:italic; } .gal{ padding-left:27px; } .gal ul{ margin:0; padding:0; } .gal ul li{ float:left; width:23%; padding:1%; list-style: none; } .gal img{ border-radius: 3px; } .bottom{ margin-bottom:50px; } .ser img{ padding:10px; border-radius:3px; border:#ccc solid 1px;} .service{ padding:30px 0; border-bottom:#d6d6d6 solid 1px; } .services{ padding-left:1.5%; } .services ul li{ list-style: url(img/tick.jpg); } .services h2{ margin-top:-15px; } /*styles for 768px and up! iPad portrait*/ @media only screen and (max-width: 768px) { body { padding-right: 5px; padding-left: 5px; } .wel{ padding-top:0px; } h1{ font-size:33px; margin-top:0; } } /* Large desktop */ @media (min-width: 1200px) { ... } /* Portrait tablet to landscape and desktop */ @media (min-width: 768px) and (max-width: 979px) { .scott{ display:none;} } /* Landscape phone to portrait tablet */ @media (max-width: 767px) { .callus { text-align: center; font-size: 22px; margin-top: 15px; } .menu{ color:#666; font-size:12px; position:relative; top:5px; left:20px; } .scott{ display:none;} .services h2{ margin-top:5px; } .testimonial p{ text-align:center; } .gal ul li{ width:50%; } } /* Landscape phones and down */ @media (max-width: 480px) { h1{ font-six:33px; margin-top:0; } .ser img { padding: 0px; } .page-wrap { background: #63a4d9; height: 43px; } .page-title { padding: 6px 0 0 0; } .gal ul li{ width:100%; } }
speddernz/ttplumbing
wp-content/themes/tt-pulmbing/style.css
CSS
gpl-2.0
6,553
<?php $themecolors = array( 'bg' => 'ffffff', 'text' => '333333', 'link' => '0b76ae' ); $content_width = 550; add_theme_support( 'automatic-feed-links' ); register_nav_menus( array( 'primary' => __( 'Primary Navigation', 'pool' ), ) ); function pool_page_menu() { // fallback for primary navigation ?> <ul> <li<?php if ( is_front_page() ) echo ' class="current_page_item"'; ?>><a href="<?php echo home_url( '/' ); ?>">Blog</a></li> <?php wp_list_pages('title_li=&depth=1'); ?> </ul> <?php } // Custom background add_custom_background(); function pool_custom_background() { if ( '' != get_background_color() && '' == get_background_image() ) { ?> <style type="text/css"> body { background-image: none; } </style> <?php } } add_action( 'wp_head', 'pool_custom_background' ); define('HEADER_TEXTCOLOR', 'FFFFFF'); define('HEADER_IMAGE', '%s/images/logo.gif'); // %s is theme dir uri define('HEADER_IMAGE_WIDTH', 795); define('HEADER_IMAGE_HEIGHT', 150); function pool_admin_header_style() { ?> <style type="text/css"> #headimg { height: <?php echo HEADER_IMAGE_HEIGHT; ?>px; width: <?php echo HEADER_IMAGE_WIDTH; ?>px; } #headimg h1 { font-size: 30px; letter-spacing: 0.1em; margin: 0; padding: 20px 0 20px 30px; width: 300px; } #headimg a, #headimg a:hover { background: transparent; text-decoration: none; color: #<?php header_textcolor() ?>; border-bottom: none; } #headimg #desc { display: none; } <?php if ( 'blank' == get_header_textcolor() ) { ?> #headerimg h1, #headerimg #desc { display: none; } #headimg h1 a, #headimg #desc { color:#<?php echo HEADER_TEXTCOLOR ?>; } <?php } ?> </style> <?php } function header_style() { ?> <style type="text/css"> #header { background: #8EBAFD url(<?php header_image() ?>) left repeat-y; } <?php if ( 'blank' == get_header_textcolor() ) { ?> #header h1 a, #header #desc { display: none; } <?php } else { ?> #header h1 a, #header h1 a:hover, #header #desc { color: #<?php header_textcolor() ?>; } <?php } ?> </style> <?php } add_custom_image_header('header_style', 'pool_admin_header_style'); if ( function_exists('register_sidebars') ) register_sidebars(1); ?>
yondri/newyorkando
wp-content/themes/pool/functions.php
PHP
gpl-2.0
2,152
/* * MALLOC_INFO Shell Command Implmentation * * COPYRIGHT (c) 1989-2008. * On-Line Applications Research Corporation (OAR). * * The license and distribution terms for this file may be * found in the file LICENSE in this distribution or at * http://www.rtems.com/license/LICENSE. * * $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <inttypes.h> #include <rtems.h> #include <rtems/malloc.h> #include <rtems/shell.h> #include "internal.h" extern int malloc_info( region_information_block * ); extern void rtems_shell_print_unified_work_area_message(void); int rtems_shell_main_malloc_info( int argc, char *argv[] ) { if ( argc == 2 ) { rtems_shell_print_unified_work_area_message(); if ( !strcmp( argv[1], "info" ) ) { region_information_block info; malloc_info( &info ); rtems_shell_print_heap_info( "free", &info.Free ); rtems_shell_print_heap_info( "used", &info.Used ); return 0; } else if ( !strcmp( argv[1], "stats" ) ) { malloc_report_statistics_with_plugin( stdout, (rtems_printk_plugin_t) fprintf ); return 0; } } fprintf( stderr, "%s: [info|stats]\n", argv[0] ); return -1; } rtems_shell_cmd_t rtems_shell_MALLOC_INFO_Command = { "malloc", /* name */ "[info|stats]", /* usage */ "mem", /* topic */ rtems_shell_main_malloc_info, /* command */ NULL, /* alias */ NULL /* next */ };
t-crest/rtems
cpukit/libmisc/shell/main_mallocinfo.c
C
gpl-2.0
1,627
/* Copyright (C) 2008-2016 Vana Development Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. 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. */ #include "fame.hpp" #include "common/io/database.hpp" #include "common/packet_reader.hpp" #include "channel_server/channel_server.hpp" #include "channel_server/fame_packet.hpp" #include "channel_server/player.hpp" #include "channel_server/player_data_provider.hpp" namespace vana { namespace channel_server { auto fame::handle_fame(ref_ptr<player> player, packet_reader &reader) -> void { game_player_id target_id = reader.get<game_player_id>(); uint8_t type = reader.get<uint8_t>(); if (target_id > 0) { if (player->get_id() == target_id) { // Hacking return; } packets::fame::errors check_result = can_fame(player, target_id); if (check_result == packets::fame::errors::no_error_fame_sent) { player->send(packets::fame::send_error(check_result)); } else { auto famee = channel_server::get_instance().get_player_data_provider().get_player(target_id); game_fame new_fame = famee->get_stats()->get_fame() + (type == 1 ? 1 : -1); famee->get_stats()->set_fame(new_fame); add_fame_log(player->get_id(), target_id); player->send(packets::fame::send_fame(famee->get_name(), type, new_fame)); famee->send(packets::fame::receive_fame(player->get_name(), type)); } } else { player->send(packets::fame::send_error(packets::fame::errors::incorrect_user)); } } auto fame::can_fame(ref_ptr<player> player, game_player_id to) -> packets::fame::errors { game_player_id from = player->get_id(); if (player->get_stats()->get_level() < 15) { return packets::fame::errors::level_under15; } if (get_last_fame_log(from) == search_result::found) { return packets::fame::errors::already_famed_today; } if (get_last_fame_sp_log(from, to) == search_result::found) { return packets::fame::errors::famed_this_month; } return packets::fame::errors::no_error_fame_sent; } auto fame::add_fame_log(game_player_id from, game_player_id to) -> void { auto &db = vana::io::database::get_char_db(); auto &sql = db.get_session(); sql.once << "INSERT INTO " << db.make_table(vana::table::fame_log) << " (from_character_id, to_character_id, fame_time) " << "VALUES (:from, :to, NOW())", soci::use(from, "from"), soci::use(to, "to"); } auto fame::get_last_fame_log(game_player_id from) -> search_result { int32_t fame_time = static_cast<int32_t>(channel_server::get_instance().get_config().fame_time.count()); if (fame_time == 0) { return search_result::found; } if (fame_time == -1) { return search_result::not_found; } auto &db = vana::io::database::get_char_db(); auto &sql = db.get_session(); optional<unix_time> time; sql.once << "SELECT fame_time " << "FROM " << db.make_table(vana::table::fame_log) << " " << "WHERE from_character_id = :from AND UNIX_TIMESTAMP(fame_time) > UNIX_TIMESTAMP() - :fame_time " << "ORDER BY fame_time DESC", soci::use(from, "from"), soci::use(fame_time, "fame_time"), soci::into(time); return time.is_initialized() ? search_result::found : search_result::not_found; } auto fame::get_last_fame_sp_log(game_player_id from, game_player_id to) -> search_result { int32_t fame_reset_time = static_cast<int32_t>(channel_server::get_instance().get_config().fame_reset_time.count()); if (fame_reset_time == 0) { return search_result::found; } if (fame_reset_time == -1) { return search_result::not_found; } auto &db = vana::io::database::get_char_db(); auto &sql = db.get_session(); optional<unix_time> time; sql.once << "SELECT fame_time " << "FROM " << db.make_table(vana::table::fame_log) << " " << "WHERE from_character_id = :from AND to_character_id = :to AND UNIX_TIMESTAMP(fame_time) > UNIX_TIMESTAMP() - :fame_reset_time " << "ORDER BY fame_time DESC", soci::use(from, "from"), soci::use(to, "to"), soci::use(fame_reset_time, "fame_reset_time"), soci::into(time); return time.is_initialized() ? search_result::found : search_result::not_found; } } }
diamondo25/Vana
src/channel_server/fame.cpp
C++
gpl-2.0
4,586
package org.mewx.wenku8; import android.annotation.SuppressLint; import android.app.Application; import android.content.Context; /** * The class is for getting context everywhere */ public class MyApp extends Application { @SuppressLint("StaticFieldLeak") private static Context context; @Override public void onCreate() { super.onCreate(); context = getApplicationContextLocal(); } /** * wrap the getApplicationContext() function for easier unit testing * @return the results from getApplicationContext() */ Context getApplicationContextLocal() { return getApplicationContext(); } public static Context getContext(){ return context; } }
MewX/light-novel-library_Wenku8_Android
studio-android/LightNovelLibrary/app/src/main/java/org/mewx/wenku8/MyApp.java
Java
gpl-2.0
732
<?php if (!defined('THINK_PATH')) exit();?><!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>首页</title> <style type="text/css"> .container{width:300px;margin:0 auto;} </style> </head> <body> <div class="container"> <form action="/thinkphp_siteinfo/index.php/Home/Siteuser/add" method="post"> <p>用户名 <input type="text" name="username" value=""></p> <p>QQ号 <input type="text" name="uin" value=""></p> <p>密码 <input type="text" name="password" value=""></p> <p> <select name="userid"> <?php echo ($option); ?> </select> </p> <input type="submit" value="添加"> </form> </div> </body> </html>
highmind/Study
php/php-jwt/Server/Application/Runtime/Cache/Home/b392b30b0ada41f791f77020f2b27846.php
PHP
gpl-2.0
755
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2021 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #ifndef UNORDEREDTASKPOINT_HPP #define UNORDEREDTASKPOINT_HPP #include "Task/Points/TaskWaypoint.hpp" struct TaskBehaviour; /** * Class for unordered task points (e.g. goto and abort) * */ class UnorderedTaskPoint final : public TaskWaypoint { double safety_height_arrival; public: /** * Constructor. * * @param wp Waypoint to be used as task point origin * @param tb Task Behaviour defining options (esp safety heights) */ UnorderedTaskPoint(WaypointPtr wp, const TaskBehaviour &tb); void SetTaskBehaviour(const TaskBehaviour &tb); /* virtual methods from class TaskPoint */ virtual GeoVector GetVectorRemaining(const GeoPoint &reference) const override; virtual double GetElevation() const override; }; #endif
sandrinr/XCSoar
src/Engine/Task/Unordered/UnorderedTaskPoint.hpp
C++
gpl-2.0
1,676
/* * Copyright (c) 2009, Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE 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. * */ package se.sics.cooja.mspmote; import java.awt.Container; import java.io.File; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import se.sics.cooja.GUI; import se.sics.cooja.MoteInterface; import se.sics.cooja.Simulation; import se.sics.cooja.dialogs.AbstractCompileDialog; public class MspCompileDialog extends AbstractCompileDialog { private static final long serialVersionUID = -7273193946433145019L; private final String target; public static boolean showDialog( Container parent, Simulation simulation, MspMoteType moteType, String target) { final AbstractCompileDialog dialog = new MspCompileDialog(parent, simulation, moteType, target); /* Show dialog and wait for user */ dialog.setVisible(true); /* BLOCKS */ if (!dialog.createdOK()) { return false; } /* Assume that if a firmware exists, compilation was ok */ return true; } private MspCompileDialog(Container parent, Simulation simulation, MspMoteType moteType, String target) { super(parent, simulation, moteType); this.target = target; setTitle("Create Mote Type: Compile Contiki for " + target); addCompilationTipsTab(tabbedPane); } public Class<? extends MoteInterface>[] getAllMoteInterfaces() { return ((MspMoteType)moteType).getAllMoteInterfaceClasses(); } public Class<? extends MoteInterface>[] getDefaultMoteInterfaces() { return ((MspMoteType)moteType).getDefaultMoteInterfaceClasses(); } private void addCompilationTipsTab(JTabbedPane parent) { JTextArea textArea = new JTextArea(); textArea.setEditable(false); textArea.append("# Without low-power radio:\n" + "DEFINES=NETSTACK_MAC=nullmac_driver,NETSTACK_RDC=nullrdc_noframer_driver,CC2420_CONF_AUTOACK=0\n" + "# (remember to \"make clean\" after changing compilation flags)" ); parent.addTab("Tips", null, new JScrollPane(textArea), "Compilation tips"); } public boolean canLoadFirmware(File file) { if (file.getName().endsWith("." + target)) { return true; } if (file.getName().equals("main.exe")) { return true; } return false; } public String getDefaultCompileCommands(File source) { /* TODO Split into String[] */ return GUI.getExternalToolsSetting("PATH_MAKE") + " " + getExpectedFirmwareFile(source).getName() + " TARGET=" + target; } public File getExpectedFirmwareFile(File source) { return ((MspMoteType)moteType).getExpectedFirmwareFile(source); } public void writeSettingsToMoteType() { /* Nothing to do */ } protected String getTargetName() { /* Override me */ return target; } }
miiicmueller/TerraZoo
contiki-2.7/tools/cooja/apps/mspsim/src/se/sics/cooja/mspmote/MspCompileDialog.java
Java
gpl-2.0
4,289
; master library - MSDOS - int29h ; ; Description: ; int29h‚ª‚È‚¢DOS‚Ì‚½‚߂́AƒGƒ~ƒ…ƒŒ[ƒVƒ‡ƒ“Ý’è ; ; Function/Procedures: ; void dos29fake_start(void) ; ; void dos29fake_end(void) ; ; ; Parameters: ; none ; ; Returns: ; none ; ; Binding Target: ; Microsoft-C / Turbo-C / Turbo Pascal ; ; Running Target: ; PC-9801 ; ; Requiring Resources: ; CPU: 8086 ; MS-DOS: v2` ; ; Notes: ; @int29h‚ª‘¶Ý‚µ‚È‚¢‚Æ‚«‚¾‚¯‘g‚ݍž‚݂܂·B ; ‚»‚Ì”»’è‚É‚ÍCONƒfƒoƒCƒX‚ÌSPECLƒrƒbƒg‚ðŒ©‚Ä‚¢‚Ü‚·B ; ‘g‚ݍž‚ñ‚¾ê‡Aƒtƒ@ƒCƒ‹ƒnƒ“ƒhƒ‹‚ð‚ЂƂè—L‚µ‚Ü‚·B ; ; Compiler/Assembler: ; TASM 3.0 ; OPTASM 1.6 ; ; Author: ; —ö’ˏº•F ; ; Revision History: ; 93/ 3/30 Initial .MODEL SMALL include func.inc EXTRN DOS_SETVECT:CALLMODEL .DATA con db 'CON',0 .DATA? last29 dd ? .CODE handle dw 1 int29 proc far push DS push AX push BX push CX push DX mov BX,SP lea DX,[BX+6] mov AX,SS mov DS,AX mov BX,CS:handle mov AH,40h ; write handle mov CX,1 int 21h pop DX pop CX pop BX pop AX pop DS iret int29 endp func DOS29FAKE_START ; dos92fake_start() { cmp CS:handle,1 jne short IGNORE ; house keeping mov DX,offset con mov AX,3d01h int 21h ; open handle for write jc short IGNORE ; failure... mov BX,AX mov AX,4400h ; read device information int 21h and DX,0092h ; ISDEV,SPECL,ISCOT cmp DX,0092h je short END_FAKE mov CS:handle,BX mov AX,29h push AX push CS mov AX,offset int29 push AX call DOS_SETVECT mov word ptr last29,AX mov word ptr last29+2,DX IGNORE: ret endfunc ; } func DOS29FAKE_END ; dos29fake_end() { mov AX,1 xchg AX,CS:handle cmp AX,1 je short IGNORE ; house keeping mov BX,AX mov AX,29h push AX push word ptr last29+2 push word ptr last29 call DOS_SETVECT END_FAKE: mov AH,3eh int 21h ; close handle ret endfunc ; } END
joncampbell123/dosbox-x
ref/master-lib/src/dos29fak.asm
Assembly
gpl-2.0
1,915
EXTRA_CFLAGS += $(USER_EXTRA_CFLAGS) EXTRA_CFLAGS += -O1 #EXTRA_CFLAGS += -O3 #EXTRA_CFLAGS += -Wall #EXTRA_CFLAGS += -Wextra #EXTRA_CFLAGS += -Werror #EXTRA_CFLAGS += -pedantic #EXTRA_CFLAGS += -Wshadow -Wpointer-arith -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes EXTRA_CFLAGS += -Wno-unused-variable EXTRA_CFLAGS += -Wno-unused-value EXTRA_CFLAGS += -Wno-unused-label EXTRA_CFLAGS += -Wno-unused-parameter EXTRA_CFLAGS += -Wno-unused-function EXTRA_CFLAGS += -Wno-unused #EXTRA_CFLAGS += -Wno-uninitialized EXTRA_CFLAGS += -I$(src)/include EXTRA_LDFLAGS += --strip-debug CONFIG_AUTOCFG_CP = n ########################## WIFI IC ############################ CONFIG_MULTIDRV = n CONFIG_RTL8192C = n CONFIG_RTL8192D = n CONFIG_RTL8723A = n CONFIG_RTL8188E = y CONFIG_RTL8812A = n CONFIG_RTL8821A = n CONFIG_RTL8192E = n CONFIG_RTL8723B = n ######################### Interface ########################### CONFIG_USB_HCI = y CONFIG_PCI_HCI = n CONFIG_SDIO_HCI = n CONFIG_GSPI_HCI = n ########################## Features ########################### CONFIG_MP_INCLUDED = y CONFIG_POWER_SAVING = y CONFIG_USB_AUTOSUSPEND = n CONFIG_HW_PWRP_DETECTION = n CONFIG_WIFI_TEST = n CONFIG_BT_COEXIST = n CONFIG_RTL8192CU_REDEFINE_1X1 = n CONFIG_INTEL_WIDI = n CONFIG_WAPI_SUPPORT = n CONFIG_EFUSE_CONFIG_FILE = n CONFIG_EXT_CLK = n CONFIG_TRAFFIC_PROTECT = n CONFIG_LOAD_PHY_PARA_FROM_FILE = y CONFIG_CALIBRATE_TX_POWER_BY_REGULATORY = n CONFIG_CALIBRATE_TX_POWER_TO_MAX = n CONFIG_ODM_ADAPTIVITY = n ######################## Wake On Lan ########################## CONFIG_WOWLAN = n CONFIG_GPIO_WAKEUP = n CONFIG_PNO_SUPPORT = n CONFIG_PNO_SET_DEBUG = n CONFIG_AP_WOWLAN = n ######### Notify SDIO Host Keep Power During Syspend ########## CONFIG_RTW_SDIO_PM_KEEP_POWER = y ###################### Platform Related ####################### CONFIG_PLATFORM_I386_PC = n CONFIG_PLATFORM_ANDROID_X86 = n CONFIG_PLATFORM_JB_X86 = n CONFIG_PLATFORM_ARM_S3C2K4 = n CONFIG_PLATFORM_ARM_PXA2XX = n CONFIG_PLATFORM_ARM_S3C6K4 = n CONFIG_PLATFORM_MIPS_RMI = n CONFIG_PLATFORM_RTD2880B = n CONFIG_PLATFORM_MIPS_AR9132 = n CONFIG_PLATFORM_RTK_DMP = n CONFIG_PLATFORM_MIPS_PLM = n CONFIG_PLATFORM_MSTAR389 = n CONFIG_PLATFORM_MT53XX = n CONFIG_PLATFORM_ARM_MX51_241H = n CONFIG_PLATFORM_FS_MX61 = n CONFIG_PLATFORM_ACTIONS_ATJ227X = n CONFIG_PLATFORM_TEGRA3_CARDHU = n CONFIG_PLATFORM_TEGRA4_DALMORE = n CONFIG_PLATFORM_ARM_TCC8900 = n CONFIG_PLATFORM_ARM_TCC8920 = n CONFIG_PLATFORM_ARM_TCC8920_JB42 = n CONFIG_PLATFORM_ARM_RK2818 = n CONFIG_PLATFORM_ARM_RK3066 = n CONFIG_PLATFORM_ARM_RK3188 = n CONFIG_PLATFORM_ARM_URBETTER = n CONFIG_PLATFORM_ARM_TI_PANDA = n CONFIG_PLATFORM_MIPS_JZ4760 = n CONFIG_PLATFORM_DMP_PHILIPS = n CONFIG_PLATFORM_TI_DM365 = n CONFIG_PLATFORM_MSTAR_TITANIA12 = n CONFIG_PLATFORM_MSTAR = n CONFIG_PLATFORM_SZEBOOK = n CONFIG_PLATFORM_ARM_SUNxI = n CONFIG_PLATFORM_ARM_SUN6I = n CONFIG_PLATFORM_ARM_SUN7I = n CONFIG_PLATFORM_ARM_SUN8I = n CONFIG_PLATFORM_ACTIONS_ATM702X = n CONFIG_PLATFORM_ACTIONS_ATV5201 = n CONFIG_PLATFORM_ARM_RTD299X = n CONFIG_PLATFORM_ARM_SPREADTRUM_6820 = n CONFIG_PLATFORM_ARM_SPREADTRUM_8810 = n CONFIG_PLATFORM_AML = y ############################################################### CONFIG_DRVEXT_MODULE = n export TopDIR ?= $(shell pwd) ########### COMMON ################################# ifeq ($(CONFIG_GSPI_HCI), y) HCI_NAME = gspi endif ifeq ($(CONFIG_SDIO_HCI), y) HCI_NAME = sdio endif ifeq ($(CONFIG_USB_HCI), y) HCI_NAME = usb endif ifeq ($(CONFIG_PCI_HCI), y) HCI_NAME = pci endif _OS_INTFS_FILES := os_dep/osdep_service.o \ os_dep/linux/os_intfs.o \ os_dep/linux/$(HCI_NAME)_intf.o \ os_dep/linux/$(HCI_NAME)_ops_linux.o \ os_dep/linux/ioctl_linux.o \ os_dep/linux/xmit_linux.o \ os_dep/linux/mlme_linux.o \ os_dep/linux/recv_linux.o \ os_dep/linux/ioctl_cfg80211.o \ os_dep/linux/wifi_regd.o \ os_dep/linux/rtw_android.o \ os_dep/linux/rtw_proc.o ifeq ($(CONFIG_SDIO_HCI), y) _OS_INTFS_FILES += os_dep/linux/custom_gpio_linux.o _OS_INTFS_FILES += os_dep/linux/$(HCI_NAME)_ops_linux.o endif ifeq ($(CONFIG_GSPI_HCI), y) _OS_INTFS_FILES += os_dep/linux/custom_gpio_linux.o _OS_INTFS_FILES += os_dep/linux/$(HCI_NAME)_ops_linux.o endif _HAL_INTFS_FILES := hal/hal_intf.o \ hal/hal_com.o \ hal/hal_com_phycfg.o \ hal/hal_phy.o \ hal/hal_btcoex.o \ hal/hal_hci/hal_$(HCI_NAME).o \ hal/led/hal_$(HCI_NAME)_led.o _OUTSRC_FILES := hal/OUTSRC/odm_debug.o \ hal/OUTSRC/odm_AntDiv.o\ hal/OUTSRC/odm_interface.o\ hal/OUTSRC/odm_HWConfig.o\ hal/OUTSRC/odm.o\ hal/OUTSRC/HalPhyRf.o EXTRA_CFLAGS += -I$(src)/platform _PLATFORM_FILES := platform/platform_ops.o ifeq ($(CONFIG_BT_COEXIST), y) EXTRA_CFLAGS += -I$(src)/hal/OUTSRC-BTCoexist _OUTSRC_FILES += hal/OUTSRC-BTCoexist/HalBtc8188c2Ant.o \ hal/OUTSRC-BTCoexist/HalBtc8192d2Ant.o \ hal/OUTSRC-BTCoexist/HalBtc8192e1Ant.o \ hal/OUTSRC-BTCoexist/HalBtc8192e2Ant.o \ hal/OUTSRC-BTCoexist/HalBtc8723a1Ant.o \ hal/OUTSRC-BTCoexist/HalBtc8723a2Ant.o \ hal/OUTSRC-BTCoexist/HalBtc8723b1Ant.o \ hal/OUTSRC-BTCoexist/HalBtc8723b2Ant.o \ hal/OUTSRC-BTCoexist/HalBtc8812a1Ant.o \ hal/OUTSRC-BTCoexist/HalBtc8812a2Ant.o \ hal/OUTSRC-BTCoexist/HalBtc8821a1Ant.o \ hal/OUTSRC-BTCoexist/HalBtc8821a2Ant.o endif ########### HAL_RTL8192C ################################# ifeq ($(CONFIG_RTL8192C), y) RTL871X = rtl8192c ifeq ($(CONFIG_USB_HCI), y) MODULE_NAME = 8192cu endif ifeq ($(CONFIG_PCI_HCI), y) MODULE_NAME = 8192ce endif EXTRA_CFLAGS += -DCONFIG_RTL8192C _HAL_INTFS_FILES += \ hal/$(RTL871X)/$(RTL871X)_sreset.o \ hal/$(RTL871X)/$(RTL871X)_xmit.o _HAL_INTFS_FILES += hal/$(RTL871X)/$(RTL871X)_hal_init.o \ hal/$(RTL871X)/$(RTL871X)_phycfg.o \ hal/$(RTL871X)/$(RTL871X)_rf6052.o \ hal/$(RTL871X)/$(RTL871X)_dm.o \ hal/$(RTL871X)/$(RTL871X)_rxdesc.o \ hal/$(RTL871X)/$(RTL871X)_cmd.o \ hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_halinit.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_led.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_xmit.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_recv.o _HAL_INTFS_FILES += hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_ops_linux.o ifeq ($(CONFIG_MP_INCLUDED), y) _HAL_INTFS_FILES += hal/$(RTL871X)/$(RTL871X)_mp.o endif _OUTSRC_FILES += hal/OUTSRC/$(RTL871X)/odm_RTL8192C.o\ hal/OUTSRC/$(RTL871X)/HalDMOutSrc8192C_CE.o ifeq ($(CONFIG_USB_HCI), y) _OUTSRC_FILES += hal/OUTSRC/$(RTL871X)/Hal8192CUFWImg_CE.o \ hal/OUTSRC/$(RTL871X)/Hal8192CUPHYImg_CE.o \ hal/OUTSRC/$(RTL871X)/Hal8192CUMACImg_CE.o endif ifeq ($(CONFIG_PCI_HCI), y) _OUTSRC_FILES += hal/OUTSRC/$(RTL871X)/Hal8192CEFWImg_CE.o \ hal/OUTSRC/$(RTL871X)/Hal8192CEPHYImg_CE.o \ hal/OUTSRC/$(RTL871X)/Hal8192CEMACImg_CE.o endif endif ########### HAL_RTL8192D ################################# ifeq ($(CONFIG_RTL8192D), y) RTL871X = rtl8192d ifeq ($(CONFIG_USB_HCI), y) MODULE_NAME = 8192du endif ifeq ($(CONFIG_PCI_HCI), y) MODULE_NAME = 8192de endif EXTRA_CFLAGS += -DCONFIG_RTL8192D _HAL_INTFS_FILES += \ hal/$(RTL871X)/$(RTL871X)_xmit.o _HAL_INTFS_FILES += hal/$(RTL871X)/$(RTL871X)_hal_init.o \ hal/$(RTL871X)/$(RTL871X)_phycfg.o \ hal/$(RTL871X)/$(RTL871X)_rf6052.o \ hal/$(RTL871X)/$(RTL871X)_dm.o \ hal/$(RTL871X)/$(RTL871X)_rxdesc.o \ hal/$(RTL871X)/$(RTL871X)_cmd.o \ hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_halinit.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_led.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_xmit.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_recv.o _HAL_INTFS_FILES += hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_ops_linux.o ifeq ($(CONFIG_MP_INCLUDED), y) _HAL_INTFS_FILES += hal/$(RTL871X)/$(RTL871X)_mp.o endif _OUTSRC_FILES += hal/OUTSRC/$(RTL871X)/odm_RTL8192D.o\ hal/OUTSRC/$(RTL871X)/HalDMOutSrc8192D_CE.o ifeq ($(CONFIG_USB_HCI), y) _OUTSRC_FILES += hal/OUTSRC/$(RTL871X)/Hal8192DUFWImg_CE.o \ hal/OUTSRC/$(RTL871X)/Hal8192DUPHYImg_CE.o \ hal/OUTSRC/$(RTL871X)/Hal8192DUMACImg_CE.o endif ifeq ($(CONFIG_PCI_HCI), y) _OUTSRC_FILES += hal/OUTSRC/$(RTL871X)/Hal8192DEFWImg_CE.o \ hal/OUTSRC/$(RTL871X)/Hal8192DEPHYImg_CE.o \ hal/OUTSRC/$(RTL871X)/Hal8192DEMACImg_CE.o endif endif ########### HAL_RTL8723A ################################# ifeq ($(CONFIG_RTL8723A), y) RTL871X = rtl8723a ifeq ($(CONFIG_GSPI_HCI), y) MODULE_NAME = 8723as endif ifeq ($(CONFIG_SDIO_HCI), y) MODULE_NAME = 8723as endif ifeq ($(CONFIG_USB_HCI), y) MODULE_NAME = 8723au endif ifeq ($(CONFIG_PCI_HCI), y) MODULE_NAME = 8723ae endif EXTRA_CFLAGS += -DCONFIG_RTL8723A _HAL_INTFS_FILES += hal/HalPwrSeqCmd.o \ hal/$(RTL871X)/Hal8723PwrSeq.o\ hal/$(RTL871X)/$(RTL871X)_xmit.o \ hal/$(RTL871X)/$(RTL871X)_sreset.o _HAL_INTFS_FILES += hal/$(RTL871X)/$(RTL871X)_hal_init.o \ hal/$(RTL871X)/$(RTL871X)_phycfg.o \ hal/$(RTL871X)/$(RTL871X)_rf6052.o \ hal/$(RTL871X)/$(RTL871X)_dm.o \ hal/$(RTL871X)/$(RTL871X)_rxdesc.o \ hal/$(RTL871X)/$(RTL871X)_cmd.o \ hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_halinit.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_led.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_xmit.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_recv.o ifeq ($(CONFIG_SDIO_HCI), y) _HAL_INTFS_FILES += hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_ops.o else ifeq ($(CONFIG_GSPI_HCI), y) _HAL_INTFS_FILES += hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_ops.o else _HAL_INTFS_FILES += hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_ops_linux.o endif endif ifeq ($(CONFIG_MP_INCLUDED), y) _HAL_INTFS_FILES += hal/$(RTL871X)/$(RTL871X)_mp.o endif ifeq ($(CONFIG_GSPI_HCI), y) _OUTSRC_FILES += hal/OUTSRC/$(RTL871X)/Hal8723SHWImg_CE.o endif ifeq ($(CONFIG_SDIO_HCI), y) _OUTSRC_FILES += hal/OUTSRC/$(RTL871X)/Hal8723SHWImg_CE.o endif ifeq ($(CONFIG_USB_HCI), y) _OUTSRC_FILES += hal/OUTSRC/$(RTL871X)/Hal8723UHWImg_CE.o endif ifeq ($(CONFIG_PCI_HCI), y) _OUTSRC_FILES += hal/OUTSRC/$(RTL871X)/Hal8723EHWImg_CE.o endif #hal/OUTSRC/$(RTL871X)/HalHWImg8723A_FW.o _OUTSRC_FILES += hal/OUTSRC/$(RTL871X)/HalHWImg8723A_BB.o\ hal/OUTSRC/$(RTL871X)/HalHWImg8723A_MAC.o\ hal/OUTSRC/$(RTL871X)/HalHWImg8723A_RF.o\ hal/OUTSRC/$(RTL871X)/odm_RegConfig8723A.o _OUTSRC_FILES += hal/OUTSRC/rtl8192c/HalDMOutSrc8192C_CE.o endif ########### HAL_RTL8188E ################################# ifeq ($(CONFIG_RTL8188E), y) RTL871X = rtl8188e ifeq ($(CONFIG_SDIO_HCI), y) MODULE_NAME = 8189es endif ifeq ($(CONFIG_USB_HCI), y) MODULE_NAME = 8188eu endif ifeq ($(CONFIG_PCI_HCI), y) MODULE_NAME = 8188ee endif EXTRA_CFLAGS += -DCONFIG_RTL8188E _HAL_INTFS_FILES += hal/HalPwrSeqCmd.o \ hal/$(RTL871X)/Hal8188EPwrSeq.o\ hal/$(RTL871X)/$(RTL871X)_xmit.o\ hal/$(RTL871X)/$(RTL871X)_sreset.o _HAL_INTFS_FILES += hal/$(RTL871X)/$(RTL871X)_hal_init.o \ hal/$(RTL871X)/$(RTL871X)_phycfg.o \ hal/$(RTL871X)/$(RTL871X)_rf6052.o \ hal/$(RTL871X)/$(RTL871X)_dm.o \ hal/$(RTL871X)/$(RTL871X)_rxdesc.o \ hal/$(RTL871X)/$(RTL871X)_cmd.o \ hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_halinit.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_led.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_xmit.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_recv.o ifeq ($(CONFIG_SDIO_HCI), y) _HAL_INTFS_FILES += hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_ops.o else ifeq ($(CONFIG_GSPI_HCI), y) _HAL_INTFS_FILES += hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_ops.o else _HAL_INTFS_FILES += hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_ops_linux.o endif endif ifeq ($(CONFIG_MP_INCLUDED), y) _HAL_INTFS_FILES += hal/$(RTL871X)/$(RTL871X)_mp.o endif #hal/OUTSRC/$(RTL871X)/Hal8188EFWImg_CE.o _OUTSRC_FILES += hal/OUTSRC/$(RTL871X)/HalHWImg8188E_MAC.o\ hal/OUTSRC/$(RTL871X)/HalHWImg8188E_BB.o\ hal/OUTSRC/$(RTL871X)/HalHWImg8188E_RF.o\ hal/OUTSRC/$(RTL871X)/HalHWImg8188E_FW.o\ hal/OUTSRC/$(RTL871X)/HalPhyRf_8188e.o\ hal/OUTSRC/$(RTL871X)/odm_RegConfig8188E.o\ hal/OUTSRC/$(RTL871X)/Hal8188ERateAdaptive.o\ hal/OUTSRC/$(RTL871X)/odm_RTL8188E.o endif ########### HAL_RTL8192E ################################# ifeq ($(CONFIG_RTL8192E), y) RTL871X = rtl8192e ifeq ($(CONFIG_SDIO_HCI), y) MODULE_NAME = 8192es endif ifeq ($(CONFIG_USB_HCI), y) MODULE_NAME = 8192eu endif ifeq ($(CONFIG_PCI_HCI), y) MODULE_NAME = 8192ee endif EXTRA_CFLAGS += -DCONFIG_RTL8192E _HAL_INTFS_FILES += hal/HalPwrSeqCmd.o \ hal/$(RTL871X)/Hal8192EPwrSeq.o\ hal/$(RTL871X)/$(RTL871X)_xmit.o\ hal/$(RTL871X)/$(RTL871X)_sreset.o _HAL_INTFS_FILES += hal/$(RTL871X)/$(RTL871X)_hal_init.o \ hal/$(RTL871X)/$(RTL871X)_phycfg.o \ hal/$(RTL871X)/$(RTL871X)_rf6052.o \ hal/$(RTL871X)/$(RTL871X)_dm.o \ hal/$(RTL871X)/$(RTL871X)_rxdesc.o \ hal/$(RTL871X)/$(RTL871X)_cmd.o \ hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_halinit.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_led.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_xmit.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_recv.o ifeq ($(CONFIG_SDIO_HCI), y) _HAL_INTFS_FILES += hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_ops.o else ifeq ($(CONFIG_GSPI_HCI), y) _HAL_INTFS_FILES += hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_ops.o else _HAL_INTFS_FILES += hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_ops_linux.o endif endif ifeq ($(CONFIG_MP_INCLUDED), y) _HAL_INTFS_FILES += hal/$(RTL871X)/$(RTL871X)_mp.o endif #hal/OUTSRC/$(RTL871X)/HalHWImg8188E_FW.o _OUTSRC_FILES += hal/OUTSRC/$(RTL871X)/HalHWImg8192E_MAC.o\ hal/OUTSRC/$(RTL871X)/HalHWImg8192E_BB.o\ hal/OUTSRC/$(RTL871X)/HalHWImg8192E_RF.o\ hal/OUTSRC/$(RTL871X)/HalHWImg8192E_FW.o\ hal/OUTSRC/$(RTL871X)/HalPhyRf_8192e.o\ hal/OUTSRC/$(RTL871X)/odm_RegConfig8192E.o\ hal/OUTSRC/$(RTL871X)/odm_RTL8192E.o endif ########### HAL_RTL8812A_RTL8821A ################################# ifneq ($(CONFIG_RTL8812A)_$(CONFIG_RTL8821A), n_n) RTL871X = rtl8812a ifeq ($(CONFIG_USB_HCI), y) MODULE_NAME = 8812au endif ifeq ($(CONFIG_PCI_HCI), y) MODULE_NAME = 8812ae endif ifeq ($(CONFIG_SDIO_HCI), y) MODULE_NAME = 8812as endif _HAL_INTFS_FILES += hal/HalPwrSeqCmd.o \ hal/$(RTL871X)/Hal8812PwrSeq.o \ hal/$(RTL871X)/Hal8821APwrSeq.o\ hal/$(RTL871X)/$(RTL871X)_xmit.o\ hal/$(RTL871X)/$(RTL871X)_sreset.o _HAL_INTFS_FILES += hal/$(RTL871X)/$(RTL871X)_hal_init.o \ hal/$(RTL871X)/$(RTL871X)_phycfg.o \ hal/$(RTL871X)/$(RTL871X)_rf6052.o \ hal/$(RTL871X)/$(RTL871X)_dm.o \ hal/$(RTL871X)/$(RTL871X)_rxdesc.o \ hal/$(RTL871X)/$(RTL871X)_cmd.o \ hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_halinit.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_led.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_xmit.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_recv.o ifeq ($(CONFIG_SDIO_HCI), y) _HAL_INTFS_FILES += hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_ops.o else ifeq ($(CONFIG_GSPI_HCI), y) _HAL_INTFS_FILES += hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_ops.o else _HAL_INTFS_FILES += hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_ops_linux.o endif endif ifeq ($(CONFIG_MP_INCLUDED), y) _HAL_INTFS_FILES += hal/$(RTL871X)/$(RTL871X)_mp.o endif ifeq ($(CONFIG_RTL8812A), y) EXTRA_CFLAGS += -DCONFIG_RTL8812A _OUTSRC_FILES += hal/OUTSRC/$(RTL871X)/HalHWImg8812A_FW.o\ hal/OUTSRC/$(RTL871X)/HalHWImg8812A_MAC.o\ hal/OUTSRC/$(RTL871X)/HalHWImg8812A_BB.o\ hal/OUTSRC/$(RTL871X)/HalHWImg8812A_RF.o\ hal/OUTSRC/$(RTL871X)/HalHWImg8812A_TestChip_FW.o\ hal/OUTSRC/$(RTL871X)/HalHWImg8812A_TestChip_MAC.o\ hal/OUTSRC/$(RTL871X)/HalHWImg8812A_TestChip_BB.o\ hal/OUTSRC/$(RTL871X)/HalHWImg8812A_TestChip_RF.o\ hal/OUTSRC/$(RTL871X)/HalPhyRf_8812A.o\ hal/OUTSRC/$(RTL871X)/odm_RegConfig8812A.o\ hal/OUTSRC/$(RTL871X)/odm_RTL8812A.o endif ifeq ($(CONFIG_RTL8821A), y) ifeq ($(CONFIG_RTL8812A), n) RTL871X = rtl8821a ifeq ($(CONFIG_USB_HCI), y) MODULE_NAME := 8821au endif ifeq ($(CONFIG_PCI_HCI), y) MODULE_NAME := 8821ae endif ifeq ($(CONFIG_SDIO_HCI), y) MODULE_NAME := 8821as endif endif EXTRA_CFLAGS += -DCONFIG_RTL8821A _OUTSRC_FILES += hal/OUTSRC/rtl8821a/HalHWImg8821A_FW.o\ hal/OUTSRC/rtl8821a/HalHWImg8821A_MAC.o\ hal/OUTSRC/rtl8821a/HalHWImg8821A_BB.o\ hal/OUTSRC/rtl8821a/HalHWImg8821A_RF.o\ hal/OUTSRC/rtl8821a/HalHWImg8821A_TestChip_MAC.o\ hal/OUTSRC/rtl8821a/HalHWImg8821A_TestChip_BB.o\ hal/OUTSRC/rtl8821a/HalHWImg8821A_TestChip_RF.o\ hal/OUTSRC/rtl8812a/HalPhyRf_8812A.o\ hal/OUTSRC/rtl8821a/HalPhyRf_8821A.o\ hal/OUTSRC/rtl8821a/odm_RegConfig8821A.o\ hal/OUTSRC/rtl8821a/odm_RTL8821A.o endif endif ########### HAL_RTL8723B ################################# ifeq ($(CONFIG_RTL8723B), y) RTL871X = rtl8723b ifeq ($(CONFIG_USB_HCI), y) MODULE_NAME = 8723bu endif ifeq ($(CONFIG_PCI_HCI), y) MODULE_NAME = 8723be endif ifeq ($(CONFIG_SDIO_HCI), y) MODULE_NAME = 8723bs endif EXTRA_CFLAGS += -DCONFIG_RTL8723B _HAL_INTFS_FILES += hal/HalPwrSeqCmd.o \ hal/$(RTL871X)/Hal8723BPwrSeq.o\ hal/$(RTL871X)/$(RTL871X)_sreset.o _HAL_INTFS_FILES += hal/$(RTL871X)/$(RTL871X)_hal_init.o \ hal/$(RTL871X)/$(RTL871X)_phycfg.o \ hal/$(RTL871X)/$(RTL871X)_rf6052.o \ hal/$(RTL871X)/$(RTL871X)_dm.o \ hal/$(RTL871X)/$(RTL871X)_rxdesc.o \ hal/$(RTL871X)/$(RTL871X)_cmd.o \ _HAL_INTFS_FILES += \ hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_halinit.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_led.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_xmit.o \ hal/$(RTL871X)/$(HCI_NAME)/rtl$(MODULE_NAME)_recv.o ifeq ($(CONFIG_PCI_HCI), y) _HAL_INTFS_FILES += hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_ops_linux.o else _HAL_INTFS_FILES += hal/$(RTL871X)/$(HCI_NAME)/$(HCI_NAME)_ops.o endif ifeq ($(CONFIG_MP_INCLUDED), y) _HAL_INTFS_FILES += hal/$(RTL871X)/$(RTL871X)_mp.o endif _OUTSRC_FILES += hal/OUTSRC/$(RTL871X)/HalHWImg8723B_BB.o\ hal/OUTSRC/$(RTL871X)/HalHWImg8723B_MAC.o\ hal/OUTSRC/$(RTL871X)/HalHWImg8723B_RF.o\ hal/OUTSRC/$(RTL871X)/HalHWImg8723B_FW.o\ hal/OUTSRC/$(RTL871X)/HalHWImg8723B_MP.o\ hal/OUTSRC/$(RTL871X)/odm_RegConfig8723B.o\ hal/OUTSRC/$(RTL871X)/HalPhyRf_8723B.o\ hal/OUTSRC/$(RTL871X)/odm_RTL8723B.o endif ########### AUTO_CFG ################################# ifeq ($(CONFIG_AUTOCFG_CP), y) ifeq ($(CONFIG_MULTIDRV), y) $(shell cp $(TopDIR)/autoconf_multidrv_$(HCI_NAME)_linux.h $(TopDIR)/include/autoconf.h) else ifeq ($(CONFIG_RTL8188E)$(CONFIG_SDIO_HCI),yy) $(shell cp $(TopDIR)/autoconf_rtl8189e_$(HCI_NAME)_linux.h $(TopDIR)/include/autoconf.h) else $(shell cp $(TopDIR)/autoconf_$(RTL871X)_$(HCI_NAME)_linux.h $(TopDIR)/include/autoconf.h) endif endif endif ########### END OF PATH ################################# ifeq ($(CONFIG_USB_HCI), y) ifeq ($(CONFIG_USB_AUTOSUSPEND), y) EXTRA_CFLAGS += -DCONFIG_USB_AUTOSUSPEND endif endif ifeq ($(CONFIG_MP_INCLUDED), y) #MODULE_NAME := $(MODULE_NAME)_mp EXTRA_CFLAGS += -DCONFIG_MP_INCLUDED endif ifeq ($(CONFIG_POWER_SAVING), y) EXTRA_CFLAGS += -DCONFIG_POWER_SAVING endif ifeq ($(CONFIG_HW_PWRP_DETECTION), y) EXTRA_CFLAGS += -DCONFIG_HW_PWRP_DETECTION endif ifeq ($(CONFIG_WIFI_TEST), y) EXTRA_CFLAGS += -DCONFIG_WIFI_TEST endif ifeq ($(CONFIG_BT_COEXIST), y) EXTRA_CFLAGS += -DCONFIG_BT_COEXIST endif ifeq ($(CONFIG_RTL8192CU_REDEFINE_1X1), y) EXTRA_CFLAGS += -DRTL8192C_RECONFIG_TO_1T1R endif ifeq ($(CONFIG_INTEL_WIDI), y) EXTRA_CFLAGS += -DCONFIG_INTEL_WIDI endif ifeq ($(CONFIG_WAPI_SUPPORT), y) EXTRA_CFLAGS += -DCONFIG_WAPI_SUPPORT endif ifeq ($(CONFIG_EFUSE_CONFIG_FILE), y) EXTRA_CFLAGS += -DCONFIG_EFUSE_CONFIG_FILE endif ifeq ($(CONFIG_EXT_CLK), y) EXTRA_CFLAGS += -DCONFIG_EXT_CLK endif ifeq ($(CONFIG_TRAFFIC_PROTECT), y) EXTRA_CFLAGS += -DCONFIG_TRAFFIC_PROTECT endif ifeq ($(CONFIG_LOAD_PHY_PARA_FROM_FILE), y) EXTRA_CFLAGS += -DCONFIG_LOAD_PHY_PARA_FROM_FILE endif ifeq ($(CONFIG_CALIBRATE_TX_POWER_BY_REGULATORY), y) EXTRA_CFLAGS += -DCONFIG_CALIBRATE_TX_POWER_BY_REGULATORY endif ifeq ($(CONFIG_CALIBRATE_TX_POWER_TO_MAX), y) EXTRA_CFLAGS += -DCONFIG_CALIBRATE_TX_POWER_TO_MAX endif ifeq ($(CONFIG_ODM_ADAPTIVITY), y) EXTRA_CFLAGS += -DCONFIG_ODM_ADAPTIVITY endif ifeq ($(CONFIG_WOWLAN), y) EXTRA_CFLAGS += -DCONFIG_WOWLAN ifeq ($(CONFIG_SDIO_HCI), y) EXTRA_CFLAGS += -DCONFIG_RTW_SDIO_PM_KEEP_POWER endif endif ifeq ($(CONFIG_AP_WOWLAN), y) EXTRA_CFLAGS += -DCONFIG_AP_WOWLAN ifeq ($(CONFIG_SDIO_HCI), y) EXTRA_CFLAGS += -DCONFIG_RTW_SDIO_PM_KEEP_POWER endif endif ifeq ($(CONFIG_PNO_SUPPORT), y) EXTRA_CFLAGS += -DCONFIG_PNO_SUPPORT ifeq ($(CONFIG_PNO_SET_DEBUG), y) EXTRA_CFLAGS += -DCONFIG_PNO_SET_DEBUG endif endif ifeq ($(CONFIG_GPIO_WAKEUP), y) EXTRA_CFLAGS += -DCONFIG_GPIO_WAKEUP endif ifeq ($(CONFIG_RTW_SDIO_PM_KEEP_POWER), y) ifeq ($(CONFIG_SDIO_HCI), y) EXTRA_CFLAGS += -DCONFIG_RTW_SDIO_PM_KEEP_POWER endif endif ifeq ($(CONFIG_PLATFORM_I386_PC), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN SUBARCH := $(shell uname -m | sed -e s/i.86/i386/) ARCH ?= $(SUBARCH) CROSS_COMPILE ?= KVER := $(shell uname -r) KSRC := /lib/modules/$(KVER)/build MODDESTDIR := /lib/modules/$(KVER)/kernel/drivers/net/wireless/ INSTALL_PREFIX := endif ifeq ($(CONFIG_PLATFORM_ACTIONS_ATM702X), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN -DCONFIG_PLATFORM_ANDROID -DCONFIG_PLATFORM_ACTIONS_ATM702X #ARCH := arm ARCH := $(R_ARCH) #CROSS_COMPILE := arm-none-linux-gnueabi- CROSS_COMPILE := $(R_CROSS_COMPILE) KVER:= 3.4.0 #KSRC := ../../../../build/out/kernel KSRC := $(KERNEL_BUILD_PATH) MODULE_NAME :=wlan endif ifeq ($(CONFIG_PLATFORM_TI_AM3517), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN -DCONFIG_PLATFORM_ANDROID -DCONFIG_PLATFORM_SHUTTLE CROSS_COMPILE := arm-eabi- KSRC := $(shell pwd)/../../../Android/kernel ARCH := arm endif ifeq ($(CONFIG_PLATFORM_MSTAR_TITANIA12), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN -DCONFIG_PLATFORM_MSTAR -DCONFIG_PLATFORM_MSTAR_TITANIA12 ARCH:=mips CROSS_COMPILE:= /usr/src/Mstar_kernel/mips-4.3/bin/mips-linux-gnu- KVER:= 2.6.28.9 KSRC:= /usr/src/Mstar_kernel/2.6.28.9/ endif ifeq ($(CONFIG_PLATFORM_MSTAR), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN -DCONFIG_PLATFORM_MSTAR #-DCONFIG_PLATFORM_MSTAR_SCAN_BEFORE_CONNECT ARCH:=arm CROSS_COMPILE:= /usr/src/bin/arm-none-linux-gnueabi- KVER:= 3.1.10 KSRC:= /usr/src/Mstar_kernel/3.1.10/ endif ifeq ($(CONFIG_PLATFORM_ANDROID_X86), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN SUBARCH := $(shell uname -m | sed -e s/i.86/i386/) ARCH := $(SUBARCH) CROSS_COMPILE := /media/DATA-2/android-x86/ics-x86_20120130/prebuilt/linux-x86/toolchain/i686-unknown-linux-gnu-4.2.1/bin/i686-unknown-linux-gnu- KSRC := /media/DATA-2/android-x86/ics-x86_20120130/out/target/product/generic_x86/obj/kernel MODULE_NAME :=wlan endif ifeq ($(CONFIG_PLATFORM_JB_X86), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN EXTRA_CFLAGS += -DCONFIG_CONCURRENT_MODE EXTRA_CFLAGS += -DCONFIG_IOCTL_CFG80211 -DRTW_USE_CFG80211_STA_EVENT EXTRA_CFLAGS += -DCONFIG_P2P_IPS SUBARCH := $(shell uname -m | sed -e s/i.86/i386/) ARCH := $(SUBARCH) CROSS_COMPILE := /home/android_sdk/android-x86_JB/prebuilts/gcc/linux-x86/x86/i686-linux-android-4.7/bin/i686-linux-android- KSRC := /home/android_sdk/android-x86_JB/out/target/product/x86/obj/kernel/ MODULE_NAME :=wlan endif ifeq ($(CONFIG_PLATFORM_ARM_PXA2XX), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN ARCH := arm CROSS_COMPILE := arm-none-linux-gnueabi- KVER := 2.6.34.1 KSRC ?= /usr/src/linux-2.6.34.1 endif ifeq ($(CONFIG_PLATFORM_ARM_S3C2K4), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN ARCH := arm CROSS_COMPILE := arm-linux- KVER := 2.6.24.7_$(ARCH) KSRC := /usr/src/kernels/linux-$(KVER) endif ifeq ($(CONFIG_PLATFORM_ARM_S3C6K4), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN ARCH := arm CROSS_COMPILE := arm-none-linux-gnueabi- KVER := 2.6.34.1 KSRC ?= /usr/src/linux-2.6.34.1 endif ifeq ($(CONFIG_PLATFORM_RTD2880B), y) EXTRA_CFLAGS += -DCONFIG_BIG_ENDIAN -DCONFIG_PLATFORM_RTD2880B ARCH:= CROSS_COMPILE:= KVER:= KSRC:= endif ifeq ($(CONFIG_PLATFORM_MIPS_RMI), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN ARCH:=mips CROSS_COMPILE:=mipsisa32r2-uclibc- KVER:= KSRC:= /root/work/kernel_realtek endif ifeq ($(CONFIG_PLATFORM_MIPS_PLM), y) EXTRA_CFLAGS += -DCONFIG_BIG_ENDIAN ARCH:=mips CROSS_COMPILE:=mipsisa32r2-uclibc- KVER:= KSRC:= /root/work/kernel_realtek endif ifeq ($(CONFIG_PLATFORM_MSTAR389), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN -DCONFIG_PLATFORM_MSTAR389 ARCH:=mips CROSS_COMPILE:= mips-linux-gnu- KVER:= 2.6.28.10 KSRC:= /home/mstar/mstar_linux/2.6.28.9/ endif ifeq ($(CONFIG_PLATFORM_MIPS_AR9132), y) EXTRA_CFLAGS += -DCONFIG_BIG_ENDIAN ARCH := mips CROSS_COMPILE := mips-openwrt-linux- KSRC := /home/alex/test_openwrt/tmp/linux-2.6.30.9 endif ifeq ($(CONFIG_PLATFORM_DMP_PHILIPS), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN -DRTK_DMP_PLATFORM ARCH := mips #CROSS_COMPILE:=/usr/local/msdk-4.3.6-mips-EL-2.6.12.6-0.9.30.3/bin/mipsel-linux- CROSS_COMPILE:=/usr/local/toolchain_mipsel/bin/mipsel-linux- KSRC ?=/usr/local/Jupiter/linux-2.6.12 endif ifeq ($(CONFIG_PLATFORM_RTK_DMP), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN -DRTK_DMP_PLATFORM -DCONFIG_WIRELESS_EXT EXTRA_CFLAGS += -DCONFIG_PLATFORM_OPS ifeq ($(CONFIG_USB_HCI), y) _PLATFORM_FILES += platform/platform_RTK_DMP_usb.o endif ARCH:=mips CROSS_COMPILE:=mipsel-linux- KVER:= KSRC ?= /usr/src/DMP_Kernel/jupiter/linux-2.6.12 endif ifeq ($(CONFIG_PLATFORM_MT53XX), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN -DCONFIG_PLATFORM_MT53XX ARCH:= arm CROSS_COMPILE:= arm11_mtk_le- KVER:= 2.6.27 KSRC?= /proj/mtk00802/BD_Compare/BDP/Dev/BDP_V301/BDP_Linux/linux-2.6.27 endif ifeq ($(CONFIG_PLATFORM_ARM_MX51_241H), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN -DCONFIG_WISTRON_PLATFORM ARCH := arm CROSS_COMPILE := /opt/freescale/usr/local/gcc-4.1.2-glibc-2.5-nptl-3/arm-none-linux-gnueabi/bin/arm-none-linux-gnueabi- KVER := 2.6.31 KSRC ?= /lib/modules/2.6.31-770-g0e46b52/source endif ifeq ($(CONFIG_PLATFORM_FS_MX61), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN ARCH := arm CROSS_COMPILE := /home/share/CusEnv/FreeScale/arm-eabi-4.4.3/bin/arm-eabi- KSRC ?= /home/share/CusEnv/FreeScale/FS_kernel_env endif ifeq ($(CONFIG_PLATFORM_ACTIONS_ATJ227X), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN -DCONFIG_PLATFORM_ACTIONS_ATJ227X ARCH := mips CROSS_COMPILE := /home/cnsd4/project/actions/tools-2.6.27/bin/mipsel-linux-gnu- KVER := 2.6.27 KSRC := /home/cnsd4/project/actions/linux-2.6.27.28 endif ifeq ($(CONFIG_PLATFORM_TI_DM365), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN -DCONFIG_PLATFORM_TI_DM365 ARCH := arm CROSS_COMPILE := /home/cnsd4/Appro/mv_pro_5.0/montavista/pro/devkit/arm/v5t_le/bin/arm_v5t_le- KVER := 2.6.18 KSRC := /home/cnsd4/Appro/mv_pro_5.0/montavista/pro/devkit/lsp/ti-davinci/linux-dm365 endif ifeq ($(CONFIG_PLATFORM_TEGRA3_CARDHU), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN # default setting for Android 4.1, 4.2 EXTRA_CFLAGS += -DRTW_ENABLE_WIFI_CONTROL_FUNC EXTRA_CFLAGS += -DCONFIG_CONCURRENT_MODE EXTRA_CFLAGS += -DCONFIG_IOCTL_CFG80211 -DRTW_USE_CFG80211_STA_EVENT EXTRA_CFLAGS += -DCONFIG_P2P_IPS ARCH := arm CROSS_COMPILE := /home/android_sdk/nvidia/tegra-16r3-partner-android-4.1_20120723/prebuilt/linux-x86/toolchain/arm-eabi-4.4.3/bin/arm-eabi- KSRC := /home/android_sdk/nvidia/tegra-16r3-partner-android-4.1_20120723/out/target/product/cardhu/obj/KERNEL MODULE_NAME := wlan endif ifeq ($(CONFIG_PLATFORM_TEGRA4_DALMORE), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN # default setting for Android 4.1, 4.2 EXTRA_CFLAGS += -DRTW_ENABLE_WIFI_CONTROL_FUNC EXTRA_CFLAGS += -DCONFIG_CONCURRENT_MODE EXTRA_CFLAGS += -DCONFIG_IOCTL_CFG80211 -DRTW_USE_CFG80211_STA_EVENT EXTRA_CFLAGS += -DCONFIG_P2P_IPS ARCH := arm CROSS_COMPILE := /home/android_sdk/nvidia/tegra-17r9-partner-android-4.2-dalmore_20130131/prebuilts/gcc/linux-x86/arm/arm-eabi-4.6/bin/arm-eabi- KSRC := /home/android_sdk/nvidia/tegra-17r9-partner-android-4.2-dalmore_20130131/out/target/product/dalmore/obj/KERNEL MODULE_NAME := wlan endif ifeq ($(CONFIG_PLATFORM_ARM_TCC8900), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN ARCH := arm CROSS_COMPILE := /home/android_sdk/Telechips/SDK_2304_20110613/prebuilt/linux-x86/toolchain/arm-eabi-4.4.3/bin/arm-eabi- KSRC := /home/android_sdk/Telechips/SDK_2304_20110613/kernel MODULE_NAME := wlan endif ifeq ($(CONFIG_PLATFORM_ARM_TCC8920), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN ARCH := arm CROSS_COMPILE := /home/android_sdk/Telechips/v12.06_r1-tcc-android-4.0.4/prebuilt/linux-x86/toolchain/arm-eabi-4.4.3/bin/arm-eabi- KSRC := /home/android_sdk/Telechips/v12.06_r1-tcc-android-4.0.4/kernel MODULE_NAME := wlan endif ifeq ($(CONFIG_PLATFORM_ARM_TCC8920_JB42), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN # default setting for Android 4.1, 4.2 EXTRA_CFLAGS += -DCONFIG_CONCURRENT_MODE EXTRA_CFLAGS += -DCONFIG_IOCTL_CFG80211 -DRTW_USE_CFG80211_STA_EVENT EXTRA_CFLAGS += -DCONFIG_P2P_IPS ARCH := arm CROSS_COMPILE := /home/android_sdk/Telechips/v13.03_r1-tcc-android-4.2.2_ds_patched/prebuilts/gcc/linux-x86/arm/arm-eabi-4.6/bin/arm-eabi- KSRC := /home/android_sdk/Telechips/v13.03_r1-tcc-android-4.2.2_ds_patched/kernel MODULE_NAME := wlan endif ifeq ($(CONFIG_PLATFORM_ARM_RK2818), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN -DCONFIG_PLATFORM_ANDROID -DCONFIG_PLATFORM_ROCKCHIPS -DCONFIG_MINIMAL_MEMORY_USAGE ARCH := arm CROSS_COMPILE := /usr/src/release_fae_version/toolchain/arm-eabi-4.4.0/bin/arm-eabi- KSRC := /usr/src/release_fae_version/kernel25_A7_281x MODULE_NAME := wlan endif ifeq ($(CONFIG_PLATFORM_ARM_RK3188), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN -DCONFIG_PLATFORM_ANDROID -DCONFIG_PLATFORM_ROCKCHIPS -DCONFIG_MINIMAL_MEMORY_USAGE EXTRA_CFLAGS += -DRTW_ENABLE_WIFI_CONTROL_FUNC EXTRA_CFLAGS += -DRTW_SUPPORT_PLATFORM_SHUTDOWN EXTRA_CFLAGS += -DRTW_USE_CFG80211_STA_EVENT ARCH := arm CROSS_COMPILE := /home/android_sdk/Rockchip/Rk3188/prebuilts/gcc/linux-x86/arm/arm-eabi-4.6/bin/arm-eabi- KSRC := /home/android_sdk/Rockchip/Rk3188/kernel MODULE_NAME := wlan endif ifeq ($(CONFIG_PLATFORM_ARM_RK3066), y) EXTRA_CFLAGS += -DRTW_ENABLE_WIFI_CONTROL_FUNC EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN EXTRA_CFLAGS += -DCONFIG_CONCURRENT_MODE EXTRA_CFLAGS += -DCONFIG_IOCTL_CFG80211 EXTRA_CFLAGS += -DCONFIG_P2P_IPS ifeq ($(CONFIG_SDIO_HCI), y) EXTRA_CFLAGS += -DRTW_SUPPORT_PLATFORM_SHUTDOWN endif EXTRA_CFLAGS += -fno-pic ARCH := arm CROSS_COMPILE := /home/android_sdk/Rockchip/rk3066_20130607/prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.6/bin/arm-linux-androideabi- #CROSS_COMPILE := /home/android_sdk/Rockchip/Rk3066sdk/prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.6/bin/arm-linux-androideabi- KSRC := /home/android_sdk/Rockchip/Rk3066sdk/kernel MODULE_NAME :=wlan endif ifeq ($(CONFIG_PLATFORM_ARM_URBETTER), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN #-DCONFIG_MINIMAL_MEMORY_USAGE ARCH := arm CROSS_COMPILE := /media/DATA-1/urbetter/arm-2009q3/bin/arm-none-linux-gnueabi- KSRC := /media/DATA-1/urbetter/ics-urbetter/kernel MODULE_NAME := wlan endif ifeq ($(CONFIG_PLATFORM_ARM_TI_PANDA), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN #-DCONFIG_MINIMAL_MEMORY_USAGE ARCH := arm #CROSS_COMPILE := /media/DATA-1/aosp/ics-aosp_20111227/prebuilt/linux-x86/toolchain/arm-eabi-4.4.3/bin/arm-eabi- #KSRC := /media/DATA-1/aosp/android-omap-panda-3.0_20120104 CROSS_COMPILE := /media/DATA-1/android-4.0/prebuilt/linux-x86/toolchain/arm-eabi-4.4.3/bin/arm-eabi- KSRC := /media/DATA-1/android-4.0/panda_kernel/omap MODULE_NAME := wlan endif ifeq ($(CONFIG_PLATFORM_MIPS_JZ4760), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN -DCONFIG_MINIMAL_MEMORY_USAGE ARCH ?= mips CROSS_COMPILE ?= /mnt/sdb5/Ingenic/Umido/mips-4.3/bin/mips-linux-gnu- KSRC ?= /mnt/sdb5/Ingenic/Umido/kernel endif ifeq ($(CONFIG_PLATFORM_SZEBOOK), y) EXTRA_CFLAGS += -DCONFIG_BIG_ENDIAN ARCH:=arm CROSS_COMPILE:=/opt/crosstool2/bin/armeb-unknown-linux-gnueabi- KVER:= 2.6.31.6 KSRC:= ../code/linux-2.6.31.6-2020/ endif #Add setting for MN10300 ifeq ($(CONFIG_PLATFORM_MN10300), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN -DCONFIG_PLATFORM_MN10300 ARCH := mn10300 CROSS_COMPILE := mn10300-linux- KVER := 2.6.32.2 KSRC := /home/winuser/work/Plat_sLD2T_V3010/usr/src/linux-2.6.32.2 INSTALL_PREFIX := endif ifeq ($(CONFIG_PLATFORM_ARM_SUNxI), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN EXTRA_CFLAGS += -DCONFIG_PLATFORM_ARM_SUNxI # default setting for Android 4.1, 4.2 EXTRA_CFLAGS += -DCONFIG_CONCURRENT_MODE EXTRA_CFLAGS += -DCONFIG_IOCTL_CFG80211 -DRTW_USE_CFG80211_STA_EVENT EXTRA_CFLAGS += -DDCONFIG_P2P_IPS EXTRA_CFLAGS += -DCONFIG_PLATFORM_OPS ifeq ($(CONFIG_USB_HCI), y) EXTRA_CFLAGS += -DCONFIG_USE_USB_BUFFER_ALLOC_TX _PLATFORM_FILES += platform/platform_ARM_SUNxI_usb.o endif ifeq ($(CONFIG_SDIO_HCI), y) # default setting for A10-EVB mmc0 #EXTRA_CFLAGS += -DCONFIG_WITS_EVB_V13 _PLATFORM_FILES += platform/platform_ARM_SUNxI_sdio.o endif ARCH := arm #CROSS_COMPILE := arm-none-linux-gnueabi- CROSS_COMPILE=/home/android_sdk/Allwinner/a10/android-jb42/lichee-jb42/buildroot/output/external-toolchain/bin/arm-none-linux-gnueabi- KVER := 3.0.8 #KSRC:= ../lichee/linux-3.0/ KSRC=/home/android_sdk/Allwinner/a10/android-jb42/lichee-jb42/linux-3.0 endif ifeq ($(CONFIG_PLATFORM_ARM_SUN6I), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN EXTRA_CFLAGS += -DCONFIG_PLATFORM_ARM_SUN6I EXTRA_CFLAGS += -DCONFIG_TRAFFIC_PROTECT # default setting for Android 4.1, 4.2, 4.3, 4.4 EXTRA_CFLAGS += -DCONFIG_CONCURRENT_MODE EXTRA_CFLAGS += -DCONFIG_IOCTL_CFG80211 -DRTW_USE_CFG80211_STA_EVENT EXTRA_CFLAGS += -DCONFIG_P2P_IPS -DCONFIG_QOS_OPTIMIZATION EXTRA_CFLAGS += -DCONFIG_PLATFORM_OPS ifeq ($(CONFIG_USB_HCI), y) EXTRA_CFLAGS += -DCONFIG_USE_USB_BUFFER_ALLOC_TX _PLATFORM_FILES += platform/platform_ARM_SUNxI_usb.o endif ifeq ($(CONFIG_SDIO_HCI), y) # default setting for A31-EVB mmc0 EXTRA_CFLAGS += -DCONFIG_A31_EVB _PLATFORM_FILES += platform/platform_ARM_SUNnI_sdio.o endif ARCH := arm #Android-JB42 #CROSS_COMPILE := /home/android_sdk/Allwinner/a31/android-jb42/lichee/buildroot/output/external-toolchain/bin/arm-linux-gnueabi- #KSRC :=/home/android_sdk/Allwinner/a31/android-jb42/lichee/linux-3.3 #ifeq ($(CONFIG_USB_HCI), y) #MODULE_NAME := 8188eu_sw #endif # ==== Cross compile setting for kitkat-a3x_v4.5 ===== CROSS_COMPILE := /home/android_sdk/Allwinner/a31/kitkat-a3x_v4.5/lichee/buildroot/output/external-toolchain/bin/arm-linux-gnueabi- KSRC :=/home/android_sdk/Allwinner/a31/kitkat-a3x_v4.5/lichee/linux-3.3 endif ifeq ($(CONFIG_PLATFORM_ARM_SUN7I), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN EXTRA_CFLAGS += -DCONFIG_PLATFORM_ARM_SUN7I EXTRA_CFLAGS += -DCONFIG_TRAFFIC_PROTECT # default setting for Android 4.1, 4.2, 4.3, 4.4 EXTRA_CFLAGS += -DCONFIG_CONCURRENT_MODE EXTRA_CFLAGS += -DCONFIG_IOCTL_CFG80211 -DRTW_USE_CFG80211_STA_EVENT EXTRA_CFLAGS += -DCONFIG_P2P_IPS -DCONFIG_QOS_OPTIMIZATION EXTRA_CFLAGS += -DCONFIG_PLATFORM_OPS ifeq ($(CONFIG_USB_HCI), y) EXTRA_CFLAGS += -DCONFIG_USE_USB_BUFFER_ALLOC_TX _PLATFORM_FILES += platform/platform_ARM_SUNxI_usb.o endif ifeq ($(CONFIG_SDIO_HCI), y) _PLATFORM_FILES += platform/platform_ARM_SUNnI_sdio.o endif ARCH := arm # ===Cross compile setting for Android 4.2 SDK === #CROSS_COMPILE := /home/android_sdk/Allwinner/a20_evb/lichee/out/android/common/buildroot/external-toolchain/bin/arm-linux-gnueabi- #KSRC := /home/android_sdk/Allwinner/a20_evb/lichee/linux-3.3 # ==== Cross compile setting for Android 4.3 SDK ===== #CROSS_COMPILE := /home/android_sdk/Allwinner/a20/android-jb43/lichee/out/android/common/buildroot/external-toolchain/bin/arm-linux-gnueabi- #KSRC := /home/android_sdk/Allwinner/a20/android-jb43/lichee/linux-3.4 # ==== Cross compile setting for kitkat-a20_v4.4 ===== CROSS_COMPILE := /home/android_sdk/Allwinner/a20/kitkat-a20_v4.4/lichee/out/android/common/buildroot/external-toolchain/bin/arm-linux-gnueabi- KSRC := /home/android_sdk/Allwinner/a20/kitkat-a20_v4.4/lichee/linux-3.4 endif ifeq ($(CONFIG_PLATFORM_ARM_SUN8I), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN EXTRA_CFLAGS += -DCONFIG_PLATFORM_ARM_SUN8I EXTRA_CFLAGS += -DCONFIG_TRAFFIC_PROTECT # default setting for Android 4.1, 4.2 EXTRA_CFLAGS += -DCONFIG_CONCURRENT_MODE EXTRA_CFLAGS += -DCONFIG_IOCTL_CFG80211 -DRTW_USE_CFG80211_STA_EVENT EXTRA_CFLAGS += -DCONFIG_P2P_IPS EXTRA_CFLAGS += -DCONFIG_PLATFORM_OPS ifeq ($(CONFIG_USB_HCI), y) EXTRA_CFLAGS += -DCONFIG_USE_USB_BUFFER_ALLOC_TX _PLATFORM_FILES += platform/platform_ARM_SUNxI_usb.o endif ifeq ($(CONFIG_SDIO_HCI), y) _PLATFORM_FILES += platform/platform_ARM_SUNnI_sdio.o endif ARCH := arm CROSS_COMPILE := /home/android_sdk/Allwinner/a23/android-jb42/lichee/out/android/common/buildroot/external-toolchain/bin/arm-linux-gnueabi- KVER := 3.4.39 KSRC :=/home/android_sdk/Allwinner/a23/android-jb42/lichee/linux-3.4 endif ifeq ($(CONFIG_PLATFORM_ACTIONS_ATV5201), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN -DCONFIG_PLATFORM_ACTIONS_ATV5201 ARCH := mips CROSS_COMPILE := mipsel-linux-gnu- KVER := $(KERNEL_VER) KSRC:= $(CFGDIR)/../../kernel/linux-$(KERNEL_VER) endif ifeq ($(CONFIG_PLATFORM_ARM_RTD299X), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN -DUSB_XMITBUF_ALIGN_SZ=1024 -DUSB_PACKET_OFFSET_SZ=0 #ARCH, CROSS_COMPILE, KSRC,and MODDESTDIR are provided by external makefile INSTALL_PREFIX := endif # Platfrom setting ifeq ($(CONFIG_PLATFORM_ARM_SPREADTRUM_6820), y) ifeq ($(CONFIG_ANDROID_2X), y) EXTRA_CFLAGS += -DANDROID_2X endif EXTRA_CFLAGS += -DCONFIG_PLATFORM_SPRD EXTRA_CFLAGS += -DPLATFORM_SPREADTRUM_6820 EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN ifeq ($(RTL871X), rtl8188e) EXTRA_CFLAGS += -DSOFTAP_PS_DURATION=50 endif ifeq ($(CONFIG_SDIO_HCI), y) EXTRA_CFLAGS += -DCONFIG_PLATFORM_OPS _PLATFORM_FILES += platform/platform_sprd_sdio.o endif endif ifeq ($(CONFIG_PLATFORM_ARM_SPREADTRUM_8810), y) ifeq ($(CONFIG_ANDROID_2X), y) EXTRA_CFLAGS += -DANDROID_2X endif EXTRA_CFLAGS += -DCONFIG_PLATFORM_SPRD EXTRA_CFLAGS += -DPLATFORM_SPREADTRUM_8810 EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN ifeq ($(RTL871X), rtl8188e) EXTRA_CFLAGS += -DSOFTAP_PS_DURATION=50 endif ifeq ($(CONFIG_SDIO_HCI), y) EXTRA_CFLAGS += -DCONFIG_PLATFORM_OPS _PLATFORM_FILES += platform/platform_sprd_sdio.o endif endif ifeq ($(CONFIG_MULTIDRV), y) ifeq ($(CONFIG_SDIO_HCI), y) MODULE_NAME := rtw_sdio endif ifeq ($(CONFIG_USB_HCI), y) MODULE_NAME := rtw_usb endif ifeq ($(CONFIG_PCI_HCI), y) MODULE_NAME := rtw_pci endif endif ifeq ($(CONFIG_PLATFORM_AML), y) EXTRA_CFLAGS += -DCONFIG_LITTLE_ENDIAN ARCH := arm CROSS_COMPILE := arm-none-linux-gnueabi- KSRC := endif ifneq ($(USER_MODULE_NAME),) MODULE_NAME := $(USER_MODULE_NAME) endif ifneq ($(KERNELRELEASE),) rtk_core := core/rtw_cmd.o \ core/rtw_security.o \ core/rtw_debug.o \ core/rtw_io.o \ core/rtw_ioctl_query.o \ core/rtw_ioctl_set.o \ core/rtw_ieee80211.o \ core/rtw_mlme.o \ core/rtw_mlme_ext.o \ core/rtw_wlan_util.o \ core/rtw_vht.o \ core/rtw_pwrctrl.o \ core/rtw_rf.o \ core/rtw_recv.o \ core/rtw_sta_mgt.o \ core/rtw_ap.o \ core/rtw_xmit.o \ core/rtw_p2p.o \ core/rtw_tdls.o \ core/rtw_br_ext.o \ core/rtw_iol.o \ core/rtw_sreset.o \ core/rtw_btcoex.o \ core/rtw_beamforming.o \ core/rtw_odm.o \ core/efuse/rtw_efuse.o $(MODULE_NAME)-y += $(rtk_core) $(MODULE_NAME)-$(CONFIG_INTEL_WIDI) += core/rtw_intel_widi.o $(MODULE_NAME)-$(CONFIG_WAPI_SUPPORT) += core/rtw_wapi.o \ core/rtw_wapi_sms4.o $(MODULE_NAME)-y += $(_OS_INTFS_FILES) $(MODULE_NAME)-y += $(_HAL_INTFS_FILES) $(MODULE_NAME)-y += $(_OUTSRC_FILES) $(MODULE_NAME)-y += $(_PLATFORM_FILES) $(MODULE_NAME)-$(CONFIG_MP_INCLUDED) += core/rtw_mp.o \ core/rtw_mp_ioctl.o ifeq ($(CONFIG_RTL8723A), y) $(MODULE_NAME)-$(CONFIG_MP_INCLUDED)+= core/rtw_bt_mp.o endif ifeq ($(CONFIG_RTL8723B), y) $(MODULE_NAME)-$(CONFIG_MP_INCLUDED)+= core/rtw_bt_mp.o endif ifeq ($(CONFIG_RTL8821A), y) $(MODULE_NAME)-$(CONFIG_MP_INCLUDED)+= core/rtw_bt_mp.o endif obj-$(CONFIG_RTL8188EU_SDK) := $(MODULE_NAME).o else export CONFIG_RTL8188EU_SDK = m all: modules modules: $(MAKE) ARCH=$(ARCH) CROSS_COMPILE=$(CROSS_COMPILE) -C $(KSRC) M=$(shell pwd) modules strip: $(CROSS_COMPILE)strip $(MODULE_NAME).ko --strip-unneeded install: install -p -m 644 $(MODULE_NAME).ko $(MODDESTDIR) /sbin/depmod -a ${KVER} uninstall: rm -f $(MODDESTDIR)/$(MODULE_NAME).ko /sbin/depmod -a ${KVER} config_r: @echo "make config" /bin/bash script/Configure script/config.in .PHONY: modules clean clean: cd hal/OUTSRC/ ; rm -fr */*.mod.c */*.mod */*.o */.*.cmd */*.ko cd hal/OUTSRC/ ; rm -fr *.mod.c *.mod *.o .*.cmd *.ko cd hal/led ; rm -fr *.mod.c *.mod *.o .*.cmd *.ko cd hal ; rm -fr */*/*.mod.c */*/*.mod */*/*.o */*/.*.cmd */*/*.ko cd hal ; rm -fr */*.mod.c */*.mod */*.o */.*.cmd */*.ko cd hal ; rm -fr *.mod.c *.mod *.o .*.cmd *.ko cd core/efuse ; rm -fr *.mod.c *.mod *.o .*.cmd *.ko cd core ; rm -fr *.mod.c *.mod *.o .*.cmd *.ko cd os_dep/linux ; rm -fr *.mod.c *.mod *.o .*.cmd *.ko cd os_dep ; rm -fr *.mod.c *.mod *.o .*.cmd *.ko cd platform ; rm -fr *.mod.c *.mod *.o .*.cmd *.ko rm -fr Module.symvers ; rm -fr Module.markers ; rm -fr modules.order rm -fr *.mod.c *.mod *.o .*.cmd *.ko *~ rm -fr .tmp_versions endif
voodik/android_kernel_hardkernel_odroidxu3
drivers/net/wireless/rtl8xxx_EU/Makefile
Makefile
gpl-2.0
40,946
/* Navicat MySQL Data Transfer Source Server : HomeServer Source Server Version : 50621 Source Host : localhost:3306 Source Database : webzoo Target Server Type : MYSQL Target Server Version : 50621 File Encoding : 65001 Date: 2015-05-22 19:49:48 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for animals -- ---------------------------- DROP TABLE IF EXISTS `animals`; CREATE TABLE `animals` ( `id_anim` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `kindId` int(5) unsigned NOT NULL, `comingDate` date NOT NULL, PRIMARY KEY (`id_anim`), KEY `namesIndex` (`name`) USING HASH, KEY `kindId` (`kindId`), CONSTRAINT `kindKey` FOREIGN KEY (`kindId`) REFERENCES `kinds` (`id_kind`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for areals -- ---------------------------- DROP TABLE IF EXISTS `areals`; CREATE TABLE `areals` ( `id_areal` int(5) unsigned NOT NULL AUTO_INCREMENT, `arealName` varchar(255) NOT NULL, `climateId` int(2) unsigned NOT NULL, PRIMARY KEY (`id_areal`), KEY `climateId` (`climateId`), CONSTRAINT `climateId` FOREIGN KEY (`climateId`) REFERENCES `climates` (`id_clim`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for climates -- ---------------------------- DROP TABLE IF EXISTS `climates`; CREATE TABLE `climates` ( `id_clim` int(2) unsigned NOT NULL AUTO_INCREMENT, `climateName` varchar(255) NOT NULL, PRIMARY KEY (`id_clim`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for groups -- ---------------------------- DROP TABLE IF EXISTS `groups`; CREATE TABLE `groups` ( `id_group` int(1) unsigned NOT NULL AUTO_INCREMENT, `nameGroup` varchar(255) NOT NULL, PRIMARY KEY (`id_group`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for kinds -- ---------------------------- DROP TABLE IF EXISTS `kinds`; CREATE TABLE `kinds` ( `id_kind` int(5) unsigned NOT NULL AUTO_INCREMENT, `nameKind` varchar(255) NOT NULL, `groupId` int(1) unsigned NOT NULL, `arealId` int(5) unsigned NOT NULL, PRIMARY KEY (`id_kind`), KEY `arealId` (`arealId`), KEY `groupId` (`groupId`), CONSTRAINT `arealKey` FOREIGN KEY (`arealId`) REFERENCES `areals` (`id_areal`), CONSTRAINT `groupKey` FOREIGN KEY (`groupId`) REFERENCES `groups` (`id_group`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
Rafalem/JavaProjects
WebZoo/src/main/java/ru/nsu/java/db/webzoo.sql
SQL
gpl-2.0
2,719
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>libudev Reference Manual: udev_monitor</title> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="index.html" title="libudev Reference Manual"> <link rel="up" href="ch01.html" title="API Reference"> <link rel="prev" href="libudev-udev-device.html" title="udev_device"> <link rel="next" href="libudev-udev-enumerate.html" title="udev_enumerate"> <meta name="generator" content="GTK-Doc V1.20 (XML mode)"> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table class="navigation" id="top" width="100%" summary="Navigation header" cellpadding="2" cellspacing="10"><tr valign="middle"> <td width="100%" align="left" class="shortcuts"> <a href="#" class="shortcut">Top</a><span id="nav_description"> <span class="dim">|</span>  <a href="#libudev-udev-monitor.description" class="shortcut">Description</a></span><span id="nav_hierarchy"> <span class="dim">|</span>  <a href="#libudev-udev-monitor.object-hierarchy" class="shortcut">Object Hierarchy</a></span> </td> <td><a accesskey="h" href="index.html"><img src="home.png" width="16" height="16" border="0" alt="Home"></a></td> <td><a accesskey="u" href="ch01.html"><img src="up.png" width="16" height="16" border="0" alt="Up"></a></td> <td><a accesskey="p" href="libudev-udev-device.html"><img src="left.png" width="16" height="16" border="0" alt="Prev"></a></td> <td><a accesskey="n" href="libudev-udev-enumerate.html"><img src="right.png" width="16" height="16" border="0" alt="Next"></a></td> </tr></table> <div class="refentry"> <a name="libudev-udev-monitor"></a><div class="titlepage"></div> <div class="refnamediv"><table width="100%"><tr> <td valign="top"> <h2><span class="refentrytitle"><a name="libudev-udev-monitor.top_of_page"></a>udev_monitor</span></h2> <p>udev_monitor — device event source</p> </td> <td class="gallery_image" valign="top" align="right"></td> </tr></table></div> <div class="refsect1"> <a name="libudev-udev-monitor.functions"></a><h2>Functions</h2> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="functions_return"> <col class="functions_name"> </colgroup> <tbody> <tr> <td class="function_type">struct <a class="link" href="libudev-udev-monitor.html#udev-monitor" title="struct udev_monitor"><span class="returnvalue">udev_monitor</span></a> * </td> <td class="function_name"> <a class="link" href="libudev-udev-monitor.html#udev-monitor-ref" title="udev_monitor_ref ()">udev_monitor_ref</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type">struct <a class="link" href="libudev-udev-monitor.html#udev-monitor" title="struct udev_monitor"><span class="returnvalue">udev_monitor</span></a> * </td> <td class="function_name"> <a class="link" href="libudev-udev-monitor.html#udev-monitor-unref" title="udev_monitor_unref ()">udev_monitor_unref</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type">struct <a class="link" href="libudev-udev.html#udev" title="struct udev"><span class="returnvalue">udev</span></a> * </td> <td class="function_name"> <a class="link" href="libudev-udev-monitor.html#udev-monitor-get-udev" title="udev_monitor_get_udev ()">udev_monitor_get_udev</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type">struct <a class="link" href="libudev-udev-monitor.html#udev-monitor" title="struct udev_monitor"><span class="returnvalue">udev_monitor</span></a> * </td> <td class="function_name"> <a class="link" href="libudev-udev-monitor.html#udev-monitor-new-from-netlink" title="udev_monitor_new_from_netlink ()">udev_monitor_new_from_netlink</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">int</span> </td> <td class="function_name"> <a class="link" href="libudev-udev-monitor.html#udev-monitor-enable-receiving" title="udev_monitor_enable_receiving ()">udev_monitor_enable_receiving</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">int</span> </td> <td class="function_name"> <a class="link" href="libudev-udev-monitor.html#udev-monitor-set-receive-buffer-size" title="udev_monitor_set_receive_buffer_size ()">udev_monitor_set_receive_buffer_size</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">int</span> </td> <td class="function_name"> <a class="link" href="libudev-udev-monitor.html#udev-monitor-get-fd" title="udev_monitor_get_fd ()">udev_monitor_get_fd</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type">struct <a class="link" href="libudev-udev-device.html#udev-device" title="struct udev_device"><span class="returnvalue">udev_device</span></a> * </td> <td class="function_name"> <a class="link" href="libudev-udev-monitor.html#udev-monitor-receive-device" title="udev_monitor_receive_device ()">udev_monitor_receive_device</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">int</span> </td> <td class="function_name"> <a class="link" href="libudev-udev-monitor.html#udev-monitor-filter-add-match-subsystem-devtype" title="udev_monitor_filter_add_match_subsystem_devtype ()">udev_monitor_filter_add_match_subsystem_devtype</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">int</span> </td> <td class="function_name"> <a class="link" href="libudev-udev-monitor.html#udev-monitor-filter-add-match-tag" title="udev_monitor_filter_add_match_tag ()">udev_monitor_filter_add_match_tag</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">int</span> </td> <td class="function_name"> <a class="link" href="libudev-udev-monitor.html#udev-monitor-filter-update" title="udev_monitor_filter_update ()">udev_monitor_filter_update</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">int</span> </td> <td class="function_name"> <a class="link" href="libudev-udev-monitor.html#udev-monitor-filter-remove" title="udev_monitor_filter_remove ()">udev_monitor_filter_remove</a> <span class="c_punctuation">()</span> </td> </tr> </tbody> </table></div> </div> <div class="refsect1"> <a name="libudev-udev-monitor.other"></a><h2>Types and Values</h2> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="name"> <col class="description"> </colgroup> <tbody><tr> <td class="datatype_keyword">struct</td> <td class="function_name"><a class="link" href="libudev-udev-monitor.html#udev-monitor" title="struct udev_monitor">udev_monitor</a></td> </tr></tbody> </table></div> </div> <div class="refsect1"> <a name="libudev-udev-monitor.object-hierarchy"></a><h2>Object Hierarchy</h2> <pre class="screen"> </pre> </div> <div class="refsect1"> <a name="libudev-udev-monitor.description"></a><h2>Description</h2> <p>Connects to a device event source.</p> </div> <div class="refsect1"> <a name="libudev-udev-monitor.functions_details"></a><h2>Functions</h2> <div class="refsect2"> <a name="udev-monitor-ref"></a><h3>udev_monitor_ref ()</h3> <pre class="programlisting">struct <a class="link" href="libudev-udev-monitor.html#udev-monitor" title="struct udev_monitor"><span class="returnvalue">udev_monitor</span></a> * udev_monitor_ref (<em class="parameter"><code><span class="type">struct udev_monitor</span> *udev_monitor</code></em>);</pre> <p>Take a reference of a udev monitor.</p> <div class="refsect3"> <a name="id-1.2.5.7.2.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>udev_monitor</p></td> <td class="parameter_description"><p>udev monitor</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.2.5.7.2.6"></a><h4>Returns</h4> <p> the passed udev monitor</p> <p></p> </div> </div> <hr> <div class="refsect2"> <a name="udev-monitor-unref"></a><h3>udev_monitor_unref ()</h3> <pre class="programlisting">struct <a class="link" href="libudev-udev-monitor.html#udev-monitor" title="struct udev_monitor"><span class="returnvalue">udev_monitor</span></a> * udev_monitor_unref (<em class="parameter"><code><span class="type">struct udev_monitor</span> *udev_monitor</code></em>);</pre> <p>Drop a reference of a udev monitor. If the refcount reaches zero, the bound socket will be closed, and the resources of the monitor will be released.</p> <div class="refsect3"> <a name="id-1.2.5.7.3.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>udev_monitor</p></td> <td class="parameter_description"><p>udev monitor</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.2.5.7.3.6"></a><h4>Returns</h4> <p> <span class="type">NULL</span></p> <p></p> </div> </div> <hr> <div class="refsect2"> <a name="udev-monitor-get-udev"></a><h3>udev_monitor_get_udev ()</h3> <pre class="programlisting">struct <a class="link" href="libudev-udev.html#udev" title="struct udev"><span class="returnvalue">udev</span></a> * udev_monitor_get_udev (<em class="parameter"><code><span class="type">struct udev_monitor</span> *udev_monitor</code></em>);</pre> <p>Retrieve the udev library context the monitor was created with.</p> <div class="refsect3"> <a name="id-1.2.5.7.4.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>udev_monitor</p></td> <td class="parameter_description"><p>udev monitor</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.2.5.7.4.6"></a><h4>Returns</h4> <p> the udev library context</p> <p></p> </div> </div> <hr> <div class="refsect2"> <a name="udev-monitor-new-from-netlink"></a><h3>udev_monitor_new_from_netlink ()</h3> <pre class="programlisting">struct <a class="link" href="libudev-udev-monitor.html#udev-monitor" title="struct udev_monitor"><span class="returnvalue">udev_monitor</span></a> * udev_monitor_new_from_netlink (<em class="parameter"><code><span class="type">struct udev</span> *udev</code></em>, <em class="parameter"><code>const <span class="type">char</span> *name</code></em>);</pre> <p>Create new udev monitor and connect to a specified event source. Valid sources identifiers are "udev" and "kernel".</p> <p>Applications should usually not connect directly to the "kernel" events, because the devices might not be useable at that time, before udev has configured them, and created device nodes. Accessing devices at the same time as udev, might result in unpredictable behavior. The "udev" events are sent out after udev has finished its event processing, all rules have been processed, and needed device nodes are created.</p> <p>The initial refcount is 1, and needs to be decremented to release the resources of the udev monitor.</p> <div class="refsect3"> <a name="id-1.2.5.7.5.7"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>udev</p></td> <td class="parameter_description"><p>udev library context</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>name</p></td> <td class="parameter_description"><p>name of event source</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.2.5.7.5.8"></a><h4>Returns</h4> <p> a new udev monitor, or <span class="type">NULL</span>, in case of an error</p> <p></p> </div> </div> <hr> <div class="refsect2"> <a name="udev-monitor-enable-receiving"></a><h3>udev_monitor_enable_receiving ()</h3> <pre class="programlisting"><span class="returnvalue">int</span> udev_monitor_enable_receiving (<em class="parameter"><code><span class="type">struct udev_monitor</span> *udev_monitor</code></em>);</pre> <p>Binds the <em class="parameter"><code>udev_monitor</code></em> socket to the event source.</p> <div class="refsect3"> <a name="id-1.2.5.7.6.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>udev_monitor</p></td> <td class="parameter_description"><p>the monitor which should receive events</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.2.5.7.6.6"></a><h4>Returns</h4> <p> 0 on success, otherwise a negative error value.</p> <p></p> </div> </div> <hr> <div class="refsect2"> <a name="udev-monitor-set-receive-buffer-size"></a><h3>udev_monitor_set_receive_buffer_size ()</h3> <pre class="programlisting"><span class="returnvalue">int</span> udev_monitor_set_receive_buffer_size (<em class="parameter"><code><span class="type">struct udev_monitor</span> *udev_monitor</code></em>, <em class="parameter"><code><span class="type">int</span> size</code></em>);</pre> <p>Set the size of the kernel socket buffer. This call needs the appropriate privileges to succeed.</p> <div class="refsect3"> <a name="id-1.2.5.7.7.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>udev_monitor</p></td> <td class="parameter_description"><p>the monitor which should receive events</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>size</p></td> <td class="parameter_description"><p>the size in bytes</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.2.5.7.7.6"></a><h4>Returns</h4> <p> 0 on success, otherwise -1 on error.</p> <p></p> </div> </div> <hr> <div class="refsect2"> <a name="udev-monitor-get-fd"></a><h3>udev_monitor_get_fd ()</h3> <pre class="programlisting"><span class="returnvalue">int</span> udev_monitor_get_fd (<em class="parameter"><code><span class="type">struct udev_monitor</span> *udev_monitor</code></em>);</pre> <p>Retrieve the socket file descriptor associated with the monitor.</p> <div class="refsect3"> <a name="id-1.2.5.7.8.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>udev_monitor</p></td> <td class="parameter_description"><p>udev monitor</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.2.5.7.8.6"></a><h4>Returns</h4> <p> the socket file descriptor</p> <p></p> </div> </div> <hr> <div class="refsect2"> <a name="udev-monitor-receive-device"></a><h3>udev_monitor_receive_device ()</h3> <pre class="programlisting">struct <a class="link" href="libudev-udev-device.html#udev-device" title="struct udev_device"><span class="returnvalue">udev_device</span></a> * udev_monitor_receive_device (<em class="parameter"><code><span class="type">struct udev_monitor</span> *udev_monitor</code></em>);</pre> <p>Receive data from the udev monitor socket, allocate a new udev device, fill in the received data, and return the device.</p> <p>Only socket connections with uid=0 are accepted.</p> <p>The monitor socket is by default set to NONBLOCK. A variant of <code class="function">poll()</code> on the file descriptor returned by <a class="link" href="libudev-udev-monitor.html#udev-monitor-get-fd" title="udev_monitor_get_fd ()"><code class="function">udev_monitor_get_fd()</code></a> should to be used to wake up when new devices arrive, or alternatively the file descriptor switched into blocking mode.</p> <p>The initial refcount is 1, and needs to be decremented to release the resources of the udev device.</p> <div class="refsect3"> <a name="id-1.2.5.7.9.8"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>udev_monitor</p></td> <td class="parameter_description"><p>udev monitor</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.2.5.7.9.9"></a><h4>Returns</h4> <p> a new udev device, or <span class="type">NULL</span>, in case of an error</p> <p></p> </div> </div> <hr> <div class="refsect2"> <a name="udev-monitor-filter-add-match-subsystem-devtype"></a><h3>udev_monitor_filter_add_match_subsystem_devtype ()</h3> <pre class="programlisting"><span class="returnvalue">int</span> udev_monitor_filter_add_match_subsystem_devtype (<em class="parameter"><code><span class="type">struct udev_monitor</span> *udev_monitor</code></em>, <em class="parameter"><code>const <span class="type">char</span> *subsystem</code></em>, <em class="parameter"><code>const <span class="type">char</span> *devtype</code></em>);</pre> <p>This filter is efficiently executed inside the kernel, and libudev subscribers will usually not be woken up for devices which do not match.</p> <p>The filter must be installed before the monitor is switched to listening mode.</p> <div class="refsect3"> <a name="id-1.2.5.7.10.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>udev_monitor</p></td> <td class="parameter_description"><p>the monitor</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>subsystem</p></td> <td class="parameter_description"><p>the subsystem value to match the incoming devices against</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>devtype</p></td> <td class="parameter_description"><p>the devtype value to match the incoming devices against</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.2.5.7.10.7"></a><h4>Returns</h4> <p> 0 on success, otherwise a negative error value.</p> <p></p> </div> </div> <hr> <div class="refsect2"> <a name="udev-monitor-filter-add-match-tag"></a><h3>udev_monitor_filter_add_match_tag ()</h3> <pre class="programlisting"><span class="returnvalue">int</span> udev_monitor_filter_add_match_tag (<em class="parameter"><code><span class="type">struct udev_monitor</span> *udev_monitor</code></em>, <em class="parameter"><code>const <span class="type">char</span> *tag</code></em>);</pre> <p>This filter is efficiently executed inside the kernel, and libudev subscribers will usually not be woken up for devices which do not match.</p> <p>The filter must be installed before the monitor is switched to listening mode.</p> <div class="refsect3"> <a name="id-1.2.5.7.11.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>udev_monitor</p></td> <td class="parameter_description"><p>the monitor</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>tag</p></td> <td class="parameter_description"><p>the name of a tag</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.2.5.7.11.7"></a><h4>Returns</h4> <p> 0 on success, otherwise a negative error value.</p> <p></p> </div> </div> <hr> <div class="refsect2"> <a name="udev-monitor-filter-update"></a><h3>udev_monitor_filter_update ()</h3> <pre class="programlisting"><span class="returnvalue">int</span> udev_monitor_filter_update (<em class="parameter"><code><span class="type">struct udev_monitor</span> *udev_monitor</code></em>);</pre> <p>Update the installed socket filter. This is only needed, if the filter was removed or changed.</p> <div class="refsect3"> <a name="id-1.2.5.7.12.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>udev_monitor</p></td> <td class="parameter_description"><p>monitor</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.2.5.7.12.6"></a><h4>Returns</h4> <p> 0 on success, otherwise a negative error value.</p> <p></p> </div> </div> <hr> <div class="refsect2"> <a name="udev-monitor-filter-remove"></a><h3>udev_monitor_filter_remove ()</h3> <pre class="programlisting"><span class="returnvalue">int</span> udev_monitor_filter_remove (<em class="parameter"><code><span class="type">struct udev_monitor</span> *udev_monitor</code></em>);</pre> <p>Remove all filters from monitor.</p> <div class="refsect3"> <a name="id-1.2.5.7.13.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>udev_monitor</p></td> <td class="parameter_description"><p>monitor</p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.2.5.7.13.6"></a><h4>Returns</h4> <p> 0 on success, otherwise a negative error value.</p> <p></p> </div> </div> </div> <div class="refsect1"> <a name="libudev-udev-monitor.other_details"></a><h2>Types and Values</h2> <div class="refsect2"> <a name="udev-monitor"></a><h3>struct udev_monitor</h3> <pre class="programlisting">struct udev_monitor;</pre> <p>Opaque object handling an event source.</p> </div> </div> </div> <div class="footer"> <hr> Generated by GTK-Doc V1.20</div> </body> </html>
PennartLoettring/Poettrix
rootfs/usr/share/gtk-doc/html/libudev/libudev-udev-monitor.html
HTML
gpl-2.0
23,760
/** * This file is part of the Goobi viewer - a content presentation and management application for digitized objects. * * Visit these websites for more information. * - http://www.intranda.com * - http://digiverso.com * * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.goobi.viewer.model.iiif.presentation.v3.builder; import static io.goobi.viewer.api.rest.v2.ApiUrls.RECORDS_ALTO; import static io.goobi.viewer.api.rest.v2.ApiUrls.RECORDS_PDF; import static io.goobi.viewer.api.rest.v2.ApiUrls.RECORDS_PLAINTEXT; import static io.goobi.viewer.api.rest.v2.ApiUrls.RECORDS_RECORD; import java.net.URI; import java.net.URISyntaxException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeParseException; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import javax.ws.rs.core.UriBuilder; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.intranda.api.iiif.presentation.IPresentationModelElement; import de.intranda.api.iiif.presentation.enums.Format; import de.intranda.api.iiif.presentation.enums.ViewingHint; import de.intranda.api.iiif.presentation.v2.Manifest2; import de.intranda.api.iiif.presentation.v3.AbstractPresentationModelElement3; import de.intranda.api.iiif.presentation.v3.Canvas3; import de.intranda.api.iiif.presentation.v3.Collection3; import de.intranda.api.iiif.presentation.v3.IIIFAgent; import de.intranda.api.iiif.presentation.v3.IPresentationModelElement3; import de.intranda.api.iiif.presentation.v3.LabeledResource; import de.intranda.api.iiif.presentation.v3.Manifest3; import de.intranda.api.iiif.presentation.v3.Range3; import de.intranda.api.iiif.search.AutoSuggestService; import de.intranda.api.iiif.search.SearchService; import de.intranda.metadata.multilanguage.IMetadataValue; import de.intranda.metadata.multilanguage.SimpleMetadataValue; import de.unigoettingen.sub.commons.contentlib.exceptions.ContentLibException; import de.unigoettingen.sub.commons.contentlib.exceptions.ContentNotFoundException; import de.unigoettingen.sub.commons.util.datasource.media.PageSource.IllegalPathSyntaxException; import io.goobi.viewer.api.rest.AbstractApiUrlManager; import io.goobi.viewer.controller.DataManager; import io.goobi.viewer.controller.model.ProviderConfiguration; import io.goobi.viewer.exceptions.DAOException; import io.goobi.viewer.exceptions.IndexUnreachableException; import io.goobi.viewer.exceptions.PresentationException; import io.goobi.viewer.exceptions.ViewerConfigurationException; import io.goobi.viewer.model.iiif.presentation.v3.builder.LinkingProperty.LinkingTarget; import io.goobi.viewer.model.viewer.PageType; import io.goobi.viewer.model.viewer.PhysicalElement; import io.goobi.viewer.model.viewer.StructElement; import io.goobi.viewer.model.viewer.pageloader.AbstractPageLoader; import io.goobi.viewer.model.viewer.pageloader.EagerPageLoader; import io.goobi.viewer.model.viewer.pageloader.IPageLoader; /** * <p> * ManifestBuilder class. * </p> * * @author Florian Alpers */ public class ManifestBuilder extends AbstractBuilder { private static final Logger logger = LoggerFactory.getLogger(ManifestBuilder.class); /** * <p> * Constructor for ManifestBuilder. * </p> * * @param request a {@link javax.servlet.http.HttpServletRequest} object. */ public ManifestBuilder(AbstractApiUrlManager apiUrlManager) { super(apiUrlManager); } public IPresentationModelElement3 build(String pi) throws PresentationException, IndexUnreachableException, ViewerConfigurationException, IllegalPathSyntaxException, ContentLibException, URISyntaxException, DAOException { List<StructElement> documents = this.dataRetriever.getDocumentWithChildren(pi); StructElement mainDocument = documents.get(0); List<StructElement> childDocuments = documents.subList(1, documents.size()); AbstractPresentationModelElement3 manifest = generateManifest(mainDocument); if(manifest instanceof Manifest3) { addPages(mainDocument, (Manifest3) manifest); addStructures(mainDocument, childDocuments, (Manifest3) manifest); } else if (manifest instanceof Collection3){ addVolumes(mainDocument, childDocuments, (Collection3) manifest); } return manifest; } /** * @param mainDocument * @param childDocuments * @param manifest */ private void addVolumes(StructElement mainDocument, List<StructElement> childDocuments, Collection3 manifest) { for (StructElement volume : childDocuments) { try { IPresentationModelElement child = generateManifest(volume); if (child instanceof Manifest3) { // addBaseSequence((Manifest)child, volume, child.getId().toString()); manifest.addItem((Manifest3) child); } } catch (ViewerConfigurationException | URISyntaxException | PresentationException | IndexUnreachableException | ContentLibException e) { logger.error("Error creating child manigest for " + volume); } } } /** * @param mainDocument * @param childDocuments * @param manifest * @throws ContentNotFoundException * @throws PresentationException */ private void addStructures(StructElement mainDocument, List<StructElement> childDocuments, Manifest3 manifest) throws ContentNotFoundException, PresentationException { RangeBuilder rangeBuilder = new RangeBuilder(urls); Range3 topRange = rangeBuilder.build(mainDocument, childDocuments, null); topRange.getItems().stream() .filter(item -> item instanceof Range3) .map(item -> (Range3)item) .forEach(manifest::addRange); } /** * <p> * generateManifest. * </p> * * @param ele a {@link io.goobi.viewer.model.viewer.StructElement} object. * @return a {@link de.intranda.api.iiif.presentation.IPresentationModelElement} object. * @throws java.net.URISyntaxException if any. * @throws io.goobi.viewer.exceptions.PresentationException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. * @throws io.goobi.viewer.exceptions.ViewerConfigurationException if any. * @throws ContentLibException * @throws IllegalPathSyntaxException * @throws io.goobi.viewer.exceptions.DAOException if any. */ private AbstractPresentationModelElement3 generateManifest(StructElement ele) throws PresentationException, IndexUnreachableException, ViewerConfigurationException, IllegalPathSyntaxException, ContentLibException, URISyntaxException { final AbstractPresentationModelElement3 manifest; if (ele.isAnchor()) { manifest = new Collection3(getManifestURI(ele.getPi()), ele.getPi()); manifest.addBehavior(ViewingHint.multipart); } else { ele.setImageNumber(1); manifest = new Manifest3(getManifestURI(ele.getPi())); SearchService search = new SearchService(v1Builder.getSearchServiceURI(ele.getPi())); AutoSuggestService autoComplete = new AutoSuggestService(v1Builder.getAutoCompleteServiceURI(ele.getPi())); search.addService(autoComplete); manifest.addService(search); } populateData(ele, manifest); return manifest; } /** * @throws DAOException * @throws URISyntaxException * @throws ContentLibException * @throws IllegalPathSyntaxException * @param ele * @param manifest * @throws IndexUnreachableException * @throws PresentationException * @throws */ private void addPages(StructElement ele, Manifest3 manifest) throws PresentationException, IndexUnreachableException, IllegalPathSyntaxException, ContentLibException, URISyntaxException, DAOException { CanvasBuilder canvasBuilder = new CanvasBuilder(urls); IPageLoader pageLoader = AbstractPageLoader.create(ele); for (int order = pageLoader.getFirstPageOrder(); order <= pageLoader.getLastPageOrder(); order++) { PhysicalElement page = pageLoader.getPage(order); if(page != null) { Canvas3 canvas = canvasBuilder.build(page); manifest.addItem(canvas); } } } /** * <p> * populate. * </p> * * @param ele a {@link io.goobi.viewer.model.viewer.StructElement} object. * @param manifest a {@link de.intranda.api.iiif.presentation.AbstractPresentationModelElement} object. * @throws io.goobi.viewer.exceptions.ViewerConfigurationException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. * @throws io.goobi.viewer.exceptions.DAOException if any. * @throws io.goobi.viewer.exceptions.PresentationException if any. */ private AbstractPresentationModelElement3 populateData(StructElement ele, final AbstractPresentationModelElement3 manifest) throws ViewerConfigurationException, IndexUnreachableException, PresentationException { manifest.setLabel(ele.getMultiLanguageDisplayLabel()); getDescription(ele).ifPresent(desc -> manifest.setDescription(desc)); manifest.addThumbnail(getThumbnail(ele)); manifest.setRequiredStatement(getRequiredStatement()); manifest.setRights(getRightsStatement(ele).orElse(null)); manifest.setNavDate(getNavDate(ele)); manifest.addBehavior(getViewingBehavior(ele)); //TODO: add provider from config DataManager.getInstance().getConfiguration().getIIIFProvider().forEach(providerConfig -> manifest.addProvider(getProvider(providerConfig))); addMetadata(manifest, ele); addRelatedResources(manifest, ele); return manifest; } /** * @param manifest * @param ele */ private void addRelatedResources(AbstractPresentationModelElement3 manifest, StructElement ele) { // metadata document if (ele.isLidoRecord()) { LabeledResource resolver = new LabeledResource(getLidoResolverUrl(ele), "Dataset", Format.TEXT_XML.getLabel(), "http://www.lido-schema.org", null); manifest.addSeeAlso(resolver); } else { LabeledResource resolver = new LabeledResource(getMetsResolverUrl(ele), "Dataset", Format.TEXT_XML.getLabel(), "http://www.loc.gov/METS/", null); manifest.addSeeAlso(resolver); } if(DataManager.getInstance().getConfiguration().isVisibleIIIFRenderingViewer()) { PageType pageType = PageType.viewMetadata; if(ele.isHasImages()) { pageType = PageType.viewImage; } else if(ele.isAnchor()) { pageType = PageType.viewToc; } URI recordURI = UriBuilder.fromPath(urls.getApplicationUrl()).path("{pageType}").path("{pi}").build(pageType.getName(), ele.getPi()); LinkingProperty homepage = new LinkingProperty(LinkingTarget.VIEWER, createLabel(DataManager.getInstance().getConfiguration().getLabelIIIFRenderingViewer())); manifest.addHomepage(homepage.getResource(recordURI)); getCmsPageLinks(ele.getPi()).forEach(link -> manifest.addHomepage(link)); } if(DataManager.getInstance().getConfiguration().isVisibleIIIFRenderingPDF()) { URI uri = urls.path(RECORDS_RECORD, RECORDS_PDF).params(ele.getPi()).buildURI(); LinkingProperty pdf = new LinkingProperty(LinkingTarget.PDF, createLabel(DataManager.getInstance().getConfiguration().getLabelIIIFRenderingPDF())); manifest.addRendering(pdf.getResource(uri)); } if(DataManager.getInstance().getConfiguration().isVisibleIIIFRenderingAlto()) { URI uri = urls.path(RECORDS_RECORD, RECORDS_ALTO).params(ele.getPi()).buildURI(); LinkingProperty alto = new LinkingProperty(LinkingTarget.ALTO, createLabel(DataManager.getInstance().getConfiguration().getLabelIIIFRenderingAlto())); manifest.addSeeAlso(alto.getResource(uri)); } if(DataManager.getInstance().getConfiguration().isVisibleIIIFRenderingPlaintext()) { URI uri = urls.path(RECORDS_RECORD, RECORDS_PLAINTEXT).params(ele.getPi()).buildURI(); LinkingProperty text = new LinkingProperty(LinkingTarget.PLAINTEXT, createLabel(DataManager.getInstance().getConfiguration().getLabelIIIFRenderingPlaintext())); manifest.addRendering(text.getResource(uri)); } } /** * TODO: config for docStruct types that should be presented as "paged" * * @param ele * @return */ private ViewingHint getViewingBehavior(StructElement ele) { String docStructType = ele.getDocStructType().toLowerCase(); switch (docStructType) { case "monograph": case "volume": case "newspaper_volume": case "periodical_volume": return ViewingHint.paged; default: return ViewingHint.individuals; } } private LocalDateTime getNavDate(StructElement ele) { String navDateField = DataManager.getInstance().getConfiguration().getIIIFNavDateField(); if (StringUtils.isNotBlank(navDateField) && StringUtils.isNotBlank(ele.getMetadataValue(navDateField))) { try { String eleValue = ele.getMetadataValue(navDateField); LocalDate date = LocalDate.parse(eleValue); return date.atStartOfDay(); } catch (NullPointerException | DateTimeParseException e) { logger.warn("Unable to parse {} as Date", ele.getMetadataValue(navDateField)); } } return null; } private List<LabeledResource> getCmsPageLinks(String pi) { try { return DataManager.getInstance() .getDao() .getCMSPagesForRecord(pi, null) .stream() .filter(page -> page.isPublished()) .map(page -> { LinkingProperty cmsPageLink = new LinkingProperty(LinkingTarget.VIEWER, page.getTitleTranslations()); LabeledResource cmsPage = cmsPageLink.getResource(URI.create(this.urls.getApplicationUrl() + "/" + page.getUrl())); return cmsPage; }) .collect(Collectors.toList()); } catch (Throwable e) { logger.warn(e.toString()); return Collections.emptyList(); } } }
intranda/goobi-viewer-core
goobi-viewer-core/src/main/java/io/goobi/viewer/model/iiif/presentation/v3/builder/ManifestBuilder.java
Java
gpl-2.0
15,695
/* * casim, cellular automaton simulation for multi-destination pedestrian * crowds; see www.cacrowd.org * Copyright (C) 2016-2017 CACrowd and contributors * * This file is part of casim. * casim 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. * * */ package org.cacrowd.casim.pedca.environment.grid; import org.apache.log4j.Logger; import org.cacrowd.casim.pedca.environment.grid.neighbourhood.Neighbourhood; import org.cacrowd.casim.pedca.environment.network.Coordinate; import org.cacrowd.casim.pedca.utility.Constants; import java.io.File; import java.io.IOException; import java.util.ArrayList; public abstract class Grid<T> { private static final Logger log = Logger.getLogger(Grid.class); protected ArrayList<ArrayList<GridCell<T>>> cells; private double offsetY = 0.; private double offsetX = 0.; Grid(int rows, int cols, double offsetX, double offsetY) { this.offsetX = offsetX; this.offsetY = offsetY; initGrid(rows, cols); } public Grid(int rows, int cols) { this(rows, cols, 0, 0); } Grid(File file) throws IOException { initEmptyGrid(); loadFromCSV(file); } Grid(String fileName) throws IOException { initEmptyGrid(); loadFromCSV(fileName); } private void initEmptyGrid() { cells = new ArrayList<ArrayList<GridCell<T>>>(); } private void initGrid(int rows, int cols) { cells = new ArrayList<ArrayList<GridCell<T>>>(); for (int i = 0; i < rows; i++) { addRow(); for (int j = 0; j < cols; j++) addElementAt(i); } } public Coordinate rowCol2Coordinate(int row, int col) { GridPoint gp = new GridPoint(col, row); return gridPoint2Coordinate(gp); } public Coordinate gridPoint2Coordinate(GridPoint gp) { return new Coordinate(gp.getX() * Constants.CELL_SIZE + offsetX, gp.getY() * Constants.CELL_SIZE + offsetY); } public GridPoint coordinate2GridPoint(Coordinate c) { int col = (int) ((c.getX() - offsetX) / Constants.CELL_SIZE); int row = (int) ((c.getY() - offsetY) / Constants.CELL_SIZE); return new GridPoint(col, row); } public double getOffsetX() { return this.offsetX; } public double getOffsetY() { return this.offsetY; } public int y2Row(double y) { return (int) ((y - offsetY) / Constants.CELL_SIZE); } public int x2Col(double x) { return (int) ((x - offsetX) / Constants.CELL_SIZE); } public void add(int i, int j, T object) { get(i, j).add(object); } public GridCell<T> get(GridPoint p) { return cells.get(p.getY()).get(p.getX()); } public GridCell<T> get(int row, int col) { return cells.get(row).get(col); } void addRow() { cells.add(new ArrayList<GridCell<T>>()); } private void addElementAt(int row) { cells.get(row).add(new GridCell<T>()); } void addElementAt(int row, T object) { GridCell<T> cell = new GridCell<T>(); cell.add(object); cells.get(row).add(cell); } public int getRows() { return cells.size(); } public int getColumns() { return cells.get(0).size(); } public ArrayList<T> getObjectsAt(int i, int j) { return get(i, j).getObjects(); } /** * Return Moore neighbourhood of gp, excluding cells over the boundaries of the grid */ public Neighbourhood getNeighbourhood(GridPoint gp) { Neighbourhood neighbourhood = new Neighbourhood(); final int radius = 1; int row_gp = gp.getY(); int col_gp = gp.getX(); for (int row = row_gp - radius; row <= row_gp + radius; row++) for (int col = col_gp - radius; col <= col_gp + radius; col++) if (neighbourCondition(row, col))// &&(row==row_gp||col==col_gp)) for the Von Neumann neighbourhood neighbourhood.add(new GridPoint(col, row)); return neighbourhood; } public String toString() { StringBuilder res = new StringBuilder(); for (ArrayList<GridCell<T>> cell : cells) { for (GridCell<T> aCell : cell) res.append(aCell.toString()).append(" "); res.append("\n"); } return res.toString(); } protected boolean neighbourCondition(int row, int col) { return row >= 0 && col >= 0 && col < getColumns() && row < getRows(); } protected abstract void loadFromCSV(File file) throws IOException; private void loadFromCSV(String fileName) throws IOException { File environmentFile = new File(fileName); loadFromCSV(environmentFile); } public abstract void saveCSV(String path) throws IOException; }
CACrowd/casim
src/main/java/org/cacrowd/casim/pedca/environment/grid/Grid.java
Java
gpl-2.0
5,026
<?php /** * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages * and that other 'pages' on your WordPress site will use a * different template. * * @package WordPress * @subpackage MyBlog * @since 3.0 */ get_template_part( '_head' ); ?> <body <?php body_class(); ?>> <?php get_header(); ?> <div id="wrapper" class="hfeed"> <div id="main" class="content-wrapper"> <div id="container"> <div id="content" role="main"> <?php /* Run the loop to output the page. * If you want to overload this in a child theme then include a file * called loop-page.php and that will be used instead. */ get_template_part( 'loop', 'page' ); ?> </div><!-- #content --> </div><!-- #container --> <?php get_sidebar('secondary'); ?> </div><!-- #main --> <?php get_footer(); ?> </div><!-- #wrapper --> <?php wp_footer(); ?> </body></html>
Bielousov/blog
page.php
PHP
gpl-2.0
993
<?php class WC_Catalog_Restrictions_User_Admin { public static $instance; public static function instance() { if (!self::$instance) { $instance = new WC_Catalog_Restrictions_User_Admin(); } } public function __construct() { add_action('show_user_profile', array($this, 'profile_fields')); add_action('edit_user_profile', array($this, 'profile_fields')); add_action('personal_options_update', array($this, 'save_profile_fields')); add_action('edit_user_profile_update', array($this, 'save_profile_fields')); } public function profile_fields($user) { $location = get_user_meta($user->ID, '_wc_location', true); $can_change = get_user_meta($user->ID, '_wc_location_user_changeable', true); $can_change = $can_change == 'yes' || empty($can_change); if (current_user_can('administrator') || $can_change) { include 'views/user-profile-fields.php'; } } public function save_profile_fields($user_id) { if (!current_user_can('edit_user', $user_id)) { return false; } $location = isset($_POST['location']) ? $_POST['location'] : ''; $can_change = isset($_POST['can_change']) ? $_POST['can_change'] : 'yes'; update_user_meta($user_id, '_wc_location', $location); update_user_meta($user_id, '_wc_location_user_changeable', $can_change); } }
aman104/stockhouse
wp-content/plugins/woocommerce-catalog-visibility-options/lib/woocommerce-catalog-restrictions/classes/class-wc-catalog-restrictions-user-admin.php
PHP
gpl-2.0
1,293
package com.nnero.nnero.views; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Toast; import java.util.Calendar; import java.util.Date; import butterknife.ButterKnife; import butterknife.InjectView; /** * Created by NNERO on 16/1/28. */ public class DatePickerView extends LinearLayout{ public DatePickerView(Context context) { super(context); } public DatePickerView(Context context, AttributeSet attrs) { super(context, attrs); } public DatePickerView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } // @InjectView(R.id.year_view) WheelView yearView; // @InjectView(R.id.month_view) WheelView monthView; // @InjectView(R.id.day_view) WheelView dayView; // // private Calendar calendar; // private View datePickView; //布局填充形式 植入选择器 // // private int defCurTvSize = 47; //默认中心位置字体 // private int defCurItemSize = 42;//默认外围位置字体 // // private int minYear = 2009; //年最低值 // // private NumericWheelAdapter yearAdapter; // private NumericWheelAdapter monthAdapter; // private NumericWheelAdapter dayAdapter; // private int currentYear; // private int currentMonth; // private int currentDay; // private boolean isMonthChanged; //避免频繁改变月份adapter // // private String yearText; // private String monthText; // private String dayText; // // public DatePickerView(Context context) { // super(context); // init(); // } // // public DatePickerView(Context context, AttributeSet attrs) { // super(context, attrs); // init(); // } // // public DatePickerView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(); // } // // private void init() { // setPadding(0, ScreenSizeCaculation.dip2px(getContext(), 25), 0, ScreenSizeCaculation.dip2px(getContext(), 25)); // calendar = Calendar.getInstance(); // calendar.setTime(new Date()); // // yearText = getResources().getString(R.string.edu_baby_year); // monthText = getResources().getString(R.string.edu_baby_month); // dayText = getResources().getString(R.string.edu_baby_day); // // initViews(); // initListeners(); // initCurrentDay(); // } // // //设置当前时间是 今天 // private void initCurrentDay() { // currentYear = calendar.get(Calendar.YEAR); // currentMonth = calendar.get(Calendar.MONTH); // currentDay = calendar.get(Calendar.DAY_OF_MONTH); // // changeMonthAndDayByCurrentYear(currentYear); // changeDayByCurrentYearAndMonth(currentYear, currentMonth); // // yearView.setCurrentItem(currentYear - minYear); // monthView.setCurrentItem(currentMonth); // dayView.setCurrentItem(currentDay - 1); // // } // // private void initViews(){ // datePickView = View.inflate(getContext(), R.layout.date_picker_view, null); // ButterKnife.inject(this, datePickView); // // LinearLayout centerArea = new LinearLayout(getContext()); // centerArea.setOrientation(LinearLayout.VERTICAL); // RelativeLayout.LayoutParams centerParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); // centerParams.addRule(RelativeLayout.CENTER_IN_PARENT); // centerArea.setLayoutParams(centerParams); // // View lineViewTop = new View(getContext()); // View lineViewDown = new View(getContext()); // lineViewTop.setBackgroundColor(getResources().getColor(R.color.edu_date_picker_line_bg)); // lineViewDown.setBackgroundColor(getResources().getColor(R.color.edu_date_picker_line_bg)); // LinearLayout.LayoutParams lineTopParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ScreenSizeCaculation.dip2px(getContext(),1)); // LinearLayout.LayoutParams lineDownParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ScreenSizeCaculation.dip2px(getContext(),1)); // lineDownParams.topMargin = ScreenSizeCaculation.dip2px(getContext(),32); // centerArea.addView(lineViewTop,lineTopParams); // centerArea.addView(lineViewDown,lineDownParams); // // yearView.setVisibleItems(5); // monthView.setVisibleItems(5); // dayView.setVisibleItems(5); // // int curTextSize = Util.getFrontSize(getContext(), defCurTvSize); // int itemSize = Util.getFrontSize(getContext(),defCurItemSize); // yearView.setTextSize(curTextSize, itemSize); // monthView.setTextSize(curTextSize, itemSize); // dayView.setTextSize(curTextSize, itemSize); // // yearView.setCyclic(true); // monthView.setCyclic(true); // dayView.setCyclic(true); // // addView(datePickView); // addView(centerArea); // } // // private void initListeners(){ // yearView.addScrollingListener(new OnWheelScrollListener() { // @Override // public void onScrollingStarted(WheelView wheel) { // } // // @Override // public void onScrollingFinished(WheelView wheel) { // changeMonthAndDayByCurrentYear(Integer.parseInt(yearAdapter.getItem(yearView.getCurrentItem()).replace(yearText,""))); // } // }); // monthView.addScrollingListener(new OnWheelScrollListener() { // @Override // public void onScrollingStarted(WheelView wheel) { // } // // @Override // public void onScrollingFinished(WheelView wheel) { // changeDayByCurrentYearAndMonth( // Integer.parseInt(yearAdapter.getItem(yearView.getCurrentItem()).replace(yearText, "")), // Integer.parseInt(monthAdapter.getItem(monthView.getCurrentItem()).replace(monthText,""))); // } // }); // } // // private void changeDayByMonth(int month){ // dayAdapter = new NumericWheelAdapter(1,calculateDay(month),"%1s"+dayText); // dayView.setAdapter(dayAdapter); // } // // //计算 day的 数值 分为 大月 小月 2月 包括闰年判断 // private int calculateDay(int month){ // int day = 0; // switch (month){ // case 1: // case 3: // case 5: // case 7: // case 8: // case 10: // case 12: // day = 31; // break; // case 4: // case 6: // case 9: // case 11: // day = 30; // break; // case 2: // String year = yearAdapter.getItem(yearView.getCurrentItem()); // year = year.replace(getResources().getString(R.string.edu_baby_month),""); // try { //防止意外 // if(TimeHelper.isLeapYear(Integer.parseInt(year))){ // day = 29; // } else { // day = 28; // } // } catch (NumberFormatException e) { // day = 28; // } // break; // } // return day; // } // // //滚动年份计算 当年份是当前年的 时候 会重新计算 月份 和日 的adapter 因为选择生日 不能超过今天 // private void changeMonthAndDayByCurrentYear(int year){ // if(year == currentYear){ // monthAdapter = new NumericWheelAdapter(1,currentMonth+1,"%1s"+monthText); // monthView.setAdapter(monthAdapter); // isMonthChanged = true; // } else if(year == minYear){ // monthAdapter = new NumericWheelAdapter(currentMonth+1,12,"%1s"+monthText); // monthView.setAdapter(monthAdapter); // isMonthChanged = true; // } else { // if(isMonthChanged) { // monthAdapter = new NumericWheelAdapter(1, 12, "%1s" + monthText); // monthView.setAdapter(monthAdapter); // isMonthChanged = false; // } // changeDayByMonth(monthView.getCurrentItem()+1); // } // } // //滚动月份计算 // private void changeDayByCurrentYearAndMonth(int year,int month){ // if(year == currentYear && month == currentMonth+1){ // dayAdapter = new NumericWheelAdapter(1,currentDay,"%1s"+dayText); // dayView.setAdapter(dayAdapter); // } else if(year == minYear && month == currentMonth+1){ // dayAdapter = new NumericWheelAdapter(currentDay,calculateDay(month),"%1s"+dayText); // dayView.setAdapter(dayAdapter); // } else { // changeDayByMonth(monthView.getCurrentItem() + 1); // } // } // // /** // * 获取选中的日期 yyyy-MM-dd // * @return // */ // public String getDate(){ // String year = yearAdapter.getItem(yearView.getCurrentItem()); // String month = monthAdapter.getItem(monthView.getCurrentItem()); // String day = dayAdapter.getItem(dayView.getCurrentItem()); // if(year == null){ // Toast.makeText(getContext(), R.string.edu_date_request_year, Toast.LENGTH_SHORT).show(); // return null; // } else if(month == null){ // Toast.makeText(getContext(),R.string.edu_date_request_month,Toast.LENGTH_SHORT).show(); // return null; // } else if(day == null){ // Toast.makeText(getContext(),R.string.edu_date_request_day,Toast.LENGTH_SHORT).show(); // return null; // } // return year.replace(yearText, "")+"-"+formatNumber(month.replace(monthText, "")) +"-"+formatNumber(day.replace(dayText,"")); // } // // private String formatNumber(String number){ // return number.length() == 1 ? "0"+number : number; // } // // /** // * 支持 yyyy-MM-dd 的日期 // */ // public void setDate(String date){ // if(StringUtils.isBlank(date)){ // return; // } // String[] elements = date.split("-"); // try { // int year = Integer.parseInt(elements[0]); // int month = Integer.parseInt(elements[1]); // int day = Integer.parseInt(elements[2]); // changeMonthAndDayByCurrentYear(year); // changeDayByCurrentYearAndMonth(year, month); // yearView.setCurrentItem(year-minYear); // monthView.setCurrentItem(month-1); // dayView.setCurrentItem(day-1); // } catch (NumberFormatException e) { // } // } // // /** // * 设置最新年值 根据最大年龄计算 // * @param age // */ // public void setMinYear(int age){ // minYear = currentYear - age; // yearAdapter = new NumericWheelAdapter(minYear, calendar.get(Calendar.YEAR), "%1s" + yearText); // yearView.setAdapter(yearAdapter); // yearView.setCurrentItem(currentYear - minYear); // } }
nnero2235/NNERO
app/src/main/java/com/nnero/nnero/views/DatePickerView.java
Java
gpl-2.0
11,223
package com.numericmethods; import java.util.*; public class LU{ public static double[][] rozklad(int n, double[][] a) { //n wymiarowa macierz A double[][] L = new double[n][n]; double[][] U = new double[n][n]; for(int i=0;i<L.length;i++){ //wypelniam diagonalie jedynkami L[i][i]=1; } int m=a.length; for(int j=0;j<=m-1;j++){ for(int i=0;i<=j;i++){ double sum=0; for(int k=0;k<=i-1;k++){ sum+=L[i][k]*U[k][j]; } U[i][j]=a[i][j]-sum; } for(int i=j+1;i<=m-1;i++){ double sum=0; for(int k=0;k<=j-1;k++){ sum+=L[i][k]*U[k][j]; } L[i][j] = (a[i][j] - sum) / U[j][j]; } } System.out.println("L=" + Arrays.deepToString(L)); return U; } public static void main(String[] args){ System.out.println("Jaki rozmiar macierzy?"); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); //pobrac rozmiar double[][] m = new double[n][n]; for(int i=0;i<=n-1;i++){ for(int j=0;j<=n-1;j++){ System.out.println("Wprowadź wartość= [" + i +"]" + "[" + j + "]"); m[i][j]=sc.nextDouble(); } } System.out.println("Wprowadzona macierz A="+ Arrays.deepToString(m)); System.out.println("Rozkład A=L*U"); System.out.println("U="+ Arrays.deepToString(rozklad(n,m))); } }
xcodeassocietd/NumericalMethods
NumericMethods_02-java/eclipse_project/src/com/numericmethods/LU.java
Java
gpl-2.0
1,272
<?php /** * @version $Id$ * @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License <http://www.gnu.org/copyleft/gpl.html> */ // Check to ensure this file is included in Joomla! defined('_JEXEC') or die; jimport('joomla.application.component.controller'); /** * Users mail controller. * * @package Joomla.Administrator * @subpackage com_users */ class UsersControllerMail extends JController { public function send() { // Check for request forgeries. JRequest::checkToken('request') or jexit(JText::_('JInvalid_Token')); $model = &$this->getModel('Mail'); if ($model->send()) { $type = 'message'; } else { $type = 'error'; } $msg = &$model->getError(); $this->setredirect('index.php?option=com_users&view=mail', $msg, $type); } public function cancel() { // Check for request forgeries. JRequest::checkToken('request') or jexit(JText::_('JInvalid_Token')); $this->setRedirect('index.php'); } }
joebushi/joomla
administrator/components/com_users/controllers/mail.php
PHP
gpl-2.0
1,012
/* $Id: test1.c 53 2007-03-10 14:46:36Z bja $ * * Copyright (C) 2007, Joel Andersson <bja@kth.se> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include "wiimote.h" #include "wiimote_api.h" int main(int argc, char **argv) { wiimote_t wiimote = WIIMOTE_INIT; wiimote_report_t report = WIIMOTE_REPORT_INIT; if (argc < 2) { fprintf(stderr, "Usage: test1 BDADDR\n"); exit(1); } /* Print help information. */ printf("test1 - libwiimote test application\n\n"); printf(" A - Enable accelerometer\n"); printf(" B - Enable ir-sensor\n"); printf(" 1 - Enable rumble\n"); printf(" + - Increment leds\n"); printf(" - - Decrement leds\n"); printf(" Home - Exit\n\n"); printf("Press buttons 1 and 2 on the wiimote now to connect.\n"); /* Connect the wiimote specified on the command line. */ if (wiimote_connect(&wiimote, argv[1]) < 0) { fprintf(stderr, "unable to open wiimote: %s\n", wiimote_get_error()); exit(1); } /* Activate the first led on the wiimote. It will take effect on the next call to wiimote_update. */ wiimote.led.one = 1; while (wiimote_is_open(&wiimote)) { /* The wiimote_update function is used to synchronize the wiimote object with the real wiimote. It should be called as often as possible in order to minimize latency. */ if (wiimote_update(&wiimote) < 0) { wiimote_disconnect(&wiimote); break; } /* The wiimote object has member 'keys' which keep track of the current key state. */ if (wiimote.keys.home) { wiimote_disconnect(&wiimote); } /* To see if a specific key has been pressed you can either test a specific member of the 'keys' structure, or compare them all at once with a bit mask. See wiimote_event.h for details. */ if (wiimote.keys.bits & WIIMOTE_KEY_1) { /* This will activate the rumble feature on the next update. The wiimote will rumble until the 'one' key is released. */ wiimote.rumble = 1; } else { /* Disable rumble on the next update. */ wiimote.rumble = 0; } /* Prepare and send a status report request. */ if (wiimote.keys.two) { report.channel = WIIMOTE_RID_STATUS; if (wiimote_report(&wiimote, &report, sizeof (report.status)) < 0) { wiimote_perror("unable to get status report"); } } /* Activate the IR-sensor when the 'B' key is pressed. */ if (wiimote.keys.b) { wiimote.mode.ir = 1; } else { wiimote.mode.ir = 0; } /* Activate the accelerometer when the 'A' key is pressed. */ if (wiimote.keys.a) { wiimote.mode.acc = 1; } else { wiimote.mode.acc = 0; } /* Change the LEDs on the wiimote when the plus and minus keys are pressed. */ if (wiimote.keys.plus) { wiimote.led.bits += 1; } if (wiimote.keys.minus) { wiimote.led.bits -= 1; } /* Print the current state of the wiimote. */ fprintf(stderr, "MODE %02x\n", wiimote.mode.bits); fprintf(stderr, "BAT %02x\n", wiimote.battery); fprintf(stderr, "KEYS %04x one=%d two=%d a=%d b=%d <=%d >=%d ^=%d v=%d h=%d +=%d -=%d\n", wiimote.keys.bits, wiimote.keys.one, wiimote.keys.two, wiimote.keys.a, wiimote.keys.b, wiimote.keys.left, wiimote.keys.right, wiimote.keys.up, wiimote.keys.down, wiimote.keys.home, wiimote.keys.plus, wiimote.keys.minus); fprintf(stderr, "JOY1 joyx=%03d joyy=%03d x=%03d y=%03d z=%03d keys.z=%d keys.c=%d\n", wiimote.ext.nunchuk.joyx, wiimote.ext.nunchuk.joyy, wiimote.ext.nunchuk.axis.x, wiimote.ext.nunchuk.axis.y, wiimote.ext.nunchuk.axis.z, wiimote.ext.nunchuk.keys.z, wiimote.ext.nunchuk.keys.c); fprintf(stderr, "JOY2 joyx=%03d joyy=%03d\n", wiimote.ext.classic.joyx1, wiimote.ext.classic.joyy1); fprintf(stderr, "JOY3 joyx=%03d joyy=%03d\n", wiimote.ext.classic.joyx2, wiimote.ext.classic.joyy2); fprintf(stderr, "AXIS x=%03d y=%03d z=%03d\n", wiimote.axis.x, wiimote.axis.y, wiimote.axis.z); #ifdef _ENABLE_TILT fprintf(stderr, "TILT x=%.3f y=%.3f z=%.3f\n", wiimote.tilt.x, wiimote.tilt.y, wiimote.tilt.z); #endif #ifdef _ENABLE_FORCE fprintf(stderr, "FORCE x=%.3f y=%.3f z=%.3f (sum=%.3f)\n", wiimote.force.x, wiimote.force.y, wiimote.force.z, sqrt(wiimote.force.x*wiimote.force.x+wiimote.force.y*wiimote.force.y+wiimote.force.z*wiimote.force.z)); #endif fprintf(stderr, "IR1 x=%04d y=%04d ss=%d\n", wiimote.ir1.x, wiimote.ir1.y, wiimote.ir1.size); fprintf(stderr, "IR2 x=%04d y=%04d ss=%d\n", wiimote.ir2.x, wiimote.ir2.y, wiimote.ir2.size); fprintf(stderr, "IR3 x=%04d y=%04d ss=%d\n", wiimote.ir3.x, wiimote.ir3.y, wiimote.ir3.size); fprintf(stderr, "IR4 x=%04d y=%04d ss=%d\n", wiimote.ir4.x, wiimote.ir4.y, wiimote.ir4.size); fprintf(stderr, "\n"); } return 0; }
meke/libwiimote
test/test1.c
C
gpl-2.0
5,579
/* * (c) BayCom GmbH, http://www.baycom.de, info@baycom.de * * See the COPYING file for copyright information and * how to reach the author. * */ typedef struct { struct list list; pthread_t ci_recv_thread; char uuid[UUID_SIZE]; SOCKET fd_ci; int recv_run; int device; int connected; recv_cacaps_t *cacaps; u_int8_t *txdata; u_int8_t *rxdata; int (*handle_ci_slot[CA_MAX_SLOTS]) (ci_pdu_t *tpdu, void *context); void *handle_ci_slot_context[CA_MAX_SLOTS]; } ci_dev_t; DLL_SYMBOL int ci_register_handler(ci_dev_t *c, int slot, int (*p) (ci_pdu_t *, void *), void *context); DLL_SYMBOL int ci_unregister_handler(ci_dev_t *c, int slot); DLL_SYMBOL int ci_write_pdu(ci_dev_t *c, ci_pdu_t *tpdu); DLL_SYMBOL ci_dev_t *ci_find_dev_by_uuid (char *uuid); DLL_SYMBOL int ci_init (int ca_enable, char *intf, int p); DLL_SYMBOL void ci_exit (void);
Moorviper/vdr-plugin-mcli
mcast/client/ci_handler.h
C
gpl-2.0
859
/* * parse.c * */ /* Portions of this file are subject to the following copyrights. See * the Net-SNMP's COPYING file for more details and other copyrights * that may apply: */ /****************************************************************** Copyright 1989, 1991, 1992 by Carnegie Mellon University All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of CMU not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* * Copyright © 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms specified in the COPYING file * distributed with the Net-SNMP package. */ #include <net-snmp/net-snmp-config.h> #ifndef NETSNMP_DISABLE_MIB_LOADING #if HAVE_LIMITS_H #include <limits.h> #endif #include <stdio.h> #if HAVE_STDLIB_H #include <stdlib.h> #endif #if HAVE_STRING_H #include <string.h> #else #include <strings.h> #endif #include <ctype.h> #include <sys/types.h> #if HAVE_SYS_STAT_H #include <sys/stat.h> #endif /* * Wow. This is ugly. -- Wes */ #if HAVE_DIRENT_H # include <dirent.h> # define NAMLEN(dirent) strlen((dirent)->d_name) #else # define dirent direct # define NAMLEN(dirent) (dirent)->d_namlen # if HAVE_SYS_NDIR_H # include <sys/ndir.h> # endif # if HAVE_SYS_DIR_H # include <sys/dir.h> # endif # if HAVE_NDIR_H # include <ndir.h> # endif #endif #if TIME_WITH_SYS_TIME # ifdef WIN32 # include <sys/timeb.h> # else # include <sys/time.h> # endif # include <time.h> #else # if HAVE_SYS_TIME_H # include <sys/time.h> # else # include <time.h> # endif #endif #if HAVE_WINSOCK_H #include <winsock.h> #endif #if HAVE_NETINET_IN_H #include <netinet/in.h> #endif #if defined(HAVE_REGEX_H) && defined(HAVE_REGCOMP) #include <regex.h> #endif #if HAVE_DMALLOC_H #include <dmalloc.h> #endif #include <errno.h> #include <net-snmp/types.h> #include <net-snmp/output_api.h> #include <net-snmp/config_api.h> #include <net-snmp/utilities.h> #include <net-snmp/library/parse.h> #include <net-snmp/library/mib.h> #include <net-snmp/library/snmp_api.h> /* * This is one element of an object identifier with either an integer * subidentifier, or a textual string label, or both. * The subid is -1 if not present, and label is NULL if not present. */ struct subid_s { int subid; int modid; char *label; }; #define MAXTC 4096 struct tc { /* textual conventions */ int type; int modid; char *descriptor; char *hint; struct enum_list *enums; struct range_list *ranges; char *description; } tclist[MAXTC]; int mibLine = 0; const char *File = "(none)"; static int anonymous = 0; struct objgroup { char *name; int line; struct objgroup *next; } *objgroups = NULL, *objects = NULL, *notifs = NULL; #define SYNTAX_MASK 0x80 /* * types of tokens * Tokens wiht the SYNTAX_MASK bit set are syntax tokens */ #define CONTINUE -1 #define ENDOFFILE 0 #define LABEL 1 #define SUBTREE 2 #define SYNTAX 3 #define OBJID (4 | SYNTAX_MASK) #define OCTETSTR (5 | SYNTAX_MASK) #define INTEGER (6 | SYNTAX_MASK) #define NETADDR (7 | SYNTAX_MASK) #define IPADDR (8 | SYNTAX_MASK) #define COUNTER (9 | SYNTAX_MASK) #define GAUGE (10 | SYNTAX_MASK) #define TIMETICKS (11 | SYNTAX_MASK) #define KW_OPAQUE (12 | SYNTAX_MASK) #define NUL (13 | SYNTAX_MASK) #define SEQUENCE 14 #define OF 15 /* SEQUENCE OF */ #define OBJTYPE 16 #define ACCESS 17 #define READONLY 18 #define READWRITE 19 #define WRITEONLY 20 #ifdef NOACCESS #undef NOACCESS /* agent 'NOACCESS' token */ #endif #define NOACCESS 21 #define STATUS 22 #define MANDATORY 23 #define KW_OPTIONAL 24 #define OBSOLETE 25 /* * #define RECOMMENDED 26 */ #define PUNCT 27 #define EQUALS 28 #define NUMBER 29 #define LEFTBRACKET 30 #define RIGHTBRACKET 31 #define LEFTPAREN 32 #define RIGHTPAREN 33 #define COMMA 34 #define DESCRIPTION 35 #define QUOTESTRING 36 #define INDEX 37 #define DEFVAL 38 #define DEPRECATED 39 #define SIZE 40 #define BITSTRING (41 | SYNTAX_MASK) #define NSAPADDRESS (42 | SYNTAX_MASK) #define COUNTER64 (43 | SYNTAX_MASK) #define OBJGROUP 44 #define NOTIFTYPE 45 #define AUGMENTS 46 #define COMPLIANCE 47 #define READCREATE 48 #define UNITS 49 #define REFERENCE 50 #define NUM_ENTRIES 51 #define MODULEIDENTITY 52 #define LASTUPDATED 53 #define ORGANIZATION 54 #define CONTACTINFO 55 #define UINTEGER32 (56 | SYNTAX_MASK) #define CURRENT 57 #define DEFINITIONS 58 #define END 59 #define SEMI 60 #define TRAPTYPE 61 #define ENTERPRISE 62 /* * #define DISPLAYSTR (63 | SYNTAX_MASK) */ #define BEGIN 64 #define IMPORTS 65 #define EXPORTS 66 #define ACCNOTIFY 67 #define BAR 68 #define RANGE 69 #define CONVENTION 70 #define DISPLAYHINT 71 #define FROM 72 #define AGENTCAP 73 #define MACRO 74 #define IMPLIED 75 #define SUPPORTS 76 #define INCLUDES 77 #define VARIATION 78 #define REVISION 79 #define NOTIMPL 80 #define OBJECTS 81 #define NOTIFICATIONS 82 #define MODULE 83 #define MINACCESS 84 #define PRODREL 85 #define WRSYNTAX 86 #define CREATEREQ 87 #define NOTIFGROUP 88 #define MANDATORYGROUPS 89 #define GROUP 90 #define OBJECT 91 #define IDENTIFIER 92 #define CHOICE 93 #define LEFTSQBRACK 95 #define RIGHTSQBRACK 96 #define IMPLICIT 97 #define APPSYNTAX (98 | SYNTAX_MASK) #define OBJSYNTAX (99 | SYNTAX_MASK) #define SIMPLESYNTAX (100 | SYNTAX_MASK) #define OBJNAME (101 | SYNTAX_MASK) #define NOTIFNAME (102 | SYNTAX_MASK) #define VARIABLES 103 #define UNSIGNED32 (104 | SYNTAX_MASK) #define INTEGER32 (105 | SYNTAX_MASK) #define OBJIDENTITY 106 /* * Beware of reaching SYNTAX_MASK (0x80) */ struct tok { const char *name; /* token name */ int len; /* length not counting nul */ int token; /* value */ int hash; /* hash of name */ struct tok *next; /* pointer to next in hash table */ }; static struct tok tokens[] = { {"obsolete", sizeof("obsolete") - 1, OBSOLETE} , {"Opaque", sizeof("Opaque") - 1, KW_OPAQUE} , {"optional", sizeof("optional") - 1, KW_OPTIONAL} , {"LAST-UPDATED", sizeof("LAST-UPDATED") - 1, LASTUPDATED} , {"ORGANIZATION", sizeof("ORGANIZATION") - 1, ORGANIZATION} , {"CONTACT-INFO", sizeof("CONTACT-INFO") - 1, CONTACTINFO} , {"MODULE-IDENTITY", sizeof("MODULE-IDENTITY") - 1, MODULEIDENTITY} , {"MODULE-COMPLIANCE", sizeof("MODULE-COMPLIANCE") - 1, COMPLIANCE} , {"DEFINITIONS", sizeof("DEFINITIONS") - 1, DEFINITIONS} , {"END", sizeof("END") - 1, END} , {"AUGMENTS", sizeof("AUGMENTS") - 1, AUGMENTS} , {"not-accessible", sizeof("not-accessible") - 1, NOACCESS} , {"write-only", sizeof("write-only") - 1, WRITEONLY} , {"NsapAddress", sizeof("NsapAddress") - 1, NSAPADDRESS} , {"UNITS", sizeof("Units") - 1, UNITS} , {"REFERENCE", sizeof("REFERENCE") - 1, REFERENCE} , {"NUM-ENTRIES", sizeof("NUM-ENTRIES") - 1, NUM_ENTRIES} , {"BITSTRING", sizeof("BITSTRING") - 1, BITSTRING} , {"BIT", sizeof("BIT") - 1, CONTINUE} , {"BITS", sizeof("BITS") - 1, BITSTRING} , {"Counter64", sizeof("Counter64") - 1, COUNTER64} , {"TimeTicks", sizeof("TimeTicks") - 1, TIMETICKS} , {"NOTIFICATION-TYPE", sizeof("NOTIFICATION-TYPE") - 1, NOTIFTYPE} , {"OBJECT-GROUP", sizeof("OBJECT-GROUP") - 1, OBJGROUP} , {"OBJECT-IDENTITY", sizeof("OBJECT-IDENTITY") - 1, OBJIDENTITY} , {"IDENTIFIER", sizeof("IDENTIFIER") - 1, IDENTIFIER} , {"OBJECT", sizeof("OBJECT") - 1, OBJECT} , {"NetworkAddress", sizeof("NetworkAddress") - 1, NETADDR} , {"Gauge", sizeof("Gauge") - 1, GAUGE} , {"Gauge32", sizeof("Gauge32") - 1, GAUGE} , {"Unsigned32", sizeof("Unsigned32") - 1, UNSIGNED32} , {"read-write", sizeof("read-write") - 1, READWRITE} , {"read-create", sizeof("read-create") - 1, READCREATE} , {"OCTETSTRING", sizeof("OCTETSTRING") - 1, OCTETSTR} , {"OCTET", sizeof("OCTET") - 1, CONTINUE} , {"OF", sizeof("OF") - 1, OF} , {"SEQUENCE", sizeof("SEQUENCE") - 1, SEQUENCE} , {"NULL", sizeof("NULL") - 1, NUL} , {"IpAddress", sizeof("IpAddress") - 1, IPADDR} , {"UInteger32", sizeof("UInteger32") - 1, UINTEGER32} , {"INTEGER", sizeof("INTEGER") - 1, INTEGER} , {"Integer32", sizeof("Integer32") - 1, INTEGER32} , {"Counter", sizeof("Counter") - 1, COUNTER} , {"Counter32", sizeof("Counter32") - 1, COUNTER} , {"read-only", sizeof("read-only") - 1, READONLY} , {"DESCRIPTION", sizeof("DESCRIPTION") - 1, DESCRIPTION} , {"INDEX", sizeof("INDEX") - 1, INDEX} , {"DEFVAL", sizeof("DEFVAL") - 1, DEFVAL} , {"deprecated", sizeof("deprecated") - 1, DEPRECATED} , {"SIZE", sizeof("SIZE") - 1, SIZE} , {"MAX-ACCESS", sizeof("MAX-ACCESS") - 1, ACCESS} , {"ACCESS", sizeof("ACCESS") - 1, ACCESS} , {"mandatory", sizeof("mandatory") - 1, MANDATORY} , {"current", sizeof("current") - 1, CURRENT} , {"STATUS", sizeof("STATUS") - 1, STATUS} , {"SYNTAX", sizeof("SYNTAX") - 1, SYNTAX} , {"OBJECT-TYPE", sizeof("OBJECT-TYPE") - 1, OBJTYPE} , {"TRAP-TYPE", sizeof("TRAP-TYPE") - 1, TRAPTYPE} , {"ENTERPRISE", sizeof("ENTERPRISE") - 1, ENTERPRISE} , {"BEGIN", sizeof("BEGIN") - 1, BEGIN} , {"IMPORTS", sizeof("IMPORTS") - 1, IMPORTS} , {"EXPORTS", sizeof("EXPORTS") - 1, EXPORTS} , {"accessible-for-notify", sizeof("accessible-for-notify") - 1, ACCNOTIFY} , {"TEXTUAL-CONVENTION", sizeof("TEXTUAL-CONVENTION") - 1, CONVENTION} , {"NOTIFICATION-GROUP", sizeof("NOTIFICATION-GROUP") - 1, NOTIFGROUP} , {"DISPLAY-HINT", sizeof("DISPLAY-HINT") - 1, DISPLAYHINT} , {"FROM", sizeof("FROM") - 1, FROM} , {"AGENT-CAPABILITIES", sizeof("AGENT-CAPABILITIES") - 1, AGENTCAP} , {"MACRO", sizeof("MACRO") - 1, MACRO} , {"IMPLIED", sizeof("IMPLIED") - 1, IMPLIED} , {"SUPPORTS", sizeof("SUPPORTS") - 1, SUPPORTS} , {"INCLUDES", sizeof("INCLUDES") - 1, INCLUDES} , {"VARIATION", sizeof("VARIATION") - 1, VARIATION} , {"REVISION", sizeof("REVISION") - 1, REVISION} , {"not-implemented", sizeof("not-implemented") - 1, NOTIMPL} , {"OBJECTS", sizeof("OBJECTS") - 1, OBJECTS} , {"NOTIFICATIONS", sizeof("NOTIFICATIONS") - 1, NOTIFICATIONS} , {"MODULE", sizeof("MODULE") - 1, MODULE} , {"MIN-ACCESS", sizeof("MIN-ACCESS") - 1, MINACCESS} , {"PRODUCT-RELEASE", sizeof("PRODUCT-RELEASE") - 1, PRODREL} , {"WRITE-SYNTAX", sizeof("WRITE-SYNTAX") - 1, WRSYNTAX} , {"CREATION-REQUIRES", sizeof("CREATION-REQUIRES") - 1, CREATEREQ} , {"MANDATORY-GROUPS", sizeof("MANDATORY-GROUPS") - 1, MANDATORYGROUPS} , {"GROUP", sizeof("GROUP") - 1, GROUP} , {"CHOICE", sizeof("CHOICE") - 1, CHOICE} , {"IMPLICIT", sizeof("IMPLICIT") - 1, IMPLICIT} , {"ObjectSyntax", sizeof("ObjectSyntax") - 1, OBJSYNTAX} , {"SimpleSyntax", sizeof("SimpleSyntax") - 1, SIMPLESYNTAX} , {"ApplicationSyntax", sizeof("ApplicationSyntax") - 1, APPSYNTAX} , {"ObjectName", sizeof("ObjectName") - 1, OBJNAME} , {"NotificationName", sizeof("NotificationName") - 1, NOTIFNAME} , {"VARIABLES", sizeof("VARIABLES") - 1, VARIABLES} , {NULL} }; static struct module_compatability *module_map_head; static struct module_compatability module_map[] = { {"RFC1065-SMI", "RFC1155-SMI", NULL, 0}, {"RFC1066-MIB", "RFC1156-MIB", NULL, 0}, /* * 'mib' -> 'mib-2' */ {"RFC1156-MIB", "RFC1158-MIB", NULL, 0}, /* * 'snmpEnableAuthTraps' -> 'snmpEnableAuthenTraps' */ {"RFC1158-MIB", "RFC1213-MIB", NULL, 0}, /* * 'nullOID' -> 'zeroDotZero' */ {"RFC1155-SMI", "SNMPv2-SMI", NULL, 0}, {"RFC1213-MIB", "SNMPv2-SMI", "mib-2", 0}, {"RFC1213-MIB", "SNMPv2-MIB", "sys", 3}, {"RFC1213-MIB", "IF-MIB", "if", 2}, {"RFC1213-MIB", "IP-MIB", "ip", 2}, {"RFC1213-MIB", "IP-MIB", "icmp", 4}, {"RFC1213-MIB", "TCP-MIB", "tcp", 3}, {"RFC1213-MIB", "UDP-MIB", "udp", 3}, {"RFC1213-MIB", "SNMPv2-SMI", "transmission", 0}, {"RFC1213-MIB", "SNMPv2-MIB", "snmp", 4}, {"RFC1231-MIB", "TOKENRING-MIB", NULL, 0}, {"RFC1271-MIB", "RMON-MIB", NULL, 0}, {"RFC1286-MIB", "SOURCE-ROUTING-MIB", "dot1dSr", 7}, {"RFC1286-MIB", "BRIDGE-MIB", NULL, 0}, {"RFC1315-MIB", "FRAME-RELAY-DTE-MIB", NULL, 0}, {"RFC1316-MIB", "CHARACTER-MIB", NULL, 0}, {"RFC1406-MIB", "DS1-MIB", NULL, 0}, {"RFC-1213", "RFC1213-MIB", NULL, 0}, }; #define MODULE_NOT_FOUND 0 #define MODULE_LOADED_OK 1 #define MODULE_ALREADY_LOADED 2 /* * #define MODULE_LOAD_FAILED 3 */ #define MODULE_LOAD_FAILED MODULE_NOT_FOUND #define HASHSIZE 32 #define BUCKET(x) (x & (HASHSIZE-1)) #define NHASHSIZE 128 #define NBUCKET(x) (x & (NHASHSIZE-1)) static struct tok *buckets[HASHSIZE]; static struct node *nbuckets[NHASHSIZE]; static struct tree *tbuckets[NHASHSIZE]; static struct module *module_head = NULL; struct node *orphan_nodes = NULL; struct tree *tree_head = NULL; #define NUMBER_OF_ROOT_NODES 3 static struct module_import root_imports[NUMBER_OF_ROOT_NODES]; static int current_module = 0; static int max_module = 0; static char *last_err_module = 0; /* no repeats on "Cannot find module..." */ static void tree_from_node(struct tree *tp, struct node *np); static void do_subtree(struct tree *, struct node **); static void do_linkup(struct module *, struct node *); static void dump_module_list(void); static int get_token(FILE *, char *, int); static int parseQuoteString(FILE *, char *, int); static int tossObjectIdentifier(FILE *); static int name_hash(const char *); static void init_node_hash(struct node *); static void print_error(const char *, const char *, int); static void free_tree(struct tree *); static void free_partial_tree(struct tree *, int); static void free_node(struct node *); static void build_translation_table(void); static void init_tree_roots(void); static void merge_anon_children(struct tree *, struct tree *); static void unlink_tbucket(struct tree *); static void unlink_tree(struct tree *); static int getoid(FILE *, struct subid_s *, int); static struct node *parse_objectid(FILE *, char *); static int get_tc(const char *, int, int *, struct enum_list **, struct range_list **, char **); static int get_tc_index(const char *, int); static struct enum_list *parse_enumlist(FILE *, struct enum_list **); static struct range_list *parse_ranges(FILE * fp, struct range_list **); static struct node *parse_asntype(FILE *, char *, int *, char *); static struct node *parse_objecttype(FILE *, char *); static struct node *parse_objectgroup(FILE *, char *, int, struct objgroup **); static struct node *parse_notificationDefinition(FILE *, char *); static struct node *parse_trapDefinition(FILE *, char *); static struct node *parse_compliance(FILE *, char *); static struct node *parse_capabilities(FILE *, char *); static struct node *parse_moduleIdentity(FILE *, char *); static struct node *parse_macro(FILE *, char *); static void parse_imports(FILE *); static struct node *parse(FILE *, struct node *); static int read_module_internal(const char *); static int read_module_replacements(const char *); static int read_import_replacements(const char *, struct module_import *); static void new_module(const char *, const char *); static struct node *merge_parse_objectid(struct node *, FILE *, char *); static struct index_list *getIndexes(FILE * fp, struct index_list **); static struct varbind_list *getVarbinds(FILE * fp, struct varbind_list **); static void free_indexes(struct index_list **); static void free_varbinds(struct varbind_list **); static void free_ranges(struct range_list **); static void free_enums(struct enum_list **); static struct range_list *copy_ranges(struct range_list *); static struct enum_list *copy_enums(struct enum_list *); static u_int compute_match(const char *search_base, const char *key); void snmp_mib_toggle_options_usage(const char *lead, FILE * outf) { fprintf(outf, "%su: %sallow the use of underlines in MIB symbols\n", lead, ((netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_PARSE_LABEL)) ? "dis" : "")); fprintf(outf, "%sc: %sallow the use of \"--\" to terminate comments\n", lead, ((netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_COMMENT_TERM)) ? "" : "dis")); fprintf(outf, "%sd: %ssave the DESCRIPTIONs of the MIB objects\n", lead, ((netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) ? "do not " : "")); fprintf(outf, "%se: disable errors when MIB symbols conflict\n", lead); fprintf(outf, "%sw: enable warnings when MIB symbols conflict\n", lead); fprintf(outf, "%sW: enable detailed warnings when MIB symbols conflict\n", lead); fprintf(outf, "%sR: replace MIB symbols from latest module\n", lead); } char * snmp_mib_toggle_options(char *options) { if (options) { while (*options) { switch (*options) { case 'u': netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_PARSE_LABEL, !netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_PARSE_LABEL)); break; case 'c': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_COMMENT_TERM); break; case 'e': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_ERRORS); break; case 'w': netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS, 1); break; case 'W': netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS, 2); break; case 'd': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS); break; case 'R': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_REPLACE); break; default: /* * return at the unknown option */ return options; } options++; } } return NULL; } static int name_hash(const char *name) { int hash = 0; const char *cp; if (!name) return 0; for (cp = name; *cp; cp++) hash += tolower(*cp); return (hash); } void netsnmp_init_mib_internals(void) { register struct tok *tp; register int b, i; int max_modc; if (tree_head) return; /* * Set up hash list of pre-defined tokens */ memset(buckets, 0, sizeof(buckets)); for (tp = tokens; tp->name; tp++) { tp->hash = name_hash(tp->name); b = BUCKET(tp->hash); if (buckets[b]) tp->next = buckets[b]; /* BUG ??? */ buckets[b] = tp; } /* * Initialise other internal structures */ max_modc = sizeof(module_map) / sizeof(module_map[0]) - 1; for (i = 0; i < max_modc; ++i) module_map[i].next = &(module_map[i + 1]); module_map[max_modc].next = NULL; module_map_head = module_map; memset(nbuckets, 0, sizeof(nbuckets)); memset(tbuckets, 0, sizeof(tbuckets)); memset(tclist, 0, MAXTC * sizeof(struct tc)); build_translation_table(); init_tree_roots(); /* Set up initial roots */ /* * Relies on 'add_mibdir' having set up the modules */ } #ifndef NETSNMP_CLEAN_NAMESPACE void init_mib_internals(void) { netsnmp_init_mib_internals(); } #endif static void init_node_hash(struct node *nodes) { struct node *np, *nextp; int hash; memset(nbuckets, 0, sizeof(nbuckets)); for (np = nodes; np;) { nextp = np->next; hash = NBUCKET(name_hash(np->parent)); np->next = nbuckets[hash]; nbuckets[hash] = np; np = nextp; } } static int erroneousMibs = 0; int get_mib_parse_error_count(void) { return erroneousMibs; } static void print_error(const char *str, const char *token, int type) { erroneousMibs++; DEBUGMSGTL(("parse-mibs", "\n")); if (type == ENDOFFILE) snmp_log(LOG_ERR, "%s (EOF): At line %d in %s\n", str, mibLine, File); else if (token && *token) snmp_log(LOG_ERR, "%s (%s): At line %d in %s\n", str, token, mibLine, File); else snmp_log(LOG_ERR, "%s: At line %d in %s\n", str, mibLine, File); } static void print_module_not_found(const char *cp) { if (!last_err_module || strcmp(cp, last_err_module)) print_error("Cannot find module", cp, CONTINUE); if (last_err_module) free(last_err_module); last_err_module = strdup(cp); } static struct node * alloc_node(int modid) { struct node *np; np = (struct node *) calloc(1, sizeof(struct node)); if (np) { np->tc_index = -1; np->modid = modid; np->filename = strdup(File); np->lineno = mibLine; } return np; } static void unlink_tbucket(struct tree *tp) { int hash = NBUCKET(name_hash(tp->label)); struct tree *otp = NULL, *ntp = tbuckets[hash]; while (ntp && ntp != tp) { otp = ntp; ntp = ntp->next; } if (!ntp) snmp_log(LOG_EMERG, "Can't find %s in tbuckets\n", tp->label); else if (otp) otp->next = ntp->next; else tbuckets[hash] = tp->next; } static void unlink_tree(struct tree *tp) { struct tree *otp = NULL, *ntp = tp->parent; if (!ntp) { /* this tree has no parent */ DEBUGMSGTL(("unlink_tree", "Tree node %s has no parent\n", tp->label)); } else { ntp = ntp->child_list; while (ntp && ntp != tp) { otp = ntp; ntp = ntp->next_peer; } if (!ntp) snmp_log(LOG_EMERG, "Can't find %s in %s's children\n", tp->label, tp->parent->label); else if (otp) otp->next_peer = ntp->next_peer; else tp->parent->child_list = tp->next_peer; } if (tree_head == tp) tree_head = tp->next_peer; } static void free_partial_tree(struct tree *tp, int keep_label) { if (!tp) return; /* * remove the data from this tree node */ free_enums(&tp->enums); free_ranges(&tp->ranges); free_indexes(&tp->indexes); free_varbinds(&tp->varbinds); if (!keep_label) SNMP_FREE(tp->label); SNMP_FREE(tp->hint); SNMP_FREE(tp->units); SNMP_FREE(tp->description); SNMP_FREE(tp->reference); SNMP_FREE(tp->augments); SNMP_FREE(tp->defaultValue); } /* * free a tree node. Note: the node must already have been unlinked * from the tree when calling this routine */ static void free_tree(struct tree *Tree) { if (!Tree) return; unlink_tbucket(Tree); free_partial_tree(Tree, FALSE); if (Tree->number_modules > 1) free((char *) Tree->module_list); free((char *) Tree); } static void free_node(struct node *np) { if (!np) return; free_enums(&np->enums); free_ranges(&np->ranges); free_indexes(&np->indexes); free_varbinds(&np->varbinds); if (np->label) free(np->label); if (np->hint) free(np->hint); if (np->units) free(np->units); if (np->description) free(np->description); if (np->reference) free(np->reference); if (np->defaultValue) free(np->defaultValue); if (np->parent) free(np->parent); if (np->augments) free(np->augments); if (np->filename) free(np->filename); free((char *) np); } #ifdef TEST static void print_nodes(FILE * fp, struct node *root) { extern void xmalloc_stats(FILE *); struct enum_list *ep; struct index_list *ip; struct range_list *rp; struct varbind_list *vp; struct node *np; for (np = root; np; np = np->next) { fprintf(fp, "%s ::= { %s %ld } (%d)\n", np->label, np->parent, np->subid, np->type); if (np->tc_index >= 0) fprintf(fp, " TC = %s\n", tclist[np->tc_index].descriptor); if (np->enums) { fprintf(fp, " Enums: \n"); for (ep = np->enums; ep; ep = ep->next) { fprintf(fp, " %s(%d)\n", ep->label, ep->value); } } if (np->ranges) { fprintf(fp, " Ranges: \n"); for (rp = np->ranges; rp; rp = rp->next) { fprintf(fp, " %d..%d\n", rp->low, rp->high); } } if (np->indexes) { fprintf(fp, " Indexes: \n"); for (ip = np->indexes; ip; ip = ip->next) { fprintf(fp, " %s\n", ip->ilabel); } } if (np->augments) fprintf(fp, " Augments: %s\n", np->augments); if (np->varbinds) { fprintf(fp, " Varbinds: \n"); for (vp = np->varbinds; vp; vp = vp->next) { fprintf(fp, " %s\n", vp->vblabel); } } if (np->hint) fprintf(fp, " Hint: %s\n", np->hint); if (np->units) fprintf(fp, " Units: %s\n", np->units); if (np->defaultValue) fprintf(fp, " DefaultValue: %s\n", np->defaultValue); } } #endif void print_subtree(FILE * f, struct tree *tree, int count) { struct tree *tp; int i; char modbuf[256]; for (i = 0; i < count; i++) fprintf(f, " "); fprintf(f, "Children of %s(%ld):\n", tree->label, tree->subid); count++; for (tp = tree->child_list; tp; tp = tp->next_peer) { for (i = 0; i < count; i++) fprintf(f, " "); fprintf(f, "%s:%s(%ld) type=%d", module_name(tp->module_list[0], modbuf), tp->label, tp->subid, tp->type); if (tp->tc_index != -1) fprintf(f, " tc=%d", tp->tc_index); if (tp->hint) fprintf(f, " hint=%s", tp->hint); if (tp->units) fprintf(f, " units=%s", tp->units); if (tp->number_modules > 1) { fprintf(f, " modules:"); for (i = 1; i < tp->number_modules; i++) fprintf(f, " %s", module_name(tp->module_list[i], modbuf)); } fprintf(f, "\n"); } for (tp = tree->child_list; tp; tp = tp->next_peer) { if (tp->child_list) print_subtree(f, tp, count); } } void print_ascii_dump_tree(FILE * f, struct tree *tree, int count) { struct tree *tp; count++; for (tp = tree->child_list; tp; tp = tp->next_peer) { fprintf(f, "%s OBJECT IDENTIFIER ::= { %s %ld }\n", tp->label, tree->label, tp->subid); } for (tp = tree->child_list; tp; tp = tp->next_peer) { if (tp->child_list) print_ascii_dump_tree(f, tp, count); } } static int translation_table[256]; static void build_translation_table() { int count; for (count = 0; count < 256; count++) { switch (count) { case OBJID: translation_table[count] = TYPE_OBJID; break; case OCTETSTR: translation_table[count] = TYPE_OCTETSTR; break; case INTEGER: translation_table[count] = TYPE_INTEGER; break; case NETADDR: translation_table[count] = TYPE_NETADDR; break; case IPADDR: translation_table[count] = TYPE_IPADDR; break; case COUNTER: translation_table[count] = TYPE_COUNTER; break; case GAUGE: translation_table[count] = TYPE_GAUGE; break; case TIMETICKS: translation_table[count] = TYPE_TIMETICKS; break; case KW_OPAQUE: translation_table[count] = TYPE_OPAQUE; break; case NUL: translation_table[count] = TYPE_NULL; break; case COUNTER64: translation_table[count] = TYPE_COUNTER64; break; case BITSTRING: translation_table[count] = TYPE_BITSTRING; break; case NSAPADDRESS: translation_table[count] = TYPE_NSAPADDRESS; break; case INTEGER32: translation_table[count] = TYPE_INTEGER32; break; case UINTEGER32: translation_table[count] = TYPE_UINTEGER; break; case UNSIGNED32: translation_table[count] = TYPE_UNSIGNED32; break; case TRAPTYPE: translation_table[count] = TYPE_TRAPTYPE; break; case NOTIFTYPE: translation_table[count] = TYPE_NOTIFTYPE; break; case NOTIFGROUP: translation_table[count] = TYPE_NOTIFGROUP; break; case OBJGROUP: translation_table[count] = TYPE_OBJGROUP; break; case MODULEIDENTITY: translation_table[count] = TYPE_MODID; break; case OBJIDENTITY: translation_table[count] = TYPE_OBJIDENTITY; break; case AGENTCAP: translation_table[count] = TYPE_AGENTCAP; break; case COMPLIANCE: translation_table[count] = TYPE_MODCOMP; break; default: translation_table[count] = TYPE_OTHER; break; } } } static void init_tree_roots() { struct tree *tp, *lasttp; int base_modid; int hash; base_modid = which_module("SNMPv2-SMI"); if (base_modid == -1) base_modid = which_module("RFC1155-SMI"); if (base_modid == -1) base_modid = which_module("RFC1213-MIB"); /* * build root node */ tp = (struct tree *) calloc(1, sizeof(struct tree)); if (tp == NULL) return; tp->label = strdup("joint-iso-ccitt"); tp->modid = base_modid; tp->number_modules = 1; tp->module_list = &(tp->modid); tp->subid = 2; tp->tc_index = -1; set_function(tp); /* from mib.c */ hash = NBUCKET(name_hash(tp->label)); tp->next = tbuckets[hash]; tbuckets[hash] = tp; lasttp = tp; root_imports[0].label = strdup(tp->label); root_imports[0].modid = base_modid; /* * build root node */ tp = (struct tree *) calloc(1, sizeof(struct tree)); if (tp == NULL) return; tp->next_peer = lasttp; tp->label = strdup("ccitt"); tp->modid = base_modid; tp->number_modules = 1; tp->module_list = &(tp->modid); tp->subid = 0; tp->tc_index = -1; set_function(tp); /* from mib.c */ hash = NBUCKET(name_hash(tp->label)); tp->next = tbuckets[hash]; tbuckets[hash] = tp; lasttp = tp; root_imports[1].label = strdup(tp->label); root_imports[1].modid = base_modid; /* * build root node */ tp = (struct tree *) calloc(1, sizeof(struct tree)); if (tp == NULL) return; tp->next_peer = lasttp; tp->label = strdup("iso"); tp->modid = base_modid; tp->number_modules = 1; tp->module_list = &(tp->modid); tp->subid = 1; tp->tc_index = -1; set_function(tp); /* from mib.c */ hash = NBUCKET(name_hash(tp->label)); tp->next = tbuckets[hash]; tbuckets[hash] = tp; lasttp = tp; root_imports[2].label = strdup(tp->label); root_imports[2].modid = base_modid; tree_head = tp; } #ifdef STRICT_MIB_PARSEING #define label_compare strcasecmp #else #define label_compare strcmp #endif struct tree * find_tree_node(const char *name, int modid) { struct tree *tp, *headtp; int count, *int_p; if (!name || !*name) return (NULL); headtp = tbuckets[NBUCKET(name_hash(name))]; for (tp = headtp; tp; tp = tp->next) { if (tp->label && !label_compare(tp->label, name)) { if (modid == -1) /* Any module */ return (tp); for (int_p = tp->module_list, count = 0; count < tp->number_modules; ++count, ++int_p) if (*int_p == modid) return (tp); } } return (NULL); } /* * computes a value which represents how close name1 is to name2. * * high scores mean a worse match. * * (yes, the algorithm sucks!) */ #define MAX_BAD 0xffffff static u_int compute_match(const char *search_base, const char *key) { #if defined(HAVE_REGEX_H) && defined(HAVE_REGCOMP) int rc; regex_t parsetree; regmatch_t pmatch; rc = regcomp(&parsetree, key, REG_ICASE | REG_EXTENDED); if (rc == 0) rc = regexec(&parsetree, search_base, 1, &pmatch, 0); regfree(&parsetree); if (rc == 0) { /* * found */ return pmatch.rm_so; } #else /* use our own wildcard matcher */ /* * first find the longest matching substring (ick) */ char *first = NULL, *result = NULL, *entry; const char *position; char *newkey = strdup(key); char *st; entry = strtok_r(newkey, "*", &st); position = search_base; while (entry) { result = strcasestr(position, entry); if (result == NULL) { free(newkey); return MAX_BAD; } if (first == NULL) first = result; position = result + strlen(entry); entry = strtok_r(NULL, "*", &st); } free(newkey); if (result) return (first - search_base); #endif /* * not found */ return MAX_BAD; } /* * Find the tree node that best matches the pattern string. * Use the "reported" flag such that only one match * is attempted for every node. * * Warning! This function may recurse. * * Caller _must_ invoke clear_tree_flags before first call * to this function. This function may be called multiple times * to ensure that the entire tree is traversed. */ struct tree * find_best_tree_node(const char *pattrn, struct tree *tree_top, u_int * match) { struct tree *tp, *best_so_far = NULL, *retptr; u_int old_match = MAX_BAD, new_match = MAX_BAD; if (!pattrn || !*pattrn) return (NULL); if (!tree_top) tree_top = get_tree_head(); for (tp = tree_top; tp; tp = tp->next_peer) { if (!tp->reported && tp->label) new_match = compute_match(tp->label, pattrn); tp->reported = 1; if (new_match < old_match) { best_so_far = tp; old_match = new_match; } if (new_match == 0) break; /* this is the best result we can get */ if (tp->child_list) { retptr = find_best_tree_node(pattrn, tp->child_list, &new_match); if (new_match < old_match) { best_so_far = retptr; old_match = new_match; } if (new_match == 0) break; /* this is the best result we can get */ } } if (match) *match = old_match; return (best_so_far); } static void merge_anon_children(struct tree *tp1, struct tree *tp2) /* * NB: tp1 is the 'anonymous' node */ { struct tree *child1, *child2, *previous; for (child1 = tp1->child_list; child1;) { for (child2 = tp2->child_list, previous = NULL; child2; previous = child2, child2 = child2->next_peer) { if (child1->subid == child2->subid) { /* * Found 'matching' children, * so merge them */ if (!strncmp(child1->label, ANON, ANON_LEN)) { merge_anon_children(child1, child2); child1->child_list = NULL; previous = child1; /* Finished with 'child1' */ child1 = child1->next_peer; free_tree(previous); goto next; } else if (!strncmp(child2->label, ANON, ANON_LEN)) { merge_anon_children(child2, child1); if (previous) previous->next_peer = child2->next_peer; else tp2->child_list = child2->next_peer; free_tree(child2); previous = child1; /* Move 'child1' to 'tp2' */ child1 = child1->next_peer; previous->next_peer = tp2->child_list; tp2->child_list = previous; for (previous = tp2->child_list; previous; previous = previous->next_peer) previous->parent = tp2; goto next; } else if (!label_compare(child1->label, child2->label)) { if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "Warning: %s.%ld is both %s and %s (%s)\n", tp2->label, child1->subid, child1->label, child2->label, File); } continue; } else { /* * Two copies of the same node. * 'child2' adopts the children of 'child1' */ if (child2->child_list) { for (previous = child2->child_list; previous->next_peer; previous = previous->next_peer); /* Find the end of the list */ previous->next_peer = child1->child_list; } else child2->child_list = child1->child_list; for (previous = child1->child_list; previous; previous = previous->next_peer) previous->parent = child2; child1->child_list = NULL; previous = child1; /* Finished with 'child1' */ child1 = child1->next_peer; free_tree(previous); goto next; } } } /* * If no match, move 'child1' to 'tp2' child_list */ if (child1) { previous = child1; child1 = child1->next_peer; previous->parent = tp2; previous->next_peer = tp2->child_list; tp2->child_list = previous; } next:; } } /* * Find all the children of root in the list of nodes. Link them into the * tree and out of the nodes list. */ static void do_subtree(struct tree *root, struct node **nodes) { struct tree *tp, *anon_tp = NULL; struct tree *xroot = root; struct node *np, **headp; struct node *oldnp = NULL, *child_list = NULL, *childp = NULL; int hash; int *int_p; while (xroot->next_peer && xroot->next_peer->subid == root->subid) { #if 0 printf("xroot: %s.%s => %s\n", xroot->parent->label, xroot->label, xroot->next_peer->label); #endif xroot = xroot->next_peer; } tp = root; headp = &nbuckets[NBUCKET(name_hash(tp->label))]; /* * Search each of the nodes for one whose parent is root, and * move each into a separate list. */ for (np = *headp; np; np = np->next) { if (!label_compare(tp->label, np->parent)) { /* * take this node out of the node list */ if (oldnp == NULL) { *headp = np->next; /* fix root of node list */ } else { oldnp->next = np->next; /* link around this node */ } if (child_list) childp->next = np; else child_list = np; childp = np; } else { oldnp = np; } } if (childp) childp->next = NULL; /* * Take each element in the child list and place it into the tree. */ for (np = child_list; np; np = np->next) { struct tree *otp = NULL; struct tree *xxroot = xroot; anon_tp = NULL; tp = xroot->child_list; if (np->subid == -1) { /* * name ::= { parent } */ np->subid = xroot->subid; tp = xroot; xxroot = xroot->parent; } while (tp) { if (tp->subid == np->subid) break; else { otp = tp; tp = tp->next_peer; } } if (tp) { if (!label_compare(tp->label, np->label)) { /* * Update list of modules */ int_p = (int *) malloc((tp->number_modules + 1) * sizeof(int)); if (int_p == NULL) return; memcpy(int_p, tp->module_list, tp->number_modules * sizeof(int)); int_p[tp->number_modules] = np->modid; if (tp->number_modules > 1) free((char *) tp->module_list); ++tp->number_modules; tp->module_list = int_p; if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_REPLACE)) { /* * Replace from node */ tree_from_node(tp, np); } /* * Handle children */ do_subtree(tp, nodes); continue; } if (!strncmp(np->label, ANON, ANON_LEN) || !strncmp(tp->label, ANON, ANON_LEN)) { anon_tp = tp; /* Need to merge these two trees later */ } else if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "Warning: %s.%ld is both %s and %s (%s)\n", root->label, np->subid, tp->label, np->label, File); } } tp = (struct tree *) calloc(1, sizeof(struct tree)); if (tp == NULL) return; tp->parent = xxroot; tp->modid = np->modid; tp->number_modules = 1; tp->module_list = &(tp->modid); tree_from_node(tp, np); tp->next_peer = otp ? otp->next_peer : xxroot->child_list; if (otp) otp->next_peer = tp; else xxroot->child_list = tp; hash = NBUCKET(name_hash(tp->label)); tp->next = tbuckets[hash]; tbuckets[hash] = tp; do_subtree(tp, nodes); if (anon_tp) { if (!strncmp(tp->label, ANON, ANON_LEN)) { /* * The new node is anonymous, * so merge it with the existing one. */ merge_anon_children(tp, anon_tp); /* * unlink and destroy tp */ unlink_tree(tp); free_tree(tp); } else if (!strncmp(anon_tp->label, ANON, ANON_LEN)) { struct tree *ntp; /* * The old node was anonymous, * so merge it with the existing one, * and fill in the full information. */ merge_anon_children(anon_tp, tp); /* * unlink anon_tp from the hash */ unlink_tbucket(anon_tp); /* * get rid of old contents of anon_tp */ free_partial_tree(anon_tp, FALSE); /* * put in the current information */ anon_tp->label = tp->label; anon_tp->child_list = tp->child_list; anon_tp->modid = tp->modid; anon_tp->tc_index = tp->tc_index; anon_tp->type = tp->type; anon_tp->enums = tp->enums; anon_tp->indexes = tp->indexes; anon_tp->augments = tp->augments; anon_tp->varbinds = tp->varbinds; anon_tp->ranges = tp->ranges; anon_tp->hint = tp->hint; anon_tp->units = tp->units; anon_tp->description = tp->description; anon_tp->reference = tp->reference; anon_tp->defaultValue = tp->defaultValue; anon_tp->parent = tp->parent; set_function(anon_tp); /* * update parent pointer in moved children */ ntp = anon_tp->child_list; while (ntp) { ntp->parent = anon_tp; ntp = ntp->next_peer; } /* * hash in anon_tp in its new place */ hash = NBUCKET(name_hash(anon_tp->label)); anon_tp->next = tbuckets[hash]; tbuckets[hash] = anon_tp; /* * unlink and destroy tp */ unlink_tbucket(tp); unlink_tree(tp); free(tp); } else { /* * Uh? One of these two should have been anonymous! */ if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "Warning: expected anonymous node (either %s or %s) in %s\n", tp->label, anon_tp->label, File); } } anon_tp = NULL; } } /* * free all nodes that were copied into tree */ oldnp = NULL; for (np = child_list; np; np = np->next) { if (oldnp) free_node(oldnp); oldnp = np; } if (oldnp) free_node(oldnp); } static void do_linkup(struct module *mp, struct node *np) { struct module_import *mip; struct node *onp, *oldp, *newp; struct tree *tp; int i, more; /* * All modules implicitly import * the roots of the tree */ if (snmp_get_do_debugging() > 1) dump_module_list(); DEBUGMSGTL(("parse-mibs", "Processing IMPORTS for module %d %s\n", mp->modid, mp->name)); if (mp->no_imports == 0) { mp->no_imports = NUMBER_OF_ROOT_NODES; mp->imports = root_imports; } /* * Build the tree */ init_node_hash(np); for (i = 0, mip = mp->imports; i < mp->no_imports; ++i, ++mip) { char modbuf[256]; DEBUGMSGTL(("parse-mibs", " Processing import: %s\n", mip->label)); if (get_tc_index(mip->label, mip->modid) != -1) continue; tp = find_tree_node(mip->label, mip->modid); if (!tp) { snmp_log(LOG_WARNING, "Did not find '%s' in module %s (%s)\n", mip->label, module_name(mip->modid, modbuf), File); continue; } do_subtree(tp, &np); } /* * If any nodes left over, * check that they're not the result of a "fully qualified" * name, and then add them to the list of orphans */ if (!np) return; for (tp = tree_head; tp; tp = tp->next_peer) do_subtree(tp, &np); if (!np) return; /* * quietly move all internal references to the orphan list */ oldp = orphan_nodes; do { for (i = 0; i < NHASHSIZE; i++) for (onp = nbuckets[i]; onp; onp = onp->next) { struct node *op = NULL; int hash = NBUCKET(name_hash(onp->label)); np = nbuckets[hash]; while (np) { if (label_compare(onp->label, np->parent)) { op = np; np = np->next; } else { if (op) op->next = np->next; else nbuckets[hash] = np->next; np->next = orphan_nodes; orphan_nodes = np; op = NULL; np = nbuckets[hash]; } } } newp = orphan_nodes; more = 0; for (onp = orphan_nodes; onp != oldp; onp = onp->next) { struct node *op = NULL; int hash = NBUCKET(name_hash(onp->label)); np = nbuckets[hash]; while (np) { if (label_compare(onp->label, np->parent)) { op = np; np = np->next; } else { if (op) op->next = np->next; else nbuckets[hash] = np->next; np->next = orphan_nodes; orphan_nodes = np; op = NULL; np = nbuckets[hash]; more = 1; } } } oldp = newp; } while (more); /* * complain about left over nodes */ for (np = orphan_nodes; np && np->next; np = np->next); /* find the end of the orphan list */ for (i = 0; i < NHASHSIZE; i++) if (nbuckets[i]) { if (orphan_nodes) onp = np->next = nbuckets[i]; else onp = orphan_nodes = nbuckets[i]; nbuckets[i] = NULL; while (onp) { snmp_log(LOG_WARNING, "Unlinked OID in %s: %s ::= { %s %ld }\n", (mp->name ? mp->name : "<no module>"), (onp->label ? onp->label : "<no label>"), (onp->parent ? onp->parent : "<no parent>"), onp->subid); snmp_log(LOG_WARNING, "Undefined identifier: %s near line %d of %s\n", (onp->parent ? onp->parent : "<no parent>"), onp->lineno, onp->filename); np = onp; onp = onp->next; } } return; } /* * Takes a list of the form: * { iso org(3) dod(6) 1 } * and creates several nodes, one for each parent-child pair. * Returns 0 on error. */ static int getoid(FILE * fp, struct subid_s *id, /* an array of subids */ int length) { /* the length of the array */ register int count; int type; char token[MAXTOKEN]; if ((type = get_token(fp, token, MAXTOKEN)) != LEFTBRACKET) { print_error("Expected \"{\"", token, type); return 0; } type = get_token(fp, token, MAXTOKEN); for (count = 0; count < length; count++, id++) { id->label = NULL; id->modid = current_module; id->subid = -1; if (type == RIGHTBRACKET) return count; if (type == LABEL) { /* * this entry has a label */ id->label = strdup(token); type = get_token(fp, token, MAXTOKEN); if (type == LEFTPAREN) { type = get_token(fp, token, MAXTOKEN); if (type == NUMBER) { id->subid = strtoul(token, NULL, 10); if ((type = get_token(fp, token, MAXTOKEN)) != RIGHTPAREN) { print_error("Expected a closing parenthesis", token, type); return 0; } } else { print_error("Expected a number", token, type); return 0; } } else { continue; } } else if (type == NUMBER) { /* * this entry has just an integer sub-identifier */ id->subid = strtoul(token, NULL, 10); } else { print_error("Expected label or number", token, type); return 0; } type = get_token(fp, token, MAXTOKEN); } print_error("Too long OID", token, type); return 0; } /* * Parse a sequence of object subidentifiers for the given name. * The "label OBJECT IDENTIFIER ::=" portion has already been parsed. * * The majority of cases take this form : * label OBJECT IDENTIFIER ::= { parent 2 } * where a parent label and a child subidentifier number are specified. * * Variations on the theme include cases where a number appears with * the parent, or intermediate subidentifiers are specified by label, * by number, or both. * * Here are some representative samples : * internet OBJECT IDENTIFIER ::= { iso org(3) dod(6) 1 } * mgmt OBJECT IDENTIFIER ::= { internet 2 } * rptrInfoHealth OBJECT IDENTIFIER ::= { snmpDot3RptrMgt 0 4 } * * Here is a very rare form : * iso OBJECT IDENTIFIER ::= { 1 } * * Returns NULL on error. When this happens, memory may be leaked. */ static struct node * parse_objectid(FILE * fp, char *name) { register int count; register struct subid_s *op, *nop; int length; struct subid_s loid[32]; struct node *np, *root = NULL, *oldnp = NULL; struct tree *tp; if ((length = getoid(fp, loid, 32)) == 0) { print_error("Bad object identifier", NULL, CONTINUE); return NULL; } /* * Handle numeric-only object identifiers, * by labelling the first sub-identifier */ op = loid; if (!op->label) { if (length == 1) { print_error("Attempt to define a root oid", name, OBJECT); return NULL; } for (tp = tree_head; tp; tp = tp->next_peer) if ((int) tp->subid == op->subid) { op->label = strdup(tp->label); break; } } /* * Handle "label OBJECT-IDENTIFIER ::= { subid }" */ if (length == 1) { op = loid; np = alloc_node(op->modid); if (np == NULL) return (NULL); np->subid = op->subid; np->label = strdup(name); np->parent = op->label; return np; } /* * For each parent-child subid pair in the subid array, * create a node and link it into the node list. */ for (count = 0, op = loid, nop = loid + 1; count < (length - 1); count++, op++, nop++) { /* * every node must have parent's name and child's name or number */ /* * XX the next statement is always true -- does it matter ?? */ if (op->label && (nop->label || (nop->subid != -1))) { np = alloc_node(nop->modid); if (np == NULL) return (NULL); if (root == NULL) root = np; np->parent = strdup(op->label); if (count == (length - 2)) { /* * The name for this node is the label for this entry */ np->label = strdup(name); } else { if (!nop->label) { nop->label = (char *) malloc(20 + ANON_LEN); if (nop->label == NULL) return (NULL); sprintf(nop->label, "%s%d", ANON, anonymous++); } np->label = strdup(nop->label); } if (nop->subid != -1) np->subid = nop->subid; else print_error("Warning: This entry is pretty silly", np->label, CONTINUE); /* * set up next entry */ if (oldnp) oldnp->next = np; oldnp = np; } /* end if(op->label... */ } /* * free the loid array */ for (count = 0, op = loid; count < length; count++, op++) { if (op->label) free(op->label); } return root; } static int get_tc(const char *descriptor, int modid, int *tc_index, struct enum_list **ep, struct range_list **rp, char **hint) { int i; struct tc *tcp; i = get_tc_index(descriptor, modid); if (tc_index) *tc_index = i; if (i != -1) { tcp = &tclist[i]; if (ep) { free_enums(ep); *ep = copy_enums(tcp->enums); } if (rp) { free_ranges(rp); *rp = copy_ranges(tcp->ranges); } if (hint) { if (*hint) free(*hint); *hint = (tcp->hint ? strdup(tcp->hint) : NULL); } return tcp->type; } return LABEL; } /* * return index into tclist of given TC descriptor * return -1 if not found */ static int get_tc_index(const char *descriptor, int modid) { int i; struct tc *tcp; struct module *mp; struct module_import *mip; /* * Check that the descriptor isn't imported * by searching the import list */ for (mp = module_head; mp; mp = mp->next) if (mp->modid == modid) break; if (mp) for (i = 0, mip = mp->imports; i < mp->no_imports; ++i, ++mip) { if (!label_compare(mip->label, descriptor)) { /* * Found it - so amend the module ID */ modid = mip->modid; break; } } for (i = 0, tcp = tclist; i < MAXTC; i++, tcp++) { if (tcp->type == 0) break; if (!label_compare(descriptor, tcp->descriptor) && ((modid == tcp->modid) || (modid == -1))) { return i; } } return -1; } /* * translate integer tc_index to string identifier from tclist * * * * Returns pointer to string in table (should not be modified) or NULL */ const char * get_tc_descriptor(int tc_index) { if (tc_index < 0 || tc_index >= MAXTC) return NULL; return (tclist[tc_index].descriptor); } const char * get_tc_description(int tc_index) { if (tc_index < 0 || tc_index >= MAXTC) return NULL; return (tclist[tc_index].description); } /* * Parses an enumeration list of the form: * { label(value) label(value) ... } * The initial { has already been parsed. * Returns NULL on error. */ static struct enum_list * parse_enumlist(FILE * fp, struct enum_list **retp) { register int type; char token[MAXTOKEN]; struct enum_list *ep = NULL, **epp = &ep; free_enums(retp); while ((type = get_token(fp, token, MAXTOKEN)) != ENDOFFILE) { if (type == RIGHTBRACKET) break; /* some enums use "deprecated" to indicate a no longer value label */ /* (EG: IP-MIB's IpAddressStatusTC) */ if (type == LABEL || type == DEPRECATED) { /* * this is an enumerated label */ *epp = (struct enum_list *) calloc(1, sizeof(struct enum_list)); if (*epp == NULL) return (NULL); /* * a reasonable approximation for the length */ (*epp)->label = strdup(token); type = get_token(fp, token, MAXTOKEN); if (type != LEFTPAREN) { print_error("Expected \"(\"", token, type); return NULL; } type = get_token(fp, token, MAXTOKEN); if (type != NUMBER) { print_error("Expected integer", token, type); return NULL; } (*epp)->value = strtol(token, NULL, 10); type = get_token(fp, token, MAXTOKEN); if (type != RIGHTPAREN) { print_error("Expected \")\"", token, type); return NULL; } epp = &(*epp)->next; } } if (type == ENDOFFILE) { print_error("Expected \"}\"", token, type); return NULL; } *retp = ep; return ep; } static struct range_list * parse_ranges(FILE * fp, struct range_list **retp) { int low, high; char nexttoken[MAXTOKEN]; int nexttype; struct range_list *rp = NULL, **rpp = &rp; int size = 0, taken = 1; free_ranges(retp); nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype == SIZE) { size = 1; taken = 0; nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype != LEFTPAREN) print_error("Expected \"(\" after SIZE", nexttoken, nexttype); } do { if (!taken) nexttype = get_token(fp, nexttoken, MAXTOKEN); else taken = 0; high = low = strtol(nexttoken, NULL, 10); nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype == RANGE) { nexttype = get_token(fp, nexttoken, MAXTOKEN); errno = 0; high = strtol(nexttoken, NULL, 10); if ( errno == ERANGE ) { if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) snmp_log(LOG_WARNING, "Warning: Upper bound not handled correctly (%s != %d): At line %d in %s\n", nexttoken, high, mibLine, File); } nexttype = get_token(fp, nexttoken, MAXTOKEN); } *rpp = (struct range_list *) calloc(1, sizeof(struct range_list)); if (*rpp == NULL) break; (*rpp)->low = low; (*rpp)->high = high; rpp = &(*rpp)->next; } while (nexttype == BAR); if (size) { if (nexttype != RIGHTPAREN) print_error("Expected \")\" after SIZE", nexttoken, nexttype); nexttype = get_token(fp, nexttoken, nexttype); } if (nexttype != RIGHTPAREN) print_error("Expected \")\"", nexttoken, nexttype); *retp = rp; return rp; } /* * Parses an asn type. Structures are ignored by this parser. * Returns NULL on error. */ static struct node * parse_asntype(FILE * fp, char *name, int *ntype, char *ntoken) { int type, i; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; char *hint = NULL; char *descr = NULL; struct tc *tcp; int level; type = get_token(fp, token, MAXTOKEN); if (type == SEQUENCE || type == CHOICE) { level = 0; while ((type = get_token(fp, token, MAXTOKEN)) != ENDOFFILE) { if (type == LEFTBRACKET) { level++; } else if (type == RIGHTBRACKET && --level == 0) { *ntype = get_token(fp, ntoken, MAXTOKEN); return NULL; } } print_error("Expected \"}\"", token, type); return NULL; } else if (type == LEFTBRACKET) { struct node *np; int ch_next = '{'; ungetc(ch_next, fp); np = parse_objectid(fp, name); if (np != NULL) { *ntype = get_token(fp, ntoken, MAXTOKEN); return np; } return NULL; } else if (type == LEFTSQBRACK) { int size = 0; do { type = get_token(fp, token, MAXTOKEN); } while (type != ENDOFFILE && type != RIGHTSQBRACK); if (type != RIGHTSQBRACK) { print_error("Expected \"]\"", token, type); return NULL; } type = get_token(fp, token, MAXTOKEN); if (type == IMPLICIT) type = get_token(fp, token, MAXTOKEN); *ntype = get_token(fp, ntoken, MAXTOKEN); if (*ntype == LEFTPAREN) { switch (type) { case OCTETSTR: *ntype = get_token(fp, ntoken, MAXTOKEN); if (*ntype != SIZE) { print_error("Expected SIZE", ntoken, *ntype); return NULL; } size = 1; *ntype = get_token(fp, ntoken, MAXTOKEN); if (*ntype != LEFTPAREN) { print_error("Expected \"(\" after SIZE", ntoken, *ntype); return NULL; } /* * fall through */ case INTEGER: *ntype = get_token(fp, ntoken, MAXTOKEN); do { if (*ntype != NUMBER) print_error("Expected NUMBER", ntoken, *ntype); *ntype = get_token(fp, ntoken, MAXTOKEN); if (*ntype == RANGE) { *ntype = get_token(fp, ntoken, MAXTOKEN); if (*ntype != NUMBER) print_error("Expected NUMBER", ntoken, *ntype); *ntype = get_token(fp, ntoken, MAXTOKEN); } } while (*ntype == BAR); if (*ntype != RIGHTPAREN) { print_error("Expected \")\"", ntoken, *ntype); return NULL; } *ntype = get_token(fp, ntoken, MAXTOKEN); if (size) { if (*ntype != RIGHTPAREN) { print_error("Expected \")\" to terminate SIZE", ntoken, *ntype); return NULL; } *ntype = get_token(fp, ntoken, MAXTOKEN); } } } return NULL; } else { if (type == CONVENTION) { while (type != SYNTAX && type != ENDOFFILE) { if (type == DISPLAYHINT) { type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) print_error("DISPLAY-HINT must be string", token, type); else hint = strdup(token); } else if (type == DESCRIPTION && netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) print_error("DESCRIPTION must be string", token, type); else descr = strdup(quoted_string_buffer); } else type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); } type = get_token(fp, token, MAXTOKEN); if (type == OBJECT) { type = get_token(fp, token, MAXTOKEN); if (type != IDENTIFIER) { print_error("Expected IDENTIFIER", token, type); SNMP_FREE(hint); return NULL; } type = OBJID; } } else if (type == OBJECT) { type = get_token(fp, token, MAXTOKEN); if (type != IDENTIFIER) { print_error("Expected IDENTIFIER", token, type); return NULL; } type = OBJID; } if (type == LABEL) { type = get_tc(token, current_module, NULL, NULL, NULL, NULL); } /* * textual convention */ for (i = 0; i < MAXTC; i++) { if (tclist[i].type == 0) break; } if (i == MAXTC) { print_error("Too many textual conventions", token, type); SNMP_FREE(hint); return NULL; } if (!(type & SYNTAX_MASK)) { print_error("Textual convention doesn't map to real type", token, type); SNMP_FREE(hint); return NULL; } tcp = &tclist[i]; tcp->modid = current_module; tcp->descriptor = strdup(name); tcp->hint = hint; tcp->description = descr; tcp->type = type; *ntype = get_token(fp, ntoken, MAXTOKEN); if (*ntype == LEFTPAREN) { tcp->ranges = parse_ranges(fp, &tcp->ranges); *ntype = get_token(fp, ntoken, MAXTOKEN); } else if (*ntype == LEFTBRACKET) { /* * if there is an enumeration list, parse it */ tcp->enums = parse_enumlist(fp, &tcp->enums); *ntype = get_token(fp, ntoken, MAXTOKEN); } return NULL; } } /* * Parses an OBJECT TYPE macro. * Returns 0 on error. */ static struct node * parse_objecttype(FILE * fp, char *name) { register int type; char token[MAXTOKEN]; char nexttoken[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; int nexttype, tctype; register struct node *np; type = get_token(fp, token, MAXTOKEN); if (type != SYNTAX) { print_error("Bad format for OBJECT-TYPE", token, type); return NULL; } np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); if (type == OBJECT) { type = get_token(fp, token, MAXTOKEN); if (type != IDENTIFIER) { print_error("Expected IDENTIFIER", token, type); free_node(np); return NULL; } type = OBJID; } if (type == LABEL) { int tmp_index; tctype = get_tc(token, current_module, &tmp_index, &np->enums, &np->ranges, &np->hint); if (tctype == LABEL && netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS) > 1) { print_error("Warning: No known translation for type", token, type); } type = tctype; np->tc_index = tmp_index; /* store TC for later reference */ } np->type = type; nexttype = get_token(fp, nexttoken, MAXTOKEN); switch (type) { case SEQUENCE: if (nexttype == OF) { nexttype = get_token(fp, nexttoken, MAXTOKEN); nexttype = get_token(fp, nexttoken, MAXTOKEN); } break; case INTEGER: case INTEGER32: case UINTEGER32: case UNSIGNED32: case COUNTER: case GAUGE: case BITSTRING: case LABEL: if (nexttype == LEFTBRACKET) { /* * if there is an enumeration list, parse it */ np->enums = parse_enumlist(fp, &np->enums); nexttype = get_token(fp, nexttoken, MAXTOKEN); } else if (nexttype == LEFTPAREN) { /* * if there is a range list, parse it */ np->ranges = parse_ranges(fp, &np->ranges); nexttype = get_token(fp, nexttoken, MAXTOKEN); } break; case OCTETSTR: case KW_OPAQUE: /* * parse any SIZE specification */ if (nexttype == LEFTPAREN) { nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype == SIZE) { nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype == LEFTPAREN) { np->ranges = parse_ranges(fp, &np->ranges); nexttype = get_token(fp, nexttoken, MAXTOKEN); /* ) */ if (nexttype == RIGHTPAREN) { nexttype = get_token(fp, nexttoken, MAXTOKEN); break; } } } print_error("Bad SIZE syntax", token, type); free_node(np); return NULL; } break; case OBJID: case NETADDR: case IPADDR: case TIMETICKS: case NUL: case NSAPADDRESS: case COUNTER64: break; default: print_error("Bad syntax", token, type); free_node(np); return NULL; } if (nexttype == UNITS) { type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad UNITS", quoted_string_buffer, type); free_node(np); return NULL; } np->units = strdup(quoted_string_buffer); nexttype = get_token(fp, nexttoken, MAXTOKEN); } if (nexttype != ACCESS) { print_error("Should be ACCESS", nexttoken, nexttype); free_node(np); return NULL; } type = get_token(fp, token, MAXTOKEN); if (type != READONLY && type != READWRITE && type != WRITEONLY && type != NOACCESS && type != READCREATE && type != ACCNOTIFY) { print_error("Bad ACCESS type", token, type); free_node(np); return NULL; } np->access = type; type = get_token(fp, token, MAXTOKEN); if (type != STATUS) { print_error("Should be STATUS", token, type); free_node(np); return NULL; } type = get_token(fp, token, MAXTOKEN); if (type != MANDATORY && type != CURRENT && type != KW_OPTIONAL && type != OBSOLETE && type != DEPRECATED) { print_error("Bad STATUS", token, type); free_node(np); return NULL; } np->status = type; /* * Optional parts of the OBJECT-TYPE macro */ type = get_token(fp, token, MAXTOKEN); while (type != EQUALS && type != ENDOFFILE) { switch (type) { case DESCRIPTION: type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); free_node(np); return NULL; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { np->description = strdup(quoted_string_buffer); } break; case REFERENCE: type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad REFERENCE", quoted_string_buffer, type); free_node(np); return NULL; } np->reference = strdup(quoted_string_buffer); break; case INDEX: if (np->augments) { print_error("Cannot have both INDEX and AUGMENTS", token, type); free_node(np); return NULL; } np->indexes = getIndexes(fp, &np->indexes); if (np->indexes == NULL) { print_error("Bad INDEX list", token, type); free_node(np); return NULL; } break; case AUGMENTS: if (np->indexes) { print_error("Cannot have both INDEX and AUGMENTS", token, type); free_node(np); return NULL; } np->indexes = getIndexes(fp, &np->indexes); if (np->indexes == NULL) { print_error("Bad AUGMENTS list", token, type); free_node(np); return NULL; } np->augments = strdup(np->indexes->ilabel); free_indexes(&np->indexes); break; case DEFVAL: /* * Mark's defVal section */ type = get_token(fp, quoted_string_buffer, MAXTOKEN); if (type != LEFTBRACKET) { print_error("Bad DEFAULTVALUE", quoted_string_buffer, type); free_node(np); return NULL; } { int level = 1; char defbuf[512]; defbuf[0] = 0; while (1) { type = get_token(fp, quoted_string_buffer, MAXTOKEN); if ((type == RIGHTBRACKET && --level == 0) || type == ENDOFFILE) break; else if (type == LEFTBRACKET) level++; if (type == QUOTESTRING) { if (strlen(defbuf)+2 < sizeof(defbuf)) { defbuf[ strlen(defbuf)+2 ] = 0; defbuf[ strlen(defbuf)+1 ] = '"'; defbuf[ strlen(defbuf) ] = '\\'; } defbuf[ sizeof(defbuf)-1 ] = 0; } strncat(defbuf, quoted_string_buffer, sizeof(defbuf)-strlen(defbuf)); defbuf[ sizeof(defbuf)-1 ] = 0; if (type == QUOTESTRING) { if (strlen(defbuf)+2 < sizeof(defbuf)) { defbuf[ strlen(defbuf)+2 ] = 0; defbuf[ strlen(defbuf)+1 ] = '"'; defbuf[ strlen(defbuf) ] = '\\'; } defbuf[ sizeof(defbuf)-1 ] = 0; } if (strlen(defbuf)+1 < sizeof(defbuf)) { defbuf[ strlen(defbuf)+1 ] = 0; defbuf[ strlen(defbuf) ] = ' '; } } if (type != RIGHTBRACKET) { print_error("Bad DEFAULTVALUE", quoted_string_buffer, type); free_node(np); return NULL; } defbuf[strlen(defbuf) - 1] = 0; np->defaultValue = strdup(defbuf); } break; case NUM_ENTRIES: if (tossObjectIdentifier(fp) != OBJID) { print_error("Bad Object Identifier", token, type); free_node(np); return NULL; } break; default: print_error("Bad format of optional clauses", token, type); free_node(np); return NULL; } type = get_token(fp, token, MAXTOKEN); } if (type != EQUALS) { print_error("Bad format", token, type); free_node(np); return NULL; } return merge_parse_objectid(np, fp, name); } /* * Parses an OBJECT GROUP macro. * Returns 0 on error. * * Also parses object-identity, since they are similar (ignore STATUS). * - WJH 10/96 */ static struct node * parse_objectgroup(FILE * fp, char *name, int what, struct objgroup **ol) { int type; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; struct node *np; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); if (type == what) { type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { print_error("Expected \"{\"", token, type); goto skip; } do { struct objgroup *o; type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad identifier", token, type); goto skip; } o = (struct objgroup *) malloc(sizeof(struct objgroup)); if (!o) { print_error("Resource failure", token, type); goto skip; } o->line = mibLine; o->name = strdup(token); o->next = *ol; *ol = o; type = get_token(fp, token, MAXTOKEN); } while (type == COMMA); if (type != RIGHTBRACKET) { print_error("Expected \"}\" after list", token, type); goto skip; } type = get_token(fp, token, type); } if (type != STATUS) { print_error("Expected STATUS", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != CURRENT && type != DEPRECATED && type != OBSOLETE) { print_error("Bad STATUS value", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); free_node(np); return NULL; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { np->description = strdup(quoted_string_buffer); } type = get_token(fp, token, MAXTOKEN); if (type == REFERENCE) { type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad REFERENCE", quoted_string_buffer, type); free_node(np); return NULL; } np->reference = strdup(quoted_string_buffer); type = get_token(fp, token, MAXTOKEN); } if (type != EQUALS) print_error("Expected \"::=\"", token, type); skip: while (type != EQUALS && type != ENDOFFILE) type = get_token(fp, token, MAXTOKEN); return merge_parse_objectid(np, fp, name); } /* * Parses a NOTIFICATION-TYPE macro. * Returns 0 on error. */ static struct node * parse_notificationDefinition(FILE * fp, char *name) { register int type; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; register struct node *np; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); while (type != EQUALS && type != ENDOFFILE) { switch (type) { case DESCRIPTION: type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); free_node(np); return NULL; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { np->description = strdup(quoted_string_buffer); } break; case REFERENCE: type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad REFERENCE", quoted_string_buffer, type); free_node(np); return NULL; } np->reference = strdup(quoted_string_buffer); break; case OBJECTS: np->varbinds = getVarbinds(fp, &np->varbinds); if (!np->varbinds) { print_error("Bad OBJECTS list", token, type); free_node(np); return NULL; } break; default: /* * NOTHING */ break; } type = get_token(fp, token, MAXTOKEN); } return merge_parse_objectid(np, fp, name); } /* * Parses a TRAP-TYPE macro. * Returns 0 on error. */ static struct node * parse_trapDefinition(FILE * fp, char *name) { register int type; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; register struct node *np; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); while (type != EQUALS && type != ENDOFFILE) { switch (type) { case DESCRIPTION: type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); free_node(np); return NULL; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { np->description = strdup(quoted_string_buffer); } break; case REFERENCE: /* I'm not sure REFERENCEs are legal in smiv1 traps??? */ type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad REFERENCE", quoted_string_buffer, type); free_node(np); return NULL; } np->reference = strdup(quoted_string_buffer); break; case ENTERPRISE: type = get_token(fp, token, MAXTOKEN); if (type == LEFTBRACKET) { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad Trap Format", token, type); free_node(np); return NULL; } np->parent = strdup(token); /* * Get right bracket */ type = get_token(fp, token, MAXTOKEN); } else if (type == LABEL) np->parent = strdup(token); break; case VARIABLES: np->varbinds = getVarbinds(fp, &np->varbinds); if (!np->varbinds) { print_error("Bad VARIABLES list", token, type); free_node(np); return NULL; } break; default: /* * NOTHING */ break; } type = get_token(fp, token, MAXTOKEN); } type = get_token(fp, token, MAXTOKEN); np->label = strdup(name); if (type != NUMBER) { print_error("Expected a Number", token, type); free_node(np); return NULL; } np->subid = strtoul(token, NULL, 10); np->next = alloc_node(current_module); if (np->next == NULL) { free_node(np); return (NULL); } np->next->parent = np->parent; np->parent = (char *) malloc(strlen(np->parent) + 2); if (np->parent == NULL) { free_node(np->next); free_node(np); return (NULL); } strcpy(np->parent, np->next->parent); strcat(np->parent, "#"); np->next->label = strdup(np->parent); return np; } /* * Parses a compliance macro * Returns 0 on error. */ static int eat_syntax(FILE * fp, char *token, int maxtoken) { int type, nexttype; struct node *np = alloc_node(current_module); char nexttoken[MAXTOKEN]; type = get_token(fp, token, maxtoken); nexttype = get_token(fp, nexttoken, MAXTOKEN); switch (type) { case INTEGER: case INTEGER32: case UINTEGER32: case UNSIGNED32: case COUNTER: case GAUGE: case BITSTRING: case LABEL: if (nexttype == LEFTBRACKET) { /* * if there is an enumeration list, parse it */ np->enums = parse_enumlist(fp, &np->enums); nexttype = get_token(fp, nexttoken, MAXTOKEN); } else if (nexttype == LEFTPAREN) { /* * if there is a range list, parse it */ np->ranges = parse_ranges(fp, &np->ranges); nexttype = get_token(fp, nexttoken, MAXTOKEN); } break; case OCTETSTR: case KW_OPAQUE: /* * parse any SIZE specification */ if (nexttype == LEFTPAREN) { nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype == SIZE) { nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype == LEFTPAREN) { np->ranges = parse_ranges(fp, &np->ranges); nexttype = get_token(fp, nexttoken, MAXTOKEN); /* ) */ if (nexttype == RIGHTPAREN) { nexttype = get_token(fp, nexttoken, MAXTOKEN); break; } } } print_error("Bad SIZE syntax", token, type); free_node(np); return nexttype; } break; case OBJID: case NETADDR: case IPADDR: case TIMETICKS: case NUL: case NSAPADDRESS: case COUNTER64: break; default: print_error("Bad syntax", token, type); free_node(np); return nexttype; } free_node(np); return nexttype; } static int compliance_lookup(const char *name, int modid) { if (modid == -1) { struct objgroup *op = (struct objgroup *) malloc(sizeof(struct objgroup)); if (!op) return 0; op->next = objgroups; op->name = strdup(name); op->line = mibLine; objgroups = op; return 1; } else return find_tree_node(name, modid) != NULL; } static struct node * parse_compliance(FILE * fp, char *name) { int type; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; struct node *np; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); if (type != STATUS) { print_error("Expected STATUS", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != CURRENT && type != DEPRECATED && type != OBSOLETE) { print_error("Bad STATUS", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); goto skip; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) np->description = strdup(quoted_string_buffer); type = get_token(fp, token, MAXTOKEN); if (type == REFERENCE) { type = get_token(fp, quoted_string_buffer, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad REFERENCE", quoted_string_buffer, type); goto skip; } np->reference = strdup(quoted_string_buffer); type = get_token(fp, token, MAXTOKEN); } if (type != MODULE) { print_error("Expected MODULE", token, type); goto skip; } while (type == MODULE) { int modid = -1; char modname[MAXTOKEN]; type = get_token(fp, token, MAXTOKEN); if (type == LABEL && strcmp(token, module_name(current_module, modname))) { modid = read_module_internal(token); if (modid != MODULE_LOADED_OK && modid != MODULE_ALREADY_LOADED) { print_error("Unknown module", token, type); goto skip; } modid = which_module(token); type = get_token(fp, token, MAXTOKEN); } if (type == MANDATORYGROUPS) { type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { print_error("Expected \"{\"", token, type); goto skip; } do { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad group name", token, type); goto skip; } if (!compliance_lookup(token, modid)) print_error("Unknown group", token, type); type = get_token(fp, token, MAXTOKEN); } while (type == COMMA); if (type != RIGHTBRACKET) { print_error("Expected \"}\"", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } while (type == GROUP || type == OBJECT) { if (type == GROUP) { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad group name", token, type); goto skip; } if (!compliance_lookup(token, modid)) print_error("Unknown group", token, type); type = get_token(fp, token, MAXTOKEN); } else { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad object name", token, type); goto skip; } if (!compliance_lookup(token, modid)) print_error("Unknown group", token, type); type = get_token(fp, token, MAXTOKEN); if (type == SYNTAX) type = eat_syntax(fp, token, MAXTOKEN); if (type == WRSYNTAX) type = eat_syntax(fp, token, MAXTOKEN); if (type == MINACCESS) { type = get_token(fp, token, MAXTOKEN); if (type != NOACCESS && type != ACCNOTIFY && type != READONLY && type != WRITEONLY && type != READCREATE && type != READWRITE) { print_error("Bad MIN-ACCESS spec", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } } if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } } skip: while (type != EQUALS && type != ENDOFFILE) type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); return merge_parse_objectid(np, fp, name); } /* * Parses a capabilities macro * Returns 0 on error. */ static struct node * parse_capabilities(FILE * fp, char *name) { int type; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; struct node *np; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); if (type != PRODREL) { print_error("Expected PRODUCT-RELEASE", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) { print_error("Expected STRING after PRODUCT-RELEASE", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != STATUS) { print_error("Expected STATUS", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != CURRENT && type != OBSOLETE) { print_error("STATUS should be current or obsolete", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", token, type); goto skip; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { np->description = strdup(token); } type = get_token(fp, token, MAXTOKEN); if (type == REFERENCE) { type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad REFERENCE", token, type); goto skip; } np->reference = strdup(token); type = get_token(fp, token, type); } while (type == SUPPORTS) { int modid; struct tree *tp; type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad module name", token, type); goto skip; } modid = read_module_internal(token); if (modid != MODULE_LOADED_OK && modid != MODULE_ALREADY_LOADED) { print_error("Module not found", token, type); goto skip; } modid = which_module(token); type = get_token(fp, token, MAXTOKEN); if (type != INCLUDES) { print_error("Expected INCLUDES", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { print_error("Expected \"{\"", token, type); goto skip; } do { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Expected group name", token, type); goto skip; } tp = find_tree_node(token, modid); if (!tp) print_error("Group not found in module", token, type); type = get_token(fp, token, MAXTOKEN); } while (type == COMMA); if (type != RIGHTBRACKET) { print_error("Expected \"}\" after group list", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); while (type == VARIATION) { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad object name", token, type); goto skip; } tp = find_tree_node(token, modid); if (!tp) print_error("Object not found in module", token, type); type = get_token(fp, token, MAXTOKEN); if (type == SYNTAX) { type = eat_syntax(fp, token, MAXTOKEN); } if (type == WRSYNTAX) { type = eat_syntax(fp, token, MAXTOKEN); } if (type == ACCESS) { type = get_token(fp, token, MAXTOKEN); if (type != ACCNOTIFY && type != READONLY && type != READWRITE && type != READCREATE && type != WRITEONLY && type != NOTIMPL) { print_error("Bad ACCESS", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } if (type == CREATEREQ) { type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { print_error("Expected \"{\"", token, type); goto skip; } do { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad object name in list", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } while (type == COMMA); if (type != RIGHTBRACKET) { print_error("Expected \"}\" after list", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } if (type == DEFVAL) { int level = 1; type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { print_error("Expected \"{\" after DEFVAL", token, type); goto skip; } do { type = get_token(fp, token, MAXTOKEN); if (type == LEFTBRACKET) level++; else if (type == RIGHTBRACKET) level--; } while (type != RIGHTBRACKET && type != ENDOFFILE && level != 0); if (type != RIGHTBRACKET) { print_error("Missing \"}\" after DEFVAL", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } } if (type != EQUALS) print_error("Expected \"::=\"", token, type); skip: while (type != EQUALS && type != ENDOFFILE) { type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); } return merge_parse_objectid(np, fp, name); } /* * Parses a module identity macro * Returns 0 on error. */ static void check_utc(const char *utc) { int len, year, month, day, hour, minute; len = strlen(utc); if (utc[len - 1] != 'Z' && utc[len - 1] != 'z') { print_error("Timestamp should end with Z", utc, QUOTESTRING); return; } if (len == 11) { len = sscanf(utc, "%2d%2d%2d%2d%2dZ", &year, &month, &day, &hour, &minute); year += 1900; } else if (len == 13) len = sscanf(utc, "%4d%2d%2d%2d%2dZ", &year, &month, &day, &hour, &minute); else { print_error("Bad timestamp format (11 or 13 characters)", utc, QUOTESTRING); return; } if (len != 5) { print_error("Bad timestamp format", utc, QUOTESTRING); return; } if (month < 1 || month > 12) print_error("Bad month in timestamp", utc, QUOTESTRING); if (day < 1 || day > 31) print_error("Bad day in timestamp", utc, QUOTESTRING); if (hour < 0 || hour > 23) print_error("Bad hour in timestamp", utc, QUOTESTRING); if (minute < 0 || minute > 59) print_error("Bad minute in timestamp", utc, QUOTESTRING); } static struct node * parse_moduleIdentity(FILE * fp, char *name) { register int type; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; register struct node *np; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); if (type != LASTUPDATED) { print_error("Expected LAST-UPDATED", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) { print_error("Need STRING for LAST-UPDATED", token, type); goto skip; } check_utc(token); type = get_token(fp, token, MAXTOKEN); if (type != ORGANIZATION) { print_error("Expected ORGANIZATION", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad ORGANIZATION", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != CONTACTINFO) { print_error("Expected CONTACT-INFO", token, type); goto skip; } type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad CONTACT-INFO", quoted_string_buffer, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); goto skip; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { np->description = strdup(quoted_string_buffer); } type = get_token(fp, token, MAXTOKEN); while (type == REVISION) { type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad REVISION", token, type); goto skip; } check_utc(token); type = get_token(fp, token, MAXTOKEN); if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } if (type != EQUALS) print_error("Expected \"::=\"", token, type); skip: while (type != EQUALS && type != ENDOFFILE) { type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); } return merge_parse_objectid(np, fp, name); } /* * Parses a MACRO definition * Expect BEGIN, discard everything to end. * Returns 0 on error. */ static struct node * parse_macro(FILE * fp, char *name) { register int type; char token[MAXTOKEN]; struct node *np; int iLine = mibLine; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, sizeof(token)); while (type != EQUALS && type != ENDOFFILE) { type = get_token(fp, token, sizeof(token)); } if (type != EQUALS) { if (np) free_node(np); return NULL; } while (type != BEGIN && type != ENDOFFILE) { type = get_token(fp, token, sizeof(token)); } if (type != BEGIN) { if (np) free_node(np); return NULL; } while (type != END && type != ENDOFFILE) { type = get_token(fp, token, sizeof(token)); } if (type != END) { if (np) free_node(np); return NULL; } if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "%s MACRO (lines %d..%d parsed and ignored).\n", name, iLine, mibLine); } return np; } /* * Parses a module import clause * loading any modules referenced */ static void parse_imports(FILE * fp) { register int type; char token[MAXTOKEN]; char modbuf[256]; #define MAX_IMPORTS 256 struct module_import import_list[MAX_IMPORTS]; int this_module; struct module *mp; int import_count = 0; /* Total number of imported descriptors */ int i = 0, old_i; /* index of first import from each module */ type = get_token(fp, token, MAXTOKEN); /* * Parse the IMPORTS clause */ while (type != SEMI && type != ENDOFFILE) { if (type == LABEL) { if (import_count == MAX_IMPORTS) { print_error("Too many imported symbols", token, type); do { type = get_token(fp, token, MAXTOKEN); } while (type != SEMI && type != ENDOFFILE); return; } import_list[import_count++].label = strdup(token); } else if (type == FROM) { type = get_token(fp, token, MAXTOKEN); if (import_count == i) { /* All imports are handled internally */ type = get_token(fp, token, MAXTOKEN); continue; } this_module = which_module(token); for (old_i = i; i < import_count; ++i) import_list[i].modid = this_module; /* * Recursively read any pre-requisite modules */ if (read_module_internal(token) == MODULE_NOT_FOUND) { int found = 0; for (; old_i < import_count; ++old_i) { found += read_import_replacements(token, &import_list[old_i]); } if (!found) print_module_not_found(token); } } type = get_token(fp, token, MAXTOKEN); } /* * Save the import information * in the global module table */ for (mp = module_head; mp; mp = mp->next) if (mp->modid == current_module) { if (import_count == 0) return; if (mp->imports && (mp->imports != root_imports)) { /* * this can happen if all modules are in one source file. */ for (i = 0; i < mp->no_imports; ++i) { DEBUGMSGTL(("parse-mibs", "#### freeing Module %d '%s' %d\n", mp->modid, mp->imports[i].label, mp->imports[i].modid)); free((char *) mp->imports[i].label); } free((char *) mp->imports); } mp->imports = (struct module_import *) calloc(import_count, sizeof(struct module_import)); if (mp->imports == NULL) return; for (i = 0; i < import_count; ++i) { mp->imports[i].label = import_list[i].label; mp->imports[i].modid = import_list[i].modid; DEBUGMSGTL(("parse-mibs", "#### adding Module %d '%s' %d\n", mp->modid, mp->imports[i].label, mp->imports[i].modid)); } mp->no_imports = import_count; return; } /* * Shouldn't get this far */ print_module_not_found(module_name(current_module, modbuf)); return; } /* * MIB module handling routines */ static void dump_module_list(void) { struct module *mp = module_head; DEBUGMSGTL(("parse-mibs", "Module list:\n")); while (mp) { DEBUGMSGTL(("parse-mibs", " %s %d %s %d\n", mp->name, mp->modid, mp->file, mp->no_imports)); mp = mp->next; } } int which_module(const char *name) { struct module *mp; for (mp = module_head; mp; mp = mp->next) if (!label_compare(mp->name, name)) return (mp->modid); DEBUGMSGTL(("parse-mibs", "Module %s not found\n", name)); return (-1); } /* * module_name - copy module name to user buffer, return ptr to same. */ char * module_name(int modid, char *cp) { struct module *mp; for (mp = module_head; mp; mp = mp->next) if (mp->modid == modid) { strcpy(cp, mp->name); return (cp); } if (modid != -1) DEBUGMSGTL(("parse-mibs", "Module %d not found\n", modid)); sprintf(cp, "#%d", modid); return (cp); } /* * Backwards compatability * Read newer modules that replace the one specified:- * either all of them (read_module_replacements), * or those relating to a specified identifier (read_import_replacements) * plus an interface to add new replacement requirements */ void add_module_replacement(const char *old_module, const char *new_module_name, const char *tag, int len) { struct module_compatability *mcp; mcp = (struct module_compatability *) calloc(1, sizeof(struct module_compatability)); if (mcp == NULL) return; mcp->old_module = strdup(old_module); mcp->new_module = strdup(new_module_name); if (tag) mcp->tag = strdup(tag); mcp->tag_len = len; mcp->next = module_map_head; module_map_head = mcp; } static int read_module_replacements(const char *name) { struct module_compatability *mcp; for (mcp = module_map_head; mcp; mcp = mcp->next) { if (!label_compare(mcp->old_module, name)) { if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "Loading replacement module %s for %s (%s)\n", mcp->new_module, name, File); } (void) netsnmp_read_module(mcp->new_module); return 1; } } return 0; } static int read_import_replacements(const char *old_module_name, struct module_import *identifier) { struct module_compatability *mcp; /* * Look for matches first */ for (mcp = module_map_head; mcp; mcp = mcp->next) { if (!label_compare(mcp->old_module, old_module_name)) { if ( /* exact match */ (mcp->tag_len == 0 && (mcp->tag == NULL || !label_compare(mcp->tag, identifier->label))) || /* * prefix match */ (mcp->tag_len != 0 && !strncmp(mcp->tag, identifier->label, mcp->tag_len)) ) { if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "Importing %s from replacement module %s instead of %s (%s)\n", identifier->label, mcp->new_module, old_module_name, File); } (void) netsnmp_read_module(mcp->new_module); identifier->modid = which_module(mcp->new_module); return 1; /* finished! */ } } } /* * If no exact match, load everything relevant */ return read_module_replacements(old_module_name); } /* * Read in the named module * Returns the root of the whole tree * (by analogy with 'read_mib') */ static int read_module_internal(const char *name) { struct module *mp; FILE *fp; struct node *np; netsnmp_init_mib_internals(); for (mp = module_head; mp; mp = mp->next) if (!label_compare(mp->name, name)) { const char *oldFile = File; int oldLine = mibLine; int oldModule = current_module; if (mp->no_imports != -1) { DEBUGMSGTL(("parse-mibs", "Module %s already loaded\n", name)); return MODULE_ALREADY_LOADED; } if ((fp = fopen(mp->file, "r")) == NULL) { snmp_log_perror(mp->file); return MODULE_LOAD_FAILED; } mp->no_imports = 0; /* Note that we've read the file */ File = mp->file; mibLine = 1; current_module = mp->modid; /* * Parse the file */ np = parse(fp, NULL); fclose(fp); File = oldFile; mibLine = oldLine; current_module = oldModule; return MODULE_LOADED_OK; } return MODULE_NOT_FOUND; } void adopt_orphans(void) { struct node *np, *onp; struct tree *tp; int i, adopted = 1; if (!orphan_nodes) return; init_node_hash(orphan_nodes); orphan_nodes = NULL; while (adopted) { adopted = 0; for (i = 0; i < NHASHSIZE; i++) if (nbuckets[i]) { for (np = nbuckets[i]; np != NULL; np = np->next) { tp = find_tree_node(np->parent, -1); if (tp) { do_subtree(tp, &np); adopted = 1; /* * if do_subtree adopted the entire bucket, stop */ if(NULL == nbuckets[i]) break; /* * do_subtree may modify nbuckets, and if np * was adopted, np->next probably isn't an orphan * anymore. if np is still in the bucket (do_subtree * didn't adopt it) keep on plugging. otherwise * start over, at the top of the bucket. */ for(onp = nbuckets[i]; onp; onp = onp->next) if(onp == np) break; if(NULL == onp) { /* not in the list */ np = nbuckets[i]; /* start over */ } } } } } /* * Report on outstanding orphans * and link them back into the orphan list */ for (i = 0; i < NHASHSIZE; i++) if (nbuckets[i]) { if (orphan_nodes) onp = np->next = nbuckets[i]; else onp = orphan_nodes = nbuckets[i]; nbuckets[i] = NULL; while (onp) { char modbuf[256]; snmp_log(LOG_WARNING, "Cannot adopt OID in %s: %s ::= { %s %ld }\n", module_name(onp->modid, modbuf), (onp->label ? onp->label : "<no label>"), (onp->parent ? onp->parent : "<no parent>"), onp->subid); np = onp; onp = onp->next; } } } #ifndef NETSNMP_CLEAN_NAMESPACE struct tree * read_module(const char *name) { return netsnmp_read_module(name); } #endif struct tree * netsnmp_read_module(const char *name) { if (read_module_internal(name) == MODULE_NOT_FOUND) if (!read_module_replacements(name)) print_module_not_found(name); return tree_head; } /* * Prototype definition */ void unload_module_by_ID(int modID, struct tree *tree_top); void unload_module_by_ID(int modID, struct tree *tree_top) { struct tree *tp, *next; int i; for (tp = tree_top; tp; tp = next) { /* * Essentially, this is equivalent to the code fragment: * if (tp->modID == modID) * tp->number_modules--; * but handles one tree node being part of several modules, * and possible multiple copies of the same module ID. */ int nmod = tp->number_modules; if (nmod > 0) { /* in some module */ /* * Remove all copies of this module ID */ int cnt = 0, *pi1, *pi2 = tp->module_list; for (i = 0, pi1 = pi2; i < nmod; i++, pi2++) { if (*pi2 == modID) continue; cnt++; *pi1++ = *pi2; } if (nmod != cnt) { /* in this module */ /* * if ( (nmod - cnt) > 1) * printf("Dup modid %d, %d times, '%s'\n", tp->modid, (nmod-cnt), tp->label); fflush(stdout); ?* XXDEBUG */ tp->number_modules = cnt; switch (cnt) { case 0: tp->module_list[0] = -1; /* Mark unused, and FALL THROUGH */ case 1: /* save the remaining module */ if (&(tp->modid) != tp->module_list) { tp->modid = tp->module_list[0]; free(tp->module_list); tp->module_list = &(tp->modid); } break; default: break; } } /* if tree node is in this module */ } /* * if tree node is in some module */ next = tp->next_peer; /* * OK - that's dealt with *this* node. * Now let's look at the children. * (Isn't recursion wonderful!) */ if (tp->child_list) unload_module_by_ID(modID, tp->child_list); if (tp->number_modules == 0) { /* * This node isn't needed any more (except perhaps * for the sake of the children) */ if (tp->child_list == NULL) { unlink_tree(tp); free_tree(tp); } else { free_partial_tree(tp, TRUE); } } } } #ifndef NETSNMP_CLEAN_NAMESPACE int unload_module(const char *name) { return netsnmp_unload_module(name); } #endif int netsnmp_unload_module(const char *name) { struct module *mp; int modID = -1; for (mp = module_head; mp; mp = mp->next) if (!label_compare(mp->name, name)) { modID = mp->modid; break; } if (modID == -1) { DEBUGMSGTL(("unload-mib", "Module %s not found to unload\n", name)); return MODULE_NOT_FOUND; } unload_module_by_ID(modID, tree_head); mp->no_imports = -1; /* mark as unloaded */ return MODULE_LOADED_OK; /* Well, you know what I mean! */ } /* * Clear module map, tree nodes, textual convention table. */ void unload_all_mibs() { struct module *mp; struct module_compatability *mcp; struct tc *ptc; int i; for (mcp = module_map_head; mcp; mcp = module_map_head) { if (mcp == module_map) break; module_map_head = mcp->next; if (mcp->tag) free((char *) mcp->tag); free((char *) mcp->old_module); free((char *) mcp->new_module); free(mcp); } for (mp = module_head; mp; mp = module_head) { struct module_import *mi = mp->imports; if (mi) { for (i = 0; i < mp->no_imports; ++i) { SNMP_FREE((mi + i)->label); } mp->no_imports = 0; if (mi == root_imports) memset(mi, 0, sizeof(*mi)); else free(mi); } unload_module_by_ID(mp->modid, tree_head); module_head = mp->next; free(mp->name); free(mp->file); free(mp); } unload_module_by_ID(-1, tree_head); /* * tree nodes are cleared */ for (i = 0, ptc = tclist; i < MAXTC; i++, ptc++) { if (ptc->type == 0) continue; free_enums(&ptc->enums); free_ranges(&ptc->ranges); free(ptc->descriptor); if (ptc->hint) free(ptc->hint); } memset(tclist, 0, MAXTC * sizeof(struct tc)); memset(buckets, 0, sizeof(buckets)); memset(nbuckets, 0, sizeof(nbuckets)); memset(tbuckets, 0, sizeof(tbuckets)); for (i = 0; i < sizeof(root_imports) / sizeof(root_imports[0]); i++) { SNMP_FREE(root_imports[i].label); } max_module = 0; current_module = 0; module_map_head = NULL; SNMP_FREE(last_err_module); } static void new_module(const char *name, const char *file) { struct module *mp; for (mp = module_head; mp; mp = mp->next) if (!label_compare(mp->name, name)) { DEBUGMSGTL(("parse-mibs", " Module %s already noted\n", name)); /* * Not the same file */ if (label_compare(mp->file, file)) { DEBUGMSGTL(("parse-mibs", " %s is now in %s\n", name, file)); if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "Warning: Module %s was in %s now is %s\n", name, mp->file, file); } /* * Use the new one in preference */ free(mp->file); mp->file = strdup(file); } return; } /* * Add this module to the list */ DEBUGMSGTL(("parse-mibs", " Module %d %s is in %s\n", max_module, name, file)); mp = (struct module *) calloc(1, sizeof(struct module)); if (mp == NULL) return; mp->name = strdup(name); mp->file = strdup(file); mp->imports = NULL; mp->no_imports = -1; /* Not yet loaded */ mp->modid = max_module; ++max_module; mp->next = module_head; /* Or add to the *end* of the list? */ module_head = mp; } static void scan_objlist(struct node *root, struct objgroup *list, const char *error) { int oLine = mibLine; while (list) { struct objgroup *gp = list; struct node *np; list = list->next; np = root; while (np) if (label_compare(np->label, gp->name)) np = np->next; else break; if (!np) { mibLine = gp->line; print_error(error, gp->name, QUOTESTRING); } free(gp->name); free(gp); } mibLine = oLine; } /* * Parses a mib file and returns a linked list of nodes found in the file. * Returns NULL on error. */ static struct node * parse(FILE * fp, struct node *root) { char token[MAXTOKEN]; char name[MAXTOKEN]; int type = LABEL; int lasttype = LABEL; #define BETWEEN_MIBS 1 #define IN_MIB 2 int state = BETWEEN_MIBS; struct node *np, *nnp; struct objgroup *oldgroups = NULL, *oldobjects = NULL, *oldnotifs = NULL; DEBUGMSGTL(("parse-file", "Parsing file: %s...\n", File)); if (last_err_module) free(last_err_module); last_err_module = 0; np = root; if (np != NULL) { /* * now find end of chain */ while (np->next) np = np->next; } while (type != ENDOFFILE) { if (lasttype == CONTINUE) lasttype = type; else type = lasttype = get_token(fp, token, MAXTOKEN); switch (type) { case END: if (state != IN_MIB) { print_error("Error, END before start of MIB", NULL, type); return NULL; } else { struct module *mp; #ifdef TEST printf("\nNodes for Module %s:\n", name); print_nodes(stdout, root); #endif scan_objlist(root, objgroups, "Undefined OBJECT-GROUP"); scan_objlist(root, objects, "Undefined OBJECT"); scan_objlist(root, notifs, "Undefined NOTIFICATION"); objgroups = oldgroups; objects = oldobjects; notifs = oldnotifs; for (mp = module_head; mp; mp = mp->next) if (mp->modid == current_module) break; do_linkup(mp, root); np = root = NULL; } state = BETWEEN_MIBS; #ifdef TEST if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { xmalloc_stats(stderr); } #endif continue; case IMPORTS: parse_imports(fp); continue; case EXPORTS: while (type != SEMI && type != ENDOFFILE) type = get_token(fp, token, MAXTOKEN); continue; case LABEL: case INTEGER: case INTEGER32: case UINTEGER32: case UNSIGNED32: case COUNTER: case COUNTER64: case GAUGE: case IPADDR: case NETADDR: case NSAPADDRESS: case OBJSYNTAX: case APPSYNTAX: case SIMPLESYNTAX: case OBJNAME: case NOTIFNAME: case KW_OPAQUE: case TIMETICKS: break; case ENDOFFILE: continue; default: strcpy(name, token); type = get_token(fp, token, MAXTOKEN); nnp = NULL; if (type == MACRO) { nnp = parse_macro(fp, name); if (nnp == NULL) { print_error("Bad parse of MACRO", NULL, type); /* * return NULL; */ } free_node(nnp); /* IGNORE */ nnp = NULL; } else print_error(name, "is a reserved word", lasttype); continue; /* see if we can parse the rest of the file */ } strcpy(name, token); type = get_token(fp, token, MAXTOKEN); nnp = NULL; /* * Handle obsolete method to assign an object identifier to a * module */ if (lasttype == LABEL && type == LEFTBRACKET) { while (type != RIGHTBRACKET && type != ENDOFFILE) type = get_token(fp, token, MAXTOKEN); if (type == ENDOFFILE) { print_error("Expected \"}\"", token, type); return NULL; } type = get_token(fp, token, MAXTOKEN); } switch (type) { case DEFINITIONS: if (state != BETWEEN_MIBS) { print_error("Error, nested MIBS", NULL, type); return NULL; } state = IN_MIB; current_module = which_module(name); oldgroups = objgroups; objgroups = NULL; oldobjects = objects; objects = NULL; oldnotifs = notifs; notifs = NULL; if (current_module == -1) { new_module(name, File); current_module = which_module(name); } DEBUGMSGTL(("parse-mibs", "Parsing MIB: %d %s\n", current_module, name)); while ((type = get_token(fp, token, MAXTOKEN)) != ENDOFFILE) if (type == BEGIN) break; break; case OBJTYPE: nnp = parse_objecttype(fp, name); if (nnp == NULL) { print_error("Bad parse of OBJECT-TYPE", NULL, type); return NULL; } break; case OBJGROUP: nnp = parse_objectgroup(fp, name, OBJECTS, &objects); if (nnp == NULL) { print_error("Bad parse of OBJECT-GROUP", NULL, type); return NULL; } break; case NOTIFGROUP: nnp = parse_objectgroup(fp, name, NOTIFICATIONS, &notifs); if (nnp == NULL) { print_error("Bad parse of NOTIFICATION-GROUP", NULL, type); return NULL; } break; case TRAPTYPE: nnp = parse_trapDefinition(fp, name); if (nnp == NULL) { print_error("Bad parse of TRAP-TYPE", NULL, type); return NULL; } break; case NOTIFTYPE: nnp = parse_notificationDefinition(fp, name); if (nnp == NULL) { print_error("Bad parse of NOTIFICATION-TYPE", NULL, type); return NULL; } break; case COMPLIANCE: nnp = parse_compliance(fp, name); if (nnp == NULL) { print_error("Bad parse of MODULE-COMPLIANCE", NULL, type); return NULL; } break; case AGENTCAP: nnp = parse_capabilities(fp, name); if (nnp == NULL) { print_error("Bad parse of AGENT-CAPABILITIES", NULL, type); return NULL; } break; case MACRO: nnp = parse_macro(fp, name); if (nnp == NULL) { print_error("Bad parse of MACRO", NULL, type); /* * return NULL; */ } free_node(nnp); /* IGNORE */ nnp = NULL; break; case MODULEIDENTITY: nnp = parse_moduleIdentity(fp, name); if (nnp == NULL) { print_error("Bad parse of MODULE-IDENTITY", NULL, type); return NULL; } break; case OBJIDENTITY: nnp = parse_objectgroup(fp, name, OBJECTS, &objects); if (nnp == NULL) { print_error("Bad parse of OBJECT-IDENTITY", NULL, type); return NULL; } break; case OBJECT: type = get_token(fp, token, MAXTOKEN); if (type != IDENTIFIER) { print_error("Expected IDENTIFIER", token, type); return NULL; } type = get_token(fp, token, MAXTOKEN); if (type != EQUALS) { print_error("Expected \"::=\"", token, type); return NULL; } nnp = parse_objectid(fp, name); if (nnp == NULL) { print_error("Bad parse of OBJECT IDENTIFIER", NULL, type); return NULL; } break; case EQUALS: nnp = parse_asntype(fp, name, &type, token); lasttype = CONTINUE; break; case ENDOFFILE: break; default: print_error("Bad operator", token, type); return NULL; } if (nnp) { if (np) np->next = nnp; else np = root = nnp; while (np->next) np = np->next; if (np->type == TYPE_OTHER) np->type = type; } } DEBUGMSGTL(("parse-file", "End of file (%s)\n", File)); return root; } /* * return zero if character is not a label character. */ static int is_labelchar(int ich) { if ((isalnum(ich)) || (ich == '-')) return 1; if (ich == '_' && netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_PARSE_LABEL)) { return 1; } return 0; } /* * Parses a token from the file. The type of the token parsed is returned, * and the text is placed in the string pointed to by token. * Warning: this method may recurse. */ static int get_token(FILE * fp, char *token, int maxtlen) { register int ch, ch_next; register char *cp = token; register int hash = 0; register struct tok *tp; int too_long = 0; /* * skip all white space */ do { ch = getc(fp); if (ch == '\n') mibLine++; } while (isspace(ch) && ch != EOF); *cp++ = ch; *cp = '\0'; switch (ch) { case EOF: return ENDOFFILE; case '"': return parseQuoteString(fp, token, maxtlen); case '\'': /* binary or hex constant */ while ((ch = getc(fp)) != EOF && ch != '\'' && cp - token < maxtlen - 2) *cp++ = ch; if (ch == '\'') { unsigned long val = 0; *cp++ = '\''; *cp++ = ch = getc(fp); *cp = 0; cp = token + 1; switch (ch) { case EOF: return ENDOFFILE; case 'b': case 'B': while ((ch = *cp++) != '\'') if (ch != '0' && ch != '1') return LABEL; else val = val * 2 + ch - '0'; break; case 'h': case 'H': while ((ch = *cp++) != '\'') if ('0' <= ch && ch <= '9') val = val * 16 + ch - '0'; else if ('a' <= ch && ch <= 'f') val = val * 16 + ch - 'a' + 10; else if ('A' <= ch && ch <= 'F') val = val * 16 + ch - 'A' + 10; else return LABEL; break; default: return LABEL; } sprintf(token, "%ld", val); return NUMBER; } else return LABEL; case '(': return LEFTPAREN; case ')': return RIGHTPAREN; case '{': return LEFTBRACKET; case '}': return RIGHTBRACKET; case '[': return LEFTSQBRACK; case ']': return RIGHTSQBRACK; case ';': return SEMI; case ',': return COMMA; case '|': return BAR; case '.': ch_next = getc(fp); if (ch_next == '.') return RANGE; ungetc(ch_next, fp); return LABEL; case ':': ch_next = getc(fp); if (ch_next != ':') { ungetc(ch_next, fp); return LABEL; } ch_next = getc(fp); if (ch_next != '=') { ungetc(ch_next, fp); return LABEL; } return EQUALS; case '-': ch_next = getc(fp); if (ch_next == '-') { if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_COMMENT_TERM)) { /* * Treat the rest of this line as a comment. */ while ((ch_next != EOF) && (ch_next != '\n')) ch_next = getc(fp); } else { /* * Treat the rest of the line or until another '--' as a comment */ /* * (this is the "technically" correct way to parse comments) */ ch = ' '; ch_next = getc(fp); while (ch_next != EOF && ch_next != '\n' && (ch != '-' || ch_next != '-')) { ch = ch_next; ch_next = getc(fp); } } if (ch_next == EOF) return ENDOFFILE; if (ch_next == '\n') mibLine++; return get_token(fp, token, maxtlen); } ungetc(ch_next, fp); default: /* * Accumulate characters until end of token is found. Then attempt to * match this token as a reserved word. If a match is found, return the * type. Else it is a label. */ if (!is_labelchar(ch)) return LABEL; hash += tolower(ch); more: while (is_labelchar(ch_next = getc(fp))) { hash += tolower(ch_next); if (cp - token < maxtlen - 1) *cp++ = ch_next; else too_long = 1; } ungetc(ch_next, fp); *cp = '\0'; if (too_long) print_error("Warning: token too long", token, CONTINUE); for (tp = buckets[BUCKET(hash)]; tp; tp = tp->next) { if ((tp->hash == hash) && (!label_compare(tp->name, token))) break; } if (tp) { if (tp->token != CONTINUE) return (tp->token); while (isspace((ch_next = getc(fp)))) if (ch_next == '\n') mibLine++; if (ch_next == EOF) return ENDOFFILE; if (isalnum(ch_next)) { *cp++ = ch_next; hash += tolower(ch_next); goto more; } } if (token[0] == '-' || isdigit(token[0])) { for (cp = token + 1; *cp; cp++) if (!isdigit(*cp)) return LABEL; return NUMBER; } return LABEL; } } int snmp_get_token(FILE * fp, char *token, int maxtlen) { return get_token(fp, token, maxtlen); } int add_mibfile(const char* tmpstr, const char* d_name, FILE *ip ) { FILE *fp; char token[MAXTOKEN], token2[MAXTOKEN]; /* * which module is this */ if ((fp = fopen(tmpstr, "r")) == NULL) { snmp_log_perror(tmpstr); return 1; } DEBUGMSGTL(("parse-mibs", "Checking file: %s...\n", tmpstr)); mibLine = 1; File = tmpstr; get_token(fp, token, MAXTOKEN); /* * simple test for this being a MIB */ if (get_token(fp, token2, MAXTOKEN) == DEFINITIONS) { new_module(token, tmpstr); if (ip) fprintf(ip, "%s %s\n", token, d_name); fclose(fp); return 0; } else { fclose(fp); return 1; } } /* For Win32 platforms, the directory does not maintain a last modification * date that we can compare with the modification date of the .index file. * Therefore there is no way to know whether any .index file is valid. * This is the reason for the #if !(defined(WIN32) || defined(cygwin)) * in the add_mibdir function */ int add_mibdir(const char *dirname) { FILE *ip; DIR *dir, *dir2; const char *oldFile = File; struct dirent *file; char tmpstr[300]; int count = 0; int fname_len = 0; #if !(defined(WIN32) || defined(cygwin)) char token[MAXTOKEN]; char space; char newline; struct stat dir_stat, idx_stat; char tmpstr1[300]; int empty = 1; #endif DEBUGMSGTL(("parse-mibs", "Scanning directory %s\n", dirname)); #if !(defined(WIN32) || defined(cygwin)) snprintf(token, sizeof(token), "%s/%s", dirname, ".index"); token[ sizeof(token)-1 ] = 0; if (stat(token, &idx_stat) == 0 && stat(dirname, &dir_stat) == 0) { if (dir_stat.st_mtime < idx_stat.st_mtime) { DEBUGMSGTL(("parse-mibs", "The index is good\n")); if ((ip = fopen(token, "r")) != NULL) { while (fscanf(ip, "%127s%c%299s%c", token, &space, tmpstr, &newline) == 4) { empty = 0; /* * If an overflow of the token or tmpstr buffers has been * found log a message and break out of the while loop, * thus the rest of the file tokens will be ignored. */ if (space != ' ' || newline != '\n') { snmp_log(LOG_ERR, "add_mibdir: strings scanned in from %s/%s " \ "are too large. count = %d\n ", dirname, ".index", count); break; } snprintf(tmpstr1, sizeof(tmpstr1), "%s/%s", dirname, tmpstr); tmpstr1[ sizeof(tmpstr1)-1 ] = 0; new_module(token, tmpstr1); count++; } fclose(ip); if ( !empty ) { return count; } DEBUGMSGTL(("parse-mibs", "Empty MIB index\n")); } else DEBUGMSGTL(("parse-mibs", "Can't read index\n")); } else DEBUGMSGTL(("parse-mibs", "Index outdated\n")); } else DEBUGMSGTL(("parse-mibs", "No index\n")); #endif if ((dir = opendir(dirname))) { snprintf(tmpstr, sizeof(tmpstr), "%s/.index", dirname); tmpstr[ sizeof(tmpstr)-1 ] = 0; ip = fopen(tmpstr, "w"); while ((file = readdir(dir))) { /* * Only parse file names that don't begin with a '.' * Also skip files ending in '~', or starting/ending * with '#' which are typically editor backup files. */ if (file->d_name != NULL) { fname_len = strlen( file->d_name ); if (fname_len > 0 && file->d_name[0] != '.' && file->d_name[0] != '#' && file->d_name[fname_len-1] != '#' && file->d_name[fname_len-1] != '~') { snprintf(tmpstr, sizeof(tmpstr), "%s/%s", dirname, file->d_name); tmpstr[ sizeof(tmpstr)-1 ] = 0; if ((dir2 = opendir(tmpstr))) { /* * file is a directory, don't read it */ closedir(dir2); } else { if ( add_mibfile( tmpstr, file->d_name, ip )) count++; } } } } File = oldFile; closedir(dir); if (ip) fclose(ip); return (count); } else DEBUGMSGTL(("parse-mibs","cannot open MIB directory %s\n", dirname)); return (-1); } /* * Returns the root of the whole tree * (for backwards compatability) */ struct tree * read_mib(const char *filename) { FILE *fp; char token[MAXTOKEN]; fp = fopen(filename, "r"); if (fp == NULL) { snmp_log_perror(filename); return NULL; } mibLine = 1; File = filename; DEBUGMSGTL(("parse-mibs", "Parsing file: %s...\n", filename)); get_token(fp, token, MAXTOKEN); fclose(fp); new_module(token, filename); (void) netsnmp_read_module(token); return tree_head; } struct tree * read_all_mibs() { struct module *mp; for (mp = module_head; mp; mp = mp->next) if (mp->no_imports == -1) netsnmp_read_module(mp->name); adopt_orphans(); return tree_head; } #ifdef TEST main(int argc, char *argv[]) { int i; struct tree *tp; netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS, 2); netsnmp_init_mib(); if (argc == 1) (void) read_all_mibs(); else for (i = 1; i < argc; i++) read_mib(argv[i]); for (tp = tree_head; tp; tp = tp->next_peer) print_subtree(stdout, tp, 0); free_tree(tree_head); return 0; } #endif /* TEST */ static int parseQuoteString(FILE * fp, char *token, int maxtlen) { register int ch; int count = 0; int too_long = 0; char *token_start = token; for (ch = getc(fp); ch != EOF; ch = getc(fp)) { if (ch == '\r') continue; if (ch == '\n') { mibLine++; } else if (ch == '"') { *token = '\0'; if (too_long && netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS) > 1) { /* * show short form for brevity sake */ char ch_save = *(token_start + 50); *(token_start + 50) = '\0'; print_error("Warning: string too long", token_start, QUOTESTRING); *(token_start + 50) = ch_save; } return QUOTESTRING; } /* * maximum description length check. If greater, keep parsing * but truncate the string */ if (++count < maxtlen) *token++ = ch; else too_long = 1; } return 0; } /* * struct index_list * * getIndexes(FILE *fp): * This routine parses a string like { blah blah blah } and returns a * list of the strings enclosed within it. * */ static struct index_list * getIndexes(FILE * fp, struct index_list **retp) { int type; char token[MAXTOKEN]; char nextIsImplied = 0; struct index_list *mylist = NULL; struct index_list **mypp = &mylist; free_indexes(retp); type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { return NULL; } type = get_token(fp, token, MAXTOKEN); while (type != RIGHTBRACKET && type != ENDOFFILE) { if ((type == LABEL) || (type & SYNTAX_MASK)) { *mypp = (struct index_list *) calloc(1, sizeof(struct index_list)); if (*mypp) { (*mypp)->ilabel = strdup(token); (*mypp)->isimplied = nextIsImplied; mypp = &(*mypp)->next; nextIsImplied = 0; } } else if (type == IMPLIED) { nextIsImplied = 1; } type = get_token(fp, token, MAXTOKEN); } *retp = mylist; return mylist; } static struct varbind_list * getVarbinds(FILE * fp, struct varbind_list **retp) { int type; char token[MAXTOKEN]; struct varbind_list *mylist = NULL; struct varbind_list **mypp = &mylist; free_varbinds(retp); type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { return NULL; } type = get_token(fp, token, MAXTOKEN); while (type != RIGHTBRACKET && type != ENDOFFILE) { if ((type == LABEL) || (type & SYNTAX_MASK)) { *mypp = (struct varbind_list *) calloc(1, sizeof(struct varbind_list)); if (*mypp) { (*mypp)->vblabel = strdup(token); mypp = &(*mypp)->next; } } type = get_token(fp, token, MAXTOKEN); } *retp = mylist; return mylist; } static void free_indexes(struct index_list **spp) { if (spp && *spp) { struct index_list *pp, *npp; pp = *spp; *spp = NULL; while (pp) { npp = pp->next; if (pp->ilabel) free(pp->ilabel); free(pp); pp = npp; } } } static void free_varbinds(struct varbind_list **spp) { if (spp && *spp) { struct varbind_list *pp, *npp; pp = *spp; *spp = NULL; while (pp) { npp = pp->next; if (pp->vblabel) free(pp->vblabel); free(pp); pp = npp; } } } static void free_ranges(struct range_list **spp) { if (spp && *spp) { struct range_list *pp, *npp; pp = *spp; *spp = NULL; while (pp) { npp = pp->next; free(pp); pp = npp; } } } static void free_enums(struct enum_list **spp) { if (spp && *spp) { struct enum_list *pp, *npp; pp = *spp; *spp = NULL; while (pp) { npp = pp->next; if (pp->label) free(pp->label); free(pp); pp = npp; } } } static struct enum_list * copy_enums(struct enum_list *sp) { struct enum_list *xp = NULL, **spp = &xp; while (sp) { *spp = (struct enum_list *) calloc(1, sizeof(struct enum_list)); if (!*spp) break; (*spp)->label = strdup(sp->label); (*spp)->value = sp->value; spp = &(*spp)->next; sp = sp->next; } return (xp); } static struct range_list * copy_ranges(struct range_list *sp) { struct range_list *xp = NULL, **spp = &xp; while (sp) { *spp = (struct range_list *) calloc(1, sizeof(struct range_list)); if (!*spp) break; (*spp)->low = sp->low; (*spp)->high = sp->high; spp = &(*spp)->next; sp = sp->next; } return (xp); } /* * This routine parses a string like { blah blah blah } and returns OBJID if * it is well formed, and NULL if not. */ static int tossObjectIdentifier(FILE * fp) { int type; char token[MAXTOKEN]; int bracketcount = 1; type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) return 0; while ((type != RIGHTBRACKET || bracketcount > 0) && type != ENDOFFILE) { type = get_token(fp, token, MAXTOKEN); if (type == LEFTBRACKET) bracketcount++; else if (type == RIGHTBRACKET) bracketcount--; } if (type == RIGHTBRACKET) return OBJID; else return 0; } /* Find node in any MIB module Used by Perl modules */ struct tree * find_node(const char *name, struct tree *subtree) { /* Unused */ return (find_tree_node(name, -1)); } /* Find node in specific MIB module Used by Perl modules */ struct tree * find_node2(const char *name, const char *module) { int modid = -1; if (module) { modid = which_module(module); } if (modid == -1) { return (NULL); } return (find_tree_node(name, modid)); } struct module * find_module(int mid) { struct module *mp; for (mp = module_head; mp != NULL; mp = mp->next) { if (mp->modid == mid) break; } if (mp != 0) return mp; return NULL; } static char leave_indent[256]; static int leave_was_simple; static void print_mib_leaves(FILE * f, struct tree *tp, int width) { struct tree *ntp; char *ip = leave_indent + strlen(leave_indent) - 1; char last_ipch = *ip; *ip = '+'; if (tp->type == TYPE_OTHER || tp->type > TYPE_SIMPLE_LAST) { fprintf(f, "%s--%s(%ld)\n", leave_indent, tp->label, tp->subid); if (tp->indexes) { struct index_list *xp = tp->indexes; int first = 1, cpos = 0, len, cmax = width - strlen(leave_indent) - 12; *ip = last_ipch; fprintf(f, "%s | Index: ", leave_indent); while (xp) { if (first) first = 0; else fprintf(f, ", "); cpos += (len = strlen(xp->ilabel) + 2); if (cpos > cmax) { fprintf(f, "\n"); fprintf(f, "%s | ", leave_indent); cpos = len; } fprintf(f, "%s", xp->ilabel); xp = xp->next; } fprintf(f, "\n"); *ip = '+'; } } else { const char *acc, *typ; int size = 0; switch (tp->access) { case MIB_ACCESS_NOACCESS: acc = "----"; break; case MIB_ACCESS_READONLY: acc = "-R--"; break; case MIB_ACCESS_WRITEONLY: acc = "--W-"; break; case MIB_ACCESS_READWRITE: acc = "-RW-"; break; case MIB_ACCESS_NOTIFY: acc = "---N"; break; case MIB_ACCESS_CREATE: acc = "CR--"; break; default: acc = " "; break; } switch (tp->type) { case TYPE_OBJID: typ = "ObjID "; break; case TYPE_OCTETSTR: typ = "String "; size = 1; break; case TYPE_INTEGER: if (tp->enums) typ = "EnumVal "; else typ = "INTEGER "; break; case TYPE_NETADDR: typ = "NetAddr "; break; case TYPE_IPADDR: typ = "IpAddr "; break; case TYPE_COUNTER: typ = "Counter "; break; case TYPE_GAUGE: typ = "Gauge "; break; case TYPE_TIMETICKS: typ = "TimeTicks"; break; case TYPE_OPAQUE: typ = "Opaque "; size = 1; break; case TYPE_NULL: typ = "Null "; break; case TYPE_COUNTER64: typ = "Counter64"; break; case TYPE_BITSTRING: typ = "BitString"; break; case TYPE_NSAPADDRESS: typ = "NsapAddr "; break; case TYPE_UNSIGNED32: typ = "Unsigned "; break; case TYPE_UINTEGER: typ = "UInteger "; break; case TYPE_INTEGER32: typ = "Integer32"; break; default: typ = " "; break; } fprintf(f, "%s-- %s %s %s(%ld)\n", leave_indent, acc, typ, tp->label, tp->subid); *ip = last_ipch; if (tp->tc_index >= 0) fprintf(f, "%s Textual Convention: %s\n", leave_indent, tclist[tp->tc_index].descriptor); if (tp->enums) { struct enum_list *ep = tp->enums; int cpos = 0, cmax = width - strlen(leave_indent) - 16; fprintf(f, "%s Values: ", leave_indent); while (ep) { char buf[80]; int bufw; if (ep != tp->enums) fprintf(f, ", "); snprintf(buf, sizeof(buf), "%s(%d)", ep->label, ep->value); buf[ sizeof(buf)-1 ] = 0; cpos += (bufw = strlen(buf) + 2); if (cpos >= cmax) { fprintf(f, "\n%s ", leave_indent); cpos = bufw; } fprintf(f, "%s", buf); ep = ep->next; } fprintf(f, "\n"); } if (tp->ranges) { struct range_list *rp = tp->ranges; if (size) fprintf(f, "%s Size: ", leave_indent); else fprintf(f, "%s Range: ", leave_indent); while (rp) { if (rp != tp->ranges) fprintf(f, " | "); if (rp->low == rp->high) fprintf(f, "%d", rp->low); else fprintf(f, "%d..%d", rp->low, rp->high); rp = rp->next; } fprintf(f, "\n"); } } *ip = last_ipch; strcat(leave_indent, " |"); leave_was_simple = tp->type != TYPE_OTHER; { int i, j, count = 0; struct leave { oid id; struct tree *tp; } *leaves, *lp; for (ntp = tp->child_list; ntp; ntp = ntp->next_peer) count++; if (count) { leaves = (struct leave *) calloc(count, sizeof(struct leave)); if (!leaves) return; for (ntp = tp->child_list, count = 0; ntp; ntp = ntp->next_peer) { for (i = 0, lp = leaves; i < count; i++, lp++) if (lp->id >= ntp->subid) break; for (j = count; j > i; j--) leaves[j] = leaves[j - 1]; lp->id = ntp->subid; lp->tp = ntp; count++; } for (i = 1, lp = leaves; i <= count; i++, lp++) { if (!leave_was_simple || lp->tp->type == 0) fprintf(f, "%s\n", leave_indent); if (i == count) ip[3] = ' '; print_mib_leaves(f, lp->tp, width); } free(leaves); leave_was_simple = 0; } } ip[1] = 0; } void print_mib_tree(FILE * f, struct tree *tp, int width) { leave_indent[0] = ' '; leave_indent[1] = 0; leave_was_simple = 1; print_mib_leaves(f, tp, width); } /* * Merge the parsed object identifier with the existing node. * If there is a problem with the identifier, release the existing node. */ static struct node * merge_parse_objectid(struct node *np, FILE * fp, char *name) { struct node *nnp; /* * printf("merge defval --> %s\n",np->defaultValue); */ nnp = parse_objectid(fp, name); if (nnp) { /* * apply last OID sub-identifier data to the information */ /* * already collected for this node. */ struct node *headp, *nextp; int ncount = 0; nextp = headp = nnp; while (nnp->next) { nextp = nnp; ncount++; nnp = nnp->next; } np->label = nnp->label; np->subid = nnp->subid; np->modid = nnp->modid; np->parent = nnp->parent; if (nnp->filename != NULL) { free(nnp->filename); } free(nnp); if (ncount) { nextp->next = np; np = headp; } } else { free_node(np); np = NULL; } return np; } /* * transfer data to tree from node * * move pointers for alloc'd data from np to tp. * this prevents them from being freed when np is released. * parent member is not moved. * * CAUTION: nodes may be repeats of existing tree nodes. * This can happen especially when resolving IMPORT clauses. * */ static void tree_from_node(struct tree *tp, struct node *np) { free_partial_tree(tp, FALSE); tp->label = np->label; np->label = NULL; tp->enums = np->enums; np->enums = NULL; tp->ranges = np->ranges; np->ranges = NULL; tp->indexes = np->indexes; np->indexes = NULL; tp->augments = np->augments; np->augments = NULL; tp->varbinds = np->varbinds; np->varbinds = NULL; tp->hint = np->hint; np->hint = NULL; tp->units = np->units; np->units = NULL; tp->description = np->description; np->description = NULL; tp->reference = np->reference; np->reference = NULL; tp->defaultValue = np->defaultValue; np->defaultValue = NULL; tp->subid = np->subid; tp->tc_index = np->tc_index; tp->type = translation_table[np->type]; tp->access = np->access; tp->status = np->status; set_function(tp); } #endif /* NETSNMP_DISABLE_MIB_LOADING */
odit/rv042
linux/embedded_rootfs/pkg_addon/net-snmp-5.4.1.2/snmplib/parse.c
C
gpl-2.0
164,582
/* * Asterisk -- An open source telephony toolkit. * * Copyright (C) 2007, Digium, Inc. * * See http://www.iaxproxy.org for more information about * the Asterisk project. Please do not directly contact * any of the maintainers of this project for assistance; * the project provides a web site, mailing lists and IRC * channels for your use. * * This program is free software, distributed under the terms of * the GNU General Public License Version 2. See the LICENSE file * at the top of the source tree. */ /*! \file * * \brief Dialplan group functions check if a dialplan entry exists * * \author Gregory Nietsky AKA irroot <gregory@networksentry.co.za> * \author Russell Bryant <russell@digium.com> * * \ingroup functions */ #include "iaxproxy.h" ASTERISK_FILE_VERSION(__FILE__, "$Revision: 211580 $") #include "iaxproxy/module.h" #include "iaxproxy/channel.h" #include "iaxproxy/pbx.h" #include "iaxproxy/app.h" /*** DOCUMENTATION <function name="DIALPLAN_EXISTS" language="en_US"> <synopsis> Checks the existence of a dialplan target. </synopsis> <syntax> <parameter name="context" required="true" /> <parameter name="extension" /> <parameter name="priority" /> </syntax> <description> <para>This function returns <literal>1</literal> if the target exits. Otherwise, it returns <literal>0</literal>.</para> </description> </function> ***/ static int isexten_function_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len) { char *parse; AST_DECLARE_APP_ARGS(args, AST_APP_ARG(context); AST_APP_ARG(exten); AST_APP_ARG(priority); ); strcpy(buf, "0"); if (ast_strlen_zero(data)) { ast_log(LOG_ERROR, "DIALPLAN_EXISTS() requires an argument\n"); return -1; } parse = ast_strdupa(data); AST_STANDARD_APP_ARGS(args, parse); if (!ast_strlen_zero(args.priority)) { int priority_num; if (sscanf(args.priority, "%30d", &priority_num) == 1 && priority_num > 0) { int res; res = ast_exists_extension(chan, args.context, args.exten, priority_num, chan->cid.cid_num); if (res) strcpy(buf, "1"); } else { int res; res = ast_findlabel_extension(chan, args.context, args.exten, args.priority, chan->cid.cid_num); if (res > 0) strcpy(buf, "1"); } } else if (!ast_strlen_zero(args.exten)) { int res; res = ast_exists_extension(chan, args.context, args.exten, 1, chan->cid.cid_num); if (res) strcpy(buf, "1"); } else if (!ast_strlen_zero(args.context)) { if (ast_context_find(args.context)) strcpy(buf, "1"); } else { ast_log(LOG_ERROR, "Invalid arguments provided to DIALPLAN_EXISTS\n"); return -1; } return 0; } static struct ast_custom_function isexten_function = { .name = "DIALPLAN_EXISTS", .read = isexten_function_read, }; static int unload_module(void) { return ast_custom_function_unregister(&isexten_function); } static int load_module(void) { return ast_custom_function_register(&isexten_function); } AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Dialplan Context/Extension/Priority Checking Functions");
primuslabs/iaxproxy
funcs/func_dialplan.c
C
gpl-2.0
3,095
/* * (C) 2007-2010 Taobao Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * * Version: $Id$ * * Authors: * duolong <duolong@taobao.com> * */ #ifndef TBSYS_RUNNABLE_H_ #define TBSYS_RUNNABLE_H_ namespace tbsys { /** * @brief RunnableÊÇÒ»¸ö³éÏóÀ࣬ËüÓµÓÐÒ»¸örun´¿Ðé·½·¨ * Ö÷ÒªÓÃÓÚThreadÀà */ class Runnable { public: /* * Îö¹¹ */ virtual ~Runnable() { } /** * ÔËÐÐÈë¿Úº¯Êý */ virtual void run(CThread *thread, void *arg) = 0; }; } #endif /*RUNNABLE_H_*/
heartsg/oceanbase
tb-common-utils/tbsys/src/runnable.h
C
gpl-2.0
664
<?php namespace Wikia\Sass\Filter; /** * Base64 filter handles encoding and embedding files in CSS stylesheet * for URLs marked to be processed that way. * * @author Inez Korczyński <korczynski@gmail.com> * @author Piotr Bablok <piotr.bablok@gmail.com> * @author Władysław Bodzek <wladek@wikia-inc.com> */ class Base64Filter extends Filter { protected $rootDir; public function __construct( $rootDir ) { $this->rootDir = $rootDir; } public function process( $contents ) { wfProfileIn(__METHOD__); $contents = preg_replace_callback("/([, ]url[^\n]*?)(\s*\/\*\s*base64\s*\*\/)/is", array( $this, 'processMatches' ), $contents); wfProfileOut(__METHOD__); return $contents; } protected function processMatches($matches) { $fileName = $this->rootDir . trim(substr($matches[1], 4, -1), '\'"() '); $encoded = $this->encodeFile($fileName); if ($encoded !== false) { return "url({$encoded});"; } else { throw new \Wikia\Sass\Exception("/* Base64 encoding failed: {$fileName} not found! */"); } } protected function encodeFile( $fileName ) { wfProfileIn(__METHOD__); if (!file_exists($fileName)) { wfProfileOut(__METHOD__); return false; } $parts = explode('.', $fileName); $ext = end($parts); switch ($ext) { case 'gif': case 'png': $type = $ext; break; case 'jpg': $type = 'jpeg'; break; // not supported image type provided default: wfProfileOut(__METHOD__); return false; } $content = file_get_contents($fileName); $encoded = base64_encode($content); wfProfileOut(__METHOD__); return "data:image/{$type};base64,{$encoded}"; } }
Wikia/OldStructuredDataPrototype
includes/wikia/services/sass/Filter/Base64Filter.class.php
PHP
gpl-2.0
1,655
/* * Copyright (C) 2013 Team XBMC * http://xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, 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 XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include <limits.h> #include <netinet/in.h> #include <sys/socket.h> #include <arpa/inet.h> #include "system.h" #include "network/Network.h" #include "Application.h" #include "DNSNameCache.h" #include "dialogs/GUIDialogProgress.h" #include "dialogs/GUIDialogKaiToast.h" #include "filesystem/SpecialProtocol.h" #include "guilib/GUIWindowManager.h" #include "guilib/LocalizeStrings.h" #include "settings/AdvancedSettings.h" #include "settings/Settings.h" #include "settings/MediaSourceSettings.h" #include "utils/JobManager.h" #include "utils/log.h" #include "utils/XMLUtils.h" #include "utils/URIUtils.h" #include "utils/StringUtils.h" #include "utils/Variant.h" #include "WakeOnAccess.h" #define DEFAULT_NETWORK_INIT_SEC (20) // wait 20 sec for network after startup or resume #define DEFAULT_NETWORK_SETTLE_MS (500) // require 500ms of consistent network availability before trusting it #define DEFAULT_TIMEOUT_SEC (5*60) // at least 5 minutes between each magic packets #define DEFAULT_WAIT_FOR_ONLINE_SEC_1 (40) // wait at 40 seconds after sending magic packet #define DEFAULT_WAIT_FOR_ONLINE_SEC_2 (40) // same for extended wait #define DEFAULT_WAIT_FOR_SERVICES_SEC (5) // wait 5 seconds after host go online to launch file sharing deamons static int GetTotalSeconds(const CDateTimeSpan& ts) { int hours = ts.GetHours() + ts.GetDays() * 24; int minutes = ts.GetMinutes() + hours * 60; return ts.GetSeconds() + minutes * 60; } static unsigned long HostToIP(const std::string& host) { std::string ip; CDNSNameCache::Lookup(host, ip); return inet_addr(ip.c_str()); } CWakeOnAccess::WakeUpEntry::WakeUpEntry (bool isAwake) : timeout (0, 0, 0, DEFAULT_TIMEOUT_SEC) , wait_online1_sec(DEFAULT_WAIT_FOR_ONLINE_SEC_1) , wait_online2_sec(DEFAULT_WAIT_FOR_ONLINE_SEC_2) , wait_services_sec(DEFAULT_WAIT_FOR_SERVICES_SEC) , ping_port(0), ping_mode(0) { nextWake = CDateTime::GetCurrentDateTime(); if (isAwake) nextWake += timeout; } //** class CMACDiscoveryJob : public CJob { public: CMACDiscoveryJob(const std::string& host) : m_host(host) {} virtual bool DoWork(); const std::string& GetMAC() const { return m_macAddres; } const std::string& GetHost() const { return m_host; } private: std::string m_macAddres; std::string m_host; }; bool CMACDiscoveryJob::DoWork() { unsigned long ipAddress = HostToIP(m_host); if (ipAddress == INADDR_NONE) { CLog::Log(LOGERROR, "%s - can't determine ip of '%s'", __FUNCTION__, m_host.c_str()); return false; } std::vector<CNetworkInterface*>& ifaces = g_application.getNetwork().GetInterfaceList(); for (std::vector<CNetworkInterface*>::const_iterator it = ifaces.begin(); it != ifaces.end(); ++it) { if ((*it)->GetHostMacAddress(ipAddress, m_macAddres)) return true; } return false; } //** class WaitCondition { public: virtual bool SuccessWaiting () const { return false; } }; // class NestDetect { public: NestDetect() : m_gui_thread (g_application.IsCurrentThread()) { if (m_gui_thread) ++m_nest; } ~NestDetect() { if (m_gui_thread) m_nest--; } static int Level() { return m_nest; } bool IsNested() const { return m_gui_thread && m_nest > 1; } private: static int m_nest; const bool m_gui_thread; }; int NestDetect::m_nest = 0; // class ProgressDialogHelper { public: ProgressDialogHelper (const std::string& heading) : m_dialog(0) { if (g_application.IsCurrentThread()) m_dialog = (CGUIDialogProgress*) g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS); if (m_dialog) { m_dialog->SetHeading(CVariant{heading}); m_dialog->SetLine(0, CVariant{""}); m_dialog->SetLine(1, CVariant{""}); m_dialog->SetLine(2, CVariant{""}); int nest_level = NestDetect::Level(); if (nest_level > 1) { m_dialog->SetLine(2, CVariant{StringUtils::Format("Nesting:%d", nest_level)}); } } } ~ProgressDialogHelper () { if (m_dialog) m_dialog->Close(); } bool HasDialog() const { return m_dialog != 0; } enum wait_result { TimedOut, Canceled, Success }; wait_result ShowAndWait (const WaitCondition& waitObj, unsigned timeOutSec, const std::string& line1) { unsigned timeOutMs = timeOutSec * 1000; if (m_dialog) { m_dialog->SetLine(1, CVariant{line1}); m_dialog->SetPercentage(1); // avoid flickering by starting at 1% .. } XbmcThreads::EndTime end_time (timeOutMs); while (!end_time.IsTimePast()) { if (waitObj.SuccessWaiting()) return Success; if (m_dialog) { if (!m_dialog->IsActive()) m_dialog->Open(); if (m_dialog->IsCanceled()) return Canceled; m_dialog->Progress(); unsigned ms_passed = timeOutMs - end_time.MillisLeft(); int percentage = (ms_passed * 100) / timeOutMs; m_dialog->SetPercentage(std::max(percentage, 1)); // avoid flickering , keep minimum 1% } Sleep (m_dialog ? 20 : 200); } return TimedOut; } private: CGUIDialogProgress* m_dialog; }; class NetworkStartWaiter : public WaitCondition { public: NetworkStartWaiter (unsigned settle_time_ms, const std::string& host) : m_settle_time_ms (settle_time_ms), m_host(host) { } virtual bool SuccessWaiting () const { unsigned long address = ntohl(HostToIP(m_host)); bool online = g_application.getNetwork().HasInterfaceForIP(address); if (!online) // setup endtime so we dont return true until network is consistently connected m_end.Set (m_settle_time_ms); return online && m_end.IsTimePast(); } private: mutable XbmcThreads::EndTime m_end; unsigned m_settle_time_ms; const std::string m_host; }; class PingResponseWaiter : public WaitCondition, private IJobCallback { public: PingResponseWaiter (bool async, const CWakeOnAccess::WakeUpEntry& server) : m_server(server), m_jobId(0), m_hostOnline(false) { if (async) { CJob* job = new CHostProberJob(server); m_jobId = CJobManager::GetInstance().AddJob(job, this); } } ~PingResponseWaiter() { CJobManager::GetInstance().CancelJob(m_jobId); } virtual bool SuccessWaiting () const { return m_jobId ? m_hostOnline : Ping(m_server); } virtual void OnJobComplete(unsigned int jobID, bool success, CJob *job) { m_hostOnline = success; } static bool Ping (const CWakeOnAccess::WakeUpEntry& server) { ULONG dst_ip = HostToIP(server.host); return g_application.getNetwork().PingHost(dst_ip, server.ping_port, 2000, server.ping_mode & 1); } private: class CHostProberJob : public CJob { public: CHostProberJob(const CWakeOnAccess::WakeUpEntry& server) : m_server (server) {} virtual bool DoWork() { while (!ShouldCancel(0,0)) { if (PingResponseWaiter::Ping(m_server)) return true; } return false; } private: const CWakeOnAccess::WakeUpEntry& m_server; }; const CWakeOnAccess::WakeUpEntry& m_server; unsigned int m_jobId; bool m_hostOnline; }; // CWakeOnAccess::CWakeOnAccess() : m_netinit_sec(DEFAULT_NETWORK_INIT_SEC) // wait for network to connect , m_netsettle_ms(DEFAULT_NETWORK_SETTLE_MS) // wait for network to settle , m_enabled(false) { } CWakeOnAccess &CWakeOnAccess::GetInstance() { static CWakeOnAccess sWakeOnAccess; return sWakeOnAccess; } bool CWakeOnAccess::WakeUpHost(const CURL& url) { std::string hostName = url.GetHostName(); if (!hostName.empty()) return WakeUpHost (hostName, url.Get()); return true; } bool CWakeOnAccess::WakeUpHost (const std::string& hostName, const std::string& customMessage) { if (!IsEnabled()) return true; // bail if feature is turned off WakeUpEntry server; if (FindOrTouchHostEntry(hostName, server)) { CLog::Log(LOGNOTICE,"WakeOnAccess [%s] trigged by accessing : %s", hostName.c_str(), customMessage.c_str()); NestDetect nesting ; // detect recursive calls on gui thread.. if (nesting.IsNested()) // we might get in trouble if it gets called back in loop CLog::Log(LOGWARNING,"WakeOnAccess recursively called on gui-thread [%d]", NestDetect::Level()); bool ret = WakeUpHost(server); if (!ret) // extra log if we fail for some reason CLog::Log(LOGWARNING,"WakeOnAccess failed to bring up [%s] - there may be trouble ahead !", hostName.c_str()); TouchHostEntry(hostName); return ret; } return true; } #define LOCALIZED(id) g_localizeStrings.Get(id) bool CWakeOnAccess::WakeUpHost(const WakeUpEntry& server) { std::string heading = StringUtils::Format(LOCALIZED(13027).c_str(), server.host.c_str()); ProgressDialogHelper dlg (heading); { NetworkStartWaiter waitObj (m_netsettle_ms, server.host); // wait until network connected before sending wake-on-lan if (dlg.ShowAndWait (waitObj, m_netinit_sec, LOCALIZED(13028)) != ProgressDialogHelper::Success) { if (g_application.getNetwork().IsConnected() && HostToIP(server.host) == INADDR_NONE) { // network connected (at least one interface) but dns-lookup failed (host by name, not ip-address), so dont abort yet CLog::Log(LOGWARNING, "WakeOnAccess timeout/cancel while waiting for network (proceeding anyway)"); } else { CLog::Log(LOGNOTICE, "WakeOnAccess timeout/cancel while waiting for network"); return false; // timedout or canceled ; give up } } } { ULONG dst_ip = HostToIP(server.host); if (g_application.getNetwork().PingHost(dst_ip, server.ping_port, 500)) // quick ping with short timeout to not block too long { CLog::Log(LOGNOTICE,"WakeOnAccess success exit, server already running"); return true; } } if (!g_application.getNetwork().WakeOnLan(server.mac.c_str())) { CLog::Log(LOGERROR,"WakeOnAccess failed to send. (Is it blocked by firewall?)"); if (g_application.IsCurrentThread() || !g_application.m_pPlayer->IsPlaying()) CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Error, heading, LOCALIZED(13029)); return false; } { PingResponseWaiter waitObj (dlg.HasDialog(), server); // wait for ping response .. ProgressDialogHelper::wait_result result = dlg.ShowAndWait (waitObj, server.wait_online1_sec, LOCALIZED(13030)); if (result == ProgressDialogHelper::TimedOut) result = dlg.ShowAndWait (waitObj, server.wait_online2_sec, LOCALIZED(13031)); if (result != ProgressDialogHelper::Success) { CLog::Log(LOGNOTICE,"WakeOnAccess timeout/cancel while waiting for response"); return false; // timedout or canceled } } // we have ping response ; just add extra wait-for-services before returning if requested { WaitCondition waitObj ; // wait uninteruptable fixed time for services .. dlg.ShowAndWait (waitObj, server.wait_services_sec, LOCALIZED(13032)); CLog::Log(LOGNOTICE,"WakeOnAccess sequence completed, server started"); } return true; } bool CWakeOnAccess::FindOrTouchHostEntry (const std::string& hostName, WakeUpEntry& result) { CSingleLock lock (m_entrylist_protect); bool need_wakeup = false; for (EntriesVector::iterator i = m_entries.begin();i != m_entries.end(); ++i) { WakeUpEntry& server = *i; if (StringUtils::EqualsNoCase(hostName, server.host)) { CDateTime now = CDateTime::GetCurrentDateTime(); if (now > server.nextWake) { result = server; need_wakeup = true; } else // 'touch' next wakeup time { server.nextWake = now + server.timeout; } break; } } return need_wakeup; } void CWakeOnAccess::TouchHostEntry (const std::string& hostName) { CSingleLock lock (m_entrylist_protect); for (EntriesVector::iterator i = m_entries.begin();i != m_entries.end(); ++i) { WakeUpEntry& server = *i; if (StringUtils::EqualsNoCase(hostName, server.host)) { server.nextWake = CDateTime::GetCurrentDateTime() + server.timeout; return; } } } static void AddHost (const std::string& host, std::vector<std::string>& hosts) { for (std::vector<std::string>::const_iterator it = hosts.begin(); it != hosts.end(); ++it) if (StringUtils::EqualsNoCase(host, *it)) return; // allready there .. if (!host.empty()) hosts.push_back(host); } static void AddHostFromDatabase(const DatabaseSettings& setting, std::vector<std::string>& hosts) { if (StringUtils::EqualsNoCase(setting.type, "mysql")) AddHost(setting.host, hosts); } void CWakeOnAccess::QueueMACDiscoveryForHost(const std::string& host) { if (IsEnabled()) { if (URIUtils::IsHostOnLAN(host, true)) CJobManager::GetInstance().AddJob(new CMACDiscoveryJob(host), this); else CLog::Log(LOGNOTICE, "%s - skip Mac discovery for non-local host '%s'", __FUNCTION__, host.c_str()); } } static void AddHostsFromMediaSource(const CMediaSource& source, std::vector<std::string>& hosts) { for (std::vector<std::string>::const_iterator it = source.vecPaths.begin() ; it != source.vecPaths.end(); ++it) { CURL url(*it); AddHost (url.GetHostName(), hosts); } } static void AddHostsFromVecSource(const VECSOURCES& sources, std::vector<std::string>& hosts) { for (VECSOURCES::const_iterator it = sources.begin(); it != sources.end(); ++it) AddHostsFromMediaSource(*it, hosts); } static void AddHostsFromVecSource(const VECSOURCES* sources, std::vector<std::string>& hosts) { if (sources) AddHostsFromVecSource(*sources, hosts); } void CWakeOnAccess::QueueMACDiscoveryForAllRemotes() { std::vector<std::string> hosts; // add media sources CMediaSourceSettings& ms = CMediaSourceSettings::GetInstance(); AddHostsFromVecSource(ms.GetSources("video"), hosts); AddHostsFromVecSource(ms.GetSources("music"), hosts); AddHostsFromVecSource(ms.GetSources("files"), hosts); AddHostsFromVecSource(ms.GetSources("pictures"), hosts); AddHostsFromVecSource(ms.GetSources("programs"), hosts); // add mysql servers AddHostFromDatabase(g_advancedSettings.m_databaseVideo, hosts); AddHostFromDatabase(g_advancedSettings.m_databaseMusic, hosts); AddHostFromDatabase(g_advancedSettings.m_databaseEpg, hosts); AddHostFromDatabase(g_advancedSettings.m_databaseTV, hosts); // add from path substitutions .. for (CAdvancedSettings::StringMapping::iterator i = g_advancedSettings.m_pathSubstitutions.begin(); i != g_advancedSettings.m_pathSubstitutions.end(); ++i) { CURL url(i->second); AddHost (url.GetHostName(), hosts); } for (std::vector<std::string>::const_iterator it = hosts.begin(); it != hosts.end(); ++it) QueueMACDiscoveryForHost(*it); } void CWakeOnAccess::SaveMACDiscoveryResult(const std::string& host, const std::string& mac) { CLog::Log(LOGNOTICE, "%s - Mac discovered for host '%s' -> '%s'", __FUNCTION__, host.c_str(), mac.c_str()); std::string heading = LOCALIZED(13033); for (EntriesVector::iterator i = m_entries.begin(); i != m_entries.end(); ++i) { if (StringUtils::EqualsNoCase(host, i->host)) { CLog::Log(LOGDEBUG, "%s - Update existing entry for host '%s'", __FUNCTION__, host.c_str()); if (!StringUtils::EqualsNoCase(mac, i->mac)) { if (IsEnabled()) // show notification only if we have general feature enabled { std::string message = StringUtils::Format(LOCALIZED(13034).c_str(), host.c_str()); CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Info, heading, message, 4000, true, 3000); } i->mac = mac; SaveToXML(); } return; } } // not found entry to update - create using default values WakeUpEntry entry (true); entry.host = host; entry.mac = mac; m_entries.push_back(entry); CLog::Log(LOGDEBUG, "%s - Create new entry for host '%s'", __FUNCTION__, host.c_str()); if (IsEnabled()) // show notification only if we have general feature enabled { std::string message = StringUtils::Format(LOCALIZED(13035).c_str(), host.c_str()); CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Info, heading, message, 4000, true, 3000); } SaveToXML(); } void CWakeOnAccess::OnJobComplete(unsigned int jobID, bool success, CJob *job) { CMACDiscoveryJob* discoverJob = (CMACDiscoveryJob*)job; const std::string& host = discoverJob->GetHost(); const std::string& mac = discoverJob->GetMAC(); if (success) { CSingleLock lock (m_entrylist_protect); SaveMACDiscoveryResult(host, mac); } else { CLog::Log(LOGERROR, "%s - Mac discovery failed for host '%s'", __FUNCTION__, host.c_str()); if (IsEnabled()) { std::string heading = LOCALIZED(13033); std::string message = StringUtils::Format(LOCALIZED(13036).c_str(), host.c_str()); CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Error, heading, message, 4000, true, 3000); } } } void CWakeOnAccess::OnSettingChanged(const CSetting *setting) { if (setting == nullptr) return; const std::string& settingId = setting->GetId(); if (settingId == CSettings::SETTING_POWERMANAGEMENT_WAKEONACCESS) { bool enabled = static_cast<const CSettingBool*>(setting)->GetValue(); SetEnabled(enabled); if (enabled) QueueMACDiscoveryForAllRemotes(); } } std::string CWakeOnAccess::GetSettingFile() { return CSpecialProtocol::TranslatePath("special://profile/wakeonlan.xml"); } void CWakeOnAccess::OnSettingsLoaded() { CSingleLock lock (m_entrylist_protect); LoadFromXML(); } void CWakeOnAccess::SetEnabled(bool enabled) { m_enabled = enabled; CLog::Log(LOGNOTICE,"WakeOnAccess - Enabled:%s", m_enabled ? "TRUE" : "FALSE"); } void CWakeOnAccess::LoadFromXML() { bool enabled = CSettings::GetInstance().GetBool(CSettings::SETTING_POWERMANAGEMENT_WAKEONACCESS); CXBMCTinyXML xmlDoc; if (!xmlDoc.LoadFile(GetSettingFile())) { if (enabled) CLog::Log(LOGNOTICE, "%s - unable to load:%s", __FUNCTION__, GetSettingFile().c_str()); return; } TiXmlElement* pRootElement = xmlDoc.RootElement(); if (strcmpi(pRootElement->Value(), "onaccesswakeup")) { CLog::Log(LOGERROR, "%s - XML file %s doesnt contain <onaccesswakeup>", __FUNCTION__, GetSettingFile().c_str()); return; } m_entries.clear(); CLog::Log(LOGNOTICE,"WakeOnAccess - Load settings :"); SetEnabled(enabled); int tmp; if (XMLUtils::GetInt(pRootElement, "netinittimeout", tmp, 0, 5 * 60)) m_netinit_sec = tmp; CLog::Log(LOGNOTICE," -Network init timeout : [%d] sec", m_netinit_sec); if (XMLUtils::GetInt(pRootElement, "netsettletime", tmp, 0, 5 * 1000)) m_netsettle_ms = tmp; CLog::Log(LOGNOTICE," -Network settle time : [%d] ms", m_netsettle_ms); const TiXmlNode* pWakeUp = pRootElement->FirstChildElement("wakeup"); while (pWakeUp) { WakeUpEntry entry; std::string strtmp; if (XMLUtils::GetString(pWakeUp, "host", strtmp)) entry.host = strtmp; if (XMLUtils::GetString(pWakeUp, "mac", strtmp)) entry.mac = strtmp; if (entry.host.empty()) CLog::Log(LOGERROR, "%s - Missing <host> tag or it's empty", __FUNCTION__); else if (entry.mac.empty()) CLog::Log(LOGERROR, "%s - Missing <mac> tag or it's empty", __FUNCTION__); else { if (XMLUtils::GetInt(pWakeUp, "pingport", tmp, 0, USHRT_MAX)) entry.ping_port = (unsigned short) tmp; if (XMLUtils::GetInt(pWakeUp, "pingmode", tmp, 0, USHRT_MAX)) entry.ping_mode = (unsigned short) tmp; if (XMLUtils::GetInt(pWakeUp, "timeout", tmp, 10, 12 * 60 * 60)) entry.timeout.SetDateTimeSpan (0, 0, 0, tmp); if (XMLUtils::GetInt(pWakeUp, "waitonline", tmp, 0, 10 * 60)) // max 10 minutes entry.wait_online1_sec = tmp; if (XMLUtils::GetInt(pWakeUp, "waitonline2", tmp, 0, 10 * 60)) // max 10 minutes entry.wait_online2_sec = tmp; if (XMLUtils::GetInt(pWakeUp, "waitservices", tmp, 0, 5 * 60)) // max 5 minutes entry.wait_services_sec = tmp; CLog::Log(LOGNOTICE," Registering wakeup entry:"); CLog::Log(LOGNOTICE," HostName : %s", entry.host.c_str()); CLog::Log(LOGNOTICE," MacAddress : %s", entry.mac.c_str()); CLog::Log(LOGNOTICE," PingPort : %d", entry.ping_port); CLog::Log(LOGNOTICE," PingMode : %d", entry.ping_mode); CLog::Log(LOGNOTICE," Timeout : %d (sec)", GetTotalSeconds(entry.timeout)); CLog::Log(LOGNOTICE," WaitForOnline : %d (sec)", entry.wait_online1_sec); CLog::Log(LOGNOTICE," WaitForOnlineEx : %d (sec)", entry.wait_online2_sec); CLog::Log(LOGNOTICE," WaitForServices : %d (sec)", entry.wait_services_sec); m_entries.push_back(entry); } pWakeUp = pWakeUp->NextSiblingElement("wakeup"); // get next one } } void CWakeOnAccess::SaveToXML() { CXBMCTinyXML xmlDoc; TiXmlElement xmlRootElement("onaccesswakeup"); TiXmlNode *pRoot = xmlDoc.InsertEndChild(xmlRootElement); if (!pRoot) return; XMLUtils::SetInt(pRoot, "netinittimeout", m_netinit_sec); XMLUtils::SetInt(pRoot, "netsettletime", m_netsettle_ms); for (EntriesVector::const_iterator i = m_entries.begin(); i != m_entries.end(); ++i) { TiXmlElement xmlSetting("wakeup"); TiXmlNode* pWakeUpNode = pRoot->InsertEndChild(xmlSetting); if (pWakeUpNode) { XMLUtils::SetString(pWakeUpNode, "host", i->host); XMLUtils::SetString(pWakeUpNode, "mac", i->mac); XMLUtils::SetInt(pWakeUpNode, "pingport", i->ping_port); XMLUtils::SetInt(pWakeUpNode, "pingmode", i->ping_mode); XMLUtils::SetInt(pWakeUpNode, "timeout", GetTotalSeconds(i->timeout)); XMLUtils::SetInt(pWakeUpNode, "waitonline", i->wait_online1_sec); XMLUtils::SetInt(pWakeUpNode, "waitonline2", i->wait_online2_sec); XMLUtils::SetInt(pWakeUpNode, "waitservices", i->wait_services_sec); } } xmlDoc.SaveFile(GetSettingFile()); }
virtuallysafe/kodi
xbmc/network/WakeOnAccess.cpp
C++
gpl-2.0
22,820
/** Copyright 2011 Red Hat, Inc. This software is licensed to you under the GNU General Public License as published by the Free Software Foundation; either version 2 of the License (GPLv2) or (at your option) any later version. There is NO WARRANTY for this software, express or implied, including the implied warranties of MERCHANTABILITY, NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 along with this software; if not, see http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. */ var notices = (function() { return { setup_notices: function(pollingTimeOut) { if (pollingTimeOut === undefined) { pollingTimeOut = 45000; } notices.checkTimeout = pollingTimeOut; //start continual checking for new notifications notices.start(); }, clearPreviousFailures: function(requestType) { $('.' + requestType).closest('.jnotify-notification').remove(); }, displayNotice: function(level, notice, requestType) { var noticesParsed = $.parseJSON(notice), options = { type: level, slideSpeed: 200, alwaysClosable: true }, generate_list = function(notices){ var notices_list = '<ul class='+requestType+'>', i, length = notices.length; for( i=0; i < length; i += 1) { notices_list += '<li>' + notices[i] + '</li>'; } notices_list += '</ul>'; return notices_list; }; if (level === 'success') { notices.clearPreviousFailures(requestType); } if ((level === "error") || (level === "warning")) { options["sticky"] = true; options["fadeSpeed"] = 600; } else if( level === "message" ) { options["sticky"] = true; options["fadeSpeed"] = 600; } else { options["sticky"] = false; options["fadeSpeed"] = 600; } if( noticesParsed['validation_errors'] !== undefined ){ var validation_html = generate_list(noticesParsed['validation_errors']); validation_html = '<span>' + i18n.validation_errors + '</span>' + validation_html; $.jnotify(validation_html, options); $('.jnotify-message ul').css({'list-style': 'disc', 'margin-left': '30px'}); } if( noticesParsed['notices'] && noticesParsed['notices'].length !== 0 ){ $.jnotify(generate_list(noticesParsed['notices']), options); } }, addNotices: function(data) { if (!data || data.new_notices.length === 0) { return true; } //if coming from the server may have new count if (data.unread_count) { $("#unread_notices").text(data.unread_count); } $.each(data.new_notices, function(index, notice) { notices.displayNotice(notice.level, window.JSON.stringify({ "notices": [notice.text] }), notice.request_type); }); return true; }, checkNotices : function() { var url = $('#get_notices_url').attr('data-url'); //Make sure when we load the page we get notifs $.ajax({ type: 'GET', url: url, dataType: 'json', global: false, success: notices.addNotices }); }, checkNoticesInResponse : function(xhr) { var message, messageType; if (xhr !== undefined) { message = xhr.getResponseHeader('X-Message'); if (message) { messageType = xhr.getResponseHeader('X-Message-Type'); messageRequestType = xhr.getResponseHeader('X-Message-Request-Type'); notices.displayNotice(messageType, KT.common.decode(message), messageRequestType); } } }, start: function () { var url = $('#get_notices_url').attr('data-url'); // do not wait for PeriodUpdater, check new notices immediately $.ajax({ type:"GET", url:url, cache:false, success:notices.addNotices }); var pu = $.PeriodicalUpdater(url, { method: 'get', type: 'json', global: false, minTimeout: notices.checkTimeout, maxTimeout: notices.checkTimeout }, notices.addNotices); } }; })(); $(document).ready(function() { // perform periodic polling of notices (e.g. async scenarios) //notices.checkNotices(); $(document).ajaxComplete(function(event, xhr, options){ // look for notices in the response (e.g. sync scenarios) notices.checkNoticesInResponse(xhr); }); });
iNecas/katello
src/public/javascripts/notices.js
JavaScript
gpl-2.0
5,298
2/sT<?php exit; ?>a:1:{s:7:"content";O:8:"stdClass":24:{s:2:"ID";i:1218;s:11:"post_author";s:1:"1";s:9:"post_date";s:19:"2014-10-28 07:44:46";s:13:"post_date_gmt";s:19:"2014-10-28 07:44:46";s:12:"post_content";s:0:"";s:10:"post_title";s:20:"Quay World's Banquet";s:12:"post_excerpt";s:0:"";s:11:"post_status";s:7:"publish";s:14:"comment_status";s:6:"closed";s:11:"ping_status";s:6:"closed";s:13:"post_password";s:0:"";s:9:"post_name";s:19:"quay-worlds-banquet";s:7:"to_ping";s:0:"";s:6:"pinged";s:0:"";s:13:"post_modified";s:19:"2014-10-28 07:44:46";s:17:"post_modified_gmt";s:19:"2014-10-28 07:44:46";s:21:"post_content_filtered";s:0:"";s:11:"post_parent";i:0;s:4:"guid";s:61:"http://greenapplesolutions.com/?post_type=mg_items&amp;p=1218";s:10:"menu_order";i:0;s:9:"post_type";s:8:"mg_items";s:14:"post_mime_type";s:0:"";s:13:"comment_count";s:1:"0";s:6:"filter";s:3:"raw";}}
ngupta0309/greenapplesolutions
wp-content/cache/object/000000/9cc/407/9cc40753f1c92f262e04aae2dce28d0d.php
PHP
gpl-2.0
877
from datetime import datetime, timedelta import time class Match: def __init__(self, json): i = (int)(json['_links']['competition']['href'].rfind('/') + 1) self.competitionId = (int)(json['_links']['competition']['href'][i:]) ind = (int)(json['_links']['self']['href'].rfind('/') + 1) self.matchId = (int)(json['_links']['self']['href'][ind:]) self.homeTeamName = json['homeTeamName'] self.awayTeamName = json['awayTeamName'] self.homeTeamGoals = json['result']['goalsHomeTeam'] self.awayTeamGoals = json['result']['goalsAwayTeam'] self.date = json['date'] self.status = json['status'] self.favourite = False self.odds = {} if(json.get('odds', False)): self.odds = json['odds'] self.updatedStatus = '' def __str__(self): fav = '' if self.favourite: fav = 'Fav.' homeGoals = self.homeTeamGoals awayGoals = self.awayTeamGoals if self.homeTeamGoals is None: homeGoals = '-' if self.awayTeamGoals is None: awayGoals = '-' return self.updatedStatus + 'Id : ' + (str)(self.matchId) + ' ' + \ (str)(self.calculateMinutes()) + ' ' + self.homeTeamName + \ ' ' + \ (str)(homeGoals) + ' : ' + \ (str)(awayGoals) + ' ' + self.awayTeamName + ' ' + fav def calculateMinutes(self): if self.status == 'TIMED' or self.status == 'SCHEDULED': return self.date[11:16] elif self.status == 'FINISHED': return 'FT' elif self.status == 'IN_PLAY': ''' tf = '%Y-%m-%dT%H:%M:%S' dt1 = datetime.strptime(self.date[:19], tf) dt2 = datetime.strftime(tf, time.gmtime()) dt2 = datetime.strptime(dt2, tf) mins = ((dt2 - dt1) // timedelta(minutes=1)) ''' now = time.strftime("%H:%M:%S") nowH = (int)(now[0:2]) - 3 nowM = (int)(now[3:5]) matchH = (int)(self.date[11:13]) metchM = (int)(self.date[14:16]) mins = 0 if nowH == matchH: mins = nowM - matchM elif nowH == matchM + 1: mins = 60 - matchM + nowM elif nowH == matchM + 2: mins = 60 - matchM + nowM + 60 if mins > 45 and mins <= 60: mins = 'HT' elif mins > 60: mins = mins - 15 return (str)(mins) + '\'' else: return self.status def refresh(self, json): if self.status == 'FINISHED': return newHomeGoals = json['result']['goalsHomeTeam'] newAwayGoals = json['result']['goalsAwayTeam'] self.status = json['status'] self.updatedStatus = '' if self.homeTeamGoals != newHomeGoals: self.updatedStatus += self.homeTeamName + ' scores in ' + \ (str)(self.calculateMinutes()) + '\n' self.homeTeamGoals = newHomeGoals if self.awayTeamGoals != newAwayGoals: self.updatedStatus += self.awayTeamName + ' scores in ' + \ (str)(self.calculateMinutes()) + '\n' self.awayTeamGoals = newAwayGoals def printMatchOdds(self): if self.odds: print('Odds : ' + self.homeTeamName + ' : ' +\ (str)(self.odds['homeWin']) +\ ' Draw : ' + (str)(self.odds['draw']) +\ ' ' + self.awayTeamName + ' : ' +\ (str)(self.odds['awayWin'])) def markAsFavourite(self): self.favourite = True def markAsNotFavourite(self): self.favourite = False
dimoynwa/DLivescore
data/match.py
Python
gpl-2.0
3,878
<?php /** * @author JoomlaShine.com Team * @copyright JoomlaShine.com * @link joomlashine.com * @package JSN ImageShow * @version $Id: default_backup.php 6637 2011-06-08 08:21:13Z giangnd $ * @license GNU/GPL v2 http://www.gnu.org/licenses/gpl-2.0.html */ defined('_JEXEC') or die( 'Restricted access' ); ?> <script language="javascript"> function backup(){ document.getElementById('frm_backup').submit(); } function restore(){ if (document.getElementById('file-upload').value == ""){ alert( "<?php echo JText::_('MAINTENANCE_BACKUP_YOU_MUST_SELECT_A_FILE_BEFORE_IMPORTING', true); ?>" ); return false; }else { document.getElementById('frm_restore').submit(); } } </script> <?php $pane = JPane::getInstance('tabs',array('startOffset'=>0)); ?> <div id="jsnis-main-content"> <div id="jsn-data-maintenance"> <?php echo $pane->startPane('pane'); ?> <?php echo $pane->startPanel( JText::_('MAINTENANCE_BACKUP_DATA_BACKUP'), 'panel1' ); ?> <form action="index.php?option=com_imageshow&controller=maintenance" method="POST" name="adminForm" id="frm_backup"> <div id="jsnis-data-backup"> <p class="item-title"><?php echo JText::_('MAINTENANCE_BACKUP_BACKUP_OPTIONS'); ?>:</p> <p> <input type="checkbox" name="showlists" id="showlist" value="1" /> <label for="showlist"><?php echo JText::_('MAINTENANCE_BACKUP_BACKUP_SHOWLISTS'); ?></label> </p> <p> <input type="checkbox" name="showcases" id="showcases" value="1" /> <label for="showcases"><?php echo JText::_('MAINTENANCE_BACKUP_BACKUP_SHOWCASES'); ?></label> </p> <p class="item-title"><?php echo JText::_('MAINTENANCE_BACKUP_BACKUP_FILENAME'); ?>:</p> <p> <input type="text" id="filename" name="filename" /> </p> <p> <input type="checkbox" name="timestamp" id="timestamp" value="1" /> <label for="timestamp"><?php echo JText::_('MAINTENANCE_BACKUP_ATTACH_TIMESTAMP_TO_FILENAME'); ?></label> </p> <input type="hidden" name="option" value="com_imageshow" /> <input type="hidden" name="controller" value="maintenance" /> <input type="hidden" name="task" value="backup" /> <?php echo JHTML::_( 'form.token' ); ?> </div> <div class="jsnis-button-container"> <button class="jsnis-button" type="button" value="<?php echo JText::_('MAINTENANCE_BACKUP_BACKUP');?>" onclick="backup();"><?php echo JText::_('MAINTENANCE_BACKUP_BACKUP');?></button> </div> </form> <?php echo $pane->endPanel(); ?> <?php echo $pane->startPanel( JText::_('MAINTENANCE_BACKUP_DATA_RESTORE'), 'panel2' ); ?> <form action="index.php?option=com_imageshow&controller=maintenance" method="POST" name="adminForm" enctype="multipart/form-data" id="frm_restore"> <div id="jsnis-data-restore"> <p class="item-title"><?php echo JText::_('MAINTENANCE_BACKUP_BACKUP_FILE'); ?>:</p> <p> <input type="file" id="file-upload" name="filedata" size="100" /> </p> <input type="hidden" name="option" value="com_imageshow" /> <input type="hidden" name="controller" value="maintenance" /> <input type="hidden" name="task" value="restore" /> <?php echo JHTML::_( 'form.token' ); ?> </div> <div class="jsnis-button-container"> <button class="jsnis-button" type="button" value="<?php echo JText::_('MAINTENANCE_BACKUP_RESTORE'); ?>" onclick="return restore();"><?php echo JText::_('MAINTENANCE_BACKUP_RESTORE'); ?></button> </div> </form> <?php echo $pane->endPanel(); ?> <?php echo $pane->endPane(); ?> </div> </div>
scanalesespinoza/battlebit
administrator/components/com_imageshow/views/maintenance/tmpl/default_backup.php
PHP
gpl-2.0
3,571
/* Copyright (C) 2006 - 2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Winterspring SD%Complete: 90 SDComment: Quest support: 5126 (Loraxs' tale missing proper gossip items text). Vendor Rivern Frostwind. Obtain Cache of Mau'ari SDCategory: Winterspring EndScriptData */ /* ContentData npc_lorax npc_rivern_frostwind npc_witch_doctor_mauari EndContentData */ #include "precompiled.h" /*###### ## npc_lorax ######*/ bool GossipHello_npc_lorax(Player* pPlayer, Creature* pCreature) { if (pCreature->isQuestGiver()) pPlayer->PrepareQuestMenu(pCreature->GetGUID()); if (pPlayer->GetQuestStatus(5126) == QUEST_STATUS_INCOMPLETE) pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Talk to me", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF); pPlayer->SEND_GOSSIP_MENU(pCreature->GetNpcTextId(), pCreature->GetGUID()); return true; } bool GossipSelect_npc_lorax(Player* pPlayer, Creature* pCreature, uint32 uiSender, uint32 uiAction) { switch(uiAction) { case GOSSIP_ACTION_INFO_DEF: pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "What do you do here?", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); pPlayer->SEND_GOSSIP_MENU(3759, pCreature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+1: pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "I can help you", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2); pPlayer->SEND_GOSSIP_MENU(3760, pCreature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+2: pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "What deal?", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3); pPlayer->SEND_GOSSIP_MENU(3761, pCreature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+3: pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "Then what happened?", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 4); pPlayer->SEND_GOSSIP_MENU(3762, pCreature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+4: pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "He is not safe, i'll make sure of that.", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 5); pPlayer->SEND_GOSSIP_MENU(3763, pCreature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+5: pPlayer->CLOSE_GOSSIP_MENU(); pPlayer->AreaExploredOrEventHappens(5126); break; } return true; } /*###### ## npc_rivern_frostwind ######*/ bool GossipHello_npc_rivern_frostwind(Player* pPlayer, Creature* pCreature) { if (pCreature->isQuestGiver()) pPlayer->PrepareQuestMenu(pCreature->GetGUID()); if (pCreature->isVendor() && pPlayer->GetReputationRank(589) == REP_EXALTED) pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_VENDOR, GOSSIP_TEXT_BROWSE_GOODS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_TRADE); pPlayer->SEND_GOSSIP_MENU(pCreature->GetNpcTextId(), pCreature->GetGUID()); return true; } bool GossipSelect_npc_rivern_frostwind(Player* pPlayer, Creature* pCreature, uint32 uiSender, uint32 uiAction) { if (uiAction == GOSSIP_ACTION_TRADE) pPlayer->SEND_VENDORLIST(pCreature->GetGUID()); return true; } /*###### ## npc_witch_doctor_mauari ######*/ bool GossipHello_npc_witch_doctor_mauari(Player* pPlayer, Creature* pCreature) { if (pCreature->isQuestGiver()) pPlayer->PrepareQuestMenu(pCreature->GetGUID()); if (pPlayer->GetQuestRewardStatus(975)) { pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "I'd like you to make me a new Cache of Mau'ari please.", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); pPlayer->SEND_GOSSIP_MENU(3377, pCreature->GetGUID()); }else pPlayer->SEND_GOSSIP_MENU(3375, pCreature->GetGUID()); return true; } bool GossipSelect_npc_witch_doctor_mauari(Player* pPlayer, Creature* pCreature, uint32 uiSender, uint32 uiAction) { if (uiAction==GOSSIP_ACTION_INFO_DEF+1) { pPlayer->CLOSE_GOSSIP_MENU(); pCreature->CastSpell(pPlayer, 16351, false); } return true; } void AddSC_winterspring() { Script *newscript; newscript = new Script; newscript->Name = "npc_lorax"; newscript->pGossipHello = &GossipHello_npc_lorax; newscript->pGossipSelect = &GossipSelect_npc_lorax; newscript->RegisterSelf(); newscript = new Script; newscript->Name = "npc_rivern_frostwind"; newscript->pGossipHello = &GossipHello_npc_rivern_frostwind; newscript->pGossipSelect = &GossipSelect_npc_rivern_frostwind; newscript->RegisterSelf(); newscript = new Script; newscript->Name = "npc_witch_doctor_mauari"; newscript->pGossipHello = &GossipHello_npc_witch_doctor_mauari; newscript->pGossipSelect = &GossipSelect_npc_witch_doctor_mauari; newscript->RegisterSelf(); }
web0316/WOW
src/bindings/ScriptDev2/scripts/kalimdor/winterspring.cpp
C++
gpl-2.0
5,702
<?php /** * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages and that other * 'pages' on your WordPress site will use a different template. * * @package WordPress * @subpackage Twenty_Thirteen * @since Twenty Thirteen 1.0 */ get_header(); ?> <div id="primary" class="content-area"> <div id="content" class="site-content" role="main"> <div class="leftnmenu"> <h1>DỊCH VỤ</h1> <?php wp_nav_menu( array( 'container_class' => 'leftnmenu', 'theme_location' => 'leftsiderbar' ,'menu'=> 'leftsiderbar') ); ?> <img class="Fsubcont" src="<?php bloginfo('template_url'); ?>/images/Fsubscribe.png" alt=""/> </div> <div class="centralcon"> <?php if (have_posts()): ?> <?php while(have_posts()):the_post(); ?> <h2><?php the_title(); ?></h2> <?php the_content(); ?> <!-- <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy...Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy...</p> <img src="<?php //bloginfo('template_url'); ?>/images/hinh2.png" alt=""/> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy...</p> <img src="<?php //bloginfo('template_url'); ?>/images/hinh3.png" alt=""/> --> <?php endwhile ; ?> <?php endif; wp_reset_query(); ?> </div> <div class="Ntecgy"> <h3>CÔNG NGHỆ LIÊN QUAN</h3> <ul> <li>Công nghệ phun laser abcdezxy </li> <li>Công nghệ phun laser </li> <li>Công nghệ phun laser abcdezxy</li> <li>Công nghệ phun laser </li> <li>Công nghệ phun laser abcd</li> <li>Công nghệ phun laser</li> <li>Công nghệ phun laser</li> </ul> <h3>SẢN PHẨM LIÊN QUAN</h3> <img src="<?php bloginfo('template_url'); ?>/images/splq.png" alt=""/> <img class="pdctslide" src="<?php bloginfo('template_url'); ?>/images/hinh4.png" alt=""/> </div> </div><!-- #content --> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
andykim/Pamas
wp-content/themes/pamas/single-category-dich-vu.php
PHP
gpl-2.0
2,855
#!/bin/sh BREW_IS_AVAILABLE="$(brew --version 2>&1 >/dev/null)" if [[ ${BREW_IS_AVAILABLE} == '' ]]; then echo -e "${bakgrn}[installed][Brew]${txtrst}" ; else echo -e "${bakcyn}[Brew] Start Install ${txtrst}"; /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" echo -e "${bakgrn}[Brew] Finish Install ${txtrst}"; fi
rtancman/dotfiles
sh/osx/scripts/brew.sh
Shell
gpl-2.0
388
/* * 响应式 */ // 添加导航菜单 $(window).resize(function(){ var window_width = $(window).width(),$menu = $('#response-menu'); if(window_width <= _options_.response_phone_width) { if($menu.length <= 0) { $('#menu').before('<a id="response-menu"></a>'); $('#search-area').insertBefore('#menu'); $menu = $('#response-menu'); } $menu.show(); $('#menu .sub-menu').show(); $('#menu,#search-area').not('.phone-hidden').hide().addClass('phone-hidden'); } else { $menu.hide(); } }).resize(); $('body').on('click','#response-menu',function(){ $('#menu,#search-area').slideToggle(); }); // 显示边栏 $(window).resize(function(){ if($(window).width() > _options_.response_phone_width) { $('.phone-hide-sidebar').remove(); } }); /* * 页面需要尽快加载的代码 */ // 下拉菜单效果 $(window).resize(function(){ if($(window).width() <= _options_.response_phone_width) { $('#menu .menu-item-has-children').unbind('mouseenter mouseleave'); return; } $('#menu,#search-area').show().removeClass('phone-hidden'); $('#menu .sub-menu').hide(); var $timer = {}; $timer.menu = false; $('#menu .menu-item-has-children').bind('mouseenter',function(){ var $this = $(this),$child = $this.children('.sub-menu'); $('#menu .menu-item-has-children .sub-menu').fadeOut(100); $child.hide(); clearTimeout($timer.menu); $timer.menu = setTimeout(function(){ $child.fadeIn(300); },200); }).bind('mouseleave',function(){ var $this = $(this),$child = $this.children('.sub-menu'); clearTimeout($timer.menu); $timer.menu = setTimeout(function(){ $child.fadeOut(100); },100); }); }).resize(); // 响应式布局切换 $(window).resize(function(){ var window_width = $(window).width(), screen_style = _options_.template_url + '/css/' + _options_.style_color + '-screen.css', pad_style = _options_.template_url + '/css/' + _options_.style_color + '-pad.css', phone_style = _options_.template_url + '/css/' + _options_.style_color + '-phone.css', $style = $('#response-style-link'); if(window_width <= _options_.response_phone_width)$style.attr('href',phone_style); else if(window_width <= _options_.response_pad_width)$style.attr('href',pad_style); else if(window_width <= _options_.response_screen_width)$style.attr('href',screen_style); else $style.removeAttr('href'); }).resize(); // 幻灯片 if($('#slider').length > 0) { $('#load-page-scripts').before('<script src="' + _options_.template_url + '/js/jquery.devrama.slider.js">\x3C/script>'); $('#slider').DrSlider({onLoad:function(){ $('#slider').slideDown(500); }}); } // 图片延时加载 if(_options_.img_lazyload && $('.post img').length > 0) { $('#load-page-scripts').before('<script src="' + _options_.template_url + '/js/jquery.lazyload.min.js">\x3C/script>'); $('.post img').not('.pagenavi-loading-image').lazyload({effect:"fadeIn",threshold:200}); } // 固定边栏 if($('#fixed-sidebar').length > 0 && $(window).width() > _options_.response_phone_width) { $('#load-page-scripts').before('<script src="' + _options_.template_url + '/js/fixed-widget.js">\x3C/script>'); $.fixedwidget({ fixedObj : '#fixed-sidebar', bottomObj : '#footer', fixedPos : 10 }); } // 无限加载 if($('#pagenavi').length > 0 && _options_.pagenavi_num > 0) { $('#load-page-scripts').before('<script src="' + _options_.template_url + '/js/pagenavi-ajax.js">\x3C/script>'); $.pagenavajax({ loading_html : '<img src="' + _options_.template_url + '/images/loading.gif" style="clear:both;display:block;margin:0 auto;text-align:center;" alt="正在加载..." class="pagenavi-loading-image" />', pagenav : '#pagenavi', container : '#post-list', pendObj : 'div.post', startPos : 50, currentNav : 'span.current', real_current_page : _options_.real_current_page, nav_page_num : _options_.pagenavi_num, is_forever_btn : false, call_before_fun : function() { if(_options_.img_lazyload && $('.post img').length > 0)$('.post img').addClass('lazyload'); }, call_back_fun : function(){ if(_options_.img_lazyload && $('.post img').length > 0 && $('.post img').not('.lazyload').length > 0) { $('.post img').not('.lazyload').lazyload({effect:"fadeIn",threshold:200}); } } }); } // 返回顶部按钮 $('body').append('<a href="javascript:void(0);" class="to-top" id="to-top-btn"></a>'); $(document).on('click','#to-top-btn',function(){ $('html,body').animate({scrollTop:0},500); }); $(window).scroll(function(){ var scrollTop = $(window).scrollTop(); if(scrollTop > 200) { $('#to-top-btn').fadeIn(500); } else { $('#to-top-btn:visible').fadeOut(500); } }).scroll(); /* * 等到加载完才执行的代码 */ jQuery(function($){ // 非本站链接跳出 $(document).on('click','a',function(e){ var href = $(this).attr('href'); if(href.indexOf('http://') >= 0 && $href.indexOf(window.location.host) < 0){ window.open(href); return false; } }); // 主要区域的高度 function set_same_height() { if($('#sidebar').is(':hidden')) return; var left = $('#content').outerHeight(true), right = $('#sidebar').outerHeight(true); if(right > left) $('#main').css('min-height',right + 100 + 'px'); } $(window).load(function(){set_same_height();}); });
xfalcons/wordpress-youmeifd
wp-content/themes/magic-tech/js/javascript.js
JavaScript
gpl-2.0
5,578
# FPGA DVB-S implementation This repository contains a networked FPGA DVB-S encoder implementation. For documentation, see: http://loetlabor-jena.de/doku.php?id=projekte:das:dvbs This repository is part of the DAS project.
thasti/dvbs
README.md
Markdown
gpl-2.0
226
// vim: ts=4 sw=4 expandtab ft=c // Copyright (C) 2008 The University of Melbourne. // This file may only be copied under the terms of the GNU Library General // Public License - see the file COPYING.LIB in the Mercury distribution. #include "mercury_backjump.h" #include "mercury_thread.h" #if defined(MR_THREAD_SAFE) #include <pthread.h> #endif // The low-level C counterparts to these globals are the `backjump_handler' // and `backjump_next_choice_id' fields of the MR_Context structure. // (See mercury_context.h for details.) #if defined(MR_HIGHLEVEL_CODE) #if defined(MR_THREAD_SAFE) MercuryThreadKey MR_backjump_handler_key; MercuryThreadKey MR_backjump_next_choice_id_key; #else // not MR_THREAD_SAFE MR_BackJumpHandler *MR_backjump_handler; MR_BackJumpChoiceId MR_backjump_next_choice_id = 0; #endif // not MR_THREAD_SAFE #endif // not MR_HIGHLEVEL_CODE #if defined(MR_HIGHLEVEL_CODE) && defined(MR_THREAD_SAFE) MR_BackJumpChoiceId MR_get_tl_backjump_next_choice_id(void) { MR_BackJumpChoiceId new_choice_id; // NOTE: this only works because sizeof(MR_Integer) == sizeof(void *). new_choice_id = (MR_Integer) MR_GETSPECIFIC(MR_backjump_next_choice_id_key); pthread_setspecific(MR_backjump_next_choice_id_key, (void *)(new_choice_id + 1)); return new_choice_id; } #endif // MR_HIGLEVEL_CODE && MR_THREAD_SAFE ////////////////////////////////////////////////////////////////////////////
PaulBone/mercury
runtime/mercury_backjump.c
C
gpl-2.0
1,506
/*************************************************************************** qgssymbollayer.cpp --------------------- begin : November 2009 copyright : (C) 2009 by Martin Dobias email : wonder dot sk at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgssymbollayer.h" #include "qgsclipper.h" #include "qgsexpression.h" #include "qgsrendercontext.h" #include "qgsvectorlayer.h" #include "qgsdxfexport.h" #include "qgsgeometrysimplifier.h" #include "qgspainteffect.h" #include "qgseffectstack.h" #include "qgspainteffectregistry.h" #include "qgsproperty.h" #include "qgsexpressioncontext.h" #include "qgssymbollayerutils.h" #include "qgsapplication.h" #include "qgsmultipoint.h" #include "qgslegendpatchshape.h" #include "qgsstyle.h" #include <QSize> #include <QPainter> #include <QPointF> #include <QPolygonF> QgsPropertiesDefinition QgsSymbolLayer::sPropertyDefinitions; void QgsSymbolLayer::initPropertyDefinitions() { if ( !sPropertyDefinitions.isEmpty() ) return; QString origin = QStringLiteral( "symbol" ); sPropertyDefinitions = QgsPropertiesDefinition { { QgsSymbolLayer::PropertySize, QgsPropertyDefinition( "size", QObject::tr( "Symbol size" ), QgsPropertyDefinition::Size, origin ) }, { QgsSymbolLayer::PropertyAngle, QgsPropertyDefinition( "angle", QObject::tr( "Rotation angle" ), QgsPropertyDefinition::Rotation, origin ) }, { QgsSymbolLayer::PropertyName, QgsPropertyDefinition( "name", QObject::tr( "Symbol name" ), QgsPropertyDefinition::String, origin ) }, { QgsSymbolLayer::PropertyFillColor, QgsPropertyDefinition( "fillColor", QObject::tr( "Symbol fill color" ), QgsPropertyDefinition::ColorWithAlpha, origin ) }, { QgsSymbolLayer::PropertyStrokeColor, QgsPropertyDefinition( "outlineColor", QObject::tr( "Symbol stroke color" ), QgsPropertyDefinition::ColorWithAlpha, origin ) }, { QgsSymbolLayer::PropertyStrokeWidth, QgsPropertyDefinition( "outlineWidth", QObject::tr( "Symbol stroke width" ), QgsPropertyDefinition::StrokeWidth, origin ) }, { QgsSymbolLayer::PropertyStrokeStyle, QgsPropertyDefinition( "outlineStyle", QObject::tr( "Symbol stroke style" ), QgsPropertyDefinition::LineStyle, origin )}, { QgsSymbolLayer::PropertyOffset, QgsPropertyDefinition( "offset", QObject::tr( "Symbol offset" ), QgsPropertyDefinition::Offset, origin )}, { QgsSymbolLayer::PropertyCharacter, QgsPropertyDefinition( "char", QObject::tr( "Marker character(s)" ), QgsPropertyDefinition::String, origin )}, { QgsSymbolLayer::PropertyFontFamily, QgsPropertyDefinition( "fontFamily", QObject::tr( "Font family" ), QgsPropertyDefinition::String, origin )}, { QgsSymbolLayer::PropertyFontStyle, QgsPropertyDefinition( "fontStyle", QObject::tr( "Font style" ), QgsPropertyDefinition::String, origin )}, { QgsSymbolLayer::PropertyWidth, QgsPropertyDefinition( "width", QObject::tr( "Symbol width" ), QgsPropertyDefinition::DoublePositive, origin )}, { QgsSymbolLayer::PropertyHeight, QgsPropertyDefinition( "height", QObject::tr( "Symbol height" ), QgsPropertyDefinition::DoublePositive, origin )}, { QgsSymbolLayer::PropertyPreserveAspectRatio, QgsPropertyDefinition( "preserveAspectRatio", QObject::tr( "Preserve aspect ratio between width and height" ), QgsPropertyDefinition::Boolean, origin )}, { QgsSymbolLayer::PropertyFillStyle, QgsPropertyDefinition( "fillStyle", QObject::tr( "Symbol fill style" ), QgsPropertyDefinition::FillStyle, origin )}, { QgsSymbolLayer::PropertyJoinStyle, QgsPropertyDefinition( "joinStyle", QObject::tr( "Outline join style" ), QgsPropertyDefinition::PenJoinStyle, origin )}, { QgsSymbolLayer::PropertySecondaryColor, QgsPropertyDefinition( "color2", QObject::tr( "Secondary fill color" ), QgsPropertyDefinition::ColorWithAlpha, origin )}, { QgsSymbolLayer::PropertyLineAngle, QgsPropertyDefinition( "lineAngle", QObject::tr( "Angle for line fills" ), QgsPropertyDefinition::Rotation, origin )}, { QgsSymbolLayer::PropertyGradientType, QgsPropertyDefinition( "gradientType", QgsPropertyDefinition::DataTypeString, QObject::tr( "Gradient type" ), QObject::tr( "string " ) + QLatin1String( "[<b>linear</b>|<b>radial</b>|<b>conical</b>]" ), origin )}, { QgsSymbolLayer::PropertyCoordinateMode, QgsPropertyDefinition( "gradientMode", QgsPropertyDefinition::DataTypeString, QObject::tr( "Gradient mode" ), QObject::tr( "string " ) + QLatin1String( "[<b>feature</b>|<b>viewport</b>]" ), origin )}, { QgsSymbolLayer::PropertyGradientSpread, QgsPropertyDefinition( "gradientSpread", QgsPropertyDefinition::DataTypeString, QObject::tr( "Gradient spread" ), QObject::tr( "string " ) + QLatin1String( "[<b>pad</b>|<b>repeat</b>|<b>reflect</b>]" ), origin )}, { QgsSymbolLayer::PropertyGradientReference1X, QgsPropertyDefinition( "gradientRef1X", QObject::tr( "Reference point 1 (X)" ), QgsPropertyDefinition::Double0To1, origin )}, { QgsSymbolLayer::PropertyGradientReference1Y, QgsPropertyDefinition( "gradientRef1Y", QObject::tr( "Reference point 1 (Y)" ), QgsPropertyDefinition::Double0To1, origin )}, { QgsSymbolLayer::PropertyGradientReference2X, QgsPropertyDefinition( "gradientRef2X", QObject::tr( "Reference point 2 (X)" ), QgsPropertyDefinition::Double0To1, origin )}, { QgsSymbolLayer::PropertyGradientReference2Y, QgsPropertyDefinition( "gradientRef2Y", QObject::tr( "Reference point 2 (Y)" ), QgsPropertyDefinition::Double0To1, origin )}, { QgsSymbolLayer::PropertyGradientReference1IsCentroid, QgsPropertyDefinition( "gradientRef1Centroid", QObject::tr( "Reference point 1 follows feature centroid" ), QgsPropertyDefinition::Boolean, origin )}, { QgsSymbolLayer::PropertyGradientReference2IsCentroid, QgsPropertyDefinition( "gradientRef2Centroid", QObject::tr( "Reference point 2 follows feature centroid" ), QgsPropertyDefinition::Boolean, origin )}, { QgsSymbolLayer::PropertyBlurRadius, QgsPropertyDefinition( "blurRadius", QgsPropertyDefinition::DataTypeNumeric, QObject::tr( "Blur radius" ), QObject::tr( "Integer between 0 and 18" ), origin )}, { QgsSymbolLayer::PropertyLineDistance, QgsPropertyDefinition( "lineDistance", QObject::tr( "Distance between lines" ), QgsPropertyDefinition::DoublePositive, origin )}, { QgsSymbolLayer::PropertyShapeburstUseWholeShape, QgsPropertyDefinition( "shapeburstWholeShape", QObject::tr( "Shade whole shape" ), QgsPropertyDefinition::Boolean, origin )}, { QgsSymbolLayer::PropertyShapeburstMaxDistance, QgsPropertyDefinition( "shapeburstMaxDist", QObject::tr( "Maximum distance for shapeburst fill" ), QgsPropertyDefinition::DoublePositive, origin )}, { QgsSymbolLayer::PropertyShapeburstIgnoreRings, QgsPropertyDefinition( "shapeburstIgnoreRings", QObject::tr( "Ignore rings in feature" ), QgsPropertyDefinition::Boolean, origin )}, { QgsSymbolLayer::PropertyFile, QgsPropertyDefinition( "file", QObject::tr( "Symbol file path" ), QgsPropertyDefinition::String, origin )}, { QgsSymbolLayer::PropertyDistanceX, QgsPropertyDefinition( "distanceX", QObject::tr( "Horizontal distance between markers" ), QgsPropertyDefinition::DoublePositive, origin )}, { QgsSymbolLayer::PropertyDistanceY, QgsPropertyDefinition( "distanceY", QObject::tr( "Vertical distance between markers" ), QgsPropertyDefinition::DoublePositive, origin )}, { QgsSymbolLayer::PropertyDisplacementX, QgsPropertyDefinition( "displacementX", QObject::tr( "Horizontal displacement between rows" ), QgsPropertyDefinition::DoublePositive, origin )}, { QgsSymbolLayer::PropertyDisplacementY, QgsPropertyDefinition( "displacementY", QObject::tr( "Vertical displacement between columns" ), QgsPropertyDefinition::DoublePositive, origin )}, { QgsSymbolLayer::PropertyOffsetX, QgsPropertyDefinition( "offsetX", QObject::tr( "Horizontal offset" ), QgsPropertyDefinition::Double, origin )}, { QgsSymbolLayer::PropertyOffsetY, QgsPropertyDefinition( "offsetY", QObject::tr( "Vertical offset" ), QgsPropertyDefinition::Double, origin )}, { QgsSymbolLayer::PropertyOpacity, QgsPropertyDefinition( "alpha", QObject::tr( "Opacity" ), QgsPropertyDefinition::Opacity, origin )}, { QgsSymbolLayer::PropertyCustomDash, QgsPropertyDefinition( "customDash", QgsPropertyDefinition::DataTypeString, QObject::tr( "Custom dash pattern" ), QObject::tr( "[<b><dash>;<space></b>] e.g. '8;2;1;2'" ), origin )}, { QgsSymbolLayer::PropertyCapStyle, QgsPropertyDefinition( "capStyle", QObject::tr( "Line cap style" ), QgsPropertyDefinition::CapStyle, origin )}, { QgsSymbolLayer::PropertyPlacement, QgsPropertyDefinition( "placement", QgsPropertyDefinition::DataTypeString, QObject::tr( "Marker placement" ), QObject::tr( "string " ) + "[<b>interval</b>|<b>vertex</b>|<b>lastvertex</b>|<b>firstvertex</b>|<b>centerpoint</b>|<b>curvepoint</b>|<b>segmentcenter</b>]", origin )}, { QgsSymbolLayer::PropertyInterval, QgsPropertyDefinition( "interval", QObject::tr( "Marker interval" ), QgsPropertyDefinition::DoublePositive, origin )}, { QgsSymbolLayer::PropertyOffsetAlongLine, QgsPropertyDefinition( "offsetAlongLine", QObject::tr( "Offset along line" ), QgsPropertyDefinition::DoublePositive, origin )}, { QgsSymbolLayer::PropertyAverageAngleLength, QgsPropertyDefinition( "averageAngleLength", QObject::tr( "Average line angles over" ), QgsPropertyDefinition::DoublePositive, origin )}, { QgsSymbolLayer::PropertyHorizontalAnchor, QgsPropertyDefinition( "hAnchor", QObject::tr( "Horizontal anchor point" ), QgsPropertyDefinition::HorizontalAnchor, origin )}, { QgsSymbolLayer::PropertyVerticalAnchor, QgsPropertyDefinition( "vAnchor", QObject::tr( "Vertical anchor point" ), QgsPropertyDefinition::VerticalAnchor, origin )}, { QgsSymbolLayer::PropertyLayerEnabled, QgsPropertyDefinition( "enabled", QObject::tr( "Layer enabled" ), QgsPropertyDefinition::Boolean, origin )}, { QgsSymbolLayer::PropertyArrowWidth, QgsPropertyDefinition( "arrowWidth", QObject::tr( "Arrow line width" ), QgsPropertyDefinition::StrokeWidth, origin )}, { QgsSymbolLayer::PropertyArrowStartWidth, QgsPropertyDefinition( "arrowStartWidth", QObject::tr( "Arrow line start width" ), QgsPropertyDefinition::StrokeWidth, origin )}, { QgsSymbolLayer::PropertyArrowHeadLength, QgsPropertyDefinition( "arrowHeadLength", QObject::tr( "Arrow head length" ), QgsPropertyDefinition::DoublePositive, origin )}, { QgsSymbolLayer::PropertyArrowHeadThickness, QgsPropertyDefinition( "arrowHeadThickness", QObject::tr( "Arrow head thickness" ), QgsPropertyDefinition::DoublePositive, origin )}, { QgsSymbolLayer::PropertyArrowHeadType, QgsPropertyDefinition( "arrowHeadType", QgsPropertyDefinition::DataTypeString, QObject::tr( "Arrow head type" ), QObject::tr( "string " ) + QLatin1String( "[<b>single</b>|<b>reversed</b>|<b>double</b>]" ), origin )}, { QgsSymbolLayer::PropertyArrowType, QgsPropertyDefinition( "arrowType", QgsPropertyDefinition::DataTypeString, QObject::tr( "Arrow type" ), QObject::tr( "string " ) + QLatin1String( "[<b>plain</b>|<b>lefthalf</b>|<b>righthalf</b>]" ), origin )}, { QgsSymbolLayer::PropertyPointCount, QgsPropertyDefinition( "pointCount", QObject::tr( "Point count" ), QgsPropertyDefinition::IntegerPositive, origin )}, { QgsSymbolLayer::PropertyRandomSeed, QgsPropertyDefinition( "randomSeed", QgsPropertyDefinition::DataTypeNumeric, QObject::tr( "Random number seed" ), QObject::tr( "integer > 0, or 0 for completely random sequence" ), origin )}, { QgsSymbolLayer::PropertyClipPoints, QgsPropertyDefinition( "clipPoints", QObject::tr( "Clip markers" ), QgsPropertyDefinition::Boolean, origin )}, { QgsSymbolLayer::PropertyClipPoints, QgsPropertyDefinition( "densityArea", QObject::tr( "Density area" ), QgsPropertyDefinition::DoublePositive, origin )}, { QgsSymbolLayer::PropertyDashPatternOffset, QgsPropertyDefinition( "dashPatternOffset", QObject::tr( "Dash pattern offset" ), QgsPropertyDefinition::DoublePositive, origin )}, }; } void QgsSymbolLayer::setDataDefinedProperty( QgsSymbolLayer::Property key, const QgsProperty &property ) { dataDefinedProperties().setProperty( key, property ); } void QgsSymbolLayer::startFeatureRender( const QgsFeature &, QgsRenderContext & ) { } void QgsSymbolLayer::stopFeatureRender( const QgsFeature &, QgsRenderContext & ) { } bool QgsSymbolLayer::writeDxf( QgsDxfExport &e, double mmMapUnitScaleFactor, const QString &layerName, QgsSymbolRenderContext &context, QPointF shift ) const { Q_UNUSED( e ) Q_UNUSED( mmMapUnitScaleFactor ) Q_UNUSED( layerName ) Q_UNUSED( context ) Q_UNUSED( shift ) return false; } double QgsSymbolLayer::dxfWidth( const QgsDxfExport &e, QgsSymbolRenderContext &context ) const { Q_UNUSED( e ) Q_UNUSED( context ) return 1.0; } double QgsSymbolLayer::dxfOffset( const QgsDxfExport &e, QgsSymbolRenderContext &context ) const { Q_UNUSED( e ) Q_UNUSED( context ) return 0.0; } QColor QgsSymbolLayer::dxfColor( QgsSymbolRenderContext &context ) const { Q_UNUSED( context ) return color(); } double QgsSymbolLayer::dxfAngle( QgsSymbolRenderContext &context ) const { Q_UNUSED( context ) return 0.0; } QVector<qreal> QgsSymbolLayer::dxfCustomDashPattern( QgsUnitTypes::RenderUnit &unit ) const { Q_UNUSED( unit ) return QVector<qreal>(); } Qt::PenStyle QgsSymbolLayer::dxfPenStyle() const { return Qt::SolidLine; } QColor QgsSymbolLayer::dxfBrushColor( QgsSymbolRenderContext &context ) const { Q_UNUSED( context ) return color(); } Qt::BrushStyle QgsSymbolLayer::dxfBrushStyle() const { return Qt::NoBrush; } QgsPaintEffect *QgsSymbolLayer::paintEffect() const { return mPaintEffect.get(); } void QgsSymbolLayer::setPaintEffect( QgsPaintEffect *effect ) { if ( effect == mPaintEffect.get() ) return; mPaintEffect.reset( effect ); } QgsSymbolLayer::QgsSymbolLayer( QgsSymbol::SymbolType type, bool locked ) : mType( type ) , mLocked( locked ) { } void QgsSymbolLayer::prepareExpressions( const QgsSymbolRenderContext &context ) { mDataDefinedProperties.prepare( context.renderContext().expressionContext() ); if ( !context.fields().isEmpty() ) { //QgsFields is implicitly shared, so it's cheap to make a copy mFields = context.fields(); } } bool QgsSymbolLayer::hasDataDefinedProperties() const { return mDataDefinedProperties.hasActiveProperties(); } const QgsPropertiesDefinition &QgsSymbolLayer::propertyDefinitions() { QgsSymbolLayer::initPropertyDefinitions(); return sPropertyDefinitions; } QgsSymbolLayer::~QgsSymbolLayer() = default; bool QgsSymbolLayer::isCompatibleWithSymbol( QgsSymbol *symbol ) const { if ( symbol->type() == QgsSymbol::Fill && mType == QgsSymbol::Line ) return true; return symbol->type() == mType; } void QgsSymbolLayer::setRenderingPass( int renderingPass ) { mRenderingPass = renderingPass; } int QgsSymbolLayer::renderingPass() const { return mRenderingPass; } QSet<QString> QgsSymbolLayer::usedAttributes( const QgsRenderContext &context ) const { // calling referencedFields() with ignoreContext=true because in our expression context // we do not have valid QgsFields yet - because of that the field names from expressions // wouldn't get reported QSet<QString> columns = mDataDefinedProperties.referencedFields( context.expressionContext(), true ); return columns; } QgsProperty propertyFromMap( const QgsStringMap &map, const QString &baseName ) { QString prefix; if ( !baseName.isEmpty() ) { prefix.append( QStringLiteral( "%1_dd_" ).arg( baseName ) ); } if ( !map.contains( QStringLiteral( "%1expression" ).arg( prefix ) ) ) { //requires at least the expression value return QgsProperty(); } bool active = ( map.value( QStringLiteral( "%1active" ).arg( prefix ), QStringLiteral( "1" ) ) != QLatin1String( "0" ) ); QString expression = map.value( QStringLiteral( "%1expression" ).arg( prefix ) ); bool useExpression = ( map.value( QStringLiteral( "%1useexpr" ).arg( prefix ), QStringLiteral( "1" ) ) != QLatin1String( "0" ) ); QString field = map.value( QStringLiteral( "%1field" ).arg( prefix ), QString() ); if ( useExpression ) return QgsProperty::fromExpression( expression, active ); else return QgsProperty::fromField( field, active ); } void QgsSymbolLayer::restoreOldDataDefinedProperties( const QgsStringMap &stringMap ) { // property string to type upgrade map static const QMap< QString, QgsSymbolLayer::Property > OLD_PROPS { { "color", QgsSymbolLayer::PropertyFillColor }, { "arrow_width", QgsSymbolLayer::PropertyArrowWidth }, { "arrow_start_width", QgsSymbolLayer::PropertyArrowStartWidth }, { "head_length", QgsSymbolLayer::PropertyArrowHeadLength }, { "head_thickness", QgsSymbolLayer::PropertyArrowHeadThickness }, { "offset", QgsSymbolLayer::PropertyOffset }, { "head_type", QgsSymbolLayer::PropertyArrowHeadType }, { "arrow_type", QgsSymbolLayer::PropertyArrowType }, { "width_field", QgsSymbolLayer::PropertyWidth }, { "height_field", QgsSymbolLayer::PropertyHeight }, { "rotation_field", QgsSymbolLayer::PropertyAngle }, { "outline_width_field", QgsSymbolLayer::PropertyStrokeWidth }, { "fill_color_field", QgsSymbolLayer::PropertyFillColor }, { "outline_color_field", QgsSymbolLayer::PropertyStrokeColor }, { "symbol_name_field", QgsSymbolLayer::PropertyName }, { "outline_width", QgsSymbolLayer::PropertyStrokeWidth }, { "outline_style", QgsSymbolLayer::PropertyStrokeStyle }, { "join_style", QgsSymbolLayer::PropertyJoinStyle }, { "fill_color", QgsSymbolLayer::PropertyFillColor }, { "outline_color", QgsSymbolLayer::PropertyStrokeColor }, { "width", QgsSymbolLayer::PropertyWidth }, { "height", QgsSymbolLayer::PropertyHeight }, { "symbol_name", QgsSymbolLayer::PropertyName }, { "angle", QgsSymbolLayer::PropertyAngle }, { "fill_style", QgsSymbolLayer::PropertyFillStyle }, { "color_border", QgsSymbolLayer::PropertyStrokeColor }, { "width_border", QgsSymbolLayer::PropertyStrokeWidth }, { "border_color", QgsSymbolLayer::PropertyStrokeColor }, { "border_style", QgsSymbolLayer::PropertyStrokeStyle }, { "color2", QgsSymbolLayer::PropertySecondaryColor }, { "gradient_type", QgsSymbolLayer::PropertyGradientType }, { "coordinate_mode", QgsSymbolLayer::PropertyCoordinateMode }, { "spread", QgsSymbolLayer::PropertyGradientSpread }, { "reference1_x", QgsSymbolLayer::PropertyGradientReference1X }, { "reference1_y", QgsSymbolLayer::PropertyGradientReference1Y }, { "reference2_x", QgsSymbolLayer::PropertyGradientReference2X }, { "reference2_y", QgsSymbolLayer::PropertyGradientReference2Y }, { "reference1_iscentroid", QgsSymbolLayer::PropertyGradientReference1IsCentroid }, { "reference2_iscentroid", QgsSymbolLayer::PropertyGradientReference2IsCentroid }, { "blur_radius", QgsSymbolLayer::PropertyBlurRadius }, { "use_whole_shape", QgsSymbolLayer::PropertyShapeburstUseWholeShape }, { "max_distance", QgsSymbolLayer::PropertyShapeburstMaxDistance }, { "ignore_rings", QgsSymbolLayer::PropertyShapeburstIgnoreRings }, { "svgFillColor", QgsSymbolLayer::PropertyFillColor }, { "svgOutlineColor", QgsSymbolLayer::PropertyStrokeColor }, { "svgOutlineWidth", QgsSymbolLayer::PropertyStrokeWidth }, { "svgFile", QgsSymbolLayer::PropertyFile }, { "lineangle", QgsSymbolLayer::PropertyLineAngle }, { "distance", QgsSymbolLayer::PropertyLineDistance }, { "distance_x", QgsSymbolLayer::PropertyDistanceX }, { "distance_y", QgsSymbolLayer::PropertyDistanceY }, { "displacement_x", QgsSymbolLayer::PropertyDisplacementX }, { "displacement_y", QgsSymbolLayer::PropertyDisplacementY }, { "file", QgsSymbolLayer::PropertyFile }, { "alpha", QgsSymbolLayer::PropertyOpacity }, { "customdash", QgsSymbolLayer::PropertyCustomDash }, { "line_style", QgsSymbolLayer::PropertyStrokeStyle }, { "joinstyle", QgsSymbolLayer::PropertyJoinStyle }, { "capstyle", QgsSymbolLayer::PropertyCapStyle }, { "placement", QgsSymbolLayer::PropertyPlacement }, { "interval", QgsSymbolLayer::PropertyInterval }, { "offset_along_line", QgsSymbolLayer::PropertyOffsetAlongLine }, { "name", QgsSymbolLayer::PropertyName }, { "size", QgsSymbolLayer::PropertySize }, { "fill", QgsSymbolLayer::PropertyFillColor }, { "outline", QgsSymbolLayer::PropertyStrokeColor }, { "char", QgsSymbolLayer::PropertyCharacter }, { "enabled", QgsSymbolLayer::PropertyLayerEnabled }, { "rotation", QgsSymbolLayer::PropertyAngle }, { "horizontal_anchor_point", QgsSymbolLayer::PropertyHorizontalAnchor }, { "vertical_anchor_point", QgsSymbolLayer::PropertyVerticalAnchor }, }; QgsStringMap::const_iterator propIt = stringMap.constBegin(); for ( ; propIt != stringMap.constEnd(); ++propIt ) { QgsProperty prop; QString propertyName; if ( propIt.key().endsWith( QLatin1String( "_dd_expression" ) ) ) { //found a data defined property //get data defined property name by stripping "_dd_expression" from property key propertyName = propIt.key().left( propIt.key().length() - 14 ); prop = propertyFromMap( stringMap, propertyName ); } else if ( propIt.key().endsWith( QLatin1String( "_expression" ) ) ) { //old style data defined property, upgrade //get data defined property name by stripping "_expression" from property key propertyName = propIt.key().left( propIt.key().length() - 11 ); prop = QgsProperty::fromExpression( propIt.value() ); } if ( !prop || !OLD_PROPS.contains( propertyName ) ) continue; QgsSymbolLayer::Property key = static_cast< QgsSymbolLayer::Property >( OLD_PROPS.value( propertyName ) ); if ( type() == QgsSymbol::Line ) { //these keys had different meaning for line symbol layers if ( propertyName == QLatin1String( "width" ) ) key = QgsSymbolLayer::PropertyStrokeWidth; else if ( propertyName == QLatin1String( "color" ) ) key = QgsSymbolLayer::PropertyStrokeColor; } setDataDefinedProperty( key, prop ); } } void QgsSymbolLayer::copyDataDefinedProperties( QgsSymbolLayer *destLayer ) const { if ( !destLayer ) return; destLayer->setDataDefinedProperties( mDataDefinedProperties ); } void QgsSymbolLayer::copyPaintEffect( QgsSymbolLayer *destLayer ) const { if ( !destLayer || !mPaintEffect ) return; if ( !QgsPaintEffectRegistry::isDefaultStack( mPaintEffect.get() ) ) destLayer->setPaintEffect( mPaintEffect->clone() ); else destLayer->setPaintEffect( nullptr ); } QgsMarkerSymbolLayer::QgsMarkerSymbolLayer( bool locked ) : QgsSymbolLayer( QgsSymbol::Marker, locked ) { } QgsLineSymbolLayer::QgsLineSymbolLayer( bool locked ) : QgsSymbolLayer( QgsSymbol::Line, locked ) { } QgsLineSymbolLayer::RenderRingFilter QgsLineSymbolLayer::ringFilter() const { return mRingFilter; } void QgsLineSymbolLayer::setRingFilter( const RenderRingFilter filter ) { mRingFilter = filter; } QgsFillSymbolLayer::QgsFillSymbolLayer( bool locked ) : QgsSymbolLayer( QgsSymbol::Fill, locked ) { } void QgsMarkerSymbolLayer::startRender( QgsSymbolRenderContext &context ) { Q_UNUSED( context ) } void QgsMarkerSymbolLayer::stopRender( QgsSymbolRenderContext &context ) { Q_UNUSED( context ) } void QgsMarkerSymbolLayer::drawPreviewIcon( QgsSymbolRenderContext &context, QSize size ) { startRender( context ); QgsPaintEffect *effect = paintEffect(); QPolygonF points = context.patchShape() ? context.patchShape()->toQPolygonF( QgsSymbol::Marker, size ).value( 0 ).value( 0 ) : QgsStyle::defaultStyle()->defaultPatchAsQPolygonF( QgsSymbol::Marker, size ).value( 0 ).value( 0 ); std::unique_ptr< QgsEffectPainter > effectPainter; if ( effect && effect->enabled() ) effectPainter = qgis::make_unique< QgsEffectPainter >( context.renderContext(), effect ); for ( QPointF point : qgis::as_const( points ) ) renderPoint( point, context ); effectPainter.reset(); stopRender( context ); } void QgsMarkerSymbolLayer::markerOffset( QgsSymbolRenderContext &context, double &offsetX, double &offsetY ) const { markerOffset( context, mSize, mSize, mSizeUnit, mSizeUnit, offsetX, offsetY, mSizeMapUnitScale, mSizeMapUnitScale ); } void QgsMarkerSymbolLayer::markerOffset( QgsSymbolRenderContext &context, double width, double height, double &offsetX, double &offsetY ) const { markerOffset( context, width, height, mSizeUnit, mSizeUnit, offsetX, offsetY, mSizeMapUnitScale, mSizeMapUnitScale ); } void QgsMarkerSymbolLayer::markerOffset( QgsSymbolRenderContext &context, double width, double height, QgsUnitTypes::RenderUnit widthUnit, QgsUnitTypes::RenderUnit heightUnit, double &offsetX, double &offsetY, const QgsMapUnitScale &widthMapUnitScale, const QgsMapUnitScale &heightMapUnitScale ) const { offsetX = mOffset.x(); offsetY = mOffset.y(); if ( mDataDefinedProperties.isActive( QgsSymbolLayer::PropertyOffset ) ) { context.setOriginalValueVariable( QgsSymbolLayerUtils::encodePoint( mOffset ) ); QVariant exprVal = mDataDefinedProperties.value( QgsSymbolLayer::PropertyOffset, context.renderContext().expressionContext() ); bool ok = false; const QPointF offset = QgsSymbolLayerUtils::toPoint( exprVal, &ok ); if ( ok ) { offsetX = offset.x(); offsetY = offset.y(); } } offsetX = context.renderContext().convertToPainterUnits( offsetX, mOffsetUnit, mOffsetMapUnitScale ); offsetY = context.renderContext().convertToPainterUnits( offsetY, mOffsetUnit, mOffsetMapUnitScale ); HorizontalAnchorPoint horizontalAnchorPoint = mHorizontalAnchorPoint; VerticalAnchorPoint verticalAnchorPoint = mVerticalAnchorPoint; if ( mDataDefinedProperties.isActive( QgsSymbolLayer::PropertyHorizontalAnchor ) ) { QVariant exprVal = mDataDefinedProperties.value( QgsSymbolLayer::PropertyHorizontalAnchor, context.renderContext().expressionContext() ); if ( exprVal.isValid() ) { horizontalAnchorPoint = decodeHorizontalAnchorPoint( exprVal.toString() ); } } if ( mDataDefinedProperties.isActive( QgsSymbolLayer::PropertyVerticalAnchor ) ) { QVariant exprVal = mDataDefinedProperties.value( QgsSymbolLayer::PropertyVerticalAnchor, context.renderContext().expressionContext() ); if ( exprVal.isValid() ) { verticalAnchorPoint = decodeVerticalAnchorPoint( exprVal.toString() ); } } //correct horizontal position according to anchor point if ( horizontalAnchorPoint == HCenter && verticalAnchorPoint == VCenter ) { return; } double anchorPointCorrectionX = context.renderContext().convertToPainterUnits( width, widthUnit, widthMapUnitScale ) / 2.0; if ( widthUnit == QgsUnitTypes::RenderMetersInMapUnits && context.renderContext().flags() & QgsRenderContext::RenderSymbolPreview ) { // rendering for symbol previews -- an size in meters in map units can't be calculated, so treat the size as millimeters // and clamp it to a reasonable range. It's the best we can do in this situation! anchorPointCorrectionX = std::min( std::max( context.renderContext().convertToPainterUnits( width, QgsUnitTypes::RenderMillimeters ), 3.0 ), 100.0 ) / 2.0; } double anchorPointCorrectionY = context.renderContext().convertToPainterUnits( height, heightUnit, heightMapUnitScale ) / 2.0; if ( heightUnit == QgsUnitTypes::RenderMetersInMapUnits && context.renderContext().flags() & QgsRenderContext::RenderSymbolPreview ) { // rendering for symbol previews -- an size in meters in map units can't be calculated, so treat the size as millimeters // and clamp it to a reasonable range. It's the best we can do in this situation! anchorPointCorrectionY = std::min( std::max( context.renderContext().convertToPainterUnits( height, QgsUnitTypes::RenderMillimeters ), 3.0 ), 100.0 ) / 2.0; } if ( horizontalAnchorPoint == Left ) { offsetX += anchorPointCorrectionX; } else if ( horizontalAnchorPoint == Right ) { offsetX -= anchorPointCorrectionX; } //correct vertical position according to anchor point if ( verticalAnchorPoint == Top ) { offsetY += anchorPointCorrectionY; } else if ( verticalAnchorPoint == Bottom ) { offsetY -= anchorPointCorrectionY; } } QPointF QgsMarkerSymbolLayer::_rotatedOffset( QPointF offset, double angle ) { angle = DEG2RAD( angle ); double c = std::cos( angle ), s = std::sin( angle ); return QPointF( offset.x() * c - offset.y() * s, offset.x() * s + offset.y() * c ); } QgsMarkerSymbolLayer::HorizontalAnchorPoint QgsMarkerSymbolLayer::decodeHorizontalAnchorPoint( const QString &str ) { if ( str.compare( QLatin1String( "left" ), Qt::CaseInsensitive ) == 0 ) { return QgsMarkerSymbolLayer::Left; } else if ( str.compare( QLatin1String( "right" ), Qt::CaseInsensitive ) == 0 ) { return QgsMarkerSymbolLayer::Right; } else { return QgsMarkerSymbolLayer::HCenter; } } QgsMarkerSymbolLayer::VerticalAnchorPoint QgsMarkerSymbolLayer::decodeVerticalAnchorPoint( const QString &str ) { if ( str.compare( QLatin1String( "top" ), Qt::CaseInsensitive ) == 0 ) { return QgsMarkerSymbolLayer::Top; } else if ( str.compare( QLatin1String( "bottom" ), Qt::CaseInsensitive ) == 0 ) { return QgsMarkerSymbolLayer::Bottom; } else { return QgsMarkerSymbolLayer::VCenter; } } void QgsMarkerSymbolLayer::setOutputUnit( QgsUnitTypes::RenderUnit unit ) { mSizeUnit = unit; mOffsetUnit = unit; } QgsUnitTypes::RenderUnit QgsMarkerSymbolLayer::outputUnit() const { if ( mOffsetUnit != mSizeUnit ) { return QgsUnitTypes::RenderUnknownUnit; } return mOffsetUnit; } void QgsMarkerSymbolLayer::setMapUnitScale( const QgsMapUnitScale &scale ) { mSizeMapUnitScale = scale; mOffsetMapUnitScale = scale; } QgsMapUnitScale QgsMarkerSymbolLayer::mapUnitScale() const { if ( mSizeMapUnitScale == mOffsetMapUnitScale ) { return mSizeMapUnitScale; } return QgsMapUnitScale(); } void QgsLineSymbolLayer::setOutputUnit( QgsUnitTypes::RenderUnit unit ) { mWidthUnit = unit; } QgsUnitTypes::RenderUnit QgsLineSymbolLayer::outputUnit() const { return mWidthUnit; } void QgsLineSymbolLayer::setMapUnitScale( const QgsMapUnitScale &scale ) { mWidthMapUnitScale = scale; } QgsMapUnitScale QgsLineSymbolLayer::mapUnitScale() const { return mWidthMapUnitScale; } void QgsLineSymbolLayer::drawPreviewIcon( QgsSymbolRenderContext &context, QSize size ) { const QList< QList< QPolygonF > > points = context.patchShape() ? context.patchShape()->toQPolygonF( QgsSymbol::Line, size ) : QgsStyle::defaultStyle()->defaultPatchAsQPolygonF( QgsSymbol::Line, size ); startRender( context ); QgsPaintEffect *effect = paintEffect(); std::unique_ptr< QgsEffectPainter > effectPainter; if ( effect && effect->enabled() ) effectPainter = qgis::make_unique< QgsEffectPainter >( context.renderContext(), effect ); for ( const QList< QPolygonF > &line : points ) renderPolyline( line.value( 0 ), context ); effectPainter.reset(); stopRender( context ); } void QgsLineSymbolLayer::renderPolygonStroke( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context ) { switch ( mRingFilter ) { case AllRings: case ExteriorRingOnly: renderPolyline( points, context ); break; case InteriorRingsOnly: break; } if ( rings ) { switch ( mRingFilter ) { case AllRings: case InteriorRingsOnly: { for ( const QPolygonF &ring : qgis::as_const( *rings ) ) renderPolyline( ring, context ); } break; case ExteriorRingOnly: break; } } } double QgsLineSymbolLayer::width( const QgsRenderContext &context ) const { return context.convertToPainterUnits( mWidth, mWidthUnit, mWidthMapUnitScale ); } double QgsLineSymbolLayer::dxfWidth( const QgsDxfExport &e, QgsSymbolRenderContext &context ) const { Q_UNUSED( context ) return width() * e.mapUnitScaleFactor( e.symbologyScale(), widthUnit(), e.mapUnits(), context.renderContext().mapToPixel().mapUnitsPerPixel() ); } void QgsFillSymbolLayer::drawPreviewIcon( QgsSymbolRenderContext &context, QSize size ) { const QList< QList< QPolygonF > > polys = context.patchShape() ? context.patchShape()->toQPolygonF( QgsSymbol::Fill, size ) : QgsStyle::defaultStyle()->defaultPatchAsQPolygonF( QgsSymbol::Fill, size ); startRender( context ); QgsPaintEffect *effect = paintEffect(); std::unique_ptr< QgsEffectPainter > effectPainter; if ( effect && effect->enabled() ) effectPainter = qgis::make_unique< QgsEffectPainter >( context.renderContext(), effect ); for ( const QList< QPolygonF > &poly : polys ) { QVector< QPolygonF > rings; for ( int i = 1; i < poly.size(); ++i ) rings << poly.at( i ); renderPolygon( poly.value( 0 ), &rings, context ); } effectPainter.reset(); stopRender( context ); } void QgsFillSymbolLayer::_renderPolygon( QPainter *p, const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context ) { if ( !p ) { return; } // Disable 'Antialiasing' if the geometry was generalized in the current RenderContext (We known that it must have least #5 points). if ( points.size() <= 5 && ( context.renderContext().vectorSimplifyMethod().simplifyHints() & QgsVectorSimplifyMethod::AntialiasingSimplification ) && QgsAbstractGeometrySimplifier::isGeneralizableByDeviceBoundingBox( points, context.renderContext().vectorSimplifyMethod().threshold() ) && ( p->renderHints() & QPainter::Antialiasing ) ) { p->setRenderHint( QPainter::Antialiasing, false ); p->drawRect( points.boundingRect() ); p->setRenderHint( QPainter::Antialiasing, true ); return; } // polygons outlines are sometimes rendered wrongly with drawPolygon, when // clipped (see #13343), so use drawPath instead. if ( !rings && p->pen().style() == Qt::NoPen ) { // simple polygon without holes p->drawPolygon( points ); } else { // polygon with holes must be drawn using painter path QPainterPath path; path.addPolygon( points ); if ( rings ) { for ( auto it = rings->constBegin(); it != rings->constEnd(); ++it ) { QPolygonF ring = *it; path.addPolygon( ring ); } } p->drawPath( path ); } } void QgsMarkerSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, const QgsStringMap &props ) const { QDomElement symbolizerElem = doc.createElement( QStringLiteral( "se:PointSymbolizer" ) ); if ( !props.value( QStringLiteral( "uom" ), QString() ).isEmpty() ) symbolizerElem.setAttribute( QStringLiteral( "uom" ), props.value( QStringLiteral( "uom" ), QString() ) ); element.appendChild( symbolizerElem ); // <Geometry> QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( QStringLiteral( "geom" ), QString() ) ); writeSldMarker( doc, symbolizerElem, props ); } QgsSymbolLayerReferenceList QgsSymbolLayer::masks() const { return {}; }
rldhont/Quantum-GIS
src/core/symbology/qgssymbollayer.cpp
C++
gpl-2.0
35,790
/*! * \file tpm.h * \brief TPM Peripheral API * * \addtogroup tpm_peripheral * @{ */ #ifndef _TPM_H_ #define _TPM_H_ #include <stdbool.h> #include <stdint.h> #include "v1_2.h" #include "lgr_vector.h" #include "core_cm0plus.h" #include "cmsis_gcc.h" #include "ringbuffer.h" #include "port.h" extern uint32_t tpm_clock_input; // TPM0 Status control register #define TPM0_PS (0b000 << 0) #define TPM0_CMOD (0b01 << 3) #define TPM0_SC (TPM0_CMOD | TPM0_PS) #define TPM0_TOIE (0b1 << 6) #define TPM0_TOIE_MASK (~(0b1 << 6)) // TPM0 Configuration #define TPM0_DBGMODE (0b11 << 6) // Debug mode #define TPM0_CONF_LGR (TPM0_DBGMODE) // TPM Status #define TPM_STATUS_TOF 0b11111111 #define TPM_SC_TOF (1 << 7) #define TPM_C0SC_CHF (11 << 6) #define TPM_SC_DISABLE 0b00000000 #define TPM_SC_SET_CMOD (01 << 3) void isr_tpm0(void) __attribute__((interrupt("IRQ"))); void tpm0_init(bool ); void wait_n_ms(uint32_t ); #ifdef TPM_TEST void tpm0_test_loop(void); #endif #endif /*! @} */
oresat/low-gain-radio
firmware/drivers/include/tpm.h
C
gpl-2.0
1,182
/*********************************************************** Copyright 1987, 1989, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. Copyright 1987, 1989 by Digital Equipment Corporation, Maynard, Massachusetts. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Digital not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /***************************************************************** * Stuff to create connections --- OS dependent * * EstablishNewConnections, CreateWellKnownSockets, ResetWellKnownSockets, * CloseDownConnection, CheckConnections, AddEnabledDevice, * RemoveEnabledDevice, OnlyListToOneClient, * ListenToAllClients, * * (WaitForSomething is in its own file) * * In this implementation, a client socket table is not kept. * Instead, what would be the index into the table is just the * file descriptor of the socket. This won't work for if the * socket ids aren't small nums (0 - 2^8) * *****************************************************************/ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> #endif #ifdef WIN32 #include <X11/Xwinsock.h> #endif #include <X11/X.h> #include <X11/Xproto.h> #define XSERV_t #define TRANS_SERVER #define TRANS_REOPEN #include <X11/Xtrans/Xtrans.h> #include <errno.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #ifndef WIN32 #if defined(Lynx) #include <socket.h> #else #include <sys/socket.h> #endif #ifdef hpux #include <sys/utsname.h> #include <sys/ioctl.h> #endif #if defined(DGUX) #include <sys/ioctl.h> #include <sys/utsname.h> #include <sys/socket.h> #include <sys/uio.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/param.h> #include <unistd.h> #endif #ifdef AIXV3 #include <sys/ioctl.h> #endif #if defined(TCPCONN) || defined(STREAMSCONN) # include <netinet/in.h> # include <arpa/inet.h> # if !defined(hpux) # ifdef apollo # ifndef NO_TCP_H # include <netinet/tcp.h> # endif # else # ifdef CSRG_BASED # include <sys/param.h> # endif # include <netinet/tcp.h> # endif # endif # include <arpa/inet.h> #endif #ifndef Lynx #include <sys/uio.h> #else #include <uio.h> #endif #endif /* WIN32 */ #include "misc.h" /* for typedef of pointer */ #include "osdep.h" #include <X11/Xpoll.h> #include "opaque.h" #include "dixstruct.h" #ifdef XAPPGROUP #include "appgroup.h" #endif #include "xace.h" #ifdef XCSECURITY #include "securitysrv.h" #endif #ifdef X_NOT_POSIX #define Pid_t int #else #define Pid_t pid_t #endif #ifdef DNETCONN #include <netdnet/dn.h> #endif /* DNETCONN */ #ifdef HAS_GETPEERUCRED # include <ucred.h> # include <zone.h> #endif #ifdef XSERVER_DTRACE # include <sys/types.h> typedef const char *string; # ifndef HAS_GETPEERUCRED # define zoneid_t int # endif # include "../dix/Xserver-dtrace.h" #endif static int lastfdesc; /* maximum file descriptor */ fd_set WellKnownConnections; /* Listener mask */ fd_set EnabledDevices; /* mask for input devices that are on */ fd_set AllSockets; /* select on this */ fd_set AllClients; /* available clients */ fd_set LastSelectMask; /* mask returned from last select call */ fd_set ClientsWithInput; /* clients with FULL requests in buffer */ fd_set ClientsWriteBlocked; /* clients who cannot receive output */ fd_set OutputPending; /* clients with reply/event data ready to go */ int MaxClients = 0; Bool NewOutputPending; /* not yet attempted to write some new output */ Bool AnyClientsWriteBlocked; /* true if some client blocked on write */ static Bool RunFromSmartParent; /* send SIGUSR1 to parent process */ Bool PartialNetwork; /* continue even if unable to bind all addrs */ static Pid_t ParentProcess; static Bool debug_conns = FALSE; fd_set IgnoredClientsWithInput; static fd_set GrabImperviousClients; static fd_set SavedAllClients; static fd_set SavedAllSockets; static fd_set SavedClientsWithInput; _X_EXPORT int GrabInProgress = 0; #if !defined(WIN32) int *ConnectionTranslation = NULL; #else /* * On NT fds are not between 0 and MAXSOCKS, they are unrelated, and there is * not even a known maximum value, so use something quite arbitrary for now. * Do storage is a hash table of size 256. Collisions are handled in a linked * list. */ #undef MAXSOCKS #define MAXSOCKS 500 #undef MAXSELECT #define MAXSELECT 500 #define MAXFD 500 struct _ct_node { struct _ct_node *next; int key; int value; }; struct _ct_node *ct_head[256]; void InitConnectionTranslation(void) { bzero(ct_head, sizeof(ct_head)); } int GetConnectionTranslation(int conn) { struct _ct_node *node = ct_head[conn & 0xff]; while (node != NULL) { if (node->key == conn) return node->value; node = node->next; } return 0; } void SetConnectionTranslation(int conn, int client) { struct _ct_node **node = ct_head + (conn & 0xff); if (client == 0) /* remove entry */ { while (*node != NULL) { if ((*node)->key == conn) { struct _ct_node *temp = *node; *node = (*node)->next; free(temp); return; } node = &((*node)->next); } return; } else { while (*node != NULL) { if ((*node)->key == conn) { (*node)->value = client; return; } node = &((*node)->next); } *node = (struct _ct_node*)xalloc(sizeof(struct _ct_node)); (*node)->next = NULL; (*node)->key = conn; (*node)->value = client; return; } } void ClearConnectionTranslation(void) { unsigned i; for (i = 0; i < 256; i++) { struct _ct_node *node = ct_head[i]; while (node != NULL) { struct _ct_node *temp = node; node = node->next; xfree(temp); } } } #endif static XtransConnInfo *ListenTransConns = NULL; static int *ListenTransFds = NULL; static int ListenTransCount; static void ErrorConnMax(XtransConnInfo /* trans_conn */); static XtransConnInfo lookup_trans_conn (int fd) { if (ListenTransFds) { int i; for (i = 0; i < ListenTransCount; i++) if (ListenTransFds[i] == fd) return ListenTransConns[i]; } return (NULL); } /* Set MaxClients and lastfdesc, and allocate ConnectionTranslation */ void InitConnectionLimits(void) { lastfdesc = -1; #ifndef __CYGWIN__ #if !defined(XNO_SYSCONF) && defined(_SC_OPEN_MAX) lastfdesc = sysconf(_SC_OPEN_MAX) - 1; #endif #ifdef HAS_GETDTABLESIZE if (lastfdesc < 0) lastfdesc = getdtablesize() - 1; #endif #ifdef _NFILE if (lastfdesc < 0) lastfdesc = _NFILE - 1; #endif #endif /* __CYGWIN__ */ /* This is the fallback */ if (lastfdesc < 0) lastfdesc = MAXSOCKS; if (lastfdesc > MAXSELECT) lastfdesc = MAXSELECT; if (lastfdesc > MAXCLIENTS) { lastfdesc = MAXCLIENTS; if (debug_conns) ErrorF( "REACHED MAXIMUM CLIENTS LIMIT %d\n", MAXCLIENTS); } MaxClients = lastfdesc; #ifdef DEBUG ErrorF("InitConnectionLimits: MaxClients = %d\n", MaxClients); #endif #if !defined(WIN32) ConnectionTranslation = (int *)xnfalloc(sizeof(int)*(lastfdesc + 1)); #else InitConnectionTranslation(); #endif } /***************** * CreateWellKnownSockets * At initialization, create the sockets to listen on for new clients. *****************/ void CreateWellKnownSockets(void) { int i; int partial; char port[20]; OsSigHandlerPtr handler; FD_ZERO(&AllSockets); FD_ZERO(&AllClients); FD_ZERO(&LastSelectMask); FD_ZERO(&ClientsWithInput); #if !defined(WIN32) for (i=0; i<MaxClients; i++) ConnectionTranslation[i] = 0; #else ClearConnectionTranslation(); #endif FD_ZERO (&WellKnownConnections); sprintf (port, "%d", atoi (display)); if ((_XSERVTransMakeAllCOTSServerListeners (port, &partial, &ListenTransCount, &ListenTransConns) >= 0) && (ListenTransCount >= 1)) { if (!PartialNetwork && partial) { FatalError ("Failed to establish all listening sockets"); } else { ListenTransFds = (int *) xalloc (ListenTransCount * sizeof (int)); for (i = 0; i < ListenTransCount; i++) { int fd = _XSERVTransGetConnectionNumber (ListenTransConns[i]); ListenTransFds[i] = fd; FD_SET (fd, &WellKnownConnections); if (!_XSERVTransIsLocal (ListenTransConns[i])) { DefineSelf (fd); } } } } if (!XFD_ANYSET (&WellKnownConnections)) FatalError ("Cannot establish any listening sockets - Make sure an X server isn't already running"); #if !defined(WIN32) OsSignal (SIGPIPE, SIG_IGN); OsSignal (SIGHUP, AutoResetServer); #endif OsSignal (SIGINT, GiveUp); OsSignal (SIGTERM, GiveUp); XFD_COPYSET (&WellKnownConnections, &AllSockets); ResetHosts(display); /* * Magic: If SIGUSR1 was set to SIG_IGN when * the server started, assume that either * * a- The parent process is ignoring SIGUSR1 * * or * * b- The parent process is expecting a SIGUSR1 * when the server is ready to accept connections * * In the first case, the signal will be harmless, * in the second case, the signal will be quite * useful */ #if !defined(WIN32) handler = OsSignal (SIGUSR1, SIG_IGN); if ( handler == SIG_IGN) RunFromSmartParent = TRUE; OsSignal(SIGUSR1, handler); ParentProcess = getppid (); if (RunFromSmartParent) { if (ParentProcess > 1) { kill (ParentProcess, SIGUSR1); } } #endif #ifdef XDMCP XdmcpInit (); #endif } void ResetWellKnownSockets (void) { int i; ResetOsBuffers(); for (i = 0; i < ListenTransCount; i++) { int status = _XSERVTransResetListener (ListenTransConns[i]); if (status != TRANS_RESET_NOOP) { if (status == TRANS_RESET_FAILURE) { /* * ListenTransConns[i] freed by xtrans. * Remove it from out list. */ FD_CLR (ListenTransFds[i], &WellKnownConnections); ListenTransFds[i] = ListenTransFds[ListenTransCount - 1]; ListenTransConns[i] = ListenTransConns[ListenTransCount - 1]; ListenTransCount -= 1; i -= 1; } else if (status == TRANS_RESET_NEW_FD) { /* * A new file descriptor was allocated (the old one was closed) */ int newfd = _XSERVTransGetConnectionNumber (ListenTransConns[i]); FD_CLR (ListenTransFds[i], &WellKnownConnections); ListenTransFds[i] = newfd; FD_SET(newfd, &WellKnownConnections); } } } ResetAuthorization (); ResetHosts(display); /* * See above in CreateWellKnownSockets about SIGUSR1 */ #if !defined(WIN32) if (RunFromSmartParent) { if (ParentProcess > 1) { kill (ParentProcess, SIGUSR1); } } #endif /* * restart XDMCP */ #ifdef XDMCP XdmcpReset (); #endif } void CloseWellKnownConnections(void) { int i; for (i = 0; i < ListenTransCount; i++) _XSERVTransClose (ListenTransConns[i]); } static void AuthAudit (ClientPtr client, Bool letin, struct sockaddr *saddr, int len, unsigned int proto_n, char *auth_proto, int auth_id) { char addr[128]; char *out = addr; int client_uid; char client_uid_string[64]; #ifdef HAS_GETPEERUCRED ucred_t *peercred = NULL; #endif #if defined(HAS_GETPEERUCRED) || defined(XSERVER_DTRACE) pid_t client_pid = -1; zoneid_t client_zid = -1; #endif if (!len) strcpy(out, "local host"); else switch (saddr->sa_family) { case AF_UNSPEC: #if defined(UNIXCONN) || defined(LOCALCONN) case AF_UNIX: #endif strcpy(out, "local host"); break; #if defined(TCPCONN) || defined(STREAMSCONN) || defined(MNX_TCPCONN) case AF_INET: sprintf(out, "IP %s", inet_ntoa(((struct sockaddr_in *) saddr)->sin_addr)); break; #if defined(IPv6) && defined(AF_INET6) case AF_INET6: { char ipaddr[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, &((struct sockaddr_in6 *) saddr)->sin6_addr, ipaddr, sizeof(ipaddr)); sprintf(out, "IP %s", ipaddr); } break; #endif #endif #ifdef DNETCONN case AF_DECnet: sprintf(out, "DN %s", dnet_ntoa(&((struct sockaddr_dn *) saddr)->sdn_add)); break; #endif default: strcpy(out, "unknown address"); } #ifdef HAS_GETPEERUCRED if (getpeerucred(((OsCommPtr)client->osPrivate)->fd, &peercred) >= 0) { client_uid = ucred_geteuid(peercred); client_pid = ucred_getpid(peercred); client_zid = ucred_getzoneid(peercred); ucred_free(peercred); snprintf(client_uid_string, sizeof(client_uid_string), " (uid %ld, pid %ld, zone %ld)", (long) client_uid, (long) client_pid, (long) client_zid); } #else if (LocalClientCred(client, &client_uid, NULL) != -1) { snprintf(client_uid_string, sizeof(client_uid_string), " (uid %d)", client_uid); } #endif else { client_uid_string[0] = '\0'; } #ifdef XSERVER_DTRACE XSERVER_CLIENT_AUTH(client->index, addr, client_pid, client_zid); if (auditTrailLevel > 1) { #endif if (proto_n) AuditF("client %d %s from %s%s\n Auth name: %.*s ID: %d\n", client->index, letin ? "connected" : "rejected", addr, client_uid_string, (int)proto_n, auth_proto, auth_id); else AuditF("client %d %s from %s%s\n", client->index, letin ? "connected" : "rejected", addr, client_uid_string); #ifdef XSERVER_DTRACE } #endif } XID AuthorizationIDOfClient(ClientPtr client) { if (client->osPrivate) return ((OsCommPtr)client->osPrivate)->auth_id; else return None; } /***************************************************************** * ClientAuthorized * * Sent by the client at connection setup: * typedef struct _xConnClientPrefix { * CARD8 byteOrder; * BYTE pad; * CARD16 majorVersion, minorVersion; * CARD16 nbytesAuthProto; * CARD16 nbytesAuthString; * } xConnClientPrefix; * * It is hoped that eventually one protocol will be agreed upon. In the * mean time, a server that implements a different protocol than the * client expects, or a server that only implements the host-based * mechanism, will simply ignore this information. * *****************************************************************/ char * ClientAuthorized(ClientPtr client, unsigned int proto_n, char *auth_proto, unsigned int string_n, char *auth_string) { OsCommPtr priv; Xtransaddr *from = NULL; int family; int fromlen; XID auth_id; char *reason = NULL; XtransConnInfo trans_conn; priv = (OsCommPtr)client->osPrivate; trans_conn = priv->trans_conn; auth_id = CheckAuthorization (proto_n, auth_proto, string_n, auth_string, client, &reason); if (auth_id == (XID) ~0L) { if ( #ifdef XCSECURITY (proto_n == 0 || strncmp (auth_proto, XSecurityAuthorizationName, proto_n) != 0) && #endif _XSERVTransGetPeerAddr (trans_conn, &family, &fromlen, &from) != -1) { if (InvalidHost ((struct sockaddr *) from, fromlen, client)) AuthAudit(client, FALSE, (struct sockaddr *) from, fromlen, proto_n, auth_proto, auth_id); else { auth_id = (XID) 0; #ifdef XSERVER_DTRACE if ((auditTrailLevel > 1) || XSERVER_CLIENT_AUTH_ENABLED()) #else if (auditTrailLevel > 1) #endif AuthAudit(client, TRUE, (struct sockaddr *) from, fromlen, proto_n, auth_proto, auth_id); } xfree ((char *) from); } if (auth_id == (XID) ~0L) { if (reason) return reason; else return "Client is not authorized to connect to Server"; } } #ifdef XSERVER_DTRACE else if ((auditTrailLevel > 1) || XSERVER_CLIENT_AUTH_ENABLED()) #else else if (auditTrailLevel > 1) #endif { if (_XSERVTransGetPeerAddr (trans_conn, &family, &fromlen, &from) != -1) { AuthAudit(client, TRUE, (struct sockaddr *) from, fromlen, proto_n, auth_proto, auth_id); xfree ((char *) from); } } priv->auth_id = auth_id; priv->conn_time = 0; #ifdef XDMCP /* indicate to Xdmcp protocol that we've opened new client */ XdmcpOpenDisplay(priv->fd); #endif /* XDMCP */ XaceHook(XACE_AUTH_AVAIL, client, auth_id); /* At this point, if the client is authorized to change the access control * list, we should getpeername() information, and add the client to * the selfhosts list. It's not really the host machine, but the * true purpose of the selfhosts list is to see who may change the * access control list. */ return((char *)NULL); } static ClientPtr AllocNewConnection (XtransConnInfo trans_conn, int fd, CARD32 conn_time) { OsCommPtr oc; ClientPtr client; if ( #ifndef WIN32 fd >= lastfdesc #else XFD_SETCOUNT(&AllClients) >= MaxClients #endif ) return NullClient; oc = (OsCommPtr)xalloc(sizeof(OsCommRec)); if (!oc) return NullClient; oc->trans_conn = trans_conn; oc->fd = fd; oc->input = (ConnectionInputPtr)NULL; oc->output = (ConnectionOutputPtr)NULL; oc->auth_id = None; oc->conn_time = conn_time; if (!(client = NextAvailableClient((pointer)oc))) { xfree (oc); return NullClient; } #if !defined(WIN32) ConnectionTranslation[fd] = client->index; #else SetConnectionTranslation(fd, client->index); #endif if (GrabInProgress) { FD_SET(fd, &SavedAllClients); FD_SET(fd, &SavedAllSockets); } else { FD_SET(fd, &AllClients); FD_SET(fd, &AllSockets); } #ifdef DEBUG ErrorF("AllocNewConnection: client index = %d, socket fd = %d\n", client->index, fd); #endif #ifdef XSERVER_DTRACE XSERVER_CLIENT_CONNECT(client->index, fd); #endif return client; } /***************** * EstablishNewConnections * If anyone is waiting on listened sockets, accept them. * Returns a mask with indices of new clients. Updates AllClients * and AllSockets. *****************/ /*ARGSUSED*/ Bool EstablishNewConnections(ClientPtr clientUnused, pointer closure) { fd_set readyconnections; /* set of listeners that are ready */ int curconn; /* fd of listener that's ready */ register int newconn; /* fd of new client */ CARD32 connect_time; register int i; register ClientPtr client; register OsCommPtr oc; fd_set tmask; XFD_ANDSET (&tmask, (fd_set*)closure, &WellKnownConnections); XFD_COPYSET(&tmask, &readyconnections); if (!XFD_ANYSET(&readyconnections)) return TRUE; connect_time = GetTimeInMillis(); /* kill off stragglers */ for (i=1; i<currentMaxClients; i++) { if ((client = clients[i])) { oc = (OsCommPtr)(client->osPrivate); if ((oc && (oc->conn_time != 0) && (connect_time - oc->conn_time) >= TimeOutValue) || (client->noClientException != Success && !client->clientGone)) CloseDownClient(client); } } #ifndef WIN32 for (i = 0; i < howmany(XFD_SETSIZE, NFDBITS); i++) { while (readyconnections.fds_bits[i]) #else for (i = 0; i < XFD_SETCOUNT(&readyconnections); i++) #endif { XtransConnInfo trans_conn, new_trans_conn; int status; #ifndef WIN32 curconn = ffs (readyconnections.fds_bits[i]) - 1; readyconnections.fds_bits[i] &= ~((fd_mask)1 << curconn); curconn += (i * (sizeof(fd_mask)*8)); #else curconn = XFD_FD(&readyconnections, i); #endif if ((trans_conn = lookup_trans_conn (curconn)) == NULL) continue; if ((new_trans_conn = _XSERVTransAccept (trans_conn, &status)) == NULL) continue; newconn = _XSERVTransGetConnectionNumber (new_trans_conn); if (newconn < lastfdesc) { int clientid; #if !defined(WIN32) clientid = ConnectionTranslation[newconn]; #else clientid = GetConnectionTranslation(newconn); #endif if(clientid && (client = clients[clientid])) CloseDownClient(client); } _XSERVTransSetOption(new_trans_conn, TRANS_NONBLOCKING, 1); if (!AllocNewConnection (new_trans_conn, newconn, connect_time)) { ErrorConnMax(new_trans_conn); _XSERVTransClose(new_trans_conn); } } #ifndef WIN32 } #endif return TRUE; } #define NOROOM "Maximum number of clients reached" /************ * ErrorConnMax * Fail a connection due to lack of client or file descriptor space ************/ static void ErrorConnMax(XtransConnInfo trans_conn) { int fd = _XSERVTransGetConnectionNumber (trans_conn); xConnSetupPrefix csp; char pad[3]; struct iovec iov[3]; char byteOrder = 0; int whichbyte = 1; struct timeval waittime; fd_set mask; /* if these seems like a lot of trouble to go to, it probably is */ waittime.tv_sec = BOTIMEOUT / MILLI_PER_SECOND; waittime.tv_usec = (BOTIMEOUT % MILLI_PER_SECOND) * (1000000 / MILLI_PER_SECOND); FD_ZERO(&mask); FD_SET(fd, &mask); (void)Select(fd + 1, &mask, NULL, NULL, &waittime); /* try to read the byte-order of the connection */ (void)_XSERVTransRead(trans_conn, &byteOrder, 1); if ((byteOrder == 'l') || (byteOrder == 'B')) { csp.success = xFalse; csp.lengthReason = sizeof(NOROOM) - 1; csp.length = (sizeof(NOROOM) + 2) >> 2; csp.majorVersion = X_PROTOCOL; csp.minorVersion = X_PROTOCOL_REVISION; if (((*(char *) &whichbyte) && (byteOrder == 'B')) || (!(*(char *) &whichbyte) && (byteOrder == 'l'))) { swaps(&csp.majorVersion, whichbyte); swaps(&csp.minorVersion, whichbyte); swaps(&csp.length, whichbyte); } iov[0].iov_len = sz_xConnSetupPrefix; iov[0].iov_base = (char *) &csp; iov[1].iov_len = csp.lengthReason; iov[1].iov_base = NOROOM; iov[2].iov_len = (4 - (csp.lengthReason & 3)) & 3; iov[2].iov_base = pad; (void)_XSERVTransWritev(trans_conn, iov, 3); } } /************ * CloseDownFileDescriptor: * Remove this file descriptor and it's I/O buffers, etc. ************/ static void CloseDownFileDescriptor(OsCommPtr oc) { int connection = oc->fd; if (oc->trans_conn) { _XSERVTransDisconnect(oc->trans_conn); _XSERVTransClose(oc->trans_conn); } #ifndef WIN32 ConnectionTranslation[connection] = 0; #else SetConnectionTranslation(connection, 0); #endif FD_CLR(connection, &AllSockets); FD_CLR(connection, &AllClients); FD_CLR(connection, &ClientsWithInput); FD_CLR(connection, &GrabImperviousClients); if (GrabInProgress) { FD_CLR(connection, &SavedAllSockets); FD_CLR(connection, &SavedAllClients); FD_CLR(connection, &SavedClientsWithInput); } FD_CLR(connection, &ClientsWriteBlocked); if (!XFD_ANYSET(&ClientsWriteBlocked)) AnyClientsWriteBlocked = FALSE; FD_CLR(connection, &OutputPending); } /***************** * CheckConnections * Some connection has died, go find which one and shut it down * The file descriptor has been closed, but is still in AllClients. * If would truly be wonderful if select() would put the bogus * file descriptors in the exception mask, but nooooo. So we have * to check each and every socket individually. *****************/ void CheckConnections(void) { #ifndef WIN32 fd_mask mask; #endif fd_set tmask; int curclient, curoff; int i; struct timeval notime; int r; #ifdef WIN32 fd_set savedAllClients; #endif notime.tv_sec = 0; notime.tv_usec = 0; #ifndef WIN32 for (i=0; i<howmany(XFD_SETSIZE, NFDBITS); i++) { mask = AllClients.fds_bits[i]; while (mask) { curoff = ffs (mask) - 1; curclient = curoff + (i * (sizeof(fd_mask)*8)); FD_ZERO(&tmask); FD_SET(curclient, &tmask); r = Select (curclient + 1, &tmask, NULL, NULL, &notime); if (r < 0) CloseDownClient(clients[ConnectionTranslation[curclient]]); mask &= ~((fd_mask)1 << curoff); } } #else XFD_COPYSET(&AllClients, &savedAllClients); for (i = 0; i < XFD_SETCOUNT(&savedAllClients); i++) { curclient = XFD_FD(&savedAllClients, i); FD_ZERO(&tmask); FD_SET(curclient, &tmask); r = Select (curclient + 1, &tmask, NULL, NULL, &notime); if (r < 0 && GetConnectionTranslation(curclient) > 0) CloseDownClient(clients[GetConnectionTranslation(curclient)]); } #endif } /***************** * CloseDownConnection * Delete client from AllClients and free resources *****************/ void CloseDownConnection(ClientPtr client) { OsCommPtr oc = (OsCommPtr)client->osPrivate; if (oc->output && oc->output->count) FlushClient(client, oc, (char *)NULL, 0); #ifdef XDMCP XdmcpCloseDisplay(oc->fd); #endif CloseDownFileDescriptor(oc); FreeOsBuffers(oc); xfree(client->osPrivate); client->osPrivate = (pointer)NULL; if (auditTrailLevel > 1) AuditF("client %d disconnected\n", client->index); } _X_EXPORT void AddGeneralSocket(int fd) { FD_SET(fd, &AllSockets); if (GrabInProgress) FD_SET(fd, &SavedAllSockets); } _X_EXPORT void AddEnabledDevice(int fd) { FD_SET(fd, &EnabledDevices); AddGeneralSocket(fd); } _X_EXPORT void RemoveGeneralSocket(int fd) { FD_CLR(fd, &AllSockets); if (GrabInProgress) FD_CLR(fd, &SavedAllSockets); } _X_EXPORT void RemoveEnabledDevice(int fd) { FD_CLR(fd, &EnabledDevices); RemoveGeneralSocket(fd); } /***************** * OnlyListenToOneClient: * Only accept requests from one client. Continue to handle new * connections, but don't take any protocol requests from the new * ones. Note that if GrabInProgress is set, EstablishNewConnections * needs to put new clients into SavedAllSockets and SavedAllClients. * Note also that there is no timeout for this in the protocol. * This routine is "undone" by ListenToAllClients() *****************/ void OnlyListenToOneClient(ClientPtr client) { OsCommPtr oc = (OsCommPtr)client->osPrivate; int connection = oc->fd; if (! GrabInProgress) { XFD_COPYSET(&ClientsWithInput, &SavedClientsWithInput); XFD_ANDSET(&ClientsWithInput, &ClientsWithInput, &GrabImperviousClients); if (FD_ISSET(connection, &SavedClientsWithInput)) { FD_CLR(connection, &SavedClientsWithInput); FD_SET(connection, &ClientsWithInput); } XFD_UNSET(&SavedClientsWithInput, &GrabImperviousClients); XFD_COPYSET(&AllSockets, &SavedAllSockets); XFD_COPYSET(&AllClients, &SavedAllClients); XFD_UNSET(&AllSockets, &AllClients); XFD_ANDSET(&AllClients, &AllClients, &GrabImperviousClients); FD_SET(connection, &AllClients); XFD_ORSET(&AllSockets, &AllSockets, &AllClients); GrabInProgress = client->index; } } /**************** * ListenToAllClients: * Undoes OnlyListentToOneClient() ****************/ void ListenToAllClients(void) { if (GrabInProgress) { XFD_ORSET(&AllSockets, &AllSockets, &SavedAllSockets); XFD_ORSET(&AllClients, &AllClients, &SavedAllClients); XFD_ORSET(&ClientsWithInput, &ClientsWithInput, &SavedClientsWithInput); GrabInProgress = 0; } } /**************** * IgnoreClient * Removes one client from input masks. * Must have cooresponding call to AttendClient. ****************/ _X_EXPORT void IgnoreClient (ClientPtr client) { OsCommPtr oc = (OsCommPtr)client->osPrivate; int connection = oc->fd; isItTimeToYield = TRUE; if (!GrabInProgress || FD_ISSET(connection, &AllClients)) { if (FD_ISSET (connection, &ClientsWithInput)) FD_SET(connection, &IgnoredClientsWithInput); else FD_CLR(connection, &IgnoredClientsWithInput); FD_CLR(connection, &ClientsWithInput); FD_CLR(connection, &AllSockets); FD_CLR(connection, &AllClients); FD_CLR(connection, &LastSelectMask); } else { if (FD_ISSET (connection, &SavedClientsWithInput)) FD_SET(connection, &IgnoredClientsWithInput); else FD_CLR(connection, &IgnoredClientsWithInput); FD_CLR(connection, &SavedClientsWithInput); FD_CLR(connection, &SavedAllSockets); FD_CLR(connection, &SavedAllClients); } } /**************** * AttendClient * Adds one client back into the input masks. ****************/ _X_EXPORT void AttendClient (ClientPtr client) { OsCommPtr oc = (OsCommPtr)client->osPrivate; int connection = oc->fd; if (!GrabInProgress || GrabInProgress == client->index || FD_ISSET(connection, &GrabImperviousClients)) { FD_SET(connection, &AllClients); FD_SET(connection, &AllSockets); FD_SET(connection, &LastSelectMask); if (FD_ISSET (connection, &IgnoredClientsWithInput)) FD_SET(connection, &ClientsWithInput); } else { FD_SET(connection, &SavedAllClients); FD_SET(connection, &SavedAllSockets); if (FD_ISSET(connection, &IgnoredClientsWithInput)) FD_SET(connection, &SavedClientsWithInput); } } /* make client impervious to grabs; assume only executing client calls this */ _X_EXPORT void MakeClientGrabImpervious(ClientPtr client) { OsCommPtr oc = (OsCommPtr)client->osPrivate; int connection = oc->fd; FD_SET(connection, &GrabImperviousClients); if (ServerGrabCallback) { ServerGrabInfoRec grabinfo; grabinfo.client = client; grabinfo.grabstate = CLIENT_IMPERVIOUS; CallCallbacks(&ServerGrabCallback, &grabinfo); } } /* make client pervious to grabs; assume only executing client calls this */ _X_EXPORT void MakeClientGrabPervious(ClientPtr client) { OsCommPtr oc = (OsCommPtr)client->osPrivate; int connection = oc->fd; FD_CLR(connection, &GrabImperviousClients); if (GrabInProgress && (GrabInProgress != client->index)) { if (FD_ISSET(connection, &ClientsWithInput)) { FD_SET(connection, &SavedClientsWithInput); FD_CLR(connection, &ClientsWithInput); } FD_CLR(connection, &AllSockets); FD_CLR(connection, &AllClients); isItTimeToYield = TRUE; } if (ServerGrabCallback) { ServerGrabInfoRec grabinfo; grabinfo.client = client; grabinfo.grabstate = CLIENT_PERVIOUS; CallCallbacks(&ServerGrabCallback, &grabinfo); } }
mcr/xorg-xvnc4
xorg-server/os/connection.c
C
gpl-2.0
32,023
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ /* * Copyright (C) 2004 Nokia Corporation. * * This program 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; version 2 of the * License. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef __DBUS_UTILS_H__ #define __DBUS_UTILS_H__ #include <libmatevfs/mate-vfs.h> #include <dbus/dbus-glib-lowlevel.h> gboolean dbus_utils_message_iter_append_file_info (DBusMessageIter *iter, const MateVFSFileInfo *info); gboolean dbus_utils_message_append_file_info (DBusMessage *message, const MateVFSFileInfo *info); MateVFSFileInfo *dbus_utils_message_iter_get_file_info (DBusMessageIter *dict); GList * dbus_utils_message_get_file_info_list (DBusMessage *message); void dbus_utils_message_append_volume_list (DBusMessage *message, GList *volumes); void dbus_utils_message_append_drive_list (DBusMessage *message, GList *drives); void dbus_utils_message_append_volume (DBusMessage *message, MateVFSVolume *volume); void dbus_utils_message_append_drive (DBusMessage *message, MateVFSDrive *drive); void dbus_util_reply_result (DBusConnection *conn, DBusMessage *message, MateVFSResult result); void dbus_util_reply_id (DBusConnection *conn, DBusMessage *message, gint32 id); void dbus_util_start_track_name (DBusConnection *conn, const char *name); void dbus_util_stop_track_name (DBusConnection *conn, const char *name); #endif /* __DBUS_UTILS_H__ */
mate-desktop/mate-vfs
daemon/dbus-utils.h
C
gpl-2.0
2,585
SET client_encoding TO 'UTF8'; SET search_path = :"alkis_schema", :"parent_schema", :"postgis_schema", public; -- -- Moor (43005) -- SELECT 'Moor wird verarbeitet.'; -- Moor, Flächen INSERT INTO po_polygons(gml_id,thema,layer,polygon,signaturnummer,modell) SELECT gml_id, 'Vegetation' AS thema, 'ax_moor' AS layer, st_multi(wkb_geometry) AS polygon, 25171404 AS signaturnummer, advstandardmodell||sonstigesmodell FROM ax_moor WHERE endet IS NULL; -- Moor, Symbole INSERT INTO po_points(gml_id,thema,layer,point,drehwinkel,signaturnummer,modell) SELECT o.gml_id, 'Vegetation' AS thema, 'ax_moor' AS layer, st_multi(coalesce(p.wkb_geometry,alkis_flaechenfuellung(o.wkb_geometry,d.positionierungsregel),st_centroid(o.wkb_geometry))) AS point, coalesce(p.drehwinkel,0) AS drehwinkel, coalesce(d.signaturnummer,p.signaturnummer,'3476') AS signaturnummer, coalesce( p.advstandardmodell||p.sonstigesmodell||d.advstandardmodell||d.sonstigesmodell, o.advstandardmodell||o.sonstigesmodell ) AS modell FROM ax_moor o LEFT OUTER JOIN ap_ppo p ON ARRAY[o.gml_id] <@ p.dientzurdarstellungvon AND p.art='Moor' AND p.endet IS NULL LEFT OUTER JOIN ap_darstellung d ON ARRAY[o.gml_id] <@ d.dientzurdarstellungvon AND d.art='Moor' AND d.endet IS NULL WHERE o.endet IS NULL; -- Moor, Namen INSERT INTO po_labels(gml_id,thema,layer,point,text,signaturnummer,drehwinkel,horizontaleausrichtung,vertikaleausrichtung,skalierung,fontsperrung,modell) SELECT gml_id, 'Vegetation' AS thema, 'ax_moor' AS layer, point, text, signaturnummer, drehwinkel,horizontaleausrichtung,vertikaleausrichtung,skalierung,fontsperrung,modell FROM ( SELECT o.gml_id, coalesce(t.wkb_geometry,st_centroid(o.wkb_geometry)) AS point, coalesce(t.schriftinhalt,o.name) AS text, coalesce(d.signaturnummer,t.signaturnummer,'4209') AS signaturnummer, drehwinkel,horizontaleausrichtung,vertikaleausrichtung,skalierung,fontsperrung, coalesce(t.advstandardmodell||t.sonstigesmodell,o.advstandardmodell||o.sonstigesmodell) AS modell FROM ax_moor o LEFT OUTER JOIN ap_pto t ON ARRAY[o.gml_id] <@ t.dientzurdarstellungvon AND t.art='NAM' AND t.endet IS NULL LEFT OUTER JOIN ap_darstellung d ON ARRAY[o.gml_id] <@ d.dientzurdarstellungvon AND d.art='NAM' AND d.endet IS NULL WHERE o.endet IS NULL AND NOT name IS NULL ) AS n;
norBIT/alkisimport
postprocessing.d/1_ableitungsregeln/43005.sql
SQL
gpl-2.0
2,312
<!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_03) on Sun Nov 18 03:31:48 CST 2012 --> <title>I-Index</title> <meta name="date" content="2012-11-18"> <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="I-Index"; } //--> </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="../se350/afifsohaili/sudoku/package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li><a href="../se350/afifsohaili/sudoku/package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-4.html">Prev Letter</a></li> <li><a href="index-6.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-filesindex-5.html" target="_top">Frames</a></li> <li><a href="index-5.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="contentContainer"><a href="index-1.html">C</a>&nbsp;<a href="index-2.html">D</a>&nbsp;<a href="index-3.html">E</a>&nbsp;<a href="index-4.html">G</a>&nbsp;<a href="index-5.html">I</a>&nbsp;<a href="index-6.html">M</a>&nbsp;<a href="index-7.html">N</a>&nbsp;<a href="index-8.html">R</a>&nbsp;<a href="index-9.html">S</a>&nbsp;<a href="index-10.html">U</a>&nbsp;<a name="_I_"> <!-- --> </a> <h2 class="title">I</h2> <dl> <dt><span class="strong"><a href="../se350/afifsohaili/sudoku/SudokuGrid.html#init()">init()</a></span> - Method in class se350.afifsohaili.sudoku.<a href="../se350/afifsohaili/sudoku/SudokuGrid.html" title="class in se350.afifsohaili.sudoku">SudokuGrid</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../se350/afifsohaili/sudoku/SudokuMechanics.html#input(java.lang.String...)">input(String...)</a></span> - Method in class se350.afifsohaili.sudoku.<a href="../se350/afifsohaili/sudoku/SudokuMechanics.html" title="class in se350.afifsohaili.sudoku">SudokuMechanics</a></dt> <dd>&nbsp;</dd> </dl> <a href="index-1.html">C</a>&nbsp;<a href="index-2.html">D</a>&nbsp;<a href="index-3.html">E</a>&nbsp;<a href="index-4.html">G</a>&nbsp;<a href="index-5.html">I</a>&nbsp;<a href="index-6.html">M</a>&nbsp;<a href="index-7.html">N</a>&nbsp;<a href="index-8.html">R</a>&nbsp;<a href="index-9.html">S</a>&nbsp;<a href="index-10.html">U</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../se350/afifsohaili/sudoku/package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li><a href="../se350/afifsohaili/sudoku/package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-4.html">Prev Letter</a></li> <li><a href="index-6.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-filesindex-5.html" target="_top">Frames</a></li> <li><a href="index-5.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
afifsohaili/gameframework
Sudoku/doc/index-files/index-5.html
HTML
gpl-2.0
4,906
<?php get_header(); ?> <?php //////////////////////////////////////////////////////////////////////////////// // INTRO (category info) //////////////////////////////////////////////////////////////////////////////// ?> <div id="intro_wrapper"> <div class="intro_page"> <h2><?php echo $post->post_title; ?></h2> <div class="page_meta_box"><?php echo htmlspecialchars_decode(stripslashes(get_post_meta($post->ID, 'Description', true))); ?></div> </div><!-- END "div.intro_home" --> </div><!-- END "div#intro_wrapper" --> <?php //////////////////////////////////////////////////////////////////////////////// // END INTRO //////////////////////////////////////////////////////////////////////////////// ?> <?php //////////////////////////////////////////////////////////////////////////////// // CONTENT WRAPPER //////////////////////////////////////////////////////////////////////////////// ?> <div id="content_wrapper"> <div class="content_shadow_right"> <div id="content" class="content_page"> <?php // >>>>>>>>>>>>>>>>> WIDGET SIDEBARS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> include 'sidebar.php'; // external link to showtime sidebar processor // <<<<<<<<<<<<<<<<< END WIDGETS SIDEBARS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ?> <div id="page" class="page_template_blog"> <?php //////////////////////////////////////////////////////////////////////////////// // POST START //////////////////////////////////////////////////////////////////////////////// if ( $wp_query->have_posts()) : while (have_posts()) : the_post(); ?> <div class="entry" id="post-<?php the_ID();?>"> <?php the_content(); ?> </div><!-- END "div.entry" --> <?php if ( comments_open() ) comments_template(); ?> <?php endwhile; endif; ?> <?php //////////////////////////////////////////////////////////////////////////////// // POST END //////////////////////////////////////////////////////////////////////////////// ?> </div><!-- END "div#page" --> <div class="clear"></div> </div><!-- END "div#content" --> </div><!-- END "div.content_shadow_right" --> </div><!-- END "div#content_wrapper" --> <?php //////////////////////////////////////////////////////////////////////////////// // END CONTENT WRAPPER //////////////////////////////////////////////////////////////////////////////// ?> <?php get_footer(); ?>
jonthewayne/FanActions
wp-content/themes/showtime/page.php
PHP
gpl-2.0
2,470
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html class Mycar168Pipeline(object): def process_item(self, item, spider): return item
yzhuan/car
crawler/mycar168/mycar168/pipelines.py
Python
gpl-2.0
262
<script language="JavaScript"> /* code modified from ColdFusion's cfdump code */ function dBug_toggleRow(source) { var target = (document.all) ? source.parentElement.cells[1] : source.parentNode.lastChild; dBug_toggleTarget(target,dBug_toggleSource(source)); } function dBug_toggleSource(source) { if (source.style.fontStyle=='italic') { source.style.fontStyle='normal'; source.title='click to collapse'; return 'open'; } else { source.style.fontStyle='italic'; source.title='click to expand'; return 'closed'; } } function dBug_toggleTarget(target,switchToState) { target.style.display = (switchToState=='open') ? '' : 'none'; } function dBug_toggleTable(source) { var switchToState=dBug_toggleSource(source); if(document.all) { var table=source.parentElement.parentElement; for(var i=1;i<table.rows.length;i++) { target=table.rows[i]; dBug_toggleTarget(target,switchToState); } } else { var table=source.parentNode.parentNode; for (var i=1;i<table.childNodes.length;i++) { target=table.childNodes[i]; if(target.style) { dBug_toggleTarget(target,switchToState); } } } } </script> <style type="text/css"> pre{font-family:12px Arial;white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-o-pre-wrap;white-space:-pre-wrap;word-wrap:break-word} table.dBug_arrayNew,table.dBug_arrayOld,table.dBug_array,table.dBug_object,table.dBug_resource,table.dBug_resourceC,table.dBug_xml { font-family:Verdana, Arial, Helvetica, sans-serif; color:#000000; font-size:12px; } .dBug_arrayHeader, .dBug_arrayNewHeader, .dBug_arrayOldHeader, .dBug_objectHeader, .dBug_resourceHeader, .dBug_resourceCHeader, .dBug_xmlHeader { font-weight:bold; color:#FFFFFF; cursor:pointer; } .dBug_arrayKey, .dBug_arrayNewKey, .dBug_arrayOldKey, .dBug_objectKey, .dBug_xmlKey { cursor:pointer; } /* array */ table.dBug_array { background-color:#888888;position:relative;z-index:1000} table.dBug_arrayNew { background-color:#888888;} table.dBug_arrayOld { background-color:darkgray; } table.dBug_array td { background-color:#FFFFFF; } table.dBug_array td.dBug_arrayHeader { background-color:#AAAAAA;color:white;} table.dBug_array td.dBug_arrayNewHeader{ background-color:#cfc;color:green; } table.dBug_array td.dBug_arrayOldHeader{ background-color:lightgray;color:gray; } table.dBug_array td.dBug_arrayKey { background-color:#DDDDDD; } table.dBug_array td.dBug_arrayNewKey { background-color:#cfc;color:green; } table.dBug_array td.dBug_arrayOldKey { background-color:lightgray;color:gray; } table.dBug_array td.dBug_arrayNewKeyBody { color:green;padding:1px; } table.dBug_array td.dBug_arrayOldKeyBody { color:#808080; } table.dBug_arrayBug { background-color:#884488 } table.dBug_array td.dBug_arrayBugHeader{ background-color:#AA66AA;color:white; } table.dBug_array td.dBug_arrayBugKey { background-color:#FFDDFF;color:black; } table.dBug_array td.dBug_arrayBugKeyBody { color:black;padding:1px; } /* object */ table.dBug_object { background-color:#0000CC; } table.dBug_object td { background-color:#FFFFFF; } table.dBug_object td.dBug_objectHeader { background-color:#4444CC; } table.dBug_object td.dBug_objectKey { background-color:#CCDDFF; } /* resource */ table.dBug_resourceC { background-color:#884488; } table.dBug_resourceC td { background-color:#FFFFFF; } table.dBug_resourceC td.dBug_resourceCHeader { background-color:#AA66AA; } table.dBug_resourceC td.dBug_resourceCKey { background-color:#FFDDFF; } /* resource */ table.dBug_resource { background-color:#884488; } table.dBug_resource td { background-color:#FFFFFF; } table.dBug_resource td.dBug_resourceHeader { background-color:#AA66AA; } table.dBug_resource td.dBug_resourceKey { background-color:#FFDDFF; } /* xml */ table.dBug_xml { background-color:#888888; } table.dBug_xml td { background-color:#FFFFFF; } table.dBug_xml td.dBug_xmlHeader { background-color:#AAAAAA; } table.dBug_xml td.dBug_xmlKey { background-color:#DDDDDD; } </style><table cellspacing=2 cellpadding=3 class="dBug_array"><tr><td class="dBug_arrayHeader" colspan=2 onClick='dBug_toggleTable(this)'>#$var (Array)</td> </tr><tr> <td valign="top" onClick='dBug_toggleRow(this)' class="dBug_arrayKey">LoadController</td> <td class="dBug_arrayKeyBody">hello</td></tr> <tr> <td valign="top" onClick='dBug_toggleRow(this)' class="dBug_arrayKey">LoadMethod</td> <td class="dBug_arrayKeyBody">default</td></tr> <tr> <td valign="top" onClick='dBug_toggleRow(this)' class="dBug_arrayKey">ajax</td> <td class="dBug_arrayKeyBody">True</td></tr> <tr> <td valign="top" onClick='dBug_toggleRow(this)' class="dBug_arrayKey">param</td> <td class="dBug_arrayKeyBody"><table cellspacing=2 cellpadding=3 class="dBug_array"><tr> <td valign="top" onClick='dBug_toggleRow(this)' class="dBug_arrayKey">default</td> <td class="dBug_arrayKeyBody"><table cellspacing=2 cellpadding=3 class="dBug_array"><tr> <td valign="top" onClick='dBug_toggleRow(this)' class="dBug_arrayKey">ModelsErrors_getError</td> <td class="dBug_arrayKeyBody"><table cellspacing=2 cellpadding=3 class="dBug_array"><tr> <td valign="top" onClick='dBug_toggleRow(this)' class="dBug_arrayKey">info</td> <td class="dBug_arrayKeyBody"><table cellspacing=2 cellpadding=3 class="dBug_arrayOld"><tr> <td valign="top" onClick='dBug_toggleRow(this)' class="dBug_arrayOldKey"></td> <td class="dBug_arrayOldKeyBody">ModelsHelloWorld->setThrowNewException throw new Exception('')</td></tr> <tr> <td valign="top" onClick='dBug_toggleRow(this)' class="dBug_arrayNewKey"></td> <td class="dBug_arrayNewKeyBody">alternative_way_of_setting_errors</td></tr> </table></td></tr> </table></td></tr> </table></td></tr> </table></td></tr> <tr> <td valign="top" onClick='dBug_toggleRow(this)' class="dBug_arrayKey">ModelsHelloWorld_setThrowNewException</td> <td class="dBug_arrayKeyBody"><table cellspacing=2 cellpadding=3 class="dBug_array"><tr> <td valign="top" onClick='dBug_toggleRow(this)' class="dBug_arrayKey">ModelsHelloWorld->setThrowNewException throw new Exception('')</td> <td class="dBug_arrayKeyBody">ModelsHelloWorld->setThrowNewException throw new Exception('')</td></tr> </table></td></tr> <tr> <td valign="top" onClick='dBug_toggleRow(this)' class="dBug_arrayKey">ModelsErrors_getError</td> <td class="dBug_arrayKeyBody"><table cellspacing=2 cellpadding=3 class="dBug_array"><tr> <td valign="top" onClick='dBug_toggleRow(this)' class="dBug_arrayKey">ModelsHelloWorld->setThrowNewException throw new Exception('')</td> <td class="dBug_arrayKeyBody">ModelsHelloWorld->setThrowNewException throw new Exception('')</td></tr> <tr> <td valign="top" onClick='dBug_toggleRow(this)' class="dBug_arrayKey">alternative_way_of_setting_errors</td> <td class="dBug_arrayKeyBody">ModelsErrors->errors_array['alternative_way_of_setting_errors']=description or array key</td></tr> </table></td></tr> </table>
ev9eniy/evnine
evnine-lesson-04-Validation-Errors-ExceptionThrow/ModelsMSGExceptionThrowError/index_output.html
HTML
gpl-2.0
7,369
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <wctype.h> #include <wchar.h> #include <string.h> #include <locale.h> #include "uli_list.h" #include "W_Word.h" #include "words_list.h" #include "hash_table.h" int check_for_close_positions(UnsgLongIntList* list1,UnsgLongIntList* list2,int range) { unsigned long int loop_value; int found; UnsgLongIntCell* loop_cell1,*loop_cell2; found = 0; loop_cell1 = getCell_UnsgLongIntList(list1,0); while(loop_cell1 != NULL) { loop_value = getValue_UnsgLongIntCell(loop_cell1); if(getIndexOf_UnsgLongIntList(list2,loop_value + range,1) != -1) { return 1; } loop_cell1 = getNextCell_UnsgLongIntCell(loop_cell1); } return 0; } char** check_for_close_word(W_Word* word1,W_Word** words_vector,int words_vector_length,int space,int is_position_restrictive,int* files_result_count) { TextReference* loop_ref; UnsgLongIntList* loop_ulist,*loop_ulist2; UnsgLongIntCell* loop_ucell; char** result_files; long int reference_count; int i,c,found_words_count,close_found_words_count,check,str_len; unsigned long int loop_pos_value; char* loop_filename; found_words_count = 0; close_found_words_count = 0; reference_count = getReferenceCount_W_Word(word1); result_files = (char**) malloc(sizeof(char*)*(reference_count)); loop_ref = getReference_W_Word(word1,0); c = 0; while(loop_ref != NULL) { loop_filename = getFileName_TextReference(loop_ref); loop_ulist = getWordPosition_TextReference(loop_ref); //wprintf(L"FILE NAME: %s\n",loop_filename); for(i=0;i<words_vector_length;i++) { //print_W_Word(words_vector[i]); //wprintf(L"\n"); loop_ulist2 = getPositionsByFile_W_Word(words_vector[i],loop_filename,1); if(loop_ulist2 != NULL && loop_ulist != NULL) { //report_UnsgLongIntList(loop_ulist2); // wprintf(L"\n"); found_words_count++; if(is_position_restrictive == 1) { check = check_for_close_positions(loop_ulist,loop_ulist2,i * space); if(check == 1) { close_found_words_count += check; } else { break; } } } else { break; } } //wprintf(L"|||%d:%d\n",found_words_count,reference_count); if((is_position_restrictive == 1 && close_found_words_count == words_vector_length) || (is_position_restrictive == 0 && found_words_count == words_vector_length)) { str_len = strlen(loop_filename); result_files[c] = (char*) malloc(sizeof(char)*(str_len+1)); strncpy(result_files[c],loop_filename,str_len+1); c++; } found_words_count = 0; close_found_words_count = 0; loop_ref = getNext_TextReference(loop_ref); } *files_result_count = c; return result_files; } W_Word** retrive_references_hash_search(HashTable* hash_table,WordsList* query_words,int* number_words_found,W_Word* (*search)(HashTable*,wchar_t*)) { W_Word** found_words; WordsListCell* loop_cell; W_Word* loop_word,*found_word; int i,query_words_length; long int *text_pos_index; query_words_length = get_length_WordsList(query_words); found_words = (W_Word**) malloc(sizeof(W_Word*)*query_words_length); i = 0; // wprintf(L"saçdkhaljsd"); // wprintf(L":||%ld\n",query_words_length); loop_cell = getCell_WordsList(query_words,0); while(loop_cell != NULL && i < query_words_length) { loop_word = getWord_WordsListCell(loop_cell); // wprintf(L"%ls\n",get_str_W_Word(loop_word)); found_words[i] = (*search)(hash_table,get_str_W_Word(loop_word)); if(found_words[i] == NULL) { *number_words_found = 0; free(found_words); return NULL; } loop_cell = getNextCell_WordsListCell(loop_cell); i++; } *number_words_found = i; return found_words; } char** hash_search(HashTable* hash_table,WordsList* query_words,int position_restrictive_flag,int search_type,int* number_results) { W_Word** found_words = NULL; char** files_found = NULL; int files_found_count; int i,number_words_found; number_words_found = 0; switch(search_type) { case 0: found_words = retrive_references_hash_search(hash_table,query_words,&number_words_found,listSearchW_Word_HashTable); break; case 1: found_words = retrive_references_hash_search(hash_table,query_words,&number_words_found,linearSearchW_Word_HashTable); break; case 2: found_words = retrive_references_hash_search(hash_table,query_words,&number_words_found,doubleSearchW_Word_HashTable); break; } if(number_words_found > 0) { files_found_count = 0; files_found = NULL; files_found = check_for_close_word(found_words[0],found_words,number_words_found,1,position_restrictive_flag,&number_words_found); *number_results = number_words_found; } if(found_words != NULL) free(found_words); return files_found; }
willilucas/Search_Machine
hash_search.c
C
gpl-2.0
4,671
<?php require_once(__DIR__ . "/../../server/tools.php"); require_once(__DIR__ . "/../../server/auth/Config.php"); $config =Config::getInstance(); ?> <table id="finales_equipos-datagrid"> <thead> <tr> <th colspan="3"> <span class="main_theader"><?php _e('Team data'); ?></span></th> <th colspan="2"> <span class="main_theader" id="finales_equipos_roundname_m1"><?php _e('Round'); ?> 1</span></th> <th colspan="2"> <span class="main_theader" id="finales_equipos_roundname_m2"><?php _e('Round'); ?> 2</span></th> <th colspan="2"> <span class="main_theader"><?php _e('Final scores'); ?></span></th> </tr> <tr> <!-- <th data-options="field:'ID', hidden:true"></th> <th data-options="field:'Prueba', hidden:true"></th> <th data-options="field:'Jornada', hidden:true"></th> --> <th data-options="field:'Logo', width:'19%', sortable:false, formatter:formatTeamLogos">&nbsp</th> <th data-options="field:'Nombre', width:'20.5%', sortable:false, formatter:formatBold"><?php _e('Team'); ?></th> <th data-options="field:'Categorias', width:'4%', sortable:false, formatter:formatCategoria"><?php _e('Cat'); ?></th> <th data-options="field:'T1', align:'center', width:'9.5%', sortable:false"><?php _e('Time'); ?> 1</th> <th data-options="field:'P1', align:'center',width:'10%', sortable:false"><?php _e('Penal'); ?> 1</th> <th data-options="field:'T2', align:'center',width:'9.5%', sortable:false"><?php _e('Time'); ?> 2</th> <th data-options="field:'P2', align:'center',width:'10%', sortable:false"><?php _e('Penal'); ?> 2</th> <th data-options="field:'Tiempo', align:'center',width:'8.5%', sortable:false,formatter:formatBold"><?php _e('Time'); ?></th> <th data-options="field:'Penalizacion', align:'center',width:'9%', sortable:false,formatter:formatBold"><?php _e('Penalization'); ?></th> </tr> </thead> </table> <script type="text/javascript"> $('#finales_equipos-datagrid').datagrid({ expandCount: 0, // propiedades del panel asociado fit: false, // do not set to true to take care on extra elements in panel border: false, closable: false, collapsible: false, collapsed: false, // no tenemos metodo get ni parametros: directamente cargamos desde el datagrid loadMsg: "<?php _e('Updating final scores');?>...", // propiedades del datagrid width:'99%', height:1080, // enought big to assure overflow pagination: false, rownumbers: true, fitColumns: true, singleSelect: true, rowStyler:myRowStyler, autoRowHeight: false, idField: 'ID', pageSize: 1000, // enought bit to make it senseless // columns declared at html section to show additional headers // especificamos un formateador especial para desplegar la tabla de perros por equipos view:detailview, detailFormatter:function(idx,row){ var dgname="finales_equipos-datagrid-"+parseInt(row.ID); return '<div style="padding:2px"><table id="'+dgname+'"></table></div>'; }, onExpandRow: function(idx,row) { $(this).datagrid('options').expandCount++; showFinalScoresByTeam("#finales_equipos-datagrid",idx,row); }, onCollapseRow: function(idx,row) { $(this).datagrid('options').expandCount--; var dg="#finales_equipos-datagrid-" + parseInt(row.ID); $(dg).remove(); } }); </script>
nedy13/AgilityContest
agility/lib/templates/final_teams.inc.php
PHP
gpl-2.0
3,639
/** * @file ProjectFilePathsDlg.h * * @brief Declaration file for ProjectFilePathsDlg dialog */ // RCS ID line follows -- this is updated by CVS // $Id: ProjectFilePathsDlg.h 3375 2006-07-19 11:58:51Z kimmov $ #ifndef _PROJECTFILEPATHSDLG_H_ #define _PROJECTFILEPATHSDLG_H_ /** * @brief Dialog allowing user to load, edit and save project files. */ class ProjectFilePathsDlg : public CPropertyPage { DECLARE_DYNCREATE(ProjectFilePathsDlg) public: ProjectFilePathsDlg(); // standard constructor CString GetFilePath(); // Dialog Data //{{AFX_DATA(SaveClosingDlg) enum { IDD = IDD_PROJFILES_PATHS }; CString m_sLeftFile; CString m_sRightFile; CString m_sFilter; BOOL m_bIncludeSubfolders; BOOL m_bLeftPathReadOnly; BOOL m_bRightPathReadOnly; //}}AFX_DATA protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Generated message map functions //{{AFX_MSG(ProjectFilePathsDlg) afx_msg BOOL OnInitDialog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() CString AskProjectFileName(BOOL bOpen); // Implementation data private: CString m_sProjFilePath; /**< (Last/current) Path for project file */ public: void SetPaths(LPCTSTR left, LPCTSTR right); afx_msg void OnBnClickedProjLfileBrowse(); afx_msg void OnBnClickedProjRfileBrowse(); afx_msg void OnBnClickedProjFilterSelect(); afx_msg void OnBnClickedProjOpen(); afx_msg void OnBnClickedProjSave(); }; #endif // _PROJECTFILEPATHSDLG_H_
thistleknot/winmerge-2-14
ProjectFilePathsDlg.h
C
gpl-2.0
1,446
''' mysql> desc problem; +-------------+---------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+---------------+------+-----+---------+----------------+ | pid | int(11) | NO | PRI | NULL | auto_increment | | title | varchar(255) | YES | | NULL | | | source | varchar(255) | YES | | NULL | | | url | varchar(1024) | YES | | NULL | | | originOJ | varchar(255) | YES | | NULL | | | originProb | varchar(45) | YES | | NULL | | | memorylimit | varchar(45) | YES | | NULL | | | timelimit | varchar(45) | YES | | NULL | | +-------------+---------------+------+-----+---------+----------------+ mysql> desc problemdetail; +--------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+--------------+------+-----+---------+----------------+ | did | int(11) | NO | PRI | NULL | auto_increment | | pid | int(11) | YES | MUL | NULL | | | description | text | YES | | NULL | | | input | text | YES | | NULL | | | output | text | YES | | NULL | | | sampleinput | text | YES | | NULL | | | sampleoutput | text | YES | | NULL | | | hint | text | YES | | NULL | | | author | varchar(255) | YES | | NULL | | | source | varchar(255) | YES | | NULL | | | updateTime | datetime | YES | | NULL | | +--------------+--------------+------+-----+---------+----------------+ ''' import pickle import time from tools.encode import Base64StrToUTF8Str, UTF8StrToBase64Str from tools.dbcore import ConnPool from tools.dbtools import getQuerySQL,getInserSQL, getUpdateSQL,FetchAll,FetchOne,ExeSQL def GetProblemID(orj, orid): sql = 'SELECT problem.pid FROM problem WHERE ' \ '( problem.originOJ LIKE "{}" AND problem.originProb LIKE "{}" )'.format(orj, orid) conn = ConnPool.connect() cur = conn.cursor() cur.execute(sql) tp = cur.fetchall() cur.close() conn.close() if tp.__len__() == 0: return 0 else: return tp[0][0] def pretreat_Problem(problem): pass ''' if 'source' in problem : problem['source'] = UTF8StrToBase64Str(problem['source']) ''' def InsertProblem(problem): pretreat_Problem(problem) sql = getInserSQL('problem', problem) ExeSQL(sql) def UpdateProblem(problem, pid): pretreat_Problem(problem) cluse = 'pid = {}'.format(pid) sql = getUpdateSQL('problem', data=problem, clause=cluse) #print('Update',sql) ExeSQL(sql) def pretreat_ProblemDetail(problem): baselist = ['description', 'input', 'output', 'sampleinput', 'sampleoutput', 'hint', 'author', 'source'] for key in problem: if problem[key] is None: continue if key in baselist: problem[key] = UTF8StrToBase64Str(problem[key]) def InsertProblemDetail(problem): pretreat_ProblemDetail(problem) sql = getInserSQL('problemdetail', problem) ExeSQL(sql) def UpdateProblemDetail(problem, pid): pretreat_ProblemDetail(problem) sql = getQuerySQL('problemdetail',' pid={} '.format(pid),' did ') rs = FetchOne(sql) if rs is None : InsertProblemDetail(problem) else : clause = 'problemdetail.pid = %d' % pid sql = getUpdateSQL('problemdetail', data=problem, clause=clause) ExeSQL(sql) problem = dict( title=None, source=None, url=None, originOJ=None, originProb=None, virtualOJ=None, virtualProb=None, ) problemdetail = dict( pid=None, description=None, input=None, output=None, sampleinput=None, sampleoutput=None, hint=None, author=None, source=None, updatetime=None, memorylimit=None, timelimit=None, specialjudge=False, ) def InsertOrUpdateProblem(kwargs): pd = problem.copy() pdd = problemdetail.copy() for key in kwargs: if key in pd: pd[key] = kwargs[key] if key in pdd: pdd[key] = kwargs[key] pid = GetProblemID(pd['originOJ'], pd['originProb']) print('pid ---> ',pid) if pid == 0: # Insert problem table InsertProblem(pd) pid = GetProblemID(pd['originOJ'], pd['originProb']) pdd['pid'] = pid # Insert problemDetail title InsertProblemDetail(pdd) else: pdd['pid'] = pid # Update problem table print('Update problem table') UpdateProblem(pd, pid) # Update problemDetail table print('Update problemDetail table') UpdateProblemDetail(pdd, pid) ''' print('-'*30) print(pd) print('-'*30) print(pdd) print('-'*30) ''' def test1(): print(time.strftime('%Y-%m-%d %H:%M:%S')) def main(): f = open('/home/ckboss/Desktop/Development/testData/POJ/POJ_4050.pkl', 'rb') data = pickle.load(f) data['updatetime'] = time.strftime('%Y-%m-%d %H:%M:%S') InsertOrUpdateProblem(data) ''' f = open('/tmp/HDOJ5011.pkl','rb') data = pickle.load(f) InsertOrUpdateProblem(data) ''' if __name__ == '__main__': #main() test1()
CKboss/VirtualJudgePY
dao/problemdao.py
Python
gpl-2.0
5,683
<html lang="en"> <head> <title>Functions for C++ - GNU Compiler Collection (GCC) Internals</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="GNU Compiler Collection (GCC) Internals"> <meta name="generator" content="makeinfo 4.8"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="C-and-C_002b_002b-Trees.html#C-and-C_002b_002b-Trees" title="C and C++ Trees"> <link rel="prev" href="Classes.html#Classes" title="Classes"> <link rel="next" href="Statements-for-C_002b_002b.html#Statements-for-C_002b_002b" title="Statements for C++"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- Copyright (C) 1988-2017 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being ``Funding Free Software'', the Front-Cover Texts being (a) (see below), and with the Back-Cover Texts being (b) (see below). A copy of the license is included in the section entitled ``GNU Free Documentation License''. (a) The FSF's Front-Cover Text is: A GNU Manual (b) The FSF's Back-Cover Text is: You have freedom to copy and modify this GNU Manual, like GNU software. Copies published by the Free Software Foundation raise funds for GNU development.--> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> </head> <body> <div class="node"> <p> <a name="Functions-for-C++"></a> <a name="Functions-for-C_002b_002b"></a> Next:&nbsp;<a rel="next" accesskey="n" href="Statements-for-C_002b_002b.html#Statements-for-C_002b_002b">Statements for C++</a>, Previous:&nbsp;<a rel="previous" accesskey="p" href="Classes.html#Classes">Classes</a>, Up:&nbsp;<a rel="up" accesskey="u" href="C-and-C_002b_002b-Trees.html#C-and-C_002b_002b-Trees">C and C++ Trees</a> <hr> </div> <h4 class="subsection">10.10.4 Functions for C++</h4> <p><a name="index-function-2060"></a><a name="index-FUNCTION_005fDECL-2061"></a><a name="index-OVERLOAD-2062"></a><a name="index-OVL_005fCURRENT-2063"></a><a name="index-OVL_005fNEXT-2064"></a> A function is represented by a <code>FUNCTION_DECL</code> node. A set of overloaded functions is sometimes represented by an <code>OVERLOAD</code> node. <p>An <code>OVERLOAD</code> node is not a declaration, so none of the `<samp><span class="samp">DECL_</span></samp>' macros should be used on an <code>OVERLOAD</code>. An <code>OVERLOAD</code> node is similar to a <code>TREE_LIST</code>. Use <code>OVL_CURRENT</code> to get the function associated with an <code>OVERLOAD</code> node; use <code>OVL_NEXT</code> to get the next <code>OVERLOAD</code> node in the list of overloaded functions. The macros <code>OVL_CURRENT</code> and <code>OVL_NEXT</code> are actually polymorphic; you can use them to work with <code>FUNCTION_DECL</code> nodes as well as with overloads. In the case of a <code>FUNCTION_DECL</code>, <code>OVL_CURRENT</code> will always return the function itself, and <code>OVL_NEXT</code> will always be <code>NULL_TREE</code>. <p>To determine the scope of a function, you can use the <code>DECL_CONTEXT</code> macro. This macro will return the class (either a <code>RECORD_TYPE</code> or a <code>UNION_TYPE</code>) or namespace (a <code>NAMESPACE_DECL</code>) of which the function is a member. For a virtual function, this macro returns the class in which the function was actually defined, not the base class in which the virtual declaration occurred. <p>If a friend function is defined in a class scope, the <code>DECL_FRIEND_CONTEXT</code> macro can be used to determine the class in which it was defined. For example, in <pre class="smallexample"> class C { friend void f() {} }; </pre> <p class="noindent">the <code>DECL_CONTEXT</code> for <code>f</code> will be the <code>global_namespace</code>, but the <code>DECL_FRIEND_CONTEXT</code> will be the <code>RECORD_TYPE</code> for <code>C</code>. <p>The following macros and functions can be used on a <code>FUNCTION_DECL</code>: <dl> <dt><code>DECL_MAIN_P</code><a name="index-DECL_005fMAIN_005fP-2065"></a><dd>This predicate holds for a function that is the program entry point <code>::code</code>. <br><dt><code>DECL_LOCAL_FUNCTION_P</code><a name="index-DECL_005fLOCAL_005fFUNCTION_005fP-2066"></a><dd>This predicate holds if the function was declared at block scope, even though it has a global scope. <br><dt><code>DECL_ANTICIPATED</code><a name="index-DECL_005fANTICIPATED-2067"></a><dd>This predicate holds if the function is a built-in function but its prototype is not yet explicitly declared. <br><dt><code>DECL_EXTERN_C_FUNCTION_P</code><a name="index-DECL_005fEXTERN_005fC_005fFUNCTION_005fP-2068"></a><dd>This predicate holds if the function is declared as an `<code>extern "C"</code>' function. <br><dt><code>DECL_LINKONCE_P</code><a name="index-DECL_005fLINKONCE_005fP-2069"></a><dd>This macro holds if multiple copies of this function may be emitted in various translation units. It is the responsibility of the linker to merge the various copies. Template instantiations are the most common example of functions for which <code>DECL_LINKONCE_P</code> holds; G++ instantiates needed templates in all translation units which require them, and then relies on the linker to remove duplicate instantiations. <p>FIXME: This macro is not yet implemented. <br><dt><code>DECL_FUNCTION_MEMBER_P</code><a name="index-DECL_005fFUNCTION_005fMEMBER_005fP-2070"></a><dd>This macro holds if the function is a member of a class, rather than a member of a namespace. <br><dt><code>DECL_STATIC_FUNCTION_P</code><a name="index-DECL_005fSTATIC_005fFUNCTION_005fP-2071"></a><dd>This predicate holds if the function a static member function. <br><dt><code>DECL_NONSTATIC_MEMBER_FUNCTION_P</code><a name="index-DECL_005fNONSTATIC_005fMEMBER_005fFUNCTION_005fP-2072"></a><dd>This macro holds for a non-static member function. <br><dt><code>DECL_CONST_MEMFUNC_P</code><a name="index-DECL_005fCONST_005fMEMFUNC_005fP-2073"></a><dd>This predicate holds for a <code>const</code>-member function. <br><dt><code>DECL_VOLATILE_MEMFUNC_P</code><a name="index-DECL_005fVOLATILE_005fMEMFUNC_005fP-2074"></a><dd>This predicate holds for a <code>volatile</code>-member function. <br><dt><code>DECL_CONSTRUCTOR_P</code><a name="index-DECL_005fCONSTRUCTOR_005fP-2075"></a><dd>This macro holds if the function is a constructor. <br><dt><code>DECL_NONCONVERTING_P</code><a name="index-DECL_005fNONCONVERTING_005fP-2076"></a><dd>This predicate holds if the constructor is a non-converting constructor. <br><dt><code>DECL_COMPLETE_CONSTRUCTOR_P</code><a name="index-DECL_005fCOMPLETE_005fCONSTRUCTOR_005fP-2077"></a><dd>This predicate holds for a function which is a constructor for an object of a complete type. <br><dt><code>DECL_BASE_CONSTRUCTOR_P</code><a name="index-DECL_005fBASE_005fCONSTRUCTOR_005fP-2078"></a><dd>This predicate holds for a function which is a constructor for a base class sub-object. <br><dt><code>DECL_COPY_CONSTRUCTOR_P</code><a name="index-DECL_005fCOPY_005fCONSTRUCTOR_005fP-2079"></a><dd>This predicate holds for a function which is a copy-constructor. <br><dt><code>DECL_DESTRUCTOR_P</code><a name="index-DECL_005fDESTRUCTOR_005fP-2080"></a><dd>This macro holds if the function is a destructor. <br><dt><code>DECL_COMPLETE_DESTRUCTOR_P</code><a name="index-DECL_005fCOMPLETE_005fDESTRUCTOR_005fP-2081"></a><dd>This predicate holds if the function is the destructor for an object a complete type. <br><dt><code>DECL_OVERLOADED_OPERATOR_P</code><a name="index-DECL_005fOVERLOADED_005fOPERATOR_005fP-2082"></a><dd>This macro holds if the function is an overloaded operator. <br><dt><code>DECL_CONV_FN_P</code><a name="index-DECL_005fCONV_005fFN_005fP-2083"></a><dd>This macro holds if the function is a type-conversion operator. <br><dt><code>DECL_GLOBAL_CTOR_P</code><a name="index-DECL_005fGLOBAL_005fCTOR_005fP-2084"></a><dd>This predicate holds if the function is a file-scope initialization function. <br><dt><code>DECL_GLOBAL_DTOR_P</code><a name="index-DECL_005fGLOBAL_005fDTOR_005fP-2085"></a><dd>This predicate holds if the function is a file-scope finalization function. <br><dt><code>DECL_THUNK_P</code><a name="index-DECL_005fTHUNK_005fP-2086"></a><dd>This predicate holds if the function is a thunk. <p>These functions represent stub code that adjusts the <code>this</code> pointer and then jumps to another function. When the jumped-to function returns, control is transferred directly to the caller, without returning to the thunk. The first parameter to the thunk is always the <code>this</code> pointer; the thunk should add <code>THUNK_DELTA</code> to this value. (The <code>THUNK_DELTA</code> is an <code>int</code>, not an <code>INTEGER_CST</code>.) <p>Then, if <code>THUNK_VCALL_OFFSET</code> (an <code>INTEGER_CST</code>) is nonzero the adjusted <code>this</code> pointer must be adjusted again. The complete calculation is given by the following pseudo-code: <pre class="smallexample"> this += THUNK_DELTA if (THUNK_VCALL_OFFSET) this += (*((ptrdiff_t **) this))[THUNK_VCALL_OFFSET] </pre> <p>Finally, the thunk should jump to the location given by <code>DECL_INITIAL</code>; this will always be an expression for the address of a function. <br><dt><code>DECL_NON_THUNK_FUNCTION_P</code><a name="index-DECL_005fNON_005fTHUNK_005fFUNCTION_005fP-2087"></a><dd>This predicate holds if the function is <em>not</em> a thunk function. <br><dt><code>GLOBAL_INIT_PRIORITY</code><a name="index-GLOBAL_005fINIT_005fPRIORITY-2088"></a><dd>If either <code>DECL_GLOBAL_CTOR_P</code> or <code>DECL_GLOBAL_DTOR_P</code> holds, then this gives the initialization priority for the function. The linker will arrange that all functions for which <code>DECL_GLOBAL_CTOR_P</code> holds are run in increasing order of priority before <code>main</code> is called. When the program exits, all functions for which <code>DECL_GLOBAL_DTOR_P</code> holds are run in the reverse order. <br><dt><code>TYPE_RAISES_EXCEPTIONS</code><a name="index-TYPE_005fRAISES_005fEXCEPTIONS-2089"></a><dd>This macro returns the list of exceptions that a (member-)function can raise. The returned list, if non <code>NULL</code>, is comprised of nodes whose <code>TREE_VALUE</code> represents a type. <br><dt><code>TYPE_NOTHROW_P</code><a name="index-TYPE_005fNOTHROW_005fP-2090"></a><dd>This predicate holds when the exception-specification of its arguments is of the form `<code>()</code>'. <br><dt><code>DECL_ARRAY_DELETE_OPERATOR_P</code><a name="index-DECL_005fARRAY_005fDELETE_005fOPERATOR_005fP-2091"></a><dd>This predicate holds if the function an overloaded <code>operator delete[]</code>. </dl> <!-- --> <!-- Function Bodies --> <!-- --> </body></html>
jocelynmass/nrf51
toolchain/arm_cm0/share/doc/gcc-arm-none-eabi/html/gccint/Functions-for-C_002b_002b.html
HTML
gpl-2.0
11,607
/* * Generated by asn1c-0.9.22 (http://lionet.info/asn1c) * From ASN.1 module "PKIXCMP" * found in "lpa2.asn1" * `asn1c -S/skeletons` */ #ifndef _RevDetails_H_ #define _RevDetails_H_ #include <asn_application.h> /* Including external dependencies */ #include "CertTemplate.h" #include "ReasonFlags.h" #include <GeneralizedTime.h> #include <constr_SEQUENCE.h> #ifdef __cplusplus extern "C" { #endif /* Forward declarations */ struct Extensions; /* RevDetails */ typedef struct RevDetails { CertTemplate_t certDetails; ReasonFlags_t *revocationReason /* OPTIONAL */; GeneralizedTime_t *badSinceDate /* OPTIONAL */; struct Extensions *crlEntryDetails /* OPTIONAL */; /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } RevDetails_t; /* Implementation */ extern asn_TYPE_descriptor_t asn_DEF_RevDetails; #ifdef __cplusplus } #endif /* Referred external types */ #include "Extensions.h" #endif /* _RevDetails_H_ */
lades-unb/asn1pas
include/RevDetails.h
C
gpl-2.0
965
/* * startmenu.h * * Copyright (C) 1995-2001 Kenichi Kourai * * 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, 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 qvwm; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef _STARTMENU_H_ #define _STARTMENU_H_ #include "menu.h" class QvImage; class StartMenu : public Menu { private: Window logo; // window for logo mark in the left side Window* itemFocus; // transparent window for each item // this includes the parts of logo. private: static QvImage* imgLogoMark; // logo mark static QvImage* imgStart[2]; static const int LOGO_WIDTH = 21; public: StartMenu(MenuElem* mItem); ~StartMenu(); void MapMenu(); void UnmapMenu(); void DrawMenu(Window win); int FindItem(Window win); void ExecFunction(FuncNumber fn, int num); static void Initialize(); }; #endif // _STARTMENU_H_
alivardar/qvwm
src/startmenu.h
C
gpl-2.0
1,491
// RU lang variables KOI8-R tinyMCE.addToLang('',{ insert_advhr_desc : '÷ÓÔÁ×ÉÔØ / ÒÅÄÁËÔÉÒÏ×ÁÔØ ÇÏÒÉÚÏÎÔÁÌØÎÙÊ ÒÁÚÄÅÌÉÔÅÌØ', insert_advhr_width : 'ûÉÒÉÎÁ', insert_advhr_size : '÷ÙÓÏÔÁ', insert_advhr_noshade : 'âÅÚ ÔÅÎÉ' });
tectronics/volunteer-passport
_tinymce/jscripts/tiny_mce/plugins/advhr/langs/ru_KOI8-R.js
JavaScript
gpl-2.0
234
/* * Copyright (c) 2012-2013 Open Source Community - <http://www.peerfact.org> * Copyright (c) 2011-2012 University of Paderborn - UPB * Copyright (c) 2005-2011 KOM - Multimedia Communications Lab * * This file is part of PeerfactSim.KOM. * * PeerfactSim.KOM 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. * * PeerfactSim.KOM 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 PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>. * */ package org.peerfact.impl.util.timeoutcollections; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import org.peerfact.impl.simengine.Simulator; /** * A set of objects where elements 'run out' after a certain amount of time and * get thrown out of the collection. Element e (added via addNow(e)) is removed * from this set after a defined timeout since it is added. <br> * <br> * You can add listeners to this set that announce elements that are removed * from this set during the cleanup process. * * @author Leo Nobach <peerfact@kom.tu-darmstadt.de> * * @param <E> * @version 05/06/2011 */ public class TimeoutSet<E> { Set<E> elements = new LinkedHashSet<E>(); Queue<TimeoutObject> timeQ = new LinkedBlockingQueue<TimeoutObject>(); List<ITimeoutSetListener<E>> listeners = new ArrayList<ITimeoutSetListener<E>>(); long timeout; /** * Creates a new TimeoutSet with the given timeout in simulation time units, * i.e. the time until element e (added via addNow(e)) is removed from this * set. * * @param timeout * , the time until element e (added via addNow(e)) is removed * from this set. */ public TimeoutSet(long timeout) { this.timeout = timeout; } /** * Removes the oldest element that is currently i this set. * * @return */ public E removeOldest() { cleanup(); TimeoutObject obj = timeQ.remove(); elements.remove(obj.object); // assertSet(); return obj.object; } @Override public String toString() { return elements.toString(); } /** * Returns an unmodifiable view of this timeout set, using the interface * java.util.Set * * @return */ public Set<E> getUnmodifiableSet() { return Collections.unmodifiableSet(elements); } /** * Adds an element to this timeout set. The element will time out in * currentTime + timeout simulation time units. * * @param element */ public void addNow(E element) { cleanup(); long time = getCurrentTime(); if (elements.contains(element)) { timeQ.remove(new TimeoutObject(element, 0)); } elements.add(element); timeQ.add(new TimeoutObject(element, time + timeout)); // assertSet(); } /** * Returns whether this set contains the specified element. Behaves like * java.util.Set * * @param element * @return */ public boolean contains(E element) { cleanup(); // assertSet(); return elements.contains(element); } /** * Removes the given element from this set, although if it is not timeouted. * Returns whether the given element was contained in this set. * * @param element * @return */ public boolean remove(E element) { // log.debug("Q+SET-BEFORE: " + timeQ + ", " + elements + // " REMOVING: " + element); cleanup(); boolean result = false; if (elements.contains(element)) { result = true; timeQ.remove(new TimeoutObject(element, 0)); // log.debug("SET CONTAINS ELEMENT"); } elements.remove(element); // assertSet(); return result; } /** * Returns the size of this timeout set. Works like in java.util.Set */ public int size() { cleanup(); return elements.size(); } /** * Returns whether this timeout set is empty. Works like in java.util.Set * * @return */ public boolean isEmpty() { return size() == 0; } /* * private void assertSet() { if (elements.size() != timeQ.size()) throw new * AssertionError("Inequal sizes of queue and set: " + timeQ.size() + ", " + * elements.size()); } */ /** * Cleans up this set. Calling this method does not change anything in the * semantics of the TimeoutSet, but should be done when you want to purge * old elements from memory. Automatically done by other methods. * */ public void cleanup() { long time = getCurrentTime(); while (!timeQ.isEmpty() && timeQ.element().timeoutValue <= time) { TimeoutObject obj = timeQ.remove(); elements.remove(obj.object); elementTimeouted(obj.object, obj.timeoutValue); } // assertSet(); } protected static long getCurrentTime() { return Simulator.getCurrentTime(); } /** * Adds a new ITimeoutCollectionListener to this timeout set. * * @param l */ public void addListener(ITimeoutSetListener<E> l) { listeners.add(l); } protected void elementTimeouted(E element, long timeoutTime) { for (ITimeoutSetListener<E> l : listeners) { l.elementTimeouted(this, element, timeoutTime); } } protected class TimeoutObject { public TimeoutObject(E object, long timeout) { this.object = object; this.timeoutValue = timeout; } public E object; public long timeoutValue; @Override public boolean equals(Object o) { if (o == null) { return false; } else if (!(o instanceof TimeoutSet<?>.TimeoutObject)) { return false; } else { return ((TimeoutSet.TimeoutObject) o).object .equals(this.object); } } @Override public int hashCode() { return this.object.hashCode(); } } }
flyroom/PeerfactSimKOM_Clone
src/org/peerfact/impl/util/timeoutcollections/TimeoutSet.java
Java
gpl-2.0
6,004
// fonthunter4.cpp // // A utility for testing fonts. // // (C) Copyright 2019 Fred Gleason <fredg@paravelsystems.com> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // #include <stdio.h> #include <stdlib.h> #include <QApplication> #include <QFontInfo> #include <QLabel> #include <QResizeEvent> #include <QStringList> #include "fonthunter4.h" MainWidget::MainWidget(QWidget *parent) : QWidget(parent) { // // Create Fonts // QFont label_font(font().family(),font().pointSize(),QFont::Bold); // // Set Window Title // setWindowTitle(tr("FontHunter - Qt4")); setMinimumSize(sizeHint()); // // Family // font_family_label=new QLabel(tr("Family")+":",this); font_family_label->setFont(label_font); font_family_label->setAlignment(Qt::AlignRight|Qt::AlignVCenter); font_family_edit=new QLineEdit(this); font_family_edit->setText(font().family()); // // Size // font_size_label=new QLabel(tr("Size")+":",this); font_size_label->setFont(label_font); font_size_label->setAlignment(Qt::AlignRight|Qt::AlignVCenter); font_size_spin=new QSpinBox(this); font_size_spin->setRange(2,200); font_size_spin->setValue(font().pointSize()); // // Weight // font_weight_label=new QLabel(tr("Weight")+":",this); font_weight_label->setFont(label_font); font_weight_label->setAlignment(Qt::AlignRight|Qt::AlignVCenter); font_weight_box=new QComboBox(this); font_weights.push_back(QFont::Light); font_weight_names.push_back(tr("Light")); font_weight_box->insertItem(font_weight_box->count(),tr("Light")); font_weights.push_back(QFont::Normal); font_weight_names.push_back(tr("Normal")); font_weight_box->insertItem(font_weight_box->count(),tr("Normal")); font_weights.push_back(QFont::DemiBold); font_weight_names.push_back(tr("DemiBold")); font_weight_box->insertItem(font_weight_box->count(),tr("DemiBold")); font_weights.push_back(QFont::Bold); font_weight_names.push_back(tr("Bold")); font_weight_box->insertItem(font_weight_box->count(),tr("Bold")); font_weights.push_back(QFont::Black); font_weight_names.push_back(tr("Black")); font_weight_box->insertItem(font_weight_box->count(),tr("Black")); for(unsigned i=0;i<font_weights.size();i++) { if(font_weights.at(i)>=font().weight()) { font_weight_box->setCurrentIndex(i); break; } } // // Italic // font_italic_label=new QLabel(tr("Italicize")+":",this); font_italic_label->setFont(label_font); font_italic_label->setAlignment(Qt::AlignRight|Qt::AlignVCenter); font_italic_box=new QComboBox(this); font_italic_box->insertItem(0,tr("No")); font_italic_box->insertItem(1,tr("Yes")); // // Apply Button // font_apply_button=new QPushButton(tr("Apply"),this); font_apply_button->setFont(label_font); connect(font_apply_button,SIGNAL(clicked()),this,SLOT(applyData())); // // Metric Value Outputs // font_metric_exact_match_label=new QLabel(tr("Exact Match")+":",this); font_metric_exact_match_label->setFont(label_font); font_metric_exact_match_label->setAlignment(Qt::AlignRight|Qt::AlignVCenter); font_metric_exact_match_value=new QLabel(this); font_metric_exact_match_value->setAlignment(Qt::AlignLeft|Qt::AlignVCenter); font_metric_family_label=new QLabel(tr("Family")+":",this); font_metric_family_label->setFont(label_font); font_metric_family_label->setAlignment(Qt::AlignRight|Qt::AlignVCenter); font_metric_family_value=new QLabel(this); font_metric_family_value->setAlignment(Qt::AlignLeft|Qt::AlignVCenter); font_metric_size_label=new QLabel(tr("Point Size")+":",this); font_metric_size_label->setFont(label_font); font_metric_size_label->setAlignment(Qt::AlignRight|Qt::AlignVCenter); font_metric_size_value=new QLabel(this); font_metric_size_value->setAlignment(Qt::AlignLeft|Qt::AlignVCenter); font_metric_weight_label=new QLabel(tr("Weight")+":",this); font_metric_weight_label->setFont(label_font); font_metric_weight_label->setAlignment(Qt::AlignRight|Qt::AlignVCenter); font_metric_weight_value=new QLabel(this); font_metric_weight_value->setAlignment(Qt::AlignLeft|Qt::AlignVCenter); font_metric_bold_label=new QLabel(tr("Is Bold")+":",this); font_metric_bold_label->setFont(label_font); font_metric_bold_label->setAlignment(Qt::AlignRight|Qt::AlignVCenter); font_metric_bold_value=new QLabel(this); font_metric_bold_value->setAlignment(Qt::AlignLeft|Qt::AlignVCenter); font_metric_italic_label=new QLabel(tr("Is Italicized")+":",this); font_metric_italic_label->setFont(label_font); font_metric_italic_label->setAlignment(Qt::AlignRight|Qt::AlignVCenter); font_metric_italic_value=new QLabel(this); font_metric_italic_value->setAlignment(Qt::AlignLeft|Qt::AlignVCenter); // // Samples // font_sample_label_label=new QLabel("QLabel",this); font_sample_label_label->setFont(label_font); font_sample_label_label->setAlignment(Qt::AlignLeft|Qt::AlignVCenter); font_sample_label=new QLabel(this); font_sample_label->setFrameStyle(QFrame::Box|QFrame::Plain); font_sample_label->setLineWidth(1); font_sample_edit_label=new QLabel("QLineEdit",this); font_sample_edit_label->setFont(label_font); font_sample_edit_label->setAlignment(Qt::AlignLeft|Qt::AlignVCenter); font_sample_edit=new QLineEdit(this); connect(font_sample_edit,SIGNAL(textChanged(const QString &)), font_sample_label,SLOT(setText(const QString &))); font_sample_textedit_label=new QLabel("QTextEdit",this); font_sample_textedit_label->setFont(label_font); font_sample_textedit_label->setAlignment(Qt::AlignLeft|Qt::AlignVCenter); font_sample_textedit=new QTextEdit(this); font_sample_textedit->setAcceptRichText(true); applyData(); } QSize MainWidget::sizeHint() const { return QSize(400,622); } void MainWidget::applyData() { QFont test_font(font_family_edit->text(),font_size_spin->value(), font_weights.at(font_weight_box->currentIndex()), font_italic_box->currentIndex()); QFontInfo fi(test_font); if(fi.exactMatch()) { font_metric_exact_match_value->setText(tr("True")); } else { font_metric_exact_match_value->setText(tr("False")); } font_metric_family_value->setText(fi.family()); font_metric_size_value->setText(QString().sprintf("%d",fi.pointSize())); QString name=""; for(unsigned i=0;i<font_weights.size();i++) { if(fi.weight()==font_weights.at(i)) { name=font_weight_names[i]; } } if(name.isEmpty()) { font_metric_weight_value->setText(QString().sprintf("%d",fi.weight())); } else { font_metric_weight_value->setText(name); } if(fi.bold()) { font_metric_bold_value->setText(tr("True")); } else { font_metric_bold_value->setText(tr("False")); } if(fi.italic()) { font_metric_italic_value->setText(tr("True")); } else { font_metric_italic_value->setText(tr("False")); } font_sample_label->setFont(test_font); font_sample_edit->setFont(test_font); font_sample_textedit->setFont(test_font); resizeEvent(NULL); } void MainWidget::resizeEvent(QResizeEvent *e) { int w=width(); font_family_label->setGeometry(10,2,100,20); font_family_edit->setGeometry(115,2,w-125,20); font_size_label->setGeometry(10,27,100,20); font_size_spin->setGeometry(115,27,w-125,20); font_weight_label->setGeometry(10,52,100,20); font_weight_box->setGeometry(115,52,w-125,20); font_italic_label->setGeometry(10,77,100,20); font_italic_box->setGeometry(115,77,60,20); font_apply_button->setGeometry(10,102,w-20,40); font_metric_exact_match_label->setGeometry(10,150,100,20); font_metric_exact_match_value->setGeometry(115,150,w-20,20); font_metric_family_label->setGeometry(10,175,100,20); font_metric_family_value->setGeometry(115,175,w-20,20); font_metric_size_label->setGeometry(10,200,100,20); font_metric_size_value->setGeometry(115,200,w-20,20); font_metric_weight_label->setGeometry(10,225,100,20); font_metric_weight_value->setGeometry(115,225,w-20,20); font_metric_bold_label->setGeometry(10,250,100,20); font_metric_bold_value->setGeometry(115,250,w-20,20); font_metric_italic_label->setGeometry(10,275,100,20); font_metric_italic_value->setGeometry(115,275,w-20,20); QFont test_font=font_sample_label->font(); int ypos=310; font_sample_label_label->setGeometry(20,ypos,w-30,20); ypos+=20; font_sample_label->setGeometry(10,ypos,w-20,3*test_font.pointSize()); ypos+=3*test_font.pointSize()+20; font_sample_edit_label->setGeometry(20,ypos,w-30,20); ypos+=20; font_sample_edit->setGeometry(10,ypos,w-20,3*test_font.pointSize()); ypos+=3*test_font.pointSize()+20; font_sample_textedit_label->setGeometry(20,ypos,w-30,20); ypos+=20; font_sample_textedit->setGeometry(10,ypos,w-20,10*test_font.pointSize()); ypos+=10*test_font.pointSize()+20; } int main(int argc,char *argv[]) { QApplication a(argc,argv); MainWidget *w=new MainWidget(); w->show(); return a.exec(); }
ElvishArtisan/mojihunter
src/fonthunter/qt4/fonthunter4.cpp
C++
gpl-2.0
9,572
/** * CPUFreq plugin to lxpanel * * Copyright (C) 2009 by Daniel Kesler <kesler.daniel@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <glib.h> #include <gtk/gtk.h> #include <glib/gi18n.h> #include <string.h> #include "plugin.h" #include "dbg.h" #define PROC_ICON "cpufreq-icon" #define SYSFS_CPU_DIRECTORY "/sys/devices/system/cpu" #define SCALING_GOV "scaling_governor" #define SCALING_AGOV "scaling_available_governors" #define SCALING_AFREQ "scaling_available_frequencies" #define SCALING_CUR_FREQ "scaling_cur_freq" #define SCALING_SETFREQ "scaling_setspeed" #define SCALING_MAX "scaling_max_freq" #define SCALING_MIN "scaling_min_freq" typedef struct { GtkWidget *main; GSettings *settings; GtkWidget *namew; GList *governors; GList *cpus; int has_cpufreq; char* cur_governor; int cur_freq; unsigned int timer; //gboolean remember; } cpufreq; typedef struct { char *data; cpufreq *cf; } Param; static void cpufreq_destructor(gpointer user_data); static void get_cur_governor(cpufreq *cf){ FILE *fp; char buf[ 100 ], sstmp [ 256 ]; snprintf(sstmp, sizeof(sstmp), "%s/%s", (char*)cf->cpus->data, SCALING_GOV); if ((fp = fopen( sstmp, "r")) != NULL) { if(cf->cur_governor) { g_free(cf->cur_governor); cf->cur_governor = NULL; } if (fgets(buf, 100, fp)) { buf[strlen(buf)-1] = '\0'; cf->cur_governor = strdup(buf); } fclose(fp); } } static void get_cur_freq(cpufreq *cf){ FILE *fp; char buf[ 100 ], sstmp [ 256 ]; snprintf(sstmp, sizeof(sstmp), "%s/%s", (char*)cf->cpus->data, SCALING_CUR_FREQ); if ((fp = fopen( sstmp, "r")) != NULL) { if (fgets(buf, 100, fp)) { buf[strlen(buf)-1] = '\0'; cf->cur_freq = atoi(buf); } fclose(fp); } } /*static void get_governors(cpufreq *cf){ FILE *fp; GList *l; char buf[ 100 ], sstmp [ 256 ], c, bufl = 0; g_list_free(cf->governors); cf->governors = NULL; get_cur_governor(cf); if(cf->cpus == NULL){ cf->governors = NULL; return; } sprintf(sstmp,"%s/%s",cf->cpus->data, SCALING_AGOV); if (!(fp = fopen( sstmp, "r"))) { printf("cpufreq: cannot open %s\n",sstmp); return; } while((c = fgetc(fp)) != EOF){ if(c == ' '){ if(bufl > 1){ buf[bufl] = '\0'; cf->governors = g_list_append(cf->governors, strdup(buf)); } bufl = 0; buf[0] = '\0'; }else{ buf[bufl++] = c; } } fclose(fp); } static void cpufreq_set_freq(GtkWidget *widget, Param* p){ FILE *fp; char buf[ 100 ], sstmp [ 256 ]; if(strcmp(p->cf->cur_governor, "userspace")) return; sprintf(sstmp,"%s/%s",p->cf->cpus->data, SCALING_SETFREQ); if ((fp = fopen( sstmp, "w")) != NULL) { fprintf(fp,"%s",p->data); fclose(fp); } } static GtkWidget * frequency_menu(cpufreq *cf){ FILE *fp; Param* param; char buf[ 100 ], sstmp [ 256 ], c, bufl = 0; sprintf(sstmp,"%s/%s",cf->cpus->data, SCALING_AFREQ); if (!(fp = fopen( sstmp, "r"))) { printf("cpufreq: cannot open %s\n",sstmp); return 0; } GtkMenu* menu = GTK_MENU(gtk_menu_new()); GtkWidget* menuitem; while((c = fgetc(fp)) != EOF){ if(c == ' '){ if(bufl > 1){ buf[bufl] = '\0'; menuitem = gtk_menu_item_new_with_label(strdup(buf)); gtk_menu_append (GTK_MENU_SHELL (menu), menuitem); gtk_widget_show (menuitem); param = g_new0(Param, 1); param->data = strdup(buf); param->cf = cf; g_signal_connect(G_OBJECT(menuitem), "activate", G_CALLBACK(cpufreq_set_freq), param); g_object_weak_ref(G_OBJECT(menuitem), (GWeakNotify)g_free, param); } bufl = 0; buf[0] = '\0'; }else{ buf[bufl++] = c; } } fclose(fp); return GTK_WIDGET(menu); }*/ static void get_cpus(cpufreq *cf) { const char *cpu; char cpu_path[100]; GDir * cpuDirectory = g_dir_open(SYSFS_CPU_DIRECTORY, 0, NULL); if (cpuDirectory == NULL) { cf->cpus = NULL; printf("cpufreq: no cpu found\n"); return; } while ((cpu = g_dir_read_name(cpuDirectory))) { /* Look for directories of the form "cpu<n>", where "<n>" is a decimal integer. */ if ((strncmp(cpu, "cpu", 3) == 0) && (cpu[3] >= '0') && (cpu[3] <= '9')) { snprintf(cpu_path, sizeof(cpu_path), "%s/%s/cpufreq", SYSFS_CPU_DIRECTORY, cpu); GDir * cpufreqDir = g_dir_open(SYSFS_CPU_DIRECTORY, 0, NULL); if (cpufreqDir == NULL) { cf->cpus = NULL; cf->has_cpufreq = 0; break; } cf->has_cpufreq = 1; cf->cpus = g_list_append(cf->cpus, strdup(cpu_path)); } } g_dir_close(cpuDirectory); } /*static void cpufreq_set_governor(GtkWidget *widget, Param* p){ FILE *fp; char buf[ 100 ], sstmp [ 256 ]; sprintf(sstmp, "%s/%s", p->cf->cpus->data, SCALING_GOV); if ((fp = fopen( sstmp, "w")) != NULL) { fprintf(fp,"%s",p->data); fclose(fp); } } static GtkWidget * cpufreq_menu(cpufreq *cf){ GList *l; GSList *group; char buff[100]; GtkMenuItem* menuitem; Param* param; GtkMenu* menu = GTK_MENU(gtk_menu_new()); g_signal_connect(menu, "selection-done", G_CALLBACK(gtk_widget_destroy), NULL); get_governors(cf); group = NULL; if((cf->governors == NULL) || (!cf->has_cpufreq) || (cf->cur_governor == NULL)){ menuitem = GTK_MENU_ITEM(gtk_menu_item_new_with_label("CPUFreq not supported")); gtk_menu_append (GTK_MENU_SHELL (menu), GTK_WIDGET (menuitem)); gtk_widget_show (GTK_WIDGET (menuitem)); return GTK_WIDGET(menu); } if(strcmp(cf->cur_governor, "userspace") == 0){ menuitem = GTK_MENU_ITEM(gtk_menu_item_new_with_label(" Frequency")); gtk_menu_append (GTK_MENU_SHELL (menu), GTK_WIDGET (menuitem)); gtk_widget_show (GTK_WIDGET (menuitem)); gtk_menu_item_set_submenu(menuitem, frequency_menu(cf)); menuitem = GTK_MENU_ITEM(gtk_separator_menu_item_new()); gtk_menu_append (GTK_MENU_SHELL (menu), GTK_WIDGET (menuitem)); gtk_widget_show (GTK_WIDGET(menuitem)); } for( l = cf->governors; l; l = l->next ) { if(strcmp((char*)l->data, cf->cur_governor) == 0){ sprintf(buff,"> %s", l->data); menuitem = GTK_MENU_ITEM(gtk_menu_item_new_with_label(strdup(buff))); }else{ sprintf(buff," %s", l->data); menuitem = GTK_MENU_ITEM(gtk_menu_item_new_with_label(strdup(buff))); } gtk_menu_shell_append (GTK_MENU_SHELL (menu), GTK_WIDGET (menuitem)); gtk_widget_show (GTK_WIDGET (menuitem)); param = g_new0(Param, 1); param->data = l->data; param->cf = cf; g_signal_connect(G_OBJECT(menuitem), "activate", G_CALLBACK(cpufreq_set_governor), param); g_object_weak_ref(G_OBJECT(menuitem), (GWeakNotify) g_free, param); } return GTK_WIDGET (menu); }*/ static gboolean clicked(GtkWidget *widget, GdkEventButton *evt, SimplePanel *panel) { ENTER; /* Standard right-click handling. */ if( evt->button == 1 ) { // Setting governor can't work without root privilege // gtk_menu_popup( cpufreq_menu((cpufreq*)plugin->priv), NULL, NULL, NULL, NULL, // evt->button, evt->time ); return TRUE; } RET(FALSE); } static gboolean _update_tooltip(cpufreq *cf) { char *tooltip; get_cur_freq(cf); get_cur_governor(cf); ENTER; tooltip = g_strdup_printf(_("Frequency: %d MHz\nGovernor: %s"), cf->cur_freq / 1000, cf->cur_governor); gtk_widget_set_tooltip_text(cf->main, tooltip); g_free(tooltip); RET(TRUE); } static gboolean update_tooltip(gpointer user_data) { if (g_source_is_destroyed(g_main_current_source())) return FALSE; return _update_tooltip(user_data); } static GtkWidget *cpufreq_constructor(SimplePanel *panel, GSettings *settings) { cpufreq *cf; //GtkWidget *button; ENTER; cf = g_new0(cpufreq, 1); g_return_val_if_fail(cf != NULL, NULL); cf->governors = NULL; cf->cpus = NULL; cf->settings = settings; cf->main = gtk_event_box_new(); lxpanel_plugin_set_data(cf->main, cf, cpufreq_destructor); gtk_widget_set_has_window(cf->main, FALSE); GIcon* icon = g_themed_icon_new_with_default_fallbacks("cpu-frequency-indicator"); g_themed_icon_append_name(G_THEMED_ICON(icon),"cpufreq-100"); g_themed_icon_append_name(G_THEMED_ICON(icon),"indicator-cpufreq"); g_themed_icon_append_name(G_THEMED_ICON(icon),"gnome-cpu-frequency-applet"); g_themed_icon_append_name(G_THEMED_ICON(icon),"mate-cpu-frequency-applet"); g_themed_icon_append_name(G_THEMED_ICON(icon),"xfce4-cpugraph-plugin"); g_themed_icon_append_name(G_THEMED_ICON(icon),PROC_ICON); cf->namew = simple_panel_image_new_for_gicon(panel,icon,-1); g_object_unref(icon); gtk_container_add(GTK_CONTAINER(cf->main), cf->namew); cf->has_cpufreq = 0; get_cpus(cf); //if (config_setting_lookup_int(settings, "Remember", &tmp_int)) cf->remember = tmp_int != 0; //if (config_setting_lookup_int(settings, "Governor", &tmp_str)) cf->cur_governor = g_strdup(tmp_str); //config_setting_lookup_int(settings, "Frequency", &cf->cur_freq); _update_tooltip(cf); cf->timer = g_timeout_add_seconds(2, update_tooltip, (gpointer)cf); gtk_widget_show(cf->namew); RET(cf->main); } /* static gboolean applyConfig(gpointer user_data) { cpufreq *cf = lxpanel_plugin_get_data(user_data); config_group_set_int(cf->settings, "Remember", cf->remember); return FALSE; } static GtkWidget *config(SimplePanel *panel, GtkWidget *p, GtkWindow *parent) { cpufreq *cf = lxpanel_plugin_get_data(p); return lxpanel_generic_config_dlg(_("CPUFreq frontend"), panel, applyConfig, p, _("Remember governor and frequency"), &cf->remember, CONF_TYPE_BOOL, NULL); } */ static void cpufreq_destructor(gpointer user_data) { cpufreq *cf = (cpufreq *)user_data; g_list_free ( cf->cpus ); g_list_free ( cf->governors ); g_source_remove(cf->timer); g_free(cf); } FM_DEFINE_MODULE(lxpanel_gtk, cpufreq) /* Plugin descriptor. */ SimplePanelPluginInit fm_module_init_lxpanel_gtk = { .name = N_("CPUFreq frontend"), .description = N_("Display CPU frequency and allow to change governors and frequency"), .new_instance = cpufreq_constructor, //.config = config, .button_press_event = clicked, .has_config = FALSE };
rilian-la-te/simple-panel
plugins/cpufreq/cpufreq.c
C
gpl-2.0
11,831
/* Bulgarian initialisation for the jQuery UI date picker plugin. */ /* Written by Stoyan Kyosev (http://svest.org). */ jQuery(function ($) { $.datepicker.regional['bg'] = { closeText: 'затвори', prevText: '&#x3c;назад', nextText: 'напред&#x3e;', nextBigText: '&#x3e;&#x3e;', currentText: 'днес', monthNames: ['Януари', 'Февруари', 'Март', 'Април', 'Май', 'Юни', 'Юли', 'Август', 'Септември', 'Октомври', 'Ноември', 'Декември'], monthNamesShort: ['Яну', 'Фев', 'Мар', 'Апр', 'Май', 'Юни', 'Юли', 'Авг', 'Сеп', 'Окт', 'Нов', 'Дек'], dayNames: ['Неделя', 'Понеделник', 'Вторник', 'Сряда', 'Четвъртък', 'Петък', 'Събота'], dayNamesShort: ['Нед', 'Пон', 'Вто', 'Сря', 'Чет', 'Пет', 'Съб'], dayNamesMin: ['Не', 'По', 'Вт', 'Ср', 'Че', 'Пе', 'Съ'], weekHeader: 'Wk', dateFormat: 'dd.mm.yy', firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: ''}; $.datepicker.setDefaults($.datepicker.regional['bg']); });
parksandwildlife/parkstay
jomres/javascript/jquery-ui-cal-localisation/jquery.ui.datepicker-bg.js
JavaScript
gpl-2.0
1,166
<?php /** * Cart Page * * @author WooThemes * @package WooCommerce/Templates * @version 2.1.0 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly wc_print_notices(); do_action( 'woocommerce_before_cart' ); ?> <form action="<?php echo esc_url( WC()->cart->get_cart_url() ); ?>" method="post"> <?php do_action( 'woocommerce_before_cart_table' ); ?> <table class="shop_table cart" cellspacing="0"> <thead> <tr> <th class="product-remove">&nbsp;</th> <th class="product-thumbnail">&nbsp;</th> <th class="product-name">osmel<?php _e( 'Product', 'woocommerce' ); ?></th> <th class="product-price"><?php _e( 'Price', 'woocommerce' ); ?></th> <th class="product-quantity"><?php _e( 'Quantity', 'woocommerce' ); ?></th> <th class="product-subtotal"><?php _e( 'Total', 'woocommerce' ); ?></th> </tr> </thead> <tbody> <?php do_action( 'woocommerce_before_cart_contents' ); ?> <?php foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key ); $product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key ); if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_cart_item_visible', true, $cart_item, $cart_item_key ) ) { ?> <tr class="<?php echo esc_attr( apply_filters( 'woocommerce_cart_item_class', 'cart_item', $cart_item, $cart_item_key ) ); ?>"> <td class="product-remove"> <?php echo apply_filters( 'woocommerce_cart_item_remove_link', sprintf( '<a href="%s" class="remove" title="%s">&times;</a>', esc_url( WC()->cart->get_remove_url( $cart_item_key ) ), __( 'Remove this item', 'woocommerce' ) ), $cart_item_key ); ?> </td> <td class="product-thumbnail"> <?php $thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key ); if ( ! $_product->is_visible() ) echo $thumbnail; else printf( '<a href="%s">%s</a>', $_product->get_permalink(), $thumbnail ); ?> </td> <td class="product-name"> <?php if ( ! $_product->is_visible() ) echo apply_filters( 'woocommerce_cart_item_name', $_product->get_title(), $cart_item, $cart_item_key ); else echo apply_filters( 'woocommerce_cart_item_name', sprintf( '<a href="%s">%s</a>', $_product->get_permalink(), $_product->get_title() ), $cart_item, $cart_item_key ); // Meta data echo WC()->cart->get_item_data( $cart_item ); // Backorder notification if ( $_product->backorders_require_notification() && $_product->is_on_backorder( $cart_item['quantity'] ) ) echo '<p class="backorder_notification">' . __( 'Available on backorder', 'woocommerce' ) . '</p>'; ?> </td> <td class="product-price"> <?php echo apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $_product ), $cart_item, $cart_item_key ); ?> </td> <td class="product-quantity"> <?php if ( $_product->is_sold_individually() ) { $product_quantity = sprintf( '1 <input type="hidden" name="cart[%s][qty]" value="1" />', $cart_item_key ); } else { $product_quantity = woocommerce_quantity_input( array( 'input_name' => "cart[{$cart_item_key}][qty]", 'input_value' => $cart_item['quantity'], 'max_value' => $_product->backorders_allowed() ? '' : $_product->get_stock_quantity(), 'min_value' => '0' ), $_product, false ); } echo apply_filters( 'woocommerce_cart_item_quantity', $product_quantity, $cart_item_key ); ?> </td> <td class="product-subtotal"> <?php echo apply_filters( 'woocommerce_cart_item_subtotal', WC()->cart->get_product_subtotal( $_product, $cart_item['quantity'] ), $cart_item, $cart_item_key ); ?> </td> </tr> <?php } } do_action( 'woocommerce_cart_contents' ); ?> <tr> <td colspan="6" class="actions"> <?php if ( WC()->cart->coupons_enabled() ) { ?> <div class="coupon"> <label for="coupon_code"><?php _e( 'Coupon', 'woocommerce' ); ?>:</label> <input type="text" name="coupon_code" class="input-text" id="coupon_code" value="" placeholder="<?php _e( 'Coupon code', 'woocommerce' ); ?>" /> <input type="submit" class="button" name="apply_coupon" value="<?php _e( 'Apply Coupon', 'woocommerce' ); ?>" /> <?php do_action('woocommerce_cart_coupon'); ?> </div> <?php } ?> <input type="submit" class="button" name="update_cart" value="<?php _e( 'Update Cart', 'woocommerce' ); ?>" /> <input type="submit" class="checkout-button button alt wc-forward" name="proceed" value="<?php _e( 'Proceed to Checkout', 'woocommerce' ); ?>" /> <?php do_action( 'woocommerce_proceed_to_checkout' ); ?> <?php wp_nonce_field( 'woocommerce-cart' ); ?> </td> </tr> <?php do_action( 'woocommerce_after_cart_contents' ); ?> </tbody> </table> <?php do_action( 'woocommerce_after_cart_table' ); ?> </form> <div class="cart-collaterals"> <?php do_action( 'woocommerce_cart_collaterals' ); ?> <?php woocommerce_cart_totals(); ?> <?php woocommerce_shipping_calculator(); ?> </div> <?php do_action( 'woocommerce_after_cart' ); ?>
estrategasdigitales/onisuzume
wp-content/themes/placeres-woocommerce/woocommerce/templates/cart/cart.php
PHP
gpl-2.0
5,483
#include <kcharsets.h> #include <kdebug.h> #include <QtCore/QString> #include <assert.h> int main() { // Note: ctest sets LANG=C, while running the test directly uses your real $LANG. // And since the static initializer runs before main, we cannot setenv("LANG") here, // it's too late. //kDebug() << "LANG=" << getenv("LANG"); //kDebug() << "LC_ALL=" << getenv("LC_ALL"); // Test that toLocal8Bit works even without a QCoreApplication, // thanks to the static initializer in KCatalog. // Do NOT move this code to a QTestLib unit test ;-) QString one = QString::fromUtf8("é"); QByteArray one8bit = one.toLocal8Bit(); if (qgetenv("LANG").endsWith("UTF-8")) { // krazy:exclude=strings kDebug() << one << one8bit; Q_ASSERT(one8bit.length() == 2); } QString input( "&lt;Hello &amp;World&gt;" ); QString output = KCharsets::resolveEntities( input ); assert( output == "<Hello &World>" ); return 0; }
vasi/kdelibs
kdecore/tests/kcharsetstest.cpp
C++
gpl-2.0
981
/* SPDX-License-Identifier: GPL-2.0-only */ #include <console/console.h> #include <device/device.h> #include <device/pci.h> #include <device/pci_ids.h> #include <device/mmio.h> #include <device/pci_ops.h> #include <arch/ioapic.h> #include <acpi/acpi.h> #include <cpu/x86/smm.h> #include <bootstate.h> #include <soc/lpc.h> #include <soc/pci_devs.h> #include <soc/ramstage.h> #include <soc/iomap.h> #include <soc/pcr.h> #include <soc/p2sb.h> #include <soc/acpi.h> #include "chip.h" /* PCH I/O APIC redirection entries */ #define PCH_REDIR_ETR 120 /** * Set miscellaneous static southbridge features. * * @param dev PCI device with I/O APIC control registers */ static void pch_enable_ioapic(struct device *dev) { /* affirm full set of redirection table entries ("write once") */ ioapic_set_max_vectors(VIO_APIC_VADDR, PCH_REDIR_ETR); setup_ioapic((void *)IO_APIC_ADDR, IO_APIC0); } /* interrupt router lookup for internal devices */ struct dnv_ir_lut { /* (dev << 3) | fn */ u8 devfn; u8 ir; }; #define DEVFN(dev, fn) ((dev << 3) | (fn)) static const struct dnv_ir_lut dnv_ir_lut[] = { {.devfn = DEVFN(0x05, 0), .ir = 3}, /* RCEC */ {.devfn = DEVFN(0x06, 0), .ir = 4}, /* Virtual RP to QAT */ {.devfn = DEVFN(0x09, 0), .ir = 7}, /* PCIe RP0 */ {.devfn = DEVFN(0x0a, 0), .ir = 7}, /* PCIe RP1 */ {.devfn = DEVFN(0x0b, 0), .ir = 7}, /* PCIe RP2 */ {.devfn = DEVFN(0x0c, 0), .ir = 7}, /* PCIe RP3 */ {.devfn = DEVFN(0x0e, 0), .ir = 8}, /* PCIe RP4 */ {.devfn = DEVFN(0x0f, 0), .ir = 8}, /* PCIe RP5 */ {.devfn = DEVFN(0x10, 0), .ir = 8}, /* PCIe RP6 */ {.devfn = DEVFN(0x11, 0), .ir = 8}, /* PCIe RP7 */ {.devfn = DEVFN(0x12, 0), .ir = 10}, /* SMBus - Host */ {.devfn = DEVFN(0x13, 0), .ir = 6}, /* AHCI0 */ {.devfn = DEVFN(0x14, 0), .ir = 11}, /* AHCI1 */ {.devfn = DEVFN(0x15, 0), .ir = 9}, /* USB */ {.devfn = DEVFN(0x16, 0), .ir = 1}, /* Virtual RP to LAN0 */ {.devfn = DEVFN(0x17, 0), .ir = 2}, /* Virtual RP to LAN1 */ {.devfn = DEVFN(0x18, 0), .ir = 5}, /* ME HECI1 */ {.devfn = DEVFN(0x18, 1), .ir = 5}, /* ME HECI1 */ {.devfn = DEVFN(0x18, 2), .ir = 5}, /* ME PTIO-IDER */ {.devfn = DEVFN(0x18, 3), .ir = 5}, /* ME PTIO-KT */ {.devfn = DEVFN(0x18, 4), .ir = 5}, /* ME HECI3 */ {.devfn = DEVFN(0x1a, 0), .ir = 10}, /* HSUART0 */ {.devfn = DEVFN(0x1a, 1), .ir = 10}, /* HSUART1 */ {.devfn = DEVFN(0x1a, 2), .ir = 10}, /* HSUART2 */ {.devfn = DEVFN(0x1b, 0), .ir = 12}, /* IE HECI1 */ {.devfn = DEVFN(0x1b, 1), .ir = 12}, /* IE HECI1 */ {.devfn = DEVFN(0x1b, 2), .ir = 12}, /* IE PTIO-IDER */ {.devfn = DEVFN(0x1b, 3), .ir = 12}, /* IE PTIO-KT */ {.devfn = DEVFN(0x1b, 4), .ir = 12}, /* IE HECI3 */ {.devfn = DEVFN(0x1c, 0), .ir = 12}, /* SDHCI */ {.devfn = DEVFN(0x1f, 0), .ir = 0}, /* LPC */ {.devfn = DEVFN(0x1f, 1), .ir = 0}, /* PS2B */ {.devfn = DEVFN(0x1f, 4), .ir = 0}, /* SMBus - Legacy */ {.devfn = DEVFN(0x1f, 7), .ir = 0}, /* Trace Hub */ }; /* * Only 6 of the 8 root ports have swizzling, return '1' if this bdf is one of * them, '0' otherwise */ static int is_dnv_swizzled_rp(uint16_t bdf) { switch (bdf) { case DEVFN(10, 0): case DEVFN(11, 0): case DEVFN(12, 0): case DEVFN(15, 0): case DEVFN(16, 0): case DEVFN(17, 0): return 1; } return 0; } /* * Figure out which upstream interrupt pin a downstream device gets swizzled to * * config - pointer to chip_info containing routing info * devfn - device/function of root port to check swizzling for * pin - interrupt pin 1-4 = A-D * * Return new pin mapping, 0 if invalid pin */ static int dnv_get_swizzled_pin(config_t *config, u8 devfn, u8 pin) { if (pin < 1 || pin > 4) return 0; devfn >>= 3; if (devfn < 13) devfn -= 9; else devfn -= 14; return ((pin - 1 + devfn) % 4) + 1; } /* * Figure out which upstream interrupt pin a downstream device gets swizzled to * * config - pointer to chip_info containing routing info * devfn - device/function of root port to check swizzling for * pin - interrupt pin 1-4 = A-D * * Return new pin mapping, 0 if invalid pin */ static int dnv_get_ir(config_t *config, u8 devfn, u8 pin) { int i = 0; int line = 0xff; u16 ir = 0xffff; /* The only valid pin values are 1-4 for A-D */ if (pin < 1 || pin > 4) { printk(BIOS_WARNING, "%s: pin %d is invalid\n", __func__, pin); goto dnv_get_ir_done; } for (i = 0; i < ARRAY_SIZE(dnv_ir_lut); i++) { if (dnv_ir_lut[i].devfn == devfn) break; } if (i == ARRAY_SIZE(dnv_ir_lut)) { printk(BIOS_WARNING, "%s: no entry\n", __func__); goto dnv_get_ir_done; } switch (dnv_ir_lut[i].ir) { case 0: ir = config->ir00_routing; break; case 1: ir = config->ir01_routing; break; case 2: ir = config->ir02_routing; break; case 3: ir = config->ir03_routing; break; case 4: ir = config->ir04_routing; break; case 5: ir = config->ir05_routing; break; case 6: ir = config->ir06_routing; break; case 7: ir = config->ir07_routing; break; case 8: ir = config->ir08_routing; break; case 9: ir = config->ir09_routing; break; case 10: ir = config->ir10_routing; break; case 11: ir = config->ir11_routing; break; case 12: ir = config->ir12_routing; break; default: printk(BIOS_ERR, "%s: invalid ir %d for entry %d\n", __func__, dnv_ir_lut[i].ir, i); goto dnv_get_ir_done; } ir >>= (pin - 1) * 4; ir &= 0xf; switch (ir) { case 0: line = config->pirqa_routing; break; case 1: line = config->pirqb_routing; break; case 2: line = config->pirqc_routing; break; case 3: line = config->pirqd_routing; break; case 4: line = config->pirqe_routing; break; case 5: line = config->pirqf_routing; break; case 6: line = config->pirqg_routing; break; case 7: line = config->pirqh_routing; break; default: printk(BIOS_ERR, "%s: invalid ir pirq %d for entry %d\n", __func__, ir, i); break; } dnv_get_ir_done: return line; } /* * PCI devices have the INT_LINE (0x3C) and INT_PIN (0x3D) registers which * report interrupt routing information to operating systems and drivers. The * INT_PIN register is generally read only and reports which interrupt pin * A - D it uses. The INT_LINE register is configurable and reports which IRQ * (generally the PIC IRQs 1 - 15) it will use. This needs to take interrupt * pin swizzling on devices that are downstream on a PCI bridge into account. */ static u8 dnv_get_int_line(struct device *irq_dev) { config_t *config; struct device *targ_dev = NULL; uint16_t parent_bdf = 0; int8_t original_int_pin = 0, new_int_pin = 0, swiz_int_pin = 0; uint8_t int_line = 0xff; if (irq_dev->path.type != DEVICE_PATH_PCI || !irq_dev->enabled) { printk(BIOS_ERR, "%s for non pci device?\n", __func__); goto dnv_get_int_line_done; } /* * Get the INT_PIN swizzled up to the root port if necessary * using the existing coreboot pci_device code */ original_int_pin = pci_read_config8(irq_dev, PCI_INTERRUPT_PIN); new_int_pin = get_pci_irq_pins(irq_dev, &targ_dev); if (targ_dev == NULL || new_int_pin < 1) goto dnv_get_int_line_done; printk(BIOS_DEBUG, "%s: irq_dev %s, targ_dev %s:\n", __func__, dev_path(irq_dev), dev_path(targ_dev)); printk(BIOS_DEBUG, "%s: std swizzle %s from %c to %c\n", __func__, dev_path(targ_dev), '@' + original_int_pin, '@' + new_int_pin); /* Swizzle this device if needed */ config = targ_dev->chip_info; parent_bdf = targ_dev->path.pci.devfn | targ_dev->bus->secondary << 8; if (is_dnv_swizzled_rp(parent_bdf) && irq_dev != targ_dev) { swiz_int_pin = dnv_get_swizzled_pin(config, parent_bdf, new_int_pin); printk(BIOS_DEBUG, "%s: dnv swizzle %s from %c to %c\n", __func__, dev_path(targ_dev), '@' + new_int_pin, '@' + swiz_int_pin); } else { swiz_int_pin = new_int_pin; } /* Look up the routing for the pin */ int_line = dnv_get_ir(config, parent_bdf, swiz_int_pin); dnv_get_int_line_done: printk(BIOS_DEBUG, "\tINT_LINE\t\t: %d\n", int_line); return int_line; } /* PIRQ[n]_ROUT[3:0] - PIRQ Routing Control * 0x00 - 0000 = Reserved * 0x01 - 0001 = Reserved * 0x02 - 0010 = Reserved * 0x03 - 0011 = IRQ3 * 0x04 - 0100 = IRQ4 * 0x05 - 0101 = IRQ5 * 0x06 - 0110 = IRQ6 * 0x07 - 0111 = IRQ7 * 0x08 - 1000 = Reserved * 0x09 - 1001 = IRQ9 * 0x0A - 1010 = IRQ10 * 0x0B - 1011 = IRQ11 * 0x0C - 1100 = IRQ12 * 0x0D - 1101 = Reserved * 0x0E - 1110 = IRQ14 * 0x0F - 1111 = IRQ15 * PIRQ[n]_ROUT[7] - PIRQ Routing Control * 0x80 - The PIRQ is not routed. */ static void pch_pirq_init(struct device *dev) { struct device *irq_dev; /* Get the chip configuration */ config_t *config = config_of(dev); /* Initialize PIRQ Routings */ write8((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIRQA_ROUT), config->pirqa_routing); write8((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIRQB_ROUT), config->pirqb_routing); write8((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIRQC_ROUT), config->pirqc_routing); write8((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIRQD_ROUT), config->pirqd_routing); write8((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIRQE_ROUT), config->pirqe_routing); write8((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIRQF_ROUT), config->pirqf_routing); write8((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIRQG_ROUT), config->pirqg_routing); write8((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIRQH_ROUT), config->pirqh_routing); /* Initialize device's Interrupt Routings */ write16((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIR00), config->ir00_routing); write16((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIR01), config->ir01_routing); write16((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIR02), config->ir02_routing); write16((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIR03), config->ir03_routing); write16((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIR04), config->ir04_routing); write16((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIR05), config->ir05_routing); write16((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIR06), config->ir06_routing); write16((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIR07), config->ir07_routing); write16((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIR08), config->ir08_routing); write16((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIR09), config->ir09_routing); write16((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIR10), config->ir10_routing); write16((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIR11), config->ir11_routing); write16((void *)PCH_PCR_ADDRESS(PID_ITSS, PCR_ITSS_PIR12), config->ir12_routing); /* Initialize device's Interrupt Polarity Control */ write32((void *)PCH_PCR_ADDRESS(PID_ITSS, PCH_PCR_ITSS_IPC0), config->ipc0); write32((void *)PCH_PCR_ADDRESS(PID_ITSS, PCH_PCR_ITSS_IPC1), config->ipc1); write32((void *)PCH_PCR_ADDRESS(PID_ITSS, PCH_PCR_ITSS_IPC2), config->ipc2); write32((void *)PCH_PCR_ADDRESS(PID_ITSS, PCH_PCR_ITSS_IPC3), config->ipc3); for (irq_dev = all_devices; irq_dev; irq_dev = irq_dev->next) { int devfn = irq_dev->path.pci.devfn; u8 int_pin = 0, int_line = 0; if (!irq_dev->enabled || irq_dev->path.type != DEVICE_PATH_PCI) continue; int_pin = pci_read_config8(irq_dev, PCI_INTERRUPT_PIN); int_line = dnv_get_int_line(irq_dev); printk(BIOS_DEBUG, "%s: %02x:%02x.%d pin %d int line %d\n", __func__, irq_dev->bus->secondary, devfn >> 3, devfn & 0x7, int_pin, int_line); pci_write_config8(irq_dev, PCI_INTERRUPT_LINE, int_line); } } static void pci_p2sb_read_resources(struct device *dev) { struct resource *res; /* Add MMIO resource * Use 0xda as an unused index for PCR BAR. */ res = new_resource(dev, 0xda); res->base = DEFAULT_PCR_BASE; res->size = 16 * 1024 * 1024; /* 16MB PCR config space */ res->flags = IORESOURCE_MEM | IORESOURCE_FIXED | IORESOURCE_STORED | IORESOURCE_ASSIGNED; printk(BIOS_DEBUG, "Adding P2SB PCR config space BAR 0x%08lx-0x%08lx.\n", (unsigned long)(res->base), (unsigned long)(res->base + res->size)); /* Add MMIO resource * Use 0xdb as an unused index for IOAPIC. */ res = new_resource(dev, 0xdb); /* IOAPIC */ res->base = IO_APIC_ADDR; res->size = 0x00001000; res->flags = IORESOURCE_MEM | IORESOURCE_ASSIGNED | IORESOURCE_FIXED; } static void pch_enable_serial_irqs(struct device *dev) { /* Set packet length and toggle silent mode bit for one frame. */ pci_write_config8(dev, SERIRQ_CNTL, (1 << 7) | (1 << 6) | ((21 - 17) << 2) | (0 << 0)); #if !CONFIG(SERIRQ_CONTINUOUS_MODE) pci_write_config8(dev, SERIRQ_CNTL, (1 << 7) | (0 << 6) | ((21 - 17) << 2) | (0 << 0)); #endif } static void lpc_init(struct device *dev) { printk(BIOS_DEBUG, "pch: %s\n", __func__); /* Get the base address */ /* Set the value for PCI command register. */ pci_write_config16(dev, PCI_COMMAND, PCI_COMMAND_SPECIAL | PCI_COMMAND_MASTER | PCI_COMMAND_MEMORY | PCI_COMMAND_IO); /* Serial IRQ initialization. */ pch_enable_serial_irqs(dev); /* IO APIC initialization. */ pch_enable_ioapic(dev); /* Setup the PIRQ. */ pch_pirq_init(dev); } static void pch_lpc_add_mmio_resources(struct device *dev) { /* TODO */ } static void pch_lpc_add_io_resources(struct device *dev) { struct resource *res; u8 io_index = 0; /* Add an extra subtractive resource for both memory and I/O. */ res = new_resource(dev, IOINDEX_SUBTRACTIVE(io_index++, 0)); res->base = 0; res->size = 0x1000; res->flags = IORESOURCE_IO | IORESOURCE_SUBTRACTIVE | IORESOURCE_ASSIGNED | IORESOURCE_FIXED; res = new_resource(dev, IOINDEX_SUBTRACTIVE(io_index++, 0)); res->base = 0xff000000; res->size = 0x01000000; /* 16 MB for flash */ res->flags = IORESOURCE_MEM | IORESOURCE_SUBTRACTIVE | IORESOURCE_ASSIGNED | IORESOURCE_FIXED; } static void lpc_read_resources(struct device *dev) { /* Get the normal PCI resources of this device. */ pci_dev_read_resources(dev); /* Add non-standard MMIO resources. */ pch_lpc_add_mmio_resources(dev); /* Add IO resources. */ pch_lpc_add_io_resources(dev); /* Add MMIO resource for IOAPIC. */ pci_p2sb_read_resources(dev); } static void pch_decode_init(struct device *dev) { /* TODO */ } static void lpc_enable_resources(struct device *dev) { pch_decode_init(dev); pci_dev_enable_resources(dev); } /* Set bit in Function Disable register to hide this device */ static void pch_hide_devfn(uint32_t devfn) { /* TODO */ } void southcluster_enable_dev(struct device *dev) { u16 reg16; if (!dev->enabled) { printk(BIOS_DEBUG, "%s: Disabling device\n", dev_path(dev)); /* Ensure memory, io, and bus master are all disabled */ reg16 = pci_read_config16(dev, PCI_COMMAND); reg16 &= ~(PCI_COMMAND_MASTER | PCI_COMMAND_MEMORY | PCI_COMMAND_IO); pci_write_config16(dev, PCI_COMMAND, reg16); /* Hide this device if possible */ pch_hide_devfn(dev->path.pci.devfn); } else { /* Enable SERR */ pci_or_config16(dev, PCI_COMMAND, PCI_COMMAND_SERR); } } static struct device_operations device_ops = { .read_resources = lpc_read_resources, .set_resources = pci_dev_set_resources, #if CONFIG(HAVE_ACPI_TABLES) .write_acpi_tables = southcluster_write_acpi_tables, #endif .enable_resources = lpc_enable_resources, .init = lpc_init, .enable = southcluster_enable_dev, .scan_bus = scan_static_bus, .ops_pci = &soc_pci_ops, }; static const struct pci_driver lpc_driver __pci_driver = { .ops = &device_ops, .vendor = PCI_VID_INTEL, .device = PCI_DID_INTEL_DNV_LPC, }; static void finalize_chipset(void *unused) { apm_control(APM_CNT_FINALIZE); } BOOT_STATE_INIT_ENTRY(BS_OS_RESUME, BS_ON_ENTRY, finalize_chipset, NULL); BOOT_STATE_INIT_ENTRY(BS_PAYLOAD_LOAD, BS_ON_EXIT, finalize_chipset, NULL);
coreboot/coreboot
src/soc/intel/denverton_ns/lpc.c
C
gpl-2.0
15,711
<?php /** * @package DigiStore Joomla Extension * @author foobla.com * @version $Revision: 341 $ * @lastmodified $LastChangedDate: 2013-10-10 14:28:28 +0200 (Thu, 10 Oct 2013) $ * @copyright Copyright (C) 2013 foobla.com. All rights reserved. * @license GNU/GPLv3 */ defined ('_JEXEC') or die ("Go away."); jimport('joomla.application.component.controller'); class digistoreController extends JControllerLegacy { var $_customer = null; function __construct() { parent::__construct(); $ajax_req = JRequest::getVar("no_html", 0, "request"); $this->_customer = new digistoreSessionHelper(); $document = JFactory::getDocument(); $document->addStyleSheet(JURI::root()."components/com_digistore/assets/css/digistore.css"); $document->addStyleSheet(JURI::root().'components/com_digistore/assets/css/digistore_cart_lic_orders.css'); $document->addStyleSheet(JURI::root().'components/com_digistore/assets/css/bootstrap.css'); $document->addStyleSheet(JURI::root().'components/com_digistore/assets/css/bootstrap-responsive.css'); } function display($cachable = false, $urlparams = false){ parent::display(); } function debugStop($msg = ''){ $mainframe=JFactory::getApplication(); echo $msg; $mainframe->close(); } function breadcrumbs(){ $Itemid = JRequest::getInt("Itemid", 0); $mainframe=JFactory::getApplication(); // Get the PathWay object from the application $pw = $mainframe->getPathway(); $db = JFactory::getDBO(); $cids = JRequest::getVar('cid', 0, '', 'array'); $cid = intval($cids[0]); $pids = JRequest::getVar('pid', 0, '', 'array'); $pid = intval($pids[0]); $c = JRequest::getVar("controller", ""); $t = JRequest::getVar("task", ""); if($c != "digistoreLicenses" && $c != "digistoreOrders") { $sql = "select name, parent_id from #__digistore_categories where id=".intval($cid); $db->setQuery($sql); $res = $db->loadObjectList(); $res = $res[0]; $cname = $res->name; $parent_id = $res->parent_id; $sql = "select name from #__digistore_products where id=".intval($pid); $db->setQuery($sql); $pname = $db->loadResult(); } else{ $cname = $cid; $pname = $pid; } $link = JRoute::_("index.php?option=com_digistore&controller=digistoreCategories&Itemid".$Itemid); $name = "Category List"; $pw->addItem($name, $link); $bc_added = 0; if($c == "digistoreCategories"){ if($parent_id > 0){ $sql = "select name from #__digistore_categories where id=".intval($parent_id); $db->setQuery($sql); $name = $db->loadResult(); $link = JRoute::_("index.php?option=com_digistore&controller=digistoreCategories&task=list&cid=" . $parent_id . "&Itemid=" . $Itemid); $pw->addItem($name, $link); $bc_added = 1; } } if($c == "digistoreProducts"){ if($t == "list"){ $link = JRoute::_("index.php?option=com_digistore&controller=digistoreProducts&task=list&cid=".$parent_id."&Itemid=".$Itemid); $pw->addItem($cname, $link); $bc_added = 1; } if($t == "show"){ $link = JRoute::_("index.php?option=com_digistore&controller=digistoreProducts&task=list&cid=" . $parent_id . "&Itemid=" . $Itemid); $pw->addItem($cname, $link); $bc_added = 1; } } if($c == "digistoreCart"){ $link = JRoute::_("index.php?option=com_digistore&controller=digistoreCart&task=showCart&Itemid=" . $Itemid); $name = "Cart"; $pw->addItem($name, $link); if($t == "checkout"){ $link = ""; $name = "Checkout"; $pw->addItem($name, $link); } $bc_added = 1; } if(strlen(trim($c)) > 0 && $bc_added == 0 && $c != "digistoreCategories"){ $link = ""; $name = $c; $pw->addItem($name, $link); } } }
ryanv732/cleanease
components/com_digistore/controller.php
PHP
gpl-2.0
3,681
package gr.uoa.di.scan.thesis.entity; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.PrePersist; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity @Table(name="Comments") public class Comment { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; @Column(nullable=false) private String body; @Column(insertable=true,updatable=false,nullable=false) @Temporal(TemporalType.TIMESTAMP) private Date dateCreated; @ManyToOne @JoinColumn(name="userId",insertable=true,updatable=false,nullable=false) private User postedBy; @ManyToOne @JoinColumn(name="postId",insertable=true,updatable=false,nullable=true) private Post postedInPost; @ManyToOne @JoinColumn(name="commentId",insertable=true,updatable=false,nullable=true) private Comment postedInComment; @OneToMany(mappedBy="postedInComment",cascade=CascadeType.ALL) private Set<Comment> comments = new HashSet<Comment>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public Date getDateCreated() { return dateCreated; } public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } public User getPostedBy() { return postedBy; } public void setPostedBy(User postedBy) { this.postedBy = postedBy; } public Post getPostedInPost() { return postedInPost; } public void setPostedInPost(Post postedInPost) { this.postedInPost = postedInPost; } public Comment getPostedInComment() { return postedInComment; } public void setPostedInComment(Comment postedInComment) { this.postedInComment = postedInComment; } public Set<Comment> getComments() { return comments; } public void setComments(Set<Comment> comments) { this.comments = comments; } @PrePersist protected void dateCreated() { dateCreated = new Date(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Comment other = (Comment) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
nkalodimas/socioblog
src/main/java/gr/uoa/di/scan/thesis/entity/Comment.java
Java
gpl-2.0
2,869
<?php /** * CHRONOFORMS version 4.0 * Copyright (c) 2006 - 2011 Chrono_Man, ChronoEngine.com. All rights reserved. * Author: Chrono_Man (ChronoEngine.com) * @license GNU/GPL * Visit http://www.ChronoEngine.com for regular updates and information. **/ class ChronoFormsInputFile{ function load($clear){ if($clear){ $element_params = array( 'label_for' => 'input_file_{n}', 'label_id' => 'input_file_{n}_label', 'label_text' => 'Label Text', 'hide_label' => '0', 'label_over' => '0', 'multiline_start' => '0', 'multiline_add' => '0', 'input_name' => 'input_file_{n}', 'input_id' => '', 'ghost' => '1', 'ghost_value' => '', 'input_class' => '', 'input_title' => '', 'validations' => '', 'tooltip' => '', 'container_id' => 0, 'instructions' => ''); } return array('element_params' => $element_params); } function save($formdata_element = array(), $field_header = '', $formcontent_item_array = array()){ $formcontent_item_array['id'] = $formdata_element[$field_header.'_input_id']; $formcontent_item_array['class'] = $formdata_element[$field_header.'_input_class']; $formcontent_item_array['title'] = $formdata_element[$field_header.'_input_title']; $formcontent_item_array['ghost'] = $formdata_element[$field_header.'_ghost']; $formcontent_item_array['ghost_value'] = $formdata_element[$field_header.'_ghost_value']; $formcontent_item_array['label_over'] = $formdata_element[$field_header.'_label_over']; $formcontent_item_array['hide_label'] = $formdata_element[$field_header.'_hide_label']; $formcontent_item_array['multiline_start'] = $formdata_element[$field_header.'_multiline_start']; $formcontent_item_array['multiline_add'] = $formdata_element[$field_header.'_multiline_add']; $formcontent_item_array['validations'] = $formdata_element[$field_header.'_validations']; $formcontent_item_array['smalldesc'] = $formdata_element[$field_header.'_instructions']; $formcontent_item_array['tooltip'] = $formdata_element[$field_header.'_tooltip']; $formcontent_item_array['type'] = $formdata_element['type']; return $formcontent_item_array; } } ?>
acculitx/fleetmatrixsite
administrator/components/com_chronoforms/form_elements/input_file.php
PHP
gpl-2.0
2,271
package com.pTricKg.UnForgetter; import java.util.List; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.text.method.DigitsKeyListener; import com.pTricKg.UnForgetter.R; public class UnForgetterPreferences extends PreferenceActivity { @SuppressWarnings("deprecation") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT<Build.VERSION_CODES.HONEYCOMB) { addPreferencesFromResource(R.xml.task_preferences); } // Set the time default to a numeric number only EditTextPreference timeDefault = (EditTextPreference) findPreference(getString(R.string.pref_default_time_from_now_key)); timeDefault.getEditText().setKeyListener(DigitsKeyListener.getInstance()); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public void onBuildHeaders(List<Header> target) { loadHeadersFromResource(R.xml.task_preferences, target); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static class First extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.task_preferences); } } }
pTricKg/AndroidUnForgetter
UnForgetter/src/com/pTricKg/UnForgetter/UnForgetterPreferences.java
Java
gpl-2.0
1,475
// Copyright 2017 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #include "Core/WiiUtils.h" #include <algorithm> #include <cinttypes> #include <map> #include <memory> #include <optional> #include <sstream> #include <unordered_set> #include <utility> #include <vector> #include <pugixml.hpp> #include "Common/Assert.h" #include "Common/CommonPaths.h" #include "Common/CommonTypes.h" #include "Common/FileUtil.h" #include "Common/HttpRequest.h" #include "Common/Logging/Log.h" #include "Common/MsgHandler.h" #include "Common/NandPaths.h" #include "Common/StringUtil.h" #include "Common/Swap.h" #include "Core/CommonTitles.h" #include "Core/ConfigManager.h" #include "Core/IOS/Device.h" #include "Core/IOS/ES/ES.h" #include "Core/IOS/ES/Formats.h" #include "Core/IOS/IOS.h" #include "DiscIO/Enums.h" #include "DiscIO/NANDContentLoader.h" #include "DiscIO/WiiWad.h" namespace WiiUtils { bool InstallWAD(const std::string& wad_path) { const DiscIO::WiiWAD wad{wad_path}; if (!wad.IsValid()) { PanicAlertT("WAD installation failed: The selected file is not a valid WAD."); return false; } const auto tmd = wad.GetTMD(); IOS::HLE::Kernel ios; const auto es = ios.GetES(); IOS::HLE::Device::ES::Context context; IOS::HLE::ReturnCode ret; const bool checks_enabled = SConfig::GetInstance().m_enable_signature_checks; IOS::ES::TicketReader ticket = wad.GetTicket(); // Ensure the common key index is correct, as it's checked by IOS. ticket.FixCommonKeyIndex(); while ((ret = es->ImportTicket(ticket.GetBytes(), wad.GetCertificateChain())) < 0 || (ret = es->ImportTitleInit(context, tmd.GetBytes(), wad.GetCertificateChain())) < 0) { if (checks_enabled && ret == IOS::HLE::IOSC_FAIL_CHECKVALUE && AskYesNoT("This WAD has not been signed by Nintendo. Continue to import?")) { SConfig::GetInstance().m_enable_signature_checks = false; continue; } SConfig::GetInstance().m_enable_signature_checks = checks_enabled; PanicAlertT("WAD installation failed: Could not initialise title import."); return false; } SConfig::GetInstance().m_enable_signature_checks = checks_enabled; const bool contents_imported = [&]() { const u64 title_id = tmd.GetTitleId(); for (const IOS::ES::Content& content : tmd.GetContents()) { const std::vector<u8> data = wad.GetContent(content.index); if (es->ImportContentBegin(context, title_id, content.id) < 0 || es->ImportContentData(context, 0, data.data(), static_cast<u32>(data.size())) < 0 || es->ImportContentEnd(context, 0) < 0) { PanicAlertT("WAD installation failed: Could not import content %08x.", content.id); return false; } } return true; }(); if ((contents_imported && es->ImportTitleDone(context) < 0) || (!contents_imported && es->ImportTitleCancel(context) < 0)) { PanicAlertT("WAD installation failed: Could not finalise title import."); return false; } DiscIO::NANDContentManager::Access().ClearCache(); return true; } // Common functionality for system updaters. class SystemUpdater { public: virtual ~SystemUpdater() = default; protected: struct TitleInfo { u64 id; u16 version; }; std::string GetDeviceRegion(); std::string GetDeviceId(); bool ShouldInstallTitle(const TitleInfo& title); IOS::HLE::Kernel m_ios; }; std::string SystemUpdater::GetDeviceRegion() { // Try to determine the region from an installed system menu. const auto tmd = m_ios.GetES()->FindInstalledTMD(Titles::SYSTEM_MENU); if (tmd.IsValid()) { const DiscIO::Region region = tmd.GetRegion(); static const std::map<DiscIO::Region, std::string> regions = { {DiscIO::Region::NTSC_J, "JPN"}, {DiscIO::Region::NTSC_U, "USA"}, {DiscIO::Region::PAL, "EUR"}, {DiscIO::Region::NTSC_K, "KOR"}, {DiscIO::Region::UNKNOWN_REGION, "EUR"}}; return regions.at(region); } return ""; } std::string SystemUpdater::GetDeviceId() { u32 ios_device_id; if (m_ios.GetES()->GetDeviceId(&ios_device_id) < 0) return ""; return StringFromFormat("%" PRIu64, (u64(1) << 32) | ios_device_id); } bool SystemUpdater::ShouldInstallTitle(const TitleInfo& title) { const auto es = m_ios.GetES(); const auto installed_tmd = es->FindInstalledTMD(title.id); return !(installed_tmd.IsValid() && installed_tmd.GetTitleVersion() >= title.version && es->GetStoredContentsFromTMD(installed_tmd).size() == installed_tmd.GetNumContents()); } class OnlineSystemUpdater final : public SystemUpdater { public: OnlineSystemUpdater(UpdateCallback update_callback, const std::string& region); UpdateResult DoOnlineUpdate(); private: struct Response { std::string content_prefix_url; std::vector<TitleInfo> titles; }; Response GetSystemTitles(); Response ParseTitlesResponse(const std::vector<u8>& response) const; UpdateResult InstallTitleFromNUS(const std::string& prefix_url, const TitleInfo& title, std::unordered_set<u64>* updated_titles); // Helper functions to download contents from NUS. std::pair<IOS::ES::TMDReader, std::vector<u8>> DownloadTMD(const std::string& prefix_url, const TitleInfo& title); std::pair<std::vector<u8>, std::vector<u8>> DownloadTicket(const std::string& prefix_url, const TitleInfo& title); std::optional<std::vector<u8>> DownloadContent(const std::string& prefix_url, const TitleInfo& title, u32 cid); UpdateCallback m_update_callback; std::string m_requested_region; Common::HttpRequest m_http{std::chrono::minutes{3}}; }; OnlineSystemUpdater::OnlineSystemUpdater(UpdateCallback update_callback, const std::string& region) : m_update_callback(std::move(update_callback)), m_requested_region(region) { } OnlineSystemUpdater::Response OnlineSystemUpdater::ParseTitlesResponse(const std::vector<u8>& response) const { pugi::xml_document doc; pugi::xml_parse_result result = doc.load_buffer(response.data(), response.size()); if (!result) { ERROR_LOG(CORE, "ParseTitlesResponse: Could not parse response"); return {}; } // pugixml doesn't fully support namespaces and ignores them. const pugi::xml_node node = doc.select_node("//GetSystemUpdateResponse").node(); if (!node) { ERROR_LOG(CORE, "ParseTitlesResponse: Could not find response node"); return {}; } const int code = node.child("ErrorCode").text().as_int(); if (code != 0) { ERROR_LOG(CORE, "ParseTitlesResponse: Non-zero error code (%d)", code); return {}; } // libnup uses the uncached URL, not the cached one. However, that one is way, way too slow, // so let's use the cached endpoint. Response info; info.content_prefix_url = node.child("ContentPrefixURL").text().as_string(); // Disable HTTPS because we can't use it without a device certificate. info.content_prefix_url = ReplaceAll(info.content_prefix_url, "https://", "http://"); if (info.content_prefix_url.empty()) { ERROR_LOG(CORE, "ParseTitlesResponse: Empty content prefix URL"); return {}; } for (const pugi::xml_node& title_node : node.children("TitleVersion")) { const u64 title_id = std::stoull(title_node.child("TitleId").text().as_string(), nullptr, 16); const u16 title_version = static_cast<u16>(title_node.child("Version").text().as_uint()); info.titles.push_back({title_id, title_version}); } return info; } constexpr const char* GET_SYSTEM_TITLES_REQUEST_PAYLOAD = R"(<?xml version="1.0" encoding="UTF-8"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Body> <GetSystemUpdateRequest xmlns="urn:nus.wsapi.broadon.com"> <Version>1.0</Version> <MessageId>0</MessageId> <DeviceId></DeviceId> <RegionId></RegionId> </GetSystemUpdateRequest> </soapenv:Body> </soapenv:Envelope> )"; OnlineSystemUpdater::Response OnlineSystemUpdater::GetSystemTitles() { // Construct the request by loading the template first, then updating some fields. pugi::xml_document doc; pugi::xml_parse_result result = doc.load_string(GET_SYSTEM_TITLES_REQUEST_PAYLOAD); _assert_(result); // Nintendo does not really care about the device ID or verify that we *are* that device, // as long as it is a valid Wii device ID. const std::string device_id = GetDeviceId(); _assert_(doc.select_node("//DeviceId").node().text().set(device_id.c_str())); // Write the correct device region. const std::string region = m_requested_region.empty() ? GetDeviceRegion() : m_requested_region; _assert_(doc.select_node("//RegionId").node().text().set(region.c_str())); std::ostringstream stream; doc.save(stream); const std::string request = stream.str(); // Note: We don't use HTTPS because that would require the user to have // a device certificate which cannot be redistributed with Dolphin. // This is fine, because IOS has signature checks. const Common::HttpRequest::Response response = m_http.Post("http://nus.shop.wii.com/nus/services/NetUpdateSOAP", request, { {"SOAPAction", "urn:nus.wsapi.broadon.com/GetSystemUpdate"}, {"User-Agent", "wii libnup/1.0"}, {"Content-Type", "text/xml; charset=utf-8"}, }); if (!response) return {}; return ParseTitlesResponse(*response); } UpdateResult OnlineSystemUpdater::DoOnlineUpdate() { const Response info = GetSystemTitles(); if (info.titles.empty()) return UpdateResult::ServerFailed; // Download and install any title that is older than the NUS version. // The order is determined by the server response, which is: boot2, System Menu, IOSes, channels. // As we install any IOS required by titles, the real order is boot2, SM IOS, SM, IOSes, channels. std::unordered_set<u64> updated_titles; size_t processed = 0; for (const TitleInfo& title : info.titles) { if (!m_update_callback(processed++, info.titles.size(), title.id)) return UpdateResult::Cancelled; const UpdateResult res = InstallTitleFromNUS(info.content_prefix_url, title, &updated_titles); if (res != UpdateResult::Succeeded) { ERROR_LOG(CORE, "Failed to update %016" PRIx64 " -- aborting update", title.id); return res; } m_update_callback(processed, info.titles.size(), title.id); } if (updated_titles.empty()) { NOTICE_LOG(CORE, "Update finished - Already up-to-date"); return UpdateResult::AlreadyUpToDate; } NOTICE_LOG(CORE, "Update finished - %zu updates installed", updated_titles.size()); return UpdateResult::Succeeded; } UpdateResult OnlineSystemUpdater::InstallTitleFromNUS(const std::string& prefix_url, const TitleInfo& title, std::unordered_set<u64>* updated_titles) { // We currently don't support boot2 updates at all, so ignore any attempt to install it. if (title.id == Titles::BOOT2) return UpdateResult::Succeeded; if (!ShouldInstallTitle(title) || updated_titles->find(title.id) != updated_titles->end()) return UpdateResult::Succeeded; NOTICE_LOG(CORE, "Updating title %016" PRIx64, title.id); // Download the ticket and certificates. const auto ticket = DownloadTicket(prefix_url, title); if (ticket.first.empty() || ticket.second.empty()) { ERROR_LOG(CORE, "Failed to download ticket and certs"); return UpdateResult::DownloadFailed; } // Import the ticket. IOS::HLE::ReturnCode ret = IOS::HLE::IPC_SUCCESS; const auto es = m_ios.GetES(); if ((ret = es->ImportTicket(ticket.first, ticket.second)) < 0) { ERROR_LOG(CORE, "Failed to import ticket: error %d", ret); return UpdateResult::ImportFailed; } // Download the TMD. const auto tmd = DownloadTMD(prefix_url, title); if (!tmd.first.IsValid()) { ERROR_LOG(CORE, "Failed to download TMD"); return UpdateResult::DownloadFailed; } // Download and import any required system title first. const u64 ios_id = tmd.first.GetIOSId(); if (ios_id != 0 && IOS::ES::IsTitleType(ios_id, IOS::ES::TitleType::System)) { if (!es->FindInstalledTMD(ios_id).IsValid()) { WARN_LOG(CORE, "Importing required system title %016" PRIx64 " first", ios_id); const UpdateResult res = InstallTitleFromNUS(prefix_url, {ios_id, 0}, updated_titles); if (res != UpdateResult::Succeeded) { ERROR_LOG(CORE, "Failed to import required system title %016" PRIx64, ios_id); return res; } } } // Initialise the title import. IOS::HLE::Device::ES::Context context; if ((ret = es->ImportTitleInit(context, tmd.first.GetBytes(), tmd.second)) < 0) { ERROR_LOG(CORE, "Failed to initialise title import: error %d", ret); return UpdateResult::ImportFailed; } // Now download and install contents listed in the TMD. const std::vector<IOS::ES::Content> stored_contents = es->GetStoredContentsFromTMD(tmd.first); const UpdateResult import_result = [&]() { for (const IOS::ES::Content& content : tmd.first.GetContents()) { const bool is_already_installed = std::find_if(stored_contents.begin(), stored_contents.end(), [&content](const auto& stored_content) { return stored_content.id == content.id; }) != stored_contents.end(); // Do skip what is already installed on the NAND. if (is_already_installed) continue; if ((ret = es->ImportContentBegin(context, title.id, content.id)) < 0) { ERROR_LOG(CORE, "Failed to initialise import for content %08x: error %d", content.id, ret); return UpdateResult::ImportFailed; } const std::optional<std::vector<u8>> data = DownloadContent(prefix_url, title, content.id); if (!data) { ERROR_LOG(CORE, "Failed to download content %08x", content.id); return UpdateResult::DownloadFailed; } if (es->ImportContentData(context, 0, data->data(), static_cast<u32>(data->size())) < 0 || es->ImportContentEnd(context, 0) < 0) { ERROR_LOG(CORE, "Failed to import content %08x", content.id); return UpdateResult::ImportFailed; } } return UpdateResult::Succeeded; }(); const bool all_contents_imported = import_result == UpdateResult::Succeeded; if ((all_contents_imported && (ret = es->ImportTitleDone(context)) < 0) || (!all_contents_imported && (ret = es->ImportTitleCancel(context)) < 0)) { ERROR_LOG(CORE, "Failed to finalise title import: error %d", ret); return UpdateResult::ImportFailed; } if (!all_contents_imported) return import_result; updated_titles->emplace(title.id); return UpdateResult::Succeeded; } std::pair<IOS::ES::TMDReader, std::vector<u8>> OnlineSystemUpdater::DownloadTMD(const std::string& prefix_url, const TitleInfo& title) { const std::string url = (title.version == 0) ? prefix_url + StringFromFormat("/%016" PRIx64 "/tmd", title.id) : prefix_url + StringFromFormat("/%016" PRIx64 "/tmd.%u", title.id, title.version); const Common::HttpRequest::Response response = m_http.Get(url); if (!response) return {}; // Too small to contain both the TMD and a cert chain. if (response->size() <= sizeof(IOS::ES::TMDHeader)) return {}; const size_t tmd_size = sizeof(IOS::ES::TMDHeader) + sizeof(IOS::ES::Content) * Common::swap16(response->data() + offsetof(IOS::ES::TMDHeader, num_contents)); if (response->size() <= tmd_size) return {}; const auto tmd_begin = response->begin(); const auto tmd_end = tmd_begin + tmd_size; return {IOS::ES::TMDReader(std::vector<u8>(tmd_begin, tmd_end)), std::vector<u8>(tmd_end, response->end())}; } std::pair<std::vector<u8>, std::vector<u8>> OnlineSystemUpdater::DownloadTicket(const std::string& prefix_url, const TitleInfo& title) { const std::string url = prefix_url + StringFromFormat("/%016" PRIx64 "/cetk", title.id); const Common::HttpRequest::Response response = m_http.Get(url); if (!response) return {}; // Too small to contain both the ticket and a cert chain. if (response->size() <= sizeof(IOS::ES::Ticket)) return {}; const auto ticket_begin = response->begin(); const auto ticket_end = ticket_begin + sizeof(IOS::ES::Ticket); return {std::vector<u8>(ticket_begin, ticket_end), std::vector<u8>(ticket_end, response->end())}; } std::optional<std::vector<u8>> OnlineSystemUpdater::DownloadContent(const std::string& prefix_url, const TitleInfo& title, u32 cid) { const std::string url = prefix_url + StringFromFormat("/%016" PRIx64 "/%08x", title.id, cid); return m_http.Get(url); } UpdateResult DoOnlineUpdate(UpdateCallback update_callback, const std::string& region) { OnlineSystemUpdater updater{std::move(update_callback), region}; const UpdateResult result = updater.DoOnlineUpdate(); DiscIO::NANDContentManager::Access().ClearCache(); return result; } }
linkmauve/dolphin
Source/Core/Core/WiiUtils.cpp
C++
gpl-2.0
17,579
<?php // $Id: InvitationFileUploadPage.php 2434 2012-11-30 16:52:35Z ecgero $ Copyright (c) ConSked, LLC. All Rights Reserved. include('util/authenticateOrganizer.php'); require_once('db/Expo.php'); require_once('properties/constants.php'); require_once('section/FileUpload.php'); require_once('section/Menu.php'); require_once('swwat/gizmos/html.php'); require_once('swwat/gizmos/parse.php'); require_once('util/log.php'); require_once('util/session.php'); ?> <!DOCTYPE html> <html> <head> <meta http-equiv="cache-control" content="no-cache"/> <meta http-equiv="expires" content="31 Dec 2011 12:00:00 GMT"/> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <title><?php echo(SITE_NAME); ?> - Invitation File Upload Page</title> <link href="css/site.css" rel="stylesheet" type="text/css"> <link href="jquery/jquery-ui-1.8.20.custom.css" rel="stylesheet" type="text/css"> <script src="jquery/jquery-1.7.2.min.js"></script> <script src="jquery/jquery-ui-1.8.20.custom.min.js"></script> <script type="text/javascript"> var DISPLAY_FORMAT = 'DD dd, MM yy'; var DB_FORMAT = 'yy-mm-dd'; function init() { var stdate = $('[name=<?php echo PARAM_STOPTIME;?>]'); var d = $.datepicker.parseDate(DB_FORMAT, stdate.val()); stdate.val($.datepicker.formatDate(DISPLAY_FORMAT, d)); }; // init </script> </head> <body onload="init()"> <div id="container"> <?php $expo = getExpoCurrent(); $expDate = swwat_parse_date(html_entity_decode($_SESSION[PARAM_STOPTIME]), true); if (is_null($expDate)) { $expDate = $expo->startTime; // default $_SESSION[PARAM_STOPTIME] = $expDate; } $withCode = isset($_SESSION[PARAM_WITHCODE]); $uniqueCode = isset($_SESSION[PARAM_UNIQUE]); // ok, start the html include('section/header.php'); ?> <div id="main"> <?php if (!is_null($expo->expoid)) { include('section/LinkExpo.php'); } ?> <div id="invitation_fileupload"> <!-- form method="POST" id="invitationpage_invite" --> <table> <tr><td class="fieldTitle">Date Invitation Expires:</td> <td><input readonly="readonly" type="text" name="<?php echo PARAM_STOPTIME; ?>" value="<?php echo swwat_format_isodate($expDate); ?>" size="25"/></td> </tr> <tr><td class="fieldTitle">Require generic code:</td> <td><?php swwat_createRadioOption(PARAM_WITHCODE, array(PARAM_WITHCODE, ""), SWWAT_CHECKBOX, $withCode, TRUE); ?></td> </tr> <tr><td class="fieldTitle">Make code unique:</td> <td><?php swwat_createRadioOption(PARAM_UNIQUE, array(PARAM_UNIQUE, ""), SWWAT_CHECKBOX, $uniqueCode, TRUE); ?></td> </tr> <tr><td class="fieldTitle">CSV File Format:</td> <td><?php swwat_createSelect(0, "CSVFileFormat", array(array("FiveDegrees", "Five Degrees")), "FiveDegrees" , TRUE); ?></td> </tr> <tr><td></td><td></td></tr> <tr><td class="fieldTitle">Upload File:</td><td><?php createFileUploadForm("InvitationFileUploadAction.php", PARAM_DOCUMENT); ?></td></tr> </table> <!-- /form --> </div><!-- invitation_fileupload --> <div id="invitation_fileupload_results"> <h5>File Invitation Results</h5> <table> <tr><th class='rowTitle'>line#</th><th class='rowTitle'>email</th><th class='rowTitle'>data</th><th class='rowTitle'>message</th><th class='rowTitle'>note</th></tr> <?php // get rid of annoying notice if (isset($_SESSION[PARAM_MESSAGE])) { echo $_SESSION[PARAM_MESSAGE]; } ?> </table> </div> </div><!-- main --> <?php $menuItemArray = array(); $menuItemArray[] = MENU_VIEW_SITEADMIN; $menuItemArray[] = MENU_VIEW_WORKERLIST; Menu::addMenu($menuItemArray); include('section/footer.php'); ?> </div><!-- container --> </body></html>
ConSked/scheduler
pages/InvitationFileUploadPage.php
PHP
gpl-2.0
3,935
# FaceRnalysis Simple script for Data Analysis of Facebook pages using R
MightyLight/FaceRnalysis
README.md
Markdown
gpl-2.0
73
<?php /** * 用于显示课程列表及搜索结果 * * Created by PhpStorm. * User: lin * Date: 16-6-3 * Time: 上午11:36 */ class Course_list extends CI_Controller{ public function __construct(){ parent::__construct(); } public function index(){ $this->load->library('session'); $this->load->model('Course_model'); $intPage = $this->input->get('page', true) ? $this->input->get('page', true) : 0; $intLimit = $this->input->get('limit', true) ? $this->input->get('limit', true) : 20; $arrSchoolList = array(); if ($this->session->userdata('user_school')){ $arrSchoolList = json_decode($this->session->userdata('user_school'), true); } //获取get $strLessonSearch = $this->input->get('lesson_search', true); if (!empty($strLessonSearch)){ $arrCourseList = array(); $arrCourseRet = $this->Course_model->searchCourse($strLessonSearch, $arrSchoolList, false, $intPage, $intLimit); //合并列表 foreach ($arrCourseRet as $arrCourseData){ //以group_id为key $arrCourseList[$arrCourseData['lesson_group_id']][$arrCourseData['lesson_level']] = $arrCourseData; } //需要补充获取level0列表,即上面的查询没有查到level 0主课内容 $arrGetLevel0List = array(); foreach ($arrCourseList as $intGroupId => $arrCourseGroupDataData){ if (!isset($arrCourseGroupDataData[0])){ $arrGetLevel0List[] = $intGroupId; } } //合并列表 if (!empty($arrGetLevel0List)){ $arrRetLevel0 = $this->Course_model->getMainCourse($arrGetLevel0List); foreach ($arrRetLevel0 as $arrRetLevel0Data){ $arrCourseList[$arrRetLevel0Data['lesson_group_id']][0] = $arrRetLevel0Data; } } //查询标记 $boolSearch = true; } else { $arrCourseList = $this->Course_model->getCourseList(1, $arrSchoolList, $intPage, $intLimit); $boolSearch = false; } $this->load->view('course_list_view', array( 'bool_search' => $boolSearch, 'course_list' => $arrCourseList, )); } }
SUTFutureCoder/Cloud-platform-for-teaching-resources
application/controllers/Course_list.php
PHP
gpl-2.0
2,380
<?php namespace Drupal\Tests\Core\Entity\TypedData; use Drupal\Core\DependencyInjection\ContainerBuilder; use Drupal\Core\Entity\EntityFieldManagerInterface; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Entity\Plugin\DataType\EntityAdapter; use Drupal\Core\Field\BaseFieldDefinition; use Drupal\Core\Language\LanguageInterface; use Drupal\Core\TypedData\Exception\MissingDataException; use Drupal\Core\TypedData\TypedDataManagerInterface; use Drupal\Tests\UnitTestCase; use Drupal\Core\Language\Language; /** * @coversDefaultClass \Drupal\Core\Entity\Plugin\DataType\EntityAdapter * @group Entity * @group TypedData */ class EntityAdapterUnitTest extends UnitTestCase { /** * The bundle used for testing. * * @var string */ protected $bundle; /** * The content entity used for testing. * * @var \Drupal\Core\Entity\ContentEntityBase|\PHPUnit_Framework_MockObject_MockObject */ protected $entity; /** * The content entity adapter under test. * * @var \Drupal\Core\Entity\Plugin\DataType\EntityAdapter */ protected $entityAdapter; /** * The entity type used for testing. * * @var \Drupal\Core\Entity\EntityTypeInterface|\PHPUnit_Framework_MockObject_MockObject */ protected $entityType; /** * The entity type manager used for testing. * * @var \Drupal\Core\Entity\EntityTypeManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ protected $entityTypeManager; /** * * @var \Drupal\Core\Entity\EntityFieldManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ protected $entityFieldManager; /** * The type ID of the entity under test. * * @var string */ protected $entityTypeId; /** * The typed data manager used for testing. * * @var \Drupal\Core\TypedData\TypedDataManager|\PHPUnit_Framework_MockObject_MockObject */ protected $typedDataManager; /** * The field item list returned by the typed data manager. * * @var \Drupal\Core\Field\FieldItemListInterface|\PHPUnit_Framework_MockObject_MockObject */ protected $fieldItemList; /** * The field type manager used for testing. * * @var \Drupal\Core\Field\FieldTypePluginManager|\PHPUnit_Framework_MockObject_MockObject */ protected $fieldTypePluginManager; /** * The language manager. * * @var \Drupal\Core\Language\LanguageManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ protected $languageManager; /** * The UUID generator used for testing. * * @var \Drupal\Component\Uuid\UuidInterface|\PHPUnit_Framework_MockObject_MockObject */ protected $uuid; /** * The entity ID. * * @var int */ protected $id; /** * Field definitions. * * @var \Drupal\Core\Field\BaseFieldDefinition[] */ protected $fieldDefinitions; /** * {@inheritdoc} */ protected function setUp() { $this->id = 1; $values = [ 'id' => $this->id, 'uuid' => '3bb9ee60-bea5-4622-b89b-a63319d10b3a', 'defaultLangcode' => [LanguageInterface::LANGCODE_DEFAULT => 'en'], ]; $this->entityTypeId = $this->randomMachineName(); $this->bundle = $this->randomMachineName(); $this->entityType = $this->createMock('\Drupal\Core\Entity\EntityTypeInterface'); $this->entityType->expects($this->any()) ->method('getKeys') ->will($this->returnValue([ 'id' => 'id', 'uuid' => 'uuid', ])); $this->entityTypeManager = $this->createMock(EntityTypeManagerInterface::class); $this->entityTypeManager->expects($this->any()) ->method('getDefinition') ->with($this->entityTypeId) ->will($this->returnValue($this->entityType)); $this->uuid = $this->createMock('\Drupal\Component\Uuid\UuidInterface'); $this->typedDataManager = $this->createMock(TypedDataManagerInterface::class); $this->typedDataManager->expects($this->any()) ->method('getDefinition') ->with('entity') ->will($this->returnValue(['class' => '\Drupal\Core\Entity\Plugin\DataType\EntityAdapter'])); $this->typedDataManager->expects($this->any()) ->method('getDefaultConstraints') ->willReturn([]); $validation_constraint_manager = $this->getMockBuilder('\Drupal\Core\Validation\ConstraintManager') ->disableOriginalConstructor() ->getMock(); $validation_constraint_manager->expects($this->any()) ->method('create') ->willReturn([]); $this->typedDataManager->expects($this->any()) ->method('getValidationConstraintManager') ->willReturn($validation_constraint_manager); $not_specified = new Language(['id' => LanguageInterface::LANGCODE_NOT_SPECIFIED, 'locked' => TRUE]); $this->languageManager = $this->createMock('\Drupal\Core\Language\LanguageManagerInterface'); $this->languageManager->expects($this->any()) ->method('getLanguages') ->will($this->returnValue([LanguageInterface::LANGCODE_NOT_SPECIFIED => $not_specified])); $this->languageManager->expects($this->any()) ->method('getLanguage') ->with(LanguageInterface::LANGCODE_NOT_SPECIFIED) ->will($this->returnValue($not_specified)); $this->fieldTypePluginManager = $this->getMockBuilder('\Drupal\Core\Field\FieldTypePluginManager') ->disableOriginalConstructor() ->getMock(); $this->fieldTypePluginManager->expects($this->any()) ->method('getDefaultStorageSettings') ->will($this->returnValue([])); $this->fieldTypePluginManager->expects($this->any()) ->method('getDefaultFieldSettings') ->will($this->returnValue([])); $this->fieldItemList = $this->createMock('\Drupal\Core\Field\FieldItemListInterface'); $this->fieldTypePluginManager->expects($this->any()) ->method('createFieldItemList') ->willReturn($this->fieldItemList); $this->entityFieldManager = $this->getMockForAbstractClass(EntityFieldManagerInterface::class); $container = new ContainerBuilder(); $container->set('entity_type.manager', $this->entityTypeManager); $container->set('entity_field.manager', $this->entityFieldManager); $container->set('uuid', $this->uuid); $container->set('typed_data_manager', $this->typedDataManager); $container->set('language_manager', $this->languageManager); $container->set('plugin.manager.field.field_type', $this->fieldTypePluginManager); \Drupal::setContainer($container); $this->fieldDefinitions = [ 'id' => BaseFieldDefinition::create('integer'), 'revision_id' => BaseFieldDefinition::create('integer'), ]; $this->entityFieldManager->expects($this->any()) ->method('getFieldDefinitions') ->with($this->entityTypeId, $this->bundle) ->will($this->returnValue($this->fieldDefinitions)); $this->entity = $this->getMockForAbstractClass('\Drupal\Core\Entity\ContentEntityBase', [$values, $this->entityTypeId, $this->bundle]); $this->entityAdapter = EntityAdapter::createFromEntity($this->entity); } /** * @covers ::getConstraints */ public function testGetConstraints() { $this->assertInternalType('array', $this->entityAdapter->getConstraints()); } /** * @covers ::getName */ public function testGetName() { $this->assertNull($this->entityAdapter->getName()); } /** * @covers ::getRoot */ public function testGetRoot() { $this->assertSame(spl_object_hash($this->entityAdapter), spl_object_hash($this->entityAdapter->getRoot())); } /** * @covers ::getPropertyPath */ public function testGetPropertyPath() { $this->assertSame('', $this->entityAdapter->getPropertyPath()); } /** * @covers ::getParent */ public function testGetParent() { $this->assertNull($this->entityAdapter->getParent()); } /** * @covers ::setContext */ public function testSetContext() { $name = $this->randomMachineName(); $parent = $this->createMock('\Drupal\Core\TypedData\TraversableTypedDataInterface'); // Our mocked entity->setContext() returns NULL, so assert that. $this->assertNull($this->entityAdapter->setContext($name, $parent)); $this->assertEquals($name, $this->entityAdapter->getName()); $this->assertEquals($parent, $this->entityAdapter->getParent()); } /** * @covers ::getValue */ public function testGetValue() { $this->assertEquals($this->entity, $this->entityAdapter->getValue()); } /** * @covers ::getEntity */ public function testGetEntity() { $this->assertSame($this->entity, $this->entityAdapter->getEntity()); } /** * @covers ::setValue */ public function testSetValue() { $this->entityAdapter->setValue(NULL); $this->assertNull($this->entityAdapter->getValue()); } /** * @covers ::get */ public function testGet() { $this->assertInstanceOf('\Drupal\Core\Field\FieldItemListInterface', $this->entityAdapter->get('id')); } /** * @covers ::get */ public function testGetInvalidField() { $this->expectException(\InvalidArgumentException::class); $this->entityAdapter->get('invalid'); } /** * @covers ::get */ public function testGetWithoutData() { $this->entityAdapter->setValue(NULL); $this->expectException(MissingDataException::class); $this->entityAdapter->get('id'); } /** * @covers ::set */ public function testSet() { $id_items = [['value' => $this->id + 1]]; $this->fieldItemList->expects($this->once()) ->method('setValue') ->with($id_items); $this->entityAdapter->set('id', $id_items); } /** * @covers ::set */ public function testSetWithoutData() { $this->entityAdapter->setValue(NULL); $id_items = [['value' => $this->id + 1]]; $this->expectException(MissingDataException::class); $this->entityAdapter->set('id', $id_items); } /** * @covers ::getProperties */ public function testGetProperties() { $fields = $this->entityAdapter->getProperties(); $this->assertInstanceOf('Drupal\Core\Field\FieldItemListInterface', $fields['id']); $this->assertInstanceOf('Drupal\Core\Field\FieldItemListInterface', $fields['revision_id']); } /** * @covers ::toArray */ public function testToArray() { $array = $this->entityAdapter->toArray(); // Mock field objects return NULL values, so test keys only. $this->assertArrayHasKey('id', $array); $this->assertArrayHasKey('revision_id', $array); $this->assertEquals(count($array), 2); } /** * @covers ::toArray */ public function testToArrayWithoutData() { $this->entityAdapter->setValue(NULL); $this->expectException(MissingDataException::class); $this->entityAdapter->toArray(); } /** * @covers ::isEmpty */ public function testIsEmpty() { $this->assertFalse($this->entityAdapter->isEmpty()); $this->entityAdapter->setValue(NULL); $this->assertTrue($this->entityAdapter->isEmpty()); } /** * @covers ::onChange */ public function testOnChange() { $entity = $this->createMock('\Drupal\Core\Entity\ContentEntityInterface'); $entity->expects($this->once()) ->method('onChange') ->with('foo') ->willReturn(NULL); $this->entityAdapter->setValue($entity); $this->entityAdapter->onChange('foo'); } /** * @covers ::getDataDefinition */ public function testGetDataDefinition() { $definition = $this->entityAdapter->getDataDefinition(); $this->assertInstanceOf('\Drupal\Core\Entity\TypedData\EntityDataDefinitionInterface', $definition); $this->assertEquals($definition->getEntityTypeId(), $this->entityTypeId); $this->assertEquals($definition->getBundles(), [$this->bundle]); } /** * @covers ::getString */ public function testGetString() { $entity = $this->createMock('\Drupal\Core\Entity\ContentEntityInterface'); $entity->expects($this->once()) ->method('label') ->willReturn('foo'); $this->entityAdapter->setValue($entity); $this->assertEquals('foo', $this->entityAdapter->getString()); $this->entityAdapter->setValue(NULL); $this->assertEquals('', $this->entityAdapter->getString()); } /** * @covers ::applyDefaultValue */ public function testApplyDefaultValue() { // For each field on the entity the mock method has to be invoked once. $this->fieldItemList->expects($this->exactly(2)) ->method('applyDefaultValue'); $this->entityAdapter->applyDefaultValue(); } /** * @covers ::getIterator */ public function testGetIterator() { // Content entity test. $iterator = $this->entityAdapter->getIterator(); $fields = iterator_to_array($iterator); $this->assertArrayHasKey('id', $fields); $this->assertArrayHasKey('revision_id', $fields); $this->assertEquals(count($fields), 2); $this->entityAdapter->setValue(NULL); $this->assertEquals(new \ArrayIterator([]), $this->entityAdapter->getIterator()); } }
rsathishkumar/drupal8
core/tests/Drupal/Tests/Core/Entity/TypedData/EntityAdapterUnitTest.php
PHP
gpl-2.0
12,959
obj-$(CONFIG_F2FS_FS) += f2fs.o f2fs-y := dir.o file.o inode.o namei.o hash.o super.o inline.o f2fs-y += checkpoint.o gc.o data.o node.o segment.o recovery.o f2fs-y += shrinker.o extent_cache.o f2fs-y += f2fs_dump_info.o f2fs-$(CONFIG_F2FS_STAT_FS) += debug.o f2fs-$(CONFIG_F2FS_FS_XATTR) += xattr.o f2fs-$(CONFIG_F2FS_FS_POSIX_ACL) += acl.o f2fs-$(CONFIG_F2FS_IO_TRACE) += trace.o f2fs-$(CONFIG_F2FS_FS_ENCRYPTION) += crypto_policy.o crypto.o \ crypto_key.o crypto_fname.o
Honor8Dev/android_kernel_huawei_FRD-L04
fs/f2fs/Makefile
Makefile
gpl-2.0
481
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <CL/cl.h> unsigned char *read_buffer(char *file_name, size_t *size_ptr) { FILE *f; unsigned char *buf; size_t size; /* Open file */ f = fopen(file_name, "rb"); if (!f) return NULL; /* Obtain file size */ fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, 0, SEEK_SET); /* Allocate and read buffer */ buf = malloc(size + 1); fread(buf, 1, size, f); buf[size] = '\0'; /* Return size of buffer */ if (size_ptr) *size_ptr = size; /* Return buffer */ return buf; } void write_buffer(char *file_name, const char *buffer, size_t buffer_size) { FILE *f; /* Open file */ f = fopen(file_name, "w+"); /* Write buffer */ if(buffer) fwrite(buffer, 1, buffer_size, f); /* Close file */ fclose(f); } int main(int argc, char const *argv[]) { /* Get platform */ cl_platform_id platform; cl_uint num_platforms; cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformIDs' failed\n"); exit(1); } printf("Number of platforms: %d\n", num_platforms); printf("platform=%p\n", platform); /* Get platform name */ char platform_name[100]; ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformInfo' failed\n"); exit(1); } printf("platform.name='%s'\n\n", platform_name); /* Get device */ cl_device_id device; cl_uint num_devices; ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceIDs' failed\n"); exit(1); } printf("Number of devices: %d\n", num_devices); printf("device=%p\n", device); /* Get device name */ char device_name[100]; ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name), device_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceInfo' failed\n"); exit(1); } printf("device.name='%s'\n", device_name); printf("\n"); /* Create a Context Object */ cl_context context; context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateContext' failed\n"); exit(1); } printf("context=%p\n", context); /* Create a Command Queue Object*/ cl_command_queue command_queue; command_queue = clCreateCommandQueue(context, device, 0, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateCommandQueue' failed\n"); exit(1); } printf("command_queue=%p\n", command_queue); printf("\n"); /* Program source */ unsigned char *source_code; size_t source_length; /* Read program from 'rhadd_short16short16.cl' */ source_code = read_buffer("rhadd_short16short16.cl", &source_length); /* Create a program */ cl_program program; program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateProgramWithSource' failed\n"); exit(1); } printf("program=%p\n", program); /* Build program */ ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL); if (ret != CL_SUCCESS ) { size_t size; char *log; /* Get log size */ clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size); /* Allocate log and print */ log = malloc(size); clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL); printf("error: call to 'clBuildProgram' failed:\n%s\n", log); /* Free log and exit */ free(log); exit(1); } printf("program built\n"); printf("\n"); /* Create a Kernel Object */ cl_kernel kernel; kernel = clCreateKernel(program, "rhadd_short16short16", &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateKernel' failed\n"); exit(1); } /* Create and allocate host buffers */ size_t num_elem = 10; /* Create and init host side src buffer 0 */ cl_short16 *src_0_host_buffer; src_0_host_buffer = malloc(num_elem * sizeof(cl_short16)); for (int i = 0; i < num_elem; i++) src_0_host_buffer[i] = (cl_short16){{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}}; /* Create and init device side src buffer 0 */ cl_mem src_0_device_buffer; src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_short16), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_short16), src_0_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create and init host side src buffer 1 */ cl_short16 *src_1_host_buffer; src_1_host_buffer = malloc(num_elem * sizeof(cl_short16)); for (int i = 0; i < num_elem; i++) src_1_host_buffer[i] = (cl_short16){{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}}; /* Create and init device side src buffer 1 */ cl_mem src_1_device_buffer; src_1_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_short16), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_1_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_short16), src_1_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create host dst buffer */ cl_short16 *dst_host_buffer; dst_host_buffer = malloc(num_elem * sizeof(cl_short16)); memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_short16)); /* Create device dst buffer */ cl_mem dst_device_buffer; dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_short16), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create dst buffer\n"); exit(1); } /* Set kernel arguments */ ret = CL_SUCCESS; ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer); ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &src_1_device_buffer); ret |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clSetKernelArg' failed\n"); exit(1); } /* Launch the kernel */ size_t global_work_size = num_elem; size_t local_work_size = num_elem; ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueNDRangeKernel' failed\n"); exit(1); } /* Wait for it to finish */ clFinish(command_queue); /* Read results from GPU */ ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_short16), dst_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueReadBuffer' failed\n"); exit(1); } /* Dump dst buffer to file */ char dump_file[100]; sprintf((char *)&dump_file, "%s.result", argv[0]); write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_short16)); printf("Result dumped to %s\n", dump_file); /* Free host dst buffer */ free(dst_host_buffer); /* Free device dst buffer */ ret = clReleaseMemObject(dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 0 */ free(src_0_host_buffer); /* Free device side src buffer 0 */ ret = clReleaseMemObject(src_0_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 1 */ free(src_1_host_buffer); /* Free device side src buffer 1 */ ret = clReleaseMemObject(src_1_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Release kernel */ ret = clReleaseKernel(kernel); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseKernel' failed\n"); exit(1); } /* Release program */ ret = clReleaseProgram(program); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseProgram' failed\n"); exit(1); } /* Release command queue */ ret = clReleaseCommandQueue(command_queue); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseCommandQueue' failed\n"); exit(1); } /* Release context */ ret = clReleaseContext(context); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseContext' failed\n"); exit(1); } return 0; }
xianggong/m2c_unit_test
test/integer/rhadd_short16short16/rhadd_short16short16_src.c
C
gpl-2.0
11,056
/* * TurboSight TBS 5922SE driver * * Copyright (c) 2014 Konstantin Dimitrov <kosio.dimitrov@gmail.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, version 2. * */ #include <linux/version.h> #include "tbs5923.h" #include "tbs5922se.h" #include "tbs5922ctrl.h" #include "tbsfe.h" #ifndef USB_PID_TBS5922SE_1 #define USB_PID_TBS5922SE_1 0x5923 #endif #define TBS5922SE_READ_MSG 0 #define TBS5922SE_WRITE_MSG 1 #define TBS5922SE_VOLTAGE_CTRL (0x1800) #define TBS5922SE_RC_QUERY (0x1a00) struct tbs5922se_state { u32 last_key_pressed; }; /* struct tbs5922se_rc_keys { u32 keycode; u32 event; };*/ /* debug */ static int dvb_usb_tbs5922se_debug; module_param_named(debug, dvb_usb_tbs5922se_debug, int, 0644); MODULE_PARM_DESC(debug, "set debugging level (1=info 2=xfer (or-able))." DVB_USB_DEBUG_STATUS); DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr); static int tbs5922se_op_rw(struct usb_device *dev, u8 request, u16 value, u16 index, u8 * data, u16 len, int flags) { int ret; u8 u8buf[len]; unsigned int pipe = (flags == TBS5922SE_READ_MSG) ? usb_rcvctrlpipe(dev, 0) : usb_sndctrlpipe(dev, 0); u8 request_type = (flags == TBS5922SE_READ_MSG) ? USB_DIR_IN : USB_DIR_OUT; if (flags == TBS5922SE_WRITE_MSG) memcpy(u8buf, data, len); ret = usb_control_msg(dev, pipe, request, request_type | USB_TYPE_VENDOR, value, index, u8buf, len, 2000); if (flags == TBS5922SE_READ_MSG) memcpy(data, u8buf, len); return ret; } /* I2C */ static int tbs5922se_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[], int num) { struct dvb_usb_device *d = i2c_get_adapdata(adap); int i = 0; u8 ibuf[1], obuf[3]; u8 buf6[20]; if (!d) return -ENODEV; if (mutex_lock_interruptible(&d->i2c_mutex) < 0) return -EAGAIN; switch (num) { case 2: { /* read */ obuf[0] = msg[0].len; obuf[1] = msg[0].addr<<1; obuf[2] = msg[0].buf[0]; tbs5922se_op_rw(d->udev, 0x90, 0, 0, obuf, 3, TBS5922SE_WRITE_MSG); msleep(5); tbs5922se_op_rw(d->udev, 0x91, 0, 0, ibuf, 1, TBS5922SE_READ_MSG); memcpy(msg[1].buf, ibuf, msg[1].len); break; } case 1: switch (msg[0].addr) { case 0x68: { /* write to register */ buf6[0] = msg[0].len+1;//lenth buf6[1] = msg[0].addr<<1;//demod addr for(i=0;i<msg[0].len;i++) { buf6[2+i] = msg[0].buf[i];//register } tbs5922se_op_rw(d->udev, 0x80, 0, 0, buf6, msg[0].len+2, TBS5922SE_WRITE_MSG); //msleep(3); break; } case 0x63: { /* write to register */ buf6[0] = msg[0].len+1;//lenth buf6[1] = msg[0].addr<<1;//demod addr for(i=0;i<msg[0].len;i++) { buf6[2+i] = msg[0].buf[i];//register } tbs5922se_op_rw(d->udev, 0x80, 0, 0, buf6, msg[0].len+2, TBS5922SE_WRITE_MSG); msleep(3); break; } case (TBS5922SE_RC_QUERY): { tbs5922se_op_rw(d->udev, 0xb8, 0, 0, buf6, 4, TBS5922SE_READ_MSG); msg[0].buf[0] = buf6[2]; msg[0].buf[1] = buf6[3]; msleep(3); //info("TBS5922SE_RC_QUERY %x %x %x %x\n",buf6[0],buf6[1],buf6[2],buf6[3]); break; } case (TBS5922SE_VOLTAGE_CTRL): { break; } } break; } mutex_unlock(&d->i2c_mutex); return num; } static u32 tbs5922se_i2c_func(struct i2c_adapter *adapter) { return I2C_FUNC_I2C; } static struct i2c_algorithm tbs5922se_i2c_algo = { .master_xfer = tbs5922se_i2c_transfer, .functionality = tbs5922se_i2c_func, }; static struct tbs5922se_config tbs5923_fe_config = { .tbs5922se_address = 0x68, .tbs5922se_ctrl = tbs5922ctrl, }; static int tbs5922se_read_mac_address(struct dvb_usb_device *d, u8 mac[6]) { int i,ret; u8 ibuf[3] = {0, 0,0}; u8 eeprom[256], eepromline[16]; for (i = 0; i < 256; i++) { ibuf[0]=1;//lenth ibuf[1]=0xa0;//eeprom addr ibuf[2]=i;//register ret = tbs5922se_op_rw(d->udev, 0x90, 0, 0, ibuf, 3, TBS5922SE_WRITE_MSG); ret = tbs5922se_op_rw(d->udev, 0x91, 0, 0, ibuf, 1, TBS5922SE_READ_MSG); if (ret < 0) { err("read eeprom failed"); return -1; } else { eepromline[i%16] = ibuf[0]; eeprom[i] = ibuf[0]; } if ((i % 16) == 15) { deb_xfer("%02x: ", i - 15); debug_dump(eepromline, 16, deb_xfer); } } memcpy(mac, eeprom + 16, 6); return 0; }; static struct dvb_usb_device_properties tbs5922se_properties; static int tbs5922se_frontend_attach(struct dvb_usb_adapter *d) { u8 buf[20]; if ((d->fe[0] = dvb_attach(tbs5922se_attach, &tbs5923_fe_config, &d->dev->i2c_adap)) != NULL) { printk("TBS5922SE attached.\n"); dvb_attach(tbsfe_attach, d->fe[0]); buf[0] = 7; buf[1] = 1; tbs5922se_op_rw(d->dev->udev, 0x8a, 0, 0, buf, 2, TBS5922SE_WRITE_MSG); buf[0] = 1; buf[1] = 1; tbs5922se_op_rw(d->dev->udev, 0x8a, 0, 0, buf, 2, TBS5922SE_WRITE_MSG); buf[0] = 6; buf[1] = 1; tbs5922se_op_rw(d->dev->udev, 0x8a, 0, 0, buf, 2, TBS5922SE_WRITE_MSG); return 0; } return -EIO; } static struct rc_map_table tbs5922se_rc_keys[] = { { 0xff84, KEY_POWER2}, /* power */ { 0xff94, KEY_MUTE}, /* mute */ { 0xff87, KEY_1}, { 0xff86, KEY_2}, { 0xff85, KEY_3}, { 0xff8b, KEY_4}, { 0xff8a, KEY_5}, { 0xff89, KEY_6}, { 0xff8f, KEY_7}, { 0xff8e, KEY_8}, { 0xff8d, KEY_9}, { 0xff92, KEY_0}, { 0xff96, KEY_CHANNELUP}, /* ch+ */ { 0xff91, KEY_CHANNELDOWN}, /* ch- */ { 0xff93, KEY_VOLUMEUP}, /* vol+ */ { 0xff8c, KEY_VOLUMEDOWN}, /* vol- */ { 0xff83, KEY_RECORD}, /* rec */ { 0xff98, KEY_PAUSE}, /* pause, yellow */ { 0xff99, KEY_OK}, /* ok */ { 0xff9a, KEY_CAMERA}, /* snapshot */ { 0xff81, KEY_UP}, { 0xff90, KEY_LEFT}, { 0xff82, KEY_RIGHT}, { 0xff88, KEY_DOWN}, { 0xff95, KEY_FAVORITES}, /* blue */ { 0xff97, KEY_SUBTITLE}, /* green */ { 0xff9d, KEY_ZOOM}, { 0xff9f, KEY_EXIT}, { 0xff9e, KEY_MENU}, { 0xff9c, KEY_EPG}, { 0xff80, KEY_PREVIOUS}, /* red */ { 0xff9b, KEY_MODE}, { 0xffdd, KEY_TV }, { 0xffde, KEY_PLAY }, { 0xffdc, KEY_STOP }, { 0xffdb, KEY_REWIND }, { 0xffda, KEY_FASTFORWARD }, { 0xffd9, KEY_PREVIOUS }, /* replay */ { 0xffd8, KEY_NEXT }, /* skip */ { 0xffd1, KEY_NUMERIC_STAR }, { 0xffd2, KEY_NUMERIC_POUND }, { 0xffd4, KEY_DELETE }, /* clear */ }; static int tbs5922se_rc_query(struct dvb_usb_device *d, u32 *event, int *state) { struct rc_map_table *keymap = d->props.rc.legacy.rc_map_table; int keymap_size = d->props.rc.legacy.rc_map_size; struct tbs5922se_state *st = d->priv; u8 key[2]; struct i2c_msg msg[] = { {.addr = TBS5922SE_RC_QUERY, .flags = I2C_M_RD, .buf = key, .len = 2}, }; int i; *state = REMOTE_NO_KEY_PRESSED; if (tbs5922se_i2c_transfer(&d->i2c_adap, msg, 1) == 1) { //info("key: %x %x\n",msg[0].buf[0],msg[0].buf[1]); for (i = 0; i < keymap_size; i++) { if (rc5_data(&keymap[i]) == msg[0].buf[1]) { *state = REMOTE_KEY_PRESSED; *event = keymap[i].keycode; st->last_key_pressed = keymap[i].keycode; break; } st->last_key_pressed = 0; } } return 0; } static struct usb_device_id tbs5922se_table[] = { {USB_DEVICE(0x734c, 0x5923)}, {USB_DEVICE(USB_VID_CYPRESS, USB_PID_TBS5922SE_1)}, { } }; MODULE_DEVICE_TABLE(usb, tbs5922se_table); static int tbs5922se_load_firmware(struct usb_device *dev, const struct firmware *frmwr) { u8 *b, *p; int ret = 0, i; u8 reset; const struct firmware *fw; const char *filename = "dvb-usb-tbsqbox-id5923.fw"; switch (dev->descriptor.idProduct) { case 0x5923: ret = request_firmware(&fw, filename, &dev->dev); if (ret != 0) { err("did not find the firmware file. (%s) " "Please see linux/Documentation/dvb/ for more details " "on firmware-problems.", filename); return ret; } break; default: fw = frmwr; break; } info("start downloading TBS5922SE firmware"); p = kmalloc(fw->size, GFP_KERNEL); reset = 1; /*stop the CPU*/ tbs5922se_op_rw(dev, 0xa0, 0x7f92, 0, &reset, 1, TBS5922SE_WRITE_MSG); tbs5922se_op_rw(dev, 0xa0, 0xe600, 0, &reset, 1, TBS5922SE_WRITE_MSG); if (p != NULL) { memcpy(p, fw->data, fw->size); for (i = 0; i < fw->size; i += 0x40) { b = (u8 *) p + i; if (tbs5922se_op_rw(dev, 0xa0, i, 0, b , 0x40, TBS5922SE_WRITE_MSG) != 0x40) { err("error while transferring firmware"); ret = -EINVAL; break; } } /* restart the CPU */ reset = 0; if (ret || tbs5922se_op_rw(dev, 0xa0, 0x7f92, 0, &reset, 1, TBS5922SE_WRITE_MSG) != 1) { err("could not restart the USB controller CPU."); ret = -EINVAL; } if (ret || tbs5922se_op_rw(dev, 0xa0, 0xe600, 0, &reset, 1, TBS5922SE_WRITE_MSG) != 1) { err("could not restart the USB controller CPU."); ret = -EINVAL; } msleep(100); kfree(p); } return ret; } static struct dvb_usb_device_properties tbs5922se_properties = { .caps = DVB_USB_IS_AN_I2C_ADAPTER, .usb_ctrl = DEVICE_SPECIFIC, .firmware = "dvb-usb-tbsqbox-id5923.fw", .size_of_priv = sizeof(struct tbs5922se_state), .no_reconnect = 1, .i2c_algo = &tbs5922se_i2c_algo, .rc.legacy = { .rc_map_table = tbs5922se_rc_keys, .rc_map_size = ARRAY_SIZE(tbs5922se_rc_keys), .rc_interval = 150, .rc_query = tbs5922se_rc_query, }, .generic_bulk_ctrl_endpoint = 0x81, /* parameter for the MPEG2-data transfer */ .num_adapters = 1, .download_firmware = tbs5922se_load_firmware, .read_mac_address = tbs5922se_read_mac_address, .adapter = { { .frontend_attach = tbs5922se_frontend_attach, .streaming_ctrl = NULL, .stream = { .type = USB_BULK, .count = 8, .endpoint = 0x82, .u = { .bulk = { .buffersize = 4096, } } }, } }, .num_device_descs = 1, .devices = { {"TBS 5922SE DVBS2 USB2.0", {&tbs5922se_table[0], NULL}, {NULL}, } } }; static int tbs5922se_probe(struct usb_interface *intf, const struct usb_device_id *id) { if (0 == dvb_usb_device_init(intf, &tbs5922se_properties, THIS_MODULE, NULL, adapter_nr)) { return 0; } return -ENODEV; } static struct usb_driver tbs5922se_driver = { .name = "tbs5922se", .probe = tbs5922se_probe, .disconnect = dvb_usb_device_exit, .id_table = tbs5922se_table, }; static int __init tbs5922se_module_init(void) { int ret = usb_register(&tbs5922se_driver); if (ret) err("usb_register failed. Error number %d", ret); return ret; } static void __exit tbs5922se_module_exit(void) { usb_deregister(&tbs5922se_driver); } module_init(tbs5922se_module_init); module_exit(tbs5922se_module_exit); MODULE_AUTHOR("Konstantin Dimitrov <kosio.dimitrov@gmail.com>"); MODULE_DESCRIPTION("TurboSight TBS 5922SE driver"); MODULE_VERSION("1.0"); MODULE_LICENSE("GPL");
work40/linux-tbs-drivers
linux/drivers/media/dvb/dvb-usb/tbs5923.c
C
gpl-2.0
10,640
<?php require_once ('/home/wwwyoutube/lib/suggest/common.php'); require_once ('/home/wwwyoutube/lib/suggest/functions.php'); $indexes = 'songtext'; $arr =array(); $q = trim($_GET['term']); $stmt = $ln_sph->prepare("SELECT * FROM $indexes WHERE MATCH(:match) LIMIT 0,10"); $aq = explode(' ',$q); if(strlen($aq[count($aq)-1])<3){ $query = $q; }else{ $query = $q.'*'; } $stmt->bindValue(':match', $query,PDO::PARAM_STR); $stmt->execute(); foreach($stmt->fetchAll() as $r){ $arr[] = array('id' => utf8_encode($r['title']),'label' =>utf8_encode( $r['title'])); } echo json_encode($arr); exit();
thecerial/youtube-mp3
wwwroot/ajax/suggest.php
PHP
gpl-2.0
600
import java.util.*; public class MyLinkedList { public static void main(String[] args){ Node<Character> list = stringToLinkedList("FOLLOW UP"); ctciProblem2_1(list); } public static Node<Character> stringToLinkedList(String str){ Node<Character> node = new Node<Character>(); for(int i = 0; i < str.length(); i++){ node = node.chainNext(str.charAt(i)); } return node.getHead(); } public static void ctciProblem2_1(Node<Character> list){ System.out.println("*-----Problem-2.1-----*"); list.print(); System.out.println("RESULT:"); list.removeDuplicates(new HashSet<Character>()); list.print(); } static class ListDetail<T>{ public Node<T> head = null; public Node<T> tail = null; public int size = 0; } static class Node<T>{ private Node<T> next = null; private Node<T> prev = null; private T data = null; private ListDetail<T> detail = null; public Node(){ detail = new ListDetail<T>(); detail.size = 0; } public Node(T _data, Node<T> _next, Node<T> _prev, ListDetail<T> _detail){ this.data = _data; this.next = _next; this.prev = _prev; this.detail = _detail; this.detail.size++; } public Node<T> getNext(){ return next; } public Node<T> getPrev(){ return prev; } public Node<T> insertAfter(T _data){ if(getSize() == 0){ data = _data; detail.size++; detail.head = this; detail.tail = this; return this; } Node<T> old = next; next = new Node<T>(_data, old, this, detail); if(old != null){ old.setPrev(next); }else{ detail.tail = next; } return this; } public Node<T> insertBefore(T _data){ if(getSize() == 0){ data = _data; detail.size++; detail.head = this; detail.tail = this; return this; } Node<T> old = prev; prev = new Node<T>(_data, this, old, detail); if(old != null){ old.setNext(prev); }else{ detail.head = prev; } return this; } public boolean delete(){ if(next == null){ detail.tail = prev; }else{ next.setPrev(prev); } if(prev == null){ detail.head = next; }else{ prev.setNext(next); } if(detail.size == 0){ return false; } if(detail.size == 1){ detail.head = null; detail.tail = null; detail.size = 0; next = null; prev = null; data = null; } detail.size--; return true; } public Node<T> setNext(Node<T> n){ next = n; return this; } public Node<T> setPrev(Node<T> n){ prev = n; return this; } public int getSize(){ return detail.size; } public Node<T> getHead(){ return detail.head; } public Node<T> getTail(){ return detail.tail; } public T getData(){ return data; } public Node<T> setData(T _data){ this.data = _data; return this; } public Node<T> chainNext(T _data){ insertAfter(_data); return next == null ? this : next; } public Node<T> chainBefore(T _data){ insertBefore(_data); return prev == null ? this : prev; } public void print(){ System.out.print(getData()); if(next == null){ System.out.println(); System.out.println("SIZE:" + detail.size); }else{ next.print(); } } public Node<T> removeDuplicates(Set<T> buffer){ if(buffer.contains(data)){ delete(); }else{ buffer.add(data); } if(next == null){ return detail.head; } return next.removeDuplicates(buffer); } } }
wazeemwoz/PuzzlesCodingFunPractice
ctci/LinkedLists/MyLinkedList.java
Java
gpl-2.0
3,509
package org.hogzilla.histogram import scala.collection.mutable.HashSet import scala.collection.mutable.Map import scala.collection.mutable.Set import scala.math.log /** * @author pa */ object Histograms { val atypicalThreshold = 0.0000001D def KullbackLiebler(histogram1:Map[String,Double],histogram2:Map[String,Double]):Double = { val keys = histogram1.keySet ++ histogram2.keySet keys./:(0.0){ case (ac,key) => val p:Double = { if(histogram1.get(key).isEmpty) 0 else histogram1.get(key).get } val q:Double = { if(histogram2.get(key).isEmpty) 0 else histogram2.get(key).get } if(p==0) ac else { if(q==0) ac + 0 else ac + p*log(p/q) } } } def atypical(histogram1:Map[String,Double],histogram2:Map[String,Double]):Set[String] = { val ret = new HashSet[String] val keys = histogram2.keySet keys./:(0.0){ case (ac,key) => val p:Double = { if(histogram1.get(key).isEmpty) 0 else histogram1.get(key).get } val q:Double = { if(histogram2.get(key).isEmpty) 0 else histogram2.get(key).get } if(p<atypicalThreshold && q>atypicalThreshold) { ret.add(key) ac+1 } else 0 } ret } // Return typical events in histogram1 (main saved), which occurred in histogram2 (current) def typical(histogram1:Map[String,Double],histogram2:Map[String,Double]):Set[String] = { val ret = new HashSet[String] val keys = histogram2.keySet keys./:(0.0){ case (ac,key) => val p:Double = { if(histogram1.get(key).isEmpty) 0 else histogram1.get(key).get } val q:Double = { if(histogram2.get(key).isEmpty) 0 else histogram2.get(key).get } if(p>atypicalThreshold && q>atypicalThreshold) { ret.add(key) ac+1 } else 0 } ret } def isTypicalEvent(histogram1:Map[String,Double],event:String):Boolean= { val p:Double = { if(histogram1.get(event).isEmpty) 0 else histogram1.get(event).get } if(p>atypicalThreshold) { true } else false } def isAtypicalEvent(histogram1:Map[String,Double],event:String):Boolean= { !isTypicalEvent(histogram1,event) } def merge(histogram1:HogHistogram,histogram2:HogHistogram):HogHistogram = { val keys = histogram1.histMap.keySet ++ histogram2.histMap.keySet val keysLabel = histogram1.histLabels.keySet ++ histogram2.histLabels.keySet var div:Double = 1 if(histogram1.histSize.toDouble > 1000) div = 2 keys./:(0.0){ case (ac,key) => val p:Double = { if(histogram1.histMap.get(key).isEmpty) 0 else histogram1.histMap.get(key).get } val q:Double = { if(histogram2.histMap.get(key).isEmpty) 0 else histogram2.histMap.get(key).get } if(p>0 || q>0) { val newp = ( p*histogram1.histSize.toDouble/div+ q*histogram2.histSize.toDouble )/(histogram1.histSize.toDouble/div+histogram2.histSize.toDouble) histogram1.histMap.put(key,newp) } 0D } keysLabel./:(0.0){ case (ac,key) => if(histogram1.histLabels.get(key).isEmpty) histogram1.histLabels.put(key,histogram2.histLabels.get(key).get) 0D } val total = histogram1.histSize/div+histogram2.histSize new HogHistogram(histogram1.histName,total.toInt,histogram1.histMap,histogram1.histLabels) } // It is not exactly a histogram, but... def mergeMax(histogram1:HogHistogram,histogram2:HogHistogram):HogHistogram = { val keys = histogram1.histMap.keySet ++ histogram2.histMap.keySet val keysLabel = histogram1.histLabels.keySet ++ histogram2.histLabels.keySet keys./:(0.0){ case (ac,key) => val p:Double = { if(histogram1.histMap.get(key).isEmpty) 0 else histogram1.histMap.get(key).get } val q:Double = { if(histogram2.histMap.get(key).isEmpty) 0 else histogram2.histMap.get(key).get } if(p>0 || q>0) { histogram1.histMap.put(key,p.max(q)) } 0D } keysLabel./:(0.0){ case (ac,key) => if(histogram1.histLabels.get(key).isEmpty) histogram1.histLabels.put(key,histogram2.histLabels.get(key).get) 0D } val total = histogram1.histSize+histogram2.histSize new HogHistogram(histogram1.histName,total,histogram1.histMap,histogram1.histLabels) } // hist1 - hist2 def difference(histogram1:HogHistogram,histogram2:HogHistogram):HogHistogram = { val keys = histogram2.histMap.keySet // ++ histogram2.histMap.keySet keys./:(0.0){ case (ac,key) => val p:Double = { if(histogram1.histMap.get(key).isEmpty) 0 else histogram1.histMap.get(key).get } val q:Double = { if(histogram2.histMap.get(key).isEmpty) 0 else histogram2.histMap.get(key).get } if(p>0 || q>0) { val newp = ( p*histogram1.histSize.toDouble- q*histogram2.histSize.toDouble )/(histogram1.histSize.toDouble-histogram2.histSize.toDouble) histogram1.histMap.put(key,newp) } 0D } val total = histogram1.histSize-histogram2.histSize new HogHistogram(histogram1.histName,total,histogram1.histMap,histogram1.histLabels) } def getIPFromHistName(histogramName:String):String = { histogramName.subSequence(histogramName.lastIndexOf("-")+1, histogramName.length()).toString } /* final val EPS = 1e-10 type DATASET = Iterator[(Double, Double)] def execute( xy: DATASET, f: Double => Double): Double = { val z = xy.filter{ case(x, y) => abs(y) > EPS} - z./:(0.0){ case(s, (x, y)) => s + y*log(f(x)/y)} } def execute( xy: DATASET, fs: Iterable[Double=>Double]): Iterable[Double] = fs.map(execute(xy, _)) */ }
pauloangelo/hogzilla
src/org/hogzilla/histogram/Histograms.scala
Scala
gpl-2.0
6,997
#!/usr/bin/env python-i # draws SUMMON logo # import math import summon from summon.core import * from summon import shapes, colors def interleave(a, b): c = [] for i in xrange(0, len(a), 2): c.extend(a[i:i+2] + b[i:i+2]) return c def curve(x, y, start, end, radius, width): p = shapes.arc_path(x, y, start, end, radius, 30) p2 = shapes.arc_path(x, y, start, end, radius-width, 30) return triangle_strip(*interleave(p, p2)) def draw_u(top, bottom, w, t): return group(shapes.box(-w,top, -w+t, bottom+w), shapes.box(w,top, w-t, bottom+w), curve(0, bottom+w, -math.pi, 0.0, w, t)) def draw_m(top, bottom, w, t): return group( translate(0, -2*w+t, rotate(180, draw_u(top, bottom, w, t))), translate(2*w-t, -2*w+t, rotate(180, draw_u(top, bottom, w, t)))) def draw_summon(): t = 150 # thickness w = 200 # width s = 50 # spacing top = w bottom = -3*w+t return translate(-7*w+t-2.5*s, -(top + bottom) / 2.0, # S curve(0, 0, 0, 1.5*math.pi, w, t), curve(0, -2*w+t, -math.pi, .5*math.pi, w, t), # U translate(2*w+s, 0, draw_u(top, bottom, w, t)), # M translate(4*w+2*s, 0, draw_m(top, bottom, w, t)), # M translate(8*w-t+3*s, 0, draw_m(top, bottom, w, t)), # 0 translate(12*w-2*t+4*s, 0, curve(0, 0, 0.0, math.pi, w, t), shapes.box(-w,top-w, -w+t, bottom+w), shapes.box(w,top-w, w-t, bottom+w), curve(0, bottom+w, -math.pi, 0.0, w, t)), # N translate(14*w-2*t+5*s, 0, translate(0, -2*w+t, rotate(180, draw_u(top, bottom, w, t)))) ) def blur(x, col): return group( # color fade quads(col, -2000, 0, 2000, 0, color(0, 0, 0, 0), 2000, 300, -2000, 300), # white fades quads(color(1, 1, 1, 1), -2000, 0, -2000, 600, color(1, 1, 1, 0), -x, 600, -x, 0), quads(color(1, 1, 1, 1), 2000, 0, 2000, 600, color(1, 1, 1, 0), x, 600, x, 0)) def draw_summon_logo(): return group( blur(1200, color(0, .2, .5, .8)), rotate(180, blur(0, color(0, 0, .5, .5))), color(0, 0, 0), draw_summon(), color(0, 0, 0), text_clip("visualization prototyping and scripting", -1600, -450, 1600, -900, 0, 20, "top", "center")) # draw logo win = summon.Window("18_summon", size=(800,400)) win.set_bgcolor(1, 1, 1) win.add_group(draw_summon_logo()) win.home()
mdrasmus/summon
examples/18_summon.py
Python
gpl-2.0
2,904
<!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_79) on Tue Sep 27 23:18:31 EDT 2016 --> <title>Uses of Class corgis.slavery.domain.Slave (Slavery: version 1)</title> <meta name="date" content="2016-09-27"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class corgis.slavery.domain.Slave (Slavery: version 1)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../corgis/slavery/domain/Slave.html" title="class in corgis.slavery.domain">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?corgis/slavery/domain/class-use/Slave.html" target="_top">Frames</a></li> <li><a href="Slave.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class corgis.slavery.domain.Slave" class="title">Uses of Class<br>corgis.slavery.domain.Slave</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../corgis/slavery/domain/Slave.html" title="class in corgis.slavery.domain">Slave</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#corgis.slavery.domain">corgis.slavery.domain</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="corgis.slavery.domain"> <!-- --> </a> <h3>Uses of <a href="../../../../corgis/slavery/domain/Slave.html" title="class in corgis.slavery.domain">Slave</a> in <a href="../../../../corgis/slavery/domain/package-summary.html">corgis.slavery.domain</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../corgis/slavery/domain/package-summary.html">corgis.slavery.domain</a> that return <a href="../../../../corgis/slavery/domain/Slave.html" title="class in corgis.slavery.domain">Slave</a></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> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../corgis/slavery/domain/Slave.html" title="class in corgis.slavery.domain">Slave</a></code></td> <td class="colLast"><span class="strong">TransactionRecord.</span><code><strong><a href="../../../../corgis/slavery/domain/TransactionRecord.html#getSlave()">getSlave</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../corgis/slavery/domain/Slave.html" title="class in corgis.slavery.domain">Slave</a></code></td> <td class="colLast"><span class="strong">Slavery.</span><code><strong><a href="../../../../corgis/slavery/domain/Slavery.html#getSlave()">getSlave</a></strong>()</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../corgis/slavery/domain/Slave.html" title="class in corgis.slavery.domain">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?corgis/slavery/domain/class-use/Slave.html" target="_top">Frames</a></li> <li><a href="Slave.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
RealTimeWeb/datasets
datasets/java/slavery/docs/corgis/slavery/domain/class-use/Slave.html
HTML
gpl-2.0
6,230
package com.dblp.communities.domain; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class Person implements Serializable { private static final long serialVersionUID = -191467172380784780L; private String personName; public Person() { super(); } public Person(String name) { super(); this.personName = name; } @Override public String toString() { return "Person with name the " + personName; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.personName == null) ? 0 : this.personName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (this.getClass() != obj.getClass()) return false; Person other = (Person) obj; if (this.personName == null && other.personName != null) return false; if (this.personName != null && other.personName == null) return false; if (this.personName.equals(other.personName)) return true; return false; } public List<String> getNameParts() { StringTokenizer tokenizer = new StringTokenizer(personName); List<String> parts = new ArrayList<String>(); while (tokenizer.hasMoreTokens()) { parts.add(tokenizer.nextToken()); } return parts; } public final String getPersonName() { return personName; } public final void setPersonName(String name) { this.personName = name; } }
erlfas/DBLPCommunities
src/main/java/com/dblp/communities/domain/Person.java
Java
gpl-2.0
1,636
<?php $link_url = get_post_meta($post->ID, 'link_url', true); ?> <?php $link_title = get_post_meta($post->ID, 'link_title', true); ?> <div class="post-header"> <h2 class="post-title"><a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2> <?php if( is_sticky() ) { ?> <span class="sticky-post"><?php _e('Sticky post', 'baskerville'); ?></span> <?php } ?> </div> <!-- /post-header --> <div class="post-link"> <p><?php echo $link_title; ?></p> <a href="<?php echo $link_url; ?>" title="<?php echo $link_title; ?>"><?php echo url_to_domain( $link_url ); ?></a> </div> <!-- /post-link --> <?php if($post->post_content != "") : ?> <div class="post-excerpt"> <?php the_excerpt('100'); ?> </div> <!-- /post-excerpt --> <?php endif; ?> <div class="post-meta"> <a class="post-date" href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><i class="fa fa-clock-o"></i> <?php the_time( 'Y/m/d' ); ?></a> <?php if( function_exists('zilla_likes') ) zilla_likes(); if ( comments_open() ) { comments_popup_link( '<i class="fa fa-comments-o"></i> 0', '<i class="fa fa-comments-o"></i> 1', '<i class="fa fa-comments-o"></i> %', 'post-comments' ); } edit_post_link('<i class="fa fa-pencil-square-o"></i>'); ?> <div class="clear"></div> </div> <div class="clear"></div>
gordielachance/baskerville-fork
content-link.php
PHP
gpl-2.0
1,644
#include <string.h> void *memcpy(void *dst, const void *src, size_t len) { char *tmp = dst; const char *s = src; while(len--) { *tmp++ = *s++; } return dst; } int strlen(const char *str) { int i = 0; char *tmp = (char *)str; while(*tmp != '\0') { tmp++; i++; } return i; } int strcmp(const char *str1, const char *str2) { while(*str1++ == *str2++) { if (*str1 == '\0') { break; } } return *str1 - *str2; } void *memset(void *str, int ch, size_t n) { int i; char *tmp = (char *)str; for (i = 0; i < n; i++) { *tmp++ = ch; } return str; }
yangfan876/Finux
lib/string.c
C
gpl-2.0
582
<div class="panel panel-success"> <div class="panel-heading"> <h3> <%-headline%> <span class="pull-right btn btn-success js-like"> <span class="glyphicon glyphicon-heart" />&nbsp; <% if (liked) { %> <% if (likes == 1) { %>You love<%} else { %>You + {{likes-1}} love<% } %> this <% } else { %> <% if (likes == 0) { %>Love<% } else if (likes == 1) { %>1 loves<%} else { %>{{likes}} love<% } %> this <% } %> </span> </h3> <span class="text-muted">From a member of {{groupname}}</span><a href="/story/{{id}}"><span class="pull-right text-muted">#{{id}}</span></a> </div> <div class="panel-body"> <%-story%> </div> </div>
nicksellen/iznik
http/template/user/stories/one.html
HTML
gpl-2.0
805
<?php include("../mlpsecure/sessionsecurelistowner.inc"); include("adminsecure/changepasswordlistowner.inc"); ?> <html> <head> <title>List Owner - Change Password</title> <link rel="stylesheet" type="text/css" href="../css_mlp.css" /> </head> <body> <table cellspacing="0" cellpadding="5" align="center" border="1"> <tr> <td align="center"> <img src="../images/title.gif"> <hr> <h4>List Owner - <font color="red">Change Password</font></h4> You are <b>REQUIRED</b> to <b>CHANGE</b> your <b>PASSWORD</b>, please write it down somewhere <b>SAFE</b>. <hr><?php if ($notValid) echo "<b class=\"red\">$notValid</b><br><br>\n"; ?> <form action="<?=$_SERVER[PHP_SELF]?>" method="POST"> <b>New Password:</b><br> <input type="password" name="password1"><br><br> <b>Confirm Password:</b><br> <input type="password" name="password2"><br><br> <input type="submit" class="greenbutton" value="Submit"> <input type="hidden" name="submitted" value="1"> <input type="hidden" name="createlistowner" value="<?=$createlistowner?>"> </form> </td> </tr> </table> </body> </html>
nulled/nulled
www/planetxmail.com/mle/admin/changepasswordlistowner.php
PHP
gpl-2.0
1,152
Summary ======= A simple code to demonstrate the idea to integrate the power of Elasticsearch into slack and it is fun!!! Prerequisite ============ 1. You have to add a new BOT in your slack organization via http://yourorganization.slack.com/services/new/bot 2. Pick the name for your bot 3. Next you will get API token from Slack 4. Add the bot into a public channel Configuration ============= 1. Change API token and bot's name accordingly in /lib/slack/config.js 2. You don't need to configure ES because I've hosted in found.io and it will be available up to 28 Oct 2015 Installation ============ You can also install via npm: ```sh npm install ``` You can run via ```sh node index.js ``` After you see the message on the console, please go to the channel you have just created earlier and try command 1. siri near 1000km ![alt tag](https://raw.githubusercontent.com/pudkrong/slackbot/master/data/screenshot/near.png) 2. siri search rock ![alt tag](https://raw.githubusercontent.com/pudkrong/slackbot/master/data/screenshot/search.png)
pudkrong/slackbot
README.md
Markdown
gpl-2.0
1,055
/* * NCR 5380 defines * * Copyright 1993, Drew Eckhardt * Visionary Computing * (Unix consulting and custom programming) * drew@colorado.edu * +1 (303) 666-5836 * * DISTRIBUTION RELEASE 7 * * For more information, please consult * * NCR 5380 Family * SCSI Protocol Controller * Databook * NCR Microelectronics * 1635 Aeroplaza Drive * Colorado Springs, CO 80916 * 1+ (719) 578-3400 * 1+ (800) 334-5454 */ /* * $Log: NCR5380.h,v $ */ #ifndef NCR5380_H #define NCR5380_H #include <linux/interrupt.h> #ifdef AUTOSENSE #include <scsi/scsi_eh.h> #endif #define NCR5380_PUBLIC_RELEASE 7 #define NCR53C400_PUBLIC_RELEASE 2 #define NDEBUG_ARBITRATION 0x1 #define NDEBUG_AUTOSENSE 0x2 #define NDEBUG_DMA 0x4 #define NDEBUG_HANDSHAKE 0x8 #define NDEBUG_INFORMATION 0x10 #define NDEBUG_INIT 0x20 #define NDEBUG_INTR 0x40 #define NDEBUG_LINKED 0x80 #define NDEBUG_MAIN 0x100 #define NDEBUG_NO_DATAOUT 0x200 #define NDEBUG_NO_WRITE 0x400 #define NDEBUG_PIO 0x800 #define NDEBUG_PSEUDO_DMA 0x1000 #define NDEBUG_QUEUES 0x2000 #define NDEBUG_RESELECTION 0x4000 #define NDEBUG_SELECTION 0x8000 #define NDEBUG_USLEEP 0x10000 #define NDEBUG_LAST_BYTE_SENT 0x20000 #define NDEBUG_RESTART_SELECT 0x40000 #define NDEBUG_EXTENDED 0x80000 #define NDEBUG_C400_PREAD 0x100000 #define NDEBUG_C400_PWRITE 0x200000 #define NDEBUG_LISTS 0x400000 #define NDEBUG_ANY 0xFFFFFFFFUL /* * The contents of the OUTPUT DATA register are asserted on the bus when * either arbitration is occurring or the phase-indicating signals ( * IO, CD, MSG) in the TARGET COMMAND register and the ASSERT DATA * bit in the INITIATOR COMMAND register is set. */ #define OUTPUT_DATA_REG 0 /* wo DATA lines on SCSI bus */ #define CURRENT_SCSI_DATA_REG 0 /* ro same */ #define INITIATOR_COMMAND_REG 1 /* rw */ #define ICR_ASSERT_RST 0x80 /* rw Set to assert RST */ #define ICR_ARBITRATION_PROGRESS 0x40 /* ro Indicates arbitration complete */ #define ICR_TRI_STATE 0x40 /* wo Set to tri-state drivers */ #define ICR_ARBITRATION_LOST 0x20 /* ro Indicates arbitration lost */ #define ICR_DIFF_ENABLE 0x20 /* wo Set to enable diff. drivers */ #define ICR_ASSERT_ACK 0x10 /* rw ini Set to assert ACK */ #define ICR_ASSERT_BSY 0x08 /* rw Set to assert BSY */ #define ICR_ASSERT_SEL 0x04 /* rw Set to assert SEL */ #define ICR_ASSERT_ATN 0x02 /* rw Set to assert ATN */ #define ICR_ASSERT_DATA 0x01 /* rw SCSI_DATA_REG is asserted */ #ifdef DIFFERENTIAL #define ICR_BASE ICR_DIFF_ENABLE #else #define ICR_BASE 0 #endif #define MODE_REG 2 /* * Note : BLOCK_DMA code will keep DRQ asserted for the duration of the * transfer, causing the chip to hog the bus. You probably don't want * this. */ #define MR_BLOCK_DMA_MODE 0x80 /* rw block mode DMA */ #define MR_TARGET 0x40 /* rw target mode */ #define MR_ENABLE_PAR_CHECK 0x20 /* rw enable parity checking */ #define MR_ENABLE_PAR_INTR 0x10 /* rw enable bad parity interrupt */ #define MR_ENABLE_EOP_INTR 0x08 /* rw enable eop interrupt */ #define MR_MONITOR_BSY 0x04 /* rw enable int on unexpected bsy fail */ #define MR_DMA_MODE 0x02 /* rw DMA / pseudo DMA mode */ #define MR_ARBITRATE 0x01 /* rw start arbitration */ #ifdef PARITY #define MR_BASE MR_ENABLE_PAR_CHECK #else #define MR_BASE 0 #endif #define TARGET_COMMAND_REG 3 #define TCR_LAST_BYTE_SENT 0x80 /* ro DMA done */ #define TCR_ASSERT_REQ 0x08 /* tgt rw assert REQ */ #define TCR_ASSERT_MSG 0x04 /* tgt rw assert MSG */ #define TCR_ASSERT_CD 0x02 /* tgt rw assert CD */ #define TCR_ASSERT_IO 0x01 /* tgt rw assert IO */ #define STATUS_REG 4 /* ro */ /* * Note : a set bit indicates an active signal, driven by us or another * device. */ #define SR_RST 0x80 #define SR_BSY 0x40 #define SR_REQ 0x20 #define SR_MSG 0x10 #define SR_CD 0x08 #define SR_IO 0x04 #define SR_SEL 0x02 #define SR_DBP 0x01 /* * Setting a bit in this register will cause an interrupt to be generated when * BSY is false and SEL true and this bit is asserted on the bus. */ #define SELECT_ENABLE_REG 4 /* wo */ #define BUS_AND_STATUS_REG 5 /* ro */ #define BASR_END_DMA_TRANSFER 0x80 /* ro set on end of transfer */ #define BASR_DRQ 0x40 /* ro mirror of DRQ pin */ #define BASR_PARITY_ERROR 0x20 /* ro parity error detected */ #define BASR_IRQ 0x10 /* ro mirror of IRQ pin */ #define BASR_PHASE_MATCH 0x08 /* ro Set when MSG CD IO match TCR */ #define BASR_BUSY_ERROR 0x04 /* ro Unexpected change to inactive state */ #define BASR_ATN 0x02 /* ro BUS status */ #define BASR_ACK 0x01 /* ro BUS status */ /* Write any value to this register to start a DMA send */ #define START_DMA_SEND_REG 5 /* wo */ /* * Used in DMA transfer mode, data is latched from the SCSI bus on * the falling edge of REQ (ini) or ACK (tgt) */ #define INPUT_DATA_REG 6 /* ro */ /* Write any value to this register to start a DMA receive */ #define START_DMA_TARGET_RECEIVE_REG 6 /* wo */ /* Read this register to clear interrupt conditions */ #define RESET_PARITY_INTERRUPT_REG 7 /* ro */ /* Write any value to this register to start an ini mode DMA receive */ #define START_DMA_INITIATOR_RECEIVE_REG 7 /* wo */ #define C400_CONTROL_STATUS_REG NCR53C400_register_offset-8 /* rw */ #define CSR_RESET 0x80 /* wo Resets 53c400 */ #define CSR_53C80_REG 0x80 /* ro 5380 registers busy */ #define CSR_TRANS_DIR 0x40 /* rw Data transfer direction */ #define CSR_SCSI_BUFF_INTR 0x20 /* rw Enable int on transfer ready */ #define CSR_53C80_INTR 0x10 /* rw Enable 53c80 interrupts */ #define CSR_SHARED_INTR 0x08 /* rw Interrupt sharing */ #define CSR_HOST_BUF_NOT_RDY 0x04 /* ro Is Host buffer ready */ #define CSR_SCSI_BUF_RDY 0x02 /* ro SCSI buffer read */ #define CSR_GATED_53C80_IRQ 0x01 /* ro Last block xferred */ #if 0 #define CSR_BASE CSR_SCSI_BUFF_INTR | CSR_53C80_INTR #else #define CSR_BASE CSR_53C80_INTR #endif /* Number of 128-byte blocks to be transferred */ #define C400_BLOCK_COUNTER_REG NCR53C400_register_offset-7 /* rw */ /* Resume transfer after disconnect */ #define C400_RESUME_TRANSFER_REG NCR53C400_register_offset-6 /* wo */ /* Access to host buffer stack */ #define C400_HOST_BUFFER NCR53C400_register_offset-4 /* rw */ /* Note : PHASE_* macros are based on the values of the STATUS register */ #define PHASE_MASK (SR_MSG | SR_CD | SR_IO) #define PHASE_DATAOUT 0 #define PHASE_DATAIN SR_IO #define PHASE_CMDOUT SR_CD #define PHASE_STATIN (SR_CD | SR_IO) #define PHASE_MSGOUT (SR_MSG | SR_CD) #define PHASE_MSGIN (SR_MSG | SR_CD | SR_IO) #define PHASE_UNKNOWN 0xff /* * Convert status register phase to something we can use to set phase in * the target register so we can get phase mismatch interrupts on DMA * transfers. */ #define PHASE_SR_TO_TCR(phase) ((phase) >> 2) /* * The internal should_disconnect() function returns these based on the * expected length of a disconnect if a device supports disconnect/ * reconnect. */ #define DISCONNECT_NONE 0 #define DISCONNECT_TIME_TO_DATA 1 #define DISCONNECT_LONG 2 /* * These are "special" values for the tag parameter passed to NCR5380_select. */ #define TAG_NEXT -1 /* Use next free tag */ #define TAG_NONE -2 /* * Establish I_T_L nexus instead of I_T_L_Q * even on SCSI-II devices. */ /* * These are "special" values for the irq and dma_channel fields of the * Scsi_Host structure */ #define SCSI_IRQ_NONE 255 #define DMA_NONE 255 #define IRQ_AUTO 254 #define DMA_AUTO 254 #define PORT_AUTO 0xffff /* autoprobe io port for 53c400a */ #define FLAG_HAS_LAST_BYTE_SENT 1 /* NCR53c81 or better */ #define FLAG_CHECK_LAST_BYTE_SENT 2 /* Only test once */ #define FLAG_NCR53C400 4 /* NCR53c400 */ #define FLAG_NO_PSEUDO_DMA 8 /* Inhibit DMA */ #define FLAG_DTC3181E 16 /* DTC3181E */ #ifndef ASM struct NCR5380_hostdata { NCR5380_implementation_fields; /* implementation specific */ struct Scsi_Host *host; /* Host backpointer */ unsigned char id_mask, id_higher_mask; /* 1 << id, all bits greater */ unsigned char targets_present; /* targets we have connected to, so we can call a select failure a retryable condition */ volatile unsigned char busy[8]; /* index = target, bit = lun */ #if defined(REAL_DMA) || defined(REAL_DMA_POLL) volatile int dma_len; /* requested length of DMA */ #endif volatile unsigned char last_message; /* last message OUT */ volatile Scsi_Cmnd *connected; /* currently connected command */ volatile Scsi_Cmnd *issue_queue; /* waiting to be issued */ volatile Scsi_Cmnd *disconnected_queue; /* waiting for reconnect */ volatile int restart_select; /* we have disconnected, used to restart NCR5380_select() */ volatile unsigned aborted:1; /* flag, says aborted */ int flags; unsigned long time_expires; /* in jiffies, set prior to sleeping */ int select_time; /* timer in select for target response */ volatile Scsi_Cmnd *selecting; struct delayed_work coroutine; /* our co-routine */ #ifdef NCR5380_STATS unsigned timebase; /* Base for time calcs */ long time_read[8]; /* time to do reads */ long time_write[8]; /* time to do writes */ unsigned long bytes_read[8]; /* bytes read */ unsigned long bytes_write[8]; /* bytes written */ unsigned pendingr; unsigned pendingw; #endif #ifdef AUTOSENSE struct scsi_eh_save ses; #endif }; #ifdef __KERNEL__ #define dprintk(a,b) do {} while(0) #define NCR5380_dprint(a,b) do {} while(0) #define NCR5380_dprint_phase(a,b) do {} while(0) #if defined(AUTOPROBE_IRQ) static int NCR5380_probe_irq(struct Scsi_Host *instance, int possible); #endif static int NCR5380_init(struct Scsi_Host *instance, int flags); static void NCR5380_exit(struct Scsi_Host *instance); static void NCR5380_information_transfer(struct Scsi_Host *instance); #ifndef DONT_USE_INTR static irqreturn_t NCR5380_intr(int irq, void *dev_id); #endif static void NCR5380_main(struct work_struct *work); static void __maybe_unused NCR5380_print_options(struct Scsi_Host *instance); #ifdef NDEBUG static void NCR5380_print_phase(struct Scsi_Host *instance); static void NCR5380_print(struct Scsi_Host *instance); #endif static int NCR5380_abort(Scsi_Cmnd * cmd); static int NCR5380_bus_reset(Scsi_Cmnd * cmd); static int NCR5380_queue_command(Scsi_Cmnd * cmd, void (*done) (Scsi_Cmnd *)); static int __maybe_unused NCR5380_proc_info(struct Scsi_Host *instance, char *buffer, char **start, off_t offset, int length, int inout); static void NCR5380_reselect(struct Scsi_Host *instance); static int NCR5380_select(struct Scsi_Host *instance, Scsi_Cmnd * cmd, int tag); #if defined(PSEUDO_DMA) || defined(REAL_DMA) || defined(REAL_DMA_POLL) static int NCR5380_transfer_dma(struct Scsi_Host *instance, unsigned char *phase, int *count, unsigned char **data); #endif static int NCR5380_transfer_pio(struct Scsi_Host *instance, unsigned char *phase, int *count, unsigned char **data); #if (defined(REAL_DMA) || defined(REAL_DMA_POLL)) #if defined(i386) || defined(__alpha__) /** * NCR5380_pc_dma_setup - setup ISA DMA * @instance: adapter to set up * @ptr: block to transfer (virtual address) * @count: number of bytes to transfer * @mode: DMA controller mode to use * * Program the DMA controller ready to perform an ISA DMA transfer * on this chip. * * Locks: takes and releases the ISA DMA lock. */ static __inline__ int NCR5380_pc_dma_setup(struct Scsi_Host *instance, unsigned char *ptr, unsigned int count, unsigned char mode) { unsigned limit; unsigned long bus_addr = virt_to_bus(ptr); unsigned long flags; if (instance->dma_channel <= 3) { if (count > 65536) count = 65536; limit = 65536 - (bus_addr & 0xFFFF); } else { if (count > 65536 * 2) count = 65536 * 2; limit = 65536 * 2 - (bus_addr & 0x1FFFF); } if (count > limit) count = limit; if ((count & 1) || (bus_addr & 1)) panic("scsi%d : attempted unaligned DMA transfer\n", instance->host_no); flags=claim_dma_lock(); disable_dma(instance->dma_channel); clear_dma_ff(instance->dma_channel); set_dma_addr(instance->dma_channel, bus_addr); set_dma_count(instance->dma_channel, count); set_dma_mode(instance->dma_channel, mode); enable_dma(instance->dma_channel); release_dma_lock(flags); return count; } /** * NCR5380_pc_dma_write_setup - setup ISA DMA write * @instance: adapter to set up * @ptr: block to transfer (virtual address) * @count: number of bytes to transfer * * Program the DMA controller ready to perform an ISA DMA write to the * SCSI controller. * * Locks: called routines take and release the ISA DMA lock. */ static __inline__ int NCR5380_pc_dma_write_setup(struct Scsi_Host *instance, unsigned char *src, unsigned int count) { return NCR5380_pc_dma_setup(instance, src, count, DMA_MODE_WRITE); } /** * NCR5380_pc_dma_read_setup - setup ISA DMA read * @instance: adapter to set up * @ptr: block to transfer (virtual address) * @count: number of bytes to transfer * * Program the DMA controller ready to perform an ISA DMA read from the * SCSI controller. * * Locks: called routines take and release the ISA DMA lock. */ static __inline__ int NCR5380_pc_dma_read_setup(struct Scsi_Host *instance, unsigned char *src, unsigned int count) { return NCR5380_pc_dma_setup(instance, src, count, DMA_MODE_READ); } /** * NCR5380_pc_dma_residual - return bytes left * @instance: adapter * * Reports the number of bytes left over after the DMA was terminated. * * Locks: takes and releases the ISA DMA lock. */ static __inline__ int NCR5380_pc_dma_residual(struct Scsi_Host *instance) { unsigned long flags; int tmp; flags = claim_dma_lock(); clear_dma_ff(instance->dma_channel); tmp = get_dma_residue(instance->dma_channel); release_dma_lock(flags); return tmp; } #endif /* defined(i386) || defined(__alpha__) */ #endif /* defined(REAL_DMA) */ #endif /* __KERNEL__ */ #endif /* ndef ASM */ #endif /* NCR5380_H */
skywalker01/Samsung-Galaxy-S-Plus
drivers/scsi/NCR5380.h
C
gpl-2.0
13,954
{-# LANGUAGE Arrows #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Main (main) where import Control.Lens import Control.Monad.State import Control.Wire import Data.Fixed import Linear import FreeGame import FRP.Netwire import System.Random import Prelude hiding ((.), id) data Item = Treasure | Fuel | Upgrade UpgradeType deriving Eq data UpgradeType = Ballast | Rotor | Tank deriving Eq newtype Space = Space {getItem :: Maybe (V2 Double, Item)} makeWrapped ''Space data Stream a = a :- Stream a deriving Functor data LZipper a = LZipper {_leftZ :: Stream a, _hereZ :: a, _rightZ :: Stream a} deriving Functor makeLenses ''LZipper zleft :: LZipper a -> LZipper a zleft LZipper{_leftZ = ls, _hereZ = l, _rightZ = (r :- rs)} = LZipper{_leftZ = l :- ls, _hereZ = r, _rightZ = rs} zright :: LZipper a -> LZipper a zright LZipper{_leftZ = (l :- ls), _hereZ = r, _rightZ = rs} = LZipper{_leftZ = ls, _hereZ = l, _rightZ = r :- rs} type MapM = State (Int, StdGen) newtype Map = Map {getMap :: LZipper (LZipper (Either (MapM Space) Space))} makeWrapped ''Map initialMap :: Map initialMap = Map $ allZ (allZ initialTile) where allS x = x :- allS x allZ x = LZipper {_leftZ = allS x, _hereZ = x, _rightZ = allS x} initialTile :: Either (MapM Space) Space initialTile = Left $ do _1 +~ 1 x <- _2 %%= randomR (0, 2::Int) (Space . Just . (,) (V2 120 90)) <$> case x of 0 -> return Treasure 1 -> return Fuel 2 -> Upgrade <$> do y <- _2 %%= randomR (0, 2::Int) case y of 0 -> return Ballast 1 -> return Rotor 2 -> return Tank normalize :: Map -> MapM Map normalize m0 = do m1 <- normalize1 (mapUp m0) m2 <- normalize1 (mapLeft m1) m3 <- normalize1 (mapDown m2) m4 <- normalize1 (mapDown m3) m5 <- normalize1 (mapRight m4) m6 <- normalize1 (mapRight m5) m7 <- normalize1 (mapUp m6) m8 <- normalize1 (mapUp m7) normalize1 (mapLeft . mapDown $ m8) where normalize1 m = do case m^._Wrapped.hereZ.hereZ of Left a -> do r <- a return $ m & _Wrapped.hereZ.hereZ .~ Right r Right{} -> return m mapRight :: Map -> Map mapRight Map{getMap = m} = Map{getMap = fmap zright m} mapLeft :: Map -> Map mapLeft Map{getMap = m} = Map{getMap = fmap zleft m} mapUp :: Map -> Map mapUp Map{getMap = m} = Map{getMap = zleft m} mapDown :: Map -> Map mapDown Map{getMap = m} = Map{getMap = zright m} computeVVel :: Int -> Double -> Int -> Double computeVVel dir fuel upgradeLevel | nearZero fuel = 0 | otherwise = fromIntegral (signum dir) * speed where speed = log . (+exp 1) . fromIntegral $ upgradeLevel computeVPos :: SimpleWire Double Double computeVPos = integral 0 normalizeVPos :: Double -> (Double, Ordering) normalizeVPos c = let adjusted = c `mod'` 180 in (adjusted, adjusted `compare` c) computeHAcc :: Int -> Double -> Double -> Int -> Double computeHAcc dir fuel vel upgradeLevel | dir == 0 || nearZero fuel = -0.25 * vel | otherwise = fromIntegral (signum dir) * accel where accel = log . (+exp 1) . fromIntegral $ upgradeLevel computeHVel :: SimpleWire Double Double computeHVel = integralWith correct 0 . arr (flip (,) ()) where correct _ n | n >= 50 = 50 | otherwise = n computeHPos :: SimpleWire Double Double computeHPos = integral 0 normalizeHPos :: Double -> (Double, Ordering) normalizeHPos c = let adjusted = c `mod'` 240 in (adjusted, adjusted `compare` c) itemCollision :: SimpleWire (Map, V2 (Double, Ordering)) (Event Item, Map) itemCollision = proc (m0, V2 (xpos, xoff) (ypos, yoff)) -> let m = case (yoff, xoff) of (EQ, EQ) -> m0 (EQ, GT) -> mapUp m0 (GT, GT) -> mapUp $ mapRight m0 (GT, EQ) -> mapRight m0 (GT, LT) -> mapDown $ mapRight m0 (EQ, LT) -> mapDown m0 (LT, LT) -> mapDown $ mapLeft m0 (LT, EQ) -> mapLeft m0 (LT, GT) -> mapUp $ mapLeft m0 t = preview (_Wrapped.hereZ.hereZ._Right._Wrapped._Just) m in case t of Just (p,i) | distance p (V2 xpos ypos) <= 5 -> let n = m & _Wrapped.hereZ.hereZ._Right._Wrapped .~ Nothing in do ei <- now -< i ns <- id -< n returnA -< (ei, ns) _ -> do ei <- never -< () ms <- id -< m returnA -< (ei, ms) countItem :: Item -> SimpleWire (Event Item) Int countItem item = krSwitch (pure 0) . second adjustWire . (pure () &&& filterE (== item)) where adjustWire = arr ((arr (+1) .) <$) computeScore :: SimpleWire (Event Item) Int computeScore = countItem Treasure * 100 computeBallastUpgrade :: SimpleWire (Event Item) Int computeBallastUpgrade = countItem $ Upgrade Ballast computeRotorUpgrade :: SimpleWire (Event Item) Int computeRotorUpgrade = countItem $ Upgrade Rotor computeTankUpgrade :: SimpleWire (Event Item) Int computeTankUpgrade = countItem $ Upgrade Tank rateOfFuelDecrease :: Bool -> Bool -> Double rateOfFuelDecrease True True = 1 rateOfFuelDecrease False False = 0.2 rateOfFuelDecrease _ _ = 0.6 fuelRegenEvent :: SimpleWire (Int, Event Item) (Event Double) fuelRegenEvent = undefined maxFuel :: Int -> Double maxFuel = (*100) . log . (+exp 1) . fromIntegral computeFuel :: SimpleWire (Double, Event Double) Double computeFuel = krSwitch (stopAtZero .integral 100 . arr negate) . second adjustWire where adjustWire = arr $ fmap (\i _ -> integral i . arr negate) stopAtZero = arr $ \r -> if r < 0 then 0 else r mainWire :: SimpleWire (Int, Int, Map) (Int, Map, Bool) mainWire = proc (x,y,m0) -> do rec { vinf <- arr normalizeVPos . computeVPos -< computeVVel y fuel ballastUpgrade; hvel <- computeHVel -< computeHAcc y fuel hvel rotorUpgrade; hinf <- arr normalizeHPos . computeHPos -< hvel; (ei, m1) <- itemCollision -< (m0, V2 hinf vinf); ballastUpgrade <- computeBallastUpgrade -< ei; rotorUpgrade <- computeRotorUpgrade -< ei; tankUpgrade <- computeTankUpgrade -< ei; ef <- fuelRegenEvent -< (tankUpgrade, ei); fuel <- computeFuel -< (maxFuel tankUpgrade, ef); } score <- computeScore -< ei returnA -< (score, m1, nearZero fuel) main :: IO () main = do Just _ <- runGame Windowed (BoundingBox 0 0 480 360) $ do setTitle "Submarine game!" setFPS 60 clearColor blue sessiin <- liftIO clockSession_ return () where gameLoop m0 g0 c0 w0 = do let (m, (g, c)) = runState (normalize m) (g, c) ks <- keyStates_ u <- ks ^?! ix KeyUp d <- ks ^?! ix KeyDown l <- ks ^?! ix KeyLeft r <- ks ^?! ix KeyRight let v = case (u, d) of (Down, Up) -> (-1) (Up, Down) -> 1 (_, _) -> 0 h = case (l, r) of (Down, Up) -> (-1) (Up, Down) -> 1 (_, _) -> 0 let Identity (Left (s, m1, e), w1) = stepWire w0
Taneb/LD29
src/Main.hs
Haskell
gpl-2.0
7,122
body.wp-admin.widgets-php .option.preview, body.wp-admin.widgets-php .afg-pricing-details { display: none; } .afg-pricing-details, .afg-pricing-details ul { margin: 0; padding: 0; } .entry-content .afg-pricing-details li { margin: 0; } .afg-pricing-details.widget-settings { border: 1px dotted silver; padding: 0 1em; } .entry-content .afg-pricing-details li, .afg-pricing-details li { line-height: 1.75em; list-style: none outside none; } .entry-content .afg-pricing-details .condition, .afg-pricing-details .condition { color: silver; } .entry-content .afg-pricing-details .list-price.old, .afg-pricing-details .list-price.old { text-decoration: line-through; } .entry-content .afg-pricing-details .best-price, .afg-pricing-details .best-price { color: #990000; font-size: 1.4em; font-weight: bold; } .entry-content .afg-pricing-details .saved-amount, .entry-content .afg-pricing-details .saved-percentage, .afg-pricing-details .saved-amount, .afg-pricing-details .saved-percentage { color: #990000; }
wp-plugins/affiget-mini-for-amazon
review/elements/pricing-details/css/element.css
CSS
gpl-2.0
1,081
module("Array.prototype.reduce") test("reducing an array", function () { var a = [1,2,3], total total = a.reduce(function (a, b) { return a + b }) equal(6, total, "should sum the array") }) test("passing an initial value into the reduce", function () { var a = [1,2,3], total total = a.reduce(function (a, b) { return a + b }, 10) equal(16, total, "should sum the array") }) test("arguments that are passed to the function", function () { var a = [1, 2], previousValue, currentValue, index, array a.reduce(function (b,c,d,e) { previousValue = b currentValue = c index = d array = e }) equal(1, previousValue, "the previous value should be 0 initially and be the first argument to the function") equal(2, currentValue, "the current value should be 1 and be the second argument to the function") equal(1, index, "the index should be the third argument passed to the function") deepEqual(array, a, "the array being reduced should be passed as the fourth argument") }) test("skipping non existent indexes", function () { var a = [,,,,,,,,], count = 0 a.reduce(function () { count++ }, {}) equal(0, count, 'should skip non existent indexes') })
wangchuan/wangchuan.github.io
bower_components/augment.js/test/reduce_test.js
JavaScript
gpl-2.0
1,297
import logging from .model import LogEntry, LogLevels class NGWLogHandler(logging.Handler): """ Simple standard log handler for nextgisweb_log """ def __init__(self, level=LogLevels.default_value, component=None, group=None): logging.Handler.__init__(self, level=level) self.component = component self.group = group def emit(self, record): self.format(record) if record.exc_info: record.exc_text = logging._defaultFormatter.formatException(record.exc_info) else: record.exc_text = None # Insert log record: log_entry = LogEntry() log_entry.component = self.component log_entry.group = self.group log_entry.message_level = record.levelno log_entry.message_level_name = record.levelname log_entry.message_name = record.name log_entry.message_text = record.msg log_entry.exc_info = record.exc_text log_entry.persist()
nextgis/nextgisweb_log
nextgisweb_log/log_handler.py
Python
gpl-2.0
998
package null import ( "github.com/lmorg/murex/lang/stdio" "github.com/lmorg/murex/lang/types" ) func init() { // Register data type stdio.RegisterWriteArray(types.Null, newArrayWriter) }
lmorg/murex
builtins/types/null/init.go
GO
gpl-2.0
193
// license:BSD-3-Clause // copyright-holders:Curt Coder /********************************************************************** XL 80 cartridge emulation **********************************************************************/ #pragma once #ifndef __XL80__ #define __XL80__ #include "emu.h" #include "exp.h" #include "video/mc6845.h" //************************************************************************** // TYPE DEFINITIONS //************************************************************************** // ======================> c64_xl80_device class c64_xl80_device : public device_t, public device_c64_expansion_card_interface { public: // construction/destruction c64_xl80_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock); // optional information overrides virtual const tiny_rom_entry *device_rom_region() const override; virtual machine_config_constructor device_mconfig_additions() const override; // not really public MC6845_UPDATE_ROW( crtc_update_row ); protected: // device-level overrides virtual void device_start() override; virtual void device_reset() override; // device_c64_expansion_card_interface overrides virtual UINT8 c64_cd_r(address_space &space, offs_t offset, UINT8 data, int sphi2, int ba, int roml, int romh, int io1, int io2) override; virtual void c64_cd_w(address_space &space, offs_t offset, UINT8 data, int sphi2, int ba, int roml, int romh, int io1, int io2) override; virtual int c64_game_r(offs_t offset, int sphi2, int ba, int rw) override { return 1; } virtual int c64_exrom_r(offs_t offset, int sphi2, int ba, int rw) override { return 0; } private: required_device<h46505_device> m_crtc; required_device<palette_device> m_palette; required_memory_region m_char_rom; optional_shared_ptr<UINT8> m_ram; }; // device type definition extern const device_type C64_XL80; #endif
GiuseppeGorgoglione/mame
src/devices/bus/c64/xl80.h
C
gpl-2.0
1,902
<?php require_once(PLOGGER_DIR . 'admin/plog-admin-functions.php'); @include(PLOGGER_DIR . 'plog-config.php'); function do_install($form) { $form = array_map('stripslashes',$form); $form = array_map('trim',$form); $errors = check_requirements(); if (sizeof($errors) > 0) { print '<p>Plogger wont work until the following problems are resolved</p>'; print '<ul>'; foreach($errors as $error) { print '<li>' . $error . '</li>'; }; print '</ul>'; print '<form method="GET" action="_install.php"><input type="submit" value="Try again"/></form>'; return false; }; if (defined('PLOGGER_DB_HOST')) { $mysql = check_mysql(PLOGGER_DB_HOST,PLOGGER_DB_USER,PLOGGER_DB_PW,PLOGGER_DB_NAME); // looks like we are already configured if (empty($mysql)) { print '<p>Plogger is already installed!</p>'; return false; }; }; $ok = false; $errors = array(); if (!empty($form['action']) && 'install' == $form['action']) { if (empty($form['db_host'])) { $errors[] = 'Please enter the name of your MySQL host.'; }; if (empty($form['db_user'])) { $errors[] = 'Please enter the MySQL username.'; }; if (empty($form['db_pass'])) { $errors[] = 'Please enter the MySQL password.'; } if (empty($form['db_name'])) { $errors[] = 'Please enter the MySQL database name.'; }; if (empty($form['gallery_name'])) { $errors[] = 'Please enter the name for your gallery.'; }; if (empty($form['admin_email'])) { $errors[] = 'Please enter your e-mail address.'; }; if (empty($errors)) { $errors = check_mysql($form['db_host'],$form['db_user'],$form['db_pass'],$form['db_name']); $ok = empty($errors); }; if (!$ok) { print '<ul><li>'; print join("</li>\n<li>",$errors); print '</li></ul>'; } else { $password = generate_password(); $_SESSION["install_values"] = array( "gallery_name" => $form["gallery_name"], "admin_email" => $form["admin_email"], "admin_password" => $password, "admin_username" => "admin" ); $conf = create_config_file($form['db_host'],$form['db_user'],$form['db_pass'],$form['db_name']); // if configuration file is writable, then set the values // otherwise serve the config file to user and ask her to // upload it to webhost if (config_writable()) { write_config($conf); } else { $_SESSION["plogger_config"] = $conf; }; require(PLOGGER_DIR . 'lib/plogger/form_setup_complete.php'); return true; }; }; // most of the time it's probably running on localhost if (empty($form['db_host'])) { $form['db_host'] = 'localhost'; }; $init_vars = array('db_user','db_pass','db_name','gallery_name','admin_email'); foreach($init_vars as $var) { if (empty($form[$var])) { $form[$var] = ""; }; }; require(PLOGGER_DIR . 'lib/plogger/form_setup.php'); } function create_tables() { // since 4.1 MySQL has support for specifying character encoding for tables // and I really want to use it if available. So we need figure out what version // we are running on and to the right thing $mysql_version = mysql_get_server_info(); $mysql_charset_support = "4.1"; $default_charset = ""; if (1 == version_compare($mysql_version,$mysql_charset_support)) { $default_charset = "DEFAULT CHARACTER SET UTF8"; }; maybe_add_table( TABLE_PREFIX . 'collections' ,"`name` varchar(128) NOT NULL default '', `description` varchar(255) NOT NULL default '', `path` varchar(255) NOT NULL default '', `id` int(11) NOT NULL auto_increment, `thumbnail_id` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (id)" ,"Type=MyISAM $default_charset"); maybe_add_table( TABLE_PREFIX . 'albums' ," `name` varchar(128) NOT NULL default '', `id` int(11) NOT NULL auto_increment, `description` varchar(255) NOT NULL default '', `path` varchar(255) NOT NULL default '', `parent_id` int(11) NOT NULL default '0', `thumbnail_id` int(11) NOT NULL default '0', PRIMARY KEY (id), INDEX pid_idx (parent_id)" ," Type=MyISAM $default_charset"); maybe_add_table( TABLE_PREFIX . 'pictures' ,"`path` varchar(255) NOT NULL default '', `parent_album` int(11) NOT NULL default '0', `parent_collection` int(11) NOT NULL default '0', `caption` mediumtext NOT NULL, `description` text NOT NULL, `id` int(11) NOT NULL auto_increment, `date_modified` timestamp(14) NOT NULL, `date_submitted` timestamp(14) NOT NULL, `EXIF_date_taken` varchar(64) NOT NULL default '', `EXIF_camera` varchar(64) NOT NULL default '', `EXIF_shutterspeed` varchar(64) NOT NULL default '', `EXIF_focallength` varchar(64) NOT NULL default '', `EXIF_flash` varchar(64) NOT NULL default '', `EXIF_aperture` varchar(64) NOT NULL default '', `allow_comments` int(11) NOT NULL default '1', PRIMARY KEY (id), INDEX pa_idx (parent_album), INDEX pc_idx (parent_collection)" ,"Type=MyISAM $default_charset"); maybe_add_table( TABLE_PREFIX . 'comments' ,"`id` int(11) NOT NULL auto_increment, `parent_id` int(11) NOT NULL default '0', `author` varchar(64) NOT NULL default '', `email` varchar(64) NOT NULL default '', `url` varchar(64) NOT NULL default '', `date` datetime NOT NULL, `comment` longtext NOT NULL, `ip` char(64), `approved` tinyint default '1', PRIMARY KEY (id), INDEX pid_idx (parent_id), INDEX approved_idx (approved)" ,"Type=MyISAM $default_charset"); maybe_add_table( TABLE_PREFIX . 'config' ,"`max_thumbnail_size` int(11) NOT NULL default '0', `max_display_size` int(11) NOT NULL default '0', `thumb_num` int(11) NOT NULL default '0', `admin_username` varchar(64) NOT NULL default '', `admin_password` varchar(64) NOT NULL default '', `admin_email` varchar(50) NOT NULL default '', `date_format` varchar(64) NOT NULL default '', `compression` int(11) NOT NULL default '75', `default_sortby` varchar(20) NOT NULL default '', `default_sortdir` varchar(5) NOT NULL default '', `album_sortby` varchar(20) NOT NULL default '', `album_sortdir` varchar(5) NOT NULL default '', `collection_sortby` varchar(20) NOT NULL default '', `collection_sortdir` varchar(5) NOT NULL default '', `gallery_name` varchar(255) NOT NULL default '', `allow_dl` smallint(1) NOT NULL default '0', `allow_comments` smallint(1) NOT NULL default '1', `allow_print` smallint(1) NOT NULL default '1', `truncate` int(11) NOT NULL default '12', `square_thumbs` tinyint default 1, `feed_num_entries` int(15) NOT NULL default '15', `rss_thumbsize` int(11) NOT NULL default '400', `feed_title` text NOT NULL, `use_mod_rewrite` tinyint NOT NULL default '0', `gallery_url` varchar(255) NOT NULL default '', `comments_notify` tinyint NOT NULL default '1', `comments_moderate` tinyint NOT NULL default '0', `feed_language` varchar(255) NOT NULL default 'en-us', `theme_dir` varchar(128) NOT NULL default '', `thumb_nav_range` int(11) NOT NULL default '0', `enable_thumb_nav` tinyint default '0', `allow_fullpic` tinyint default '1'" ,"Type=MyISAM $default_charset"); maybe_add_table( TABLE_PREFIX . 'thumbnail_config' ,"`id` int(10) unsigned NOT NULL auto_increment, `update_timestamp` int(10) unsigned default NULL, `max_size` int(10) unsigned default NULL, `disabled` tinyint default 0, PRIMARY KEY (`id`)"); maybe_add_table( TABLE_PREFIX . 'tag2picture' ,"`tag_id` bigint(20) unsigned NOT NULL default '0', `picture_id` bigint(20) unsigned NOT NULL default '0', `tagdate` datetime default NULL, KEY `tag_id` (`tag_id`), KEY `picture_id` (`picture_id`)" ,"Type=MyISAM $default_charset"); maybe_add_table( TABLE_PREFIX . 'tags' ,"`id` bigint(20) unsigned NOT NULL auto_increment, `tag` char(50) NOT NULL default '', `tagdate` datetime NOT NULL default '0000-00-00 00:00:00', `urlified` char(50) NOT NULL default '', PRIMARY KEY (`id`), UNIQUE `tag` (`tag`), UNIQUE `urlified` (`urlified`)" ,"Type=MyISAM $default_charset"); } function configure_plogger($form) { // use a random timestamp from the past to keep the existing thumbnails $long_ago = 1096396500; $thumbnail_sizes = array( THUMB_SMALL => 100, THUMB_LARGE => 500, THUMB_RSS => 400, THUMB_NAV => 60 ); foreach($thumbnail_sizes as $key => $size) { $sql = "INSERT INTO `".TABLE_PREFIX."thumbnail_config` (id,update_timestamp,max_size) VALUES('$key','$long_ago','$size')"; mysql_query($sql); }; $config['default_theme_dir'] = PLOGGER_DIR . 'themes/default/'; $config['baseurl'] = "http://".$_SERVER["SERVER_NAME"]. substr($_SERVER["PHP_SELF"],0,strrpos($_SERVER["PHP_SELF"],"/")) . "/"; $config['admin_username'] = 'admin'; $config['admin_password'] = $form['admin_password']; $config['admin_email'] = $form['admin_email']; $config['gallery_name'] = $form['gallery_name']; $config = array_map('mysql_escape_string',$config); $query = "INSERT INTO `".TABLE_PREFIX."config` (`theme_dir`, `compression`, `max_thumbnail_size`, `max_display_size`, `thumb_num`, `admin_username`, `admin_email`, `admin_password`, `date_format`, `feed_title`, `gallery_name`, `gallery_url`) VALUES ('${config['default_theme_dir']}', 75, 100, 500, 20, '${config['admin_username']}', '${config['admin_email']}', MD5('${config['admin_password']}'), 'n.j.Y', 'Plogger Photo Feed', '${config['gallery_name']}', '${config['baseurl']}')"; mysql_query($query) or die(mysql_error().'<br /><br />'. $query); mail($config['admin_email'],"Your new gallery","You have successfully installed your new Plogger gallery. You can manage it at ${config['baseurl']}/admin Username is ${config['admin_username']} and password ${config['admin_password']}."); } function create_config_file($db_host,$db_user,$db_pass,$db_name) { $cfg_file = "<?php\n"; $cfg_file .= '// this is the file used to connect to your database.'."\n"; $cfg_file .= '// you must change these values in order to run the gallery.'."\n"; $cfg_file .= 'define("PLOGGER_DB_HOST","'.$db_host.'");'."\n"; $cfg_file .= 'define("PLOGGER_DB_USER","'.$db_user.'");'."\n"; $cfg_file .= 'define("PLOGGER_DB_PW","'.$db_pass.'");'."\n"; $cfg_file .= 'define("PLOGGER_DB_NAME","'.$db_name.'");'."\n"; $cfg_file .= "?>\n"; return $cfg_file; } function maybe_add_column($table,$column,$add_sql) { $sql = "DESCRIBE $table"; $res = mysql_query($sql); $found = false; while($row = mysql_fetch_array($res,MYSQL_NUM)) { if ($row[0] == $column) $found = true; }; if (!$found) { mysql_query("ALTER TABLE $table ADD `$column` ". $add_sql); return "<li>Adding new field $column to database."; } else { return "<li>$column already present in database."; }; } function maybe_drop_column($table,$column) { $sql = "DESCRIBE $table"; $res = mysql_query($sql); $found = false; while($row = mysql_fetch_array($res,MYSQL_NUM)) { if ($row[0] == $column) $found = true; }; if ($found) { $sql = "ALTER TABLE $table DROP `$column`"; mysql_query($sql); return "<li>dropping $column"; } else { //print "$column does not exist<br>"; }; } function maybe_add_table($table,$add_sql,$options = "") { $sql = "DESCRIBE $table"; $res = mysql_query($sql); if (!$res) { $q = "CREATE table `$table` ($add_sql) $options"; mysql_query($q); if (mysql_error()) { var_dump(mysql_error()); }; } else { return "<li>Table `$table` already exists, ignoring."; }; } function gd_missing() { require_once(dirname(__FILE__) . '/../../lib/phpthumb/phpthumb.functions.php'); // this is copied over from phpthumb return phpthumb_functions::gd_version() < 1; } function check_requirements() { $errors = array(); if (gd_missing()) { $errors[] = "PHP GD module was not detected."; }; if (!function_exists('mysql_connect')) { $errors[] = "PHP MySQL module was not detected."; }; $files_to_read = array("./","./admin","./css","./images","./lib","./thumbs","./uploads"); foreach($files_to_read as $file){ if (!is_readable(PLOGGER_DIR . $file)){ $errors[] = "The path ".realpath(PLOGGER_DIR . $file)." (".$file.") is not readable."; } } $files_to_write = array("./","./thumbs","./images", "./uploads"); foreach($files_to_write as $file){ if (!is_writable(PLOGGER_DIR . $file)){ $errors[] = 'The path '.realpath(PLOGGER_DIR . $file).' is not writable by the Web server.'; } } return $errors; } function check_mysql($host,$user,$pass,$database) { $errors = array(); if (function_exists('mysql_connect')) { $connection = @mysql_connect($host,$user,$pass); if (!$connection) { $errors[] = "Cannot connect to MySQL with the information provided. MySQL error: " . mysql_error(); }; }; $select = @mysql_select_db($database); if (!$select) { $errors[] = "Couldn't find the database $database. MySQL error: " . mysql_error(); }; return $errors; } function generate_password() { $src = preg_split("//","abcdefghkmnpqrstuvwxyz23456789",-1,PREG_SPLIT_NO_EMPTY); shuffle($src); return join("",array_slice($src,0,5)); } function config_writable() { $cf = PLOGGER_DIR . "plog-config.php"; if (file_exists($cf)) { return is_writable($cf); }; return is_writable(PLOGGER_DIR); } function write_config($data) { $cf = PLOGGER_DIR . "plog-config.php"; $handle = fopen($cf,"w"); fwrite($handle,$data); fclose($handle); } ?>
alanhaggai/plogger
lib/plogger/install_functions.php
PHP
gpl-2.0
13,304
/** * WooCommerce Admin RTL Styles * * @package WebMan WordPress Theme Framework * @copyright 2014 WebMan - Oliver Juhas * * @since 3.0 * @version 3.0 */ .woocommerce table.form-table .color_box, table.wc_input_table .button, table.wc_tax_rates .button, .widefat .column-order_actions a.button, .widefat .column-user_actions a.button, .widefat .column-wc_actions a.button, #order_data .order_data_column, #poststuff #woocommerce-order-totals .total_row p.first, #woocommerce-order-items .bulk_actions, #woocommerce-coupon-data ul.wc-tabs, #woocommerce-product-data ul.wc-tabs, .woocommerce ul.wc-tabs, .woocommerce_options_panel label, .woocommerce_options_panel legend, .woocommerce_options_panel input[type=email], .woocommerce_options_panel input[type=number], .woocommerce_options_panel input[type=text], .woocommerce_options_panel select, .wc-metabox-content img.ui-datepicker-trigger, .woocommerce_options_panel img.ui-datepicker-trigger, .woocommerce_options_panel .chosen-container-multi, .chosen-container-multi .chosen-choices li, .column-coupon_code .code, ul.wc_coupon_list .code, .woocommerce-reports-wide .postbox .chart-with-sidebar .chart-sidebar, .woocommerce-reports-wrap .postbox .chart-with-sidebar .chart-sidebar, .woocommerce-reports-wide .postbox h3.stats_range ul li, .woocommerce-reports-wrap .postbox h3.stats_range ul li, #woocommerce-product-images .inside #product_images_container ul li.add, #woocommerce-product-images .inside #product_images_container ul li.image, #woocommerce-product-images .inside #product_images_container ul li.wc-metabox-sortable-placeholder {float: right} table.wc_input_table .export, table.wc_input_table .import, table.wc_tax_rates .export, table.wc_tax_rates .import, #poststuff #woocommerce-order-totals .total_row p.last, #woocommerce-order-items .add_items, .woocommerce-reports-wide .postbox h3.stats_range .export_csv, .woocommerce-reports-wrap .postbox h3.stats_range .export_csv, .wc-metaboxes-wrapper .fr, .wc-metaboxes-wrapper button.add_attribute, .wc-metaboxes-wrapper button.add_variable_attribute, .wc-metaboxes-wrapper select.attribute_taxonomy {float: left} #poststuff #woocommerce-order-totals .total_row p.first {clear: right} table.wc_gateways .settings, table.wc_shipping .settings {text-align: left} .woocommerce_order_items_wrapper table.woocommerce_order_items thead th, .woocommerce_order_items_wrapper table.woocommerce_order_items tbody th, .woocommerce_order_items_wrapper table.woocommerce_order_items td, .wc-metaboxes-wrapper .wc-metabox table td label, .wc-metaboxes-wrapper .wc-metabox table td {text-align: right} table.wp-list-table span.wc-featured, table.wp-list-table span.wc-image, table.wp-list-table span.wc-type { text-indent: 9999px; overflow: hidden; } #order_data .order_data_column {padding: 0 0 0 2%} #order_data .order_data_column:last-child {padding-left: 0} #woocommerce-order-items .add_items, #woocommerce-order-items .bulk_actions { padding-left: 12px; padding-right: 12px; } #tiptip_arrow, #tiptip_arrow_inner { left: auto; right: 50%; margin-right: -6px; } ul.order_notes li .note_content:after { left: auto; right: 20px; } /** * Tabs */ #woocommerce-coupon-data .panel-wrap, #woocommerce-product-data .panel-wrap { padding-left: 0; padding-right: 153px; } #woocommerce-coupon-data .wc-tabs-back, #woocommerce-product-data .wc-tabs-back { left: auto; right: 0; border-right: 0; border-left: 1px solid #DFDFDF; } #woocommerce-coupon-data ul.wc-tabs, #woocommerce-product-data ul.wc-tabs, .woocommerce ul.wc-tabs { margin-left: 0; margin-right: -153px; } #woocommerce-coupon-data ul.wc-tabs li.active a, #woocommerce-product-data ul.wc-tabs li.active a, .woocommerce ul.wc-tabs li.active a {margin: 0 0 0 -1px} .woocommerce_options_panel fieldset.form-field, .woocommerce_options_panel p.form-field {padding: 5px 162px 5px 20px !important} .woocommerce_options_panel label, .woocommerce_options_panel legend {margin: 0 -150px 0 0} img.help_tip {margin: 0 9px 0 0} .woocommerce_options_panel .description {margin: 0 7px 0 0} .chosen-container-multi .chosen-choices li {margin: 3px 5px 3px 0} .column-coupon_code .code, ul.wc_coupon_list .code {margin: 0 0 0 8px} /** * Reports */ .woocommerce-reports-wide .postbox .chart-with-sidebar, .woocommerce-reports-wrap .postbox .chart-with-sidebar {padding: 12px 249px 12px 12px} .woocommerce-reports-wide .postbox .chart-with-sidebar .chart-sidebar, .woocommerce-reports-wrap .postbox .chart-with-sidebar .chart-sidebar { margin-left: 0; margin-right: -237px; } .woocommerce-reports-wide .postbox h3.stats_range .export_csv, .woocommerce-reports-wrap .postbox h3.stats_range .export_csv { border-left: 0; border-right: 1px solid #DFDFDF; } .woocommerce-reports-wide .postbox h3.stats_range ul li a, .woocommerce-reports-wrap .postbox h3.stats_range ul li a { border-right: 0; border-left: 1px solid #DFDFDF; } /** * Products */ #product_cat_thumbnail { float: right !important; margin-right: 0 !important; margin-left: 10px !important; } #woocommerce-product-images .inside #product_images_container {padding: 0 9px 0 0} #woocommerce-product-images .inside #product_images_container ul li.add, #woocommerce-product-images .inside #product_images_container ul li.image, #woocommerce-product-images .inside #product_images_container ul li.wc-metabox-sortable-placeholder {margin: 9px 0 0 9px} #woocommerce-product-data h3.hndle label:first-child { margin-right: 0; margin-left: 1em; border-right: 0; border-left: 1px solid #DFDFDF; } h3.hndle label[for="_virtual"], h3.hndle label[for="_downloadable"] {display: inline-block !important} .woocommerce_options_panel .downloadable_files {padding: 0 162px 0 9px} .woocommerce_options_panel .downloadable_files label { left: auto; right: 0; } .wc-metaboxes-wrapper .fr, .wc-metaboxes-wrapper button.add_attribute, .wc-metaboxes-wrapper button.add_variable_attribute, .wc-metaboxes-wrapper select.attribute_taxonomy {margin: 0 6px 0 0} /** * Chose JS layout fixes */ .chosen-container .chosen-drop { left: auto; right: -9999px; } /* End of file */
tessak22/kbs
wp-content/themes/mustang-lite/library/assets/css/rtl-admin-woocommerce.css
CSS
gpl-2.0
6,389
/************************** * * GENERAL * **************************/ .slider_wrapper { border-bottom: 0; z-index: 999; z-index: 0; position: relative; overflow: hidden; } .camera_target_content { overflow: visible !important; } .camera_wrap { overflow: hidden; display: none; position: relative; position: static; overflow: visible !important; z-index: 0; margin-bottom: 0 !important; } .camera_wrap img { max-width: 10000px; } .camera_fakehover { height: 100%; min-height: 60px; position: static; width: 100%; z-index: 990; } .camera_wrap { width: 100%; } .camera_src { display: none; } .cameraCont, .cameraContents { height: 100%; position: relative; width: 100%; z-index: 1; } .cameraSlide { bottom: 0; left: 0; position: absolute; right: 0; top: 0; width: 100%; } .cameraContent { bottom: 0; display: none; left: 0; position: absolute; right: 0; top: 0; width: 100%; } .camera_target { bottom: 0; height: 100%; left: 0; overflow: hidden; position: absolute; right: 0; text-align: left; top: 0; width: 100%; z-index: 0; } .camera_overlayer { bottom: 0; height: 100%; left: 0; overflow: hidden; position: absolute; right: 0; top: 0; width: 100%; z-index: 0; } .camera_target_content { bottom: 0; left: 0; overflow: hidden; position: absolute; right: 0; top: 0; z-index: 2; } .camera_target_content .camera_link { background: url(../images/blank.gif); display: block; height: 100%; text-decoration: none; } .camera_loader { background: #fff url(../images/camera-loader.gif) no-repeat center; background: rgba(255, 255, 255, 0.9) url(../images/camera-loader.gif) no-repeat center; border: 1px solid #ffffff; border-radius: 18px; height: 36px; left: 50%; overflow: hidden; position: absolute; margin: -18px 0 0 -18px; top: 50%; width: 36px; z-index: 3; } .camera_nav_cont { height: 65px; overflow: hidden; position: absolute; right: 9px; top: 15px; width: 120px; z-index: 4; } .camerarelative { overflow: hidden; position: relative; } .imgFake { cursor: pointer; } .camera_commands > .camera_stop { display: none; } .slide_wrapper .camera_prev{ background: url(../images/prevnext_bg.png) 0 0 repeat; width: 70px; top: 0 !important; height: auto !important; bottom: 0; left: -80px; display: block; position: absolute; opacity: 1 !important; transition: 0.5s ease; -o-transition: 0.5s ease; -webkit-transition: 0.5s ease; } .slide_wrapper .camera_prev>span { background: url(../images/prev.png) center 0 no-repeat; top: 50%; margin-top: -10px; position: absolute; display: block; height: 20px; left: 0; right: 0; } .slide_wrapper .camera_next>span { background: url(../images/next.png) center 0 no-repeat; top: 50%; margin-top: -10px; position: absolute; display: block; left: 0; right: 0; height: 20px; } .slide_wrapper .camera_next { background: url(../images/prevnext_bg.png) 0 0 repeat; width: 70px; top: 0 !important; bottom: 0; height: auto !important; right: -80px; display: block; position: absolute; opacity: 1 !important; transition: 0.5s ease; -o-transition: 0.5s ease; -webkit-transition: 0.5s ease; } .camera_thumbs_cont { z-index: 991; width: 100% !important; position: relative; height: 82px; } .camera_thumbs_cont > div { width: 100%; position: relative; height: 82px; } .camera_thumbs_cont ul { width: auto !important; padding-top: 13px; overflow: hidden; position: absolute; background-color: #fff; margin: 0 !important; margin-left: 0px !important; left: 201px !important; right: 204px !important; margin-top: -78px !important; text-align: center; } .camera_thumbs_cont ul li { background-color: #414141; display: inline-block; font-size: 0 !important; width: 170px !important; border: 1px solid #222426; } .camera_thumbs_cont ul li+li { margin-left: 5px !important; } .camera_thumbs_cont ul li+li +li { margin-left: 6px !important; } .camera_thumbs_cont ul li > img { cursor: pointer; vertical-align:bottom; transition: 0.5s ease; -o-transition: 0.5s ease; -webkit-transition: 0.5s ease; } .camera_clear { display: block; clear: both; } .showIt { display: none; } .camera_clear { clear: both; display: block; height: 1px; margin: -1px 0 25px; position: relative; } /************************** * * COLORS & SKINS * **************************/ /************************** .camera_pag { display: block; position: absolute; left: 50%; margin-left: -23px; bottom: 151px; height: 12px; overflow: hidden; float: left; z-index: 999; text-align: left; bottom: 58px; } .camera_pag_ul { overflow: hidden; } .camera_pag ul li { float: left; } .camera_pag ul li+li { margin-left: 5px; } .camera_pag ul li span { display: block; width: 12px; background: url(../images/pagination.png) right 0 no-repeat; height: 12px; overflow: hidden; color: transparent; text-indent: -100px; } .camera_pag ul li:hover span, .camera_pag ul li.cameracurrent span { background-position: 0 0; cursor: pointer; } **************************/ .camera_prev { display: block; position: absolute; width: 39px; height: 39px; z-index: 999; background: url(../images/prevnext.png) 0 0 no-repeat; bottom: 0px; opacity: 1 !important; transition: 0s ease; -o-transition: 0s ease; -webkit-transition: 0s ease; cursor: pointer; left: 40px; top: 50%; margin-top: -20px; } .camera_next { display: block; position: absolute; width: 39px; height: 39px; z-index: 999; background: url(../images/prevnext.png) right 0 no-repeat; bottom: 0px; opacity: 1 !important; transition: 0s ease; -o-transition: 0s ease; -webkit-transition: 0s ease; cursor: pointer; right: 40px; top: 50%; margin-top: -20px; } .camera_prev:hover, .camera_next:hover { opacity: 0.5 !important; }
Christophe-Delay/site_web
css/camera.css
CSS
gpl-2.0
6,180
/* ========================================================================== Karisma Theme Styles ========================================================================== */ .soliloquy-theme-karisma:after { display: none; height: 0; line-height: 0; visibility: hidden; content: url('images/left.png') url('images/right.png') url('images/circles.png') url('images/pause.png') url('images/play.png'); } .soliloquy-theme-karisma .soliloquy-controls-direction a, .soliloquy-theme-karisma .soliloquy-controls-auto-item, .soliloquy-theme-karisma .soliloquy-controls-auto-item a { -webkit-transition: background-color .2s linear, color .2s linear; -moz-transition: background-color .2s linear, color .2s linear; -o-transition: background-color .2s linear, color .2s linear; -ms-transition: background-color .2s linear, color .2s linear; transition: background-color .2s linear, color .2s linear; background: #222; border-radius: 2px; -webkit-border-radius: 2px; -moz-border-radius: 2px; top: auto; left: auto; width: 23px; height: 23px; margin-top: 0; bottom: 10px; } .soliloquy-theme-karisma .soliloquy-controls-direction a:hover, .soliloquy-theme-karisma .soliloquy-controls-auto-item a:hover { background: #ffd62c; } .soliloquy-theme-karisma .soliloquy-prev { right: 38px; } .soliloquy-theme-karisma .soliloquy-next { right: 10px; } .soliloquy-theme-karisma .soliloquy-prev span, .soliloquy-theme-karisma .soliloquy-next span { width: 7px; height: 11px; display: block; background: transparent url('images/left.png') no-repeat scroll 0 0; margin: 6px 0 0 7px; } .soliloquy-theme-karisma .soliloquy-next span { background: transparent url('images/right.png') no-repeat scroll 0 0; margin: 6px 0 0 9px; } .soliloquy-theme-karisma .soliloquy-prev:hover span, .soliloquy-theme-karisma .soliloquy-next:hover span { background-position: 0 -11px; } .soliloquy-theme-karisma .soliloquy-pager { width: auto; height: 11px; right: 10px; bottom: 16px; } .soliloquy-theme-karisma .soliloquy-has-controls-auto .soliloquy-pager { right: 43px; } .soliloquy-theme-karisma .soliloquy-has-controls-direction .soliloquy-pager { right: 71px; } .soliloquy-theme-karisma .soliloquy-has-controls-direction.soliloquy-has-controls-auto .soliloquy-pager { right: 99px; } .soliloquy-theme-karisma .soliloquy-pager-item { margin-left: 5px; } .soliloquy-theme-karisma .soliloquy-pager-link { width: 11px; height: 11px; background: transparent url('images/circles.png') no-repeat scroll 0 0; transition: none; -moz-transition: none; -webkit-transition: none; -ms-transition: none; -o-transition: none; } .soliloquy-theme-karisma .soliloquy-pager-link:hover, .soliloquy-theme-karisma .soliloquy-pager-link.active { background: transparent url('images/circles.png') no-repeat scroll 0 -11px; } .soliloquy-theme-karisma .soliloquy-controls-auto-item { right: 10px; } .soliloquy-theme-karisma .soliloquy-has-controls-direction .soliloquy-controls-auto-item { right: 67px; } .soliloquy-theme-karisma .soliloquy-controls-auto-item a { position: absolute; top: 0; left: 0; } .soliloquy-theme-karisma .soliloquy-controls-auto-item .soliloquy-stop span { width: 7px; height: 11px; display: block; background: transparent url('images/pause.png') no-repeat scroll 0 0; margin: 6px 0 0 8px; } .soliloquy-theme-karisma .soliloquy-controls-auto-item .soliloquy-stop:hover span { background-position: 0 -11px; } .soliloquy-theme-karisma .soliloquy-controls-auto-item .soliloquy-start span { width: 11px; height: 11px; display: block; background: transparent url('images/play.png') no-repeat scroll 0 0; margin: 6px 0 0 6px; } .soliloquy-theme-karisma .soliloquy-controls-auto-item .soliloquy-start:hover span { background-position: 0 -11px; } .soliloquy-theme-karisma .soliloquy-caption { width: 55%; top: 10px; left: 10px; right: auto; bottom: auto; } .soliloquy-theme-karisma .soliloquy-caption-inside { font-size: .75em; font-style: italic; font-family: Georgia, serif; padding: 10px 20px; text-align: left; } .soliloquy-theme-karisma .soliloquy-caption-inside a, .soliloquy-theme-karisma .soliloquy-caption-inside .soliloquy-fc-title-link, .soliloquy-theme-karisma .soliloquy-caption-inside .soliloquy-fc-read-more { color: #ffd62c; } .soliloquy-theme-karisma .soliloquy-caption-inside .soliloquy-fc-title, .soliloquy-theme-karisma .soliloquy-caption-inside .soliloquy-fc-title-link { font-family: Georgia, serif; font-size: 1.5em; font-weight: normal; } .soliloquy-theme-karisma .soliloquy-caption-inside .soliloquy-fc-title-link { font-size: 1em; } .soliloquy-theme-karisma .soliloquy-caption-inside .soliloquy-fc-read-more { font-weight: normal; } /* ========================================================================== Retina Styles ========================================================================== */ @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and ( min--moz-device-pixel-ratio: 2), only screen and ( -o-min-device-pixel-ratio: 2/1), only screen and ( min-device-pixel-ratio: 2), only screen and ( min-resolution: 192dpi), only screen and ( min-resolution: 2dppx) { .soliloquy-theme-karisma .soliloquy-prev span { background-image: url('images/left@2x.png'); background-size: 7px 22px; } .soliloquy-theme-karisma .soliloquy-next span { background-image: url('images/right@2x.png'); background-size: 7px 22px; } .soliloquy-theme-karisma .soliloquy-pager-link, .soliloquy-theme-karisma .soliloquy-pager-link:hover, .soliloquy-theme-karisma .soliloquy-pager-link.active { background-image: url('images/circles@2x.png'); background-size: 11px 22px; } .soliloquy-theme-karisma .soliloquy-controls-auto-item .soliloquy-stop span { background-image: url('images/pause@2x.png'); background-size: 7px 22px; } .soliloquy-theme-karisma .soliloquy-controls-auto-item .soliloquy-start span { background-image: url('images/play@2x.png'); background-size: 11px 22px; } }
gregdavispsu/kennett-design
wp-content/plugins/soliloquy-themes/themes/karisma/style.css
CSS
gpl-2.0
6,404
// ImGui Win32 + DirectX11 binding // In this binding, ImTextureID is used to store a 'ID3D11ShaderResourceView*' texture identifier. Read the FAQ about ImTextureID in imgui.cpp. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown(). // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. // https://github.com/ocornut/imgui struct ID3D11Device; struct ID3D11DeviceContext; struct IDXGISwapChain; #include "../imgui.h" IMGUI_API bool ImGui_ImplDX11_Init (IDXGISwapChain* pSwapChain, ID3D11Device* device, ID3D11DeviceContext* device_context); IMGUI_API void ImGui_ImplDX11_Shutdown (); IMGUI_API void ImGui_ImplDX11_NewFrame (); // Use if you want to reset your rendering device without losing ImGui state. IMGUI_API void ImGui_ImplDX11_InvalidateDeviceObjects(); IMGUI_API bool ImGui_ImplDX11_CreateDeviceObjects(); // Handler for Win32 messages, update mouse/keyboard data. // You may or not need this for your implementation, but it can serve as reference for handling inputs. // Commented out to avoid dragging dependencies on <windows.h> types. You can copy the extern declaration in your code. /* IMGUI_API LRESULT ImGui_ImplDX11_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); */
greedyliz/SpecialK-APPatch
include/imgui/backends/imgui_d3d11.h
C
gpl-2.0
1,509
package com.karniyarik.recognizer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import net.zemberek.erisim.Zemberek; import net.zemberek.yapi.Kelime; import net.zemberek.yapi.Kok; import org.apache.commons.lang.StringUtils; import com.karniyarik.common.util.StringUtil; import com.karniyarik.recognizer.xml.item.ItemType; public abstract class BaseFeatureRecognizer { private ItemStore itemStore = null; private Zemberek zemberek = null; public static final String DEFAULT_VALUE = "Diğer"; public void setZemberek(Zemberek zemberek) { this.zemberek = zemberek; } public Zemberek getZemberek() { return zemberek; } public String getLongestAsciiCorrectedWord(String string) { Kelime[] asciidenTurkceyeCevirilmisKelimeler = zemberek.asciiCozumle(string); Kelime enUzunKokluKelime = null; for (Kelime cevirilmisKelime : asciidenTurkceyeCevirilmisKelimeler) { if (enUzunKokluKelime != null) { if (cevirilmisKelime.kok().icerik().length() > enUzunKokluKelime.kok().icerik().length()) { enUzunKokluKelime = cevirilmisKelime; } } else { enUzunKokluKelime = cevirilmisKelime; } } if (enUzunKokluKelime != null) { string = enUzunKokluKelime.kok().icerik(); } return string; } public String getWordRoot(String string) { Kok[] kok = zemberek.kokBulucu().kokBul(string); return string; } protected final void setItemStore(ItemStore itemStore) { this.itemStore = itemStore; } protected final ItemStore getItemStore() { return itemStore; } public final static String removePunctuations(String str, String replace) { return str.replaceAll("[\\p{Punct}]", replace); } public final static String removeWhitespaces(String str, String replace) { return str.replaceAll("[\\s+]", replace); } public final static String convertTurkishChars(String str) { return StringUtil.convertTurkishCharacter(str); } public final static String removeNonTrimmableSpaces(String str) { str = str.replace(Character.valueOf((char) 160), ' '); return str; } public final static String toLowercase(String str) { return str.toLowerCase(Locale.ENGLISH); } protected List<ScoreHit> findHits(String featureName, String value) { Map<String, List<ItemType>> valueMap = getItemStore().getValueMap(featureName); String[] tokens = value.split(" "); List<ItemType> hitTypeList = null; String tmpResult = null; Map<String, ScoreHit> hitMap = new HashMap<String, ScoreHit>(); for (String token : tokens) { token = removeWhitespaces(token, ""); if (valueMap.containsKey(token)) { hitTypeList = valueMap.get(token); for (ItemType itemType : hitTypeList) { tmpResult = itemType.getName(); if (tmpResult != null) { ScoreHit hit = hitMap.get(tmpResult); if (hit != null) { hit.setScore(hit.getScore() + 1); } else { hit = new ScoreHit(); hit.setValue(tmpResult); hit.setScore(1); hitMap.put(value, hit); } } } } } List<ScoreHit> hitList = new ArrayList<ScoreHit>(hitMap.values()); Collections.sort(hitList, new ScoreComparator()); return hitList; } protected List<ScoreHit> resolveHits(String featureName, String value, int maxGroupSize) { String[] tokens = value.split(" "); Map<String, ScoreHit> hitMap = new HashMap<String, ScoreHit>(); for (int index = maxGroupSize; index > 0; index--) { loopTokens(Arrays.asList(tokens), index, hitMap); } List<ScoreHit> hitList = new ArrayList<ScoreHit>(hitMap.values()); Collections.sort(hitList, new ScoreComparator()); return hitList; } private void loopTokens(List<String> aTokens, int aGroupSize, Map<String, ScoreHit> scoreList) { String aResult = null; if (aTokens.size() >= aGroupSize) { for (int anIndex = 0; anIndex < aTokens.size() - (aGroupSize - 1); anIndex++) { List<String> tokensUnderAnalysis = new ArrayList<String>(); tokensUnderAnalysis.add(aTokens.get(anIndex)); for (int aGroupIndex = 1; aGroupIndex < aGroupSize; aGroupIndex++) { tokensUnderAnalysis.add(aTokens.get(anIndex + aGroupIndex)); } StringBuffer aString = new StringBuffer(); for (String string : tokensUnderAnalysis) { aString.append(string); } aResult = recognize(aString.toString()); if (isRecognized(aResult)) { ScoreHit hit = scoreList.get(aResult); if (hit != null) { hit.setScore(hit.getScore() + 1); } else { Double score = (aGroupSize * 5.0) + (Math.pow(2, -anIndex) * 100) + aString.length() * 2; ScoreHit scoreHit = new ScoreHit(); scoreHit.setScore(score); scoreHit.setValue(aResult); scoreList.put(aResult, scoreHit); } } } } // return aResult; } private boolean isRecognized(String value) { if (StringUtils.isNotBlank(value) && !value.equalsIgnoreCase(DEFAULT_VALUE)) { return true; } return false; } public abstract String recognize(String value); public abstract String resolve(String sentence); public abstract String normalize(String str); }
Karniyarik/karniyarik
karniyarik-recognizer/src/main/java/com/karniyarik/recognizer/BaseFeatureRecognizer.java
Java
gpl-2.0
5,507