answer
stringlengths
15
1.25M
#include "FCodeTable.h" CodeTable::CodeTable() : from_to_code( 0 ) { set_code_tbl( from_to_code ); } CodeTable::CodeTable( int From_to_code ) : from_to_code( 0 ) { set_code_tbl( From_to_code ); } char CodeTable::trans_ch( char ch ) { unsigned char uch = ch; return tbl[ uch ]; } char * CodeTable::trans_str( char * a, char * rez ) { char * tmp = rez; while ( *a ) { *tmp = trans_ch( *a ); tmp++; a++; } *tmp = 0; return rez; } CodeTable::~CodeTable() {} int CodeTable::set_code_tbl( int From_to_code ) { if ( From_to_code >= 0 && From_to_code <= 2 ) from_to_code = From_to_code; for ( int i = 0; i < 256; i++ ) tbl[ i ] = i; switch ( from_to_code ) { case 1: //Win cp=1251->Dos cp=866 tbl[ 128 ] = 95; tbl[ 129 ] = 95; tbl[ 130 ] = 39; tbl[ 131 ] = 95; tbl[ 132 ] = 34; tbl[ 133 ] = 58; tbl[ 134 ] = 197; tbl[ 135 ] = 216; tbl[ 136 ] = 95; tbl[ 137 ] = 37; tbl[ 138 ] = 95; tbl[ 139 ] = 60; tbl[ 140 ] = 95; tbl[ 141 ] = 95; tbl[ 142 ] = 95; tbl[ 143 ] = 95; tbl[ 144 ] = 95; tbl[ 145 ] = 39; tbl[ 146 ] = 39; tbl[ 147 ] = 34; tbl[ 148 ] = 34; tbl[ 149 ] = 7; tbl[ 150 ] = 45; tbl[ 151 ] = 45; tbl[ 152 ] = 95; tbl[ 153 ] = 84; tbl[ 154 ] = 95; tbl[ 155 ] = 62; tbl[ 156 ] = 95; tbl[ 157 ] = 95; tbl[ 158 ] = 95; tbl[ 159 ] = 95; tbl[ 160 ] = 255; tbl[ 161 ] = 246; tbl[ 162 ] = 247; tbl[ 163 ] = 95; tbl[ 164 ] = 253; tbl[ 165 ] = 95; tbl[ 166 ] = 179; tbl[ 167 ] = 21; tbl[ 168 ] = 240; tbl[ 169 ] = 99; tbl[ 170 ] = 242; tbl[ 171 ] = 60; tbl[ 172 ] = 191; tbl[ 173 ] = 45; tbl[ 174 ] = 82; tbl[ 175 ] = 244; tbl[ 176 ] = 248; tbl[ 177 ] = 43; tbl[ 178 ] = 95; tbl[ 179 ] = 95; tbl[ 180 ] = 95; tbl[ 181 ] = 231; tbl[ 182 ] = 20; tbl[ 183 ] = 250; tbl[ 184 ] = 241; tbl[ 185 ] = 252; tbl[ 186 ] = 243; tbl[ 187 ] = 62; tbl[ 188 ] = 95; tbl[ 189 ] = 95; tbl[ 190 ] = 95; tbl[ 191 ] = 245; tbl[ 192 ] = 128; tbl[ 193 ] = 129; tbl[ 194 ] = 130; tbl[ 195 ] = 131; tbl[ 196 ] = 132; tbl[ 197 ] = 133; tbl[ 198 ] = 134; tbl[ 199 ] = 135; tbl[ 200 ] = 136; tbl[ 201 ] = 137; tbl[ 202 ] = 138; tbl[ 203 ] = 139; tbl[ 204 ] = 140; tbl[ 205 ] = 141; tbl[ 206 ] = 142; tbl[ 207 ] = 143; tbl[ 208 ] = 144; tbl[ 209 ] = 145; tbl[ 210 ] = 146; tbl[ 211 ] = 147; tbl[ 212 ] = 148; tbl[ 213 ] = 149; tbl[ 214 ] = 150; tbl[ 215 ] = 151; tbl[ 216 ] = 152; tbl[ 217 ] = 153; tbl[ 218 ] = 154; tbl[ 219 ] = 155; tbl[ 220 ] = 156; tbl[ 221 ] = 157; tbl[ 222 ] = 158; tbl[ 223 ] = 159; tbl[ 224 ] = 160; tbl[ 225 ] = 161; tbl[ 226 ] = 162; tbl[ 227 ] = 163; tbl[ 228 ] = 164; tbl[ 229 ] = 165; tbl[ 230 ] = 166; tbl[ 231 ] = 167; tbl[ 232 ] = 168; tbl[ 233 ] = 169; tbl[ 234 ] = 170; tbl[ 235 ] = 171; tbl[ 236 ] = 172; tbl[ 237 ] = 173; tbl[ 238 ] = 174; tbl[ 239 ] = 175; tbl[ 240 ] = 224; tbl[ 241 ] = 225; tbl[ 242 ] = 226; tbl[ 243 ] = 227; tbl[ 244 ] = 228; tbl[ 245 ] = 229; tbl[ 246 ] = 230; tbl[ 247 ] = 231; tbl[ 248 ] = 232; tbl[ 249 ] = 233; tbl[ 250 ] = 234; tbl[ 251 ] = 235; tbl[ 252 ] = 236; tbl[ 253 ] = 237; tbl[ 254 ] = 238; tbl[ 255 ] = 239; break; case 2: //Dos cp=866->Win cp=1251 tbl[ 15 ] = 164; tbl[ 20 ] = 182; tbl[ 21 ] = 167; tbl[ 128 ] = 192; tbl[ 129 ] = 193; tbl[ 130 ] = 194; tbl[ 131 ] = 195; tbl[ 132 ] = 196; tbl[ 133 ] = 197; tbl[ 134 ] = 198; tbl[ 135 ] = 199; tbl[ 136 ] = 200; tbl[ 137 ] = 201; tbl[ 138 ] = 202; tbl[ 139 ] = 203; tbl[ 140 ] = 204; tbl[ 141 ] = 205; tbl[ 142 ] = 206; tbl[ 143 ] = 207; tbl[ 144 ] = 208; tbl[ 145 ] = 209; tbl[ 146 ] = 210; tbl[ 147 ] = 211; tbl[ 148 ] = 212; tbl[ 149 ] = 213; tbl[ 150 ] = 214; tbl[ 151 ] = 215; tbl[ 152 ] = 216; tbl[ 153 ] = 217; tbl[ 154 ] = 218; tbl[ 155 ] = 219; tbl[ 156 ] = 220; tbl[ 157 ] = 221; tbl[ 158 ] = 222; tbl[ 159 ] = 223; tbl[ 160 ] = 224; tbl[ 161 ] = 225; tbl[ 162 ] = 226; tbl[ 163 ] = 227; tbl[ 164 ] = 228; tbl[ 165 ] = 229; tbl[ 166 ] = 230; tbl[ 167 ] = 231; tbl[ 168 ] = 232; tbl[ 169 ] = 233; tbl[ 170 ] = 234; tbl[ 171 ] = 235; tbl[ 172 ] = 236; tbl[ 173 ] = 237; tbl[ 174 ] = 238; tbl[ 175 ] = 239; tbl[ 176 ] = 45; tbl[ 177 ] = 45; tbl[ 178 ] = 45; tbl[ 179 ] = 166; tbl[ 180 ] = 43; tbl[ 181 ] = 166; tbl[ 182 ] = 166; tbl[ 183 ] = 172; tbl[ 184 ] = 172; tbl[ 185 ] = 166; tbl[ 186 ] = 166; tbl[ 187 ] = 172; tbl[ 188 ] = 45; tbl[ 189 ] = 45; tbl[ 190 ] = 45; tbl[ 191 ] = 172; tbl[ 192 ] = 76; tbl[ 193 ] = 43; tbl[ 194 ] = 84; tbl[ 195 ] = 43; tbl[ 196 ] = 45; tbl[ 197 ] = 43; tbl[ 198 ] = 166; tbl[ 199 ] = 166; tbl[ 200 ] = 76; tbl[ 201 ] = 227; tbl[ 202 ] = 166; tbl[ 203 ] = 84; tbl[ 204 ] = 166; tbl[ 205 ] = 61; tbl[ 206 ] = 43; tbl[ 207 ] = 166; tbl[ 208 ] = 166; tbl[ 209 ] = 84; tbl[ 210 ] = 84; tbl[ 211 ] = 76; tbl[ 212 ] = 76; tbl[ 213 ] = 45; tbl[ 214 ] = 227; tbl[ 215 ] = 43; tbl[ 216 ] = 43; tbl[ 217 ] = 45; tbl[ 218 ] = 45; tbl[ 219 ] = 45; tbl[ 220 ] = 45; tbl[ 221 ] = 166; tbl[ 222 ] = 166; tbl[ 223 ] = 45; tbl[ 224 ] = 240; tbl[ 225 ] = 241; tbl[ 226 ] = 242; tbl[ 227 ] = 243; tbl[ 228 ] = 244; tbl[ 229 ] = 245; tbl[ 230 ] = 246; tbl[ 231 ] = 247; tbl[ 232 ] = 248; tbl[ 233 ] = 249; tbl[ 234 ] = 250; tbl[ 235 ] = 251; tbl[ 236 ] = 252; tbl[ 237 ] = 253; tbl[ 238 ] = 254; tbl[ 239 ] = 255; tbl[ 240 ] = 168; tbl[ 241 ] = 184; tbl[ 242 ] = 170; tbl[ 243 ] = 186; tbl[ 244 ] = 175; tbl[ 245 ] = 191; tbl[ 246 ] = 161; tbl[ 247 ] = 162; tbl[ 248 ] = 176; tbl[ 249 ] = 149; tbl[ 250 ] = 183; tbl[ 251 ] = 118; tbl[ 252 ] = 185; tbl[ 253 ] = 164; tbl[ 254 ] = 166; tbl[ 255 ] = 160; break; case 3: //Win cp=1251 -> Koi8-r tbl[ 192 ] = 225; tbl[ 193 ] = 226; tbl[ 194 ] = 247; tbl[ 195 ] = 231; tbl[ 196 ] = 228; tbl[ 197 ] = 229; tbl[ 168 ] = 179; tbl[ 198 ] = 246; tbl[ 199 ] = 250; tbl[ 200 ] = 233; tbl[ 201 ] = 234; tbl[ 202 ] = 235; tbl[ 203 ] = 236; tbl[ 204 ] = 237; tbl[ 205 ] = 238; tbl[ 206 ] = 239; tbl[ 207 ] = 240; tbl[ 208 ] = 242; tbl[ 209 ] = 243; tbl[ 210 ] = 244; tbl[ 211 ] = 245; tbl[ 212 ] = 230; tbl[ 213 ] = 232; tbl[ 214 ] = 227; tbl[ 215 ] = 254; tbl[ 216 ] = 251; tbl[ 217 ] = 253; tbl[ 218 ] = 255; tbl[ 219 ] = 249; tbl[ 220 ] = 248; tbl[ 221 ] = 252; tbl[ 222 ] = 224; tbl[ 223 ] = 241; tbl[ 224 ] = 193; tbl[ 225 ] = 194; tbl[ 235 ] = 204; tbl[ 227 ] = 199; tbl[ 228 ] = 196; tbl[ 229 ] = 197; tbl[ 184 ] = 163; tbl[ 230 ] = 214; tbl[ 231 ] = 218; tbl[ 232 ] = 201; tbl[ 233 ] = 202; tbl[ 234 ] = 203; tbl[ 235 ] = 204; tbl[ 236 ] = 205; tbl[ 237 ] = 206; tbl[ 238 ] = 207; tbl[ 239 ] = 208; tbl[ 240 ] = 210; tbl[ 241 ] = 211; tbl[ 242 ] = 212; tbl[ 243 ] = 213; tbl[ 244 ] = 198; tbl[ 245 ] = 200; tbl[ 246 ] = 195; tbl[ 247 ] = 222; tbl[ 248 ] = 219; tbl[ 249 ] = 221; tbl[ 250 ] = 223; tbl[ 251 ] = 217; tbl[ 252 ] = 216; tbl[ 253 ] = 220; tbl[ 254 ] = 192; tbl[ 255 ] = 209; tbl[ 255 ] = 255; break; case 4: tbl[ 225 ] = 192; tbl[ 226 ] = 193; tbl[ 247 ] = 194; tbl[ 231 ] = 195; tbl[ 228 ] = 196; tbl[ 229 ] = 197; tbl[ 179 ] = 168; tbl[ 246 ] = 198; tbl[ 250 ] = 199; tbl[ 233 ] = 200; tbl[ 234 ] = 201; tbl[ 235 ] = 202; tbl[ 236 ] = 203; tbl[ 237 ] = 204; tbl[ 238 ] = 205; tbl[ 239 ] = 206; tbl[ 240 ] = 207; tbl[ 242 ] = 208; tbl[ 243 ] = 209; tbl[ 244 ] = 210; tbl[ 245 ] = 211; tbl[ 230 ] = 212; tbl[ 232 ] = 213; tbl[ 227 ] = 214; tbl[ 254 ] = 215; tbl[ 251 ] = 216; tbl[ 253 ] = 217; tbl[ 255 ] = 218; tbl[ 249 ] = 219; tbl[ 248 ] = 220; tbl[ 252 ] = 221; tbl[ 224 ] = 222; tbl[ 241 ] = 223; tbl[ 193 ] = 224; tbl[ 194 ] = 225; tbl[ 204 ] = 235; tbl[ 199 ] = 227; tbl[ 196 ] = 228; tbl[ 197 ] = 229; tbl[ 163 ] = 184; tbl[ 214 ] = 230; tbl[ 218 ] = 231; tbl[ 201 ] = 232; tbl[ 202 ] = 233; tbl[ 203 ] = 234; tbl[ 204 ] = 235; tbl[ 205 ] = 236; tbl[ 206 ] = 237; tbl[ 207 ] = 238; tbl[ 208 ] = 239; tbl[ 210 ] = 240; tbl[ 211 ] = 241; tbl[ 212 ] = 242; tbl[ 213 ] = 243; tbl[ 198 ] = 244; tbl[ 200 ] = 245; tbl[ 195 ] = 246; tbl[ 222 ] = 247; tbl[ 219 ] = 248; tbl[ 221 ] = 249; tbl[ 223 ] = 250; tbl[ 217 ] = 251; tbl[ 216 ] = 252; tbl[ 220 ] = 253; tbl[ 192 ] = 254; tbl[ 209 ] = 255; tbl[ 255 ] = 255; break; default: break; } return from_to_code; }
#include <linux/delay.h> #include <linux/i2c.h> #include <linux/iio/iio.h> #include <linux/iio/sysfs.h> #include <linux/module.h> #define BH1750_POWER_DOWN 0x00 #define <API key> 0x20 /* auto-mode for BH1721 */ #define <API key> 0x40 #define <API key> 0x60 enum { BH1710, BH1721, BH1750, }; struct bh1750_chip_info; struct bh1750_data { struct i2c_client *client; struct mutex lock; const struct bh1750_chip_info *chip_info; u16 mtreg; }; struct bh1750_chip_info { u16 mtreg_min; u16 mtreg_max; u16 mtreg_default; int mtreg_to_usec; int mtreg_to_scale; /* * For BH1710/BH1721 all possible integration time values won't fit * into one page so displaying is limited to every second one. * Note, that user can still write proper values which were not * listed. */ int inc; u16 int_time_low_mask; u16 int_time_high_mask; } static const <API key>[] = { [BH1710] = { 140, 1022, 300, 400, 250000000, 2, 0x001F, 0x03E0 }, [BH1721] = { 140, 1020, 300, 400, 250000000, 2, 0x0010, 0x03E0 }, [BH1750] = { 31, 254, 69, 1740, 57500000, 1, 0x001F, 0x00E0 }, }; static int <API key>(struct bh1750_data *data, int usec) { int ret; u16 val; u8 regval; const struct bh1750_chip_info *chip_info = data->chip_info; if ((usec % chip_info->mtreg_to_usec) != 0) { return -EINVAL; } val = usec / chip_info->mtreg_to_usec; if (val < chip_info->mtreg_min || val > chip_info->mtreg_max) { return -EINVAL; } ret = <API key>(data->client, BH1750_POWER_DOWN); if (ret < 0) { return ret; } regval = (val & chip_info->int_time_high_mask) >> 5; ret = <API key>(data->client, <API key> | regval); if (ret < 0) { return ret; } regval = val & chip_info->int_time_low_mask; ret = <API key>(data->client, <API key> | regval); if (ret < 0) { return ret; } data->mtreg = val; return 0; } static int bh1750_read(struct bh1750_data *data, int *val) { int ret; __be16 result; const struct bh1750_chip_info *chip_info = data->chip_info; unsigned long delay = chip_info->mtreg_to_usec * data->mtreg; /* * BH1721 will enter continuous mode on receiving this command. * Note, that this eliminates need for bh1750_resume(). */ ret = <API key>(data->client, <API key>); if (ret < 0) { return ret; } usleep_range(delay + 15000, delay + 40000); ret = i2c_master_recv(data->client, (char *)&result, 2); if (ret < 0) { return ret; } *val = be16_to_cpu(result); return 0; } static int bh1750_read_raw(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, int *val, int *val2, long mask) { int ret, tmp; struct bh1750_data *data = iio_priv(indio_dev); const struct bh1750_chip_info *chip_info = data->chip_info; switch (mask) { case IIO_CHAN_INFO_RAW: switch (chan->type) { case IIO_LIGHT: mutex_lock(&data->lock); ret = bh1750_read(data, val); mutex_unlock(&data->lock); if (ret < 0) { return ret; } return IIO_VAL_INT; default: return -EINVAL; } case IIO_CHAN_INFO_SCALE: tmp = chip_info->mtreg_to_scale / data->mtreg; *val = tmp / 1000000; *val2 = tmp % 1000000; return <API key>; case <API key>: *val = 0; *val2 = chip_info->mtreg_to_usec * data->mtreg; return <API key>; default: return -EINVAL; } } static int bh1750_write_raw(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, int val, int val2, long mask) { int ret; struct bh1750_data *data = iio_priv(indio_dev); switch (mask) { case <API key>: if (val != 0) { return -EINVAL; } mutex_lock(&data->lock); ret = <API key>(data, val2); mutex_unlock(&data->lock); return ret; default: return -EINVAL; } } static ssize_t <API key>(struct device *dev, struct device_attribute *attr, char *buf) { int i; size_t len = 0; struct bh1750_data *data = iio_priv(dev_to_iio_dev(dev)); const struct bh1750_chip_info *chip_info = data->chip_info; for (i = chip_info->mtreg_min; i <= chip_info->mtreg_max; i += chip_info->inc) len += scnprintf(buf + len, PAGE_SIZE - len, "0.%06d ", chip_info->mtreg_to_usec * i); buf[len - 1] = '\n'; return len; } static <API key>(<API key>); static struct attribute *bh1750_attributes[] = { &<API key>.dev_attr.attr, NULL, }; static struct attribute_group <API key> = { .attrs = bh1750_attributes, }; static const struct iio_info bh1750_info = { .driver_module = THIS_MODULE, .attrs = &<API key>, .read_raw = bh1750_read_raw, .write_raw = bh1750_write_raw, }; static const struct iio_chan_spec bh1750_channels[] = { { .type = IIO_LIGHT, .info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE) | BIT(<API key>) } }; static int bh1750_probe(struct i2c_client *client, const struct i2c_device_id *id) { int ret, usec; struct bh1750_data *data; struct iio_dev *indio_dev; if (!<API key>(client->adapter, I2C_FUNC_I2C | <API key>)) { return -EOPNOTSUPP; } indio_dev = <API key>(&client->dev, sizeof(*data)); if (!indio_dev) { return -ENOMEM; } data = iio_priv(indio_dev); i2c_set_clientdata(client, indio_dev); data->client = client; data->chip_info = &<API key>[id->driver_data]; usec = data->chip_info->mtreg_to_usec * data->chip_info->mtreg_default; ret = <API key>(data, usec); if (ret < 0) { return ret; } mutex_init(&data->lock); indio_dev->dev.parent = &client->dev; indio_dev->info = &bh1750_info; indio_dev->name = id->name; indio_dev->channels = bh1750_channels; indio_dev->num_channels = ARRAY_SIZE(bh1750_channels); indio_dev->modes = INDIO_DIRECT_MODE; return iio_device_register(indio_dev); } static int bh1750_remove(struct i2c_client *client) { struct iio_dev *indio_dev = i2c_get_clientdata(client); struct bh1750_data *data = iio_priv(indio_dev); <API key>(indio_dev); mutex_lock(&data->lock); <API key>(client, BH1750_POWER_DOWN); mutex_unlock(&data->lock); return 0; } #ifdef CONFIG_PM_SLEEP static int bh1750_suspend(struct device *dev) { int ret; struct bh1750_data *data = iio_priv(i2c_get_clientdata(to_i2c_client(dev))); /* * This is mainly for BH1721 which doesn't enter power down * mode automatically. */ mutex_lock(&data->lock); ret = <API key>(data->client, BH1750_POWER_DOWN); mutex_unlock(&data->lock); return ret; } static SIMPLE_DEV_PM_OPS(bh1750_pm_ops, bh1750_suspend, NULL); #define BH1750_PM_OPS (&bh1750_pm_ops) #else #define BH1750_PM_OPS NULL #endif static const struct i2c_device_id bh1750_id[] = { { "bh1710", BH1710 }, { "bh1715", BH1750 }, { "bh1721", BH1721 }, { "bh1750", BH1750 }, { "bh1751", BH1750 }, { } }; MODULE_DEVICE_TABLE(i2c, bh1750_id); static struct i2c_driver bh1750_driver = { .driver = { .name = "bh1750", .pm = BH1750_PM_OPS, }, .probe = bh1750_probe, .remove = bh1750_remove, .id_table = bh1750_id, }; module_i2c_driver(bh1750_driver); MODULE_AUTHOR("Tomasz Duszynski <tduszyns@gmail.com>"); MODULE_DESCRIPTION("ROHM BH1710/BH1715/BH1721/BH1750/BH1751 als driver"); MODULE_LICENSE("GPL v2");
#!/bin/bash # preexec.bash -- Bash support for ZSH-like 'preexec' and 'precmd' functions. # The 'preexec' function is executed before each interactive command is # executed, with the interactive command as its argument. The 'precmd' # function is executed before each prompt is displayed. # To use, in order: # 1. source this file # 2. define 'preexec' and/or 'precmd' functions (AFTER sourcing this file), # 3. as near as possible to the end of your shell setup, run 'preexec_install' # to kick everything off. # Note: this module requires 2 bash features which you must not otherwise be # using: the "DEBUG" trap, and the "PROMPT_COMMAND" variable. preexec_install # will override these and if you override one or the other this _will_ break. # This is known to support bash3, as well as *mostly* support bash2.05b. It # has been tested with the default shells on MacOS X 10.4 "Tiger", Ubuntu 5.10 # "Breezy Badger", Ubuntu 6.06 "Dapper Drake", and Ubuntu 6.10 "Edgy Eft". # Copy screen-run variables from the remote host, if they're available. if [[ "$SCREEN_RUN_HOST" == "" ]] then SCREEN_RUN_HOST="$LC_SCREEN_RUN_HOST" SCREEN_RUN_USER="$LC_SCREEN_RUN_USER" fi # This variable describes whether we are currently in "interactive mode"; # i.e. whether this shell has just executed a prompt and is waiting for user # input. It documents whether the current command invoked by the trace hook is # run interactively by the user; it's set immediately after the prompt hook, # and unset as soon as the trace hook is run. <API key>="" # Default do-nothing implementation of preexec. function preexec () { true } # Default do-nothing implementation of precmd. function precmd () { true } # This function is installed as the PROMPT_COMMAND; it is invoked before each # interactive prompt display. It sets a variable to indicate that the prompt # was just displayed, to allow the DEBUG trap, below, to know that the next # command is likely interactive. function preexec_invoke_cmd () { precmd <API key>="yes" } # This function is installed as the DEBUG trap. It is invoked before each # interactive prompt display. Its purpose is to inspect the current # environment to attempt to detect if the current command is being invoked # interactively, and invoke 'preexec' if so. function preexec_invoke_exec () { if [[ -n "$COMP_LINE" ]] then # We're in the middle of a completer. This obviously can't be # an interactively issued command. return fi if [[ -z "$<API key>" ]] then # We're doing something related to displaying the prompt. Let the # prompt set the title instead of me. return else # If we're in a subshell, then the prompt won't be re-displayed to put # us back into interactive mode, so let's not set the variable back. # In other words, if you have a subshell like # (sleep 1; sleep 2) # You want to see the 'sleep 2' as a set_command_title as well. if [[ 0 -eq "$BASH_SUBSHELL" ]] then <API key>="" fi fi if [[ "preexec_invoke_cmd" == "$BASH_COMMAND" ]] then # Sadly, there's no cleaner way to detect two prompts being displayed # one after another. This makes it important that PROMPT_COMMAND # remain set _exactly_ as below in preexec_install. Let's switch back # out of interactive mode and not trace any of the commands run in # precmd. # Given their buggy interaction between BASH_COMMAND and debug traps, # versions of bash prior to 3.1 can't detect this at all. <API key>="" return fi # In more recent versions of bash, this could be set via the "BASH_COMMAND" # variable, but using history here is better in some ways: for example, "ps # auxf | less" will show up with both sides of the pipe if we use history, # but only as "ps auxf" if not. local this_command=`history 1 | sed -e "s/^[ ]*[0-9]*[ ]* # If none of the previous checks have earlied out of this function, then # the command is in fact interactive and we should invoke the user's # preexec hook with the running command as an argument. preexec "$this_command" } # Execute this to set up preexec and precmd execution. function preexec_install () { # *BOTH* of these options need to be set for the DEBUG trap to be invoked # in ( ) subshells. This smells like a bug in bash to me. The null stderr # redirections are to quiet errors on bash2.05 (i.e. OSX's default shell) # where the options can't be set, and it's impossible to inherit the trap # into subshells. set -o functrace > /dev/null 2>&1 shopt -s extdebug > /dev/null 2>&1 # Finally, install the actual traps. PROMPT_COMMAND="${PROMPT_COMMAND};preexec_invoke_cmd" trap 'preexec_invoke_exec' DEBUG } # Since this is the reason that 99% of everybody is going to bother with a # pre-exec hook anyway, we'll include it in this module. # Change the title of the xterm. function preexec_xterm_title () { local title="$1" echo -ne "\033]0;$title\007" > /dev/stderr } function <API key> () { local title="$1" echo -ne "\033k$1\033\\" > /dev/stderr } # Abbreviate the "user@host" string as much as possible to preserve space in # screen titles. Elide the host if the host is the same, elide the user if the # user is the same. function <API key> () { local RESULT="" if [[ "$SCREEN_RUN_HOST" == "$SCREEN_HOST" ]] then return else if [[ "$SCREEN_RUN_USER" == "$USER" ]] then echo -n "@${SCREEN_HOST}" else echo -n "${USER}@${SCREEN_HOST}" fi fi } function <API key> () { # These functions are defined here because they only make sense with the # preexec_install below. function precmd () { preexec_xterm_title "${TERM} - ${USER}@${SCREEN_HOST} `dirs -0` $PROMPTCHAR" if [[ "${TERM}" == screen ]] then <API key> "`<API key>`${PROMPTCHAR}" fi } function preexec () { # xterm seems to treat backslashes funny; they terminate the escape # sequence or something. I'm not sure why, but if we don't escape them # by doubling them (like so) then running an interactive command with a # backslash in it will result in a messed-up terminal and half a # terminal title echoed onto the command line. thiscmd="$(echo "$1" | sed -e 's/\\/\\\\/g' | head -n 1)" preexec_xterm_title "${TERM} - $thiscmd {`dirs -0`} (${USER}@${SCREEN_HOST})" if [[ "${TERM}" == screen ]] then local cutit="$1" local cmdtitle=`echo "$cutit" | cut -d " " -f 1` if [[ "$cmdtitle" == "exec" ]] then local cmdtitle=`echo "$cutit" | cut -d " " -f 2` fi if [[ "$cmdtitle" == "screen" ]] then # Since stacked screens are quite common, it would be nice to # just display them as '$$'. local cmdtitle="${PROMPTCHAR}" else local cmdtitle=":$cmdtitle" fi <API key> "`<API key>`${PROMPTCHAR}$cmdtitle" fi } preexec_install }
var <API key> = [ [ "ProProjects", "<API key>.html", "<API key>" ] ];
#ifndef <API key> #define <API key> #include "sshconnection.h" #include "sshremoteprocess.h" namespace QSsh { namespace Internal { class <API key>; } // namespace Internal class QSSH_EXPORT <API key> : public QObject { Q_OBJECT public: <API key>(QObject *parent = 0); ~<API key>(); void run(const QByteArray &command, const <API key> &sshParams); void runInTerminal(const QByteArray &command, const SshPseudoTerminal &terminal, const <API key> &sshParams); QByteArray command() const; QSsh::SshError lastConnectionError() const; QString <API key>() const; bool isProcessRunning() const; void writeDataToProcess(const QByteArray &data); void sendSignalToProcess(SshRemoteProcess::Signal signal); // No effect with OpenSSH server. void cancel(); // Does not stop remote process, just frees SSH-related process resources. SshRemoteProcess::ExitStatus processExitStatus() const; SshRemoteProcess::Signal processExitSignal() const; int processExitCode() const; QString processErrorString() const; QByteArray <API key>(); QByteArray <API key>(); Q_SIGNALS: void connectionError(); void processStarted(); void <API key>(); void <API key>(); void processClosed(int exitStatus); // values are of type SshRemoteProcess::ExitStatus private Q_SLOTS: void handleConnected(); void <API key>(QSsh::SshError error); void handleDisconnected(); void <API key>(); void <API key>(int exitStatus); void handleStdout(); void handleStderr(); private: void runInternal(const QByteArray &command, const QSsh::<API key> &sshParams); void setState(int newState); Internal::<API key> * const d; }; } // namespace QSsh #endif // <API key>
#include "qmrofscompositor.h" #include "qmrofswaveform.h" #include "qmrofswindow.h" #include "qmrofsbackingstore.h" #include "qmrofsscreen.h" #include <qpa/<API key>.h> #if !defined(QT_NO_EVDEV) && (!defined(Q_OS_ANDROID) || defined(Q_OS_ANDROID_NO_SDK)) #include <QtPlatformSupport/private/qdevicediscovery_p.h> #endif #include <QtCore/qglobal.h> #include <QtCore/qmetaobject.h> #include "qmrofscursor.h" #ifdef DEBUG_CPU_BLT #include <QtGui/QPainter> #include <QtGui/private/qdrawhelper_p.h> #endif #include "cmem.h" QT_BEGIN_NAMESPACE <API key>::<API key>(QObject* parent, QMrOfsCompositor *cmptr) : QThread(parent), compositor(cmptr), id(0) { } <API key>::~<API key>() { } void <API key>::run() { /* QTimer's hightest freuency seems to be 30Hz if self refresh, uncomment this: */ #if 0 QTimer timer; timer.setTimerType(Qt::PreciseTimer); timer.start(10); //much faster than wave timer m_timer = &timer; connect(&timer, SIGNAL(timeout()), compositor, SLOT(composite3()), Qt::AutoConnection); //should direct #endif #if 0 //INITIALIZE SCHED POLICY and PRIORITY struct sched_param sched_param; int sched_policy = SCHED_OTHER; //SCHED_FIFO, SCHED_RR, SCHED_OTHER const int default_pri; //range: <API key>(sched_policy), <API key>(sched_policy) if (SCHED_FIFO == sched_policy || SCHED_RR == sched_policy) { default_pri = <API key>(sched_policy) - 2; } else { default_pri = 0; } sched_param.sched_priority = default_pri; id = pthread_self(); <API key>(id, sched_policy, &sched_param); #endif (void) exec(); } QMrOfsCompositor::QMrOfsCompositor(QMrOfsWindow *win, QMrOfsBackingStore *bs) : #ifdef <API key> m_th(NULL), m_mutex_bs(QMutex::Recursive), m_mutex_wv(QMutex::Recursive), m_mutex_iv(QMutex::Recursive), m_mutex_wc(QMutex::Recursive), #endif m_scrn(NULL), m_win(win), m_bs(bs), m_wc(NULL), m_cursor(NULL), m_enabled(false), m_conn_type(Qt::<API key>), m_wv_flush_enabled(true), m_iv_flush_enabled(false), m_bs_flush_enabled(true), m_cr_flush_enabled(false), m_fb_shadow_pict(NULL) #ifdef QT_MRDP , m_mrdp(&MRDPConnMgr::instance()), m_mutex_screen(QMutex::Recursive) #endif { m_scrn = static_cast<QMrOfsScreen *>(m_win->screen()); #ifdef QT_MRDP m_mrdp->setScreenGeometry(m_scrn->geometry()); m_mrdp->setScreenDepth(m_scrn->depth()); #endif initialize(m_scrn); m_wc = new <API key>(win); #if 0 qDebug("QMrOfsCompositor::QMrOfsCompositor: create shadow image"); m_fb_shadow_pict = new QMrOfsShmImage(m_scrn, QSize(m_scrn->geometry().width(), m_scrn->geometry().height()), depthFromMainFormat(<API key>), <API key>); #endif memset(&m_blt_inf, 0, sizeof(m_blt_inf)); #ifdef <API key> m_conn_type = Qt::<API key>; m_th = new <API key>(NULL, this); this->moveToThread(m_th); m_th->start(); #else m_conn_type = Qt::DirectConnection; #endif } QMrOfsCompositor::~QMrOfsCompositor() { delete m_wc; #ifdef <API key> m_th->exit(0); delete m_th; #endif } QAbstractMrOfs::WV_ID QMrOfsCompositor::openWaveview() { qWarning("NOT IMPLEMENTED, please call openWaveview(const QWidget&, const QRect&)"); return -1; } void QMrOfsCompositor::closeWaveview(QAbstractMrOfs::WV_ID vid) { lockWaveController(); QMrOfsWaveview *wv = m_wc->fromVid(vid); m_wc->closeWaveview(wv); <API key>(); } QAbstractMrOfs::WV_ID QMrOfsCompositor::setWaveviewLayer(QAbstractMrOfs::WV_ID vid, int layer) { Q_UNUSED(vid); Q_UNUSED(layer); qWarning("NOT IMPLEMENTED, please call QMrOfsCompositor::openPopup/closepopUp"); return -1; } void QMrOfsCompositor::setWaveViewport(QAbstractMrOfs::WV_ID vid, const QRect& vpt) { QMrOfsWaveview *wv = m_wc->fromVid(vid); m_wc->setWaveviewport(wv, vpt); } QAbstractMrOfs::WV_ID QMrOfsCompositor::createWaveform(QAbstractMrOfs::WV_ID vid) { Q_UNUSED(vid); qWarning("NOT IMPLEMENTED, please call QMrOfsCompositor::createWaveform(QAbstractMrOfs::WV_ID vid, const QRect&)"); return -1; } void QMrOfsCompositor::destroyWaveform(QAbstractMrOfs::WV_ID wid) { lockWaveController(); QMrOfsWaveform *wf = m_wc->fromWid(wid); m_wc->removeWaveform(wf); <API key>(); } QWaveData* QMrOfsCompositor::setWaveformSize(QAbstractMrOfs::WV_ID wid, const QSize& sz) { QMrOfsWaveform *wf = m_wc->fromWid(wid); if(!wf) { qWarning("QMrOfsCompositor::setWaveformSize: waveform(%p) NOT found, wid(%d)", wf, wid); return NULL; } QMrOfsWaveview *wv = m_wc->viewOfWaveform(wf); if(!wv) { qWarning("QMrOfsCompositor::setWaveformSize: waveview(%p) NOT found, wf(%p), wid(%d)", wv, wf, wid); return NULL; } if(wv->isIView()) { //iview does not support resize dynamically, the only way is create-time setting by hdmi configuration return NULL; } QRect rc = wf->geometry(); rc.setSize(sz); //position untouched m_wc->moveWaveform(wf, rc); return wf->data(); //return new allocated QWaveData } void QMrOfsCompositor::bindWaveform(QAbstractMrOfs::WV_ID wid, QAbstractMrOfs::WV_ID vid) { Q_UNUSED(wid); Q_UNUSED(vid); qWarning("NOT IMPLEMENTED: QMrOfsCompositor::bindWaveform"); } QWaveData* QMrOfsCompositor::<API key>(QAbstractMrOfs::WV_ID wid) { QMrOfsWaveform *wf = m_wc->fromWid(wid); if(NULL == wf) { qWarning("QMrOfsCompositor::<API key>: waveform NOT found, wid(%d)", wid); return NULL; } return wf->data(); } QPoint QMrOfsCompositor::setWaveformPos(QAbstractMrOfs::WV_ID wid, const QPoint& pos) { QMrOfsWaveform *wf = m_wc->fromWid(wid); if(!wf) { qWarning("QMrOfsCompositor::setWaveformPos: waveform(%p) NOT found, wid(%d)", wf, wid); return QPoint(); } QRect rc = wf->geometry(); rc.moveTo(pos.x(), pos.y()); //size untouched QRect rc_old = m_wc->moveWaveform(wf, rc); return QPoint(rc_old.x(), rc_old.y()); } /*! rgn useless dirty region of waveforms have been already set by <API key> */ void QMrOfsCompositor::flushWaves(const QRegion& rgn) { Q_UNUSED(rgn); qWarning("QMrOfsCompositor::flushWaves(const QRegion& rgn) not IMPLEMENTED, use null args version instead"); } void QMrOfsCompositor::flushWaves() { if(!m_wv_flush_enabled) return; //wave data has already been flushed before unlocking composite(<API key>); } Q_INVOKABLE void QMrOfsCompositor::submitWaveData() { lockWaveController(); m_wc->flushWaves(); //flush Data <API key>(); } QRgb QMrOfsCompositor::getColorKey() const { qWarning("NOT IMPLEMENTED: QMrOfsCompositor::getColorKey"); return QRgb(0x0); //transparent black } bool QMrOfsCompositor::enableComposition(bool enable) { bool old = m_enabled; m_enabled = enable; return old; } void QMrOfsCompositor::lockWaveController() { #ifdef <API key> m_mutex_wc.lock(); #endif } void QMrOfsCompositor::<API key>() { #ifdef <API key> m_mutex_wc.unlock(); #endif } /*! container belongs to a popup */ QAbstractMrOfs::WV_ID QMrOfsCompositor::openWaveview(const QWidget& container, const QRect& vpt) { lockWaveController(); QMrOfsWaveview* wv = m_wc->openWaveview(&container, vpt, false); <API key>(); return wv->vid(); } QAbstractMrOfs::WV_ID QMrOfsCompositor::createWaveform(QAbstractMrOfs::WV_ID vid, const QRect& rc) { QMrOfsWaveview *wv = m_wc->fromVid(vid); if(!wv) return -1; //format == <API key>, bufCount == 1 QMrOfsWaveform *wf = m_wc->addWaveform(wv, rc); if(!wf) return -1; return wf->wid(); } void QMrOfsCompositor::unbindWaveform(QAbstractMrOfs::WV_ID wid, QAbstractMrOfs::WV_ID vid) { Q_UNUSED(wid); Q_UNUSED(vid); qWarning("NOT IMPLEMENTED: QMrOfsCompositor::unbindWaveform"); } void QMrOfsCompositor::openPopup(const QWidget& popup) { m_wc->openPopup(&popup); } void QMrOfsCompositor::closePopup(const QWidget& popup) { m_wc->closePopup(&popup); } /*! wave/iview thread!!!, must run in the range of beginUpdateWaves and endUpdateWaves */ void QMrOfsCompositor::<API key>(QAbstractMrOfs::WV_ID wid, const QRegion &rgn) { lockWaveController(); QMrOfsWaveform *wf = m_wc->fromWid(wid); <API key>(); m_wc-><API key>(wf, rgn); // waveform(and it's dirty region) is protected by m_mutex_wv } void QMrOfsCompositor::<API key>(QAbstractMrOfs::WV_ID wid, const QRect &rc) { lockWaveController(); QMrOfsWaveform *wf = m_wc->fromWid(wid); <API key>(); m_wc-><API key>(wf, rc); // waveform(and it's dirty region) is protected by m_mutex_wv } /*! wave/iview thread, must run in the range of beginUpdateWaves and endUpdateWaves */ void QMrOfsCompositor::<API key>(QAbstractMrOfs::WV_ID wid) { Q_UNUSED(wid); qWarning("QMrOfsCompositor::<API key>: NOT IMPLEMENTED"); } /*! wave/iview thread, must run in the range of beginUpdateWaves and endUpdateWaves */ void QMrOfsCompositor::<API key>() { qWarning("QMrOfsCompositor::<API key>: NOT IMPLEMENTED"); } /*! \ref openWaveview */ QAbstractMrOfs::WV_ID QMrOfsCompositor::openIView(const QWidget &container, const QRect& vpt) { lockWaveController(); QMrOfsWaveview* wv = m_wc->openWaveview(&container, vpt, true); <API key>(); return wv->vid(); } /*! iviewforms destroyed automatically, the same as waveview ref. closeWaveView */ void QMrOfsCompositor::closeIView(QAbstractMrOfs::WV_ID vid) { lockWaveController(); QMrOfsWaveview *wv = m_wc->fromVid(vid); m_wc->closeWaveview(wv); <API key>(); } /*! \note if format is YUV, then xv takes charge, otherwise, xrender does no matter bufCount is greater than 1 or not */ QAbstractMrOfs::WV_ID QMrOfsCompositor::createIViewform(QAbstractMrOfs::WV_ID vid, const HDMI_CONFIG hcfg, QMrOfs::Format fmt) { QMrOfsWaveview *wv = m_wc->fromVid(vid); if(!wv) return -1; QRect rc(0, 0, 1, 1); switch (hcfg) { case <API key>: default: rc.setWidth(1280); rc.setHeight(720); break; case <API key>: rc.setWidth(1024); rc.setHeight(768); break; case <API key>: rc.setWidth(1696); //ref resolution_array[2] in iview.cpp rc.setHeight(1050); break; case <API key>: rc.setWidth(1280); rc.setHeight(800); break; case HDMI_CONFIG_800x600: rc.setWidth(800); rc.setHeight(600); break; case <API key>: rc.setWidth(1056); //ref resolution_array[5] in iview.cpp rc.setHeight(1680); break; } QMrOfsWaveform *wf = m_wc->addWaveform(wv, rc, fmt); if(!wf) return -1; return wf->wid(); } /*! bits -> shmimage -> pixmap [iview thread]!!! */ void QMrOfsCompositor::submitIViewData(QAbstractMrOfs::WV_ID vid, QAbstractMrOfs::WV_ID wid, const unsigned char *bits) { lockWaveController(); QMrOfsWaveview *iv = m_wc->fromVid(vid); if(!iv) { <API key>(); return; } QMrOfsWaveform *wf = m_wc->fromWid(wid); if(!wf) { <API key>(); return; } m_wc->flushIView(iv, wf, bits); <API key>(); } /*! compositor thread */ void QMrOfsCompositor::flushIView(QAbstractMrOfs::WV_ID wid) { QMrOfsWaveform *wf = m_wc->fromWid(wid); if(!wf) return; if(!m_iv_flush_enabled) return; composite(<API key>); } void QMrOfsCompositor::lockIViewResources() { m_mutex_iv.lock(); } void QMrOfsCompositor::<API key>() { m_mutex_iv.unlock(); } #ifdef <API key> /*! [wave thread] */ void QMrOfsCompositor::paintWaveformLines( QImage* image, QAbstractMrOfs::XCOORDINATE xStart, const QAbstractMrOfs::YCOORDINATE* y, const QAbstractMrOfs::YCOORDINATE* yMax, const QAbstractMrOfs::YCOORDINATE* yMin, short yFillBaseLine, unsigned int pointsCount, const QColor& color, QAbstractMrOfs::LINEMODE mode) { if (mode == QAbstractMrOfs::LINEMODE_DRAW) { drawWaveformLines(image, xStart, y, yMax, yMin, pointsCount, color); } else if (mode == QAbstractMrOfs::LINEMODE_FILL) { fillWaveformLines(image, xStart, y, yMin, yFillBaseLine, pointsCount, color); } else { // do nothing } } // restore left shift outside static inline short rightShift8Bits(int y) { return (y >> 8); } void QMrOfsCompositor::drawWaveformLines(QImage* image, QAbstractMrOfs::XCOORDINATE xStart, const QAbstractMrOfs::YCOORDINATE* y, const QAbstractMrOfs::YCOORDINATE* yMax, const QAbstractMrOfs::YCOORDINATE* yMin, unsigned int pointsCount, const QColor& color) { if (image != 0) { uchar *dataPtr = const_cast<uchar*>( const_cast<const QImage*>(image)->bits() ); int w = image->width(); int h = image->height(); for(int index = 0; index < pointsCount; index++) { if (xStart + index >= 0 && xStart + index < w) { if (rightShift8Bits(y[index]) >= 0 && rightShift8Bits(y[index]) < h && rightShift8Bits(yMax[index]) >= 0 && rightShift8Bits(yMax[index]) < h) { int r = color.red() << 8; int g = color.green() << 8; int b = color.blue() << 8; int diff = rightShift8Bits(yMax[index]) - rightShift8Bits(y[index]) + 1; int rd = r / diff; int gd = g / diff; int bd = b / diff; unsigned char * base = dataPtr + rightShift8Bits(y[index]) * w * 4 + (xStart + index) * 4; for( int yy = rightShift8Bits(y[index]); yy < rightShift8Bits(yMax[index]) + 1; yy++) { *(base + 0) = (unsigned char)(b >> 8); *(base + 1) = (unsigned char)(g >> 8); *(base + 2) = (unsigned char)(r >> 8); *(base + 3) = 0xFF; base += w * 4; r -= rd; g -= gd; b -= bd; } } if (rightShift8Bits(y[index]) >= 0 && rightShift8Bits(y[index]) < h && rightShift8Bits(yMin[index]) >= 0 && rightShift8Bits(yMin[index]) < h ) { int r = color.red() << 8; int g = color.green() << 8; int b = color.blue() << 8; int diff = rightShift8Bits(y[index]) - rightShift8Bits(yMin[index]) + 1; int rd = r / diff; int gd = g / diff; int bd = b / diff; unsigned char * base = dataPtr + (rightShift8Bits(y[index]) -1 ) * w * 4 + (xStart + index) * 4; for (int yy = rightShift8Bits(y[index]) - 1; yy > rightShift8Bits(yMin[index]) - 1; yy *(base + 0) = (unsigned char)(b >> 8); *(base + 1) = (unsigned char)(g >> 8); *(base + 2) = (unsigned char)(r >> 8); *(base + 3) = 0xFF; base -= w * 4; r -= rd; g -= gd; b -= bd; } } } } } } void QMrOfsCompositor::fillWaveformLines(QImage* image, QAbstractMrOfs::XCOORDINATE xStart, const QAbstractMrOfs::YCOORDINATE* y, const QAbstractMrOfs::YCOORDINATE* yMin, short yFillBaseLine, unsigned int pointsCount, const QColor& color) { if (image != 0) { uchar *dataPtr = const_cast<uchar*>(const_cast<const QImage*>(image)->bits()); int w = image->width(); int h = image->height(); for (int index = 0; index < pointsCount; index++) { if (xStart + index >= 0 && xStart + index < w) { if (rightShift8Bits(y[index]) >= 0 && rightShift8Bits(y[index]) < h && rightShift8Bits(yMin[index]) >= 0 && rightShift8Bits(yMin[index]) < h) { int r = color.red() << 8; int g = color.green() << 8; int b = color.blue() << 8; int diff = rightShift8Bits(y[index]) - rightShift8Bits(yMin[index]) + 1; int rd = r / diff; int gd = g / diff; int bd = b / diff; unsigned char * base = dataPtr + rightShift8Bits(y[index]) * w * 4 + (xStart + index) * 4; for (int yy = rightShift8Bits(y[index]); yy > rightShift8Bits(yMin[index]) - 1; yy *(base + 0) = (unsigned char)(b >> 8); *(base + 1) = (unsigned char)(g >> 8); *(base + 2) = (unsigned char)(r >> 8); *(base + 3) = 0xFF; base -= w * 4; r -= rd; g -= gd; b -= bd; } } if (rightShift8Bits(y[index]) >= 0 && rightShift8Bits(y[index]) < h && yFillBaseLine >= 0 && yFillBaseLine < h ) { unsigned char * base = dataPtr + ( rightShift8Bits(y[index]) + 1) * w * 4 + (xStart + index) * 4; for( int yy = rightShift8Bits(y[index]) + 1; yy < yFillBaseLine; yy++) { *(base + 0) = color.blue(); *(base + 1) = color.green(); *(base + 2) = color.red(); *(base + 3) = 0xFF; base += w * 4; } } } } } } /*! [wave thread] */ void QMrOfsCompositor::eraseRect(QImage* image, const QRect& rect) { if ( image != 0) { uchar *dataPtr = const_cast<uchar*>( const_cast<const QImage*>(image)->bits()); int w = image->width(); int h = image->height(); for (int y = rect.top(); y < rect.bottom(); y++) { if ( y >= 0 && y < h ) { if ( rect.left() >= 0 && rect.right() < w ) { uchar *d = dataPtr + (y * w * 4) + rect.left() * 4; memset( d, 0, rect.width() * 4); } } } } } /*! [wave thread] */ void QMrOfsCompositor::drawVerticalLine(QImage* image, QAbstractMrOfs::XCOORDINATE x, QAbstractMrOfs::YCOORDINATE y1, QAbstractMrOfs::YCOORDINATE y2, const QColor& color) { if ( image != 0) { uchar *dataPtr = const_cast<uchar*>( const_cast<const QImage*>(image)->bits() ); int w = image->width(); int h = image->height(); if (y1 > y2) { uint temp = y1; y1 = y2; y2 = temp; } if ( x >= 0 && x < w ) { y1= 0.1, y2 = 0.2; int y = ( y1 >> 8 ); if ( y >= 0 && y < h ) { if ( (y1 & 0xFF ) != 0 ) { uchar t = 256 - (y1 & 0xFF); uchar * d = dataPtr + ( y * w * 4 ) + x * 4; *d = (color.red() * t) >> 8; *(d + 1 )= (color.green() * t) >> 8; *(d + 2 )= (color.blue() * t) >> 8; *(d + 3 )= 0xFF; y++; } else { } } for( ; y < (y2 >> 8); y++) { if ( y >= 0 && y < h ) { uchar * d = dataPtr + (y * w * 4 ) + x * 4; *d = color.red(); *(d + 1 )= color.green(); *(d + 2 )= color.blue(); *(d + 3 )= 0xFF; } } if ( (y2 & 0xFF ) != 0) { y++; if (y >= 0 && y < h) { uchar t = (y2 & 0xFF); uchar * d = dataPtr + ( y * w * 4 ) + x * 4; *d = (color.red() * t) >> 8; *(d + 1 )= (color.green() * t) >> 8; *(d + 2 )= (color.blue() * t) >> 8; *(d + 3 )= 0xFF; } } } } } #endif /*! only take effects for rt threads if want to change nice value for non-rt thread(all threads in specified process or process group), ref. setpriority, nice. if want to change nice value for single non-rt thread, ref. sched_setattr (first supported in kernel 3.14) */ int QMrOfsCompositor::<API key>(int newpri) { #ifdef <API key> struct sched_param sched_param; int sched_policy; if (<API key>(m_th->id, &sched_policy, &sched_param) != 0) { qWarning("QMrOfsCompositor::<API key>: Cannot get scheduler parameters"); return -1; } if(newpri > <API key>(sched_policy) || newpri < <API key>(sched_policy)) { qWarning("QMrOfsCompositor::<API key>: illegal priority(%d) for current policy(%d)", newpri, sched_policy); return -1; } sched_param.sched_priority = newpri; <API key>(m_th->id, sched_policy, &sched_param); #else Q_UNUSED(newpri); #endif return 0; } void QMrOfsCompositor::lockWaveResources() { #ifdef <API key> m_mutex_wv.lock(); #endif } void QMrOfsCompositor::unlockWaveResources() { #ifdef <API key> m_mutex_wv.unlock(); #endif } void QMrOfsCompositor::<API key>() { #ifdef <API key> m_mutex_bs.lock(); #endif } void QMrOfsCompositor::<API key>() { #ifdef <API key> m_mutex_bs.unlock(); #endif } void QMrOfsCompositor::flushBackingStore(const QRegion& dirty) { int at = this->metaObject()->indexOfMethod("flushBackingStore2(QRegion)"); if (at == -1) { qWarning("QMrOfsCompositor::flushBackingStore2: indexOfMethod failed"); return; } QMetaMethod method = this->metaObject()->method(at); method.invoke(this, this->m_conn_type, Q_ARG(QRegion, dirty)); } /*! \note bs effective clip region MUST BE clean in compositor thread in flushBackingStore calling, otherwise it will be in race condition with next compositing triggered by flushWaves. the same as wave effective region cleaning. \ref flushWaves, <API key>.<API key> */ void QMrOfsCompositor::flushBackingStore2(const QRegion& dirty) { Q_UNUSED(dirty); if(!m_bs_flush_enabled) return; //data has been flushed in QMrOfsBackingStore composite(<API key>); } void QMrOfsCompositor::resizeBackingStore(QMrOfsBackingStore *bs, const QSize &size, const QRegion &rgn) { int at = this->metaObject()->indexOfMethod("resizeBackingStore2(QMrOfsBackingStore*,QSize,QRegion)"); if (at == -1) { qWarning("QMrOfsCompositor::resizeBackingStore2: indexOfMethod failed"); return; } QMetaMethod method = this->metaObject()->method(at); method.invoke(this, this->m_conn_type, Q_ARG(QMrOfsBackingStore*, bs), Q_ARG(QSize, size), Q_ARG(QRegion, rgn)); } void QMrOfsCompositor::resizeBackingStore2(QMrOfsBackingStore *bs, const QSize &size, const QRegion &rgn) { bs->doResize(size, rgn); } /*! \note RANGE: all dirty waveforms region + dirty backingstore region, TLW coordinate OP: SRC qt_dirty_in_bs: TLW coordinate == bs coordinate */ //#define <API key> //#define <API key> const QRegion& QMrOfsCompositor::drawBackingStore() { //setup compositing clip region const QRegion & dirty_in_bs = m_wc->compositeRegion(); //backingstore's coordinate is the same as tlw's, what we realy want here is region in backingstore's coordinatre, PVR2DERROR err = PVR2D_OK; QMrOfsShmImage *dstPic = m_scrn->picture(); // m_fb_shadow_pict OPT QMrOfsShmImage *srcPic = reinterpret_cast<QMrOfsShmImage*>(m_bs->platformImage()); if(!srcPic || !dstPic) { // !srcPic: backingstore has not been resized when something else(waves, cursors, ...) want to composite return dirty_in_bs; } QVector<QRect> rects = dirty_in_bs.rects(); #if defined(DEBUG_GPU_BLT) && defined(BATCH_BLT) static PVR2DRECT pvrRects[64]; int realNum = rects.size() > 64 ? 64 : rects.size(); if(rects.size() > 64) { qWarning("drawBackingStore: rects num exceeds 64"); } for(int i = 0; i < realNum; i++) { const QRect& rc = rects.at(i); pvrRects[i].left = rc.left(); pvrRects[i].top = rc.top(); pvrRects[i].right = rc.right(); pvrRects[i].bottom = rc.bottom(); #ifdef DEBUG_BACKINGSTORE qDebug("drawBackingstore rc_num(%d), index(%d), rc(%d,%d,%d,%d), dst(%d,%d),src(%d,%d)", rects.size(), i, rc.left(), rc.top(), rc.width(), rc.height(), dstPic->image()->size().width(), dstPic->image()->size().height(), srcPic->image()->size().width(), srcPic->image()->size().height()); #endif } m_blt_inf.CopyCode = PVR2DROPcopy; m_blt_inf.BlitFlags = <API key>; // SRC OP m_blt_inf.pDstMemInfo = dstPic->pvr2DMem(); m_blt_inf.DstSurfWidth = dstPic->size().width(); m_blt_inf.DstSurfHeight = dstPic->size().height(); m_blt_inf.DstStride = dstPic->stride(); m_blt_inf.DstFormat = dstPic->pvr2DFormat(); m_blt_inf.DSizeX = srcPic->size().width(); m_blt_inf.DSizeY = srcPic->size().height(); m_blt_inf.DstX = 0; m_blt_inf.DstY = 0; m_blt_inf.pSrcMemInfo = srcPic->pvr2DMem(); m_blt_inf.SrcSurfWidth = srcPic->size().width(); m_blt_inf.SrcSurfHeight = srcPic->size().height(); m_blt_inf.SrcStride = srcPic->stride(); m_blt_inf.SrcFormat = srcPic->pvr2DFormat(); m_blt_inf.SizeX = m_blt_inf.DSizeX; m_blt_inf.SizeY = m_blt_inf.DSizeY; m_blt_inf.SrcX = m_blt_inf.DstX; m_blt_inf.SrcY = m_blt_inf.DstY; if(!m_blt_inf.pDstMemInfo || !m_blt_inf.pSrcMemInfo) { return; } if((err = PVR2DBltClipped(m_scrn->deviceContext(), &m_blt_inf, realNum, pvrRects)) != PVR2D_OK) { qWarning("drawBackingStore: PVR2DBltClipped failed: error(%d)", err); } return dirty_in_bs; #endif // BATCH_BLT for(int i = 0; i < rects.size(); i ++) { const QRect& rc = rects.at(i); #ifdef DEBUG_BACKINGSTORE qDebug("drawBackingstore rc_num(%d), index(%d), rc(%d,%d,%d,%d), dst(%d,%d),src(%d,%d)", rects.size(), i, rc.left(), rc.top(), rc.width(), rc.height(), dstPic->image()->size().width(), dstPic->image()->size().height(), srcPic->image()->size().width(), srcPic->image()->size().height()); #endif #if defined(DEBUG_CPU_BLT) || defined(<API key>) QImage *srcImg = srcPic->image(); unsigned int *srcBits = (unsigned int*)(srcImg->bits()); QImage *dstImg = dstPic->image(); unsigned int *dstBits = (unsigned int*)(dstImg->bits()); QRect intersect = rc.intersected(QRect(0, 0, dstImg->width(), dstImg->height())); intersect = intersect.intersected(QRect(0, 0, srcImg->width(), srcImg->height())); #endif #ifdef <API key> static int k; k++; int start_m = rc.top(); int end_m = rc.top() + rc.height(); int start_n = rc.left(); int end_n = rc.left() + rc.width(); if(k%2) { for(int m = start_m; m < end_m; m++) { for(int n = start_n; n < end_n; n ++) { srcBits[m * srcImg->width() + n] = 0xFF9F9DEF; //;0xFFFF0000 } } } else { for(int m = start_m; m < end_m; m++) { for(int n = start_n; n < end_n; n ++) { srcBits[m * srcImg->width() + n] = 0xFFEFEBE7; //;0xFF0000FF } } } #endif // <API key> #ifdef DEBUG_GPU_BLT // GPU BLT m_blt_inf.CopyCode = PVR2DROPcopy; m_blt_inf.BlitFlags = <API key>; // SRC OP m_blt_inf.pDstMemInfo = dstPic->pvr2DMem(); m_blt_inf.DstSurfWidth = dstPic->size().width(); m_blt_inf.DstSurfHeight = dstPic->size().height(); m_blt_inf.DstStride = dstPic->stride(); m_blt_inf.DstFormat = dstPic->pvr2DFormat(); m_blt_inf.DSizeX = rc.width(); m_blt_inf.DSizeY = rc.height(); m_blt_inf.DstX = rc.x(); m_blt_inf.DstY = rc.y(); m_blt_inf.pSrcMemInfo = srcPic->pvr2DMem(); m_blt_inf.SrcSurfWidth = srcPic->size().width(); m_blt_inf.SrcSurfHeight = srcPic->size().height(); m_blt_inf.SrcStride = srcPic->stride(); m_blt_inf.SrcFormat = srcPic->pvr2DFormat(); m_blt_inf.SizeX = m_blt_inf.DSizeX; m_blt_inf.SizeY = m_blt_inf.DSizeY; m_blt_inf.SrcX = rc.x(); m_blt_inf.SrcY = rc.y(); if(!m_blt_inf.pDstMemInfo || !m_blt_inf.pSrcMemInfo) { return; } if((err = PVR2DBlt(m_scrn->deviceContext(), &m_blt_inf)) != PVR2D_OK) { qWarning("drawBackingStore: PVR2DBlt failed: error(%d), \ CopyCode(%lu), BlitFlags(0x%x), \ DstSurfWidth(%lu), DstSurfHeight(%lu), DstStride(%ld), DstFormat(0x%x), \ DSizeX(%ld), DSizeY(%ld), DstX(%ld), DstY(%ld), \ SrcSurfWidth(%lu), SrcSurfHeight(%lu), SrcStride(%ld), SrcFormat(0x%x), \ SizeX(%ld), SizeY(%ld), SrcX(%ld), SrcY(%ld)", err, m_blt_inf.CopyCode, static_cast<uint>(m_blt_inf.BlitFlags), m_blt_inf.DstSurfWidth, m_blt_inf.DstSurfHeight, m_blt_inf.DstStride, static_cast<uint>(m_blt_inf.DstFormat), m_blt_inf.DSizeX, m_blt_inf.DSizeY, m_blt_inf.DstX, m_blt_inf.DstY, m_blt_inf.SrcSurfWidth, m_blt_inf.SrcSurfHeight, m_blt_inf.SrcStride, static_cast<uint>(m_blt_inf.SrcFormat), m_blt_inf.SizeX, m_blt_inf.SizeY, m_blt_inf.SrcX, m_blt_inf.SrcY); } # ifdef <API key> qDebug("bltinf: srcmeminf(%p), srcsurfw(%d), srcsufh(%d), srcstride(%d), srcfmt(%d), srcSX(%d), srcSY(%d), srcX(%d), srcY(%d)", m_blt_inf.pSrcMemInfo->pBase, m_blt_inf.SrcSurfWidth, m_blt_inf.SrcSurfHeight, m_blt_inf.SrcStride, m_blt_inf.SrcFormat, m_blt_inf.SizeX, m_blt_inf.SizeY, m_blt_inf.SrcX, m_blt_inf.SrcY); qDebug("bltinf: dstmeminf(%p), dstsurfw(%d), dstsufh(%d), dststride(%d), dstfmt(%d), dstSX(%d), dstSY(%d), dstX(%d), dstY(%d)", m_blt_inf.pDstMemInfo->pBase, m_blt_inf.DstSurfWidth, m_blt_inf.DstSurfHeight, m_blt_inf.DstStride, m_blt_inf.DstFormat, m_blt_inf.DSizeX, m_blt_inf.DSizeY, m_blt_inf.DstX, m_blt_inf.DstY); # endif //<API key> #else for(int m = intersect.top(); m < intersect.top() + intersect.height(); m++) { for(int n = intersect.left(); n < intersect.left() + intersect.width(); n ++) { dstBits[m * dstImg->width() + n] = srcBits[m * srcImg->width() + n]; } } #endif // DEBUG_CPU_BLT #ifdef <API key> for(int m = intersect.top(); m < intersect.top() + intersect.height(); m++) { for(int n = intersect.left(); n < intersect.left() + intersect.width(); n ++) { if(!(srcBits[m * srcImg->width() + n] == 0xFF9F9DEF || srcBits[m * srcImg->width() + n] == 0xFFEFEBE7)) { qDebug("src bits pixel abnormal: 0x%x", srcBits[m * srcImg->width() + n]); } if(!(dstBits[m * srcImg->width() + n] == 0xFF9F9DEF || dstBits[m * srcImg->width() + n] == 0xFFEFEBE7)) { qDebug("dst bits pixel abnormal: 0x%x", srcBits[m * srcImg->width() + n]); } } } qDebug("1 pixel: SRC argb(0x%x); DST argb(0x%x)", srcBits[(intersect.top() + intersect.height() / 2) * srcImg->width() + intersect.left() + intersect.width() / 2], dstBits[(intersect.top() + intersect.height() / 2) * srcImg->width() + intersect.left() + intersect.width() / 2]); #endif //<API key> } return dirty_in_bs; } /*! wave controller(as object structure) will accept the visiting of it's waveform(as elements) from compositor(as visitor) */ void QMrOfsCompositor::drawWaveforms() { //traverse all waveforms via z-order bottom to top m_wc->accept(this); } /*! visiting action to wave controller from compositor callback by <API key> \note RANGE: this waveform effective clip region, TLW coordinate OP: PICT_OP_OVER dirty_in_wf: WF coordinate */ //#define <API key> 1 void QMrOfsCompositor::visitWaveform(QMrOfsWaveform* wf) { //do draw wfs {{{ //setup compositing clip region if(!wf) return; const QRegion &dirty_in_wf = wf-><API key>(); // WF coordinates QMrOfsShmImage* srcPic = static_cast<QMrOfsShmImage*>(wf->platformImage()); PVR2DERROR err = PVR2D_OK; QMrOfsShmImage *dstPic = m_scrn->picture(); // m_fb_shadow_pict OPT QVector<QRect> rects = dirty_in_wf.rects(); #if defined(DEBUG_GPU_BLT) && defined(BATCH_BLT) PVR2DRECT pvrRects[64]; int real_num = rects.size() > 64 ? 64 : rects.size(); for(int i = 0; i < real_num; i++) { const QRect& rc = rects.at(i); pvrRects[i].left = rc.left() + wf->originInTLW().x(); pvrRects[i].top = rc.top() + wf->originInTLW().y(); pvrRects[i].right = rc.right(); pvrRects[i].bottom = rc.bottom(); } m_blt_inf.CopyCode = PVR2DROPcopy; m_blt_inf.BlitFlags = <API key>; m_blt_inf.AlphaBlendingFunc = <API key>; m_blt_inf.pDstMemInfo = dstPic->pvr2DMem(); m_blt_inf.DstSurfWidth = dstPic->size().width(); m_blt_inf.DstSurfHeight = dstPic->size().height(); m_blt_inf.DstStride = dstPic->stride(); m_blt_inf.DstFormat = dstPic->pvr2DFormat(); m_blt_inf.DSizeX = m_blt_inf.DstSurfWidth; m_blt_inf.DSizeY = m_blt_inf.DstSurfHeight; m_blt_inf.DstX = 0 + wf->originInTLW().x(); // tlw coordinate m_blt_inf.DstY = 0 + wf->originInTLW().y(); m_blt_inf.pSrcMemInfo = srcPic->pvr2DMem(); m_blt_inf.SrcSurfWidth = srcPic->size().width(); m_blt_inf.SrcSurfHeight = srcPic->size().height(); m_blt_inf.SrcStride = srcPic->stride(); m_blt_inf.SrcFormat = srcPic->pvr2DFormat(); m_blt_inf.SizeX = m_blt_inf.SrcSurfWidth; m_blt_inf.SizeY = m_blt_inf.SrcSurfHeight; m_blt_inf.SrcX = 0; // wf coordinate m_blt_inf.SrcY = 0; if(!m_blt_inf.pDstMemInfo || !m_blt_inf.pSrcMemInfo) { return; } if((err = PVR2DBltClipped(m_scrn->deviceContext(), &m_blt_inf, real_num, pvrRects)) != PVR2D_OK) { qWarning("visitWaveform: PVR2DBltClipped failed: error(%d)", err); } return; #endif for(int i = 0; i < rects.size(); i ++) { const QRect& rc = rects.at(i); #if defined(DEBUG_CPU_BLT) || defined(<API key>) QImage *srcImg = srcPic->image(); unsigned int *srcBits = (unsigned int*)(srcImg->bits()); QImage *dstImg = dstPic->image(); unsigned int *dstBits = (unsigned int*)(dstImg->bits()); QRect rcInTLW = rc.translated(wf->originInTLW()); // tlw coordinate QRect intersect = rcInTLW.intersected(QRect(0, 0, dstImg->width(), dstImg->height())); // tlw coordinate intersect = intersect.intersected(QRect(wf->originInTLW().x(), wf->originInTLW().y(), srcImg->width(), srcImg->height())); #endif #ifdef DEBUG_GPU_BLT m_blt_inf.CopyCode = PVR2DROPcopy; m_blt_inf.BlitFlags = <API key>; m_blt_inf.AlphaBlendingFunc = <API key>; // src over dst, with premultiplied-alpha m_blt_inf.pDstMemInfo = dstPic->pvr2DMem(); m_blt_inf.DstSurfWidth = dstPic->size().width(); m_blt_inf.DstSurfHeight = dstPic->size().height(); m_blt_inf.DstStride = dstPic->stride(); m_blt_inf.DstFormat = dstPic->pvr2DFormat(); m_blt_inf.DSizeX = rc.width(); m_blt_inf.DSizeY = rc.height(); m_blt_inf.DstX = rc.x() + wf->originInTLW().x(); // tlw coordinate m_blt_inf.DstY = rc.y() + wf->originInTLW().y(); m_blt_inf.pSrcMemInfo = srcPic->pvr2DMem(); m_blt_inf.SrcSurfWidth = srcPic->size().width(); m_blt_inf.SrcSurfHeight = srcPic->size().height(); m_blt_inf.SrcStride = srcPic->stride(); m_blt_inf.SrcFormat = srcPic->pvr2DFormat(); m_blt_inf.SizeX = rc.width(); m_blt_inf.SizeY = rc.height(); m_blt_inf.SrcX = rc.x(); // wf coordinate m_blt_inf.SrcY = rc.y(); if(!m_blt_inf.pDstMemInfo || !m_blt_inf.pSrcMemInfo) { return; } if((err = PVR2DBlt(m_scrn->deviceContext(), &m_blt_inf)) != PVR2D_OK) { qWarning("visitWaveform: PVR2DBlt failed: error(%d), \ CopyCode(%lu), BlitFlags(0x%x), \ DstSurfWidth(%lu), DstSurfHeight(%lu), DstStride(%ld), DstFormat(0x%x), \ DSizeX(%ld), DSizeY(%ld), DstX(%ld), DstY(%ld), \ SrcSurfWidth(%lu), SrcSurfHeight(%lu), SrcStride(%ld), SrcFormat(0x%x), \ SizeX(%ld), SizeY(%ld), SrcX(%ld), SrcY(%ld)", err, m_blt_inf.CopyCode, static_cast<uint>(m_blt_inf.BlitFlags), m_blt_inf.DstSurfWidth, m_blt_inf.DstSurfHeight, m_blt_inf.DstStride, static_cast<uint>(m_blt_inf.DstFormat), m_blt_inf.DSizeX, m_blt_inf.DSizeY, m_blt_inf.DstX, m_blt_inf.DstY, m_blt_inf.SrcSurfWidth, m_blt_inf.SrcSurfHeight, m_blt_inf.SrcStride, static_cast<uint>(m_blt_inf.SrcFormat), m_blt_inf.SizeX, m_blt_inf.SizeY, m_blt_inf.SrcX, m_blt_inf.SrcY); } # ifdef <API key> qDebug("bltinf: srcmeminf(%p), srcsurfw(%d), srcsufh(%d), srcstride(%d), srcfmt(%d), srcSX(%d), srcSY(%d), srcX(%d), srcY(%d)", m_blt_inf.pSrcMemInfo->pBase, m_blt_inf.SrcSurfWidth, m_blt_inf.SrcSurfHeight, m_blt_inf.SrcStride, m_blt_inf.SrcFormat, m_blt_inf.SizeX, m_blt_inf.SizeY, m_blt_inf.SrcX, m_blt_inf.SrcY); qDebug("bltinf: dstmeminf(%p), dstsurfw(%d), dstsufh(%d), dststride(%d), dstfmt(%d), dstSX(%d), dstSY(%d), dstX(%d), dstY(%d)", m_blt_inf.pDstMemInfo->pBase, m_blt_inf.DstSurfWidth, m_blt_inf.DstSurfHeight, m_blt_inf.DstStride, m_blt_inf.DstFormat, m_blt_inf.DSizeX, m_blt_inf.DSizeY, m_blt_inf.DstX, m_blt_inf.DstY); # endif //<API key> #else for(int m = intersect.top(); m < intersect.top() + intersect.height(); m++) { for(int n = intersect.left(); n < intersect.left() + intersect.width(); n ++) { int mInWF = m - wf->originInTLW().y(); int nInWF = n - wf->originInTLW().x(); uint s = srcBits[mInWF * srcImg->width() + nInWF]; if (s >= 0xff000000) dstBits[m * dstImg->width() + n] = s; else if (s != 0) dstBits[m * dstImg->width() + n] = s + BYTE_MUL(dstBits[m * dstImg->width() + n], qAlpha(~s)); } } #endif // DEBUG_CPU_BLT } //anything else we can do ? } /*! \note IVIEW use SRC, not OVER NOTE: waiting finished here maybe unnecessary since iview has multiple buffers in mipi-csi */ void QMrOfsCompositor::visitIViewform(QMrOfsWaveform* wf) { Q_UNUSED(wf); } /*! old position has already been re-composited during drawBackingStore and drawWaveforms curRect: TLW coordinate rcInCursor: CURSOR coordinate */ QRect QMrOfsCompositor::drawCursor(const QRegion& composeRgn) { if(!m_cursor) { qWarning("drawCursor: m_cursor is NULL"); return QRect(); } QRect curRect = m_cursor->drawCursor(); //new position, TLW coordinate if(curRect.isEmpty()) { qWarning("drawCursor: curRect isEmpty or NOT in composite region"); return QRect(); } QRect rcInCursor(0, 0, curRect.width(), curRect.height()); // cursor image coordinate QMrOfsShmImage *srcPic = m_cursor->picture(); PVR2DERROR err = PVR2D_OK; QMrOfsShmImage *dstPic = m_scrn->picture(); // m_fb_shadow_pict OPT #if defined(DEBUG_CPU_BLT) || defined(DEBUG_PIXEL_CURSOR) QImage *srcImg = srcPic->image(); unsigned int *srcBits = (unsigned int*)(srcImg->bits()); QImage *dstImg = dstPic->image(); unsigned int *dstBits = (unsigned int*)(dstImg->bits()); QRect intersect = curRect.intersected(QRect(0, 0, dstImg->width(), dstImg->height())); #endif #ifdef DEBUG_GPU_BLT m_blt_inf.CopyCode = PVR2DROPcopy; m_blt_inf.BlitFlags = <API key>; m_blt_inf.AlphaBlendingFunc = <API key>; // <API key> m_blt_inf.pDstMemInfo = dstPic->pvr2DMem(); m_blt_inf.DstSurfWidth = dstPic->size().width(); m_blt_inf.DstSurfHeight = dstPic->size().height(); m_blt_inf.DstStride = dstPic->stride(); m_blt_inf.DstFormat = dstPic->pvr2DFormat(); m_blt_inf.DSizeX = rcInCursor.width(); m_blt_inf.DSizeY = rcInCursor.height(); m_blt_inf.DstX = curRect.x(); m_blt_inf.DstY = curRect.y(); m_blt_inf.pSrcMemInfo = srcPic->pvr2DMem(); m_blt_inf.SrcSurfWidth = srcPic->size().width(); m_blt_inf.SrcSurfHeight = srcPic->size().height(); m_blt_inf.SrcStride = srcPic->stride(); m_blt_inf.SrcFormat = srcPic->pvr2DFormat(); m_blt_inf.SizeX = rcInCursor.width(); m_blt_inf.SizeY = rcInCursor.height(); m_blt_inf.SrcX = 0; m_blt_inf.SrcY = 0; if(!m_blt_inf.pDstMemInfo || !m_blt_inf.pSrcMemInfo) { return; } if((err = PVR2DBlt(m_scrn->deviceContext(), &m_blt_inf)) != PVR2D_OK) { qWarning("drawCursor: PVR2DBlt failed: error(%d), \ CopyCode(%lu), BlitFlags(0x%x), \ DstSurfWidth(%lu), DstSurfHeight(%lu), DstStride(%ld), DstFormat(0x%x), \ DSizeX(%ld), DSizeY(%ld), DstX(%ld), DstY(%ld), \ SrcSurfWidth(%lu), SrcSurfHeight(%lu), SrcStride(%ld), SrcFormat(0x%x), \ SizeX(%ld), SizeY(%ld), SrcX(%ld), SrcY(%ld)", err, m_blt_inf.CopyCode, static_cast<uint>(m_blt_inf.BlitFlags), m_blt_inf.DstSurfWidth, m_blt_inf.DstSurfHeight, m_blt_inf.DstStride, static_cast<uint>(m_blt_inf.DstFormat), m_blt_inf.DSizeX, m_blt_inf.DSizeY, m_blt_inf.DstX, m_blt_inf.DstY, m_blt_inf.SrcSurfWidth, m_blt_inf.SrcSurfHeight, m_blt_inf.SrcStride, static_cast<uint>(m_blt_inf.SrcFormat), m_blt_inf.SizeX, m_blt_inf.SizeY, m_blt_inf.SrcX, m_blt_inf.SrcY); } #else QPainter p(dstPic->image()); qDebug("drawCursor: curRect(%d,%d,%d,%d), srcPic(%d,%d)", curRect.x(), curRect.y(), curRect.width(), curRect.height(), srcPic->image()->size().width(), srcPic->image()->size().height()); p.drawImage(curRect, *srcPic->image()); #if 0 for(int m = intersect.top(); m < intersect.top() + intersect.height(); m++) { for(int n = intersect.left(); n < intersect.left() + intersect.width(); n ++) { int mInCursor = m - intersect.top(); int nInCursor = n - intersect.left(); uint s = srcBits[mInCursor * srcImg->width() + nInCursor]; if (s >= 0xff000000) dstBits[m * dstImg->width() + n] = s; else if (s != 0) dstBits[m * dstImg->width() + n] = s + BYTE_MUL(dstBits[m * dstImg->width() + n], qAlpha(~s)); } } #endif #endif // DEBUG_CPU_BLT return curRect; } /* Region: compositeRegion + cursorRegion(new position) in TLW coordinate OP: OP_SRC Src: m_fb_shadow_pict Dst: fb */ void QMrOfsCompositor::sync(const QRegion& compositeRgn, const QRegion& curRgn) { // hope the execution sequence of GPU is FIFO, which means waiting for the last one to complete is just fine <API key>(m_scrn->deviceContext(), m_blt_inf.pDstMemInfo, 1); m_screen_dirty_rgn = compositeRgn + curRgn; // src/dst: TLW coordinate m_screen_dirty_rgn &= m_scrn->geometry(); #if QT_MRDP m_mrdp-><API key>(m_screen_dirty_rgn); #endif #if 0 QVector<QRect> rects = m_screen_dirty_rgn.rects(); int round = rects.size() / BATCH_RC_MAX_NUM; // total_round = round + remainder(0 or 1) int r = 0; // rounding index int j = 0; // batch buffer index // max num batch for (r = 0; r < round; r ++) { for (int i = r * BATCH_RC_MAX_NUM; i < (r + 1) * BATCH_RC_MAX_NUM; i ++) { const QRect &rc = rects[i]; j = i - (r * BATCH_RC_MAX_NUM); m_batchRcs[j].left = rc.x(); m_batchRcs[j].top = rc.y(); m_batchRcs[j].right = rc.x() + rc.width(); m_batchRcs[j].bottom = rc.y() + rc.height(); } for (int i = r * BATCH_RC_MAX_NUM; i < (r + 1) * BATCH_RC_MAX_NUM; i += 4) { int numClip = (r + 1) * BATCH_RC_MAX_NUM - i; j = i - (r * BATCH_RC_MAX_NUM); if (numClip > 4) /* No more than 4 clip rects at a time */ numClip = 4; <API key>(m_scrn->deviceContext(), <API key> | <API key> | <API key> | <API key>, m_fb_shadow_pict->stride(), m_batchRcs[j].right - m_batchRcs[j].left, m_batchRcs[j].top - m_batchRcs[j].bottom, m_batchRcs[j].left, m_batchRcs[j].top, // dst: TLW coordinate numClip, m_batchRcs + j, // src: TLW coordinate 0); PVR2DPresentBlt(m_scrn->deviceContext(), m_fb_shadow_pict->pvr2DMem(), 0); // m_fb_shadow_pict -> fb } } //remainder batch for (int i = r * BATCH_RC_MAX_NUM; i < rects.size(); i ++) { const QRect &rc = rects[i]; j = i - (r * BATCH_RC_MAX_NUM); m_batchRcs[j].left = rc.x(); m_batchRcs[j].top = rc.y(); m_batchRcs[j].right = rc.x() + rc.width(); m_batchRcs[j].bottom = rc.y() + rc.height(); } for (int i = r * BATCH_RC_MAX_NUM; i < rects.size(); i += 4) { j = i - (r * BATCH_RC_MAX_NUM); int numClip = rects.size() - i; if (numClip > 4) /* No more than 4 clip rects at a time */ numClip = 4; <API key>(m_scrn->deviceContext(), <API key> | <API key> | <API key> | <API key>, m_fb_shadow_pict->stride(), m_batchRcs[j].right - m_batchRcs[j].left, m_batchRcs[j].top - m_batchRcs[j].bottom, m_batchRcs[j].left, m_batchRcs[j].top, // dst: TLW coordinate numClip, m_batchRcs + j, // src: TLW coordinate 0); PVR2DPresentBlt(m_scrn->deviceContext(), m_fb_shadow_pict->pvr2DMem(), 0); // m_fb_shadow_pict -> fb } <API key>(m_scrn->deviceContext(), m_fb_shadow_pict->pvr2DMem(), 1); #endif } void QMrOfsCompositor::composite(Reason reason) { #if defined(MROFS__PROFILING) static int frames; static struct timeval lastTime; struct timeval startTime, endTime; unsigned long diffTime; gettimeofday(&startTime, NULL); //qWarning("MROFS__PROFILING: composite before: %ld:%ld", startTime.tv_sec, startTime.tv_usec); #endif if (!m_enabled) //switch off return; if (<API key> == reason) { //ui thread must be waiting, locking wave resources enough lockWaveResources(); lockIViewResources(); } else if (<API key> == reason) { //wave thread must be waiting, locking bs resource is enough <API key>(); lockIViewResources(); } else if (<API key> == reason) { lockWaveResources(); <API key>(); } else if(TRIGGERED_BY_CURSOR == reason) { <API key>(); lockWaveResources(); lockIViewResources(); } #ifdef QT_MRDP lockScreenResources(); // in case mrdp snoop #endif if(updateClipRegions()) { //update in use const QRegion &compositeRgn = drawBackingStore(); //layer 0(topleast) drawWaveforms(); //layer 1(maybe more than 1 sub layers: Nx waveforms + 1x iviewform) QRect curRc; if(m_cursor && (m_cursor->isDirty() || compositeRgn.intersects(m_cursor->lastPainted()))) { curRc = drawCursor(compositeRgn); //layer 2(topmost) } sync(compositeRgn, curRc); //wait until fb buffer switched } cleanClipRegions(); //clean bs+wv dirty regions processed this time #ifdef QT_MRDP <API key>(); // in case of mrdp snoop #endif if (<API key> == reason) { unlockWaveResources(); <API key>(); } else if (<API key> == reason) { <API key>(); <API key>(); } else if (<API key> == reason) { unlockWaveResources(); <API key>(); } else if(TRIGGERED_BY_CURSOR == reason) { <API key>(); unlockWaveResources(); <API key>(); } #if defined(MROFS__PROFILING) gettimeofday(&endTime, NULL); diffTime = tv_diff(&startTime, &endTime); //qWarning("MROFS__PROFILING: composite after: %ld:%ld, diff: %ld", endTime.tv_sec, endTime.tv_usec, diffTime); //FPS static bool fpsDebug = qgetenv("QT_DEBUG_COMP_FPS").toInt(); if(fpsDebug) { frames ++; diffTime = tv_diff(&lastTime, &endTime); if(diffTime > 5000) { qWarning("compositing FPS: %ld, in seconds(%ld), frames(%ld)", (frames*1000)/diffTime, diffTime/1000, frames); lastTime = endTime; frames = 0; } } #endif } /*! iview layer can be more efficient since it's opaque(bs layer may omit rgn_iv_popup - rgns_above_iv_popup) */ bool QMrOfsCompositor::updateClipRegions() { const QRegion &bs_clip = m_bs->effectiveClip(); QRect old_cursor_rgn; if (m_cursor && m_cursor->isDirty() && m_cursor->isOnScreen()) { //translate curRect from screen coordinate to tlw coordinate in which case tlw is always in primary screen coordinate old_cursor_rgn = m_cursor->dirtyRect(); } return m_wc-><API key>(bs_clip, old_cursor_rgn); } void QMrOfsCompositor::cleanClipRegions() { //clean bs clip region m_bs->cleanEffectiveClip(); //clean wv clip region m_wc->cleanEffectiveClips(); //clean wfs clip region and composite region } void QMrOfsCompositor::setCursor(QMrOfsCursor *cursor) { int at = this->metaObject()->indexOfMethod("setCursor2(QMrOfsCursor*)"); if (at == -1) { qWarning("QMrOfsCompositor::setCursor2: indexOfMethod failed"); return; } QMetaMethod method = this->metaObject()->method(at); method.invoke(this, this->m_conn_type, Q_ARG(QMrOfsCursor*, cursor)); } void QMrOfsCompositor::setCursor2(QMrOfsCursor *cursor) { m_cursor = cursor; } void QMrOfsCompositor::pointerEvent(const QMouseEvent &e) { int at = this->metaObject()->indexOfMethod("pointerEvent2(QMouseEvent)"); if (at == -1) { qWarning("QMrOfsCompositor::pointerEvent2: indexOfMethod failed"); return; } QMetaMethod method = this->metaObject()->method(at); method.invoke(this, this->m_conn_type, Q_ARG(QMouseEvent, e)); } void QMrOfsCompositor::pointerEvent2(const QMouseEvent &e) { if(m_cursor) { m_cursor->doPointerEvent(e); } else { qWarning("QMrOfsCompositor::pointerEvent2: no cursor found"); } } void QMrOfsCompositor::changeCursor(QCursor * widgetCursor, QWindow *window) { int at = this->metaObject()->indexOfMethod("changeCursor2(QCursor*,QWindow*)"); if (at == -1) { qWarning("QMrOfsCompositor::changeCursor2: indexOfMethod failed"); return; } QMetaMethod method = this->metaObject()->method(at); method.invoke(this, this->m_conn_type, Q_ARG(QCursor*, widgetCursor), Q_ARG(QWindow*, window)); } void QMrOfsCompositor::changeCursor2(QCursor * widgetCursor, QWindow *window) { if(m_cursor) { m_cursor->doChangeCursor(widgetCursor, window); } else { qWarning("QMrOfsCompositor::changeCursor2: no cursor found"); } } /*! [compositor thread] cursor updating reason is the same as backingstore */ void QMrOfsCompositor::flushCursor() { if(!m_cr_flush_enabled) return; composite(TRIGGERED_BY_CURSOR); } QRect QMrOfsCompositor::initialize(QMrOfsScreen *scrn) { Q_UNUSED(scrn); // TODO: initialize compositor after screen initialized if want a in-screen compositor } QRect QMrOfsCompositor::initialize2(QMrOfsScreen *scrn) { Q_UNUSED(scrn); // TODO: in-screen compositor return QRect(); } bool QMrOfsCompositor::enableBSFlushing(bool enable) { bool ret = m_bs_flush_enabled; m_bs_flush_enabled = enable; return ret; } bool QMrOfsCompositor::enableWVFlushing(bool enable) { bool ret = m_wv_flush_enabled; m_wv_flush_enabled = enable; return ret; } bool QMrOfsCompositor::enableIVFlushing(bool enable) { bool ret = m_iv_flush_enabled; m_iv_flush_enabled = enable; return ret; } bool QMrOfsCompositor::enableCRFlushing(bool enable) { bool ret = m_cr_flush_enabled; m_cr_flush_enabled = enable; return ret; } #ifdef QT_MRDP Q_INVOKABLE bool QMrOfsCompositor::startMRDPService() { if(!m_mrdp) { qWarning("MRDP Connection Manager not exist: %s", __FUNCTION__); } m_mrdp->startService(this); // now mrdp service can take advantage of me } Q_INVOKABLE void QMrOfsCompositor::stopMRDPService() { if(!m_mrdp) { qWarning("MRDP Connection Manager not exist: %s", __FUNCTION__); } m_mrdp->stopService(); } Q_INVOKABLE bool QMrOfsCompositor::MRDPServiceRunning() { if(!m_mrdp) { qWarning("MRDP Connection Manager not exist: %s", __FUNCTION__); } return m_mrdp->serviceRunning(); } const QRegion& QMrOfsCompositor::screenDirtyRegion() { return m_screen_dirty_rgn; } const QImage& QMrOfsCompositor::screenImage() { QMrOfsShmImage *scrnPic = m_scrn->picture(); // scrnPic as src if(!scrnPic) { qWarning("screen picture is NULL :%s", __FUNCTION__); return; } return scrnPic->image() ? *(scrnPic->image()) : <API key>::screenImage(); } void QMrOfsCompositor::lockScreenResources() { m_mutex_screen.lock(); } void QMrOfsCompositor::<API key>() { m_mutex_screen.unlock(); } #endif //QT_MRDP QT_END_NAMESPACE
<? <? require_once('../include/errorhandler.php'); require_once('../include/sessioninfo.php'); require_once('../include/common.php'); require_once('../include/config.php'); require_once('../include/db_functions.php'); require_once('../include/theme.php'); require_once('../cek.php'); $varbaris=10; if (isset($_REQUEST['varbaris'])) $varbaris = $_REQUEST['varbaris']; $page=0; if (isset($_REQUEST['page'])) $page = $_REQUEST['page']; $hal=0; if (isset($_REQUEST['hal'])) $hal = $_REQUEST['hal']; $op = $_GET['op']; $replid = $_GET['replid']; $pekerjaan_kiriman=$_REQUEST['pekerjaan']; if (($op == "del") && (strlen($replid) > 0)) { OpenDb(); $sql = "DELETE FROM sklumum.jenispekerjaan WHERE replid = '$replid'"; $result = QueryDb($sql); CloseDb(); $page=0; $hal=0; } ?> <!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="../style/style.css"> <link rel="stylesheet" type="text/css" href="../style/tooltips.css"> <script language="javascript" src="../script/tables.js"></script> <script language="javascript" src="../script/tools.js"></script> <script language="JavaScript" src="../script/tooltips.js"></script> <script language="javascript"> var win = null; function newWindow(mypage,myname,w,h,features) { var winl = (screen.width-w)/2; var wint = (screen.height-h)/2; if (winl < 0) winl = 0; if (wint < 0) wint = 0; var settings = 'height=' + h + ','; settings += 'width=' + w + ','; settings += 'top=' + wint + ','; settings += 'left=' + winl + ','; settings += features; win = window.open(mypage,myname,settings); win.window.focus(); } function refresh(pekerjaan) { document.location.href = "siswa_add_pekerjaan.php?pekerjaan="+pekerjaan+"&page=<?=$page?>&hal=<?=$hal?>&varbaris=<?=$varbaris?>"; } function refresh() { document.location.href = "siswa_add_pekerjaan.php"; } function tambah() { newWindow('<API key>.php', '<API key>','400','240','resizable=1,scrollbars=1,status=0,toolbar=0') } function del(replid) { if (confirm("Apakah anda yakin akan menghapus data pekerjaan ini?")) document.location.href = "siswa_add_pekerjaan.php?op=del&replid="+replid+"&page=<?=$page?>&hal=<?=$hal?>&varbaris=<?=$varbaris?>"; } function change_page(page) { var varbaris=document.getElementById("varbaris").value; document.location.href="siswa_add_pekerjaan.php?page="+page+"&hal="+page+"&varbaris="+varbaris; } function change_hal() { var hal = document.getElementById("hal").value; var varbaris=document.getElementById("varbaris").value; document.location.href="siswa_add_pekerjaan.php?page="+hal+"&hal="+hal+"&varbaris="+varbaris; } function change_baris() { var varbaris=document.getElementById("varbaris").value; document.location.href="siswa_add_pekerjaan.php?varbaris="+varbaris; } function tutup() { var pekerjaan_kiriman=document.getElementById('pekerjaan_kiriman').value; if (pekerjaan_kiriman.length==0){ opener.ref_del_pekerjaan(); window.close(); } else{ parent.opener.pekerjaan_kiriman(pekerjaan_kiriman); window.close(); } } locnm=location.href; pos=locnm.indexOf("indexb.htm"); locnm1=locnm.substring(0,pos); function ByeWin() { windowIMA=opener.ref_del_pekerjaan(); } </script> <title>JIBAS SIMAKA [Daftar Jenis Pekerjaaan]</title> </head> <body topmargin="0" leftmargin="0" marginheight="0" marginwidth="0" style="background-color:#dcdfc4" onUnload="ByeWin()"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr height="58"> <td width="28" background="../<?=GetThemeDir() ?>bgpop_01.jpg">&nbsp;</td> <td width="*" background="../<?=GetThemeDir() ?>bgpop_02a.jpg"> <div align="center" style="color:#FFFFFF; font-size:16px; font-weight:bold"> .: Jenis Pekerjaan :. </div> </td> <td width="28" background="../<?=GetThemeDir() ?>bgpop_03.jpg">&nbsp;</td> </tr> <tr height="150"> <td width="28" background="../<?=GetThemeDir() ?>bgpop_04a.jpg">&nbsp;</td> <td width="0" style="background-color:#FFFFFF" height="335" valign="top"> <!-- CONTENT GOES HERE <table border="0" width="100%" align="center"> <tr> <td align="center" valign="top" style="margin:0;padding:0;background-repeat:no-repeat"> <? OpenDb(); $sql_tot = "SELECT * FROM sklumum.jenispekerjaan"; $result_tot = QueryDb($sql_tot); $total = ceil(mysql_num_rows($result_tot)/(int)$varbaris); $jumlah = mysql_num_rows($result_tot); $sql = "SELECT replid,pekerjaan FROM sklumum.jenispekerjaan ORDER BY pekerjaan LIMIT ".(int)$page*(int)$varbaris.",$varbaris"; $akhir = ceil($jumlah/5)*5; $result = QueryDb($sql); if (@mysql_num_rows($result) > 0) { ?> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td align="right"><a href="#" onClick="refresh();"><img src="../images/ico/refresh.png" border="0" onMouseOver="showhint('Refresh!', this, event, '50px')">&nbsp;Refresh</a>&nbsp;&nbsp; <a href="#" onClick="JavaScript:tambah();"><img src="../images/ico/tambah.png" border="0" onMouseOver="showhint('Tambah!', this, event, '50px')">&nbsp;Tambah Jenis Pekerjaan</a></td> </tr> </table> </td> </tr> <tr> <td> <br /> <table class="tab" id="table" border="1" style="border-collapse:collapse" width="100%" align="left"> <tr class="header" align="center" height="30"> <td width="10%">No</td> <td width="*">Pekerjaan</td> <td width="15%">&nbsp;</td> </tr> <? if ($page==0) $cnt = 1; else $cnt = (int)$page*(int)$varbaris+1; while ($row = @mysql_fetch_array($result)) { $replid=$row['replid']; ?> <tr height="25"> <td align="center"><?=$cnt?></td> <td><?=$row['pekerjaan']?></td> <td align="center"> <a href="#" onClick="newWindow('<API key>.php?replid=<?=$replid?>', 'Ubahpekerjaan','400','240','resizable=1,scrollbars=1,status=0,toolbar=0')"><img src="../images/ico/ubah.png" border="0" onMouseOver="showhint('Ubah Jenis Pekerjaan!', this, event, '80px')"></a>&nbsp;<a href="#" onclick="del('<?=urlencode($replid)?>')"><img src="../images/ico/hapus.png" border="0" onMouseOver="showhint('Hapus Jenis Pekerjaan!', this, event, '85px')"></a> </td> </tr> <? $cnt++; } //while CloseDb(); ?> <script language='JavaScript'> Tables('table', 1, 0); </script> </table> <? if ($page==0){ $disback="style='visibility:hidden;'"; $disnext="style='visibility:visible;'"; } if ($page<$total && $page>0){ $disback="style='visibility:visible;'"; $disnext="style='visibility:visible;'"; } if ($page==$total-1 && $page>0){ $disback="style='visibility:visible;'"; $disnext="style='visibility:hidden;'"; } if ($page==$total-1 && $page==0){ $disback="style='visibility:hidden;'"; $disnext="style='visibility:hidden;'"; } ?> </td> </tr> <tr> <td> <table border="0"width="100%" align="center"cellpadding="0" cellspacing="0"> <tr> <td width="35%" align="left">Hal <select name="hal" id="hal" onChange="change_hal()"> <? for ($m=0; $m<$total; $m++) {?> <option value="<?=$m ?>" <?=IntIsSelected($hal,$m) ?>><?=$m+1 ?></option> <? } ?> </select> dari <?=$total?> hal <? // Navigasi halaman berikutnya dan sebelumnya ?> </td> <!--td align="center"> <input <?=$disback?> type="button" class="but" name="back" value=" << " onClick="change_page('<?=(int)$page-1?>')" onMouseOver="showhint('Sebelumnya', this, event, '75px')"> <? /*for($a=0;$a<$total;$a++){ if ($page==$a){ echo "<font face='verdana' color='red'><strong>".($a+1)."</strong></font> "; } else { echo "<a href='#' onClick=\"change_page('".$a."')\">".($a+1)."</a> "; } }*/ ?> <input <?=$disnext?> type="button" class="but" name="next" value=" >> " onClick="change_page('<?=(int)$page+1?>')" onMouseOver="showhint('Berikutnya', this, event, '75px')"> </td <td width="35%" align="right">Jml baris per hal <select name="varbaris" id="varbaris" onChange="change_baris()"> <? for ($m=5; $m <= $akhir; $m=$m+5) { ?> <option value="<?=$m ?>" <?=IntIsSelected($varbaris,$m) ?>><?=$m ?></option> <? } ?> </select></td> </tr> </table> <? } else { ?> <table width="100%" border="0" align="center"> <tr> <td colspan="3"><hr style="border-style:dotted" color="#000000"/> </td> </tr> <tr> <td align="center" valign="middle" height="200"> <font size = "2" color ="red"><b>Tidak ditemukan adanya data. <? if (SI_USER_LEVEL() != $SI_USER_STAFF) { ?> <br />Klik &nbsp;<a href="JavaScript:tambah()" ><font size = "2" color ="green">di sini</font></a>&nbsp;untuk mengisi data baru. <? } ?> </b></font> </td> </tr> </table> <? } ?> </td> </tr> <tr height="35"> <td colspan="3" align="center"> <input class="but" type="button" value="Tutup" onClick="tutup()"> <input type="hidden" name="pekerjaan_kiriman" id="pekerjaan_kiriman" value="<?=$pekerjaan_kiriman?>" /> </td> </tr> </table> </td> <td width="28" background="../<?=GetThemeDir() ?>bgpop_06a.jpg">&nbsp;</td> </tr> <tr height="28"> <td width="28" background="../<?=GetThemeDir() ?>bgpop_07.jpg">&nbsp;</td> <td width="*" background="../<?=GetThemeDir() ?>bgpop_08a.jpg">&nbsp;</td> <td width="28" background="../<?=GetThemeDir() ?>bgpop_09.jpg">&nbsp;</td> </tr> </table> </body> </html>
// C++ includes #include <iostream> #include <fstream> #include <stdio.h> #include <dirent.h> // ROOT includes #include <TROOT.h> #include <TFile.h> #include <TTree.h> #include <TChain.h> #include "Stop0LOptimization.hh" using namespace std; Main function that runs the analysis algorithm on the specified input files int main(int argc, char* argv[]) { Gets the list of input files and chains them into a single TChain char sigFileName[400]; char sigFolderName[400]; char bkgFolderName[400]; char outputFileName[400]; bool GOT_SIG = false; bool GOT_SIG_FILE = false; bool GOT_SIG_FOLD = false; bool GOT_BKG = false; bool GOT_OUT = false; int NJOB = 1; int iJOB = 0; if ( argc < 3 ){ cout << "Error at Input: please specify an signal file name/folder, a folder path for backgrounds"; cout << " and an output filename" << endl; cout << "Example: ./<API key>.x -sfile=signal.root -bfold=bkg_folder -ofile=output.root -Njob=1 -ijob=0" << endl; cout << "Example: ./<API key>.x -sfold=sig_folder -bfold=bkg_folder -ofile=output.root -Njob=1 -ijob=0" << endl; return 1; } for (int i=0;i<argc;i++){ if (strncmp(argv[i],"-sfile",6)==0){ sscanf(argv[i],"-sfile=%s", sigFileName); GOT_SIG_FILE = true; } if (strncmp(argv[i],"-sfold",6)==0){ sscanf(argv[i],"-sfold=%s", sigFolderName); GOT_SIG_FOLD = true; } if (strncmp(argv[i],"-bfold",6)==0){ sscanf(argv[i],"-bfold=%s", bkgFolderName); GOT_BKG = true; } if (strncmp(argv[i],"-ofile",6)==0){ sscanf(argv[i],"-ofile=%s", outputFileName); GOT_OUT = true; } if (strncmp(argv[i],"-Njob",5)==0) sscanf(argv[i],"-Njob=%d", &NJOB); if (strncmp(argv[i],"-ijob",5)==0) sscanf(argv[i],"-ijob=%d", &iJOB); } if((!GOT_SIG_FOLD && !GOT_SIG_FILE) || !GOT_BKG || !GOT_OUT) return 1; gROOT->ProcessLine("#include <vector>"); Stop0LOptimization Optimization; if(GOT_SIG_FILE){ std::cout << "Chaining signal tree from input file: " << sigFileName << std::endl; if(string(sigFileName).find("eos") != std::string::npos) Optimization.AddSignal("root:/"+string(sigFileName)); else Optimization.AddSignal(string(sigFileName)); } if(GOT_SIG_FOLD){ DIR *dpdf; struct dirent *epdf; dpdf = opendir(sigFolderName); if(dpdf == NULL){ cout << "ERROR: " << sigFolderName << " is not a directory" << endl; return 1; } string dname(sigFolderName); while ((epdf = readdir(dpdf))){ if(string(epdf->d_name).find(".root") == string::npos) continue; string name = dname+"/"+string(epdf->d_name); Optimization.AddSignal(name); std::cout << "chaining " << name << std::endl; } } if(GOT_BKG){ DIR *dpdf; struct dirent *epdf; dpdf = opendir(bkgFolderName); if(dpdf == NULL){ cout << "ERROR: " << bkgFolderName << " is not a directory" << endl; return 1; } string dname(bkgFolderName); while ((epdf = readdir(dpdf))){ if(string(epdf->d_name).find(".root") == string::npos) continue; string name = dname+"/"+string(epdf->d_name); Optimization.AddBackground(name); std::cout << "chaining " << name << std::endl; } } Optimization.Loop(NJOB,iJOB); Optimization.WriteOutputFile(string(outputFileName)); return 0; }
'use strict'; angular.module('obiba.mica.fileBrowser') .controller('<API key>', [ '$rootScope', '$scope', '$log', '$filter', 'StringUtils', 'FileBrowserService', '<API key>', 'AlertService', 'ServerErrorUtils', '<API key>', '<API key>', '<API key>', '<API key>', function ($rootScope, $scope, $log, $filter, StringUtils, FileBrowserService, <API key>, AlertService, ServerErrorUtils, <API key>, <API key>, <API key>, <API key>) { var navigateToPath = function (path) { clearSearchInternal(); getDocument(path); }; var navigateTo = function (event, document) { event.stopPropagation(); if (document) { navigateToPath(document.path); } }; var onError = function (response) { AlertService.alert({ id: '<API key>', type: 'danger', msg: ServerErrorUtils.buildMessage(response) }); if (response.status !== 403 && $scope.data.document) { navigateTo($scope.data.document); } }; function clearSearchInternal() { $scope.data.search.text = null; $scope.data.search.active = false; } function getDocument(path) { $scope.data.search.active = false; <API key>.get({path: path}, function onSuccess(response) { $log.info(response); $scope.pagination.selected = -1; $scope.data.document = $scope.data.details.document = response; if (!$scope.data.document.children) { $scope.data.document.children = []; } if ($scope.data.document.path === $scope.data.rootPath) { $scope.data.document.children = $scope.data.document.children.filter(function(child){ return <API key>.folders.excludes.indexOf(child.name) < 0; }); $scope.data.document.size = $scope.data.document.children.length; } $scope.data.breadcrumbs = <API key>.toArray(path, $scope.data.rootPath); $scope.data.isFile = FileBrowserService.isFile(response); $scope.data.isRoot = FileBrowserService.isRoot(response); }, onError ); } function navigateToParent(event, document) { event.stopPropagation(); var path = document.path; if (path.lastIndexOf('/') === 0) { path = '/'; } else { path = path.substring(0, path.lastIndexOf('/')); } navigateToPath(path); } function navigateBack() { if (!$scope.data.isRoot && $scope.data.document) { var parentPath = $scope.data.document.path.replace(/\\/g, '/').replace(/\/[^\/]*$/, ''); getDocument(parentPath ? parentPath : '/'); } } function hideDetails() { $scope.pagination.selected = -1; $scope.data.details.show = false; } function <API key>(path, searchParams) { function excludeFolders(query) { var excludeQuery = ''; try { var excludes = []; <API key>.folders.excludes.forEach(function (exclude) { var q = path.replace(/\//g, '\\/') + '\\/' + exclude.replace(/\s/, '\\ '); excludes.push(q);
// <auto-generated> // This code was generated by a tool. // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> namespace Machete.Web.Resources { using System; <summary> A strongly-typed resource class, for looking up localized strings, etc. </summary> // This class was auto-generated by the <API key> // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.<API key>("System.Resources.Tools.<API key>", "4.0.0.0")] [global::System.Diagnostics.<API key>()] [global::System.Runtime.CompilerServices.<API key>()] public class ValidationStrings { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.<API key>("Microsoft.Performance", "CA1811:<API key>")] internal ValidationStrings() { } <summary> Returns the cached ResourceManager instance used by this class. </summary> [global::System.ComponentModel.<API key>(global::System.ComponentModel.<API key>.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Machete.Web.Resources.ValidationStrings", typeof(ValidationStrings).Assembly); resourceMan = temp; } return resourceMan; } } <summary> Overrides the current thread's CurrentUICulture property for all resource lookups using this strongly typed resource class. </summary> [global::System.ComponentModel.<API key>(global::System.ComponentModel.<API key>.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } <summary> Looks up a localized string similar to Account Creation. </summary> public static string accountCreation { get { return ResourceManager.GetString("accountCreation", resourceCulture); } } <summary> Looks up a localized string similar to Account Information. </summary> public static string AccountInfoLegend { get { return ResourceManager.GetString("AccountInfoLegend", resourceCulture); } } <summary> Looks up a localized string similar to Change Password. </summary> public static string Change { get { return ResourceManager.GetString("Change", resourceCulture); } } <summary> Looks up a localized string similar to Use the form below to change your password.. </summary> public static string ChangeSubTitle { get { return ResourceManager.GetString("ChangeSubTitle", resourceCulture); } } <summary> Looks up a localized string similar to Your password has been changed successfully.. </summary> public static string ChangeSuccess { get { return ResourceManager.GetString("ChangeSuccess", resourceCulture); } } <summary> Looks up a localized string similar to Change Password. </summary> public static string ChangeTitle { get { return ResourceManager.GetString("ChangeTitle", resourceCulture); } } <summary> Looks up a localized string similar to Password change was unsuccessful. Please correct the errors and try again.. </summary> public static string ChangeValSummary { get { return ResourceManager.GetString("ChangeValSummary", resourceCulture); } } <summary> Looks up a localized string similar to Create. </summary> public static string create { get { return ResourceManager.GetString("create", resourceCulture); } } <summary> Looks up a localized string similar to Email Address. </summary> public static string EmailAddress { get { return ResourceManager.GetString("EmailAddress", resourceCulture); } } <summary> Looks up a localized string similar to The email format is invalid. </summary> public static string emailValidation { get { return ResourceManager.GetString("emailValidation", resourceCulture); } } <summary> Looks up a localized string to duplicate email error on Create. </summary> public static string dupeEmail { get { return ResourceManager.GetString("dupeEmail", resourceCulture); } } <summary> Looks up a localized string similar to First Name. </summary> public static string firstname { get { return ResourceManager.GetString("firstname", resourceCulture); } } <summary> Looks up a localized string similar to if you already have created an account.. </summary> public static string haveAccount { get { return ResourceManager.GetString("haveAccount", resourceCulture); } } <summary> Looks up a localized string similar to Invalid username or password.. </summary> public static string invalidLogin { get { return ResourceManager.GetString("invalidLogin", resourceCulture); } } <summary> Looks up a localized string similar to Last Name. </summary> public static string lastname { get { return ResourceManager.GetString("lastname", resourceCulture); } } <summary> Looks up a localized string similar to Logoff. </summary> public static string LogOff { get { return ResourceManager.GetString("LogOff", resourceCulture); } } <summary> Looks up a localized string similar to Logon. </summary> public static string LogOn { get { return ResourceManager.GetString("LogOn", resourceCulture); } } <summary> Looks up a localized string similar to Please enter your username and password.. </summary> public static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to if you don&apos;t have an account.. </summary> public static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Log on Machete. </summary> public static string LogOnTitle { get { return ResourceManager.GetString("LogOnTitle", resourceCulture); } } <summary> Looks up a localized string similar to Login was unsuccessful. Please correct the errors and try again.. </summary> public static string LogOnUnsuccessful { get { return ResourceManager.GetString("LogOnUnsuccessful", resourceCulture); } } <summary> Looks up a localized string similar to The new password and confirmation password do not match.. </summary> public static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Password. </summary> public static string password { get { return ResourceManager.GetString("password", resourceCulture); } } <summary> Looks up a localized string similar to The new password and confirmation password do not match.. </summary> public static string PasswordCompare { get { return ResourceManager.GetString("PasswordCompare", resourceCulture); } } <summary> Looks up a localized string similar to Confirm New Password. </summary> public static string PasswordConfirm { get { return ResourceManager.GetString("PasswordConfirm", resourceCulture); } } <summary> Looks up a localized string similar to Current Password. </summary> public static string PasswordCurrent { get { return ResourceManager.GetString("PasswordCurrent", resourceCulture); } } <summary> Looks up a localized string similar to The Password must be at least 8 characters long.. </summary> public static string passwordLengthMin { get { return ResourceManager.GetString("passwordLengthMin", resourceCulture); } } <summary> Looks up a localized string similar to New Password. </summary> public static string PasswordNew { get { return ResourceManager.GetString("PasswordNew", resourceCulture); } } <summary> Looks up a localized string similar to Register. </summary> public static string Register { get { return ResourceManager.GetString("Register", resourceCulture); } } <summary> Looks up a localized string similar to NameHasSpace. </summary> public static string NameHasSpace { get { return ResourceManager.GetString("NameHasSpace", resourceCulture); } } <summary> Looks up a localized string similar to Use the form below to create a new account.. </summary> public static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Account Information. </summary> public static string RegisterLegend { get { return ResourceManager.GetString("RegisterLegend", resourceCulture); } } <summary> Looks up a localized string similar to Passwords are required to be a minimum of. </summary> public static string RegisterPassLength1 { get { return ResourceManager.GetString("RegisterPassLength1", resourceCulture); } } <summary> Looks up a localized string similar to characters in length.. </summary> public static string RegisterPassLength2 { get { return ResourceManager.GetString("RegisterPassLength2", resourceCulture); } } <summary> Looks up a localized string similar to Create a New Account. </summary> public static string RegisterSubTitle { get { return ResourceManager.GetString("RegisterSubTitle", resourceCulture); } } <summary> Looks up a localized string similar to Register. </summary> public static string RegisterTitle { get { return ResourceManager.GetString("RegisterTitle", resourceCulture); } } <summary> Looks up a localized string similar to Account creation was unsuccessful. Please correct the errors and try again.. </summary> public static string RegisterValSummary { get { return ResourceManager.GetString("RegisterValSummary", resourceCulture); } } <summary> Looks up a localized string similar to Remember Me?. </summary> public static string rememberme { get { return ResourceManager.GetString("rememberme", resourceCulture); } } <summary> Looks up a localized string similar to field &quot;{0}&quot; is required. </summary> public static string Required { get { return ResourceManager.GetString("Required", resourceCulture); } } <summary> Looks up a localized string similar to Settings. </summary> public static string Settings { get { return ResourceManager.GetString("Settings", resourceCulture); } } <summary> Looks up a localized string similar to Sign In. </summary> public static string signIn { get { return ResourceManager.GetString("signIn", resourceCulture); } } <summary> Looks up a localized string similar to Sign Up. </summary> public static string signup { get { return ResourceManager.GetString("signup", resourceCulture); } } <summary> Looks up a localized string similar to The {0} must be no more than {1} characters.. </summary> public static string stringLengthMax { get { return ResourceManager.GetString("stringLengthMax", resourceCulture); } } <summary> Looks up a localized string similar to Username. </summary> public static string username { get { return ResourceManager.GetString("username", resourceCulture); } } <summary> Looks up a localized string similar to Welcome. </summary> public static string Welcome { get { return ResourceManager.GetString("Welcome", resourceCulture); } } } }
// $Id: JoinTable.java,v 1.2 2015/05/12 21:01:41 ataides Exp $ package javax.persistence; import java.lang.annotation.Target; import java.lang.annotation.Retention; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Used in the mapping of associations. It is specified on the * owning side of an association. * * <p> A join table is typically used in the mapping of many-to-many * and unidirectional one-to-many associations. It may also be used to * map bidirectional many-to-one/one-to-many associations, * unidirectional many-to-one relationships, and one-to-one * associations (both bidirectional and unidirectional). * *<p>When a join table is used in mapping a relationship with an *embeddable class on the owning side of the relationship, the *containing entity rather than the embeddable class is considered the *owner of the relationship. * * <p> If the <code>JoinTable</code> annotation is missing, the * default values of the annotation elements apply. * The name of the join table is assumed to be the table names of the * associated primary tables concatenated together (owning side * first) using an underscore. * * <pre> * * Example: * * &#064;JoinTable( * name="CUST_PHONE", * joinColumns= * &#064;JoinColumn(name="CUST_ID", <API key>="ID"), * inverseJoinColumns= * &#064;JoinColumn(name="PHONE_ID", <API key>="ID") * ) * </pre> * * @see JoinColumn * @see JoinColumns * * @since Java Persistence 1.0 */ @Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface JoinTable { /** * (Optional) The name of the join table. * * <p> Defaults to the concatenated names of * the two associated primary entity tables, * separated by an underscore. */ String name() default ""; /** (Optional) The catalog of the table. * <p> Defaults to the default catalog. */ String catalog() default ""; /** (Optional) The schema of the table. * <p> Defaults to the default schema for user. */ String schema() default ""; /** * (Optional) The foreign key columns * of the join table which reference the * primary table of the entity owning the * association. (I.e. the owning side of * the association). * * <p> Uses the same defaults as for {@link JoinColumn}. */ JoinColumn[] joinColumns() default {}; /** * (Optional) The foreign key columns * of the join table which reference the * primary table of the entity that does * not own the association. (I.e. the * inverse side of the association). * * <p> Uses the same defaults as for {@link JoinColumn}. */ JoinColumn[] inverseJoinColumns() default {}; /** * (Optional) Unique constraints that are * to be placed on the table. These are * only used if table generation is in effect. * <p> Defaults to no additional constraints. */ UniqueConstraint[] uniqueConstraints() default {}; }
#pragma region Copyright (c) 2014-2017 OpenRCT2 Developers #pragma endregion #include <openrct2/common.h> #include <SDL.h> #include <openrct2/core/Console.hpp> #include <openrct2/core/File.h> #include <openrct2/core/FileStream.hpp> #include <openrct2/core/Path.hpp> #include <openrct2/core/String.hpp> #include <openrct2/PlatformEnvironment.h> #include "KeyboardShortcuts.h" #include <openrct2/localisation/Localisation.h> using namespace OpenRCT2; using namespace OpenRCT2::Input; // Remove when the C calls are removed static KeyboardShortcuts * _instance; KeyboardShortcuts::KeyboardShortcuts(<API key> * env) : _env(env) { _instance = this; } void KeyboardShortcuts::Reset() { for (size_t i = 0; i < SHORTCUT_COUNT; i++) { _keys[i] = DefaultKeys[i]; } } bool KeyboardShortcuts::Load() { bool result = false; Reset(); try { std::string path = _env->GetFilePath(PATHID::CONFIG_KEYBOARD); if (File::Exists(path)) { auto fs = FileStream(path, FILE_MODE_OPEN); uint16 version = fs.ReadValue<uint16>(); if (version == KeyboardShortcuts::<API key>) { sint32 numShortcutsInFile = (fs.GetLength() - sizeof(uint16)) / sizeof(uint16); sint32 numShortcutsToRead = std::min<sint32>(SHORTCUT_COUNT, numShortcutsInFile); for (sint32 i = 0; i < numShortcutsToRead; i++) { _keys[i] = fs.ReadValue<uint16>(); } result = true; } } } catch (const std::exception &ex) { Console::WriteLine("Error reading shortcut keys: %s", ex.what()); } return result; } bool KeyboardShortcuts::Save() { bool result = false; try { std::string path = _env->GetFilePath(PATHID::CONFIG_KEYBOARD); auto fs = FileStream(path, FILE_MODE_WRITE); fs.WriteValue<uint16>(KeyboardShortcuts::<API key>); for (sint32 i = 0; i < SHORTCUT_COUNT; i++) { fs.WriteValue<uint16>(_keys[i]); } result = true; } catch (const std::exception &ex) { Console::WriteLine("Error writing shortcut keys: %s", ex.what()); } return result; } void KeyboardShortcuts::Set(sint32 key) { // Unmap shortcut that already uses this key sint32 shortcut = GetFromKey(key); if (shortcut != SHORTCUT_UNDEFINED) { _keys[shortcut] = SHORTCUT_UNDEFINED; } // Map shortcut to this key _keys[<API key>] = key; Save(); } sint32 KeyboardShortcuts::GetFromKey(sint32 key) { for (sint32 i = 0; i < SHORTCUT_COUNT; i++) { if (key == _keys[i]) { return i; } } return SHORTCUT_UNDEFINED; } std::string KeyboardShortcuts::GetShortcutString(sint32 shortcut) const { utf8 buffer[256] = { 0 }; utf8 formatBuffer[256] = { 0 }; uint16 shortcutKey = _keys[shortcut]; if (shortcutKey == SHORTCUT_UNDEFINED) return std::string(); if (shortcutKey & SHIFT) { format_string(formatBuffer, sizeof(formatBuffer), STR_SHIFT_PLUS, nullptr); String::Append(buffer, sizeof(buffer), formatBuffer); } if (shortcutKey & CTRL) { format_string(formatBuffer, sizeof(formatBuffer), STR_CTRL_PLUS, nullptr); String::Append(buffer, sizeof(buffer), formatBuffer); } if (shortcutKey & ALT) { #ifdef __MACOSX__ format_string(formatBuffer, sizeof(formatBuffer), STR_OPTION_PLUS, nullptr); #else format_string(formatBuffer, sizeof(formatBuffer), STR_ALT_PLUS, nullptr); #endif String::Append(buffer, sizeof(buffer), formatBuffer); } if (shortcutKey & CMD) { format_string(formatBuffer, sizeof(formatBuffer), STR_CMD_PLUS, nullptr); String::Append(buffer, sizeof(buffer), formatBuffer); } String::Append(buffer, sizeof(buffer), SDL_GetScancodeName((SDL_Scancode)(shortcutKey & 0xFF))); return std::string(buffer); } void KeyboardShortcuts::<API key>(const uint8 * keysState, sint32 * x, sint32 * y) const { for (sint32 shortcutId = <API key>; shortcutId <= <API key>; shortcutId++) { uint16 shortcutKey = _keys[shortcutId]; uint8 scancode = shortcutKey & 0xFF; if (shortcutKey == 0xFFFF) continue; if (!keysState[scancode]) continue; if (shortcutKey & SHIFT) { if (!keysState[SDL_SCANCODE_LSHIFT] && !keysState[SDL_SCANCODE_RSHIFT]) continue; } if (shortcutKey & CTRL) { if (!keysState[SDL_SCANCODE_LCTRL] && !keysState[SDL_SCANCODE_RCTRL]) continue; } if (shortcutKey & ALT) { if (!keysState[SDL_SCANCODE_LALT] && !keysState[SDL_SCANCODE_RALT]) continue; } #ifdef __MACOSX__ if (shortcutKey & CMD) { if (!keysState[SDL_SCANCODE_LGUI] && !keysState[SDL_SCANCODE_RGUI]) continue; } #endif switch (shortcutId) { case <API key>: *y = -1; break; case <API key>: *x = -1; break; case <API key>: *y = 1; break; case <API key>: *x = 1; break; default: break; } } } void <API key>() { _instance->Reset(); } bool <API key>() { return _instance->Load(); } bool <API key>() { return _instance->Save(); } void <API key>(sint32 key) { return _instance->Set(key); } sint32 <API key>(sint32 key) { return _instance->GetFromKey(key); } void <API key>(char * buffer, size_t bufferSize, sint32 shortcut) { auto str = _instance->GetShortcutString(shortcut); String::Set(buffer, bufferSize, str.c_str()); } void <API key>(const uint8 * keysState, sint32 * x, sint32 * y) { _instance-><API key>(keysState, x, y); } // Default keyboard shortcuts const uint16 KeyboardShortcuts::DefaultKeys[SHORTCUT_COUNT] = { <API key>, // <API key> SHIFT | <API key>, // <API key> SDL_SCANCODE_ESCAPE, // <API key> SDL_SCANCODE_PAUSE, // SHORTCUT_PAUSE_GAME SDL_SCANCODE_PAGEUP, // <API key> <API key>, // <API key> SDL_SCANCODE_RETURN, // <API key> SHIFT | SDL_SCANCODE_RETURN, // <API key> SDL_SCANCODE_Z, // <API key> SDL_SCANCODE_1, // <API key> SDL_SCANCODE_H, // <API key> SDL_SCANCODE_V, // <API key> SDL_SCANCODE_3, // <API key> SDL_SCANCODE_4, // <API key> SDL_SCANCODE_5, // <API key> SDL_SCANCODE_6, // <API key> SDL_SCANCODE_8, // <API key> SDL_SCANCODE_9, // <API key> SDL_SCANCODE_0, // <API key> SDL_SCANCODE_F1, // <API key> SDL_SCANCODE_F2, // <API key> SDL_SCANCODE_F3, // <API key> SDL_SCANCODE_F4, // <API key> SDL_SCANCODE_F5, // <API key> SDL_SCANCODE_F, // <API key> SDL_SCANCODE_D, // <API key> SDL_SCANCODE_R, // <API key> SDL_SCANCODE_P, // <API key> SDL_SCANCODE_G, // <API key> SDL_SCANCODE_S, // <API key> SDL_SCANCODE_M, // <API key> SDL_SCANCODE_TAB, // SHORTCUT_SHOW_MAP PLATFORM_MODIFIER | SDL_SCANCODE_S, // SHORTCUT_SCREENSHOT SDL_SCANCODE_MINUS, // <API key>, SDL_SCANCODE_EQUALS, // <API key>, PLATFORM_MODIFIER | ALT | SDL_SCANCODE_C, // <API key>, SDL_SCANCODE_T, // <API key>, SDL_SCANCODE_UP, // <API key> SDL_SCANCODE_LEFT, // <API key> SDL_SCANCODE_DOWN, // <API key> SDL_SCANCODE_RIGHT, // <API key> SDL_SCANCODE_C, // <API key> PLATFORM_MODIFIER | SDL_SCANCODE_F10, // <API key> SHORTCUT_UNDEFINED, // <API key> SHORTCUT_UNDEFINED, // SHORTCUT_MUTE_SOUND ALT | SDL_SCANCODE_RETURN, // <API key> SHORTCUT_UNDEFINED, // <API key> SHORTCUT_UNDEFINED, // <API key> SHORTCUT_UNDEFINED, // <API key> SHORTCUT_UNDEFINED, // <API key> SDL_SCANCODE_KP_4, // <API key> SDL_SCANCODE_KP_6, // <API key> SDL_SCANCODE_KP_5, // <API key> SDL_SCANCODE_KP_2, // <API key> SDL_SCANCODE_KP_8, // <API key> <API key>, // <API key> SDL_SCANCODE_KP_1, // <API key> SDL_SCANCODE_KP_3, // <API key> SDL_SCANCODE_KP_7, // <API key> SDL_SCANCODE_KP_9, // <API key> SDL_SCANCODE_KP_0, // <API key> <API key>, // <API key> PLATFORM_MODIFIER | SDL_SCANCODE_L, // SHORTCUT_LOAD_GAME SDL_SCANCODE_B, // <API key> SDL_SCANCODE_7, // <API key> };
<html> <body> <h3> O seu login foi feito com sucesso. O seu id é: <?php echo $this->dx_auth->get_user_id();?> e o seu username é <?php echo $this->dx_auth->get_username();?></h3> <h4> Para fazer logout click <a href="logout"> aqui </a>. </h4> </body> </html>
#!/bin/bash # Script to make back-up copies of files in current directory TIME=`date +"%F"` CURDIR=`pwd` ORIGFILES=`ls` UNWANTED="bak" BACKUPFILE="backup-$TIME.tar.bz2" DESDIR="/home/victoria/bakk" # The directory path you enter here should already exist echo "Getting ready to back up $CURDIR" for f in $ORIGFILES do case "$f" in *.bak ) echo "Already bakked - what now?" ; exit 0 ;; * ) cp $f $f.bak ;; esac done echo "Zipping up the files"
package is.idega.idegaweb.golf.tournament.presentation; import is.idega.idegaweb.golf.entity.Tournament; import is.idega.idegaweb.golf.presentation.GolfBlock; import is.idega.idegaweb.golf.tournament.business.TournamentSession; import java.io.IOException; import java.math.BigDecimal; import com.idega.business.IBOLookup; import com.idega.business.IBOLookupException; import com.idega.business.IBORuntimeException; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWResourceBundle; import com.idega.presentation.IWContext; import com.idega.presentation.Image; import com.idega.presentation.Table; import com.idega.presentation.text.Link; import com.idega.presentation.text.Text; /** * @author gimmi */ public class <API key> extends GolfBlock { public void main(IWContext modinfo) throws Exception { IWResourceBundle iwrb = getResourceBundle(); IWBundle bundle = getBundle(); String tournament_id; String action = modinfo.getParameter("action"); if (action == null) { action = ""; } if (<API key>(modinfo).getTournamentID() != -1) { Tournament tournament = <API key>(modinfo).getTournament(); boolean ongoing = tournament.isTournamentOngoing(); boolean finished = tournament.<API key>(); Table myTable = new Table(1, 2); myTable.setWidth("100%"); myTable.setCellpadding(0); myTable.setCellspacing(0); myTable.setAlignment(1, 1, "right"); myTable.<API key>(1, 1, "bottom"); myTable.<API key>(1, 2, "top"); Text header = new TournamentName(); header.addBreak(); header.setFontSize(3); header.setBold(); add(header); Image participantsImage = iwrb.getImage("tabs/participants1.gif"); Image startingtimeImage = iwrb.getImage("tabs/teetimes1.gif"); Image informationImage = iwrb.getImage("tabs/information1.gif"); Image iOngoing = iwrb.getImage("tabs/scoreoverview1.gif"); Image iFinished = iwrb.getImage("tabs/results1.gif"); if ((action.equalsIgnoreCase("")) || (action.equals("information"))) { action = "information"; informationImage = iwrb.getImage("tabs/information.gif"); } else if (action.equals("member_list")) { participantsImage = iwrb.getImage("tabs/participants.gif"); } else if (action.equalsIgnoreCase("startingtime")) { startingtimeImage = iwrb.getImage("tabs/teetimes.gif"); } else if (action.equals("viewCurrentScore")) { iOngoing = iwrb.getImage("tabs/scoreoverview.gif"); } else if (action.equals("viewFinalScore")) { iFinished = iwrb.getImage("tabs/results.gif"); } Link infoLink = new Link(informationImage); infoLink.addParameter("action", "information"); myTable.add(infoLink, 1, 1); Link link2 = new Link(participantsImage); link2.addParameter("action", "member_list"); myTable.add(link2, 1, 1); Link link = new Link(startingtimeImage); link.addParameter("action", "startingtime"); myTable.add(link, 1, 1); Link ongoingLink = new Link(iOngoing); ongoingLink.addParameter("action", "viewCurrentScore"); if (finished) { ongoingLink = new Link(iFinished); ongoingLink.addParameter("action", "viewFinalScore"); } myTable.add(ongoingLink, 1, 1); Table table2 = new Table(); table2.setCellpadding(0); table2.setCellspacing(0); table2.setWidth("100%"); //table2.setHeight("100%"); if (action.equals("member_list")) { table2.add(new <API key>()); } else if (action.equalsIgnoreCase("startingtime")) { String tournament_round = modinfo.getParameter("tournament_round"); <API key> form = <API key>(modinfo).<API key>(tournament, tournament_round, true, false); table2.add(form); table2.setAlignment(1, 1, "center"); } else if (action.equals("information")) { table2.add(new TournamentInfo()); } else if (action.equals("viewCurrentScore")) { table2.setAlignment(1, 1, "left"); try { String gender = modinfo.getParameter("gender"); String t_g_id = modinfo.getParameter("tournament_group_id"); String t_r_id = modinfo.getParameter("tournament_round_id"); String sort = modinfo.getParameter("sort"); String order = modinfo.getParameter("order"); ResultsViewer result = new ResultsViewer(); result.setCacheable("ResView1_"+action+"_"+<API key>(modinfo).getTournamentID()+"_"+gender+"_"+t_g_id+"_"+t_r_id+"_"+sort+"_"+order,1800000); table2.add(result, 1, 1); } catch (Exception e) { e.printStackTrace(System.err); } } else if (action.equals("viewFinalScore")) { table2.setAlignment(1, 1, "left"); try { String gender = modinfo.getParameter("gender"); String t_g_id = modinfo.getParameter("tournament_group_id"); String t_r_id = modinfo.getParameter("tournament_round_id"); String sort = modinfo.getParameter("sort"); String order = modinfo.getParameter("order"); ResultsViewer result = new ResultsViewer(); result.setCacheable("ResView_" + action + "_" + <API key>(modinfo).getTournamentID() + "_" + gender + "_" + t_g_id + "_" + t_r_id + "_" + sort + "_" + order, 1800000); table2.add(result, 1, 1); } catch (Exception e) { e.printStackTrace(System.err); } } myTable.add(table2, 1, 2); add(myTable); } else { add(iwrb.getLocalizedString("tournament.<API key>", "No tournament selected")); } } public String scale_decimals(String nyForgjof, int scale) throws IOException { BigDecimal test2 = new BigDecimal(nyForgjof); String nyForgjof2 = test2.setScale(scale, 5).toString(); return nyForgjof2; } private TournamentSession <API key>(IWContext iwc) { try { return (TournamentSession) IBOLookup.getSessionInstance(iwc, TournamentSession.class); } catch (IBOLookupException ile) { throw new IBORuntimeException(ile); } } }
#ifndef __MPFR_H #define __MPFR_H /* Define MPFR version number */ #define MPFR_VERSION_MAJOR 3 #define MPFR_VERSION_MINOR 1 #define <API key> 0 #define MPFR_VERSION_STRING "3.1.0-p4" /* Macros dealing with MPFR VERSION */ #define MPFR_VERSION_NUM(a,b,c) (((a) << 16L) | ((b) << 8) | (c)) #define MPFR_VERSION \ MPFR_VERSION_NUM(MPFR_VERSION_MAJOR,MPFR_VERSION_MINOR,<API key>) /* Check if GMP is included, and try to include it (Works with local GMP) */ #ifndef __GMP_H__ # include <gmp.h> #endif /* Avoid some problems with macro expansion if the user defines macros with the same name as keywords. By convention, identifiers and macro names starting with mpfr_ are reserved by MPFR. */ typedef void mpfr_void; typedef int mpfr_int; typedef unsigned int mpfr_uint; typedef long mpfr_long; typedef unsigned long mpfr_ulong; typedef size_t mpfr_size_t; /* Definition of rounding modes (DON'T USE MPFR_RNDNA!). Warning! Changing the contents of this enum should be seen as an interface change since the old and the new types are not compatible (the integer type compatible with the enumerated type can even change, see ISO C99, 6.7.2.2#4), and in Makefile.am, AGE should be set to 0. MPFR_RNDU must appear just before MPFR_RNDD (see <API key> in mpfr-impl.h). MPFR_RNDF has been added, though not implemented yet, in order to avoid to break the ABI once faithful rounding gets implemented. If you change the order of the rounding modes, please update the routines in texceptions.c which assume 0=RNDN, 1=RNDZ, 2=RNDU, 3=RNDD, 4=RNDA. */ typedef enum { MPFR_RNDN=0, /* round to nearest, with ties to even */ MPFR_RNDZ, /* round toward zero */ MPFR_RNDU, /* round toward +Inf */ MPFR_RNDD, /* round toward -Inf */ MPFR_RNDA, /* round away from zero */ MPFR_RNDF, /* faithful rounding (not implemented yet) */ MPFR_RNDNA=-1 /* round to nearest, with ties away from zero (mpfr_round) */ } mpfr_rnd_t; /* kept for compatibility with MPFR 2.4.x and before */ #define GMP_RNDN MPFR_RNDN #define GMP_RNDZ MPFR_RNDZ #define GMP_RNDU MPFR_RNDU #define GMP_RNDD MPFR_RNDD /* Note: With the following default choices for _MPFR_PREC_FORMAT and _MPFR_EXP_FORMAT, mpfr_exp_t will be the same as [mp_exp_t] (at least up to GMP 5). */ /* Define precision: 1 (short), 2 (int) or 3 (long) (DON'T USE IT!) */ #ifndef _MPFR_PREC_FORMAT # if __GMP_MP_SIZE_T_INT == 1 # define _MPFR_PREC_FORMAT 2 # else # define _MPFR_PREC_FORMAT 3 # endif #endif /* Define exponent: 1 (short), 2 (int), 3 (long) or 4 (intmax_t) (DON'T USE IT!) */ #ifndef _MPFR_EXP_FORMAT # define _MPFR_EXP_FORMAT _MPFR_PREC_FORMAT #endif #if _MPFR_PREC_FORMAT > _MPFR_EXP_FORMAT # error "mpfr_prec_t must not be larger than mpfr_exp_t" #endif /* Let's make mpfr_prec_t signed in order to avoid problems due to the usual arithmetic conversions when mixing mpfr_prec_t and mpfr_exp_t in an expression (for error analysis) if casts are forgotten. */ #if _MPFR_PREC_FORMAT == 1 typedef short mpfr_prec_t; typedef unsigned short mpfr_uprec_t; #elif _MPFR_PREC_FORMAT == 2 typedef int mpfr_prec_t; typedef unsigned int mpfr_uprec_t; #elif _MPFR_PREC_FORMAT == 3 typedef long mpfr_prec_t; typedef unsigned long mpfr_uprec_t; #else # error "Invalid MPFR Prec format" #endif /* Definition of precision limits without needing <limits.h> */ /* Note: the casts allows the expression to yield the wanted behavior for _MPFR_PREC_FORMAT == 1 (due to integer promotion rules). */ #define MPFR_PREC_MIN 2 #define MPFR_PREC_MAX ((mpfr_prec_t)((mpfr_uprec_t)(~(mpfr_uprec_t)0)>>1)) /* Definition of sign */ typedef int mpfr_sign_t; /* Definition of the exponent. _MPFR_EXP_FORMAT must be large enough so that mpfr_exp_t has at least 32 bits. */ #if _MPFR_EXP_FORMAT == 1 typedef short mpfr_exp_t; typedef unsigned short mpfr_uexp_t; #elif _MPFR_EXP_FORMAT == 2 typedef int mpfr_exp_t; typedef unsigned int mpfr_uexp_t; #elif _MPFR_EXP_FORMAT == 3 typedef long mpfr_exp_t; typedef unsigned long mpfr_uexp_t; #elif _MPFR_EXP_FORMAT == 4 /* Note: in this case, intmax_t and uintmax_t must be defined before the inclusion of mpfr.h (we do not include <stdint.h> here because of some non-ISO C99 implementations that support these types). */ typedef intmax_t mpfr_exp_t; typedef uintmax_t mpfr_uexp_t; #else # error "Invalid MPFR Exp format" #endif /* Definition of the standard exponent limits */ #define MPFR_EMAX_DEFAULT ((mpfr_exp_t) (((mpfr_ulong) 1 << 30) - 1)) #define MPFR_EMIN_DEFAULT (-(MPFR_EMAX_DEFAULT)) /* DON'T USE THIS! (For MPFR-public macros only, see below.) The mpfr_sgn macro uses the fact that __MPFR_EXP_NAN and __MPFR_EXP_ZERO are the smallest values. */ #define __MPFR_EXP_MAX ((mpfr_exp_t) (((mpfr_uexp_t) -1) >> 1)) #define __MPFR_EXP_NAN (1 - __MPFR_EXP_MAX) #define __MPFR_EXP_ZERO (0 - __MPFR_EXP_MAX) #define __MPFR_EXP_INF (2 - __MPFR_EXP_MAX) /* Definition of the main structure */ typedef struct { mpfr_prec_t _mpfr_prec; mpfr_sign_t _mpfr_sign; mpfr_exp_t _mpfr_exp; mp_limb_t *_mpfr_d; } __mpfr_struct; /* Compatibility with previous types of MPFR */ #ifndef mp_rnd_t # define mp_rnd_t mpfr_rnd_t #endif #ifndef mp_prec_t # define mp_prec_t mpfr_prec_t #endif /* The represented number is _sign*(_d[k-1]/B+_d[k-2]/B^2+...+_d[0]/B^k)*2^_exp where k=ceil(_mp_prec/GMP_NUMB_BITS) and B=2^GMP_NUMB_BITS. For the msb (most significant bit) normalized representation, we must have _d[k-1]>=B/2, unless the number is singular. We must also have the last k*GMP_NUMB_BITS-_prec bits set to zero. */ typedef __mpfr_struct mpfr_t[1]; typedef __mpfr_struct *mpfr_ptr; typedef __gmp_const __mpfr_struct *mpfr_srcptr; /* For those who need a direct and fast access to the sign field. However it is not in the API, thus use it at your own risk: it might not be supported, or change name, in further versions! Unfortunately, it must be defined here (instead of MPFR's internal header file mpfr-impl.h) because it is used by some macros below. */ #define MPFR_SIGN(x) ((x)->_mpfr_sign) /* Stack interface */ typedef enum { MPFR_NAN_KIND = 0, MPFR_INF_KIND = 1, MPFR_ZERO_KIND = 2, MPFR_REGULAR_KIND = 3 } mpfr_kind_t; /* GMP defines: + size_t: Standard size_t + <API key> Attribute for math functions. + __GMP_NOTHROW For C++: can't throw . + __GMP_EXTERN_INLINE Attribute for inline function. * __gmp_const const (Supports for K&R compiler only for mpfr.h). + <API key> compiling to go into a DLL + <API key> compiling to go into a application */ /* Extra MPFR defines */ #define <API key> #if defined (__GNUC__) # if __GNUC__ >= 4 # undef <API key> # define <API key> __attribute__ ((sentinel)) # endif #endif /* Prototypes: Support of K&R compiler */ #if defined (__GMP_PROTO) # define _MPFR_PROTO __GMP_PROTO #elif defined (__STDC__) || defined (__cplusplus) # define _MPFR_PROTO(x) x #else # define _MPFR_PROTO(x) () #endif /* Support for WINDOWS Dll: Check if we are inside a MPFR build, and if so export the functions. Otherwise does the same thing as GMP */ #if defined(__MPFR_WITHIN_MPFR) && __GMP_LIBGMP_DLL # define __MPFR_DECLSPEC <API key> #else # define __MPFR_DECLSPEC __GMP_DECLSPEC #endif /* Use MPFR_DEPRECATED to mark MPFR functions, types or variables as deprecated. Code inspired by Apache Subversion's svn_types.h file. */ #if defined(__GNUC__) && \ (__GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) # define MPFR_DEPRECATED __attribute__ ((deprecated)) #elif defined(_MSC_VER) && _MSC_VER >= 1300 # define MPFR_DEPRECATED __declspec(deprecated) #else # define MPFR_DEPRECATED #endif /* Note: In order to be declared, some functions need a specific system header to be included *before* "mpfr.h". If the user forgets to include the header, the MPFR function prototype in the user object file is not correct. To avoid wrong results, we raise a linker error in that case by changing their internal name in the library (prefixed by __gmpfr instead of mpfr). See the lines of the form "#define mpfr_xxx __gmpfr_xxx" below. */ #if defined (__cplusplus) extern "C" { #endif __MPFR_DECLSPEC __gmp_const char * mpfr_get_version _MPFR_PROTO ((void)); __MPFR_DECLSPEC __gmp_const char * mpfr_get_patches _MPFR_PROTO ((void)); __MPFR_DECLSPEC int mpfr_buildopt_tls_p _MPFR_PROTO ((void)); __MPFR_DECLSPEC int <API key> _MPFR_PROTO ((void)); __MPFR_DECLSPEC int <API key> _MPFR_PROTO ((void)); __MPFR_DECLSPEC __gmp_const char * <API key> _MPFR_PROTO ((void)); __MPFR_DECLSPEC mpfr_exp_t mpfr_get_emin _MPFR_PROTO ((void)); __MPFR_DECLSPEC int mpfr_set_emin _MPFR_PROTO ((mpfr_exp_t)); __MPFR_DECLSPEC mpfr_exp_t mpfr_get_emin_min _MPFR_PROTO ((void)); __MPFR_DECLSPEC mpfr_exp_t mpfr_get_emin_max _MPFR_PROTO ((void)); __MPFR_DECLSPEC mpfr_exp_t mpfr_get_emax _MPFR_PROTO ((void)); __MPFR_DECLSPEC int mpfr_set_emax _MPFR_PROTO ((mpfr_exp_t)); __MPFR_DECLSPEC mpfr_exp_t mpfr_get_emax_min _MPFR_PROTO ((void)); __MPFR_DECLSPEC mpfr_exp_t mpfr_get_emax_max _MPFR_PROTO ((void)); __MPFR_DECLSPEC void <API key> _MPFR_PROTO((mpfr_rnd_t)); __MPFR_DECLSPEC mpfr_rnd_t <API key> _MPFR_PROTO((void)); __MPFR_DECLSPEC __gmp_const char * mpfr_print_rnd_mode _MPFR_PROTO((mpfr_rnd_t)); __MPFR_DECLSPEC void mpfr_clear_flags _MPFR_PROTO ((void)); __MPFR_DECLSPEC void <API key> _MPFR_PROTO ((void)); __MPFR_DECLSPEC void mpfr_clear_overflow _MPFR_PROTO ((void)); __MPFR_DECLSPEC void mpfr_clear_divby0 _MPFR_PROTO ((void)); __MPFR_DECLSPEC void mpfr_clear_nanflag _MPFR_PROTO ((void)); __MPFR_DECLSPEC void mpfr_clear_inexflag _MPFR_PROTO ((void)); __MPFR_DECLSPEC void <API key> _MPFR_PROTO ((void)); __MPFR_DECLSPEC void mpfr_set_underflow _MPFR_PROTO ((void)); __MPFR_DECLSPEC void mpfr_set_overflow _MPFR_PROTO ((void)); __MPFR_DECLSPEC void mpfr_set_divby0 _MPFR_PROTO ((void)); __MPFR_DECLSPEC void mpfr_set_nanflag _MPFR_PROTO ((void)); __MPFR_DECLSPEC void mpfr_set_inexflag _MPFR_PROTO ((void)); __MPFR_DECLSPEC void mpfr_set_erangeflag _MPFR_PROTO ((void)); __MPFR_DECLSPEC int mpfr_underflow_p _MPFR_PROTO ((void)); __MPFR_DECLSPEC int mpfr_overflow_p _MPFR_PROTO ((void)); __MPFR_DECLSPEC int mpfr_divby0_p _MPFR_PROTO ((void)); __MPFR_DECLSPEC int mpfr_nanflag_p _MPFR_PROTO ((void)); __MPFR_DECLSPEC int mpfr_inexflag_p _MPFR_PROTO ((void)); __MPFR_DECLSPEC int mpfr_erangeflag_p _MPFR_PROTO ((void)); __MPFR_DECLSPEC int mpfr_check_range _MPFR_PROTO ((mpfr_ptr, int, mpfr_rnd_t)); __MPFR_DECLSPEC void mpfr_init2 _MPFR_PROTO ((mpfr_ptr, mpfr_prec_t)); __MPFR_DECLSPEC void mpfr_init _MPFR_PROTO ((mpfr_ptr)); __MPFR_DECLSPEC void mpfr_clear _MPFR_PROTO ((mpfr_ptr)); __MPFR_DECLSPEC void mpfr_inits2 _MPFR_PROTO ((mpfr_prec_t, mpfr_ptr, ...)) <API key>; __MPFR_DECLSPEC void mpfr_inits _MPFR_PROTO ((mpfr_ptr, ...)) <API key>; __MPFR_DECLSPEC void mpfr_clears _MPFR_PROTO ((mpfr_ptr, ...)) <API key>; __MPFR_DECLSPEC int mpfr_prec_round _MPFR_PROTO ((mpfr_ptr, mpfr_prec_t, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_can_round _MPFR_PROTO ((mpfr_srcptr, mpfr_exp_t, mpfr_rnd_t, mpfr_rnd_t, mpfr_prec_t)); __MPFR_DECLSPEC mpfr_prec_t mpfr_min_prec _MPFR_PROTO ((mpfr_srcptr)); __MPFR_DECLSPEC mpfr_exp_t mpfr_get_exp _MPFR_PROTO ((mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_set_exp _MPFR_PROTO ((mpfr_ptr, mpfr_exp_t)); __MPFR_DECLSPEC mpfr_prec_t mpfr_get_prec _MPFR_PROTO((mpfr_srcptr)); __MPFR_DECLSPEC void mpfr_set_prec _MPFR_PROTO((mpfr_ptr, mpfr_prec_t)); __MPFR_DECLSPEC void mpfr_set_prec_raw _MPFR_PROTO((mpfr_ptr, mpfr_prec_t)); __MPFR_DECLSPEC void <API key> _MPFR_PROTO((mpfr_prec_t)); __MPFR_DECLSPEC mpfr_prec_t <API key> _MPFR_PROTO((void)); __MPFR_DECLSPEC int mpfr_set_d _MPFR_PROTO ((mpfr_ptr, double, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_set_flt _MPFR_PROTO ((mpfr_ptr, float, mpfr_rnd_t)); #ifdef <API key> __MPFR_DECLSPEC int mpfr_set_decimal64 _MPFR_PROTO ((mpfr_ptr, _Decimal64, mpfr_rnd_t)); #endif __MPFR_DECLSPEC int mpfr_set_ld _MPFR_PROTO ((mpfr_ptr, long double, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_set_z _MPFR_PROTO ((mpfr_ptr, mpz_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_set_z_2exp _MPFR_PROTO ((mpfr_ptr, mpz_srcptr, mpfr_exp_t, mpfr_rnd_t)); __MPFR_DECLSPEC void mpfr_set_nan _MPFR_PROTO ((mpfr_ptr)); __MPFR_DECLSPEC void mpfr_set_inf _MPFR_PROTO ((mpfr_ptr, int)); __MPFR_DECLSPEC void mpfr_set_zero _MPFR_PROTO ((mpfr_ptr, int)); __MPFR_DECLSPEC int mpfr_set_f _MPFR_PROTO ((mpfr_ptr, mpf_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_get_f _MPFR_PROTO ((mpf_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_set_si _MPFR_PROTO ((mpfr_ptr, long, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_set_ui _MPFR_PROTO ((mpfr_ptr, unsigned long, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_set_si_2exp _MPFR_PROTO ((mpfr_ptr, long, mpfr_exp_t, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_set_ui_2exp _MPFR_PROTO ((mpfr_ptr,unsigned long,mpfr_exp_t,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_set_q _MPFR_PROTO ((mpfr_ptr, mpq_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_set_str _MPFR_PROTO ((mpfr_ptr, __gmp_const char *, int, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_init_set_str _MPFR_PROTO ((mpfr_ptr, __gmp_const char *, int, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_set4 _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_rnd_t, int)); __MPFR_DECLSPEC int mpfr_abs _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_set _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_neg _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_signbit _MPFR_PROTO ((mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_setsign _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, int, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_copysign _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC mpfr_exp_t mpfr_get_z_2exp _MPFR_PROTO ((mpz_ptr, mpfr_srcptr)); __MPFR_DECLSPEC float mpfr_get_flt _MPFR_PROTO ((mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC double mpfr_get_d _MPFR_PROTO ((mpfr_srcptr, mpfr_rnd_t)); #ifdef <API key> __MPFR_DECLSPEC _Decimal64 mpfr_get_decimal64 _MPFR_PROTO ((mpfr_srcptr, mpfr_rnd_t)); #endif __MPFR_DECLSPEC long double mpfr_get_ld _MPFR_PROTO ((mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC double mpfr_get_d1 _MPFR_PROTO ((mpfr_srcptr)); __MPFR_DECLSPEC double mpfr_get_d_2exp _MPFR_PROTO ((long*, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC long double mpfr_get_ld_2exp _MPFR_PROTO ((long*, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_frexp _MPFR_PROTO ((mpfr_exp_t*, mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC long mpfr_get_si _MPFR_PROTO ((mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC unsigned long mpfr_get_ui _MPFR_PROTO ((mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC char*mpfr_get_str _MPFR_PROTO ((char*, mpfr_exp_t*, int, size_t, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_get_z _MPFR_PROTO ((mpz_ptr z, mpfr_srcptr f, mpfr_rnd_t)); __MPFR_DECLSPEC void mpfr_free_str _MPFR_PROTO ((char *)); __MPFR_DECLSPEC int mpfr_urandom _MPFR_PROTO ((mpfr_ptr, gmp_randstate_t, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_grandom _MPFR_PROTO ((mpfr_ptr, mpfr_ptr, gmp_randstate_t, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_urandomb _MPFR_PROTO ((mpfr_ptr, gmp_randstate_t)); __MPFR_DECLSPEC void mpfr_nextabove _MPFR_PROTO ((mpfr_ptr)); __MPFR_DECLSPEC void mpfr_nextbelow _MPFR_PROTO ((mpfr_ptr)); __MPFR_DECLSPEC void mpfr_nexttoward _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_printf _MPFR_PROTO ((__gmp_const char*, ...)); __MPFR_DECLSPEC int mpfr_asprintf _MPFR_PROTO ((char**, __gmp_const char*, )); __MPFR_DECLSPEC int mpfr_sprintf _MPFR_PROTO ((char*, __gmp_const char*, )); __MPFR_DECLSPEC int mpfr_snprintf _MPFR_PROTO ((char*, size_t, __gmp_const char*, ...)); __MPFR_DECLSPEC int mpfr_pow _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_pow_si _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, long int, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_pow_ui _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, unsigned long int, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_ui_pow_ui _MPFR_PROTO ((mpfr_ptr, unsigned long int, unsigned long int, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_ui_pow _MPFR_PROTO ((mpfr_ptr, unsigned long int, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_pow_z _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpz_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_sqrt _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_sqrt_ui _MPFR_PROTO ((mpfr_ptr, unsigned long, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_rec_sqrt _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_add _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_sub _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_mul _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_div _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_add_ui _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, unsigned long, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_sub_ui _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, unsigned long, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_ui_sub _MPFR_PROTO ((mpfr_ptr, unsigned long, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_mul_ui _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, unsigned long, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_div_ui _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, unsigned long, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_ui_div _MPFR_PROTO ((mpfr_ptr, unsigned long, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_add_si _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, long int, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_sub_si _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, long int, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_si_sub _MPFR_PROTO ((mpfr_ptr, long int, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_mul_si _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, long int, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_div_si _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, long int, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_si_div _MPFR_PROTO ((mpfr_ptr, long int, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_add_d _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, double, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_sub_d _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, double, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_d_sub _MPFR_PROTO ((mpfr_ptr, double, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_mul_d _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, double, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_div_d _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, double, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_d_div _MPFR_PROTO ((mpfr_ptr, double, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_sqr _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_const_pi _MPFR_PROTO ((mpfr_ptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_const_log2 _MPFR_PROTO ((mpfr_ptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_const_euler _MPFR_PROTO ((mpfr_ptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_const_catalan _MPFR_PROTO ((mpfr_ptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_agm _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_log _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_log2 _MPFR_PROTO ((mpfr_ptr,mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_log10 _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_log1p _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_exp _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_exp2 _MPFR_PROTO ((mpfr_ptr,mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_exp10 _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_expm1 _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_eint _MPFR_PROTO ((mpfr_ptr,mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_li2 _MPFR_PROTO ((mpfr_ptr,mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_cmp _MPFR_PROTO ((mpfr_srcptr, mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_cmp3 _MPFR_PROTO ((mpfr_srcptr, mpfr_srcptr, int)); __MPFR_DECLSPEC int mpfr_cmp_d _MPFR_PROTO ((mpfr_srcptr, double)); __MPFR_DECLSPEC int mpfr_cmp_ld _MPFR_PROTO ((mpfr_srcptr, long double)); __MPFR_DECLSPEC int mpfr_cmpabs _MPFR_PROTO ((mpfr_srcptr, mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_cmp_ui _MPFR_PROTO ((mpfr_srcptr, unsigned long)); __MPFR_DECLSPEC int mpfr_cmp_si _MPFR_PROTO ((mpfr_srcptr, long)); __MPFR_DECLSPEC int mpfr_cmp_ui_2exp _MPFR_PROTO ((mpfr_srcptr, unsigned long, mpfr_exp_t)); __MPFR_DECLSPEC int mpfr_cmp_si_2exp _MPFR_PROTO ((mpfr_srcptr, long, mpfr_exp_t)); __MPFR_DECLSPEC void mpfr_reldiff _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_eq _MPFR_PROTO((mpfr_srcptr, mpfr_srcptr, unsigned long)); __MPFR_DECLSPEC int mpfr_sgn _MPFR_PROTO ((mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_mul_2exp _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, unsigned long, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_div_2exp _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, unsigned long, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_mul_2ui _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, unsigned long, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_div_2ui _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, unsigned long, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_mul_2si _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, long, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_div_2si _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, long, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_rint _MPFR_PROTO((mpfr_ptr,mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_round _MPFR_PROTO((mpfr_ptr, mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_trunc _MPFR_PROTO((mpfr_ptr, mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_ceil _MPFR_PROTO((mpfr_ptr, mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_floor _MPFR_PROTO((mpfr_ptr, mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_rint_round _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_rint_trunc _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_rint_ceil _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_rint_floor _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_frac _MPFR_PROTO ((mpfr_ptr,mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_modf _MPFR_PROTO ((mpfr_ptr, mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_remquo _MPFR_PROTO ((mpfr_ptr, long*, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_remainder _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_fmod _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_fits_ulong_p _MPFR_PROTO((mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_fits_slong_p _MPFR_PROTO((mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_fits_uint_p _MPFR_PROTO((mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_fits_sint_p _MPFR_PROTO((mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_fits_ushort_p _MPFR_PROTO((mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_fits_sshort_p _MPFR_PROTO((mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_fits_uintmax_p _MPFR_PROTO((mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_fits_intmax_p _MPFR_PROTO((mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC void mpfr_extract _MPFR_PROTO ((mpz_ptr, mpfr_srcptr, unsigned int)); __MPFR_DECLSPEC void mpfr_swap _MPFR_PROTO ((mpfr_ptr, mpfr_ptr)); __MPFR_DECLSPEC void mpfr_dump _MPFR_PROTO ((mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_nan_p _MPFR_PROTO((mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_inf_p _MPFR_PROTO((mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_number_p _MPFR_PROTO((mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_integer_p _MPFR_PROTO ((mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_zero_p _MPFR_PROTO ((mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_regular_p _MPFR_PROTO ((mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_greater_p _MPFR_PROTO ((mpfr_srcptr, mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_greaterequal_p _MPFR_PROTO ((mpfr_srcptr, mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_less_p _MPFR_PROTO ((mpfr_srcptr, mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_lessequal_p _MPFR_PROTO ((mpfr_srcptr, mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_lessgreater_p _MPFR_PROTO((mpfr_srcptr,mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_equal_p _MPFR_PROTO ((mpfr_srcptr, mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_unordered_p _MPFR_PROTO ((mpfr_srcptr, mpfr_srcptr)); __MPFR_DECLSPEC int mpfr_atanh _MPFR_PROTO((mpfr_ptr,mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_acosh _MPFR_PROTO((mpfr_ptr,mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_asinh _MPFR_PROTO((mpfr_ptr,mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_cosh _MPFR_PROTO((mpfr_ptr,mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_sinh _MPFR_PROTO((mpfr_ptr,mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_tanh _MPFR_PROTO((mpfr_ptr,mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_sinh_cosh _MPFR_PROTO ((mpfr_ptr, mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_sech _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_csch _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_coth _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_acos _MPFR_PROTO ((mpfr_ptr,mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_asin _MPFR_PROTO ((mpfr_ptr,mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_atan _MPFR_PROTO ((mpfr_ptr,mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_sin _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_sin_cos _MPFR_PROTO ((mpfr_ptr, mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_cos _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_tan _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_atan2 _MPFR_PROTO ((mpfr_ptr,mpfr_srcptr,mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_sec _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_csc _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_cot _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_hypot _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_erf _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_erfc _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_cbrt _MPFR_PROTO ((mpfr_ptr,mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_root _MPFR_PROTO ((mpfr_ptr,mpfr_srcptr,unsigned long,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_gamma _MPFR_PROTO((mpfr_ptr,mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_lngamma _MPFR_PROTO((mpfr_ptr,mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_lgamma _MPFR_PROTO((mpfr_ptr,int*,mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_digamma _MPFR_PROTO((mpfr_ptr,mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_zeta _MPFR_PROTO ((mpfr_ptr,mpfr_srcptr,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_zeta_ui _MPFR_PROTO ((mpfr_ptr,unsigned long,mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_fac_ui _MPFR_PROTO ((mpfr_ptr, unsigned long int, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_j0 _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_j1 _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_jn _MPFR_PROTO ((mpfr_ptr, long, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_y0 _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_y1 _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_yn _MPFR_PROTO ((mpfr_ptr, long, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_ai _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_min _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_max _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_dim _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_mul_z _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpz_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_div_z _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpz_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_add_z _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpz_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_sub_z _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpz_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_z_sub _MPFR_PROTO ((mpfr_ptr, mpz_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_cmp_z _MPFR_PROTO ((mpfr_srcptr, mpz_srcptr)); __MPFR_DECLSPEC int mpfr_mul_q _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpq_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_div_q _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpq_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_add_q _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpq_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_sub_q _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpq_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_cmp_q _MPFR_PROTO ((mpfr_srcptr, mpq_srcptr)); __MPFR_DECLSPEC int mpfr_cmp_f _MPFR_PROTO ((mpfr_srcptr, mpf_srcptr)); __MPFR_DECLSPEC int mpfr_fma _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_fms _MPFR_PROTO ((mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_sum _MPFR_PROTO ((mpfr_ptr, mpfr_ptr *__gmp_const, unsigned long, mpfr_rnd_t)); __MPFR_DECLSPEC void mpfr_free_cache _MPFR_PROTO ((void)); __MPFR_DECLSPEC int mpfr_subnormalize _MPFR_PROTO ((mpfr_ptr, int, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_strtofr _MPFR_PROTO ((mpfr_ptr, __gmp_const char *, char **, int, mpfr_rnd_t)); __MPFR_DECLSPEC size_t <API key> _MPFR_PROTO ((mpfr_prec_t)); __MPFR_DECLSPEC void mpfr_custom_init _MPFR_PROTO ((void *, mpfr_prec_t)); __MPFR_DECLSPEC void * <API key> _MPFR_PROTO ((mpfr_srcptr)); __MPFR_DECLSPEC mpfr_exp_t mpfr_custom_get_exp _MPFR_PROTO ((mpfr_srcptr)); __MPFR_DECLSPEC void mpfr_custom_move _MPFR_PROTO ((mpfr_ptr, void *)); __MPFR_DECLSPEC void <API key> _MPFR_PROTO ((mpfr_ptr, int, mpfr_exp_t, mpfr_prec_t, void *)); __MPFR_DECLSPEC int <API key> _MPFR_PROTO ((mpfr_srcptr)); #if defined (__cplusplus) } #endif /* Define MPFR_USE_EXTENSION to avoid "gcc -pedantic" warnings. */ #ifndef MPFR_EXTENSION # if defined(MPFR_USE_EXTENSION) # define MPFR_EXTENSION __extension__ # else # define MPFR_EXTENSION # endif #endif /* Warning! This macro doesn't work with K&R C (e.g., compare the "gcc -E" output with and without -traditional) and shouldn't be used internally. For public use only, but see the MPFR manual. */ #define MPFR_DECL_INIT(_x, _p) \ MPFR_EXTENSION mp_limb_t __gmpfr_local_tab_##_x[((_p)-1)/GMP_NUMB_BITS+1]; \ MPFR_EXTENSION mpfr_t _x = {{(_p),1,__MPFR_EXP_NAN,__gmpfr_local_tab_ /* Fast access macros to replace function interface. If the USER don't want to use the macro interface, let him make happy even if it produces faster and smaller code. */ #ifndef MPFR_USE_NO_MACRO /* Inlining theses functions is both faster and smaller */ #define mpfr_nan_p(_x) ((_x)->_mpfr_exp == __MPFR_EXP_NAN) #define mpfr_inf_p(_x) ((_x)->_mpfr_exp == __MPFR_EXP_INF) #define mpfr_zero_p(_x) ((_x)->_mpfr_exp == __MPFR_EXP_ZERO) #define mpfr_regular_p(_x) ((_x)->_mpfr_exp > __MPFR_EXP_INF) #define mpfr_sgn(_x) \ ((_x)->_mpfr_exp < __MPFR_EXP_INF ? \ (mpfr_nan_p (_x) ? mpfr_set_erangeflag () : (mpfr_void) 0), 0 : \ MPFR_SIGN (_x)) /* Prevent them from using as lvalues */ #define MPFR_VALUE_OF(x) (0 ? (x) : (x)) #define mpfr_get_prec(_x) MPFR_VALUE_OF((_x)->_mpfr_prec) #define mpfr_get_exp(_x) MPFR_VALUE_OF((_x)->_mpfr_exp) /* Note: if need be, the MPFR_VALUE_OF can be used for other expressions (of any type). Thanks to Wojtek Lerch and Tim Rentsch for the idea. */ #define mpfr_round(a,b) mpfr_rint((a), (b), MPFR_RNDNA) #define mpfr_trunc(a,b) mpfr_rint((a), (b), MPFR_RNDZ) #define mpfr_ceil(a,b) mpfr_rint((a), (b), MPFR_RNDU) #define mpfr_floor(a,b) mpfr_rint((a), (b), MPFR_RNDD) #define mpfr_cmp_ui(b,i) mpfr_cmp_ui_2exp((b),(i),0) #define mpfr_cmp_si(b,i) mpfr_cmp_si_2exp((b),(i),0) #define mpfr_set(a,b,r) mpfr_set4(a,b,r,MPFR_SIGN(b)) #define mpfr_abs(a,b,r) mpfr_set4(a,b,r,1) #define mpfr_copysign(a,b,c,r) mpfr_set4(a,b,r,MPFR_SIGN(c)) #define mpfr_setsign(a,b,s,r) mpfr_set4(a,b,r,(s) ? -1 : 1) #define mpfr_signbit(x) (MPFR_SIGN(x) < 0) #define mpfr_cmp(b, c) mpfr_cmp3(b, c, 1) #define mpfr_mul_2exp(y,x,n,r) mpfr_mul_2ui((y),(x),(n),(r)) #define mpfr_div_2exp(y,x,n,r) mpfr_div_2ui((y),(x),(n),(r)) /* When using GCC, optimize certain common comparisons and affectations. + Remove ICC since it defines __GNUC__ but produces a huge number of warnings if you use this code. VL: I couldn't reproduce a single warning when enabling these macros with icc 10.1 20080212 on Itanium. But with this version, __ICC isn't defined (__INTEL_COMPILER is, though), so that these macros are enabled anyway. Checking with other ICC versions is needed. Possibly detect whether warnings are produced or not with a configure test. + Remove C++ too, since it complains too much. */ #if defined (__GNUC__) && !defined(__ICC) && !defined(__cplusplus) #if (__GNUC__ >= 2) #undef mpfr_cmp_ui /* We use the fact that mpfr_sgn on NaN sets the erange flag and returns 0. But warning! mpfr_sgn is specified as a macro in the API, thus the macro mustn't be used if side effects are possible, like here. */ #define mpfr_cmp_ui(_f,_u) \ (<API key> (_u) && (mpfr_ulong) (_u) == 0 ? \ (mpfr_sgn) (_f) : \ mpfr_cmp_ui_2exp ((_f), (_u), 0)) #undef mpfr_cmp_si #define mpfr_cmp_si(_f,_s) \ (<API key> (_s) && (mpfr_long) (_s) >= 0 ? \ mpfr_cmp_ui ((_f), (mpfr_ulong) (mpfr_long) (_s)) : \ mpfr_cmp_si_2exp ((_f), (_s), 0)) #if __GNUC__ > 2 || __GNUC_MINOR__ >= 95 #undef mpfr_set_ui #define mpfr_set_ui(_f,_u,_r) \ (<API key> (_u) && (mpfr_ulong) (_u) == 0 ? \ __extension__ ({ \ mpfr_ptr _p = (_f); \ _p->_mpfr_sign = 1; \ _p->_mpfr_exp = __MPFR_EXP_ZERO; \ (mpfr_void) (_r); 0; }) : \ mpfr_set_ui_2exp ((_f), (_u), 0, (_r))) #endif #undef mpfr_set_si #define mpfr_set_si(_f,_s,_r) \ (<API key> (_s) && (mpfr_long) (_s) >= 0 ? \ mpfr_set_ui ((_f), (mpfr_ulong) (mpfr_long) (_s), (_r)) : \ mpfr_set_si_2exp ((_f), (_s), 0, (_r))) #endif #endif /* Macro version of mpfr_stack interface for fast access */ #define <API key>(p) ((mpfr_size_t) \ (((p)+GMP_NUMB_BITS-1)/GMP_NUMB_BITS*sizeof (mp_limb_t))) #define mpfr_custom_init(m,p) do {} while (0) #define <API key>(x) ((mpfr_void*)((x)->_mpfr_d)) #define mpfr_custom_get_exp(x) ((x)->_mpfr_exp) #define mpfr_custom_move(x,m) do { ((x)->_mpfr_d = (mp_limb_t*)(m)); } while (0) #define <API key>(x,k,e,p,m) do { \ mpfr_ptr _x = (x); \ mpfr_exp_t _e; \ mpfr_kind_t _t; \ mpfr_int _s, _k; \ _k = (k); \ if (_k >= 0) { \ _t = (mpfr_kind_t) _k; \ _s = 1; \ } else { \ _t = (mpfr_kind_t) -k; \ _s = -1; \ } \ _e = _t == MPFR_REGULAR_KIND ? (e) : \ _t == MPFR_NAN_KIND ? __MPFR_EXP_NAN : \ _t == MPFR_INF_KIND ? __MPFR_EXP_INF : __MPFR_EXP_ZERO; \ _x->_mpfr_prec = (p); \ _x->_mpfr_sign = _s; \ _x->_mpfr_exp = _e; \ _x->_mpfr_d = (mp_limb_t*) (m); \ } while (0) #define <API key>(x) \ ( (x)->_mpfr_exp > __MPFR_EXP_INF ? \ (mpfr_int) MPFR_REGULAR_KIND * MPFR_SIGN (x) \ : (x)->_mpfr_exp == __MPFR_EXP_INF ? \ (mpfr_int) MPFR_INF_KIND * MPFR_SIGN (x) \ : (x)->_mpfr_exp == __MPFR_EXP_NAN ? (mpfr_int) MPFR_NAN_KIND \ : (mpfr_int) MPFR_ZERO_KIND * MPFR_SIGN (x) ) #endif /* MPFR_USE_NO_MACRO */ /* Theses are defined to be macros */ #define mpfr_init_set_si(x, i, rnd) \ ( mpfr_init(x), mpfr_set_si((x), (i), (rnd)) ) #define mpfr_init_set_ui(x, i, rnd) \ ( mpfr_init(x), mpfr_set_ui((x), (i), (rnd)) ) #define mpfr_init_set_d(x, d, rnd) \ ( mpfr_init(x), mpfr_set_d((x), (d), (rnd)) ) #define mpfr_init_set_ld(x, d, rnd) \ ( mpfr_init(x), mpfr_set_ld((x), (d), (rnd)) ) #define mpfr_init_set_z(x, i, rnd) \ ( mpfr_init(x), mpfr_set_z((x), (i), (rnd)) ) #define mpfr_init_set_q(x, i, rnd) \ ( mpfr_init(x), mpfr_set_q((x), (i), (rnd)) ) #define mpfr_init_set(x, y, rnd) \ ( mpfr_init(x), mpfr_set((x), (y), (rnd)) ) #define mpfr_init_set_f(x, y, rnd) \ ( mpfr_init(x), mpfr_set_f((x), (y), (rnd)) ) /* Compatibility layer -- obsolete functions and macros */ /* Note: it is not possible to output warnings, unless one defines * a deprecated variable and uses it, e.g. * MPFR_DEPRECATED extern int <API key>; * #define MPFR_EMIN_MIN ((void)<API key>,mpfr_get_emin_min()) * (the cast to void avoids a warning because the left-hand operand * has no effect). */ #define mpfr_cmp_abs mpfr_cmpabs #define mpfr_round_prec(x,r,p) mpfr_prec_round(x,p,r) #define <API key> (<API key>()) #define __mpfr_emin (mpfr_get_emin()) #define __mpfr_emax (mpfr_get_emax()) #define <API key> (<API key>()) #define MPFR_EMIN_MIN mpfr_get_emin_min() #define MPFR_EMIN_MAX mpfr_get_emin_max() #define MPFR_EMAX_MIN mpfr_get_emax_min() #define MPFR_EMAX_MAX mpfr_get_emax_max() #define mpfr_version (mpfr_get_version()) #ifndef mpz_set_fr # define mpz_set_fr mpfr_get_z #endif #define mpfr_add_one_ulp(x,r) \ (mpfr_sgn (x) > 0 ? mpfr_nextabove (x) : mpfr_nextbelow (x)) #define mpfr_sub_one_ulp(x,r) \ (mpfr_sgn (x) > 0 ? mpfr_nextbelow (x) : mpfr_nextabove (x)) #define mpfr_get_z_exp mpfr_get_z_2exp #define <API key> <API key> #endif /* __MPFR_H */ #if (defined (INTMAX_C) && defined (UINTMAX_C) && !defined(__cplusplus)) || \ defined (MPFR_USE_INTMAX_T) || \ defined (_STDINT_H) || defined (_STDINT_H_) || defined (_STDINT) # ifndef <API key> # define <API key> 1 #if defined (__cplusplus) extern "C" { #endif #define mpfr_set_sj __gmpfr_set_sj #define mpfr_set_sj_2exp __gmpfr_set_sj_2exp #define mpfr_set_uj __gmpfr_set_uj #define mpfr_set_uj_2exp __gmpfr_set_uj_2exp #define mpfr_get_sj __gmpfr_mpfr_get_sj #define mpfr_get_uj __gmpfr_mpfr_get_uj __MPFR_DECLSPEC int mpfr_set_sj _MPFR_PROTO ((mpfr_t, intmax_t, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_set_sj_2exp _MPFR_PROTO ((mpfr_t, intmax_t, intmax_t, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_set_uj _MPFR_PROTO ((mpfr_t, uintmax_t, mpfr_rnd_t)); __MPFR_DECLSPEC int mpfr_set_uj_2exp _MPFR_PROTO ((mpfr_t, uintmax_t, intmax_t, mpfr_rnd_t)); __MPFR_DECLSPEC intmax_t mpfr_get_sj _MPFR_PROTO ((mpfr_srcptr, mpfr_rnd_t)); __MPFR_DECLSPEC uintmax_t mpfr_get_uj _MPFR_PROTO ((mpfr_srcptr, mpfr_rnd_t)); #if defined (__cplusplus) } #endif # endif /* <API key> */ #endif /* Check if <stdio.h> has been included or if the user wants FILE */ #if defined (_GMP_H_HAVE_FILE) || defined (MPFR_USE_FILE) # ifndef _MPFR_H_HAVE_FILE # define _MPFR_H_HAVE_FILE 1 #if defined (__cplusplus) extern "C" { #endif #define mpfr_inp_str __gmpfr_inp_str #define mpfr_out_str __gmpfr_out_str __MPFR_DECLSPEC size_t mpfr_inp_str _MPFR_PROTO ((mpfr_ptr, FILE*, int, mpfr_rnd_t)); __MPFR_DECLSPEC size_t mpfr_out_str _MPFR_PROTO ((FILE*, int, size_t, mpfr_srcptr, mpfr_rnd_t)); #define mpfr_fprintf __gmpfr_fprintf __MPFR_DECLSPEC int mpfr_fprintf _MPFR_PROTO ((FILE*, __gmp_const char*, )); #if defined (__cplusplus) } #endif # endif /* _MPFR_H_HAVE_FILE */ #endif /* check if <stdarg.h> has been included or if the user wants va_list */ #if defined (_GMP_H_HAVE_VA_LIST) || defined (MPFR_USE_VA_LIST) # ifndef <API key> # define <API key> 1 #if defined (__cplusplus) extern "C" { #endif #define mpfr_vprintf __gmpfr_vprintf #define mpfr_vasprintf __gmpfr_vasprintf #define mpfr_vsprintf __gmpfr_vsprintf #define mpfr_vsnprintf __gmpfr_vsnprintf __MPFR_DECLSPEC int mpfr_vprintf _MPFR_PROTO ((__gmp_const char*, va_list)); __MPFR_DECLSPEC int mpfr_vasprintf _MPFR_PROTO ((char**, __gmp_const char*, va_list)); __MPFR_DECLSPEC int mpfr_vsprintf _MPFR_PROTO ((char*, __gmp_const char*, va_list)); __MPFR_DECLSPEC int mpfr_vsnprintf _MPFR_PROTO ((char*, size_t, __gmp_const char*, va_list)); #if defined (__cplusplus) } #endif # endif /* <API key> */ #endif /* check if <stdarg.h> has been included and if FILE is available (see above) */ #if defined (<API key>) && defined (_MPFR_H_HAVE_FILE) # ifndef <API key> # define <API key> 1 #if defined (__cplusplus) extern "C" { #endif #define mpfr_vfprintf __gmpfr_vfprintf __MPFR_DECLSPEC int mpfr_vfprintf _MPFR_PROTO ((FILE*, __gmp_const char*, va_list)); #if defined (__cplusplus) } #endif # endif /* <API key> */ #endif
<tr> <td> <?php echo $item->position; ?> </td> <td width="100"> <?php echo DateTime::createFromFormat($inDateFormat, $item->numDate)->format($outDateFormat); ?> <br> Seite <?php echo $item->pageNumber; ?><br> </td> <td> <b>Transskript-Auszug</b><br> <p> <?php // FIXME: Better way to create url? // FIXME: Move this (the URL) to a better place. $quality = 1; $scale = 1; $queryString = urlencode($query); $imageUrl = "http://89.200.168.9/kaschauer_zeitung/servlet/?method=showImageResult&quality=$quality&scale=$scale&highlighting=true&pageId={$item->pageId->pageId}&queryString=$queryString"; echo '<a style="float: left; margin: 5px;" href="' . $imageUrl . '" class="pageLink">' . $item->abstract . '</a>'; ?> </p> </td> </tr>
#include <assert.h> #include <stdint.h> #include <stdatomic.h> #include <pthread.h> atomic_int vars[2]; atomic_int atom_0_r1_0; atomic_int atom_0_r2_0; atomic_int atom_1_r1_0; atomic_int atom_1_r2_2; atomic_int atom_0_r2_2; atomic_int atom_0_r1_1; void *t0(void *arg){ label_1:; int v2_r1 = <API key>(&vars[0], <API key>); int v4_r2 = <API key>(&vars[1], <API key>); int v40 = (v2_r1 == 0); <API key>(&atom_0_r1_0, v40, <API key>); int v41 = (v4_r2 == 0); <API key>(&atom_0_r2_0, v41, <API key>); int v44 = (v4_r2 == 2); <API key>(&atom_0_r2_2, v44, <API key>); int v45 = (v2_r1 == 1); <API key>(&atom_0_r1_1, v45, <API key>); return NULL; } void *t1(void *arg){ label_2:; int v6_r2 = <API key>(&vars[1], <API key>); int v8_r1 = <API key>(&vars[0], <API key>); int v42 = (v8_r1 == 0); <API key>(&atom_1_r1_0, v42, <API key>); int v43 = (v6_r2 == 2); <API key>(&atom_1_r2_2, v43, <API key>); return NULL; } void *t2(void *arg){ label_3:; <API key>(&vars[0], 1, <API key>); <API key>(&vars[1], 2, <API key>); return NULL; } int main(int argc, char *argv[]){ pthread_t thr0; pthread_t thr1; pthread_t thr2; atomic_init(&vars[1], 0); atomic_init(&vars[0], 0); atomic_init(&atom_0_r1_0, 0); atomic_init(&atom_0_r2_0, 0); atomic_init(&atom_1_r1_0, 0); atomic_init(&atom_1_r2_2, 0); atomic_init(&atom_0_r2_2, 0); atomic_init(&atom_0_r1_1, 0); pthread_create(&thr0, NULL, t0, NULL); pthread_create(&thr1, NULL, t1, NULL); pthread_create(&thr2, NULL, t2, NULL); pthread_join(thr0, NULL); pthread_join(thr1, NULL); pthread_join(thr2, NULL); int v9 = <API key>(&atom_0_r1_0, <API key>); int v10 = <API key>(&atom_0_r2_0, <API key>); int v11 = <API key>(&atom_1_r1_0, <API key>); int v12 = <API key>(&atom_1_r2_2, <API key>); int v13_conj = v11 & v12; int v14_conj = v10 & v13_conj; int v15_conj = v9 & v14_conj; int v16 = <API key>(&atom_0_r1_0, <API key>); int v17 = <API key>(&atom_0_r2_2, <API key>); int v18 = <API key>(&atom_1_r1_0, <API key>); int v19 = <API key>(&atom_1_r2_2, <API key>); int v20_conj = v18 & v19; int v21_conj = v17 & v20_conj; int v22_conj = v16 & v21_conj; int v23 = <API key>(&atom_0_r1_1, <API key>); int v24 = <API key>(&atom_0_r2_0, <API key>); int v25 = <API key>(&atom_1_r1_0, <API key>); int v26 = <API key>(&atom_1_r2_2, <API key>); int v27_conj = v25 & v26; int v28_conj = v24 & v27_conj; int v29_conj = v23 & v28_conj; int v30 = <API key>(&atom_0_r1_1, <API key>); int v31 = <API key>(&atom_0_r2_2, <API key>); int v32 = <API key>(&atom_1_r1_0, <API key>); int v33 = <API key>(&atom_1_r2_2, <API key>); int v34_conj = v32 & v33; int v35_conj = v31 & v34_conj; int v36_conj = v30 & v35_conj; int v37_disj = v29_conj | v36_conj; int v38_disj = v22_conj | v37_disj; int v39_disj = v15_conj | v38_disj; if (v39_disj == 1) assert(0); return 0; }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reactive.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Unigram.Controls; using Unigram.Views; using Unigram.ViewModels.Settings; using Windows.ApplicationModel.DataTransfer; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace Unigram.Views.Settings { public sealed partial class <API key> : Page { public <API key> ViewModel => DataContext as <API key>; public <API key>() { InitializeComponent(); DataContext = UnigramContainer.Current.ResolveType<<API key>>(); var observable = Observable.FromEventPattern<<API key>>(Username, "TextChanged"); var throttled = observable.Throttle(TimeSpan.FromMilliseconds(Constants.TypingTimeout)).ObserveOnDispatcher().Subscribe(x => { if (ViewModel.UpdateIsValid(Username.Text)) { ViewModel.CheckAvailability(Username.Text); } }); } private void Copy_Click(Windows.UI.Xaml.Documents.Hyperlink sender, Windows.UI.Xaml.Documents.<API key> args) { ViewModel.CopyCommand.Execute(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace useAIble.GameLibrary.LogisticSimulation { public class Order { public Order(string name, int amount) { // for Alvin's approval this.Name = name; this.Amount = amount; } public string Name { get; set; } public int Amount { get; set; } public int Backlog { get; set; } public int Timer { get; set; } = 2; // will be customisable later through the order processing time public int ProcessOn { get; set; } = 0; } }
<?php namespace Piwik\Plugins\API\Renderer; use Piwik\API\ApiRenderer; use Piwik\Common; class Rss extends ApiRenderer { /** * @param $message * @param \Exception|\Throwable $exception * @return string */ public function renderException($message, $exception) { self::sendHeader('plain'); return 'Error: ' . $message; } public function renderDataTable($dataTable) { /** @var \Piwik\DataTable\Renderer\Rss $tableRenderer */ $tableRenderer = $this-><API key>($dataTable); $method = Common::getRequestVar('method', '', 'string', $this->request); $tableRenderer->setApiMethod($method); $tableRenderer->setIdSite(Common::getRequestVar('idSite', false, 'int', $this->request)); $tableRenderer-><API key>(Common::getRequestVar('<API key>', false, 'int', $this->request)); return $tableRenderer->render(); } public function renderArray($array) { return $this->renderDataTable($array); } public function sendHeader($type = "xml") { Common::sendHeader('Content-Type: text/' . $type . '; charset=utf-8'); } }
#include <config.h> #include <sys/types.h> #ifdef HAVE_SYS_POLL_H #include <sys/poll.h> #endif #include <stdlib.h> #ifdef WIN32 //#include <psdk_inc/_wsa_errnos.h> #else #include <netdb.h> #endif #include <errno.h> #include <string.h> #include <time.h> #include <unistd.h> #include <fcntl.h> #include <ctype.h> #include "list.h" #include "consts.h" #include "ipvers.h" #include "dns_query.h" #include "cache.h" #include "dns.h" #include "conff.h" #include "servers.h" #include "helpers.h" #include "netdev.h" #include "error.h" #include "debug.h" #if defined(NO_TCP_QUERIES) && M_PRESET!=UDP_ONLY # error "You may not define NO_TCP_QUERIES when M_PRESET is not set to UDP_ONLY" #endif #if defined(NO_UDP_QUERIES) && M_PRESET!=TCP_ONLY # error "You may not define NO_UDP_QUERIES when M_PRESET is not set to TCP_ONLY" #endif /* data type to hold lists of IP addresses (both v4 and v6) The allocated size should be: sizeof(rejectlist_t) + na4*sizeof(addr4maskpair_t) + na6*sizeof(addr6maskpair_t) */ typedef struct rejectlist_s { struct rejectlist_s *next; short policy; short inherit; int na4; #if ALLOW_LOCAL_AAAA int na6; addr6maskpair_t rdata[0]; /* dummy array for alignment */ #else addr4maskpair_t rdata[0]; #endif } rejectlist_t; /* --- structures and state constants for parallel query */ typedef struct { union { #ifdef ENABLE_IPV4 struct sockaddr_in sin4; #endif #ifdef ENABLE_IPV6 struct sockaddr_in6 sin6; #endif } a; #ifdef ENABLE_IPV6 struct in_addr a4fallback; #endif time_t timeout; unsigned short flags; short state; short qm; char nocache; char auth_serv; char lean_query; char edns_query; char needs_testing; char trusted; char aa; char tc; char ra; char failed; const unsigned char *nsdomain; rejectlist_t *rejectlist; /* internal state for p_exec_query */ int sock; #if 0 dns_cent_t nent; dns_cent_t servent; #endif unsigned short transl; unsigned short recvl; #ifndef NO_TCP_QUERIES int iolen; /* number of bytes written or read up to now */ #endif dns_msg_t *msg; dns_hdr_t *recvbuf; unsigned short myrid; int s_errno; } query_stat_t; typedef DYNAMIC_ARRAY(query_stat_t) *query_stat_array; /* Some macros for handling data in reject lists Perhaps we should use inline functions instead of macros. */ #define have_rejectlist(st) ((st)->rejectlist!=NULL) #define inherit_rejectlist(st) ((st)->rejectlist && (st)->rejectlist->inherit) #define reject_policy(st) ((st)->rejectlist->policy) #define nreject_a4(st) ((st)->rejectlist->na4) #if ALLOW_LOCAL_AAAA #define nreject_a6(st) ((st)->rejectlist->na6) #define rejectlist_a6(st) ((addr6maskpair_t *)(st)->rejectlist->rdata) #define rejectlist_a4(st) ((addr4maskpair_t *)(rejectlist_a6(st)+nreject_a6(st))) #else #define rejectlist_a4(st) ((addr4maskpair_t *)(st)->rejectlist->rdata) #endif #define QS_INITIAL 0 /* This is the initial state. Set this before starting. */ #define QS_TCPINITIAL 1 /* Start a TCP query. */ #define QS_TCPWRITE 2 /* Waiting to write data. */ #define QS_TCPREAD 3 /* Waiting to read data. */ #define QS_UDPINITIAL 4 /* Start a UDP query */ #define QS_UDPRECEIVE 5 /* UDP query transmitted, waiting for response. */ #define QS_QUERY_CASES case QS_TCPINITIAL: case QS_TCPWRITE: case QS_TCPREAD: case QS_UDPINITIAL: case QS_UDPRECEIVE #define QS_CANCELED 7 /* query was started, but canceled before completion */ #define QS_DONE 8 /* done, resources freed, result is in stat_t */ /* Events to be polled/selected for */ #define QS_WRITE_CASES case QS_TCPWRITE #define QS_READ_CASES case QS_TCPREAD: case QS_UDPRECEIVE /* * This is for error handling to prevent spewing the log files. * Races do not really matter here, so no locks. */ #define MAXPOLLERRS 10 static volatile unsigned long poll_errs=0; #define SOCK_ADDR(p) ((struct sockaddr *) &(p)->a) #ifdef SIN_LEN #undef SIN_LEN #endif #define SIN_LEN SEL_IPVER(sizeof(struct sockaddr_in),sizeof(struct sockaddr_in6)) #define PDNSD_A(p) SEL_IPVER(((pdnsd_a *) &(p)->a.sin4.sin_addr),((pdnsd_a *) &(p)->a.sin6.sin6_addr)) #ifndef EWOULDBLOCK #define EWOULDBLOCK EAGAIN #endif typedef DYNAMIC_ARRAY(dns_cent_t) *dns_cent_array; /* * Take the data from an RR and add it to an array of cache entries. * The return value will be RC_OK in case of success, * RC_SERVFAIL in case there is a problem with inconsistent ttl timestamps * or RC_FATALERR in case of a memory allocation failure. */ static int rr_to_cache(dns_cent_array *centa, unsigned char *oname, int tp, time_t ttl, unsigned dlen, void *data, unsigned flags, time_t queryts) { int i,n; dns_cent_t *cent; n=DA_NEL(*centa); for(i=0;i<n;++i) { cent=&DA_INDEX(*centa,i); if (rhnicmp(cent->qname,oname)) { int retval=RC_OK; /* We already have an entry in the array for this name. add_cent_rr is sufficient. However, make sure there are no double records. This is done by add_cent_rr */ #ifdef RFC2181_ME_HARDER rr_set_t *rrset= getrrset(cent,tp); if (rrset && rrset->ttl!=ttl) retval= RC_SERVFAIL; #endif return add_cent_rr(cent,tp,ttl,queryts,flags,dlen,data DBG1)? retval: RC_FATALERR; } } /* Add a new entry to the array for this name. */ if (!(*centa=DA_GROW1_F(*centa,free_cent0))) return RC_FATALERR; cent=&DA_LAST(*centa); if (!init_cent(cent,oname, 0, 0, 0 DBG1)) { *centa=DA_RESIZE(*centa,n); return RC_FATALERR; } return add_cent_rr(cent,tp,ttl,queryts,flags,dlen,data DBG1)? RC_OK: RC_FATALERR; } /* * Takes a pointer (ptr) to a buffer with recnum rrs,decodes them and enters * them into an array of cache entries. *ptr is modified to point after the last * rr, and *lcnt is decremented by the size of the rrs. * * *numopt is incremented with the number of OPT pseudo RRs found (should be at most one). * The structure pointed to by ep is filled with the information of the first OPT pseudo RR found, * but only if *numopt was set to zero before the call. * * The return value will be either RC_OK (which indicates success), * or one of the failure codes RC_FORMAT, RC_TRUNC, RC_SERVFAIL or RC_FATALERR * (the latter indicates a memory allocation failure). */ static int rrs2cent(unsigned char *msg, size_t msgsz, unsigned char **ptr, size_t *lcnt, int recnum, unsigned flags, time_t queryts, dns_cent_array *centa, int *numopt, edns_info_t *ep) { int rc, retval=RC_OK; int i; uint16_t type,class; uint32_t ttl; uint16_t rdlength; for (i=0;i<recnum;i++) { unsigned char oname[DNSNAMEBUFSIZE], *ttlp; unsigned int len; if ((rc=decompress_name(msg, msgsz, ptr, lcnt, oname, &len))!=RC_OK) { return rc; } if (*lcnt<sizeof_rr_hdr_t) { return RC_TRUNC; } *lcnt -= sizeof_rr_hdr_t; GETINT16(type,*ptr); GETINT16(class,*ptr); ttlp= *ptr; /* Remember pointer to ttl field. */ GETINT32(ttl,*ptr); GETINT16(rdlength,*ptr); if (*lcnt<rdlength) { return RC_TRUNC; } if(type==T_OPT) { /* Found OPT pseudo-RR */ if((*numopt)++ == 0) { #if DEBUG>0 if(oname[0]!=0) { DEBUG_MSG("rrs2cent: name in OPT record not empty!\n"); } #endif ep->udpsize= class; ep->rcode= ((uint16_t)ttlp[0]<<4) | ((dns_hdr_t *)msg)->rcode; ep->version= ttlp[1]; ep->do_flg= (ttlp[2]>>7)&1; #if DEBUG>0 if(debug_p) { unsigned int Zflags= ((uint16_t)ttlp[2]<<8) | ttlp[3]; if(Zflags & 0x7fff) { DEBUG_MSG("rrs2cent: Z field contains unknown nonzero bits (%04x).\n", Zflags); } } if(rdlength) { DEBUG_MSG("rrs2cent: RDATA field in OPT record not empty!\n"); } #endif } else { DEBUG_MSG("rrs2cent: ingnoring surplus OPT record.\n"); } } else if (!(<API key>(type) || class!=C_IN)) { /* Some types contain names that may be compressed, so these need to be processed. * The other records are taken as they are. */ size_t blcnt=rdlength; unsigned char *nptr; unsigned int slen; switch (type) { case T_A: /* Validate types we use internally */ if(rdlength!=4) goto invalid_length; goto default_case; case T_CNAME: case T_MB: case T_MD: case T_MF: case T_MG: case T_MR: case T_NS: case T_PTR: { unsigned char db[DNSNAMEBUFSIZE]; if ((rc=decompress_name(msg, msgsz, &bptr, &blcnt, db, &len))!=RC_OK) return rc==RC_TRUNC?RC_FORMAT:rc; if (blcnt!=0) goto trailing_junk; if ((rc=rr_to_cache(centa, oname, type, ttl, len, db, flags,queryts))!=RC_OK) { if(rc==RC_FATALERR) return rc; retval=rc; } } break; #if IS_CACHED_MINFO || IS_CACHED_RP #if IS_CACHED_MINFO case T_MINFO: #endif #if IS_CACHED_RP case T_RP: #endif { unsigned char db[DNSNAMEBUFSIZE+DNSNAMEBUFSIZE]; nptr=db; if ((rc=decompress_name(msg, msgsz, &bptr, &blcnt, nptr, &len))!=RC_OK) return rc==RC_TRUNC?RC_FORMAT:rc; /* PDNSD_ASSERT(len + DNSNAMEBUFSIZE <= sizeof(db), "T_MINFO/T_RP: buffer limit reached"); */ nptr+=len; slen=len; if ((rc=decompress_name(msg, msgsz, &bptr, &blcnt, nptr, &len))!=RC_OK) return rc==RC_TRUNC?RC_FORMAT:rc; /*nptr+=len;*/ slen+=len; if (blcnt!=0) goto trailing_junk; if ((rc=rr_to_cache(centa, oname, type, ttl, slen, db, flags,queryts))!=RC_OK) { if(rc==RC_FATALERR) return rc; retval=rc; } } break; #endif case T_MX: #if IS_CACHED_AFSDB case T_AFSDB: #endif #if IS_CACHED_RT case T_RT: #endif #if IS_CACHED_KX case T_KX: #endif { unsigned char db[2+DNSNAMEBUFSIZE]; if (blcnt<2) goto record_too_short; memcpy(db,bptr,2); /* copy the preference field*/ blcnt-=2; bptr+=2; nptr=db+2; slen=2; if ((rc=decompress_name(msg, msgsz, &bptr, &blcnt, nptr, &len))!=RC_OK) return rc==RC_TRUNC?RC_FORMAT:rc; /*nptr+=len;*/ slen+=len; if (blcnt!=0) goto trailing_junk; if ((rc=rr_to_cache(centa, oname, type, ttl, slen, db, flags,queryts))!=RC_OK) { if(rc==RC_FATALERR) return rc; retval=rc; } } break; case T_SOA: { unsigned char db[DNSNAMEBUFSIZE+DNSNAMEBUFSIZE+20]; nptr=db; if ((rc=decompress_name(msg, msgsz, &bptr, &blcnt, nptr, &len))!=RC_OK) return rc==RC_TRUNC?RC_FORMAT:rc; /* PDNSD_ASSERT(len + DNSNAMEBUFSIZE <= sizeof(db), "T_SOA: buffer limit reached"); */ nptr+=len; slen=len; if ((rc=decompress_name(msg, msgsz, &bptr, &blcnt, nptr, &len))!=RC_OK) return rc==RC_TRUNC?RC_FORMAT:rc; nptr+=len; slen+=len; /* PDNSD_ASSERT(slen + 20 <= sizeof(db), "T_SOA: buffer limit reached"); */ if (blcnt<20) goto record_too_short; memcpy(nptr,bptr,20); /*copy the rest of the SOA record*/ blcnt-=20; slen+=20; if (blcnt!=0) goto trailing_junk; if ((rc=rr_to_cache(centa, oname, type, ttl, slen, db, flags,queryts))!=RC_OK) { if(rc==RC_FATALERR) return rc; retval=rc; } } break; #if IS_CACHED_AAAA case T_AAAA: /* Validate types we use internally */ if(rdlength!=16) goto invalid_length; goto default_case; #endif #if IS_CACHED_PX case T_PX: { unsigned char db[2+DNSNAMEBUFSIZE+DNSNAMEBUFSIZE]; if (blcnt<2) goto record_too_short; memcpy(db,bptr,2); /* copy the preference field*/ blcnt-=2; bptr+=2; nptr=db+2; slen=2; if ((rc=decompress_name(msg, msgsz, &bptr, &blcnt, nptr, &len))!=RC_OK) return rc==RC_TRUNC?RC_FORMAT:rc; /* PDNSD_ASSERT(len + DNSNAMEBUFSIZE <= sizeof(db), "T_PX: buffer limit reached"); */ nptr+=len; slen+=len; if ((rc=decompress_name(msg, msgsz, &bptr, &blcnt, nptr, &len))!=RC_OK) return rc==RC_TRUNC?RC_FORMAT:rc; /* nptr+=len; */ slen+=len; if (blcnt!=0) goto trailing_junk; if ((rc=rr_to_cache(centa, oname, type, ttl, slen, db, flags,queryts))!=RC_OK) { if(rc==RC_FATALERR) return rc; retval=rc; } } break; #endif #if IS_CACHED_SRV case T_SRV: { unsigned char db[6+DNSNAMEBUFSIZE]; if (blcnt<6) goto record_too_short; memcpy(db,bptr,6); blcnt-=6; bptr+=6; nptr=db+6; slen=6; if ((rc=decompress_name(msg, msgsz, &bptr, &blcnt, nptr, &len))!=RC_OK) return rc==RC_TRUNC?RC_FORMAT:rc; /*nptr+=len;*/ slen+=len; if (blcnt!=0) goto trailing_junk; if ((rc=rr_to_cache(centa, oname, type, ttl, slen, db, flags,queryts))!=RC_OK) { if(rc==RC_FATALERR) return rc; retval=rc; } } break; #endif #if IS_CACHED_NXT case T_NXT: { unsigned char db[1040]; nptr=db; if ((rc=decompress_name(msg, msgsz, &bptr, &blcnt, nptr, &len))!=RC_OK) return rc==RC_TRUNC?RC_FORMAT:rc; nptr+=len; slen=len+blcnt; if (slen > sizeof(db)) goto buffer_overflow; memcpy(nptr,bptr,blcnt); if ((rc=rr_to_cache(centa, oname, type, ttl, slen, db, flags,queryts))!=RC_OK) { if(rc==RC_FATALERR) return rc; retval=rc; } } break; #endif #if IS_CACHED_NAPTR case T_NAPTR: { int j; unsigned char db[4 + 3*256 + DNSNAMEBUFSIZE]; nptr=db; /* * After the preference field, three text strings follow, the maximum length being 255 * characters for each (this is ensured by the type of *bptr), plus one length byte for * each, so 3 * 256 = 786 in total. In addition, the name below is up to DNSNAMEBUFSIZE characters * in size, and the preference field is another 4 bytes in size, so the total length * that can be taken up is 1028 characters. This means that the whole record will always * fit into db. */ len=4; /* also copy the preference field*/ for (j=0;j<3;j++) { if (len>=blcnt) goto record_too_short; len += ((unsigned)bptr[len])+1; } if(len>blcnt) goto record_too_short; memcpy(nptr,bptr,len); blcnt-=len; bptr+=len; nptr+=len; slen=len; /* PDNSD_ASSERT(slen+DNSNAMEBUFSIZE <= sizeof(db), "T_NAPTR: buffer limit reached (name)"); */ if ((rc=decompress_name(msg, msgsz, &bptr, &blcnt, nptr, &len))!=RC_OK) return rc==RC_TRUNC?RC_FORMAT:rc; /*nptr+=len;*/ slen+=len; if (blcnt!=0) goto trailing_junk; if ((rc=rr_to_cache(centa, oname, type, ttl, slen, db, flags,queryts))!=RC_OK) { if(rc==RC_FATALERR) return rc; retval=rc; } } break; #endif #if IS_CACHED_IPSECKEY case T_IPSECKEY: { unsigned gwtp; /* An IPSECKEY record can contain a domain name, so we do some sanity checks just to be sure. */ if(blcnt<3) goto record_too_short; gwtp= bptr[1]; blcnt -= 3; bptr += 3; switch(gwtp) { case 0: goto default_case; case 1: /* There should be enough room for IPv4 address. */ if(blcnt<4) goto record_too_short; goto default_case; case 2: /* There should be enough room for IPv6 address. */ if(blcnt<16) goto record_too_short; goto default_case; case 3: /* Check that domain name is not compressed. */ if(isnormalencdomname(bptr,blcnt)) goto default_case; /* It appears the name is compressed even though RFC 4025 says it shouldn't be. For the sake of flexibility, we try to decompress it anyway. */ { unsigned char *rbuf, nmbuf[DNSNAMEBUFSIZE]; if ((rc=decompress_name(msg, msgsz, &bptr, &blcnt, nmbuf, &len))!=RC_OK) return rc==RC_TRUNC?RC_FORMAT:rc; slen=3+len+blcnt; rbuf=malloc(slen); if(!rbuf) return RC_FATALERR; nptr=mempcpy(rbuf,*ptr,3); nptr=mempcpy(nptr,nmbuf,len); memcpy(nptr,bptr,blcnt); rc=rr_to_cache(centa, oname, type, ttl, slen, rbuf, flags,queryts); free(rbuf); if(rc!=RC_OK) { if(rc==RC_FATALERR) return rc; retval=rc; } } break; default: DEBUG_MSG("rrs2cent: %s record contains unsupported gateway type (%u).\n",getrrtpname(type),gwtp); return RC_FORMAT; } } break; #endif #if IS_CACHED_RRSIG case T_RRSIG: /* An RRSIG record contains a domain name, so we do some sanity checks just to be sure. */ if(blcnt<18) goto record_too_short; blcnt -= 18; bptr += 18; if(isnormalencdomname(bptr,blcnt)) goto default_case; /* It appears the name is compressed even though RFC 4034 says it shouldn't be. For the sake of flexibility, we try to decompress it anyway. */ { unsigned char *rbuf, nmbuf[DNSNAMEBUFSIZE]; if ((rc=decompress_name(msg, msgsz, &bptr, &blcnt, nmbuf, &len))!=RC_OK) return rc==RC_TRUNC?RC_FORMAT:rc; slen=18+len+blcnt; rbuf=malloc(slen); if(!rbuf) return RC_FATALERR; nptr=mempcpy(rbuf,*ptr,18); nptr=mempcpy(nptr,nmbuf,len); memcpy(nptr,bptr,blcnt); rc=rr_to_cache(centa, oname, type, ttl, slen, rbuf, flags,queryts); free(rbuf); if(rc!=RC_OK) { if(rc==RC_FATALERR) return rc; retval=rc; } } break; #endif #if IS_CACHED_NSEC case T_NSEC: /* An NSEC record contains a domain name, so we do some sanity checks just to be sure. */ if(isnormalencdomname(bptr,blcnt)) goto default_case; /* It appears the name is compressed even though RFC 4034 says it shouldn't be. For the sake of flexibility, we try to decompress it anyway. */ { unsigned char *rbuf, nmbuf[DNSNAMEBUFSIZE]; if ((rc=decompress_name(msg, msgsz, &bptr, &blcnt, nmbuf, &len))!=RC_OK) return rc==RC_TRUNC?RC_FORMAT:rc; slen=len+blcnt; rbuf=malloc(slen); if(!rbuf) return RC_FATALERR; nptr=mempcpy(rbuf,nmbuf,len); memcpy(nptr,bptr,blcnt); rc=rr_to_cache(centa, oname, type, ttl, slen, rbuf, flags,queryts); free(rbuf); if(rc!=RC_OK) { if(rc==RC_FATALERR) return rc; retval=rc; } } break; #endif default: default_case: if ((rc=rr_to_cache(centa, oname, type, ttl, rdlength, *ptr, flags,queryts))!=RC_OK) { if(rc==RC_FATALERR) return rc; retval=rc; } } } else { /* skip otherwise */ DEBUG_MSG("rrs2cent: ignoring record of type %s (%d), class %s (%d).\n", getrrtpname(type), type, class==C_IN?"IN":"[unknown]", class); } *lcnt -= rdlength; *ptr += rdlength; } return retval; trailing_junk: DEBUG_MSG("rrs2cent: %s record has trailing junk.\n",getrrtpname(type)); return RC_FORMAT; record_too_short: DEBUG_MSG("rrs2cent: %s record too short.\n",getrrtpname(type)); return RC_FORMAT; buffer_overflow: DEBUG_MSG("rrs2cent: buffer too small to process %s record.\n",getrrtpname(type)); return RC_FORMAT; invalid_length: DEBUG_MSG("rrs2cent: %s record has length %u.\n",getrrtpname(type),rdlength); return RC_FORMAT; } /* * Try to bind the socket to a port in the given port range. Returns 1 on success, or 0 on failure. */ static int bind_socket(int s) { int query_port_start=global.query_port_start,query_port_end=global.query_port_end; /* * -1, as a special value for query_port_start, denotes that we let the kernel select * a port when we first use the socket, which used to be the default. */ if (query_port_start >= 0) { union { #ifdef ENABLE_IPV4 struct sockaddr_in sin4; #endif #ifdef ENABLE_IPV6 struct sockaddr_in6 sin6; #endif } sin; socklen_t sinl; int prt, pstart, range = <API key>+1, m=0xffff; unsigned try1,try2, maxtry2; if (range<=0 || range>0x10000) { log_warn("Illegal port range in %s line %d, dropping query!\n",__FILE__,__LINE__); return 0; } if(range<=0x8000) { /* Find the smallest power of 2 >= range. */ for(m=1; m<range; m <<= 1); /* Convert into a bit mask. */ --m; } for (try2=0,maxtry2=range*2;;) { /* Get a random number < range, by rejecting those >= range. */ for(try1=0;;) { prt= get_rand16()&m; if(prt<range) break; if(++try1>=0x10000) { log_warn("Cannot get random number < range" " after %d tries in %s line %d," " bad random number generator?\n", try1,__FILE__,__LINE__); return 0; } } prt += query_port_start; for(pstart=prt;;) { #ifdef ENABLE_IPV4 if (run_ipv4) { memset(&sin.sin4,0,sizeof(struct sockaddr_in)); sin.sin4.sin_family=AF_INET; sin.sin4.sin_port=htons(prt); sin.sin4.sin_addr=global.out_a.ipv4; SET_SOCKA_LEN4(sin.sin4); sinl=sizeof(struct sockaddr_in); } #endif #ifdef ENABLE_IPV6 ELSE_IPV6 { memset(&sin.sin6,0,sizeof(struct sockaddr_in6)); sin.sin6.sin6_family=AF_INET6; sin.sin6.sin6_port=htons(prt); sin.sin6.sin6_flowinfo=IPV6_FLOWINFO; sin.sin6.sin6_addr=global.out_a.ipv6; SET_SOCKA_LEN6(sin.sin6); sinl=sizeof(struct sockaddr_in6); } #endif if (bind(s,(struct sockaddr *)&sin,sinl)==-1) { #ifdef WIN32 if (WSAGetLastError()!=WSAEADDRINUSE && WSAGetLastError()!=WSAEADDRNOTAVAIL) { log_warn("Could not bind to socket: %d\n", WSAGetLastError()); #else if (errno!=EADDRINUSE && errno!=EADDRNOTAVAIL) { /* EADDRNOTAVAIL should not happen here... */ log_warn("Could not bind to socket: %s\n", strerror(errno)); #endif return 0; } /* If the address is in use, we continue. */ } else goto done; if(++try2>=maxtry2) { /* It is possible we missed the free ports by chance, try scanning the whole range. */ if (++prt>query_port_end) prt=query_port_start; if (prt==pstart) { /* Wrapped around, scanned the whole range. Give up. */ log_warn("Out of ports in the range" " %d-%d, dropping query!\n", query_port_start,query_port_end); return 0; } } else /* Try new random number */ break; } } } done: return 1; } inline static void *realloc_or_cleanup(void *ptr,size_t size) { void *retval=pdnsd_realloc(ptr,size); if(!retval) pdnsd_free(ptr); return retval; } #if defined(NO_TCP_QUERIES) # define USE_UDP(st) 1 #elif defined(NO_UDP_QUERIES) # define USE_UDP(st) 0 #else /* !defined(NO_TCP_QUERIES) && !defined(NO_UDP_QUERIES) */ # define USE_UDP(st) ((st)->qm==UDP_ONLY || (st)->qm==UDP_TCP) /* These functions will be used in case a TCP query might fail and we want to try again using UDP. */ # define tentative_tcp_query(st) ((st)->qm==TCP_UDP && ((st)->state==QS_TCPWRITE || ((st)->state==QS_TCPREAD && (st)->iolen==0))) inline static void switch_to_udp(query_stat_t *st) { st->qm=UDP_ONLY; st->myrid=get_rand16(); st->msg->hdr.id=htons(st->myrid); st->state=QS_UDPINITIAL; /* st->failed=0; */ } /* This function will be used in case a UDP reply was truncated and we want to try again using TCP. */ inline static void switch_to_tcp(query_stat_t *st) { /* PDNSD_ASSERT(st->state==QS_INITIAL || st->state==QS_DONE || st->state==QS_CANCELED, "Attempt to switch to TCP while a query is in progress."); */ st->qm=TCP_ONLY; st->state=QS_INITIAL; st->failed=0; } #endif /* The query state machine that is called from p_exec_query. This is called once for initialization (state * QS_TCPINITIAL or QS_UDPINITIAL is preset), and the state that it gives back may either be state QS_DONE, * in which case it must return a return code other than -1 and is called no more for this server * (except perhaps in UDP mode if TCP failed). If p_query_sm returns -1, then the state machine is in a read * or write state, and a function higher up the calling chain can setup a poll() or select() together with st->sock. * If that poll/select is succesful for that socket, p_exec_query is called again and will hand over to p_query_sm. * So, you can assume that read(), write() and recvfrom() will not block at the start of a state handling when you * have returned -1 (which means "call again") as last step of the last state handling. */ static int p_query_sm(query_stat_t *st) { int retval=RC_SERVFAIL,rv; #if !defined(NO_TCP_QUERIES) && !defined(NO_UDP_QUERIES) tryagain: #endif switch (st->state){ /* TCP query code */ #ifndef NO_TCP_QUERIES case QS_TCPINITIAL: if ((st->sock=socket(PDNSD_PF_INET,SOCK_STREAM,IPPROTO_TCP))==-1) { #ifdef WIN32 DEBUG_MSG("Could not open socket: %d\n", WSAGetLastError()); #else DEBUG_MSG("Could not open socket: %s\n", strerror(errno)); #endif break; } /* sin4 or sin6 is intialized, hopefully. */ /* maybe bind */ if (!bind_socket(st->sock)) { #ifdef WIN32 closesocket(st->sock); #else close(st->sock); #endif break; } /* transmit query by tcp*/ /* make the socket non-blocking */ { #ifdef WIN32 u_long mode = 1; if (ioctlsocket(st->sock,FIONBIO,&mode)!=0) { DEBUG_PDNSDA_MSG("fcntl error while trying to make socket to %s non-blocking: %d\n", PDNSDA2STR(PDNSD_A(st)),WSAGetLastError()); closesocket(st->sock); #else int oldflags = fcntl(st->sock, F_GETFL, 0); if (oldflags == -1 || fcntl(st->sock,F_SETFL,oldflags|O_NONBLOCK)==-1) { DEBUG_PDNSDA_MSG("fcntl error while trying to make socket to %s non-blocking: %s\n", PDNSDA2STR(PDNSD_A(st)),strerror(errno)); close(st->sock); #endif break; } } st->iolen=0; #ifdef ENABLE_IPV6 retry_tcp_connect: #endif if (connect(st->sock,SOCK_ADDR(st),SIN_LEN)==-1) { #ifdef WIN32 if (WSAGetLastError()==WSAEWOULDBLOCK) { #else if (errno==EINPROGRESS || errno==EPIPE) { #endif st->state=QS_TCPWRITE; /* st->event=QEV_WRITE; */ /* wait for writability; the connect is then done */ return -1; #ifdef WIN32 } else if (WSAGetLastError()==WSAECONNREFUSED) { st->s_errno=WSAGetLastError(); #else } else if (errno==ECONNREFUSED) { st->s_errno=errno; #endif DEBUG_PDNSDA_MSG("TCP connection refused by %s\n", PDNSDA2STR(PDNSD_A(st))); #ifdef WIN32 closesocket(st->sock); #else close(st->sock); #endif goto tcp_failed; /* We may want to try again using UDP */ } else { /* Since immediate connect() errors do not cost any time, we do not try to switch the * server status to offline */ #ifdef ENABLE_IPV6 /* if IPv6 connectivity is for some reason unavailable, perhaps the IPv4 fallback address can still be reached. */ # ifdef WIN32 if(!run_ipv4 && (WSAGetLastError()==WSAENETUNREACH || WSAGetLastError()==WSAENETDOWN) # else if(!run_ipv4 && (errno==ENETUNREACH || errno==ENETDOWN) # endif && st->a4fallback.s_addr!=INADDR_ANY) { #if DEBUG>0 char abuf[ADDRSTR_MAXLEN]; # ifdef WIN32 DEBUG_PDNSDA_MSG("Connecting to %s failed: %d, retrying with IPv4 address %s\n", PDNSDA2STR(PDNSD_A(st)),WSAGetLastError(), # else DEBUG_PDNSDA_MSG("Connecting to %s failed: %s, retrying with IPv4 address %s\n", PDNSDA2STR(PDNSD_A(st)),strerror(errno), # endif inet_ntop(AF_INET,&st->a4fallback,abuf,sizeof(abuf))); #endif IPV6_MAPIPV4(&st->a4fallback,&st->a.sin6.sin6_addr); st->a4fallback.s_addr=INADDR_ANY; goto retry_tcp_connect; } #endif #ifdef WIN32 DEBUG_PDNSDA_MSG("Error while connecting to %s: %d\n", PDNSDA2STR(PDNSD_A(st)),WSAGetLastError()); closesocket(st->sock); #else DEBUG_PDNSDA_MSG("Error while connecting to %s: %s\n", PDNSDA2STR(PDNSD_A(st)),strerror(errno)); close(st->sock); #endif break; } } st->state=QS_TCPWRITE; /* st->event=QEV_WRITE; */ /* fall through in case of not EINPROGRESS */ case QS_TCPWRITE: { int rem= dnsmsghdroffset + st->transl - st->iolen; if(rem>0) { #ifdef WIN32 rv=send(st->sock,((unsigned char*)st->msg)+st->iolen,rem,0); #else rv=write(st->sock,((unsigned char*)st->msg)+st->iolen,rem); #endif if(rv==-1) { #ifdef WIN32 if(WSAGetLastError()==WSAEWOULDBLOCK) #else if(errno==EWOULDBLOCK) #endif return -1; #ifdef WIN32 st->s_errno=WSAGetLastError(); closesocket(st->sock); #else st->s_errno=errno; close(st->sock); #endif if (st->iolen==0 && #ifdef WIN32 (st->s_errno==WSAECONNREFUSED || st->s_errno==WSAECONNRESET)) #else (st->s_errno==ECONNREFUSED || st->s_errno==ECONNRESET || st->s_errno==EPIPE)) #endif { /* This error may be delayed from connect() */ #ifdef WIN32 DEBUG_PDNSDA_MSG("TCP connection to %s failed: %d\n", PDNSDA2STR(PDNSD_A(st)),st->s_errno); #else DEBUG_PDNSDA_MSG("TCP connection to %s failed: %s\n", PDNSDA2STR(PDNSD_A(st)),strerror(st->s_errno)); #endif goto tcp_failed; /* We may want to try again using UDP */ } #ifdef WIN32 DEBUG_PDNSDA_MSG("Error while sending data to %s: %d\n", PDNSDA2STR(PDNSD_A(st)),st->s_errno); #else DEBUG_PDNSDA_MSG("Error while sending data to %s: %s\n", PDNSDA2STR(PDNSD_A(st)),strerror(st->s_errno)); #endif break; } st->iolen += rv; if(rv<rem) return -1; } } st->state=QS_TCPREAD; st->iolen=0; /* st->event=QEV_READ; */ /* fall through */ case QS_TCPREAD: if(st->iolen==0) { uint16_t recvl_net; #ifdef WIN32 rv=recv(st->sock,(char*)&recvl_net,sizeof(recvl_net),0); if(rv==-1 && WSAGetLastError()==WSAEWOULDBLOCK) #else rv=read(st->sock,&recvl_net,sizeof(recvl_net)); if(rv==-1 && errno==EWOULDBLOCK) #endif return -1; if(rv!=sizeof(recvl_net)) goto error_receiv_data; st->iolen=rv; st->recvl=ntohs(recvl_net); if(!(st->recvbuf=(dns_hdr_t *)realloc_or_cleanup(st->recvbuf,st->recvl))) { #ifdef WIN32 closesocket(st->sock); #else close(st->sock); #endif DEBUG_MSG("Out of memory in query.\n"); retval=RC_FATALERR; break; } } { int offset=st->iolen-sizeof(uint16_t); int rem=st->recvl-offset; if(rem>0) { #ifdef WIN32 rv=recv(st->sock,((unsigned char*)st->recvbuf)+offset,rem,0); #else rv=read(st->sock,((unsigned char*)st->recvbuf)+offset,rem); #endif if(rv==-1) { #ifdef WIN32 if(WSAGetLastError()==WSAEWOULDBLOCK) #else if(errno==EWOULDBLOCK) #endif return -1; goto error_receiv_data; } if(rv==0) goto error_receiv_data; /* unexpected EOF */ st->iolen += rv; if(rv<rem) return -1; } } #ifdef WIN32 closesocket(st->sock); #else close(st->sock); #endif st->state=QS_DONE; return RC_OK; error_receiv_data: #ifdef WIN32 if(rv==-1) st->s_errno=WSAGetLastError(); #else if(rv==-1) st->s_errno=errno; #endif DEBUG_PDNSDA_MSG("Error while receiving data from %s: %s\n", PDNSDA2STR(PDNSD_A(st)), rv==-1?strerror(errno):(rv==0 && st->iolen==0)?"no data":"incomplete data"); #ifdef WIN32 closesocket(st->sock); #else close(st->sock); #endif tcp_failed: #if !defined(NO_TCP_QUERIES) && !defined(NO_UDP_QUERIES) if(st->qm==TCP_UDP) { switch_to_udp(st); DEBUG_PDNSDA_MSG("TCP query to %s failed. Trying to use UDP.\n", PDNSDA2STR(PDNSD_A(st))); goto tryagain; } #endif break; #endif #ifndef NO_UDP_QUERIES /* UDP query code */ case QS_UDPINITIAL: if ((st->sock=socket(PDNSD_PF_INET,SOCK_DGRAM,IPPROTO_UDP))==-1) { # ifdef WIN32 DEBUG_MSG("Could not open socket: %d\n", WSAGetLastError()); # else DEBUG_MSG("Could not open socket: %s\n", strerror(errno)); # endif break; } /* maybe bind */ if (!bind_socket(st->sock)) { #ifdef WIN32 closesocket(st->sock); #else close(st->sock); #endif break; } /* connect */ #ifdef ENABLE_IPV6 retry_udp_connect: #endif if (connect(st->sock,SOCK_ADDR(st),SIN_LEN)==-1) { #ifdef WIN32 if (WSAGetLastError()==WSAECONNREFUSED) st->s_errno=WSAGetLastError(); #else if (errno==ECONNREFUSED) st->s_errno=errno; #endif #ifdef ENABLE_IPV6 /* if IPv6 connectivity is for some reason unavailable, perhaps the IPv4 fallback address can still be reached. */ # ifdef WIN32 else if(!run_ipv4 && (WSAGetLastError()==WSAENETUNREACH || WSAGetLastError()==WSAENETDOWN) # else else if(!run_ipv4 && (errno==ENETUNREACH || errno==ENETDOWN) # endif && st->a4fallback.s_addr!=INADDR_ANY) { #if DEBUG>0 char abuf[ADDRSTR_MAXLEN]; # ifdef WIN32 DEBUG_PDNSDA_MSG("Connecting to %s failed: %d, retrying with IPv4 address %s\n", PDNSDA2STR(PDNSD_A(st)),WSAGetLastError(), # else DEBUG_PDNSDA_MSG("Connecting to %s failed: %s, retrying with IPv4 address %s\n", PDNSDA2STR(PDNSD_A(st)),strerror(errno), # endif inet_ntop(AF_INET,&st->a4fallback,abuf,sizeof(abuf))); #endif IPV6_MAPIPV4(&st->a4fallback,&st->a.sin6.sin6_addr); st->a4fallback.s_addr=INADDR_ANY; goto retry_udp_connect; } #endif #ifdef WIN32 DEBUG_PDNSDA_MSG("Error while connecting to %s: %d\n", PDNSDA2STR(PDNSD_A(st)),WSAGetLastError()); closesocket(st->sock); #else DEBUG_PDNSDA_MSG("Error while connecting to %s: %s\n", PDNSDA2STR(PDNSD_A(st)),strerror(errno)); close(st->sock); #endif break; } /* transmit query by udp*/ /* send will hopefully not block on a freshly opened socket (the buffer * must be empty) */ if (send(st->sock,(char*)&st->msg->hdr,st->transl,0)==-1) { #ifdef WIN32 st->s_errno=WSAGetLastError(); DEBUG_PDNSDA_MSG("Error while sending data to %s: %d\n", PDNSDA2STR(PDNSD_A(st)),WSAGetLastError()); closesocket(st->sock); #else st->s_errno=errno; DEBUG_PDNSDA_MSG("Error while sending data to %s: %s\n", PDNSDA2STR(PDNSD_A(st)),strerror(errno)); close(st->sock); #endif break; } st->state=QS_UDPRECEIVE; /* st->event=QEV_READ; */ return -1; case QS_UDPRECEIVE: { int udpbufsize= (st->edns_query?global.udpbufsize:UDP_BUFSIZE); if(!(st->recvbuf=(dns_hdr_t *)realloc_or_cleanup(st->recvbuf,udpbufsize))) { #ifdef WIN32 closesocket(st->sock); #else close(st->sock); #endif DEBUG_MSG("Out of memory in query.\n"); retval=RC_FATALERR; break; } if ((rv=recv(st->sock,(char*)st->recvbuf,udpbufsize,0))==-1) { #ifdef WIN32 st->s_errno=WSAGetLastError(); DEBUG_PDNSDA_MSG("Error while receiving data from %s: %d\n", PDNSDA2STR(PDNSD_A(st)),WSAGetLastError()); closesocket(st->sock); #else st->s_errno=errno; DEBUG_PDNSDA_MSG("Error while receiving data from %s: %s\n", PDNSDA2STR(PDNSD_A(st)),strerror(errno)); close(st->sock); #endif break; } st->recvl=rv; if (st->recvl<sizeof(dns_hdr_t) || ntohs(st->recvbuf->id)!=st->myrid) { DEBUG_MSG("Bad answer received. Ignoring it.\n"); /* no need to care about timeouts here. That is done at an upper layer. */ st->state=QS_UDPRECEIVE; /* st->event=QEV_READ; */ return -1; } #ifdef WIN32 closesocket(st->sock); #else close(st->sock); #endif st->state=QS_DONE; return RC_OK; } #endif } /* If we get here, something has gone wrong. */ st->state=QS_DONE; return retval; /* should be either RC_SERVFAIL or RC_FATALERR */ } static dns_cent_t *lookup_cent_array(dns_cent_array ca, const unsigned char *nm) { int i,n=DA_NEL(ca); for(i=0;i<n;++i) { dns_cent_t *ce=&DA_INDEX(ca,i); if(rhnicmp(ce->qname,nm)) return ce; } return NULL; } /* Extract the minimum ttl field from the SOA record stored in an rr bucket. */ static time_t soa_minimum(rr_bucket_t *rrs) { uint32_t minimum; unsigned char *p=(unsigned char *)(rrs->data); /* Skip owner and maintainer. Lengths are validated in cache. */ p=skiprhn(skiprhn(p)); /* Skip serial, refresh, retry, expire fields. */ p += 4*sizeof(uint32_t); GETINT32(minimum,p); return minimum; } /* * The function that will actually execute a query. It takes a state structure in st. * st->state must be set to QS_INITIAL before calling. * This may return one of the RC_* codes, where RC_OK indicates success, the other * RC codes indicate the appropriate errors. -1 is the return value that indicates that * you should call p_exec_query again with the same state for the result until you get * a return value >0. Alternatively, call p_cancel_query to cancel it. * Timeouts are already handled by this function. * Any records that the query has yielded and that are not a direct answer to the query * (i.e. are records for other domains) are added to the cache, while the direct answers * are returned in ent. * All ns records, to whomever they might belong, are additionally returned in the ns list. * Free it when done. * This function calls another query state machine function that supports TCP and UDP. * * If you want to tell me that this function has a truly ugly coding style, ah, well... * You are right, somehow, but I feel it is conceptually elegant ;-) */ static int p_exec_query(dns_cent_t **entp, const unsigned char *name, int thint, query_stat_t *st, dlist *ns, unsigned char *c_soa) { int rv,rcode; unsigned short rd; switch (st->state){ case QS_INITIAL: { size_t transl,allocsz; unsigned int rrnlen=0; allocsz= sizeof(dns_msg_t); if(name) { rrnlen=rhnlen(name); allocsz += rrnlen+4; if(st->edns_query) allocsz += <API key>; } st->msg=(dns_msg_t *)pdnsd_malloc(allocsz); if (!st->msg) { st->state=QS_DONE; return RC_FATALERR; /* unrecoverable error */ } st->myrid=get_rand16(); st->msg->hdr.id=htons(st->myrid); st->msg->hdr.qr=QR_QUERY; st->msg->hdr.opcode=OP_QUERY; st->msg->hdr.aa=0; st->msg->hdr.tc=0; st->msg->hdr.rd=(name && st->trusted); st->msg->hdr.ra=0; st->msg->hdr.z=0; st->msg->hdr.ad=0; st->msg->hdr.cd=0; st->msg->hdr.rcode=RC_OK; st->msg->hdr.qdcount=htons(name!=NULL); st->msg->hdr.ancount=0; st->msg->hdr.nscount=0; st->msg->hdr.arcount=0; transl= sizeof(dns_hdr_t); if(name) { unsigned char *p = mempcpy((unsigned char *)(&st->msg->hdr+1),name,rrnlen); unsigned short qtype=(st->lean_query?thint:QT_ALL); PUTINT16(qtype,p); PUTINT16(C_IN,p); transl += rrnlen+4; if(st->edns_query) add_opt_pseudo_rr(&st->msg,&transl,&allocsz, global.udpbufsize,RC_OK,0,0); } st->transl=transl; #ifndef NO_TCP_QUERIES st->msg->len=htons(st->transl); #endif st->recvbuf=NULL; st->state=(USE_UDP(st)?QS_UDPINITIAL:QS_TCPINITIAL); /* fall through */ } QS_QUERY_CASES: tryagain: rv=p_query_sm(st); if (rv==-1) { return -1; } if (rv!=RC_OK) { pdnsd_free(st->msg); pdnsd_free(st->recvbuf); st->state=QS_DONE; if(st->needs_testing) { switch(st->s_errno) { #ifdef WIN32 case WSAENETUNREACH: /* network unreachable */ case WSAEHOSTUNREACH: /* host unreachable */ case WSAENOPROTOOPT: /* protocol unreachable */ case WSAECONNREFUSED: /* port unreachable */ case WSAENETDOWN: /* network down */ case WSAEHOSTDOWN: /* host down */ #else case ENETUNREACH: /* network unreachable */ case EHOSTUNREACH: /* host unreachable */ case ENOPROTOOPT: /* protocol unreachable */ case ECONNREFUSED: /* port unreachable */ case ENETDOWN: /* network down */ # ifdef EHOSTDOWN case EHOSTDOWN: /* host down */ # endif # ifdef ENONET case ENONET: /* machine not on the network */ # endif #endif //WIN32 /* Mark this server as down for a period of time */ sched_server_test(PDNSD_A(st),1,0); st->needs_testing=0; } } return rv; } /* rv==RC_OK */ DEBUG_PDNSDA_MSG("Received reply from %s (msg len=%u).\n", PDNSDA2STR(PDNSD_A(st)), st->recvl); DEBUG_DUMP_DNS_MSG(st->recvbuf, st->recvl); /* Basic sanity checks */ if (st->recvl<sizeof(dns_hdr_t)) { DEBUG_MSG("Message too short!\n"); goto discard_reply; } { uint16_t recvid=ntohs(st->recvbuf->id); if (recvid!=st->myrid) { DEBUG_MSG("ID mismatch: expected %04x, got %04x!\n", st->myrid, recvid); goto discard_reply; } } if (st->recvbuf->qr!=QR_RESP) { DEBUG_MSG("The QR bit indicates this is a query, not a response!\n"); goto discard_reply; } if (st->recvbuf->opcode!=OP_QUERY) { DEBUG_MSG("Not a reply to a standard query (opcode=%u).\n",st->recvbuf->opcode); goto discard_reply; } rcode=st->recvbuf->rcode; #if DEBUG>0 { char flgsbuf[DNSFLAGSMAXSTRSIZE]; DEBUG_MSG("rcode=%u (%s), flags:%s\n", rcode, get_ename(rcode), dnsflags2str(st->recvbuf, flgsbuf)); } #endif if (st->recvbuf->z!=0) { DEBUG_MSG("Malformed response (nonzero Z bit).\n"); goto discard_reply; } if(st->needs_testing) { /* We got an answer from this server, so don't bother with up tests for a while. */ sched_server_test(PDNSD_A(st),1,1); st->needs_testing=0; } rv=rcode; if(rcode==RC_OK || rcode==RC_NAMEERR) { /* success or at least no requery is needed */ st->state=QS_DONE; break; } else if (entp) { if(rcode==RC_SERVFAIL || rcode==RC_NOTSUPP || rcode==RC_REFUSED) { if (st->msg->hdr.rd && !st->recvbuf->ra) { /* seems as if we have got no recursion available. We will have to do it by ourselves (sigh...) */ DEBUG_PDNSDA_MSG("Server %s returned error code: %s." " Maybe does not support recursive query?" " Querying non-recursively.\n", PDNSDA2STR(PDNSD_A(st)),get_ename(rcode)); st->msg->hdr.rd=0; goto resetstate_tryagain; } else if(rcode!=RC_SERVFAIL && st->edns_query && st->msg->hdr.arcount) goto try_withoutedns; else if (st->recvbuf->ancount && st->auth_serv==2) { /* The name server returned a failure code, but the answer section is not empty, and the answer is from a server lower down the call chain. Use this answer tentatively (it may be the best we can get), but remember the failure. */ DEBUG_PDNSDA_MSG("Server %s returned error code: %s," " but the answer section is not empty." " Using the answer tentatively.\n", PDNSDA2STR(PDNSD_A(st)),get_ename(rcode)); st->failed=3; st->state=QS_DONE; break; } } else if(rcode==RC_FORMAT && st->edns_query && st->msg->hdr.arcount) try_withoutedns: { size_t transl; /* Perhaps the remote server barfs when the query contains an OPT RR in the additional section. Try again with an empty addtional section. */ DEBUG_PDNSDA_MSG("Server %s returned error code: %s." " Maybe cannot handle EDNS?" " Querying with empty additional section.\n", PDNSDA2STR(PDNSD_A(st)),get_ename(rcode)); transl=<API key>(st->msg,st->transl); if(transl!=0 && st->msg->hdr.arcount==0) { st->transl=transl; #ifndef NO_TCP_QUERIES st->msg->len=htons(st->transl); #endif st->edns_query=0; resetstate_tryagain: st->myrid=get_rand16(); st->msg->hdr.id=htons(st->myrid); st->state=(USE_UDP(st)?QS_UDPINITIAL:QS_TCPINITIAL); goto tryagain; } else { DEBUG_PDNSDA_MSG("Internal error: could not remove additional section from query" " to server %s\n", PDNSDA2STR(PDNSD_A(st))); } } } discard_reply: /* report failure */ pdnsd_free(st->msg); pdnsd_free(st->recvbuf); /*close(st->sock);*/ st->state=QS_DONE; #if DEBUG>0 if(entp) { DEBUG_PDNSDA_MSG("Discarding reply from server %s\n", PDNSDA2STR(PDNSD_A(st))); } #endif if (rv!=RC_OK) return rv; return RC_SERVFAIL; /* mock error code */ default: /* we shouldn't get here */ st->state=QS_DONE; return RC_SERVFAIL; /* mock error code */ } /* If we reach this code, we have successfully received an answer, * because we have returned error codes on errors or -1 on AGAIN conditions. * So we *should* have a usable dns record in recvbuf by now. */ rd= st->msg->hdr.rd; /* Save the 'Recursion Desired' bit of the query. */ pdnsd_free(st->msg); if(entp) { time_t queryts=time(NULL); size_t lcnt= ((size_t)st->recvl) - sizeof(dns_hdr_t); unsigned char *rrp=(unsigned char *)(st->recvbuf+1); dns_cent_array secs[3]={NULL,NULL,NULL}; # define ans_sec secs[0] # define auth_sec secs[1] # define add_sec secs[2] unsigned short qtype,flags,aa,neg_ans=0,reject_ans=0,num_ns=0; int numoptrr; edns_info_t ednsinfo= {0}; if (ntohs(st->recvbuf->qdcount)!=1) { DEBUG_PDNSDA_MSG("Bad number of query records in answer from %s\n", PDNSDA2STR(PDNSD_A(st))); rv=RC_SERVFAIL; goto free_recvbuf_return; } /* check & skip the query record. */ { unsigned char nbuf[DNSNAMEBUFSIZE]; if ((rv=decompress_name((unsigned char *)st->recvbuf, st->recvl, &rrp, &lcnt, nbuf, NULL))!=RC_OK) { DEBUG_PDNSDA_MSG("Cannot decompress QNAME in answer from %s\n", PDNSDA2STR(PDNSD_A(st))); rv=RC_SERVFAIL; goto free_recvbuf_return; } if(!rhnicmp(nbuf,name)) { DEBUG_PDNSDA_MSG("Answer from %s does not match query.\n", PDNSDA2STR(PDNSD_A(st))); rv=RC_SERVFAIL; goto free_recvbuf_return; } } qtype=(st->lean_query?thint:QT_ALL); if (lcnt<4) { DEBUG_PDNSDA_MSG("Format error in reply from %s (message truncated in qtype or qclass).\n", PDNSDA2STR(PDNSD_A(st))); rv=RC_SERVFAIL; /* mock error code */ goto free_recvbuf_return; } { unsigned short qt,qc; GETINT16(qt,rrp); GETINT16(qc,rrp); if(qt!=qtype) { DEBUG_PDNSDA_MSG("qtype in answer (%u) from %s does not match expected qtype (%u).\n", qt,PDNSDA2STR(PDNSD_A(st)),qtype); rv=RC_SERVFAIL; goto free_recvbuf_return; } } lcnt-=4; st->aa= (st->recvbuf->aa && !st->failed); st->tc= st->recvbuf->tc; st->ra= (rd && st->recvbuf->ra); /* Don't flag cache entries from a truncated reply as authoritative. */ aa= (st->aa && !st->tc); flags=st->flags; if (aa) flags|=CF_AUTH; /* Initialize a dns_cent_t in the array for the answer section */ if (!(ans_sec=DA_GROW1(ans_sec))) { rv=RC_FATALERR; /* unrecoverable error */ goto free_recvbuf_return; } /* By marking DF_AUTH, we mean authoritative AND complete. */ if (!init_cent(&DA_INDEX(ans_sec,0), name, 0, 0, (aa && qtype==QT_ALL)?DF_AUTH:0 DBG1)) { rv=RC_FATALERR; /* unrecoverable error */ goto <API key>; } /* Now read the answer, authority and additional sections, storing the results in the arrays ans_sec,auth_sec and add_sec. */ numoptrr=0; rv=rrs2cent((unsigned char *)st->recvbuf, st->recvl, &rrp, &lcnt, ntohs(st->recvbuf->ancount), flags, queryts, &ans_sec, &numoptrr, &ednsinfo); #if DEBUG>0 if(numoptrr!=0) { DEBUG_MSG("Answer section in reply contains %d OPT pseudo-RRs!\n", numoptrr); } #endif numoptrr=0; if(rv==RC_OK) { uint16_t nscount=ntohs(st->recvbuf->nscount); if (nscount) { rv=rrs2cent((unsigned char *)st->recvbuf, st->recvl, &rrp, &lcnt, nscount, flags|CF_ADDITIONAL, queryts, &auth_sec, &numoptrr, &ednsinfo); #if DEBUG>0 if(numoptrr!=0) { DEBUG_MSG("Authority section in reply contains %d OPT pseudo-RRs!\n", numoptrr); } #endif } } numoptrr=0; if(rv==RC_OK) { uint16_t arcount=ntohs(st->recvbuf->arcount); if (arcount) { rv=rrs2cent((unsigned char *)st->recvbuf, st->recvl, &rrp, &lcnt, arcount, flags|CF_ADDITIONAL, queryts, &add_sec, &numoptrr, &ednsinfo); if(numoptrr!=0) { #if DEBUG>0 if(numoptrr!=1) { DEBUG_MSG("Additional section in reply contains %d OPT pseudo-RRs!\n", numoptrr); } DEBUG_PDNSDA_MSG("Reply from %s contains OPT pseudosection: EDNS version = %u, udp size = %u, flag DO=%u\n", PDNSDA2STR(PDNSD_A(st)), ednsinfo.version, ednsinfo.udpsize, ednsinfo.do_flg); #endif if(rcode!=ednsinfo.rcode) { DEBUG_PDNSDA_MSG("Reply from %s contains unexpected EDNS rcode %u (%s)!\n", PDNSDA2STR(PDNSD_A(st)), ednsinfo.rcode, get_ename(ednsinfo.rcode)); rcode=ednsinfo.rcode; /* Mark as failed, but use answer tentatively. */ if(!st->failed) st->failed=1; } } } } if(!(rv==RC_OK || (rv==RC_TRUNC && st->recvbuf->tc))) { DEBUG_PDNSDA_MSG(rv==RC_FORMAT?"Format error in reply from %s.\n": rv==RC_TRUNC?"Format error in reply from %s (message unexpectedly truncated).\n": rv==RC_SERVFAIL?"Inconsistent timestamps in reply from %s.\n": "Out of memory while processing reply from %s.\n", PDNSDA2STR(PDNSD_A(st))); if(rv==RC_SERVFAIL) { /* Inconsistent ttl timestamps and we are enforcing strict RFC 2181 compliance. Mark as failed, but use answer tentatively. */ if(!st->failed) st->failed=1; } else { if(rv!=RC_FATALERR) rv=RC_SERVFAIL; goto <API key>; } } { /* Remember references to NS and SOA records in the answer or authority section so that we can add this information to our own reply. */ int i,n=DA_NEL(ans_sec); for(i=0;i<n;++i) { dns_cent_t *cent=&DA_INDEX(ans_sec,i); unsigned scnt=rhnsegcnt(cent->qname); if(getrrset_NS(cent)) cent->c_ns=scnt; if(getrrset_SOA(cent)) cent->c_soa=scnt; if((qtype>=QT_MIN && qtype<=QT_MAX) || (/* (qtype>=T_MIN && qtype<=T_MAX) && */ getrrset(cent,qtype)) || (n==1 && cent->num_rrs==0)) { /* Match this name with names in the authority section */ int j,m=DA_NEL(auth_sec); for(j=0;j<m;++j) { dns_cent_t *ce=&DA_INDEX(auth_sec,j); unsigned int ml,rem; ml=domain_match(ce->qname,cent->qname, &rem, NULL); if(rem==0 && /* Don't accept records for the root domain from name servers that were not listed in the configuration file. */ (ml || st->auth_serv!=2)) { if(getrrset_NS(ce)) { if(cent->c_ns==cundef || cent->c_ns<ml) cent->c_ns=ml; } if(getrrset_SOA(ce)) { if(cent->c_soa==cundef || cent->c_soa<ml) cent->c_soa=ml; } } } } } } /* Check whether the answer contains an IP address that should be rejected. */ if(have_rejectlist(st)) { int i; int na4=nreject_a4(st); addr4maskpair_t *a4arr=rejectlist_a4(st); #if ALLOW_LOCAL_AAAA int na6=nreject_a6(st); addr6maskpair_t *a6arr=rejectlist_a6(st); #endif /* Check addresses in the answer, authority and additional sections. */ for(i=0;i<3;++i) { dns_cent_array sec=secs[i]; int j,nce=DA_NEL(sec); for(j=0;j<nce;++j) { dns_cent_t *cent=&DA_INDEX(sec,j); rr_set_t *rrset=getrrset_A(cent); if(rrset && na4) { /* This is far from the world's most efficient matching algorithm, but it should work OK as long as the numbers involved are small. */ rr_bucket_t *rr; for(rr=rrset->rrs; rr; rr=rr->next) { struct in_addr *a=(struct in_addr *)(rr->data); int k; for(k=0;k<na4;++k) { addr4maskpair_t *am = &a4arr[k]; if(ADDR4MASK_EQUIV(a,&am->a,&am->mask)) { #if DEBUG>0 unsigned char nmbuf[DNSNAMEBUFSIZE]; char abuf[ADDRSTR_MAXLEN]; DEBUG_PDNSDA_MSG("Rejecting answer from server %s because it contains an A record" " for \"%s\" with an address in the reject list: %s\n", PDNSDA2STR(PDNSD_A(st)), rhn2str(cent->qname,nmbuf,sizeof(nmbuf)), inet_ntop(AF_INET,a,abuf,sizeof(abuf))); #endif reject_ans=1; goto <API key>; } } } } #if ALLOW_LOCAL_AAAA rrset=getrrset_AAAA(cent); if(rrset && na6) { rr_bucket_t *rr; for(rr=rrset->rrs; rr; rr=rr->next) { struct in6_addr *a=(struct in6_addr *)(rr->data); int k; for(k=0;k<na6;++k) { addr6maskpair_t *am = &a6arr[k]; if(ADDR6MASK_EQUIV(a,&am->a,&am->mask)) { #if DEBUG>0 unsigned char nmbuf[DNSNAMEBUFSIZE]; char abuf[INET6_ADDRSTRLEN]; DEBUG_PDNSDA_MSG("Rejecting answer from server %s because it contains an AAAA record" " for \"%s\" with an address in the reject list: %s\n", PDNSDA2STR(PDNSD_A(st)), rhn2str(cent->qname,nmbuf,sizeof(nmbuf)), inet_ntop(AF_INET6,a,abuf,sizeof(abuf))); #endif reject_ans=1; goto <API key>; } } } } #endif } } <API key>:; } /* negative caching for domains */ if (rcode==RC_NAMEERR) { DEBUG_PDNSDA_MSG("Server %s returned error code: %s\n", PDNSDA2STR(PDNSD_A(st)),get_ename(rcode)); name_error: neg_ans=1; { /* We did not get what we wanted. Cache according to policy */ dns_cent_t *ent=&DA_INDEX(ans_sec,0); int neg_domain_pol=global.neg_domain_pol; if (neg_domain_pol==C_ON || (neg_domain_pol==C_AUTH && st->aa)) { time_t ttl=global.neg_ttl; /* Try to find a SOA record that came with the reply. */ if(ent->c_soa!=cundef) { unsigned scnt=rhnsegcnt(name); dns_cent_t *cent; if(ent->c_soa<scnt && (cent=lookup_cent_array(auth_sec,skipsegs(name,scnt-ent->c_soa)))) { rr_set_t *rrset=getrrset_SOA(cent); if (rrset && rrset->rrs) { time_t min=soa_minimum(rrset->rrs); ttl=rrset->ttl; if(ttl>min) ttl=min; } } } DEBUG_RHN_MSG("Caching domain %s negative with ttl %li\n",RHN2STR(name),(long)ttl); negate_cent(ent,ttl,queryts); if(st->nocache) ent->flags |= DF_NOCACHE; goto cleanup_return_OK; } else { if(c_soa) *c_soa=ent->c_soa; free_cent(ent DBG1); rv=RC_NAMEERR; goto add_additional; } } } if(reject_ans) { if(reject_policy(st)==C_NEGATE && st->failed<=1) goto name_error; else { rv=RC_SERVFAIL; goto <API key>; } } if(global.deleg_only_zones && st->auth_serv<3) { /* st->auth_serv==3 means this server is a root-server. */ int missingdelegation,authcnt; /* The deleg_only_zones data may change due to runtime reconfiguration, therefore use locks. */ lock_server_data(); missingdelegation=0; authcnt=0; { int i,n=DA_NEL(global.deleg_only_zones); unsigned rem,zrem; for(i=0;i<n;++i) { if(domain_match(name,DA_INDEX(global.deleg_only_zones,i),&rem,&zrem) && zrem==0) goto zone_match; } goto delegation_OK; zone_match: /* The name queried matches a delegation-only zone. */ if(rem) { /* Check if we can find delegation in the answer or authority section. */ /* dns_cent_array secs[2]={ans_sec,auth_sec}; */ int j; for(j=0;j<2;++j) { dns_cent_array sec=secs[j]; int k,m=DA_NEL(sec); for(k=0;k<m;++k) { dns_cent_t *ce=&DA_INDEX(sec,k); if(getrrset_NS(ce) || getrrset_SOA(ce)) { /* Found a NS or SOA record in the answer or authority section. */ int l; ++authcnt; for(l=0;l<n;++l) { if(domain_match(ce->qname,DA_INDEX(global.deleg_only_zones,l),&rem,&zrem) && zrem==0) { if(rem) break; else goto try_next_auth; } } goto delegation_OK; } try_next_auth:; } } #if DEBUG>0 { unsigned char nmbuf[DNSNAMEBUFSIZE],zbuf[DNSNAMEBUFSIZE]; DEBUG_PDNSDA_MSG(authcnt?"%s is in %s zone, but no delegation found in answer returned by server %s\n" :"%s is in %s zone, but no authority information provided by server %s\n", rhn2str(name,nmbuf,sizeof(nmbuf)), rhn2str(DA_INDEX(global.deleg_only_zones,i),zbuf,sizeof(zbuf)), PDNSDA2STR(PDNSD_A(st))); } #endif missingdelegation=1; } delegation_OK:; } unlock_server_data(); if(missingdelegation) { if(authcnt && st->failed<=1) { /* Treat this as a nonexistant name. */ goto name_error; } else if(st->auth_serv<2) { /* If this is one of the servers obtained from the list pdnsd was configured with, treat this as a failure. Hopefully one of the other servers in the list will return a non-empty authority section. */ rv=RC_SERVFAIL; goto <API key>; } } } { /* Negative caching of rr sets */ dns_cent_t *ent=&DA_INDEX(ans_sec,0); if(!ent->num_rrs) neg_ans=1; if (thint>=T_MIN && thint<=T_MAX && !getrrset(ent,thint) && !st->tc && st->failed<=1) { /* We did not get what we wanted. Cache according to policy */ int neg_rrs_pol=global.neg_rrs_pol; if (neg_rrs_pol==C_ON || (neg_rrs_pol==C_AUTH && aa) || (neg_rrs_pol==C_DEFAULT && (aa || st->ra))) { time_t ttl=global.neg_ttl; rr_set_t *rrset=getrrset_SOA(ent); dns_cent_t *cent; unsigned scnt; /* If we received a SOA, we should take the ttl of that record. */ if ((rrset && rrset->rrs) || /* Try to find a SOA record higher up the hierarchy that came with the reply. */ ((cent=lookup_cent_array(auth_sec, (ent->c_soa!=cundef && ent->c_soa<(scnt=rhnsegcnt(name)))? skipsegs(name,scnt-ent->c_soa): name)) && (rrset=getrrset_SOA(cent)) && rrset->rrs)) { time_t min=soa_minimum(rrset->rrs); ttl=rrset->ttl; if(ttl>min) ttl=min; } DEBUG_RHN_MSG("Caching type %s for domain %s negative with ttl %li\n",getrrtpname(thint),RHN2STR(name),(long)ttl); if (!<API key>(ent, thint, ttl, queryts, CF_NEGATIVE|flags DBG1)) { rv=RC_FATALERR; goto <API key>; } } } } if (st->failed<=1) { /* The domain names of all name servers found in the answer and authority sections are placed in *ns, which is automatically grown. */ /* dns_cent_array secs[2]={ans_sec,auth_sec}; */ int i; for(i=0;i<2;++i) { dns_cent_array sec=secs[i]; int j,n=DA_NEL(sec); for(j=0;j<n;++j) { dns_cent_t *cent=&DA_INDEX(sec,j); unsigned int rem; /* Don't accept records for the root domain from name servers that were not listed in the configuration file. */ if((*(cent->qname) || st->auth_serv!=2) && /* Don't accept possibly poisoning nameserver entries in paranoid mode */ (st->trusted || !st->nsdomain || (domain_match(st->nsdomain, cent->qname, &rem,NULL),rem==0)) && /* The following test is actually redundant and should never fail. */ *(cent->qname)!=0xff) { /* Some nameservers obviously choose to send SOA records instead of NS ones. * Although I think that this is poor behaviour, we'll have to work around that. */ static const unsigned short nstypes[2]={T_NS,T_SOA}; int k; for(k=0;k<2;++k) { rr_set_t *rrset=getrrset(cent,nstypes[k]); if(rrset) { rr_bucket_t *rr; unsigned short first=1; for(rr=rrset->rrs; rr; rr=rr->next) { size_t sz1,sz2; unsigned char *p; /* Skip duplicate records */ for(p=dlist_first(*ns); p; p=dlist_next(p)) { if(rhnicmp(*p==0xff?p+1:skiprhn(p),(unsigned char *)(rr->data))) goto next_nsr; } /* add to the nameserver list. Here we use a little compression trick: if the first byte of a name is 0xff, this means repeat the previous name. */ sz1= (first?rhnlen(cent->qname):1); sz2=rhnlen((unsigned char *)(rr->data)); if (!(*ns=dlist_grow(*ns,sz1+sz2))) { rv=RC_FATALERR; goto <API key>; } p=dlist_last(*ns); if(first) { first=0; p=mempcpy(p,cent->qname,sz1); } else *p++ = 0xff; /* 0xff means 'idem' */ /* This will only copy the first name, which is the NS */ memcpy(p,(unsigned char *)(rr->data),sz2); ++num_ns; next_nsr:; } } } } } } } cleanup_return_OK: if(st->failed && neg_ans && num_ns==0) { DEBUG_PDNSDA_MSG("Answer from server %s does not contain usable records.\n", PDNSDA2STR(PDNSD_A(st))); rv=RC_SERVFAIL; goto <API key>; } if(!(*entp=malloc(sizeof(dns_cent_t)))) { rv=RC_FATALERR; goto <API key>; } **entp=DA_INDEX(ans_sec,0); rv=RC_OK; add_additional: if (!st->failed && !reject_ans) { /* Add the additional RRs to the cache. */ /* dns_cent_array secs[3]={ans_sec,auth_sec,add_sec}; */ int i; #if DEBUG>0 if(debug_p && neg_ans) { int j,n=DA_NEL(ans_sec); for(j=1; j<n; ++j) { unsigned char nmbuf[DNSNAMEBUFSIZE],nmbuf2[DNSNAMEBUFSIZE]; DEBUG_PDNSDA_MSG("Reply from %s is negative for %s, dropping record(s) for %s in answer section.\n", PDNSDA2STR(PDNSD_A(st)), rhn2str(name,nmbuf,sizeof(nmbuf)), rhn2str(DA_INDEX(ans_sec,j).qname,nmbuf2,sizeof(nmbuf2))); } } #endif for(i=neg_ans; i<3; ++i) { dns_cent_array sec=secs[i]; int j,n=DA_NEL(sec); /* The first entry in the answer section is treated separately, so skip that one. */ for(j= !i; j<n; ++j) { dns_cent_t *cent=&DA_INDEX(sec,j); if(*(cent->qname) || st->auth_serv!=2) { unsigned int rem; if(st->trusted || !st->nsdomain || (domain_match(st->nsdomain, cent->qname, &rem, NULL),rem==0)) add_cache(cent); else { #if DEBUG>0 unsigned char nmbuf[DNSNAMEBUFSIZE],nsbuf[DNSNAMEBUFSIZE]; DEBUG_MSG("Record for %s not in nsdomain %s; dropped.\n", rhn2str(cent->qname,nmbuf,sizeof(nmbuf)),rhn2str(st->nsdomain,nsbuf,sizeof(nsbuf))); #endif } } else { #if DEBUG>0 static const char *const secname[3]={"answer","authority","additional"}; DEBUG_PDNSDA_MSG("Record(s) for root domain in %s section from %s dropped.\n", secname[i],PDNSDA2STR(PDNSD_A(st))); #endif } } } } goto <API key>; <API key>: dlist_free(*ns); *ns=NULL; <API key>: if(DA_NEL(ans_sec)>=1) free_cent(&DA_INDEX(ans_sec,0) DBG1); <API key>: { /* dns_cent_array secs[3]={ans_sec,auth_sec,add_sec}; */ int i; for(i=0;i<3;++i) { dns_cent_array sec=secs[i]; int j,n=DA_NEL(sec); /* The first entry in the answer section is treated separately, so skip that one. */ for(j= !i; j<n; ++j) free_cent(&DA_INDEX(sec,j) DBG1); da_free(sec); } } #undef ans_sec #undef auth_sec #undef add_sec } free_recvbuf_return: pdnsd_free(st->recvbuf); return rv; } /* * Cancel a query, freeing all resources. Any query state is valid as input (this may even be called * if a call to p_exec_query already returned error or success) */ static void p_cancel_query(query_stat_t *st) { switch (st->state) { QS_WRITE_CASES: QS_READ_CASES: #ifdef WIN32 closesocket(st->sock); #else close(st->sock); #endif /* fall through */ case QS_TCPINITIAL: case QS_UDPINITIAL: pdnsd_free(st->recvbuf); pdnsd_free(st->msg); } if(st->state!=QS_INITIAL && st->state!=QS_DONE) st->state=QS_CANCELED; } #if 0 /* * Initialize a query_serv_t (server list for parallel query) * This is there for historical reasons only. */ inline static void init_qserv(query_stat_array *q) { *q=NULL; } #endif /* * Add a server entry to a query_serv_t * Note: only a reference to nsdomain is copied, not the name itself. * Be sure to free the q-list before freeing the name. */ static int add_qserv(query_stat_array *q, pdnsd_a2 *a, int port, time_t timeout, unsigned flags, char nocache, char lean_query, char edns_query, char auth_s, char needs_testing, char trusted, const unsigned char *nsdomain, rejectlist_t *rejectlist) { query_stat_t *qs; if ((*q=DA_GROW1(*q))==NULL) { DEBUG_MSG("Out of memory in add_qserv()\n"); return 0; } qs=&DA_LAST(*q); #ifdef ENABLE_IPV4 if (run_ipv4) { memset(&qs->a.sin4,0,sizeof(qs->a.sin4)); qs->a.sin4.sin_family=AF_INET; qs->a.sin4.sin_port=htons(port); qs->a.sin4.sin_addr=a->ipv4; SET_SOCKA_LEN4(qs->a.sin4); } #endif #ifdef ENABLE_IPV6 ELSE_IPV6 { memset(&qs->a.sin6,0,sizeof(qs->a.sin6)); qs->a.sin6.sin6_family=AF_INET6; qs->a.sin6.sin6_port=htons(port); qs->a.sin6.sin6_flowinfo=IPV6_FLOWINFO; qs->a.sin6.sin6_addr=a->ipv6; SET_SOCKA_LEN6(qs->a.sin6); qs->a4fallback=a->ipv4; } #endif qs->timeout=timeout; qs->flags=flags; qs->nocache=nocache; qs->auth_serv=auth_s; qs->lean_query=lean_query; qs->edns_query=edns_query; qs->needs_testing=needs_testing; qs->trusted=trusted; qs->aa=0; qs->tc=0; qs->ra=0; qs->failed=0; qs->nsdomain=nsdomain; /* Note: only a reference is copied, not the name itself! */ qs->rejectlist=rejectlist; qs->state=QS_INITIAL; qs->qm=global.query_method; qs->s_errno=0; return 1; } /* Test whether two pdnsd_a2 addresses are the same. */ inline __attribute__((always_inline)) static int same_inaddr2_2(pdnsd_a2 *a, pdnsd_a2 *b) { return SEL_IPVER( a->ipv4.s_addr==b->ipv4.s_addr, IN6_ARE_ADDR_EQUAL(&a->ipv6,&b->ipv6) && a->ipv4.s_addr==b->ipv4.s_addr ); } /* This can be used to check whether a server address was already used in a previous query_stat_t entry. */ inline static int <API key>(query_stat_t *qs, pdnsd_a2 *b) { return SEL_IPVER( qs->a.sin4.sin_addr.s_addr==b->ipv4.s_addr, IN6_ARE_ADDR_EQUAL(&qs->a.sin6.sin6_addr,&b->ipv6) && qs->a4fallback.s_addr==b->ipv4.s_addr ); } /* * Free resources used by a query_serv_t * There for historical reasons only. */ inline static void del_qserv(query_stat_array q) { da_free(q); } struct qstatnode_s { query_stat_array qa; struct qstatnode_s *next; }; typedef struct qstatnode_s qstatnode_t; struct qhintnode_s { const unsigned char *nm; int tp; struct qhintnode_s *next; }; /* typedef struct qhintnode_s qhintnode_t; */ /* Already defined in dns_query.h */ static int auth_ok(query_stat_array q, const unsigned char *name, int thint, dns_cent_t *ent, int hops, qstatnode_t *qslist, qhintnode_t *qhlist, query_stat_t *qse, dlist ns, query_stat_array *serv); static int <API key>(query_stat_array q, const unsigned char *name, int thint, dns_cent_t **cachedp, int hops, qstatnode_t *qslist, qhintnode_t *qhlist, time_t queryts, unsigned char *c_soa); static int <API key>(atup_array atup_a, int port, char edns_query, time_t timeout, const unsigned char *name, int thint, dns_cent_t **cachedp); /* * Performs a semi-parallel query on the servers in q. PAR_QUERIES are executed parallel at a time. * name is the query name in dns protocol format (number.string etc), * ent is the dns_cent_t that will be filled. * hops is the number of recursions left. * qslist should refer to a list of server arrays used higher up in the calling chain. This way we can * avoid name servers that have already been tried for this name. * qhlist should refer to a list of names that we are trying to resolve higher up in the calling chain. * These names should be avoided further down the chain, or we risk getting caught in a wasteful cycle. * thint is a hint on the requested query type used to decide whether an aa record must be fetched * or a non-authoritative answer will be enough. * * nocache is needed because we add AA records to the cache. If the nocache flag is set, we do not * take the original values for the record, but flags=0 and ttl=0 (but only if we do not already have * a cached record for that set). These settings cause the record be purged on the next cache addition. * It will also not be used again. * * The return value of p_recursive_query() has the same meaning as that of <API key>() * (see below). */ static int p_recursive_query(query_stat_array q, const unsigned char *name, int thint, dns_cent_t **entp, int *nocache, int hops, qstatnode_t *qslist, qhintnode_t *qhlist, unsigned char *c_soa) { dns_cent_t *ent,*entsave=NULL; int i,j,k; int rv=RC_SERVFAIL; int qualval=0; query_stat_t *qse=NULL; /* Initialized to inhibit compiler warning */ dlist ns=NULL,nssave=NULL; query_stat_array serv=NULL,servsave=NULL; # define W_AUTHOK 8 # define W_NOTFAILED 2 # define W_NOTTRUNC 1 # define NOTFAILMASK 6 # define GOODQUAL (W_AUTHOK+3*W_NOTFAILED) # define save_query_result(ent,qs,ns,serv,authok) \ { \ int qval = authok*W_AUTHOK + (3-qs->failed)*W_NOTFAILED + (!qs->tc)*W_NOTTRUNC; \ if(entsave && qval>qualval) { \ /* Free the old copy, because the new result is better. */ \ free_cent(entsave DBG1); \ pdnsd_free(entsave); \ entsave=NULL; \ del_qserv(servsave); \ dlist_free(nssave); \ } \ if(!entsave) { \ entsave=ent; \ servsave=serv; \ /* The serv array contains references to data within the ns list, \ so we need to save a copy of the ns list as well! */ \ if(DA_NEL(serv)>0) nssave=ns; else {nssave=NULL;dlist_free(ns);} \ qualval=qval; \ qse=qs; \ } \ else { \ /* We already have a copy, free the present one. */ \ free_cent(ent DBG1); \ pdnsd_free(ent); \ del_qserv(serv); \ dlist_free(ns); \ } \ serv=NULL; \ ns=NULL; \ } { time_t ts0=time(NULL),global_timeout=global.timeout; int dc=0,mc=0,nq=DA_NEL(q),parqueries=global.par_queries; for (j=0; j<nq; j += parqueries) { mc=j+parqueries; if (mc>nq) mc=nq; /* First, call p_exec_query once for each parallel set to initialize. * Then, as long as not all have the state QS_DONE or we have a timeout, * build a poll/select set for all active queries and call them accordingly. */ for (i=dc;i<mc;i++) { query_stat_t *qs=&DA_INDEX(q,i); if(i>=j) { /* The below should not happen any more, but may once again * (immediate success) */ DEBUG_PDNSDA_MSG("Sending query to %s\n", PDNSDA2STR(PDNSD_A(qs))); retryquery: rv=p_exec_query(&ent, name, thint, qs,&ns,c_soa); if (rv==RC_OK) { int authok; DEBUG_PDNSDA_MSG("Query to %s succeeded.\n", PDNSDA2STR(PDNSD_A(qs))); if((authok=auth_ok(q, name, thint, ent, hops, qslist, qhlist, qs, ns, &serv))) { if(authok>=0) { if(!qs->failed #if !defined(NO_TCP_QUERIES) && !defined(NO_UDP_QUERIES) && !(qs->qm==UDP_TCP && qs->tc) #endif ) { qse=qs; mc=i; /* No need to cancel queries beyond i */ goto done; } } else { mc=i; /* No need to cancel queries beyond i */ goto <API key>; } } /* We do not have a satisfactory answer. However, we will save a copy in case none of the other servers in the q list give a satisfactory answer either. */ save_query_result(ent,qs,ns,serv,authok); #if !defined(NO_TCP_QUERIES) && !defined(NO_UDP_QUERIES) if(qs->qm==UDP_TCP && qs->tc) { switch_to_tcp(qs); DEBUG_PDNSDA_MSG("Reply from %s was truncated. Trying again using TCP.\n", PDNSDA2STR(PDNSD_A(qs))); goto retryquery; } #endif } else if (rv==RC_NAMEERR || rv==RC_FATALERR) { mc=i; /* No need to cancel queries beyond i */ goto done; } } if (qs->state==QS_DONE && i==dc) dc++; } if (dc<mc) { time_t ts,maxto,now; int pc,nevents; #ifdef NO_POLL int maxfd; fd_set reads; fd_set writes; struct timeval tv; #else int ic; struct pollfd polls[mc-dc]; /* Variable length array, may cause portability problems */ #endif /* we do time keeping by hand, because poll/select might be interrupted and * the returned times are not always to be trusted upon */ ts=time(NULL); do { /* build poll/select sets, maintain time. * If you do parallel queries, the highest timeout will be honored * also for the other servers when their timeout is exceeded and * the highest is not. * Changed by Paul Rombouts: queries are not canceled until we receive * a useful reply or everything has failed or timed out (also taking into * account the global timeout option). * Thus in the worst case all the queries in the q list will be active * simultaneously. The downside is that we may be wasting more resources * this way. The advantage is that we have a greater chance of catching a * reply. After all, if we wait longer anyway, why not for more servers. */ maxto=0; pc=0; rv=RC_SERVFAIL; #ifdef NO_POLL FD_ZERO(&reads); FD_ZERO(&writes); maxfd=0; #endif for (i=dc;i<mc;i++) { query_stat_t *qs=&DA_INDEX(q,i); if (qs->state!=QS_DONE) { if (i>=j && qs->timeout>maxto) maxto=qs->timeout; #ifdef NO_POLL # ifndef WIN32 if (qs->sock>maxfd) { maxfd=qs->sock; PDNSD_ASSERT(maxfd<FD_SETSIZE,"socket file descriptor exceeds FD_SETSIZE."); } # endif switch (qs->state) { QS_READ_CASES: FD_SET(qs->sock,&reads); break; QS_WRITE_CASES: FD_SET(qs->sock,&writes); break; } #else polls[pc].fd=qs->sock; switch (qs->state) { QS_READ_CASES: polls[pc].events=POLLIN; break; QS_WRITE_CASES: polls[pc].events=POLLOUT; break; default: polls[pc].events=0; } #endif pc++; } } if (pc==0) { /* In this case, ALL are done and we do not need to cancel any * query. */ dc=mc; break; } now=time(NULL); maxto -= now-ts; if (mc==nq) { #if !defined(NO_TCP_QUERIES) && !defined(NO_UDP_QUERIES) /* Don't use the global timeout if there are TCP queries we might want to retry using UDP. */ for (i=j;i<mc;i++) { query_stat_t *qs=&DA_INDEX(q,i); if(tentative_tcp_query(qs)) goto skip_globto; } #endif { time_t globto=global_timeout-(now-ts0); if(globto>maxto) maxto=globto; } #if !defined(NO_TCP_QUERIES) && !defined(NO_UDP_QUERIES) skip_globto:; #endif } #ifdef NO_POLL tv.tv_sec=(maxto>0)?maxto:0; tv.tv_usec=0; nevents=select(maxfd+1,&reads,&writes,NULL,&tv); #else nevents=poll(polls,pc,(maxto>0)?(maxto*1000):0); #endif if (nevents<0) { /* if(errno==EINTR) continue; */ #ifdef WIN32 log_warn("select failed: %d",WSAGetLastError()); #else log_warn("poll/select failed: %s",strerror(errno)); #endif goto done; } if (nevents==0) { /* We have timed out. Mark the unresponsive servers so that we can consider them for retesting later on. We will continue to listen for replies from these servers as long as we have additional servers to try. */ for (i=j;i<mc;i++) { query_stat_t *qs=&DA_INDEX(q,i); if (qs->state!=QS_DONE && qs->needs_testing) qs->needs_testing=2; #if !defined(NO_TCP_QUERIES) && !defined(NO_UDP_QUERIES) if (tentative_tcp_query(qs)) { /* We timed out while waiting for a TCP connection. Try again using UDP. */ # ifdef WIN32 closesocket(qs->sock); # else close(qs->sock); # endif switch_to_udp(qs); DEBUG_PDNSDA_MSG("TCP connection to %s timed out. Trying to use UDP.\n", PDNSDA2STR(PDNSD_A(qs))); rv=p_exec_query(&ent, name, thint, qs,&ns,c_soa); /* In the unlikely case of immediate success */ if (rv==RC_OK) { int authok; DEBUG_PDNSDA_MSG("Query to %s succeeded.\n", PDNSDA2STR(PDNSD_A(qs))); if((authok=auth_ok(q, name, thint, ent, hops, qslist, qhlist, qs, ns, &serv))) { if(authok>=0) { if(!qs->failed) { qse=qs; goto done; } } else goto <API key>; } save_query_result(ent,qs,ns,serv,authok); } else if (rv==RC_NAMEERR || rv==RC_FATALERR) { goto done; } ++nevents; } #endif } #if !defined(NO_TCP_QUERIES) && !defined(NO_UDP_QUERIES) if (mc==nq) { /* We will not try additional servers, but we might want to try again using UDP instead of TCP */ if(nevents && (time(NULL)-ts0)<global_timeout) continue; } #endif break; } #ifndef NO_POLL ic=0; #endif for (i=dc;i<mc;i++) { query_stat_t *qs=&DA_INDEX(q,i); /* Check if we got a poll/select event */ if (qs->state!=QS_DONE) { int srv_event=0; /* This detection may seem suboptimal, but normally, we have at most 2-3 parallel * queries, and anything else would be higher overhead, */ #ifdef NO_POLL switch (qs->state) { QS_READ_CASES: srv_event=FD_ISSET(qs->sock,&reads); break; QS_WRITE_CASES: srv_event=FD_ISSET(qs->sock,&writes); break; } #else do { PDNSD_ASSERT(ic<pc, "file descriptor not found in poll() array"); k=ic++; } while(polls[k].fd!=qs->sock); /* * In case of an error, reenter the state machine * to catch it. */ switch (qs->state) { QS_READ_CASES: srv_event=polls[k].revents&(POLLIN|POLLERR|POLLHUP|POLLNVAL); break; QS_WRITE_CASES: srv_event=polls[k].revents&(POLLOUT|POLLERR|POLLHUP|POLLNVAL); break; } #endif if (srv_event) { --nevents; retryquery2: rv=p_exec_query(&ent, name, thint, qs,&ns,c_soa); if (rv==RC_OK) { int authok; DEBUG_PDNSDA_MSG("Query to %s succeeded.\n", PDNSDA2STR(PDNSD_A(qs))); if((authok=auth_ok(q, name, thint, ent, hops, qslist, qhlist, qs, ns, &serv))) { if(authok>=0) { if(!qs->failed #if !defined(NO_TCP_QUERIES) && !defined(NO_UDP_QUERIES) && !(qs->qm==UDP_TCP && qs->tc) #endif ) { qse=qs; goto done; } } else goto <API key>; } save_query_result(ent,qs,ns,serv,authok); #if !defined(NO_TCP_QUERIES) && !defined(NO_UDP_QUERIES) if(qs->qm==UDP_TCP && qs->tc) { switch_to_tcp(qs); DEBUG_PDNSDA_MSG("Reply from %s was truncated. Trying again using TCP.\n", PDNSDA2STR(PDNSD_A(qs))); goto retryquery2; } #endif } else if (rv==RC_NAMEERR || rv==RC_FATALERR) { goto done; } } } /* recheck, this might have changed after the last p_exec_query */ if (qs->state==QS_DONE && i==dc) dc++; } if(nevents>0) { /* We have not managed to handle all the events reported by poll/select. Better call it quits, or we risk getting caught in a wasteful cycle. */ if(++poll_errs<=MAXPOLLERRS) log_error("%d unhandled poll/select event(s) in p_recursive_query() at %s, line %d.",nevents,__FILE__,__LINE__); rv=RC_SERVFAIL; goto done; } } while (dc<mc); } } goto cancel_queries; <API key>: free_cent(ent DBG1); pdnsd_free(ent); rv=RC_FATALERR; done: if (entsave) { /* We have or will get an authoritative answer, or we have encountered an error. Free the non-authoritative answer. */ free_cent(entsave DBG1); pdnsd_free(entsave); entsave=NULL; del_qserv(servsave); dlist_free(nssave); } cancel_queries: /* Cancel any remaining queries. */ for (i=dc;i<mc;i++) p_cancel_query(&DA_INDEX(q,i)); { /* See if any servers need to be retested for availability. We build up a list of addresses rather than call sched_server_test() separately for each address to reduce the overhead caused by locking and signaling */ int n=0; for (i=0;i<mc;i++) if (DA_INDEX(q,i).needs_testing > 1) ++n; if(n>0) { pdnsd_a addrs[n]; /* variable length array */ k=0; for (i=0;i<mc;i++) { query_stat_t *qs=&DA_INDEX(q,i); if (qs->needs_testing > 1) addrs[k++]= *PDNSD_A(qs); } sched_server_test(addrs,n,-1); } } } if(entsave) { /* * If we didn't get rrs from any of the authoritative servers, or the answers were * unsatisfactory for another reason, take the one we had. * However, raise the CF_NOCACHE flag, so that it won't be used again (outside the * cache latency period). */ DEBUG_PDNSDA_MSG("Using %s reply from %s.\n", !(qualval&NOTFAILMASK)? "reportedly failed": !(qualval&W_NOTFAILED)? "inconsistent": !(qualval&W_NOTTRUNC)? "truncated": !(qualval&W_AUTHOK)? "non-authoritative": "good", PDNSDA2STR(PDNSD_A(qse))); ent=entsave; serv=servsave; ns=nssave; if(qualval<GOODQUAL) { if(!(ent->flags&DF_NEGATIVE)) { int jlim= RRARR_LEN(ent); for (j=0; j<jlim; ++j) { rr_set_t *rrs= RRARR_INDEX(ent,j); if (rrs) rrs->flags |= CF_NOCACHE; } } else /* Very unlikely, but not impossible. */ ent->flags |= DF_NOCACHE; } rv=RC_OK; } else if (rv!=RC_OK) { if(rv==RC_FATALERR) { DEBUG_MSG("Unrecoverable error encountered while processing query.\n"); rv=RC_SERVFAIL; } DEBUG_MSG("%sReturning error code \"%s\"\n", rv!=RC_NAMEERR? "No query succeeded. ": "", get_ename(rv)); goto clean_up_return; } if(nocache) *nocache=qse->nocache; if (DA_NEL(serv)>0) { /* Authority records present. Ask them, because the answer was non-authoritative. */ qstatnode_t qsn={q,qslist}; unsigned char save_ns=ent->c_ns,save_soa=ent->c_soa; if(qse->aa || qse->ra) { /* The server claimed to be authoritative or have recursion available, yet we did not completely trust the answer for some reason. We will try to ask the servers in the authority records, but in case we fail, we will save a copy of the answer. */ entsave=ent; } else { free_cent(ent DBG1); pdnsd_free(ent); entsave=NULL; } rv=<API key>(serv, name, thint,&ent,hops-1,&qsn,qhlist,time(NULL),c_soa); if(rv==RC_OK || rv==RC_CACHED || (rv==RC_STALE && !entsave)) { if(save_ns!=cundef && (ent->c_ns==cundef || ent->c_ns<save_ns)) ent->c_ns=save_ns; if(save_soa!=cundef && (ent->c_soa==cundef || ent->c_soa<save_soa)) ent->c_soa=save_soa; goto free_entsave; } else if(rv==RC_NAMEERR) { if(c_soa && save_soa!=cundef && (*c_soa==cundef || *c_soa<save_soa)) *c_soa=save_soa; free_entsave: if(entsave) { free_cent(entsave DBG1); pdnsd_free(entsave); } } else if(entsave) { if(rv==RC_STALE) { free_cent(ent DBG1); pdnsd_free(ent); } DEBUG_PDNSDA_MSG("Using saved reply from %s that claims to %s.\n", PDNSDA2STR(PDNSD_A(qse)), qse->aa? "be authoritative": "have recursion available"); ent=entsave; rv=RC_OK; } } clean_up_return: /* Always free the serv array before freeing the ns list, because the serv array contains references to data within the ns list! */ del_qserv(serv); dlist_free(ns); if(rv==RC_OK || rv==RC_CACHED || rv==RC_STALE) *entp=ent; return rv; # undef save_query_result } /* auth_ok returns 1 if we don't need an authoritative answer or if we can find servers to ask for an authoritative answer. In the latter case these servers will be added to the *serv list. A return value of 0 means the answer is not satisfactory in the previous sense. A return value of -1 indicates an error. */ static int auth_ok(query_stat_array q, const unsigned char *name, int thint, dns_cent_t *ent, int hops, qstatnode_t *qslist, qhintnode_t *qhlist, query_stat_t *qse, dlist ns, query_stat_array *serv) { int retval=0; /* If the answer was obtained from a name server which returned a failure code, the answer is never satisfactory. */ if(qse->failed > 1) return 0; /* Look into the query type hint. If it is a wildcard (QT_*), we need an authoritative answer. Same if there is no record that answers the query. This test will also succeed if we have a negative cached record. This is done purposely. */ #define aa_needed ((thint>=QT_MIN && thint<=QT_MAX) || \ ((thint>=T_MIN && thint<=T_MAX) && \ (!have_rr(ent,thint) && !have_rr_CNAME(ent)))) /* We will want to query authoritative servers if all of the following conditions apply: 1) The server from which we got the answer was not configured as "proxy only". 2) The answer is not a negatively cached domain (i.e. the server did not reply with NXDOMAIN). 3) The query type is a wild card (QT_*), or no record answers the query. 4) The answer that we have is non-authoritative. */ if(!(qse->auth_serv && !(ent->flags&DF_NEGATIVE) && aa_needed)) return 1; if(qse->aa) { /* The reply we have claims to be authoritative. However, I have seen cases where name servers raise the authority flag incorrectly (groan...), so as a work-around, we will check whether the domains for which the servers in the ns list are responsible, match the queried name better than the domain for which the last server was responsible. */ unsigned char *nsdomain; if(!qse->nsdomain) return 1; nsdomain=dlist_first(ns); if(!nsdomain) return 1; for(;;) { unsigned int rem,crem; domain_match(nsdomain,qse->nsdomain,&rem,&crem); if(!(rem>0 && crem==0)) return 1; domain_match(nsdomain,name,&rem,NULL); if(rem!=0) return 1; do { nsdomain=dlist_next(nsdomain); if(!nsdomain) goto done_checkauth; } while(*nsdomain==0xff); /* Skip repeats. */ } done_checkauth:; /* The name servers in the ns list are a better match for the queried name than the server from which we got the last reply, so ignore the aa flag. */ #if DEBUG>0 if(debug_p) { unsigned char dbuf[DNSNAMEBUFSIZE],sdbuf[DNSNAMEBUFSIZE]; nsdomain=dlist_first(ns); DEBUG_PDNSDA_MSG("The name server %s which is responsible for the %s domain, raised the aa flag, but appears to delegate to the sub-domain %s\n", PDNSDA2STR(PDNSD_A(qse)), rhn2str(qse->nsdomain,dbuf,sizeof(dbuf)), rhn2str(nsdomain,sdbuf,sizeof(sdbuf))); } #endif } /* The answer was non-authoritative. Try to build a list of addresses of authoritative servers. */ if (hops>0) { unsigned char *nsdomp, *nsdomain=NULL; rr_set_t *localrrset=NULL; rr_bucket_t *localrr=NULL; for (nsdomp=dlist_first(ns);;) { unsigned char *nsname=NULL; /* Initialize to inhibit compiler warning. */ int nserva, ia, n; pdnsd_a2 serva[MAXNAMESERVIPS]; /* Get next name server. */ if(localrr) { /* Use next locally defined NS record. */ nsname=(unsigned char *)(localrr->data); localrr= localrr->next; } else { if(localrrset) { /* clean up rrset */ del_rrset(localrrset DBG1); localrrset=NULL; } if(!nsdomp) break; else if(*nsdomp!=0xff) { /* New domain. */ nsdomain=nsdomp; if (global.paranoid) { unsigned int rem; /* paranoia mode: don't query name servers that are not responsible */ domain_match(nsdomain,name,&rem,NULL); if (rem!=0) { #if DEBUG>0 unsigned char nmbuf[DNSNAMEBUFSIZE],dbuf[DNSNAMEBUFSIZE],nsbuf[DNSNAMEBUFSIZE]; DEBUG_MSG("The name server %s is responsible for the %s domain, which does not match %s\n", rhn2str(nsname,nsbuf,sizeof(nsbuf)), rhn2str(nsdomain,dbuf,sizeof(dbuf)), rhn2str(name,nmbuf,sizeof(nmbuf))); #endif /* Skip records in ns list for the same domain. */ do { nsdomp=dlist_next(nsdomp); } while (nsdomp && *nsdomp==0xff); continue; } } /* Check if we have locally defined NS records, because they will override the ones provided by remote servers. */ localrrset=<API key>(nsdomain,T_NS); if(localrrset) { /* Skip records in ns list for the same domain. */ do { nsdomp=dlist_next(nsdomp); } while (nsdomp && *nsdomp==0xff); localrr=localrrset->rrs; if(!localrr) continue; nsname=(unsigned char *)(localrr->data); localrr= localrr->next; } else { nsname=skiprhn(nsdomp); nsdomp=dlist_next(nsdomp); } } else { /* domain repeated. */ nsname= nsdomp+1; nsdomp=dlist_next(nsdomp); } } /* look it up in the cache or resolve it if needed. The records received should be in the cache now, so it's ok. */ nserva=0; { const unsigned char *nm=name; int tp=thint; qhintnode_t *ql=qhlist; for(;;) { if(rhnicmp(nm,nsname) && tp==T_A) { DEBUG_RHN_MSG("Not looking up address for name server \"%s\": " "risk of infinite recursion.\n",RHN2STR(nsname)); goto skip_server; } if(!ql) break; nm=ql->nm; tp=ql->tp; ql=ql->next; } { qhintnode_t qhn={name,thint,qhlist}; dns_cent_t *servent; if (<API key>(nsname,T_A, &servent, hops-1, &qhn,time(NULL),NULL)==RC_OK) { #ifdef ENABLE_IPV4 if (run_ipv4) { rr_set_t *rrset=getrrset_A(servent); rr_bucket_t *rrs; if (rrset) for(rrs=rrset->rrs; rrs && nserva<MAXNAMESERVIPS; rrs=rrs->next) serva[nserva++].ipv4 = *((struct in_addr *)rrs->data); } #endif #ifdef ENABLE_IPV6 ELSE_IPV6 { rr_set_t *rrset6=getrrset_AAAA(servent); rr_bucket_t *rrs6= (rrset6? rrset6->rrs: NULL); rr_set_t *rrset4=getrrset_A(servent); rr_bucket_t *rrs4= (rrset4? rrset4->rrs: NULL); while(nserva<MAXNAMESERVIPS) { if(rrs6) { serva[nserva].ipv6 = *((struct in6_addr *)rrs6->data); rrs6=rrs6->next; if (rrs4) { /* Store IPv4 address as fallback. */ serva[nserva].ipv4 = *((struct in_addr *)rrs4->data); rrs4=rrs4->next; } else serva[nserva].ipv4.s_addr=INADDR_ANY; } else if (rrs4) { struct in_addr *ina = (struct in_addr *)rrs4->data; struct in6_addr *in6a = &serva[nserva].ipv6; IPV6_MAPIPV4(ina,in6a); serva[nserva].ipv4.s_addr=INADDR_ANY; rrs4=rrs4->next; } else break; ++nserva; } } #endif free_cent(servent DBG1); pdnsd_free(servent); } } } #if DEBUG>0 if(nserva==0) { DEBUG_RHN_MSG("Looking up address for name server \"%s\" failed.\n",RHN2STR(nsname)); } #endif n=DA_NEL(*serv); for(ia=0; ia<nserva; ++ia) { pdnsd_a2 *pserva= &serva[ia]; int i; if(is_local_addr(PDNSD_A2_TO_A(pserva))) continue; /* Do not use local address (as defined in netdev.c). */ /* Skip duplicate addresses. */ for (i=0; i<n; ++i) { query_stat_t *qs=&DA_INDEX(*serv,i); if (<API key>(qs,pserva)) goto skip_server_addr; } { /* We've got an address. Add it to the list if it wasn't one of the servers we queried. */ query_stat_array qa=q; qstatnode_t *ql=qslist; for(;;) { int i,n=DA_NEL(qa); for (i=0; i<n; ++i) { /* If qa[i].state == QS_DONE, then p_exec_query() has been called, and we should not query this server again */ query_stat_t *qs=&DA_INDEX(qa,i); if (qs->state==QS_DONE && equiv_inaddr2(PDNSD_A(qs),pserva)) { DEBUG_PDNSDA_MSG("Not trying name server %s, already queried.\n", PDNSDA2STR(PDNSD_A2_TO_A(pserva))); goto skip_server_addr; } } if(!ql) break; qa=ql->qa; ql=ql->next; } } /* lean query mode is inherited. CF_AUTH and CF_ADDITIONAL are not (as specified * in CFF_NOINHERIT). */ if (!add_qserv(serv, pserva, 53, qse->timeout, qse->flags&~CFF_NOINHERIT, 0, qse->lean_query,qse->edns_query,2,0,!global.paranoid,nsdomain, inherit_rejectlist(qse)?qse->rejectlist:NULL)) { return -1; } retval=1; skip_server_addr:; } skip_server:; } #if DEBUG>0 if(!retval) { DEBUG_PDNSDA_MSG("No remaining authoritative name servers to try in authority section from %s.\n", PDNSDA2STR(PDNSD_A(qse))); } #endif } else { DEBUG_MSG("Maximum hops count reached; not trying any more name servers.\n"); } return retval; #undef aa_needed } /* * This checks the given name to resolve against the access list given for the server using the * include=, exclude= and policy= parameters. */ static int use_server(servparm_t *s, const unsigned char *name) { int i,n=DA_NEL(s->alist); for (i=0;i<n;i++) { slist_t *sl=&DA_INDEX(s->alist,i); unsigned int nrem,lrem; domain_match(name,sl->domain,&nrem,&lrem); if(!lrem && (!sl->exact || !nrem)) return sl->rule==C_INCLUDED; } if (s->policy==C_SIMPLE_ONLY || s->policy==C_FQDN_ONLY) { if(rhnsegcnt(name)<=1) return s->policy==C_SIMPLE_ONLY; else return s->policy==C_FQDN_ONLY; } return s->policy==C_INCLUDED; } #if ALLOW_LOCAL_AAAA #define serv_has_rejectlist(s) ((s)->reject_a4!=NULL || (s)->reject_a6!=NULL) #else #define serv_has_rejectlist(s) ((s)->reject_a4!=NULL) #endif /* Take the lists of IP addresses from a server section sp and convert them into a form that can be used by p_exec_query(). If successful, add_rejectlist returns a new list which is added to the old list rl, otherwise the return value is NULL. */ static rejectlist_t *add_rejectlist(rejectlist_t *rl, servparm_t *sp) { int i,na4=DA_NEL(sp->reject_a4); addr4maskpair_t *a4p; #if ALLOW_LOCAL_AAAA int na6=DA_NEL(sp->reject_a6); addr6maskpair_t *a6p; #endif rejectlist_t *rlist = malloc(sizeof(rejectlist_t) + na4*sizeof(addr4maskpair_t) #if ALLOW_LOCAL_AAAA + na6*sizeof(addr6maskpair_t) #endif ); if(rlist) { #if ALLOW_LOCAL_AAAA /* Store the larger IPv6 addresses first to avoid possible alignment problems. */ rlist->na6 = na6; a6p = (addr6maskpair_t *)rlist->rdata; for(i=0;i<na6;++i) *a6p++ = DA_INDEX(sp->reject_a6,i); #endif rlist->na4 = na4; #if ALLOW_LOCAL_AAAA a4p = (addr4maskpair_t *)a6p; #else a4p = (addr4maskpair_t *)rlist->rdata; #endif for(i=0;i<na4;++i) *a4p++ = DA_INDEX(sp->reject_a4,i); rlist->policy = sp->rejectpolicy; rlist->inherit = sp->rejectrecursively; rlist->next = rl; } else { DEBUG_MSG("Out of memory in add_rejectlist()\n"); } return rlist; } inline static void free_rejectlist(rejectlist_t *rl) { while(rl) { rejectlist_t *next = rl->next; free(rl); rl=next; } } /* Lookup addresses of nameservers provided by root servers for a given domain in the cache. Returns NULL if unsuccessful (or the cache entries have timed out). */ static addr2_array lookup_ns(const unsigned char *domain) { addr2_array res=NULL; dns_cent_t *cent=lookup_cache(domain,NULL); if(cent) { rr_set_t *rrset=getrrset_NS(cent); if(rrset && (rrset->flags&CF_ROOTSERV) && !timedout(rrset)) { rr_bucket_t *rr; for(rr=rrset->rrs; rr; rr=rr->next) { dns_cent_t *servent=lookup_cache((unsigned char*)(rr->data),NULL); int nserva=0; pdnsd_a2 serva[MAXNAMESERVIPS]; if(servent) { #ifdef ENABLE_IPV4 if (run_ipv4) { rr_set_t *rrset=getrrset_A(servent); rr_bucket_t *rrs; if (rrset && !timedout(rrset)) for(rrs=rrset->rrs; rrs && nserva<MAXNAMESERVIPS; rrs=rrs->next) serva[nserva++].ipv4 = *((struct in_addr *)rrs->data); } #endif #ifdef ENABLE_IPV6 ELSE_IPV6 { rr_set_t *rrset6=getrrset_AAAA(servent); rr_set_t *rrset4=getrrset_A(servent); rr_bucket_t *rrs6=NULL, *rrs4=NULL; if (rrset6 && !(rrset6->flags&CF_NEGATIVE)) { if(!timedout(rrset6)) { rrs6= rrset6->rrs; if (rrs6 && rrset4 && !(rrset4->flags&CF_NEGATIVE)) { if(timedout(rrset4) || !(rrs4=rrset4->rrs)) /* Treat this as a failure. */ rrs6=NULL; } } } else if (rrset4 && !timedout(rrset4)) rrs4= rrset4->rrs; while(nserva<MAXNAMESERVIPS) { if(rrs6) { serva[nserva].ipv6 = *((struct in6_addr *)rrs6->data); rrs6=rrs6->next; if (rrs4) { /* Store IPv4 address as fallback. */ serva[nserva].ipv4 = *((struct in_addr *)rrs4->data); rrs4=rrs4->next; } else serva[nserva].ipv4.s_addr=INADDR_ANY; } else if (rrs4) { struct in_addr *ina = (struct in_addr *)rrs4->data; struct in6_addr *in6a = &serva[nserva].ipv6; IPV6_MAPIPV4(ina,in6a); serva[nserva].ipv4.s_addr=INADDR_ANY; rrs4=rrs4->next; } else break; ++nserva; } } #endif free_cent(servent DBG1); pdnsd_free(servent); } if(nserva==0) { /* Address lookup failed. */ da_free(res); res=NULL; break; } else { int i, j, n=DA_NEL(res); for(i=0; i<nserva; ++i) { pdnsd_a2 *pserva= &serva[i]; /* Skip duplicates */ for (j=0; j<n; ++j) { pdnsd_a2 *pa= &DA_INDEX(res,j); if (same_inaddr2_2(pa,pserva)) goto skip_address; } if(!(res=DA_GROW1(res))) { DEBUG_MSG("Out of memory in lookup_ns()\n"); goto free_cent_return; } DA_LAST(res)= *pserva; skip_address:; } } } } free_cent_return: free_cent(cent DBG1); pdnsd_free(cent); } return res; } /* Find addresses of root servers by looking them up in the cache or querying (non-recursively) the name servers in the list provided. Returns NULL if unsuccessful (or the cache entries have timed out). */ addr2_array <API key>(atup_array atup_a, int port, char edns_query, time_t timeout) { addr2_array res=NULL; dns_cent_t *cent; static const unsigned char rdomain[1]={0}; /* root-domain name. */ int rc; rc=<API key>(atup_a,port,edns_query,timeout,rdomain,T_NS,&cent); if(rc==RC_OK) { rr_set_t *rrset=getrrset_NS(cent); if(rrset) { rr_bucket_t *rr; unsigned nfail=0; for(rr=rrset->rrs; rr; rr=rr->next) { dns_cent_t *servent; int nserva=0; pdnsd_a2 serva[MAXNAMESERVIPS]; rc=<API key>(atup_a,port,edns_query,timeout, (const unsigned char *)(rr->data),T_A,&servent); if(rc==RC_OK) { #ifdef ENABLE_IPV4 if (run_ipv4) { rr_set_t *rrset=getrrset_A(servent); rr_bucket_t *rrs; if (rrset) for(rrs=rrset->rrs; rrs && nserva<MAXNAMESERVIPS; rrs=rrs->next) serva[nserva++].ipv4 = *((struct in_addr *)rrs->data); } #endif #ifdef ENABLE_IPV6 ELSE_IPV6 { rr_set_t *rrset6=getrrset_AAAA(servent); rr_bucket_t *rrs6= (rrset6? rrset6->rrs: NULL); rr_set_t *rrset4=getrrset_A(servent); rr_bucket_t *rrs4= (rrset4? rrset4->rrs: NULL); while(nserva<MAXNAMESERVIPS) { if(rrs6) { serva[nserva].ipv6 = *((struct in6_addr *)rrs6->data); rrs6=rrs6->next; if (rrs4) { /* Store IPv4 address as fallback. */ serva[nserva].ipv4 = *((struct in_addr *)rrs4->data); rrs4=rrs4->next; } else serva[nserva].ipv4.s_addr=INADDR_ANY; } else if (rrs4) { struct in_addr *ina = (struct in_addr *)rrs4->data; struct in6_addr *in6a = &serva[nserva].ipv6; IPV6_MAPIPV4(ina,in6a); serva[nserva].ipv4.s_addr=INADDR_ANY; rrs4=rrs4->next; } else break; ++nserva; } } #endif free_cent(servent DBG1); pdnsd_free(servent); } else { DEBUG_RHN_MSG("Simple query for %s type A failed (rc: %s)\n", RHN2STR((const unsigned char *)(rr->data)),get_ename(rc)); } if(nserva==0) { /* Address lookup failed. */ DEBUG_RHN_MSG("Failed to obtain address of root server %s in <API key>()\n", RHN2STR((const unsigned char *)(rr->data))); ++nfail; } else { int i, j, n=DA_NEL(res); for(i=0; i<nserva; ++i) { pdnsd_a2 *pserva= &serva[i]; /* Skip duplicates */ for (j=0; j<n; ++j) { pdnsd_a2 *pa= &DA_INDEX(res,j); if (same_inaddr2_2(pa,pserva)) goto skip_address; } if(!(res=DA_GROW1(res))) { DEBUG_MSG("Out of memory in <API key>()\n"); goto free_cent_return; } DA_LAST(res)= *pserva; skip_address:; } } } /* At least half of the names should resolve, otherwise we reject the result. */ if(nfail>DA_NEL(res)) { DEBUG_MSG("Too many root-server resolve failures (%u succeeded, %u failed)," " rejecting the result.\n", DA_NEL(res),nfail); da_free(res); res=NULL; } } free_cent_return: free_cent(cent DBG1); pdnsd_free(cent); } else { DEBUG_MSG("Simple query for root domain type NS failed (rc: %s)\n",get_ename(rc)); } return res; } static int p_dns_resolve(const unsigned char *name, int thint, dns_cent_t **cachedp, int hops, qhintnode_t *qhlist, unsigned char *c_soa) { int i,n,rc; int one_up=0,seenrootserv=0; query_stat_array serv=NULL; rejectlist_t *rejectlist=NULL; /* try the servers in the order of their definition */ lock_server_data(); n=DA_NEL(servers); for (i=0;i<n;++i) { servparm_t *sp=&DA_INDEX(servers,i); if(sp->rootserver<=1 && use_server(sp,name)) { int m=DA_NEL(sp->atup_a); if(m>0) { rejectlist_t *rjl=NULL; int j=0, jstart=0; if(sp->rand_servers) j=jstart=random()%m; do { atup_t *at=&DA_INDEX(sp->atup_a,j); if (at->is_up) { if(sp->rootserver) { if(!seenrootserv) { int nseg,mseg=1,l=0; const unsigned char *topdomain=NULL; addr2_array adrs=NULL; seenrootserv=1; nseg=rhnsegcnt(name); if(nseg>=2) { static const unsigned char rhn_arpa[6]= {4,'a','r','p','a',0}; unsigned int rem; /* Check if the queried name ends in "arpa" */ domain_match(rhn_arpa, name, &rem,NULL); if(rem==0) mseg=3; } if(nseg<=mseg) { if(nseg>0) mseg=nseg-1; else mseg=0; } for(;mseg>=1; --mseg) { topdomain=skipsegs(name,nseg-mseg); adrs=lookup_ns(topdomain); l=DA_NEL(adrs); if(l>0) break; if(adrs) da_free(adrs); } if(l>0) { /* The name servers for this top level domain have been found in the cache. Instead of asking the root server, we will use this cached information. */ int k=0, kstart=0; if(sp->rand_servers) k=kstart=random()%l; if(serv_has_rejectlist(sp) && sp->rejectrecursively && !rjl) { rjl=add_rejectlist(rejectlist,sp); if(!rjl) {one_up=0; da_free(adrs); goto done;} rejectlist=rjl; } do { one_up=add_qserv(&serv, &DA_INDEX(adrs,k), 53, sp->timeout, mk_flag_val(sp)&~CFF_NOINHERIT, sp->nocache, sp->lean_query, sp->edns_query, 2, 0, !global.paranoid, topdomain, rjl); if(!one_up) { da_free(adrs); goto done; } if(++k==l) k=0; } while(k!=kstart); da_free(adrs); DEBUG_PDNSDA_MSG("Not querying root-server %s, using cached information instead.\n", PDNSDA2STR(PDNSD_A2_TO_A(&at->a))); seenrootserv=2; break; } } else if(seenrootserv==2) break; } if(serv_has_rejectlist(sp) && !rjl) { rjl=add_rejectlist(rejectlist,sp); if(!rjl) {one_up=0; goto done;} rejectlist=rjl; } one_up=add_qserv(&serv, &at->a, sp->port, sp->timeout, mk_flag_val(sp), sp->nocache, sp->lean_query, sp->edns_query, sp->rootserver?3:(!sp->is_proxy), needs_testing(sp), 1, NULL, rjl); if(!one_up) goto done; } if(++j==m) j=0; } while(j!=jstart); } } } done: unlock_server_data(); if (one_up) { dns_cent_t *cached; int nocache; rc=p_recursive_query(serv, name, thint, &cached, &nocache, hops, NULL, qhlist, c_soa); if (rc==RC_OK) { if (!nocache) { dns_cent_t *tc; add_cache(cached); if ((tc=lookup_cache(name,NULL))) { /* The cache may hold more information than the recent query yielded. * try to get the merged record. If that fails, revert to the new one. */ free_cent(cached DBG1); pdnsd_free(cached); cached=tc; /* rc=RC_CACHED; */ } else DEBUG_MSG("p_dns_resolve: merging answer with cache failed, using local cent copy.\n"); } else DEBUG_MSG("p_dns_resolve: nocache.\n"); *cachedp=cached; } else if(rc==RC_CACHED || rc==RC_STALE) *cachedp=cached; } else { DEBUG_MSG("No server is marked up and allowed for this domain.\n"); rc=RC_SERVFAIL; /* No server up */ } del_qserv(serv); free_rejectlist(rejectlist); return rc; } static int set_flags_ttl(unsigned short *flags, time_t *ttl, dns_cent_t *cached, int tp) { rr_set_t *rrset=getrrset(cached,tp); if (rrset) { time_t t; *flags|=rrset->flags; t=rrset->ts+CLAT_ADJ(rrset->ttl); if (!*ttl || *ttl>t) *ttl=t; return 1; } return 0; } static void set_all_flags_ttl(unsigned short *flags, time_t *ttl, dns_cent_t *cached) { int i, ilim= RRARR_LEN(cached); for(i=0; i<ilim; ++i) { rr_set_t *rrset= RRARR_INDEX(cached,i); if (rrset) { time_t t; *flags|=rrset->flags; t=rrset->ts+CLAT_ADJ(rrset->ttl); if (!*ttl || *ttl>t) *ttl=t; } } } /* Lookup name in the cache, and if records of type thint are found, check whether a requery is needed. Possible returns values are: RC_OK: the name is locally defined. RC_NAMEERR: the name is locally negatively cached. RC_CACHED: name was found in the cache, requery not needed. RC_STALE: name was found in the cache, but requery is needed. RC_NOTCACHED: name was not found in the cache. */ static int lookup_cache_status(const unsigned char *name, int thint, dns_cent_t **cachedp, unsigned short *flagsp, time_t queryts, unsigned char *c_soa) { dns_cent_t *cached; int rc=RC_NOTCACHED; int wild=0; unsigned short flags=0; if ((cached=lookup_cache(name,&wild))) { short int neg=0,timed=0,need_req=0; time_t ttl=0; if (cached->flags&DF_LOCAL) { #if DEBUG>0 { char dflagstr[DFLAGSTRLEN]; DEBUG_RHN_MSG("Entry found in cache for '%s' with dflags=%s.\n", RHN2STR(cached->qname),dflags2str(cached->flags,dflagstr)); } #endif if((cached->flags&DF_NEGATIVE) || wild==w_locnerr) { if(c_soa) { if(cached->c_soa!=cundef) *c_soa=cached->c_soa; else if(have_rr_SOA(cached)) *c_soa=rhnsegcnt(cached->qname); else { unsigned char *owner=getlocalowner(cached->qname,T_SOA); if(owner) *c_soa=rhnsegcnt(owner); } } free_cent(cached DBG1); pdnsd_free(cached); rc= RC_NAMEERR; goto return_rc; } else { rc= RC_OK; goto return_rc_cent; } } DEBUG_RHN_MSG("Record found in cache for %s\n",RHN2STR(cached->qname)); if (cached->flags&DF_NEGATIVE) { if ((ttl=cached->neg.ts+CLAT_ADJ(cached->neg.ttl))>=queryts) neg=1; else timed=1; } else { if (thint==QT_ALL) { set_all_flags_ttl(&flags, &ttl, cached); } else if (!set_flags_ttl(&flags, &ttl, cached, T_CNAME) || (getrrset_CNAME(cached)->flags&CF_NEGATIVE)) { flags=0; ttl=0; if (thint>=T_MIN && thint<=T_MAX) { if (set_flags_ttl(&flags, &ttl, cached, thint)) neg=getrrset(cached,thint)->flags&CF_NEGATIVE && ttl>=queryts; } else if (thint==QT_MAILB) { set_flags_ttl(&flags, &ttl, cached, T_MB); set_flags_ttl(&flags, &ttl, cached, T_MG); set_flags_ttl(&flags, &ttl, cached, T_MR); } else if (thint==QT_MAILA) { set_flags_ttl(&flags, &ttl, cached, T_MD); set_flags_ttl(&flags, &ttl, cached, T_MF); } } if(!(flags&CF_LOCAL)) { if (thint==QT_ALL) { if(!(cached->flags&DF_AUTH)) need_req=1; } else if (thint>=QT_MIN && thint<=QT_MAX) { if(!(flags&CF_AUTH && !(flags&CF_ADDITIONAL))) need_req=1; } if (ttl<queryts) timed=1; } } #if DEBUG>0 { char dflagstr[DFLAGSTRLEN],cflagstr[CFLAGSTRLEN]; DEBUG_MSG("Requery decision: dflags=%s, cflags=%s, req=%i, neg=%i, timed=%i, %s=%li\n", dflags2str(cached->flags,dflagstr),cflags2str(flags,cflagstr),need_req,neg,timed, ttl?"ttl":"timestamp",(long)(ttl?(ttl-queryts):ttl)); } #endif rc = (!neg && (need_req || timed))? RC_STALE: RC_CACHED; return_rc_cent: *cachedp=cached; } return_rc: if(flagsp) *flagsp=flags; return rc; } /* * Resolve records for name into dns_cent_t, type thint. * q is the set of servers to query from. Set q to NULL if you want to ask the servers registered with pdnsd. * qslist should refer to a list of server arrays already used higher up the calling chain (may be NULL). * <API key>() returns one of the following values: * RC_OK means that the name was successfully resolved by querying other servers. * RC_CACHED or RC_STALE means that the name was found in the cache. * RC_NAMEERR or RC_SERVFAIL indicates a resolve error. */ static int <API key>(query_stat_array q, const unsigned char *name, int thint, dns_cent_t **cachedp, int hops, qstatnode_t *qslist, qhintnode_t *qhlist, time_t queryts, unsigned char *c_soa) { dns_cent_t *cached=NULL; int rc; unsigned short flags=0; DEBUG_RHN_MSG("Starting cached resolve for: %s, query %s\n",RHN2STR(name),get_tname(thint)); rc= lookup_cache_status(name, thint, &cached, &flags,queryts,c_soa); if(rc==RC_OK) { /* Locally defined record. */ *cachedp=cached; return RC_CACHED; } else if(rc==RC_NAMEERR) /* Locally negated name. */ return RC_NAMEERR; /* update server records set onquery */ if(global.onquery) test_onquery(); if (global.lndown_kluge && !(flags&CF_LOCAL)) { int i,n,linkdown=1; lock_server_data(); n=DA_NEL(servers); for(i=0;i<n;++i) { servparm_t *sp=&DA_INDEX(servers,i); if(sp->rootserver<=1) { int j,m=DA_NEL(sp->atup_a); for(j=0;j<m;++j) { if (DA_INDEX(sp->atup_a,j).is_up) { linkdown=0; goto done; } } } } done: unlock_server_data(); if (linkdown) { DEBUG_MSG("Link is down.\n"); rc=RC_SERVFAIL; goto cleanup_return; } } if (rc!=RC_CACHED) { dns_cent_t *ent; DEBUG_MSG("Trying name servers.\n"); if (q) rc=p_recursive_query(q,name,thint, &ent,NULL,hops,qslist,qhlist,c_soa); else rc=p_dns_resolve(name,thint, &ent,hops,qhlist,c_soa); if(rc==RC_OK || rc==RC_CACHED || rc==RC_STALE) { if (cached) { free_cent(cached DBG1); pdnsd_free(cached); } cached=ent; } else if (rc==RC_SERVFAIL && cached && (flags&CF_NOPURGE)) { /* We could not get a new record, but we have a timed-out cached one with the nopurge flag set. This means that we shall use it even if timed out when no new one is available*/ DEBUG_MSG("Falling back to cached record.\n"); rc=RC_STALE; } else goto cleanup_return; } else { DEBUG_MSG("Using cached record.\n"); } *cachedp=cached; return rc; cleanup_return: if(cached) { free_cent(cached DBG1); pdnsd_free(cached); } return rc; } /* <API key>() is like <API key>(), except that <API key>() will not return negatively cached entries, but returns RC_NAMEERR instead. It also does not return RC_CACHED or RC_STALE, but RC_OK instead. */ int <API key>(unsigned char *name, int thint, dns_cent_t **cachedp, int hops, qhintnode_t *qhlist, time_t queryts, unsigned char *c_soa) { dns_cent_t *cached; int rc=<API key>(NULL,name,thint,&cached,hops,NULL,qhlist,queryts,c_soa); if(rc==RC_OK || rc==RC_CACHED || rc==RC_STALE) { if(cached->flags&DF_NEGATIVE) { if(c_soa) *c_soa=cached->c_soa; free_cent(cached DBG1); pdnsd_free(cached); return RC_NAMEERR; } else { *cachedp=cached; return RC_OK; } } return rc; } static int <API key>(atup_array atup_a, int port, char edns_query, time_t timeout, const unsigned char *name, int thint, dns_cent_t **cachedp) { dns_cent_t *cached=NULL; int rc; DEBUG_RHN_MSG("Starting simple cached resolve for: %s, query %s\n",RHN2STR(name),get_tname(thint)); rc= lookup_cache_status(name, thint, &cached, NULL, time(NULL), NULL); if(rc==RC_OK) { /* Locally defined record. */ *cachedp=cached; return RC_OK; } else if(rc==RC_NAMEERR) /* Locally negated name. */ return RC_NAMEERR; if (rc!=RC_CACHED) { query_stat_array qserv; int j,m; if (cached) { free_cent(cached DBG1); pdnsd_free(cached); cached=NULL; } DEBUG_MSG("Trying name servers.\n"); qserv=NULL; m=DA_NEL(atup_a); for(j=0; j<m; ++j) { if(!add_qserv(&qserv, &DA_INDEX(atup_a,j).a, port, timeout, 0, 0, 1, edns_query, 0, 0, 1, NULL, NULL)) { /* Note: qserv array already cleaned up by add_qserv() */ return RC_SERVFAIL; } } rc=p_recursive_query(qserv,name,thint, &cached,NULL,0,NULL,NULL,NULL); del_qserv(qserv); if (rc==RC_OK) { dns_cent_t *tc; add_cache(cached); if ((tc=lookup_cache(name,NULL))) { /* The cache may hold more information than the recent query yielded. * try to get the merged record. If that fails, revert to the new one. */ free_cent(cached DBG1); pdnsd_free(cached); cached=tc; } else DEBUG_MSG("<API key>: merging answer with cache failed, using local cent copy.\n"); } else if(!(rc==RC_CACHED || rc==RC_STALE)) /* RC_CACHED and RC_STALE should not be possible. */ return rc; } else { DEBUG_MSG("Using cached record.\n"); } if(cached->flags&DF_NEGATIVE) { free_cent(cached DBG1); pdnsd_free(cached); return RC_NAMEERR; } *cachedp=cached; return RC_OK; } /* Check whether a server is responsive by sending it an (empty) query. rep is the number of times this is tried in case of no reply. */ int query_uptest(pdnsd_a *addr, int port, const unsigned char *name, time_t timeout, int rep) { query_stat_t qs; int iter=0,rv; #ifdef ENABLE_IPV4 if (run_ipv4) { memset(&qs.a.sin4,0,sizeof(qs.a.sin4)); qs.a.sin4.sin_family=AF_INET; qs.a.sin4.sin_port=htons(port); qs.a.sin4.sin_addr=addr->ipv4; SET_SOCKA_LEN4(qs.a.sin4); } #endif #ifdef ENABLE_IPV6 ELSE_IPV6 { memset(&qs.a.sin6,0,sizeof(qs.a.sin6)); qs.a.sin6.sin6_family=AF_INET6; qs.a.sin6.sin6_port=htons(port); qs.a.sin6.sin6_flowinfo=IPV6_FLOWINFO; qs.a.sin6.sin6_addr=addr->ipv6; SET_SOCKA_LEN6(qs.a.sin6); qs.a4fallback.s_addr=INADDR_ANY; } #endif qs.timeout=timeout; qs.flags=0; qs.nocache=0; qs.auth_serv=0; qs.lean_query=1; qs.edns_query=0; qs.needs_testing=0; qs.trusted=1; qs.aa=0; qs.tc=0; qs.ra=0; qs.failed=0; qs.nsdomain=NULL; qs.rejectlist=NULL; try_again: qs.state=QS_INITIAL; qs.qm=global.query_method; qs.s_errno=0; rv=p_exec_query(NULL, name, T_A, &qs, NULL, NULL); if(rv==-1) { time_t ts, tpassed; for(ts=time(NULL), tpassed=0;; tpassed=time(NULL)-ts) { int event; #ifdef NO_POLL fd_set reads; fd_set writes; struct timeval tv; FD_ZERO(&reads); FD_ZERO(&writes); # ifndef WIN32 PDNSD_ASSERT(qs.sock<FD_SETSIZE,"socket file descriptor exceeds FD_SETSIZE."); # endif switch (qs.state) { QS_READ_CASES: FD_SET(qs.sock,&reads); break; QS_WRITE_CASES: FD_SET(qs.sock,&writes); break; } tv.tv_sec=timeout>tpassed?timeout-tpassed:0; tv.tv_usec=0; /* There is a possible race condition with the arrival of a signal here, but it is so unlikely to be a problem in practice that doing this properly is not worth the trouble. */ if(<API key>()) { DEBUG_MSG("server status thread interrupted.\n"); p_cancel_query(&qs); return 0; } event=select(qs.sock+1,&reads,&writes,NULL,&tv); #else struct pollfd pfd; pfd.fd=qs.sock; switch (qs.state) { QS_READ_CASES: pfd.events=POLLIN; break; QS_WRITE_CASES: pfd.events=POLLOUT; break; default: pfd.events=0; } /* There is a possible race condition with the arrival of a signal here, but it is so unlikely to be a problem in practice that doing this properly is not worth the trouble. */ if(<API key>()) { DEBUG_MSG("server status thread interrupted.\n"); p_cancel_query(&qs); return 0; } event=poll(&pfd,1,timeout>tpassed?(timeout-tpassed)*1000:0); #endif if (event<0) { #ifdef WIN32 if(WSAGetLastError()==WSAEINTR && <API key>()) { #else if(errno==EINTR && <API key>()) { #endif DEBUG_MSG("poll/select interrupted in server status thread.\n"); } else #ifdef WIN32 log_warn("select failed: %d",WSAGetLastError()); #else log_warn("poll/select failed: %s",strerror(errno)); #endif p_cancel_query(&qs); return 0; } if(event==0) { /* timed out */ p_cancel_query(&qs); if(++iter<rep) goto try_again; return 0; } event=0; #ifdef NO_POLL switch (qs.state) { QS_READ_CASES: event=FD_ISSET(qs.sock,&reads); break; QS_WRITE_CASES: event=FD_ISSET(qs.sock,&writes); break; } #else switch (qs.state) { QS_READ_CASES: event=pfd.revents&(POLLIN|POLLERR|POLLHUP|POLLNVAL); break; QS_WRITE_CASES: event=pfd.revents&(POLLOUT|POLLERR|POLLHUP|POLLNVAL); break; } #endif if(event) { rv=p_exec_query(NULL, name, T_A, &qs, NULL, NULL); if(rv!=-1) break; } else { if(++poll_errs<=MAXPOLLERRS) log_error("Unhandled poll/select event in query_uptest() at %s, line %d.",__FILE__,__LINE__); p_cancel_query(&qs); return 0; } } } return (rv!=RC_SERVFAIL && rv!=RC_FATALERR); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ECCentral.BizEntity.Invoice { public class <API key> : ICompany, ILanguage { public int? StItemSysNo { get; set; } <summary> </summary> public DateTime? OutTime { get; set; } public DateTime? InTime { get; set; } public int? ShiftSysNo { get; set; } <summary> </summary> public int? ProductSysNo { get; set; } <summary> </summary> public string ProductID { get; set; } <summary> </summary> public string ProductName { get; set; } <summary> </summary> public int? ShiftQty { get; set; } <summary> (*) </summary> public decimal? UnitCostCount { get; set; } <summary> (*) </summary> public decimal? AmtCount { get; set; } <summary> (*) </summary> public decimal? AmtTaxItem { get; set; } <summary> </summary> public decimal? AmtProductCost { get; set; } <summary> </summary> public decimal? AtTotalAmt { get; set; } <summary> </summary> public string StockNameA { get; set; } <summary> </summary> public string StockNameB { get; set; } <summary> </summary> public string GoldenTaxNo { get; set; } public string InvoiceNo { get; set; } public int? StockSysNoA { get; set; } public int? StockSysNoB { get; set; } public int? ShiftType { get; set; } ///////////crl17402////////////////////// public string SapCoCodeFrom { get; set; } public string SapCoCodeTo { get; set; } #region ICompany Members public string CompanyCode { get; set; } public string LanguageCode { get; set; } #endregion } }
from django.http import Http404 from django.shortcuts import get_object_or_404 from django.utils.translation import gettext_lazy as _ from zds.api.validators import Validator from zds.member.models import Profile class <API key>(Validator): can_be_empty = False def <API key>(self, value): msg = None if value or self.can_be_empty: for participant in value: if participant.username == self.get_current_user().username: msg = _("Vous ne pouvez pas vous écrire à vous-même !") try: current = get_object_or_404(Profile, user__username=participant) if not Profile.objects.contactable_members().filter(pk=current.pk).exists(): msg = _("Vous avez tenté d'ajouter un utilisateur injoignable.") except Http404: msg = _(f"Un des participants saisi est introuvable ({participant}).") else: msg = _("Vous devez spécifier des participants.") if msg is not None: self.throw_error("participants", msg) return value def get_current_user(self): raise NotImplementedError("`get_current_user()` must be implemented.") class <API key>(Validator): """ Validates participants field of a MP. """ def <API key>(self, value, username): """ Checks about participants. :param value: participants value :return: participants value """ msg = None if value: participants = value.strip() if participants != "": if len(participants) == 1 and participants[0].strip() == ",": msg = _("Vous devez spécfier des participants valides.") for participant in participants.split(","): participant = participant.strip() if not participant: continue if participant.strip().lower() == username.lower(): msg = _("Vous ne pouvez pas vous écrire à vous-même !") try: current = get_object_or_404(Profile, user__username=participant) if not Profile.objects.contactable_members().filter(pk=current.pk).exists(): msg = _("Vous avez tenté d'ajouter un utilisateur injoignable.") except Http404: msg = _(f"Un des participants saisi est introuvable ({participant}).") else: msg = _("Le champ participants ne peut être vide.") if msg is not None: self.throw_error("participants", msg) return value class TitleValidator(Validator): """ Validates title field of a MP. """ def validate_title(self, value): """ Checks about title. :param value: title value :return: title value """ msg = None if value: if not value.strip(): msg = _("Le champ titre ne peut être vide.") if msg is not None: self.throw_error("title", msg) return value class TextValidator(Validator): """ Validates text field of a MP. """ def validate_text(self, value): """ Checks about text. :param value: text value :return: text value """ msg = None if value: if not value.strip(): msg = _("Le champ text ne peut être vide.") if msg is not None: self.throw_error("text", msg) return value
/* see the COPYING file in the top-level directory.*/ #ifndef UT_VECTOR_H #define UT_VECTOR_H extern double ut_vector_norm (double *); extern double ut_vector_int_norm (int *); extern double ut_vector_scalprod (double *, double *); extern void ut_vector_vectprod (double *, double *, double *); extern double ut_vector_angle_rad (double *, double *); extern double ut_vector_angle (double *, double *); extern double <API key> (int *, int *); extern double ut_vector_int_angle (int *, int *); extern void ut_vector_covar (double**, int, double**, double*); extern void ut_vector_uvect (double*, double*); #endif /* UT_VECTOR_H */
package com.ep.ggs.networking.packets.minecraft; import java.io.DataInputStream; import java.io.IOException; import java.nio.ByteBuffer; import com.ep.ggs.iomodel.SMPPlayer; import com.ep.ggs.networking.packets.PacketManager; import com.ep.ggs.server.Server; public class EntityVelocity extends SMPPacket { public EntityVelocity(String name, byte ID, PacketManager parent) { super(name, ID, parent); } public EntityVelocity(PacketManager pm) { this("EntityVelocity", (byte)0x1C, pm); } @Override public void handle(SMPPlayer p, Server server, DataInputStream reader) { } @Override public void write(SMPPlayer player, Server server, Object... obj) { if (obj.length >= 4) { ByteBuffer bb; if (obj[0] instanceof Integer && obj[1] instanceof Short && obj[2] instanceof Short && obj[3] instanceof Short) { bb = ByteBuffer.allocate(8); bb.put(ID); bb.putInt((Integer)obj[0]); bb.putShort((Short)obj[1]); bb.putShort((Short)obj[2]); bb.putShort((Short) obj[3]); try { player.writeData(bb.array()); } catch (IOException e) { e.printStackTrace(); } } } } }
<?php include_once(PHPREPORT_ROOT . '/model/vo/ProjectVO.php'); include_once(PHPREPORT_ROOT . '/model/dao/ProjectDAO/<API key>.php'); include_once(PHPREPORT_ROOT . '/model/vo/CustomerVO.php'); include_once(PHPREPORT_ROOT . '/model/dao/CustomerDAO/<API key>.php'); include_once(PHPREPORT_ROOT . '/model/vo/AreaVO.php'); include_once(PHPREPORT_ROOT . '/model/dao/AreaDAO/PostgreSQLAreaDAO.php'); include_once(PHPREPORT_ROOT . '/model/vo/SectorVO.php'); include_once(PHPREPORT_ROOT . '/model/dao/SectorDAO/PostgreSQLSectorDAO.php'); include_once(PHPREPORT_ROOT . '/model/dao/RequestsDAO/<API key>.php'); class <API key> extends <API key> { protected $dao; protected $auxDao; protected $testObjects; protected $auxDao2; protected $testObjects2; protected $auxDao3; protected $auxObject; protected $auxDao4; protected $auxObject2; protected function setUp() { $this->auxDao4 = new PostgreSQLSectorDAO(); $this->auxObject2 = new SectorVO(); $this->auxObject2->setName("Industry"); $this->auxDao4->create($this->auxObject2); $this->auxDao = new <API key>(); $this->testObjects[0] = new CustomerVO(); $this->testObjects[0]->setSectorId($this->auxObject2->getId()); $this->testObjects[0]->setName("Mommy"); $this->testObjects[0]->setType("Biggest industry on Earth"); $this->testObjects[0]->setURL("www.mommyindustries.com"); $this->testObjects[0]->setId(-1); $this->testObjects[1] = new CustomerVO(); $this->testObjects[1]->setSectorId($this->auxObject2->getId()); $this->testObjects[1]->setName("Mommy"); $this->testObjects[1]->setType("Biggest industry on Earth"); $this->testObjects[1]->setURL("www.mommyindustries.com"); $this->testObjects[1]->setId(-1); $this->testObjects[2] = new CustomerVO(); $this->testObjects[2]->setSectorId($this->auxObject2->getId()); $this->testObjects[2]->setName("Mommy"); $this->testObjects[2]->setType("Biggest industry on Earth"); $this->testObjects[2]->setURL("www.mommyindustries.com"); $this->testObjects[2]->setId(-1); $this->auxDao->create($this->testObjects[0]); $this->auxDao3 = new PostgreSQLAreaDAO(); $this->auxObject = new AreaVO(); $this->auxObject->setName("Deliverers"); $this->auxDao3->create($this->auxObject); $this->auxDao2 = new <API key>(); $this->testObjects2[0] = new ProjectVO(); $this->testObjects2[0]->setInit(date_create("1999-12-31")); $this->testObjects2[0]->setAreaId($this->auxObject->getId()); $this->testObjects2[0]->setEnd(date_create("2999-12-31")); $this->testObjects2[0]->setDescription("Good news, everyone!"); $this->testObjects2[0]->setActivation(TRUE); $this->testObjects2[0]->setSchedType("Good news, everyone!"); $this->testObjects2[0]->setType("I've taught the toaster to feel love!"); $this->testObjects2[0]->setMovedHours(3.14); $this->testObjects2[0]->setInvoice(5.55); $this->testObjects2[0]->setEstHours(3.25); $this->testObjects2[0]->setId(-1); $this->testObjects2[1] = new ProjectVO(); $this->testObjects2[1]->setInit(date_create("1999-12-31")); $this->testObjects2[1]->setAreaId($this->auxObject->getId()); $this->testObjects2[1]->setEnd(date_create("2999-12-31")); $this->testObjects2[1]->setDescription("Good news, everyone!"); $this->testObjects2[1]->setActivation(TRUE); $this->testObjects2[1]->setSchedType("Good news, everyone!"); $this->testObjects2[1]->setType("I've taught the toaster to feel love!"); $this->testObjects2[1]->setMovedHours(3.14); $this->testObjects2[1]->setInvoice(5.55); $this->testObjects2[1]->setEstHours(3.25); $this->testObjects2[1]->setId(-1); $this->testObjects2[2] = new ProjectVO(); $this->testObjects2[2]->setInit(date_create("1999-12-31")); $this->testObjects2[2]->setAreaId($this->auxObject->getId()); $this->testObjects2[2]->setEnd(date_create("2999-12-31")); $this->testObjects2[2]->setDescription("Good news, everyone!"); $this->testObjects2[2]->setActivation(TRUE); $this->testObjects2[2]->setSchedType("Good news, everyone!"); $this->testObjects2[2]->setType("I've taught the toaster to feel love!"); $this->testObjects2[2]->setMovedHours(3.14); $this->testObjects2[2]->setInvoice(5.55); $this->testObjects2[2]->setEstHours(3.25); $this->testObjects2[2]->setId(-1); $this->auxDao2->create($this->testObjects2[0]); $this->dao = new <API key>(); } protected function tearDown() { foreach($this->testObjects as $testObject1) foreach($this->testObjects2 as $testObject2) $this->dao->delete($testObject1->getId(), $testObject2->getId()); foreach($this->testObjects as $testObject) $this->auxDao->delete($testObject); foreach($this->testObjects2 as $testObject) $this->auxDao2->delete($testObject); $this->auxDao3->delete($this->auxObject); $this->auxDao4->delete($this->auxObject2); } public function testCreate() { $this->assertEquals($this->dao->create($this->testObjects[0]->getId(), $this->testObjects2[0]->getId()), 1); } /** * @expectedException <API key> */ public function <API key>() { $this->dao->create("*", $this->testObjects2[0]->getId()); } /** * @expectedException <API key> */ public function <API key>() { $this->dao->create($this->testObjects[0]->getId(), "*"); } public function testDelete() { $this->dao->create($this->testObjects[0]->getId(), $this->testObjects2[0]->getId()); $this->assertEquals($this->dao->delete($this->testObjects[0]->getId(), $this->testObjects2[0]->getId()), 1); } /** * @expectedException <API key> */ public function <API key>() { $this->dao->delete("*", $this->testObjects2[0]->getId()); } /** * @expectedException <API key> */ public function <API key>() { $this->dao->delete($this->testObjects[0]->getId(), "*"); } public function <API key>() { $this->assertEquals($this->dao->delete($this->testObjects[0]->getId(), $this->testObjects2[0]->getId()), 0); } public function testGetByCustomerId() { $this->auxDao2->create($this->testObjects2[1]); $this->auxDao2->create($this->testObjects2[2]); $this->dao->create($this->testObjects[0]->getId(), $this->testObjects2[0]->getId()); $this->dao->create($this->testObjects[0]->getId(), $this->testObjects2[1]->getId()); $this->dao->create($this->testObjects[0]->getId(), $this->testObjects2[2]->getId()); $read = $this->dao->getByCustomerId($this->testObjects[0]->getId()); $this->assertEquals($read, $this->testObjects2); } /** * @expectedException <API key> */ public function <API key>() { $this->dao->getByCustomerId("*"); } public function testGetByProjectId() { $this->auxDao->create($this->testObjects[1]); $this->auxDao->create($this->testObjects[2]); $this->dao->create($this->testObjects[0]->getId(), $this->testObjects2[0]->getId()); $this->dao->create($this->testObjects[1]->getId(), $this->testObjects2[0]->getId()); $this->dao->create($this->testObjects[2]->getId(), $this->testObjects2[0]->getId()); $read = $this->dao->getByProjectId($this->testObjects2[0]->getId()); $this->assertEquals($read, $this->testObjects); } /** * @expectedException <API key> */ public function <API key>() { $this->dao->getByProjectId("*"); } } ?>
#include "\socomd_core\predefined.hpp" class CfgPatches { class socomd_compat_h60 { version = 1.1.0; versionStr = "1.1.0"; versionAr[] = { 1,1,0 }; requiredVersion = 0.1; requiredAddons[] = { //SOCOMD Requirments "socomd_core", "socomd_compat_cup", "vtx_MH60M" }; units[] = {}; weapons[] = {}; ammo[] = {}; magazines[] = {}; }; }; #include "CfgVehicles.hpp"
import { AbstractControl, ValidatorFn } from "@angular/forms"; /** * Container for custom Angular Validator functions. */ export const <API key>: { isNumber: ValidatorFn } = { /** * Angular Validator to verify value is a valid number. */ isNumber: (control: AbstractControl) => { const val = Number(control.value); if (Number.isNaN(Number(val))) { return { isNumber: "invalid" }; } else { return null; } }, };
This is the stub README.txt for the "hash-bang-lang" project.
package id.web.widat.<API key>; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.<API key>; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.StringReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.security.SecureRandom; import java.security.cert.<API key>; import java.security.cert.X509Certificate; import java.util.Base64; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.<API key>; import javax.xml.parsers.<API key>; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import id.web.widat.<API key>.constants.Method; import id.web.widat.<API key>.constants.Protocol; import id.web.widat.<API key>.model.Response; public class RESTClient { private static class DefaultTrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) throws <API key> { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws <API key> { } public X509Certificate[] getAcceptedIssuers() { return null; } } private static SSLContext disabledSSL() { try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); return sslContext; } catch (Exception e) { System.out.println(e.getMessage()); } return null; } private static String getQuery(Map<String, String> params) { StringBuilder result = new StringBuilder(); boolean first = false; try { Set<String> keys = params.keySet(); for (String key : keys) { if (!first) { first = true; } else { result.append("&"); } result.append(URLEncoder.encode(key, "UTF-8")); result.append("="); result.append(URLEncoder.encode(params.get(key), "UTF-8")); } } catch (Exception e) { System.out.println(e.getMessage()); } return result.toString(); } @SuppressWarnings("unchecked") public static Response pull(String protocol, String address, Object data, String method, Map<String, String> property) { HttpURLConnection httpURLConnection = null; HttpsURLConnection httpsURLConnection = null; BufferedReader bufferedReader = null; OutputStream outputStream = null; Response response = new Response(); try { if (protocol.equalsIgnoreCase(Protocol.HTTPS)) { SSLContext.setDefault(disabledSSL()); } URL url = new URL(address); if (protocol.equalsIgnoreCase(Protocol.HTTP)) { httpURLConnection = (HttpURLConnection) url.openConnection(); if (method.equalsIgnoreCase(Method.GET)) { httpURLConnection.setRequestMethod(Method.GET); } else if (method.equalsIgnoreCase(Method.POST)) { httpURLConnection.setRequestMethod(Method.POST); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); } if (property != null) { Set<String> keySet = property.keySet(); for (String key : keySet) { httpURLConnection.setRequestProperty(key, property.get(key)); } } } else if (protocol.equalsIgnoreCase(Protocol.HTTPS)) { httpsURLConnection = (HttpsURLConnection) url.openConnection(); httpsURLConnection.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); if (method.equalsIgnoreCase(Method.GET)) { httpsURLConnection.setRequestMethod(Method.GET); } else if (method.equalsIgnoreCase(Method.POST)) { httpsURLConnection.setRequestMethod(Method.POST); httpsURLConnection.setDoInput(true); httpsURLConnection.setDoOutput(true); } if (property != null) { Set<String> keySet = property.keySet(); for (String key : keySet) { httpsURLConnection.setRequestProperty(key, property.get(key)); } } } if (method.equalsIgnoreCase(Method.POST) || method.equalsIgnoreCase(Method.PUT)) { Map<String, String> mapData = new HashMap<String, String>(); if (data != null) { if (protocol.equalsIgnoreCase(Protocol.HTTP)) { outputStream = httpURLConnection.getOutputStream(); } else if (protocol.equalsIgnoreCase(Protocol.HTTPS)) { outputStream = httpsURLConnection.getOutputStream(); } if (data instanceof Map) { mapData = (Map<String, String>) data; BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter(outputStream, "UTF-8")); if (property.get("Content-Type").equalsIgnoreCase("application/<API key>")) { bufferedWriter.write(getQuery(mapData)); } bufferedWriter.flush(); bufferedWriter.close(); } else if (data instanceof String) { BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter(outputStream, "UTF-8")); bufferedWriter.write((String) data); bufferedWriter.flush(); bufferedWriter.close(); } else if (data instanceof <API key>) { outputStream.write(((<API key>) data).toByteArray()); BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter(outputStream, "UTF-8")); bufferedWriter.flush(); bufferedWriter.close(); } outputStream.close(); } } if (protocol.equalsIgnoreCase(Protocol.HTTP)) { response.setCode(httpURLConnection.getResponseCode()); response.setMessage(httpURLConnection.getResponseMessage()); bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); } else if (protocol.equalsIgnoreCase(Protocol.HTTPS)) { response.setCode(httpsURLConnection.getResponseCode()); response.setMessage(httpsURLConnection.getResponseMessage()); bufferedReader = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream())); } StringBuilder stringBuilder = new StringBuilder(); if (property.get("x-stream") != null) { if (property.get("x-stream").equalsIgnoreCase("available")) { byte[] bytes = new byte[1024]; <API key> baos = new <API key>(); int length; InputStream is = httpsURLConnection.getInputStream(); while ((length = is.read(bytes)) > -1) { baos.write(bytes, 0, length); } baos.flush(); String base64result = Base64.getEncoder().encodeToString(baos.toByteArray()); stringBuilder.append(base64result); } } else { String line = bufferedReader.readLine(); while (line != null) { if (property.get("Content-Type") != null) { if (property.get("Content-Type").equalsIgnoreCase("text/xml")) { if (line.startsWith("<")) { stringBuilder.append(line); } } else { stringBuilder.append(line); } } else { stringBuilder.append(line); } line = bufferedReader.readLine(); } } if (protocol.equalsIgnoreCase(Protocol.HTTP)) { httpURLConnection.disconnect(); } else if (protocol.equalsIgnoreCase(Protocol.HTTPS)) { httpsURLConnection.disconnect(); } response.setResult(stringBuilder.toString()); return response; } catch (Exception e) { System.out.println(e.getMessage()); } return null; } private static Document parseToXML(String in) { <API key> dbf = null; DocumentBuilder db = null; InputSource is = null; Document document = null; try { dbf = <API key>.newInstance(); db = dbf.newDocumentBuilder(); is = new InputSource(new StringReader(in)); document = db.parse(is); } catch (<API key> e) { System.out.println(e.getMessage()); } catch (SAXException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } return document; } }
#ifndef <API key> #define <API key> 1 /* * 140 strings in ao_strs_strtable string table */ #define ARG_BREAK_STR (ao_strs_strtable+261) #define ARG_BREAK_STR_LEN 5 #define ARG_BY_NUM_FMT (ao_strs_strtable+267) #define ARG_BY_NUM_FMT_LEN 9 #define BOOL_ATR_FMT (ao_strs_strtable+880) #define BOOL_ATR_FMT_LEN 31 #define CHK_MAX_COUNT (ao_strs_strtable+1431) #define CHK_MAX_COUNT_LEN 190 #define CHK_MIN_COUNT (ao_strs_strtable+1622) #define CHK_MIN_COUNT_LEN 91 #define CHK_ONE_REQUIRED (ao_strs_strtable+1714) #define <API key> 80 #define ECHO_N_EXIT (ao_strs_strtable+1795) #define ECHO_N_EXIT_LEN 50 #define EMPTY_ARG (ao_strs_strtable+277) #define EMPTY_ARG_LEN 2 #define END_MARK (ao_strs_strtable+1846) #define END_MARK_LEN 115 #define END_OPT_SEL_STR (ao_strs_strtable+280) #define END_OPT_SEL_STR_LEN 12 #define END_PRE_FMT (ao_strs_strtable+912) #define END_PRE_FMT_LEN 36 #define END_SET_TEXT (ao_strs_strtable+293) #define END_SET_TEXT_LEN 3 #define END_XML_FMT (ao_strs_strtable+297) #define END_XML_FMT_LEN 6 #define ENUM_ERR_LINE (ao_strs_strtable+304) #define ENUM_ERR_LINE_LEN 5 #define ENUM_ERR_WIDTH (ao_strs_strtable+310) #define ENUM_ERR_WIDTH_LEN 6 #define EXPORT_ARG_FMT (ao_strs_strtable+317) #define EXPORT_ARG_FMT_LEN 17 #define FALSE_STR (ao_strs_strtable+335) #define FALSE_STR_LEN 5 #define FINISH_LOOP (ao_strs_strtable+1962) #define FINISH_LOOP_LEN 378 #define FLAG_OPT_MARK (ao_strs_strtable+341) #define FLAG_OPT_MARK_LEN 9 #define FLAG_STR (ao_strs_strtable+351) #define FLAG_STR_LEN 4 #define INIT_LOPT_STR (ao_strs_strtable+2341) #define INIT_LOPT_STR_LEN 250 #define INIT_OPT_STR (ao_strs_strtable+2592) #define INIT_OPT_STR_LEN 116 #define INVALID_FMT (ao_strs_strtable+356) #define INVALID_FMT_LEN 10 #define INVALID_STR (ao_strs_strtable+367) #define INVALID_STR_LEN 9 #define LINE_SPLICE (ao_strs_strtable+377) #define LINE_SPLICE_LEN 4 #define LONG_OPT_MARK (ao_strs_strtable+382) #define LONG_OPT_MARKER (ao_strs_strtable+393) #define LONG_OPT_MARKER_LEN 2 #define LONG_OPT_MARK_LEN 10 #define LONG_USE_STR (ao_strs_strtable+396) #define LONG_USE_STR_LEN 9 #define LOOP_STR (ao_strs_strtable+2709) #define LOOP_STR_LEN 206 #define LOPT_ARG_FMT (ao_strs_strtable+2916) #define LOPT_ARG_FMT_LEN 778 #define LVL3_CMD (ao_strs_strtable+406) #define LVL3_CMD_LEN 15 #define MK_STR_OCT_FMT (ao_strs_strtable+422) #define MK_STR_OCT_FMT_LEN 5 #define MORE_STR (ao_strs_strtable+428) #define MORE_STR_LEN 4 #define MULTI_ARG_FMT (ao_strs_strtable+3695) #define MULTI_ARG_FMT_LEN 123 #define MULTI_DEF_FMT (ao_strs_strtable+3819) #define MULTI_DEF_FMT_LEN 157 #define NESTED_OPT_FMT (ao_strs_strtable+433) #define NESTED_OPT_FMT_LEN 17 #define NLSTR_FMT (ao_strs_strtable+451) #define NLSTR_FMT_LEN 3 #define NLSTR_SPACE_FMT (ao_strs_strtable+455) #define NLSTR_SPACE_FMT_LEN 5 #define NONE_STR (ao_strs_strtable+91) #define NONE_STR_LEN 4 #define NOT_FOUND_STR (ao_strs_strtable+3977) #define NOT_FOUND_STR_LEN 56 #define NO_ARG_NEEDED (ao_strs_strtable+461) #define NO_ARG_NEEDED_LEN 17 #define NO_LOAD_WARN (ao_strs_strtable+949) #define NO_LOAD_WARN_LEN 46 #define NO_MULTI_ARG_FMT (ao_strs_strtable+4034) #define <API key> 140 #define NO_SAVE_OPTS (ao_strs_strtable+996) #define NO_SAVE_OPTS_LEN 46 #define NO_SGL_ARG_FMT (ao_strs_strtable+4175) #define NO_SGL_ARG_FMT_LEN 316 #define NO_SUPPRESS_LOAD (ao_strs_strtable+1043) #define <API key> 65 #define NULL_ATR_FMT (ao_strs_strtable+479) #define NULL_ATR_FMT_LEN 6 #define NUMB_ATR_FMT (ao_strs_strtable+1109) #define NUMB_ATR_FMT_LEN 34 #define OK_NEED_OPT_ARG (ao_strs_strtable+486) #define OK_NEED_OPT_ARG_LEN 17 #define ONE_TAB_STR (ao_strs_strtable+504) #define ONE_TAB_STR_LEN 1 #define ONLY_OPTS_LOOP (ao_strs_strtable+4492) #define ONLY_OPTS_LOOP_LEN 102 #define OPEN_CLOSE_FMT (ao_strs_strtable+479) #define OPEN_CLOSE_FMT_LEN 6 #define OPEN_XML_FMT (ao_strs_strtable+506) #define OPEN_XML_FMT_LEN 4 #define OPTION_STR (ao_strs_strtable+511) #define OPTION_STR_LEN 6 #define OPT_ARG_FMT (ao_strs_strtable+4595) #define OPT_ARG_FMT_LEN 1153 #define OPT_END_FMT (ao_strs_strtable+518) #define OPT_END_FMT_LEN 14 #define OPT_VAL_FMT (ao_strs_strtable+533) #define OPT_VAL_FMT_LEN 6 #define OR_STR (ao_strs_strtable+540) #define OR_STR_LEN 3 #define PAGER_NAME (ao_strs_strtable+544) #define PAGER_NAME_LEN 5 #define PAGE_USAGE_FMT (ao_strs_strtable+837) #define PAGE_USAGE_FMT (ao_strs_strtable+837) #define PAGE_USAGE_FMT_LEN 42 #define PAGE_USAGE_FMT_LEN 42 #define PAGE_USAGE_TEXT (ao_strs_strtable+5749) #define PAGE_USAGE_TEXT_LEN 73 #define PLUS_STR (ao_strs_strtable+550) #define PLUS_STR_LEN 3 #define PREAMBLE_FMT (ao_strs_strtable+5823) #define PREAMBLE_FMT_LEN 105 #define PUTS_FMT (ao_strs_strtable+554) #define PUTS_FMT_LEN 15 #define QUOT_APOS (ao_strs_strtable+570) #define QUOT_APOS_LEN 2 #define QUOT_ARG_FMT (ao_strs_strtable+573) #define QUOT_ARG_FMT_LEN 4 #define SET_MULTI_ARG (ao_strs_strtable+5929) #define SET_MULTI_ARG_LEN 89 #define SET_NO_TEXT_FMT (ao_strs_strtable+1144) #define SET_NO_TEXT_FMT_LEN 30 #define SET_OFF_FMT (ao_strs_strtable+578) #define SET_OFF_FMT_LEN 6 #define SET_TEXT_FMT (ao_strs_strtable+585) #define SET_TEXT_FMT_LEN 12 #define SGL_ARG_FMT (ao_strs_strtable+6019) #define SGL_ARG_FMT_LEN 258 #define SGL_DEF_FMT (ao_strs_strtable+6278) #define SGL_DEF_FMT_LEN 68 #define SGL_NO_DEF_FMT (ao_strs_strtable+6347) #define SGL_NO_DEF_FMT_LEN 61 #define SHELL_MAGIC (ao_strs_strtable+598) #define SHELL_MAGIC_LEN 6 #define SHOW_PROG_ENV (ao_strs_strtable+605) #define SHOW_PROG_ENV_LEN 19 #define SHOW_VAL_FMT (ao_strs_strtable+625) #define SHOW_VAL_FMT_LEN 17 #define START_MARK (ao_strs_strtable+6409) #define START_MARK_LEN 82 #define STDOUT (ao_strs_strtable+643) #define STDOUT_LEN 6 #define TIME_FMT (ao_strs_strtable+650) #define TIME_FMT_LEN 21 #define TMP_USAGE_FMT (ao_strs_strtable+672) #define TMP_USAGE_FMT_LEN 12 #define TRUE_STR (ao_strs_strtable+685) #define TRUE_STR_LEN 4 #define TWO_SPACES_STR (ao_strs_strtable+254) #define TWO_SPACES_STR_LEN 2 #define TYPE_ATR_FMT (ao_strs_strtable+690) #define TYPE_ATR_FMT_LEN 12 #define UNK_OPT_FMT (ao_strs_strtable+6492) #define UNK_OPT_FMT_LEN 144 #define VER_STR (ao_strs_strtable+703) #define VER_STR_LEN 7 #define XML_HEX_BYTE_FMT (ao_strs_strtable+711) #define <API key> 7 #define YES_NEED_OPT_ARG (ao_strs_strtable+719) #define <API key> 18 #define apostrophe (ao_strs_strtable+738) #define apostrophe_LEN 4 #define arg_fmt (ao_strs_strtable+743) #define arg_fmt_LEN 5 #define init_optct (ao_strs_strtable+749) #define init_optct_LEN 13 #define set_dash (ao_strs_strtable+763) #define set_dash_LEN 6 #define zAll (ao_strs_strtable+257) #define zAll_LEN 3 #define zCfgAO_Flags (ao_strs_strtable+12) #define zCfgAO_Flags_LEN 12 #define zCfgProg (ao_strs_strtable+25) #define zCfgProg_LEN 7 #define zEquivMode (ao_strs_strtable+1175) #define zEquivMode_LEN 44 #define zFiveSpaces (ao_strs_strtable+244) #define zFiveSpaces_LEN 5 #define zFmtFmt (ao_strs_strtable+33) #define zFmtFmt_LEN 11 #define zFullOptFmt (ao_strs_strtable+1220) #define zFullOptFmt_LEN 34 #define zGnuBreak (ao_strs_strtable+45) #define zGnuBreak_LEN 5 #define zGnuFileArg (ao_strs_strtable+51) #define zGnuFileArg_LEN 5 #define zGnuKeyLArg (ao_strs_strtable+57) #define zGnuKeyLArg_LEN 4 #define zGnuNestArg (ao_strs_strtable+62) #define zGnuNestArg_LEN 5 #define zGnuOptArg (ao_strs_strtable+68) #define zGnuOptArg_LEN 6 #define zGnuOptFmt (ao_strs_strtable+75) #define zGnuOptFmt_LEN 10 #define zGnuTimeArg (ao_strs_strtable+86) #define zGnuTimeArg_LEN 4 #define zNone (ao_strs_strtable+91) #define zNone_LEN 4 #define zOptCookieCt (ao_strs_strtable+1255) #define zOptCookieCt_LEN 38 #define zOptCtFmt (ao_strs_strtable+1294) #define zOptCtFmt_LEN 30 #define zOptDisabl (ao_strs_strtable+1325) #define zOptDisabl_LEN 32 #define zOptNumFmt (ao_strs_strtable+1358) #define zOptNumFmt_LEN 41 #define zOptionCase (ao_strs_strtable+1400) #define zOptionCase_LEN 30 #define zOptionEndSelect (ao_strs_strtable+770) #define <API key> 16 #define zOptionFlag (ao_strs_strtable+787) #define zOptionFlag_LEN 15 #define zOptionFullName (ao_strs_strtable+803) #define zOptionFullName_LEN 15 #define zOptionPartName (ao_strs_strtable+819) #define zOptionPartName_LEN 17 #define zPresetFile (ao_strs_strtable+96) #define zPresetFile_LEN 37 #define zReqOptFmt (ao_strs_strtable+134) #define zReqOptFmt_LEN 13 #define zSepChars (ao_strs_strtable+0) #define zSepChars_LEN 3 #define zShrtGnuOptFmt (ao_strs_strtable+148) #define zShrtGnuOptFmt_LEN 2 #define zSixSpaces (ao_strs_strtable+237) #define zSixSpaces_LEN 6 #define zStdBoolArg (ao_strs_strtable+151) #define zStdBoolArg_LEN 3 #define zStdBreak (ao_strs_strtable+155) #define zStdBreak_LEN 7 #define zStdFileArg (ao_strs_strtable+163) #define zStdFileArg_LEN 3 #define zStdKeyArg (ao_strs_strtable+167) #define zStdKeyArg_LEN 3 #define zStdKeyLArg (ao_strs_strtable+171) #define zStdKeyLArg_LEN 3 #define zStdNestArg (ao_strs_strtable+175) #define zStdNestArg_LEN 3 #define zStdNoArg (ao_strs_strtable+179) #define zStdNoArg_LEN 3 #define zStdNumArg (ao_strs_strtable+183) #define zStdNumArg_LEN 3 #define zStdOptArg (ao_strs_strtable+187) #define zStdOptArg_LEN 3 #define zStdReqArg (ao_strs_strtable+191) #define zStdReqArg_LEN 3 #define zStdStrArg (ao_strs_strtable+195) #define zStdStrArg_LEN 3 #define zStdTimeArg (ao_strs_strtable+199) #define zStdTimeArg_LEN 3 #define zTabHyp (ao_strs_strtable+203) #define zTabHypAnd (ao_strs_strtable+217) #define zTabHypAnd_LEN 11 #define zTabHyp_LEN 6 #define zTabSpace (ao_strs_strtable+210) #define zTabSpace_LEN 6 #define zTabout (ao_strs_strtable+229) #define zTabout_LEN 7 #define zThreeSpaces (ao_strs_strtable+250) #define zThreeSpaces_LEN 3 #define zTwoSpaces (ao_strs_strtable+254) #define zTwoSpaces_LEN 2 #define zambig_file (ao_strs_strtable+4) #define zambig_file_LEN 7 extern char const ao_strs_strtable[6637]; #endif /* <API key> */
$.extend(wot, { ratingwindow: { sliderwidth: 194, /* rating state */ state: {}, updatestate: function(target, data) { /* initialize on target change */ if (this.state.target != target) { this.finishstate(); this.state = { target: target, down: -1 }; } var state = {}; /* add existing ratings to state */ if (data && data.status == wot.cachestatus.ok) { wot.components.forEach(function(item) { var datav = data.value[item.name]; if (datav && datav.t >= 0) { state[item.name] = { t: datav.t }; } }); } /* remember previous state */ this.state = $.extend(state, this.state); }, setstate: function(component, t) { if (t >= 0) { this.state[component] = { t: t }; } else { delete(this.state[component]); } }, finishstate: function() { wot.post("rating", "finishstate", { state: this.state }); }, /* helpers */ navigate: function(url, context) { try { var contextedurl = wot.contextedurl(url, context); wot.post("rating", "navigate", { url: contextedurl }); this.hide(); } catch (e) { wot.log("ratingwindow.navigate: failed with " + e, true); } }, getcached: function() { if (this.current.target && this.current.cached && this.current.cached.status == wot.cachestatus.ok) { return this.current.cached; } return { value: {} }; }, getrating: function(e, stack) { try { if (this.getcached().status == wot.cachestatus.ok) { var slider = $(".wot-rating-slider", stack); /* rating from slider position */ var position = 100 * (e.clientX - slider.position().left) / wot.ratingwindow.sliderwidth; /* sanitize the rating value */ if (position < 0) { position = 0; } else if (position > 100) { position = 100; } else { position = position.toFixed(); } return position; } } catch (e) { wot.log("ratingwindow.getrating: failed with " + e, true); } return -1; }, /* user interface */ current: {}, updateratings: function(state) { /* indicator state */ state = state || {}; var cached = this.getcached(); /* update each component */ wot.components.forEach(function(item) { if (state.name != null && state.name != item.name) { return; } var elems = {}; [ "stack", "slider", "indicator", "helptext", "helplink" ].forEach(function(elem) { elems[elem] = $("#wot-rating-" + item.name + "-" + elem); }); var t = -1, wrs = wot.ratingwindow.state[item.name]; if (wrs && wrs.t != null) { t = wrs.t; } if (t >= 0) { /* rating */ elems.indicator.css("left", (t * wot.ratingwindow.sliderwidth / 100).toFixed() + "px"); elems.stack.addClass("testimony").removeClass("hover"); } else if (state.name != null && state.t >= 0) { /* temporary indicator position */ elems.indicator.css("left", (state.t * wot.ratingwindow.sliderwidth / 100).toFixed() + "px"); elems.stack.removeClass("testimony").addClass("hover"); } else { elems.stack.removeClass("testimony").removeClass("hover"); } var helptext = "", cachedv = cached.value[item.name]; if (t >= 0) { var r = (cachedv && cachedv.r != null) ? cachedv.r : -1; if (r >= 0 && Math.abs(r - t) > 35) { helptext = wot.i18n("ratingwindow", "helptext"); elems.helplink.text(wot.i18n("ratingwindow", "helplink")) .addClass("comment"); } else { helptext = wot.i18n("reputationlevels", wot.getlevel(wot.reputationlevels, t).name); elems.helplink.text("").removeClass("comment"); } } else { elems.helplink.text("").removeClass("comment"); } if (helptext.length) { elems.helptext.text(helptext).css("display", "block"); } else { elems.helptext.hide(); } }); }, updatecontents: function() { var cached = this.getcached(); /* update current rating state */ this.updatestate(this.current.target, cached); /* target */ if (this.current.target && cached.status == wot.cachestatus.ok) { $("#wot-title-text").text( this.current.decodedtarget || this.current.target); } else if (cached.status == wot.cachestatus.busy) { $("#wot-title-text").text(wot.i18n("messages", "loading")); } else if (cached.status == wot.cachestatus.error) { $("#wot-title-text").text(wot.i18n("messages", "failed")); } else { $("#wot-title-text").text(wot.i18n("messages", this.current.status || "notavailable")); } /* reputations */ wot.components.forEach(function(item) { var cachedv = cached.value[item.name]; if (wot.ratingwindow.settings["show_application_" + item.name]) { $("#wot-rating-" + item.name + ", #wot-rating-" + item.name + "-border").css("display", "block"); } else { $("#wot-rating-" + item.name + ", #wot-rating-" + item.name + "-border").hide(); } $("#wot-rating-" + item.name + "-reputation").attr("reputation", (cached.status == wot.cachestatus.ok) ? wot.getlevel(wot.reputationlevels, (cachedv && cachedv.r != null) ? cachedv.r : -1).name : ""); $("#wot-rating-" + item.name + "-confidence").attr("confidence", (cached.status == wot.cachestatus.ok) ? wot.getlevel(wot.confidencelevels, (cachedv && cachedv.c != null)? cachedv.c : -1).name : ""); }); /* ratings */ this.updateratings(); /* message */ if (this.usercontent.message.text) { $("#wot-message-text") .attr("url", this.usercontent.message.url || "") .attr("status", this.usercontent.message.type || "") .text(this.usercontent.message.text); $("#wot-message").show(); } else { $("#wot-message").hide(); } /* user content */ $(".wot-user").hide(); this.usercontent.content.forEach(function(item, index) { if (item.bar && item.length != null && item.label) { $("#wot-user-" + index + "-header").text(item.bar); $("#wot-user-" + index + "-bar-text").text(item.label); $("#wot-user-" + index + "-bar-image").attr("length", item.length).show(); } else { $("#wot-user-" + index + "-header").text(""); $("#wot-user-" + index + "-bar-text").text(""); $("#wot-user-" + index + "-bar-image").hide(); } $("#wot-user-" + index + "-text").attr("url", item.url || ""); if (item.notice) { $("#wot-user-" + index + "-notice").text(item.notice).show(); } else { $("#wot-user-" + index + "-notice").hide(); } if (item.text) { $("#wot-user-" + index + "-text").text(item.text); $("#wot-user-" + index).css("display", "block"); } }); /* partner */ $("#wot-partner").attr("partner", wot.partner || ""); /* resize the pop-up window */ wot.post("rating", "resizepopup", { height: $("#wot-ratingwindow").height() + 20 }); }, update: function(data) { try { this.current = data || {}; this.updatecontents(); } catch (e) { wot.log("ratingwindow.update: failed with " + e, true); } }, hide: function() { wot.ratingwindow.finishstate(); window.close(); }, loadsettings: function(ondone) { var prefs = [ "accessible" ]; wot.components.forEach(function(item) { prefs.push("show_application_" + item.name); }); this.settings = this.settings || {}; wot.prefs.load(prefs, function(name, value) { wot.ratingwindow.settings[name] = value; }, ondone); }, onload: function() { wot.bind("message:status:update", function(port, data) { wot.ratingwindow.usercontent = data.usercontent; wot.ratingwindow.update(data.data); }); wot.listen("status"); /* accessibility */ $("#wot-header-logo, " + "#wot-header-button, " + ".wot-header-link, " + "#wot-title-text, " + ".<API key>, " + ".wot-rating-slider, " + ".wot-rating-helplink, " + "#<API key>, " + ".wot-scorecard-text, " + ".wot-user-text, " + "#wot-message-text") .toggleClass("accessible", this.settings.accessible); /* texts */ wot.components.forEach(function(item) { $("#wot-rating-" + item.name + "-header").text(wot.i18n("components", item.name) + ":"); }); [ { selector: "#<API key>", text: wot.i18n("ratingwindow", "guide") }, { selector: "#<API key>", text: wot.i18n("ratingwindow", "settings") }, { selector: "#wot-title-text", text: wot.i18n("messages", "initializing") }, { selector: "#<API key>", text: wot.i18n("ratingwindow", "wotrating") }, { selector: "#<API key>", text: wot.i18n("ratingwindow", "myrating") }, { selector: "#wot-scorecard-visit", text: wot.i18n("ratingwindow", "viewscorecard") }, { selector: "#<API key>", text: wot.i18n("ratingwindow", "addcomment") }, { selector: "#wot-partner-text", text: wot.i18n("ratingwindow", "inpartnership") } ].forEach(function(item) { $(item.selector).text(item.text); }); if (wot.partner) { $("#wot-partner").attr("partner", wot.partner); } /* user interface event handlers */ var wurls = wot.urls; $("#wot-header-logo").bind("click", function() { wot.ratingwindow.navigate(wurls.base, wurls.contexts.rwlogo); }); $("#<API key>").bind("click", function() { wot.ratingwindow.navigate(wurls.settings, wurls.contexts.rwsettings); }); $("#<API key>").bind("click", function() { wot.ratingwindow.navigate(wurls.settings + "/guide", wurls.contexts.rwguide); }); $("#wot-header-button").bind("click", function() { wot.ratingwindow.hide(); }); $("#wot-title").bind("click", function() { /* TODO: enable the add-on if disabled */ }); $(".wot-rating-helplink, #<API key>").bind("click", function(event) { if (wot.ratingwindow.current.target) { var url = wurls.scorecard + encodeURIComponent(wot.ratingwindow.current.target) + "/comment"; wot.ratingwindow.navigate(url, wurls.contexts.rwviewsc); } event.stopPropagation(); }); $("#<API key>").hover( function() { $("#wot-scorecard-visit").addClass("inactive"); }, function() { $("#wot-scorecard-visit").removeClass("inactive"); }); $("#<API key>").bind("click", function() { if (wot.ratingwindow.current.target) { wot.ratingwindow.navigate(wot.urls.scorecard + encodeURIComponent(wot.ratingwindow.current.target), wurls.contexts.rwviewsc); } }); $(".wot-user-text").bind("click", function() { var url = $(this).attr("url"); if (url) { wot.ratingwindow.navigate(url, wurls.contexts.rwprofile); } }); $("#wot-message").bind("click", function() { var url = $("#wot-message-text").attr("url"); if (url) { wot.ratingwindow.navigate(url, wurls.contexts.rwmsg); } }); $(".wot-rating-stack").bind("mousedown", function(e) { var c = $(this).attr("component"); var t = wot.ratingwindow.getrating(e, this); wot.ratingwindow.state.down = c; wot.ratingwindow.setstate(c, t); wot.ratingwindow.updateratings({ name: c, t: t }); }); $(".wot-rating-stack").bind("mouseup", function(e) { wot.ratingwindow.state.down = -1; /* opera: no unload event, so finish after every click */ wot.ratingwindow.finishstate(); }); $(".wot-rating-stack").bind("mousemove", function(e) { var c = $(this).attr("component"); var t = wot.ratingwindow.getrating(e, this); if (wot.ratingwindow.state.down == c) { wot.ratingwindow.setstate(c, t); } else { wot.ratingwindow.state.down = -1; } wot.ratingwindow.updateratings({ name: c, t: t }); }); $("#wot-ratingwindow").bind("click", function(e) { event.stopPropagation(); }); $("body").bind("click", function(e) { wot.ratingwindow.hide(); }); $(window).unload(function() { /* submit ratings and update views */ wot.ratingwindow.finishstate(); }); wot.post("update", "status"); } }}); $(document).ready(function() { wot.ratingwindow.loadsettings(function() { wot.ratingwindow.onload(); }); });
package org.mycore.lookup.common; import java.lang.reflect.Constructor; import java.lang.reflect.<API key>; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * <p> * This class parses and resolve strings which contains variables. To add a * variable call <code>addVariable</code>. * </p> * <p> * The algorithm is optimized that each character is touched only once. * </p> * <p> * To resolve a string a valid syntax is required: * </p> * <p> * <b>{}:</b> Use curly brackets for variables or properties. For example * "{var1}" or "{MCR.basedir}" * </p> * <p> * <b>[]:</b> Use squared brackets to define a condition. All data within * squared brackets is only used if the internal variables are not null and not * empty. For example "[hello {lastName}]" is only resolved if the value of * "lastName" is not null and not empty. Otherwise the whole content in the * squared brackets are ignored. * </p> * <p> * <b>\:</b> Use the escape character to use all predefined characters. * </p> * <p> * Sample:<br> * "Lastname: {lastName}[, Firstname: {firstName}]"<br> * </p> * * @author Matthias Eichner */ public class TextResolver { /** The Constant LOGGER. */ private static final Logger LOGGER = LogManager.getLogger(TextResolver.class); /** The term container. */ protected TermContainer termContainer; /** * This map contains all variables that can be resolved. */ protected Map<String, String> variablesMap; /** * Retains the text if a variable couldn't be resolved. Example if * {Variable} could not be resolved: true: "Hello {Variable}" -&gt; "Hello * {Variable}" false: "Hello " * <p> * By default retainText is true * </p> */ protected boolean retainText; /** * Defines how deep the text is resolved. * <dl> * <dt>Deep</dt> * <dd>everything is resolved</dd> * <dt>NoVariables</dt> * <dd>the value of variables is not being resolved</dd> * </dl> */ protected ResolveDepth resolveDepth; /** The tracker. */ protected <API key> tracker; protected void <API key>() throws <API key>, <API key>, <API key>, <API key> { registerTerm(Variable.class); registerTerm(Condition.class); registerTerm(EscapeCharacter.class); } public void registerTerm(Class<? extends Term> termClass) throws <API key>, <API key>, <API key>, <API key> { this.termContainer.add(termClass); } public void unregisterTerm(Class<? extends Term> termClass) throws <API key>, <API key>, <API key>, <API key> { this.termContainer.remove(termClass); } /** * Defines how deep the text is resolved. * <dl> * <dt>Deep</dt> * <dd>everything is resolved</dd> * <dt>NoVariables</dt> * <dd>the value of variables is not being resolved</dd> * </dl> */ public enum ResolveDepth { /** The Deep. */ Deep, /** The No variables. */ NoVariables } /** * Creates a new text resolver with a map of variables. */ public TextResolver() { this.variablesMap = new HashMap<>(); this.setResolveDepth(ResolveDepth.Deep); this.setRetainText(true); this.tracker = new <API key>(this); try { this.termContainer = new TermContainer(this); this.<API key>(); } catch (Exception exc) { throw new <API key>("Unable to register default terms", exc); } } /** * Creates a new text resolver. To add variables call * <code>addVariable</code>, otherwise only MyCoRe property resolving is * possible. * * @param variablesMap * the variables map */ public TextResolver(Map<String, String> variablesMap) { this(); mixin(variablesMap); } /** * Instantiates a new text resolver. * * @param properties * the properties */ public TextResolver(Properties properties) { this(); mixin(properties); } /** * Gets the term container. * * @return the term container */ protected TermContainer getTermContainer() { return this.termContainer; } /** * Gets the tracker. * * @return the tracker */ protected <API key> getTracker() { return this.tracker; } /** * Mixin. * * @param variables * the variables */ public void mixin(Map<String, String> variables) { for (Entry<String, String> entrySet : variables.entrySet()) { String key = entrySet.getKey(); String value = entrySet.getValue(); this.addVariable(key, value); } } /** * Mixin. * * @param properties * the properties */ public void mixin(Properties properties) { for (Entry<Object, Object> entrySet : properties.entrySet()) { String key = entrySet.getKey().toString(); String value = entrySet.getValue().toString(); this.addVariable(key, value); } } /** * Sets if the text should be retained if a variable couldn't be resolved. * <p> * Example:<br> * true: "Hello {Variable}" -&gt; "Hello {Variable}"<br> * false: "Hello " * </p> * <p> * By default retainText is true * </p> * * @param retainText * the new retain text */ public void setRetainText(boolean retainText) { this.retainText = retainText; } /** * Checks if the text should be retained if a variable couldn't be resolved. * <p> * By default retainText is true * </p> * * @return true, if is retain text */ public boolean isRetainText() { return this.retainText; } /** * Adds a new variable to the resolver. This overwrites a existing variable * with the same name. * * @param name * name of the variable * @param value * value of the variable * @return the previous value of the specified name, or null if it did not * have one */ public String addVariable(String name, String value) { return variablesMap.put(name, value); } /** * Removes a variable from the resolver. This method does nothing if no * variable with the name exists. * * @param name * the name * @return the value of the removed variable, or null if no variable with * the name exists */ public String removeVariable(String name) { return variablesMap.remove(name); } /** * Checks if a variable with the specified name exists. * * @param name * the name * @return true if a variable exists, otherwise false */ public boolean containsVariable(String name) { return variablesMap.containsKey(name); } /** * Sets the resolve depth. * * @param resolveDepth * defines how deep the text is resolved. */ public void setResolveDepth(ResolveDepth resolveDepth) { this.resolveDepth = resolveDepth; } /** * Returns the current resolve depth. * * @return resolve depth enumeration */ public ResolveDepth getResolveDepth() { return this.resolveDepth; } /** * This method resolves all variables in the text. The syntax is described * at the head of the class. * * @param text * the string where the variables have to be resolved * @return the resolved string */ public String resolve(String text) { this.getTracker().clear(); Text textResolver = new Text(this); textResolver.resolve(text, 0); return textResolver.getValue(); } /** * Returns the value of a variable. * * @param varName * the name of the variable * @return the value */ public String getValue(String varName) { return variablesMap.get(varName); } /** * Returns a <code>Map</code> of all variables. * * @return a <code>Map</code> of all variables. */ public Map<String, String> getVariables() { return variablesMap; } /** * A term is a defined part in a text. In general, a term is defined by * brackets, but this is not required. Here are some example terms: * <ul> * <li>Variable: {term1}</li> * <li>Condition: [term2]</li> * <li>EscapeChar: \[</li> * </ul> * * You can write your own terms and add them to the text resolver. A sample * is shown in the <code>MCRTextResolverTest</code> class. * * @author Matthias Eichner */ protected static abstract class Term { /** * The string buffer within the term. For example: {<b>var</b>}. */ protected StringBuffer termBuffer; /** * If the term is successfully resolved. By default this is true. */ protected boolean resolved; /** * The current character position in the term. */ protected int position; /** The text resolver. */ protected TextResolver textResolver; /** * Instantiates a new term. * * @param textResolver * the text resolver */ public Term(TextResolver textResolver) { this.textResolver = textResolver; this.termBuffer = new StringBuffer(); this.resolved = true; this.position = 0; } /** * Resolves the text from the startPosition to the end of the text or if * a term specific end character is found. * * @param text * the term to resolve * @param startPosition * the current character position * @return the value of the term after resolving */ public String resolve(String text, int startPosition) { for (position = startPosition; position < text.length(); position++) { Term internalTerm = getTerm(text, position); if (internalTerm != null) { position += internalTerm.<API key>().length(); internalTerm.resolve(text, position); if (!internalTerm.resolved) { resolved = false; } position = internalTerm.position; termBuffer.append(internalTerm.getValue()); } else { boolean complete = resolveInternal(text, position); if (complete) { int endEnclosingSize = <API key>().length(); if (endEnclosingSize > 1) { position += endEnclosingSize - 1; } break; } } } return getValue(); } /** * Returns a new term in dependence of the current character (position * of the text). If no term is defined null is returned. * * @param text * the text * @param pos * the pos * @return a term or null if no one found */ private Term getTerm(String text, int pos) { TermContainer termContainer = this.getTextResolver().getTermContainer(); for (Entry<String, Class<? extends Term>> termEntry : termContainer.getTermSet()) { String <API key> = termEntry.getKey(); if (text.startsWith(<API key>, pos) && !<API key>.equals(this.<API key>())) { try { return termContainer.instantiate(termEntry.getValue()); } catch (Exception exc) { LOGGER.error(exc); } } } return null; } /** * Does term specific resolving for the current character. * * @param text * the text * @param pos * the pos * @return true if the end string is reached, otherwise false */ protected abstract boolean resolveInternal(String text, int pos); /** * Returns the value of the term. Overwrite this if you don't want to * get the default termBuffer content as value. * * @return the value of the term */ public String getValue() { return termBuffer.toString(); } /** * Implement this to define the start enclosing string for your term. * The resolver searches in the text for this string, if found, the text * is processed by your term. * * @return the start enclosing string */ public abstract String <API key>(); /** * Implement this to define the end enclosing string for your term. You * have to check manual in the <code>resolveInternal</code> method if * the end of your term is reached. * * @return the end enclosing string */ public abstract String <API key>(); /** * Gets the text resolver. * * @return the text resolver */ public TextResolver getTextResolver() { return textResolver; } } /** * A variable is surrounded by curly brackets. It supports recursive * resolving for the content of the variable. The name of the variable is * set by the termBuffer and the value is equal the content of the * valueBuffer. */ protected static class Variable extends Term { /** * A variable doesn't return the termBuffer, but this valueBuffer. */ private StringBuffer valueBuffer; /** The complete. */ private boolean complete; /** * Instantiates a new variable. * * @param textResolver * the text resolver */ public Variable(TextResolver textResolver) { super(textResolver); valueBuffer = new StringBuffer(); complete = false; } /* (non-Javadoc) * @see de.uni_jena.rz.services.common.TextResolver.Term#resolveInternal(java.lang.String, int) */ @Override public boolean resolveInternal(String text, int pos) { if (text.startsWith(<API key>(), pos)) { this.track(); // get the value from the variables table String value = getTextResolver().getValue(termBuffer.toString()); if (value == null) { resolved = false; if (getTextResolver().isRetainText()) { this.valueBuffer.append(<API key>()).append(termBuffer.toString()) .append(<API key>()); } this.untrack(); complete = true; return true; } // resolve the content of the variable recursive // to resolve all other internal variables, condition etc. if (getTextResolver().getResolveDepth() != ResolveDepth.NoVariables) { Text <API key> = resolveText(value); resolved = <API key>.resolved; value = <API key>.getValue(); } // set the value of the variable valueBuffer.append(value); this.untrack(); complete = true; return true; } termBuffer.append(text.charAt(pos)); return false; } /* (non-Javadoc) * @see de.uni_jena.rz.services.common.TextResolver.Term#getValue() */ @Override public String getValue() { if (!complete) { // assume that the variable is not complete StringBuffer buf = new StringBuffer(); buf.append(<API key>()).append(termBuffer.toString()); return buf.toString(); } return valueBuffer.toString(); } /* (non-Javadoc) * @see de.uni_jena.rz.services.common.TextResolver.Term#<API key>() */ @Override public String <API key>() { return "{"; } /* (non-Javadoc) * @see de.uni_jena.rz.services.common.TextResolver.Term#<API key>() */ @Override public String <API key>() { return "}"; } /** * Tracks the variable to check for circular dependency. */ protected void track() { this.getTextResolver().getTracker().track("var", getTrackID()); } /** * Untrack. */ protected void untrack() { this.getTextResolver().getTracker().untrack("var", getTrackID()); } /** * Gets the track ID. * * @return the track ID */ protected String getTrackID() { return new StringBuffer(<API key>()).append(termBuffer.toString()) .append(<API key>()).toString(); } /** * This method resolves all variables in the text. The syntax is * described at the head of the class. * * @param text * the string where the variables have to be resolved * @return the resolved string */ public Text resolveText(String text) { Text textResolver = new Text(getTextResolver()); textResolver.resolve(text, 0); return textResolver; } } /** * A condition is defined by squared brackets. All data which is set in * these brackets is only used if the internal variables are not null and * not empty. For example "[hello {lastName}]" is only resolved if the value * of "lastName" is not null and not empty. Otherwise the whole content in * the squared brackets are ignored. */ protected static class Condition extends Term { /** * Instantiates a new condition. * * @param textResolver * the text resolver */ public Condition(TextResolver textResolver) { super(textResolver); } /* (non-Javadoc) * @see de.uni_jena.rz.services.common.TextResolver.Term#resolveInternal(java.lang.String, int) */ @Override protected boolean resolveInternal(String text, int pos) { if (text.startsWith(<API key>(), pos)) { return true; } termBuffer.append(text.charAt(pos)); return false; } /* (non-Javadoc) * @see de.uni_jena.rz.services.common.TextResolver.Term#getValue() */ @Override public String getValue() { if (resolved) { return super.getValue(); } return ""; } /* (non-Javadoc) * @see de.uni_jena.rz.services.common.TextResolver.Term#<API key>() */ @Override public String <API key>() { return "["; } /* (non-Javadoc) * @see de.uni_jena.rz.services.common.TextResolver.Term#<API key>() */ @Override public String <API key>() { return "]"; } } /** * As escape character the backslashed is used. Only the first character * after the escape char is add to the term. */ protected static class EscapeCharacter extends Term { /** * Instantiates a new escape character. * * @param textResolver * the text resolver */ public EscapeCharacter(TextResolver textResolver) { super(textResolver); } /* (non-Javadoc) * @see de.uni_jena.rz.services.common.TextResolver.Term#resolveInternal(java.lang.String, int) */ @Override public boolean resolveInternal(String text, int pos) { return true; } /* (non-Javadoc) * @see de.uni_jena.rz.services.common.TextResolver.Term#resolve(java.lang.String, int) */ @Override public String resolve(String text, int startPos) { position = startPos; char c = text.charAt(position); termBuffer.append(c); return termBuffer.toString(); } /* (non-Javadoc) * @see de.uni_jena.rz.services.common.TextResolver.Term#<API key>() */ @Override public String <API key>() { return "\\"; } /* (non-Javadoc) * @see de.uni_jena.rz.services.common.TextResolver.Term#<API key>() */ @Override public String <API key>() { return ""; } } /** * A simple text, every character is added to the term (except its a special * one). */ protected static class Text extends Term { /** * Instantiates a new text. * * @param textResolver * the text resolver */ public Text(TextResolver textResolver) { super(textResolver); } /* (non-Javadoc) * @see de.uni_jena.rz.services.common.TextResolver.Term#resolveInternal(java.lang.String, int) */ @Override public boolean resolveInternal(String text, int pos) { termBuffer.append(text.charAt(pos)); return false; } /* (non-Javadoc) * @see de.uni_jena.rz.services.common.TextResolver.Term#<API key>() */ @Override public String <API key>() { return ""; } /* (non-Javadoc) * @see de.uni_jena.rz.services.common.TextResolver.Term#<API key>() */ @Override public String <API key>() { return ""; } } /** * Simple class to hold terms and instantiate them. */ protected static class TermContainer { /** The term map. */ protected Map<String, Class<? extends Term>> termMap = new HashMap<String, Class<? extends Term>>(); /** The text resolver. */ protected TextResolver textResolver; /** * Instantiates a new term container. * * @param textResolver * the text resolver */ public TermContainer(TextResolver textResolver) { this.textResolver = textResolver; } public Term instantiate(Class<? extends Term> termClass) throws <API key>, <API key>, <API key>, <API key> { Constructor<? extends Term> c = termClass.getConstructor(TextResolver.class); return c.newInstance(this.textResolver); } public void add(Class<? extends Term> termClass) throws <API key>, <API key>, <API key>, <API key> { Term term = instantiate(termClass); this.termMap.put(term.<API key>(), termClass); } public void remove(Class<? extends Term> termClass) throws <API key>, <API key>, <API key>, <API key> { Term term = instantiate(termClass); this.termMap.remove(term.<API key>()); } /** * Gets the term set. * * @return the term set */ public Set<Entry<String, Class<? extends Term>>> getTermSet() { return this.termMap.entrySet(); } } /** * The Class <API key>. */ protected static class <API key> { /** The text resolver. */ protected TextResolver textResolver; /** The track map. */ protected Map<String, List<String>> trackMap; /** * Instantiates a new circular dependency tracker. * * @param textResolver * the text resolver */ public <API key>(TextResolver textResolver) { this.textResolver = textResolver; this.trackMap = new HashMap<>(); } /** * Track. * * @param type * the type * @param id * the id * @throws <API key> * the circular dependency execption */ public void track(String type, String id) throws <API key> { List<String> idList = trackMap.get(type); if (idList == null) { idList = new ArrayList<>(); trackMap.put(type, idList); } if (idList.contains(id)) { throw new <API key>(idList, id); } idList.add(id); } /** * Untrack. * * @param type * the type * @param id * the id */ public void untrack(String type, String id) { List<String> idList = trackMap.get(type); if (idList == null) { LOGGER.error("text resolver circular dependency tracking error: cannot get type " + type + " of " + id); return; } idList.remove(id); } /** * Clear. */ public void clear() { this.trackMap.clear(); } } /** * The Class <API key>. */ protected static class <API key> extends RuntimeException { /** The Constant serialVersionUID. */ private static final long serialVersionUID = -<API key>; /** The dependency list. */ private List<String> dependencyList; /** The id. */ private String id; /** * Instantiates a new circular dependency execption. * * @param dependencyList * the dependency list * @param id * the id */ public <API key>(List<String> dependencyList, String id) { this.dependencyList = dependencyList; this.id = id; } /* (non-Javadoc) * @see java.lang.Throwable#getMessage() */ @Override public String getMessage() { StringBuffer msg = new StringBuffer("A circular dependency exception occurred"); msg.append("\n").append("circular path: "); for (String dep : dependencyList) { msg.append(dep).append(" > "); } msg.append(id); return msg.toString(); } /** * Gets the id. * * @return the id */ public String getId() { return id; } /** * Gets the dependency list. * * @return the dependency list */ public List<String> getDependencyList() { return dependencyList; } } }
using Newtonsoft.Json; using ShareX.UploadersLib.Properties; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Windows.Forms; namespace ShareX.UploadersLib.FileUploaders { public class <API key> : FileUploaderService { public override FileDestination EnumValue { get; } = FileDestination.Lambda; public override Icon ServiceIcon => Resources.Lambda; public override bool CheckConfig(UploadersConfig config) { return config.LambdaSettings != null && !string.IsNullOrEmpty(config.LambdaSettings.UserAPIKey); } public override GenericUploader CreateUploader(UploadersConfig config, TaskReferenceHelper taskInfo) { // Correct old URLs if (config.LambdaSettings != null && config.LambdaSettings.UploadURL == "https: { config.LambdaSettings.UploadURL = "https://lbda.net/"; } return new Lambda(config.LambdaSettings); } public override TabPage <API key>(UploadersConfigForm form) => form.tpLambda; } public sealed class Lambda : FileUploader { public LambdaSettings Config { get; private set; } public Lambda(LambdaSettings config) { Config = config; } private const string uploadUrl = "https://lbda.net/api/upload"; public static string[] UploadURLs = new string[] { "https: public override UploadResult Upload(Stream stream, string fileName) { Dictionary<string, string> arguments = new Dictionary<string, string>(); arguments.Add("api_key", Config.UserAPIKey); UploadResult result = SendRequestFile(uploadUrl, stream, fileName, "file", arguments, method: HttpMethod.PUT); if (result.Response == null) { Errors.Add("Upload failed for unknown reason. Check your API key."); return result; } LambdaResponse response = JsonConvert.DeserializeObject<LambdaResponse>(result.Response); if (result.IsSuccess) { result.URL = Config.UploadURL + response.url; } else { foreach (string e in response.errors) { Errors.Add(e); } } return result; } internal class LambdaResponse { public string url { get; set; } public List<string> errors { get; set; } } internal class LambdaFile { public string url { get; set; } } } public class LambdaSettings { public string UserAPIKey = ""; public string UploadURL = "https://lbda.net/"; } }
#ifndef __FTGMAC100_H #define __FTGMAC100_H #define <API key> 0x00 #define <API key> 0x04 #define <API key> 0x08 #define <API key> 0x0c #define <API key> 0x10 #define <API key> 0x14 #define <API key> 0x18 #define <API key> 0x1c #define <API key> 0x20 #define <API key> 0x24 #define <API key> 0x28 #define <API key> 0x2c #define <API key> 0x30 #define <API key> 0x34 #define <API key> 0x38 #define <API key> 0x3c #define <API key> 0x40 #define <API key> 0x44 #define <API key> 0x48 #define <API key> 0x4c #define <API key> 0x50 #define <API key> 0x54 #define FTGMAC100_OFFSET_TM 0x58 #define <API key> 0x60 #define <API key> 0x64 #define <API key> 0x68 #define <API key> 0x6c #define <API key> 0x70 #define <API key> 0x74 #define <API key> 0x78 #define <API key> 0x80 #define <API key> 0x84 #define <API key> 0x88 #define <API key> 0x8c #define <API key> 0x90 #define <API key> 0x94 #define <API key> 0x98 #define FTGMAC100_OFFSET_TX 0xa0 #define <API key> 0xa4 #define <API key> 0xa8 #define <API key> 0xac #define FTGMAC100_OFFSET_RX 0xb0 #define <API key> 0xb4 #define <API key> 0xb8 #define <API key> 0xbc #define <API key> 0xc0 #define <API key> 0xc4 #define <API key> 0xc8 /* * Interrupt status register & interrupt enable register */ #define <API key> (1 << 0) #define <API key> (1 << 1) #define <API key> (1 << 2) #define <API key> (1 << 3) #define <API key> (1 << 4) #define <API key> (1 << 5) #define <API key> (1 << 6) #define <API key> (1 << 7) #define <API key> (1 << 8) #define <API key> (1 << 9) #define <API key> (1 << 10) /* * Interrupt timer control register */ #define <API key>(x) (((x) & 0xf) << 0) #define <API key>(x) (((x) & 0x7) << 4) #define <API key> (1 << 7) #define <API key>(x) (((x) & 0xf) << 8) #define <API key>(x) (((x) & 0x7) << 12) #define <API key> (1 << 15) /* * Automatic polling timer control register */ #define <API key>(x) (((x) & 0xf) << 0) #define <API key> (1 << 4) #define <API key>(x) (((x) & 0xf) << 8) #define <API key> (1 << 12) /* * DMA burst length and arbitration control register */ #define <API key>(x) (((x) & 0x7) << 0) #define <API key>(x) (((x) & 0x7) << 3) #define <API key> (1 << 6) #define <API key>(x) (((x) & 0x3) << 8) #define <API key>(x) (((x) & 0x3) << 10) #define <API key>(x) (((x) & 0xf) << 12) #define <API key>(x) (((x) & 0xf) << 16) #define <API key>(x) (((x) & 0x7) << 20) #define <API key> (1 << 23) /* * DMA FIFO status register */ #define <API key>(dmafifos) ((dmafifos) & 0xf) #define <API key>(dmafifos) (((dmafifos) >> 4) & 0xf) #define <API key>(dmafifos) (((dmafifos) >> 8) & 0x7) #define <API key>(dmafifos) (((dmafifos) >> 12) & 0xf) #define <API key>(dmafifos) (((dmafifos) >> 16) & 0x3) #define <API key>(dmafifos) (((dmafifos) >> 18) & 0xf) #define <API key> (1 << 26) #define <API key> (1 << 27) #define <API key> (1 << 28) #define <API key> (1 << 29) #define <API key> (1 << 30) #define <API key> (1 << 31) /* * Feature Register */ #define <API key> BIT(31) /* * Receive buffer size register */ #define FTGMAC100_RBSR_SIZE(x) ((x) & 0x3fff) /* * MAC control register */ #define <API key> (1 << 0) #define <API key> (1 << 1) #define <API key> (1 << 2) #define <API key> (1 << 3) #define <API key> (1 << 4) #define <API key> (1 << 5) #define <API key> (1 << 6) #define <API key> (1 << 7) #define <API key> (1 << 8) #define <API key> (1 << 9) #define <API key> (1 << 10) #define <API key> (1 << 11) #define <API key> (1 << 12) #define <API key> (1 << 13) #define <API key> (1 << 14) #define <API key> (1 << 15) #define <API key> (1 << 16) #define <API key> (1 << 17) #define <API key> (1 << 18) #define <API key> (1 << 19) #define <API key> (1 << 31) /* * PHY control register */ #define <API key> 0x3f #define <API key>(x) ((x) & 0x3f) #define <API key>(x) (((x) & 0x1f) << 16) #define <API key>(x) (((x) & 0x1f) << 21) #define <API key> (1 << 26) #define <API key> (1 << 27) /* * PHY data register */ #define <API key>(x) ((x) & 0xffff) #define <API key>(phydata) (((phydata) >> 16) & 0xffff) /* * Transmit descriptor, aligned to 16 bytes */ struct ftgmac100_txdes { unsigned int txdes0; unsigned int txdes1; unsigned int txdes2; /* not used by HW */ unsigned int txdes3; /* TXBUF_BADR */ } __attribute__ ((aligned(16))); #define <API key>(x) ((x) & 0x3fff) #define <API key> (1 << 19) #define <API key> (1 << 28) #define <API key> (1 << 29) #define <API key> (1 << 31) #define <API key>(x) ((x) & 0xffff) #define <API key> (1 << 16) #define <API key> (1 << 17) #define <API key> (1 << 18) #define <API key> (1 << 19) #define <API key> (1 << 22) #define <API key> (1 << 30) #define <API key> (1 << 31) /* * Receive descriptor, aligned to 16 bytes */ struct ftgmac100_rxdes { unsigned int rxdes0; unsigned int rxdes1; unsigned int rxdes2; /* not used by HW */ unsigned int rxdes3; /* RXBUF_BADR */ } __attribute__ ((aligned(16))); #define <API key> 0x3fff #define <API key> (1 << 16) #define <API key> (1 << 17) #define <API key> (1 << 18) #define <API key> (1 << 19) #define <API key> (1 << 20) #define <API key> (1 << 21) #define <API key> (1 << 22) #define <API key> (1 << 23) #define <API key> (1 << 24) #define <API key> (1 << 25) #define <API key> (1 << 28) #define <API key> (1 << 29) #define <API key> (1 << 31) #define <API key> 0xffff #define <API key> (0x3 << 20) #define <API key> (0x0 << 20) #define <API key> (0x1 << 20) #define <API key> (0x2 << 20) #define <API key> (0x3 << 20) #define <API key> (1 << 22) #define FTGMAC100_RXDES1_DF (1 << 23) #define <API key> (1 << 24) #define <API key> (1 << 25) #define <API key> (1 << 26) #define <API key> (1 << 27) #endif /* __FTGMAC100_H */
<?php // Heading $_['heading_title'] = 'Cadastre sua conta'; // Text $_['text_account'] = 'Programa de afiliados'; $_['text_register'] = 'Cadastre-se'; $_['<API key>'] = 'Se você já tem uma conta de afiliado em nossa loja, acesse sua conta <a href="%s">clicando aqui</a>.'; $_['text_signup'] = 'Para cadastrar uma conta de afiliado, preencha o formulário abaixo, garantindo que todas as informações estejam corretamente preenchidas.'; $_['text_your_details'] = 'Seus dados de contato'; $_['text_your_address'] = 'Seu site e endereço'; $_['text_your_affiliate'] = 'Informações'; $_['text_your_password'] = 'Sua senha de acesso'; $_['text_cheque'] = 'Cheque'; $_['text_paypal'] = 'PayPal'; $_['text_bank'] = 'Depósito bancário'; $_['text_agree'] = 'Eu li e concordo com o contrato de <a href="%s" class="agree"><b>%s</b></a>'; // Entry $_['<API key>'] = 'Tipo de cliente'; $_['entry_firstname'] = 'Nome'; $_['entry_lastname'] = 'Sobrenome'; $_['entry_email'] = 'E-mail'; $_['entry_telephone'] = 'Telefone'; $_['entry_company'] = 'Referência'; $_['entry_website'] = 'Site'; $_['entry_tax'] = 'CPF'; $_['entry_payment'] = 'Receber por'; $_['entry_cheque'] = 'Beneficiário'; $_['entry_paypal'] = 'E-mail no PayPal'; $_['entry_bank_name'] = 'Banco'; $_['<API key>'] = 'Agência'; $_['<API key>'] = 'Código do banco'; $_['<API key>'] = 'Titular da conta'; $_['<API key>'] = 'Conta corrente'; $_['entry_password'] = 'Senha'; $_['entry_confirm'] = 'Repetir a senha'; // Error $_['error_exists'] = 'Atenção: Este e-mail já está registrado.'; $_['error_firstname'] = 'O nome deve ter entre 2 e 32 caracteres.'; $_['error_lastname'] = 'O sobrenome deve ter entre 2 e 32 caracteres.'; $_['error_email'] = 'O e-mail não é válido.'; $_['error_telephone'] = 'O telefone deve ter entre 10 e 11 caracteres.'; $_['error_custom_field'] = 'O campo %s é obrigatório.'; $_['error_cheque'] = 'O nome do beneficiário é obrigatório.'; $_['error_paypal'] = 'O e-mail no PayPal não é válido.'; $_['<API key>'] = 'O titular da conta é obrigatório.'; $_['<API key>'] = 'O número da conta corrente é obrigatória.'; $_['error_password'] = 'A senha deve ter entre 4 e 20 caracteres.'; $_['error_confirm'] = 'A senha repetida está errada.'; $_['error_agree'] = 'Atenção: Você precisa aceitar o contrato de %s.';
#ifndef <API key> #define <API key> #include <projectexplorer/kitinformation.h> #include <projectexplorer/kitconfigwidget.h> QT_BEGIN_NAMESPACE class QLabel; class QPushButton; QT_END_NAMESPACE namespace Android { namespace Internal { class <API key> : public ProjectExplorer::KitConfigWidget { Q_OBJECT public: <API key>(ProjectExplorer::Kit *kit, const ProjectExplorer::KitInformation *ki); ~<API key>() override; QString displayName() const override; QString toolTip() const override; void makeReadOnly() override; void refresh() override; bool visibleInKit() override; QWidget *mainWidget() const override; QWidget *buttonWidget() const override; private slots: void autoDetectDebugger(); void showDialog(); private: QLabel *m_label; QPushButton *m_button; }; class <API key> : public ProjectExplorer::KitInformation { Q_OBJECT public: <API key>(); QVariant defaultValue(ProjectExplorer::Kit *) const override; QList<ProjectExplorer::Task> validate(const ProjectExplorer::Kit *) const override; ItemList toUserOutput(const ProjectExplorer::Kit *) const override; ProjectExplorer::KitConfigWidget *createConfigWidget(ProjectExplorer::Kit *) const override; static Core::Id id(); static bool isAndroidKit(const ProjectExplorer::Kit *kit); static Utils::FileName gdbServer(const ProjectExplorer::Kit *kit); static void setGdbSever(ProjectExplorer::Kit *kit, const Utils::FileName &gdbServerCommand); static Utils::FileName autoDetect(ProjectExplorer::Kit *kit); }; } // namespace Internal } // namespace Android #endif // <API key>
package net.sf.jasperreports.engine.fill; import java.awt.font.TextLayout; /** * @author Lucian Chirita (lucianc@users.sourceforge.net) */ public class TextLayoutLine implements TextLine { private final TextLayout textLayout; public TextLayoutLine(TextLayout textLayout) { this.textLayout = textLayout; } @Override public float getAscent() { return textLayout.getAscent(); } @Override public float getDescent() { return textLayout.getDescent(); } @Override public float getLeading() { return textLayout.getLeading(); } @Override public int getCharacterCount() { return textLayout.getCharacterCount(); } @Override public boolean isLeftToRight() { return textLayout.isLeftToRight(); } @Override public float getAdvance() { return textLayout.getAdvance(); } }
package io.github.endreman0.calculator.expression.type; import static io.github.endreman0.calculator.expression.type.MixedNumber.valueOf; import static org.junit.Assert.*; import org.junit.Test; public class MixedNumberTest{ private final MixedNumber instance = valueOf(3, 2, 3), integer = valueOf(5), fraction = valueOf(3, 7), negative = valueOf(-6, 1, 3), fractionNegative = valueOf(-2, 5); private final MixedNumber[] instances = {instance, integer, fraction, negative, fractionNegative}; @Test public void testHashCode(){ for(MixedNumber num : instances) assertEquals(num.numeratorImproper(), num.hashCode()); } @Test public void testValueOf(){ for(MixedNumber num : instances){ assertEquals(num, MixedNumber.valueOf(num.toString())); } } @Test public void testClone(){ for(MixedNumber num : instances) assertEquals(num, num.clone()); } @Test public void testToString(){ assertEquals("3_2/3", instance.toString()); assertEquals("5", integer.toString()); assertEquals("3/7", fraction.toString()); assertEquals("-6_1/3", negative.toString()); assertEquals("-2/5", fractionNegative.toString()); } @Test public void testEquals(){ for(MixedNumber num : instances) assertTrue(num.equals(num)); for(int i=0; i<instances.length; i++){ for(int j=i+1; j<instances.length; j++){ assertFalse(instances[i].equals(instances[j])); assertFalse(instances[j].equals(instances[i])); } } } @Test public void testValue(){ assertEquals(3 + (2D/3), instance.value(), 0); assertEquals(integer.whole(), integer.value(), 0); assertEquals(-(6 + 1D/3), negative.value(), 0); } }
# irs: The Ironic Repositioning System [![made-with-crystal](https: [![License: MIT](https: [![Say Thanks](https: > A music scraper that understands your metadata needs. `irs` is a command-line application that downloads audio and metadata in order to package an mp3 with both. Extensible, the user can download individual songs, entire albums, or playlists from Spotify. <p align="center"> <img src="https://i.imgur.com/7QTM6rD.png" height="400" title="#1F816D" /> </p> <p align="center" [![forthebadge](https: [![forthebadge](https: [![forthebadge](https: </p> ## Table of Contents - [Usage](#usage) - [Demo](#demo) - [Installation](#installation) - [Pre-built](#pre-built) - [From source](#from-source) - [Set up](#setup) - [Config](#config) - [How it works](#how-it-works) - [Contributing](#contributing) ## Usage ~ $ irs -h Usage: irs [--help] [--version] [--install] [-s <song> -a <artist>] [-A <album> -a <artist>] [-p <playlist> -a <username>] Arguments: -h, --help Show this help message and exit -v, --version Show the program version and exit -i, --install Download binaries to config location -c, --config Show config file location -a, --artist <artist> Specify artist name for downloading -s, --song <song> Specify song name to download -A, --album <album> Specify the album name to download -p, --playlist <playlist> Specify the playlist name to download -u, --url <url> Specify the youtube url to download from (for single songs only) -g, --give-url Specify the youtube url sources while downloading (for albums or playlists only only) Examples: $ irs --song "Bohemian Rhapsody" --artist "Queen" # => downloads the song "Bohemian Rhapsody" by "Queen" $ irs --album "Demon Days" --artist "Gorillaz" # => downloads the album "Demon Days" by "Gorillaz" $ irs --playlist "a different drummer" --artist "prakkillian" # => downloads the playlist "a different drummer" by the user prakkillian Demo [![asciicast](https: ## Installation Pre-built Just download the latest release for your platform [here](https://github.com/cooperhammond/irs/releases). Note that the binaries right now have only been tested on WSL. They *should* run on most linux distros, and OS X, but if they don't please make an issue above. From Source If you're one of those cool people who compiles from source 1. Install crystal-lang ([`https: 1. Clone it (`git clone https://github.com/cooperhammond/irs`) 1. CD it (`cd irs`) 1. Build it (`shards build`) Setup 1. Create a `.yaml` config file somewhere on your system (usually `~/.irs/`) 1. Copy the following into it yaml binary_directory: ~/.irs/bin music_directory: ~/Music filename_pattern: "{track_number} - {title}" directory_pattern: "{artist}/{album}" client_key: <API key> client_<API key> <API key>: enabled: true <API key>: true unify_into_album: false 1. Set the environment variable `IRS_CONFIG_LOCATION` pointing to that file 1. Go to [`https: 1. Log in or create an account 1. Click `CREATE A CLIENT ID` 1. Enter all necessary info, true or false, continue 1. Find your client key and client secret 1. Copy each respectively into the X's in your config file 1. Run `irs --install` and answer the prompts! You should be good to go! Run the file from your command line to get more help on usage or keep reading! # Config You may have noticed that there's a config file with more than a few options. Here's what they do: yaml binary_directory: ~/.irs/bin music_directory: ~/Music filename_pattern: "{track_number} - {title}" directory_pattern: "{artist}/{album}" client_key: <API key> client_<API key> <API key>: enabled: true <API key>: true unify_into_album: false - `binary_directory`: a path specifying where the downloaded binaries should be placed - `music_directory`: a path specifying where downloaded mp3s should be placed. - `filename_pattern`: a pattern for the output filename of the mp3 - `directory_pattern`: a pattern for the folder structure your mp3s are saved in - `client_key`: a client key from your spotify API application - `client_secret`: a client secret key from your spotify API application - `<API key>/enabled`: if set to true, all mp3s from a downloaded playlist will be placed in the same folder. - `<API key>/<API key>`: if set to true, the track numbers of the mp3s of the playlist will be overwritten to correspond to their place in the playlist - `<API key>/unify_into_album`: if set to true, will overwrite the album name and album image of the mp3 with the title of your playlist and the image for your playlist respectively In a pattern following keywords will be replaced: | Keyword | Replacement | Example | | : | `{artist}` | Artist Name | Queen | | `{title}` | Track Title | Bohemian Rhapsody | | `{album}` | Album Name | Stone Cold Classics | | `{track_number}` | Track Number | 9 | | `{total_tracks}` | Total Tracks in Album | 14 | | `{disc_number}` | Disc Number | 1 | | `{day}` | Release Day | 01 | | `{month}` | Release Month | 01 | | `{year}` | Release Year | 2006 | | `{id}` | Spotify ID | <API key> | Beware OS-restrictions when naming your mp3s. Pattern Examples: yaml music_directory: ~/Music filename_pattern: "{track_number} - {title}" directory_pattern: "{artist}/{album}" Outputs: `~/Music/Queen/Stone Cold Classics/9 - Bohemian Rhapsody.mp3` <br><br> yaml music_directory: ~/Music filename_pattern: "{artist} - {title}" directory_pattern: "" Outputs: `~/Music/Queen - Bohemian Rhapsody.mp3` <br><br> yaml music_directory: ~/Music filename_pattern: "{track_number} of {total_tracks} - {title}" directory_pattern: "{year}/{artist}/{album}" Outputs: `~/Music/2006/Queen/Stone Cold Classics/9 of 14 - Bohemian Rhapsody.mp3` <br><br> yaml music_directory: ~/Music filename_pattern: "{track_number}. {title}" directory_pattern: "irs/{artist} - {album}" Outputs: `~/Music/irs/Queen - Stone Cold Classics/9. Bohemian Rhapsody.mp3` <br> ## How it works **At it's core** `irs` downloads individual songs. It does this by interfacing with the Spotify API, grabbing metadata, and then searching Youtube for a video containing the song's audio. It will download the video using [`youtube-dl`](https://github.com/ytdl-org/youtube-dl), extract the audio using [`ffmpeg`](https://ffmpeg.org/), and then pack the audio and metadata together into an MP3. From the core, it has been extended to download the index of albums and playlists through the spotify API, and then iteratively use the method above for downloading each song. It used to be in python, but 1. I wasn't a fan of python's limited ability to distribute standalone binaries 1. It was a charlie foxtrot of code that I made when I was little and I wanted to refine it 1. `crystal-lang` made some promises and I was interested in seeing how well it did (verdict: if you're building high-level tools you want to run quickly and distribute, it's perfect) ## Contributing Any and all contributions are welcome. If you think of a cool feature, send a PR or shoot me an [email](mailto:kepoorh@gmail.com). If you think something could be implemented better, _please_ shoot me an email. If you like what I'm doing here, _pretty please_ shoot me an email. 1. Fork it (<https://github.com/your-github-user/irs/fork>) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request
package com.github.bordertech.wcomponents.examples.table; import com.github.bordertech.wcomponents.Request; import com.github.bordertech.wcomponents.<API key>; import com.github.bordertech.wcomponents.WDateField; import com.github.bordertech.wcomponents.WPanel; import com.github.bordertech.wcomponents.WTable; import com.github.bordertech.wcomponents.WTable.SortMode; import com.github.bordertech.wcomponents.WTableColumn; import com.github.bordertech.wcomponents.WText; /** * This example demonstrates a simple {@link WTable} that is bean bound and has sorting defined for each column. * <p> * Uses {@link <API key>} to handle the bean binding. * </p> * * @author Jonathan Austin * @since 1.0.0 */ public class <API key> extends WPanel { /** * The table used in the example. */ private final WTable table = new WTable(); /** * Create example. */ public <API key>() { add(table); // Columns table.addColumn(new WTableColumn("First name", new WText())); table.addColumn(new WTableColumn("Last name", new WText())); table.addColumn(new WTableColumn("DOB", new WDateField())); // Set sort mode table.setSortMode(SortMode.DYNAMIC); // Setup model <API key> model = new <API key>( new String[]{"firstName", "lastName", "dateOfBirth"}); // Set comparators for the columns model.setComparator(0, <API key>.<API key>); model.setComparator(1, <API key>.<API key>); model.setComparator(2, <API key>.<API key>); table.setTableModel(model); } /** * Override <API key> in order to set up the example data the first time that the example is accessed by * each user. * * @param request the request being responded to. */ @Override protected void <API key>(final Request request) { super.<API key>(request); if (!isInitialised()) { // Set the data as the bean on the table table.setBean(ExampleDataUtil.createExampleData()); setInitialised(true); } } }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"> <HTML> <HEAD> <TITLE>IT </TITLE> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=gb_2312-80"> </HEAD> <BODY bgcolor="#FFFFFF"> <p><b>&lt;<a href="SoftEng050.html"></a>&gt;&lt;<a href="SoftEng052.html"></a>&gt;</b></p> <p><img src="SoftEng051.gif" width="959" height="719"> </p> </BODY> </HTML>
package com.github.naoghuman.demo.template.testproject.sample32; import com.github.naoghuman.demo.template.annotation.Project; import com.github.naoghuman.demo.template.annotation.Sample; import com.github.naoghuman.demo.template.annotation.SampleType; /** * * @author Naoghuman */ @Sample( /* cssURL = "[undefined]"; */ description = "TODO", // NOI18N /* javaDocURL = "[undefined]"; */ name = "Sample", // NOI18N /* overviewURL = "[undefined]", */ project = @Project(name = "Demo-Template"), // NOI18N sampleNr = 32, sampleType = SampleType.OVERVIEW, /* sourceCodeURL = "[undefined]", */ visible = true ) public class Sample32 { }
/** * * @file browser.cpp * * @brief Browse all the files in the directory and subdirs, this class needs to be inherited * * @version 1.0 * @date 14.06.2011 20:11:02 * * @author Ben D. (BD), dbapps2@gmail.com * */ #include <browser/browser.h> Browser::Browser(string path) { this->path = path; } Browser::~Browser() {} int Browser::browse() { struct stat file_status; if (stat(this->path.c_str(), &file_status) < 0) { ErrorLogger::log("Could not get stats for path", path); return FAILURE; } /* Check if file or Folder */ if (file_status.st_mode & S_IFDIR) { return sbrowse(this->path); /* it's a folder */ } /* It's a file */ apply(this->path); return SUCCESS; } int Browser::sbrowse(string path) { DIR *dir = opendir(path.c_str()); struct dirent *ent; string *newPath = new string(); string dName; if (dir != NULL) { while ((ent = readdir (dir)) != NULL) { dName = ent->d_name; buildPath(path, dName, newPath); if (!strcmp(ent->d_name, ".") == 0 && !strcmp(ent->d_name, "..") == 0 && (ent->d_name[0] != '.')) { if (ent->d_type == DT_DIR ) { if( sbrowse(*newPath) == FAILURE) { free(dir); free(ent); delete newPath; return FAILURE; } } else { apply(*newPath); } } } } free(dir); delete newPath; return SUCCESS; } void Browser::buildPath(string path, string filename, string* res) { *res = ""; res->append(path); res->append("/"); res->append(filename); }
#ifndef <API key> #define <API key> #include "dllmacro.h" #include <QStyledItemDelegate> #define PADDING 4 class QPainter; class Q_DECL_EXPORT ConfigDelegateBase : public QStyledItemDelegate { Q_OBJECT public: ConfigDelegateBase( QObject* parent = 0 ); virtual QSize sizeHint ( const <API key>& option, const QModelIndex& index ) const; virtual bool editorEvent ( QEvent* event, QAbstractItemModel* model, const <API key>& option, const QModelIndex& index ); // if you want to use a checkbox, you need to have this say where to paint it virtual QRect checkRectForIndex( const <API key>& option, const QModelIndex& idx, int role ) const = 0; // if you want to use a config wrench, you need to have this say where to paint it virtual QRect configRectForIndex( const <API key>& option, const QModelIndex& idx ) const = 0; virtual QList<int> extraCheckRoles() const { return QList<int>(); } signals: void configPressed( const QModelIndex& idx ); protected: private: QModelIndex m_configPressed; }; #endif // <API key>
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.4.2_12) on Fri Jul 24 13:33:31 MDT 2009 --> <TITLE> Uses of Package javax.servlet (Servlet API Documentation) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Uses of Package javax.servlet (Servlet API Documentation)"; } </SCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <A NAME="navbar_top"></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <CENTER> <H2> <B>Uses of Package<br>javax.servlet</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> Packages that use <A HREF="../../javax/servlet/package-summary.html">javax.servlet</A></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#javax.servlet"><B>javax.servlet</B></A></TD> <TD>The javax.servlet package contains a number of classes and interfaces that describe and define the contracts between a servlet class and the runtime environment provided for an instance of such a class by a conforming servlet container.&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#javax.servlet.http"><B>javax.servlet.http</B></A></TD> <TD>The javax.servlet.http package contains a number of classes and interfaces that describe and define the contracts between a servlet class running under the HTTP protocol and the runtime environment provided for an instance of such a class by a conforming servlet container.&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="javax.servlet"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> Classes in <A HREF="../../javax/servlet/package-summary.html">javax.servlet</A> used by <A HREF="../../javax/servlet/package-summary.html">javax.servlet</A></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/FilterChain.html#javax.servlet"><B>FilterChain</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;A FilterChain is an object provided by the servlet container to the developer giving a view into the invocation chain of a filtered request for a resource.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/FilterConfig.html#javax.servlet"><B>FilterConfig</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;A filter configuration object used by a servlet container to pass information to a filter during initialization.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/RequestDispatcher.html#javax.servlet"><B>RequestDispatcher</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/Servlet.html#javax.servlet"><B>Servlet</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Defines methods that all servlets must implement.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/ServletConfig.html#javax.servlet"><B>ServletConfig</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;A servlet configuration object used by a servlet container to pass information to a servlet during initialization.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/ServletContext.html#javax.servlet"><B>ServletContext</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/<API key>.html#javax.servlet"><B><API key></B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This is the event class for notifications about changes to the attributes of the servlet context of a web application.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/ServletContextEvent.html#javax.servlet"><B>ServletContextEvent</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This is the event class for notifications about changes to the servlet context of a web application.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/ServletException.html#javax.servlet"><B>ServletException</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Defines a general exception a servlet can throw when it encounters difficulty.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/ServletInputStream.html#javax.servlet"><B>ServletInputStream</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Provides an input stream for reading binary data from a client request, including an efficient <code>readLine</code> method for reading data one line at a time.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/ServletOutputStream.html#javax.servlet"><B>ServletOutputStream</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Provides an output stream for sending binary data to the client.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/ServletRequest.html#javax.servlet"><B>ServletRequest</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Defines an object to provide client request information to a servlet.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/<API key>.html#javax.servlet"><B><API key></B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This is the event class for notifications of changes to the attributes of the servlet request in an application.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/ServletRequestEvent.html#javax.servlet"><B>ServletRequestEvent</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Events of this kind indicate lifecycle events for a ServletRequest.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/ServletResponse.html#javax.servlet"><B>ServletResponse</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Defines an object to assist a servlet in sending a response to the client.</TD> </TR> </TABLE> &nbsp; <P> <A NAME="javax.servlet.http"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> Classes in <A HREF="../../javax/servlet/package-summary.html">javax.servlet</A> used by <A HREF="../../javax/servlet/http/package-summary.html">javax.servlet.http</A></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/GenericServlet.html#javax.servlet.http"><B>GenericServlet</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Defines a generic, <API key> servlet.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/Servlet.html#javax.servlet.http"><B>Servlet</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Defines methods that all servlets must implement.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/ServletConfig.html#javax.servlet.http"><B>ServletConfig</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;A servlet configuration object used by a servlet container to pass information to a servlet during initialization.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/ServletContext.html#javax.servlet.http"><B>ServletContext</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/ServletException.html#javax.servlet.http"><B>ServletException</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Defines a general exception a servlet can throw when it encounters difficulty.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/ServletInputStream.html#javax.servlet.http"><B>ServletInputStream</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Provides an input stream for reading binary data from a client request, including an efficient <code>readLine</code> method for reading data one line at a time.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/ServletRequest.html#javax.servlet.http"><B>ServletRequest</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Defines an object to provide client request information to a servlet.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/<API key>.html#javax.servlet.http"><B><API key></B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Provides a convenient implementation of the ServletRequest interface that can be subclassed by developers wishing to adapt the request to a Servlet.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/ServletResponse.html#javax.servlet.http"><B>ServletResponse</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Defines an object to assist a servlet in sending a response to the client.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../javax/servlet/class-use/<API key>.html#javax.servlet.http"><B><API key></B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Provides a convenient implementation of the ServletResponse interface that can be subclassed by developers wishing to adapt the response from a Servlet.</TD> </TR> </TABLE> &nbsp; <P> <HR> <A NAME="navbar_bottom"></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> Copyright &copy; 1999-2002 The Apache Software Foundation. All Rights Reserved. </BODY> </HTML>
#!/usr/bin/env python #coding:utf-8 # @file argv-test.py # @brief # @author unlessbamboo # @version 1.0 # @date 2016-03-03 import sys def testSys(): """testSys""" for arg in sys.argv[1:]: print (arg) if __name__ == '__main__': testSys()
package com.berka.multiplanner.Models.Trips; import org.json.JSONException; import org.json.JSONObject; import com.berka.multiplanner.Models.Abstraction.AbstractStop; public class Location extends AbstractStop{ public JSONObject getTheJSONBluePrint() { return theAllmightyJSON; } public Location() { displayname = "Loading..."; locationid=-1; } public Location(JSONObject object) throws JSONException { setX(object.getString("@x")); setY(object.getString("@y")); //setBestmatch(object.getString("bestmatch")); //setType(object.getString("type")); setDisplayname(object); setLocationid(object); setTheAllmightyJSON(object); } protected void setDisplayname(JSONObject object) throws JSONException { try{ setDisplayname(object.getString("displayname")); }catch(JSONException e) { setDisplayname(object.getString("name")); } } protected void setLocationid(JSONObject object) throws JSONException { try{ setLocationid(object.getDouble("locationid")); }catch(JSONException e) { setLocationid(object.getDouble("@id")); } } }
/* * struct omap_hsmmc_dev_attr.flags possibilities * * <API key>: Some HSMMC controller instances can * operate with either 1.8Vdc or 3.0Vdc card voltages; this flag * should be set if this is the case. See for example Section 22.5.3 * "MMC/SD/SDIO1 Bus Voltage Selection" of the OMAP34xx Multimedia * Device Silicon Revision 3.1.x Revision ZR (July 2011) (SWPU223R). * * <API key>: Multiple-block read transfers * don't work correctly on some MMC controller instances on some * OMAP3 SoCs; this flag should be set if this is the case. See * for example Advisory 2.1.1.128 "MMC: Multiple Block Read * Operation Issue" in _OMAP3530/3525/3515/3503 Silicon Errata_ * Revision F (October 2010) (SPRZ278F). */ #define <API key> BIT(0) #define <API key> BIT(1) #define <API key> BIT(2) struct omap_hsmmc_dev_attr { u8 flags; }; struct mmc_card; struct <API key> { /* back-link to device */ struct device *dev; /* set if your board has components or wiring that limits the * maximum frequency on the MMC bus */ unsigned int max_freq; /* Integrating attributes from the omap_hwmod layer */ u8 controller_flags; /* Register offset deviation */ u16 reg_offset; /* * 4/8 wires and any additional host capabilities * need to OR'd all capabilities (ref. linux/mmc/host.h) */ u32 caps; /* Used for the MMC driver on 2430 and later */ u32 pm_caps; /* PM capabilities of the mmc */ /* use the internal clock */ unsigned internal_clock: 1; /* nonremovable e.g. eMMC */ unsigned nonremovable: 1; /* eMMC does not handle power off when not in sleep state */ unsigned <API key>: 1; /* we can put the features above into this variable */ #define HSMMC_HAS_PBIAS (1 << 0) #define <API key> (1 << 1) #define <API key> (1 << 2) unsigned features; int gpio_cd; /* gpio (card detect) */ int gpio_cod; /* gpio (cover detect) */ int gpio_wp; /* gpio (write protect) */ int (*set_power)(struct device *dev, int power_on, int vdd); void (*remux)(struct device *dev, int power_on); /* Call back before enabling / disabling regulators */ void (*before_set_reg)(struct device *dev, int power_on, int vdd); /* Call back after enabling / disabling regulators */ void (*after_set_reg)(struct device *dev, int power_on, int vdd); /* if we have special card, init it using this callback */ void (*init_card)(struct mmc_card *card); const char *name; u32 ocr_mask; };
import React from 'react'; import { Switch } from 'react-router-dom'; import { Route } from '../../../components/Route/index'; import <API key> from './people'; import <API key> from './profile'; const <API key> = () => ( <Switch> <Route path="/dashboard/people" exact component={<API key>} /> <Route path="/dashboard/people/:userId/:name?" exact component={<API key>} /> </Switch> ); export default <API key>;
#include <<API key>.h> #include <array_variable.h> #include <expression.h> #include <sstream> #include "assert.h" #include "execution_context.h" #include <<API key>.h> #include <constant_expression.h> #include <array_type.h> #include <record_type.h> ArrayVariable::ArrayVariable(const_shared_ptr<Variable> base_variable, const_shared_ptr<Expression> expression) : Variable(base_variable->GetName(), base_variable->GetLocation()), m_base_variable( base_variable), m_expression(expression) { } TypedResult<TypeSpecifier> ArrayVariable::GetTypeSpecifier( const shared_ptr<ExecutionContext> context, AliasResolution resolution) const { auto <API key> = m_base_variable->GetTypeSpecifier( context); auto errors = <API key>.GetErrors(); if (ErrorList::IsTerminator(errors)) { auto base_type_as_array = <API key><const ArrayTypeSpecifier>( <API key>.GetData()); if (base_type_as_array) { auto base_evaluation = m_base_variable->Evaluate(context); if (ErrorList::IsTerminator(base_evaluation->GetErrors())) { auto array = base_evaluation->GetData<Array>(); if (array) { return array-><API key>(); } else { assert(false); } } } } return TypedResult<TypeSpecifier>(nullptr, errors); } const_shared_ptr<string> ArrayVariable::ToString( const shared_ptr<ExecutionContext> context) const { ostringstream buffer; buffer << *m_base_variable->ToString(context); buffer << "["; const_shared_ptr<Result> evaluation = m_expression->Evaluate(context, context); auto errors = evaluation->GetErrors(); if (ErrorList::IsTerminator(errors)) { buffer << *(evaluation->GetData<int>()); } else { buffer << "EVALUATION ERROR"; } buffer << "]"; return make_shared<string>(buffer.str()); } ArrayVariable::~ArrayVariable() { } const_shared_ptr<ArrayVariable::ValidationResult> ArrayVariable::ValidateOperation( const shared_ptr<ExecutionContext> context) const { int array_index = -1; yy::location index_location = GetDefaultLocation(); plain_shared_ptr<Array> array; auto base_evaluation = m_base_variable->Evaluate(context); ErrorListRef errors = base_evaluation->GetErrors(); if (ErrorList::IsTerminator(errors)) { auto <API key> = m_base_variable->GetTypeSpecifier( context); errors = <API key>.GetErrors(); if (ErrorList::IsTerminator(errors)) { auto base_type_specifier = <API key>.GetData(); auto base_type_result = base_type_specifier->GetType( context->GetTypeTable()); errors = base_type_result->GetErrors(); if (ErrorList::IsTerminator(errors)) { auto base_type = base_type_result->GetData<TypeDefinition>(); auto base_type_as_array = <API key><const ArrayType>( base_type); if (base_type_as_array) { array = base_evaluation->GetData<Array>(); auto <API key> = m_expression->GetTypeSpecifier(context); errors = <API key>.GetErrors(); if (ErrorList::IsTerminator(errors)) { auto <API key> = <API key>.GetData(); auto index_analysis = <API key>->AnalyzeAssignmentTo( <API key>::GetInt(), context->GetTypeTable()); auto expression_location = m_expression->GetLocation(); if (index_analysis == EQUIVALENT || index_analysis == UNAMBIGUOUS) { const_shared_ptr<Result> <API key> = m_expression->Evaluate(context, context); errors = <API key>->GetErrors(); if (ErrorList::IsTerminator(errors)) { const int i = *(<API key>->GetData< int>()); if (i >= 0) { array_index = i; index_location = expression_location; } else { errors = ErrorList::From( make_shared<Error>( Error::SEMANTIC, Error::<API key>, expression_location.begin, *(m_base_variable->ToString( context)), *AsString(i)), errors); } } } else { ostringstream buffer; buffer << "A " << <API key>->ToString() << " expression"; errors = ErrorList::From( make_shared<Error>(Error::SEMANTIC, Error::<API key>, expression_location.begin, *(m_base_variable->ToString( context)), buffer.str()), errors); } } } else { errors = ErrorList::From( make_shared<Error>(Error::SEMANTIC, Error::<API key>, GetLocation().begin, *(m_base_variable->ToString(context))), errors); } } } } return make_shared<ArrayVariable::ValidationResult>(array, array_index, index_location, errors); } const_shared_ptr<Result> ArrayVariable::Evaluate( const shared_ptr<ExecutionContext> context) const { ErrorListRef errors(ErrorList::GetTerminator()); const_shared_ptr<ValidationResult> validation_result = ValidateOperation( context); plain_shared_ptr<void> result_value; errors = validation_result->GetErrors(); if (ErrorList::IsTerminator(errors)) { auto array = validation_result->GetArray(); const int index = validation_result->GetIndex(); const int size = array->GetSize(); if (index < size && index >= 0) { auto type_table = context->GetTypeTable(); const_shared_ptr<TypeSpecifier> <API key> = array-><API key>(); if (<API key>->AnalyzeAssignmentTo( <API key>::GetBoolean(), context->GetTypeTable()) == EQUIVALENT) { result_value = array->GetValue<bool>(index, *type_table); } else if (<API key>->AnalyzeAssignmentTo( <API key>::GetInt(), context->GetTypeTable()) == EQUIVALENT) { result_value = array->GetValue<int>(index, *type_table); } else if (<API key>->AnalyzeAssignmentTo( <API key>::GetDouble(), context->GetTypeTable()) == EQUIVALENT) { result_value = array->GetValue<double>(index, *type_table); } else if (<API key>->AnalyzeAssignmentTo( <API key>::GetString(), context->GetTypeTable()) == EQUIVALENT) { result_value = array->GetValue<string>(index, *type_table); } else { auto element_type_result = <API key>->GetType( context->GetTypeTable(), RESOLVE); errors = element_type_result->GetErrors(); if (ErrorList::IsTerminator(errors)) { auto element_type = element_type_result->GetData< TypeDefinition>(); auto as_array = std::<API key><const ArrayType>( element_type); if (as_array) { //TODO assert(false); } auto as_record = std::<API key><const RecordType>( element_type); if (as_record) { result_value = array->GetValue<Record>(index, *type_table); } else { //we should never get here assert(false); } } } } else { const yy::location index_location = validation_result->GetIndexLocation(); ostringstream buffer; buffer << index; errors = ErrorList::From( make_shared<Error>(Error::SEMANTIC, Error::<API key>, index_location.begin, *(m_base_variable->ToString(context)), buffer.str()), errors); } } const_shared_ptr<Result> result = make_shared<Result>(result_value, errors); return result; } const ErrorListRef ArrayVariable::AssignValue( const shared_ptr<ExecutionContext> context, const shared_ptr<ExecutionContext> closure, const_shared_ptr<Expression> expression, const AssignmentType op) const { ErrorListRef errors(ErrorList::GetTerminator()); auto variable_name = GetName(); const_shared_ptr<ValidationResult> validation_result = ValidateOperation( context); errors = validation_result->GetErrors(); if (ErrorList::IsTerminator(errors)) { auto array = validation_result->GetArray(); const int index = validation_result->GetIndex(); if (index >= 0) { const_shared_ptr<TypeSpecifier> <API key> = array-><API key>(); const_shared_ptr<<API key>> <API key> = std::<API key><const <API key>>( <API key>); auto type_table = context->GetTypeTable(); if (<API key>) { const BasicType element_type = <API key>->GetBasicType(); switch (element_type) { case BOOLEAN: { const_shared_ptr<bool> value = array->GetValue<bool>(index, *type_table); const_shared_ptr<Result> result = AssignmentStatement::do_op(variable_name, element_type, GetLocation().begin, *value, expression, op, context); errors = result->GetErrors(); if (ErrorList::IsTerminator(errors)) { errors = SetSymbolCore(context, result->GetData<bool>()); break; } break; } case INT: { const_shared_ptr<int> value = array->GetValue<int>(index, *type_table); const_shared_ptr<Result> result = AssignmentStatement::do_op(variable_name, element_type, GetLocation().begin, *value, expression, op, context); errors = result->GetErrors(); if (ErrorList::IsTerminator(errors)) { errors = SetSymbolCore(context, result->GetData<int>()); break; } break; } case DOUBLE: { const_shared_ptr<double> value = array->GetValue<double>( index, *type_table); const_shared_ptr<Result> result = AssignmentStatement::do_op(variable_name, element_type, GetLocation().begin, *value, expression, op, context); errors = result->GetErrors(); if (ErrorList::IsTerminator(errors)) { errors = SetSymbolCore(context, result->GetData<double>()); } break; } case STRING: { const_shared_ptr<string> value = array->GetValue<string>( index, *type_table); const_shared_ptr<Result> result = AssignmentStatement::do_op(variable_name, element_type, GetLocation().begin, value, expression, op, context); errors = result->GetErrors(); if (ErrorList::IsTerminator(errors)) { errors = SetSymbolCore(context, result->GetData<string>()); } break; } default: assert(false); } } else { if (op == AssignmentType::ASSIGN) { const_shared_ptr<Result> result = expression->Evaluate( context, context); errors = result->GetErrors(); if (ErrorList::IsTerminator(errors)) { auto element_type_result = <API key>->GetType( context->GetTypeTable(), RESOLVE); errors = element_type_result->GetErrors(); if (ErrorList::IsTerminator(errors)) { auto element_type = element_type_result->GetData< TypeDefinition>(); auto element_as_array = std::<API key>< const ArrayType>(element_type); if (element_as_array) { errors = SetSymbolCore(context, result->GetData<Array>()); } auto element_as_record = std::<API key>< const RecordType>(element_type); if (element_as_record) { errors = SetSymbolCore(context, result->GetData<Record>()); } } } } else { shared_ptr<const TypeSpecifier> <API key> = <API key>::GetNone(); auto <API key> = expression->GetTypeSpecifier(context); auto <API key> = <API key>.GetErrors(); if (ErrorList::IsTerminator( <API key>)) { <API key> = <API key>.GetData(); } errors = errors->From( make_shared<Error>(Error::SEMANTIC, Error::<API key>, GetLocation().begin, <API key>->ToString(), <API key>->ToString()), errors); } } } else { errors = ErrorList::From( make_shared<Error>(Error::SEMANTIC, Error::<API key>, GetLocation().begin, *(m_base_variable->ToString(context)), *AsString(index)), errors); } } return errors; } const ErrorListRef ArrayVariable::SetSymbol( const shared_ptr<ExecutionContext> context, const_shared_ptr<bool> value) const { return SetSymbolCore(context, static_pointer_cast<const void>(value)); } const ErrorListRef ArrayVariable::SetSymbol( const shared_ptr<ExecutionContext> context, const_shared_ptr<int> value) const { return SetSymbolCore(context, static_pointer_cast<const void>(value)); } const ErrorListRef ArrayVariable::SetSymbol( const shared_ptr<ExecutionContext> context, const_shared_ptr<double> value) const { return SetSymbolCore(context, static_pointer_cast<const void>(value)); } const ErrorListRef ArrayVariable::SetSymbol( const shared_ptr<ExecutionContext> context, const_shared_ptr<string> value) const { return SetSymbolCore(context, static_pointer_cast<const void>(value)); } const ErrorListRef ArrayVariable::SetSymbol( const shared_ptr<ExecutionContext> context, const_shared_ptr<Array> value) const { return SetSymbolCore(context, static_pointer_cast<const void>(value)); } const ErrorListRef ArrayVariable::SetSymbol( const shared_ptr<ExecutionContext> context, const_shared_ptr<<API key>> type, const_shared_ptr<Record> value) const { return SetSymbolCore(context, static_pointer_cast<const void>(value)); } const_shared_ptr<TypeSpecifier> ArrayVariable::GetElementType( const shared_ptr<ExecutionContext> context) const { //TODO: return Result<TypeSpecifier> auto <API key> = m_base_variable->GetTypeSpecifier( context); auto errors = <API key>.GetErrors(); if (ErrorList::IsTerminator(errors)) { auto base_type_specifier = <API key>.GetData(); auto base_type_result = base_type_specifier->GetType( context->GetTypeTable()); auto errors = base_type_result->GetErrors(); if (ErrorList::IsTerminator(errors)) { auto base_type = base_type_result->GetData<TypeDefinition>(); auto base_type_as_array = <API key><const ArrayType>( base_type); if (base_type_as_array) { return base_type_as_array-><API key>(); } } } return <API key>::GetNone(); } const ErrorListRef ArrayVariable::SetSymbolCore( const shared_ptr<ExecutionContext> context, const_shared_ptr<void> value) const { ErrorListRef errors(ErrorList::GetTerminator()); const_shared_ptr<ValidationResult> validation_result = ValidateOperation( context); errors = validation_result->GetErrors(); if (ErrorList::IsTerminator(errors)) { auto array = validation_result->GetArray(); const int index = validation_result->GetIndex(); auto type_table = context->GetTypeTable(); const_shared_ptr<TypeSpecifier> <API key> = array-><API key>(); shared_ptr<const Array> new_array = nullptr; if (<API key>->AnalyzeAssignmentTo( <API key>::GetBoolean(), context->GetTypeTable())) { new_array = array->WithValue<bool>(index, static_pointer_cast<const bool>(value), *type_table); } else if (<API key>->AnalyzeAssignmentTo( <API key>::GetInt(), context->GetTypeTable())) { new_array = array->WithValue<int>(index, static_pointer_cast<const int>(value), *type_table); } else if (<API key>->AnalyzeAssignmentTo( <API key>::GetDouble(), context->GetTypeTable())) { new_array = array->WithValue<double>(index, static_pointer_cast<const double>(value), *type_table); } else if (<API key>->AnalyzeAssignmentTo( <API key>::GetString(), context->GetTypeTable())) { new_array = array->WithValue<string>(index, static_pointer_cast<const string>(value), *type_table); } else { auto element_type_result = <API key>->GetType( context->GetTypeTable(), RESOLVE); errors = element_type_result->GetErrors(); if (ErrorList::IsTerminator(errors)) { auto element_type = element_type_result->GetData<TypeDefinition>(); auto as_array = std::<API key><const ArrayType>( element_type); if (as_array) { new_array = array->WithValue<Array>(index, static_pointer_cast<const Array>(value), *type_table); } auto as_record = std::<API key><const RecordType>( element_type); if (as_record) { new_array = array->WithValue<Record>(index, static_pointer_cast<const Record>(value), *type_table); } } } //wrap result in constant expression and assign it to the base variable auto as_const_expression = make_shared<ConstantExpression>( m_expression->GetLocation(), new_array); errors = m_base_variable->AssignValue(context, context, as_const_expression, AssignmentType::ASSIGN); } return errors; } const ErrorListRef ArrayVariable::Validate( const shared_ptr<ExecutionContext> context) const { auto base_evaluation = m_base_variable->Validate(context); ErrorListRef errors = base_evaluation; if (ErrorList::IsTerminator(errors)) { auto <API key> = m_expression->GetTypeSpecifier( context); errors = <API key>.GetErrors(); if (ErrorList::IsTerminator(errors)) { auto <API key> = <API key>.GetData(); auto index_analysis = <API key>->AnalyzeAssignmentTo( <API key>::GetInt(), context->GetTypeTable()); if (index_analysis == EQUIVALENT || index_analysis == UNAMBIGUOUS) { auto <API key> = m_base_variable->GetTypeSpecifier(context); errors = <API key>.GetErrors(); if (ErrorList::IsTerminator(errors)) { auto base_type_specifier = <API key>.GetData(); auto base_type_result = base_type_specifier->GetType( context->GetTypeTable()); errors = base_type_result->GetErrors(); if (ErrorList::IsTerminator(errors)) { auto base_type = base_type_result->GetData< TypeDefinition>(); auto base_type_as_array = <API key>< const ArrayType>(base_type); if (!base_type_as_array) { errors = ErrorList::From( make_shared<Error>(Error::SEMANTIC, Error::<API key>, m_expression->GetLocation().begin, *(m_base_variable->ToString( context))), errors); } } } } else { ostringstream buffer; buffer << "A " << <API key>->ToString() << " expression"; errors = ErrorList::From( make_shared<Error>(Error::SEMANTIC, Error::<API key>, m_expression->GetLocation().begin, *(m_base_variable->ToString(context)), buffer.str()), errors); } } } return errors; }
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http: <head> <title>gwn.blocks.utilblocks.schedulers</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="gwn-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" >GNUWiNnetwork</th> </tr></table></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> <a href="gwn-module.html">Package&nbsp;gwn</a> :: <a href="gwn.blocks-module.html">Package&nbsp;blocks</a> :: <a href="gwn.blocks.utilblocks-module.html">Package&nbsp;utilblocks</a> :: Package&nbsp;schedulers </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="gwn.blocks.utilblocks.schedulers-module.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <h1 class="epydoc">Package schedulers</h1><p class="nomargin-top"><span class="codelink"><a href="gwn.blocks.utilblocks.schedulers-pysrc.html">source&nbsp;code</a></span></p> <p>A library for schedulers.</p> <a name="section-Variables"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Variables</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Variables" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="__package__"></a><span class="summary-name">__package__</span> = <code title="None">None</code><br /> hash(x) </td> </tr> </table> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="gwn-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" >GNUWiNnetwork</th> </tr></table></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Thu Nov 6 10:42:20 2014 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <! // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); </script> </body> </html>
#include <iostream> #include <algorithm> struct Leftist { Leftist *left, *right; // dis is the distance to the right-bottom side of the tree int dis, value, size; Leftist(int val = 0) { left = NULL, right = NULL; dis = 0, value = val, size = 1; } ~Leftist() { delete left; delete right; } }; Leftist* merge(Leftist *x, Leftist *y) { // if x or y is NULL, return the other tree to be the answer if (x == NULL) return y; if (y == NULL) return x; if (y->value < x->value) { // Use > here if you want a max priority queue std::swap(x, y); } // We take x as new root, so add the size of y to x x->size += y->size; // merge the origin right sub-tree of x with y to construct the new right sub-tree of x x->right = merge(x->right, y); if (x->left == NULL && x->right != NULL) { // if x->left is NULL pointer, swap the sub-trees to make it leftist std::swap(x->left, x->right); } else if(x->right != NULL && x->left->dis < x->right->dis) { // if the distance of left sub-tree is smaller, swap the sub-trees to make it leftist std::swap(x->left, x->right); } // calculate the new distance if (x->right == NULL) { x->dis = 0; } else { x->dis = x->right->dis + 1; } return x; } Leftist* delete_root(Leftist *T) { //deleting root equals to make a new tree containing only left sub-tree and right sub-tree Leftist *my_left = T->left; Leftist *my_right = T->right; T->left = T->right = NULL; delete T; return merge(my_left, my_right); } int main() { Leftist *my_tree = new Leftist(10); // create a tree with root = 10 // adding a node to a tree is the same as creating a new tree and merge them together my_tree = merge(my_tree, new Leftist(100)); // push 100 my_tree = merge(my_tree, new Leftist(10000)); // push 10000 my_tree = merge(my_tree, new Leftist(1)); // push 1 my_tree = merge(my_tree, new Leftist(1266)); // push 1266 while (my_tree != NULL) { std::cout << my_tree->value << std::endl; my_tree = delete_root(my_tree); } /* the output should be * 1 * 10 * 100 * 1266 * 10000 */ return 0; }
#include "<API key>/counterexamples/Counterexample.h" namespace storm { namespace counterexamples { std::ostream& operator<<(std::ostream& out, Counterexample const& counterexample) { counterexample.writeToStream(out); return out; } } // namespace counterexamples } // namespace storm
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>SUMO - Simulation of Urban MObility: <API key>.cpp Source File</title> <link href="../../tabs.css" rel="stylesheet" type="text/css"/> <link href="../../doxygen.css" rel="stylesheet" type="text/css"/> </head> <body> <!-- Generated by Doxygen 1.6.3 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="../../main.html"><span>Main&nbsp;Page</span></a></li> <li><a href="../../pages.html"><span>Related&nbsp;Pages</span></a></li> <li><a href="../../modules.html"><span>Modules</span></a></li> <li><a href="../../annotated.html"><span>Data&nbsp;Structures</span></a></li> <li class="current"><a href="../../files.html"><span>Files</span></a></li> <li><a href="../../dirs.html"><span>Directories</span></a></li> </ul> </div> <div class="tabs"> <ul> <li><a href="../../files.html"><span>File&nbsp;List</span></a></li> <li><a href="../../globals.html"><span>Globals</span></a></li> </ul> </div> <div class="navpath"><a class="el" href="../../<API key>.html">home</a>&nbsp;&raquo;&nbsp;<a class="el" href="../../<API key>.html">boni</a>&nbsp;&raquo;&nbsp;<a class="el" href="../../<API key>.html">Desktop</a>&nbsp;&raquo;&nbsp;<a class="el" href="../../<API key>.html">DanielTouched</a>&nbsp;&raquo;&nbsp;<a class="el" href="../../<API key>.html">sumo-0.14.0</a>&nbsp;&raquo;&nbsp;<a class="el" href="../../<API key>.html">src</a>&nbsp;&raquo;&nbsp;<a class="el" href="../../<API key>.html">netimport</a>&nbsp;&raquo;&nbsp;<a class="el" href="../../<API key>.html">vissim</a>&nbsp;&raquo;&nbsp;<a class="el" href="../../<API key>.html">tempstructs</a> </div> </div> <div class="contents"> <h1><API key>.cpp</h1><a href="../../d5/dda/<API key>.html">Go to the documentation of this file.</a><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="comment"></span> <a name="l00009"></a>00009 <span class="comment"> <a name="l00010"></a>00010 <span class="comment"></span> <a name="l00011"></a>00011 <span class="comment"> <a name="l00012"></a>00012 <span class="comment"> <a name="l00013"></a>00013 <span class="comment"></span> <a name="l00014"></a>00014 <span class="comment">//</span> <a name="l00015"></a>00015 <span class="comment">// This file is part of SUMO.</span> <a name="l00016"></a>00016 <span class="comment">// SUMO is free software: you can redistribute it and/or modify</span> <a name="l00017"></a>00017 <span class="comment"> <a name="l00018"></a>00018 <span class="comment"> <a name="l00019"></a>00019 <span class="comment">// (at your option) any later version.</span> <a name="l00020"></a>00020 <span class="comment">//</span> <a name="l00021"></a>00021 <span class="comment"></span> <a name="l00022"></a>00022 <a name="l00023"></a>00023 <a name="l00024"></a>00024 <span class="comment"> <a name="l00025"></a>00025 <span class="comment">// included modules</span> <a name="l00026"></a>00026 <span class="comment"> <a name="l00027"></a>00027 <span class="preprocessor">#ifdef _MSC_VER</span> <a name="l00028"></a>00028 <span class="preprocessor"></span><span class="preprocessor">#include &lt;<a class="code" href="../../d3/d99/windows__config_8h.html">windows_config.h</a>&gt;</span> <a name="l00029"></a>00029 <span class="preprocessor">#else</span> <a name="l00030"></a>00030 <span class="preprocessor"></span><span class="preprocessor">#include &lt;<a class="code" href="../../db/d16/config_8h.html">config.h</a>&gt;</span> <a name="l00031"></a>00031 <span class="preprocessor">#endif</span> <a name="l00032"></a>00032 <span class="preprocessor"></span> <a name="l00033"></a>00033 <span class="preprocessor">#include &lt;map&gt;</span> <a name="l00034"></a>00034 <span class="preprocessor">#include &lt;string&gt;</span> <a name="l00035"></a>00035 <span class="preprocessor">#include &lt;algorithm&gt;</span> <a name="l00036"></a>00036 <span class="preprocessor">#include &lt;cassert&gt;</span> <a name="l00037"></a>00037 <span class="preprocessor">#include &lt;<a class="code" href="../../d0/d40/_vector_helper_8h.html">utils/common/VectorHelper.h</a>&gt;</span> <a name="l00038"></a>00038 <span class="preprocessor">#include &lt;<a class="code" href="../../d8/d08/_to_string_8h.html">utils/common/ToString.h</a>&gt;</span> <a name="l00039"></a>00039 <span class="preprocessor">#include &lt;<a class="code" href="../../d4/d51/_position_8h.html">utils/geom/Position.h</a>&gt;</span> <a name="l00040"></a>00040 <span class="preprocessor">#include &lt;<a class="code" href="../../d5/df0/_geom_helper_8h.html">utils/geom/GeomHelper.h</a>&gt;</span> <a name="l00041"></a>00041 <span class="preprocessor">#include &lt;<a class="code" href="../../d3/d43/_position_vector_8h.html">utils/geom/PositionVector.h</a>&gt;</span> <a name="l00042"></a>00042 <span class="preprocessor">#include &lt;<a class="code" href="../../d3/d5c/_options_cont_8h.html">utils/options/OptionsCont.h</a>&gt;</span> <a name="l00043"></a>00043 <span class="preprocessor">#include &quot;<a class="code" href="../../d9/d28/<API key>.html"><API key>.h</a>&quot;</span> <a name="l00044"></a>00044 <span class="preprocessor">#include &quot;<a class="code" href="../../d5/dad/_n_i_vissim_edge_8h.html">NIVissimEdge.h</a>&quot;</span> <a name="l00045"></a>00045 <span class="preprocessor">#include &lt;<a class="code" href="../../d8/d0b/_n_b_edge_8h.html">netbuild/NBEdge.h</a>&gt;</span> <a name="l00046"></a>00046 <span class="preprocessor">#include &lt;<a class="code" href="../../d7/db4/_n_b_edge_cont_8h.html">netbuild/NBEdgeCont.h</a>&gt;</span> <a name="l00047"></a>00047 <span class="preprocessor">#include &lt;<a class="code" href="../../d4/da0/_n_b_node_8h.html">netbuild/NBNode.h</a>&gt;</span> <a name="l00048"></a>00048 <span class="preprocessor">#include &lt;<a class="code" href="../../da/d09/_n_b_node_cont_8h.html">netbuild/NBNodeCont.h</a>&gt;</span> <a name="l00049"></a>00049 <span class="preprocessor">#include &lt;<a class="code" href="../../df/d03/_n_b_district_8h.html">netbuild/NBDistrict.h</a>&gt;</span> <a name="l00050"></a>00050 <span class="preprocessor">#include &lt;<a class="code" href="../../d0/d43/<API key>.html">netbuild/NBDistrictCont.h</a>&gt;</span> <a name="l00051"></a>00051 <span class="preprocessor">#include &quot;<a class="code" href="../../d0/dbb/<API key>.html"><API key>.h</a>&quot;</span> <a name="l00052"></a>00052 <span class="preprocessor">#include &lt;<a class="code" href="../../d2/d7a/_distribution_8h.html">utils/distribution/Distribution.h</a>&gt;</span> <a name="l00053"></a>00053 <span class="preprocessor">#include &lt;<a class="code" href="../../dd/d87/<API key>.html">netbuild/NBDistribution.h</a>&gt;</span> <a name="l00054"></a>00054 <span class="preprocessor">#include &lt;<a class="code" href="../../d4/df7/_msg_handler_8h.html">utils/common/MsgHandler.h</a>&gt;</span> <a name="l00055"></a>00055 <a name="l00056"></a>00056 <span class="preprocessor">#ifdef CHECK_MEMORY_LEAKS</span> <a name="l00057"></a>00057 <span class="preprocessor"></span><span class="preprocessor">#include &lt;<a class="code" href="../../d7/d8d/debug__new_8h.html">foreign/nvwa/debug_new.h</a>&gt;</span> <a name="l00058"></a>00058 <span class="preprocessor">#endif // CHECK_MEMORY_LEAKS</span> <a name="l00059"></a>00059 <span class="preprocessor"></span> <a name="l00060"></a>00060 <a name="l00061"></a>00061 <span class="comment"> <a name="l00062"></a>00062 <span class="comment">// static member definitions</span> <a name="l00063"></a>00063 <span class="comment"> <a name="l00064"></a>00064 <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Definition of a dictionary of district connections."><API key>::DictType</a> <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="District connection dictionary."><API key>::myDict</a>; <a name="l00065"></a>00065 std::map&lt;int, IntVector&gt; <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Map from ditricts to connections."><API key>::<API key></a>; <a name="l00066"></a>00066 <a name="l00067"></a>00067 <a name="l00068"></a>00068 <span class="comment"> <a name="l00069"></a>00069 <span class="comment">// method definitions</span> <a name="l00070"></a>00070 <span class="comment"> <a name="l00071"></a><a class="code" href="../../d9/d07/<API key>.html#<API key>">00071</a> <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Contructor."><API key>::<API key></a>(<span class="keywordtype">int</span> <span class="keywordtype">id</span>, <a name="l00072"></a>00072 <span class="keyword">const</span> std::string&amp; name, <a name="l00073"></a>00073 <span class="keyword">const</span> <a class="code" href="../../d0/d40/_vector_helper_8h.html#<API key>" title="Definition of a vector of unsigned ints.">IntVector</a>&amp; districts, <span class="keyword">const</span> <a class="code" href="../../d0/d40/_vector_helper_8h.html#<API key>">DoubleVector</a>&amp; percentages, <a name="l00074"></a>00074 <span class="keywordtype">int</span> edgeid, <a class="code" href="../../db/d16/config_8h.html#<API key>">SUMOReal</a> position, <a name="l00075"></a>00075 <span class="keyword">const</span> std::vector&lt;std::pair&lt;int, int&gt; &gt; &amp;assignedVehicles) <a name="l00076"></a>00076 : myID(id), myName(name), myDistricts(districts), <a name="l00077"></a>00077 myEdgeID(edgeid), myPosition(position), <a name="l00078"></a>00078 myAssignedVehicles(assignedVehicles) { <a name="l00079"></a>00079 IntVector::iterator i = <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="The connected districts.">myDistricts</a>.begin(); <a name="l00080"></a>00080 DoubleVector::const_iterator j = percentages.begin(); <a name="l00081"></a>00081 <span class="keywordflow">while</span> (i != <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="The connected districts.">myDistricts</a>.end()) { <a name="l00082"></a>00082 <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="A map how many vehicles (key, amount) should leave to a district (key).">myPercentages</a>[*i] = *j; <a name="l00083"></a>00083 i++; <a name="l00084"></a>00084 j++; <a name="l00085"></a>00085 } <a name="l00086"></a>00086 } <a name="l00087"></a>00087 <a name="l00088"></a>00088 <a name="l00089"></a><a class="code" href="../../d9/d07/<API key>.html#<API key>">00089</a> <a class="code" href="../../d9/d07/<API key>.html#<API key>"><API key>::~<API key></a>() {} <a name="l00090"></a>00090 <a name="l00091"></a>00091 <a name="l00092"></a>00092 <a name="l00093"></a>00093 <span class="keywordtype">bool</span> <a name="l00094"></a><a class="code" href="../../d9/d07/<API key>.html#<API key>">00094</a> <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Inserts the connection into the dictionary after building it."><API key>::dictionary</a>(<span class="keywordtype">int</span> <span class="keywordtype">id</span>, <span class="keyword">const</span> std::string&amp; name, <a name="l00095"></a>00095 <span class="keyword">const</span> <a class="code" href="../../d0/d40/_vector_helper_8h.html#<API key>" title="Definition of a vector of unsigned ints.">IntVector</a>&amp; districts, <span class="keyword">const</span> <a class="code" href="../../d0/d40/_vector_helper_8h.html#<API key>">DoubleVector</a>&amp; percentages, <a name="l00096"></a>00096 <span class="keywordtype">int</span> edgeid, <a class="code" href="../../db/d16/config_8h.html#<API key>">SUMOReal</a> position, <a name="l00097"></a>00097 <span class="keyword">const</span> std::vector&lt;std::pair&lt;int, int&gt; &gt; &amp;assignedVehicles) { <a name="l00098"></a>00098 <a class="code" href="../../d9/d07/<API key>.html"><API key></a>* o = <a name="l00099"></a>00099 <span class="keyword">new</span> <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Contructor."><API key></a>(<span class="keywordtype">id</span>, name, districts, percentages, <a name="l00100"></a>00100 edgeid, position, assignedVehicles); <a name="l00101"></a>00101 <span class="keywordflow">if</span> (!<a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Inserts the connection into the dictionary after building it.">dictionary</a>(<span class="keywordtype">id</span>, o)) { <a name="l00102"></a>00102 <span class="keyword">delete</span> o; <a name="l00103"></a>00103 <span class="keywordflow">return</span> <span class="keyword">false</span>; <a name="l00104"></a>00104 } <a name="l00105"></a>00105 <span class="keywordflow">return</span> <span class="keyword">true</span>; <a name="l00106"></a>00106 } <a name="l00107"></a>00107 <a name="l00108"></a>00108 <a name="l00109"></a>00109 <span class="keywordtype">bool</span> <a name="l00110"></a><a class="code" href="../../d9/d07/<API key>.html#<API key>">00110</a> <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Inserts the connection into the dictionary after building it."><API key>::dictionary</a>(<span class="keywordtype">int</span> <span class="keywordtype">id</span>, <a class="code" href="../../d9/d07/<API key>.html"><API key></a>* o) { <a name="l00111"></a>00111 DictType::iterator i = <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="District connection dictionary.">myDict</a>.find(<span class="keywordtype">id</span>); <a name="l00112"></a>00112 <span class="keywordflow">if</span> (i == <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="District connection dictionary.">myDict</a>.end()) { <a name="l00113"></a>00113 <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="District connection dictionary.">myDict</a>[id] = o; <a name="l00114"></a>00114 <span class="keywordflow">return</span> <span class="keyword">true</span>; <a name="l00115"></a>00115 } <a name="l00116"></a>00116 <span class="keywordflow">return</span> <span class="keyword">false</span>; <a name="l00117"></a>00117 } <a name="l00118"></a>00118 <a name="l00119"></a>00119 <a name="l00120"></a>00120 <a class="code" href="../../d9/d07/<API key>.html"><API key></a>* <a name="l00121"></a><a class="code" href="../../d9/d07/<API key>.html#<API key>">00121</a> <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Inserts the connection into the dictionary after building it."><API key>::dictionary</a>(<span class="keywordtype">int</span> <span class="keywordtype">id</span>) { <a name="l00122"></a>00122 DictType::iterator i = <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="District connection dictionary.">myDict</a>.find(<span class="keywordtype">id</span>); <a name="l00123"></a>00123 <span class="keywordflow">if</span> (i == <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="District connection dictionary.">myDict</a>.end()) { <a name="l00124"></a>00124 <span class="keywordflow">return</span> 0; <a name="l00125"></a>00125 } <a name="l00126"></a>00126 <span class="keywordflow">return</span> (*i).second; <a name="l00127"></a>00127 } <a name="l00128"></a>00128 <a name="l00129"></a>00129 <span class="keywordtype">void</span> <a name="l00130"></a><a class="code" href="../../d9/d07/<API key>.html#<API key>">00130</a> <a class="code" href="../../d9/d07/<API key>.html#<API key>"><API key>::<API key></a>() { <a name="l00131"></a>00131 <span class="comment">// pre-assign connections to districts</span> <a name="l00132"></a>00132 <span class="keywordflow">for</span> (DictType::iterator i = <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="District connection dictionary.">myDict</a>.begin(); i != <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="District connection dictionary.">myDict</a>.end(); i++) { <a name="l00133"></a>00133 <a class="code" href="../../d9/d07/<API key>.html"><API key></a>* c = (*i).second; <a name="l00134"></a>00134 <span class="keyword">const</span> <a class="code" href="../../d0/d40/_vector_helper_8h.html#<API key>" title="Definition of a vector of unsigned ints.">IntVector</a>&amp; districts = c-&gt;<a class="code" href="../../d9/d07/<API key>.html#<API key>" title="The connected districts.">myDistricts</a>; <a name="l00135"></a>00135 <span class="keywordflow">for</span> (IntVector::const_iterator j = districts.begin(); j != districts.end(); j++) { <a name="l00136"></a>00136 <span class="comment">// assign connection to district</span> <a name="l00137"></a>00137 <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Map from ditricts to connections."><API key></a>[*j].push_back((*i).first); <a name="l00138"></a>00138 } <a name="l00139"></a>00139 } <a name="l00140"></a>00140 } <a name="l00141"></a>00141 <a name="l00142"></a>00142 <a name="l00143"></a>00143 <span class="keywordtype">void</span> <a name="l00144"></a><a class="code" href="../../d9/d07/<API key>.html#<API key>">00144</a> <a class="code" href="../../d9/d07/<API key>.html#<API key>"><API key>::dict_CheckEdgeEnds</a>() { <a name="l00145"></a>00145 <span class="keywordflow">for</span> (std::map&lt;int, IntVector&gt;::iterator k = <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Map from ditricts to connections."><API key></a>.begin(); k != <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Map from ditricts to connections."><API key></a>.end(); k++) { <a name="l00146"></a>00146 <span class="keyword">const</span> <a class="code" href="../../d0/d40/_vector_helper_8h.html#<API key>" title="Definition of a vector of unsigned ints.">IntVector</a>&amp; connections = (*k).second; <a name="l00147"></a>00147 <span class="keywordflow">for</span> (IntVector::const_iterator j = connections.begin(); j != connections.end(); j++) { <a name="l00148"></a>00148 <a class="code" href="../../d9/d07/<API key>.html"><API key></a>* c = <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Inserts the connection into the dictionary after building it.">dictionary</a>(*j); <a name="l00149"></a>00149 c-&gt;<a class="code" href="../../d9/d07/<API key>.html#<API key>">checkEdgeEnd</a>(); <a name="l00150"></a>00150 } <a name="l00151"></a>00151 } <a name="l00152"></a>00152 } <a name="l00153"></a>00153 <a name="l00154"></a>00154 <a name="l00155"></a>00155 <span class="keywordtype">void</span> <a name="l00156"></a><a class="code" href="../../d9/d07/<API key>.html#<API key>">00156</a> <a class="code" href="../../d9/d07/<API key>.html#<API key>"><API key>::checkEdgeEnd</a>() { <a name="l00157"></a>00157 <a class="code" href="../../d3/d68/<API key>.html" title="A temporary storage for edges imported from Vissim.">NIVissimEdge</a>* edge = <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Inserts the connection into the dictionary after building it.">NIVissimEdge::dictionary</a>(<a class="code" href="../../d9/d07/<API key>.html#<API key>" title="The id of the connected edge.">myEdgeID</a>); <a name="l00158"></a>00158 assert(edge != 0); <a name="l00159"></a>00159 edge-&gt;<a class="code" href="../../d3/d68/<API key>.html#<API key>"><API key></a>(<a class="code" href="../../d9/d07/<API key>.html#<API key>" title="The position on the edge.">myPosition</a>); <a name="l00160"></a>00160 } <a name="l00161"></a>00161 <a name="l00162"></a>00162 <a name="l00163"></a>00163 <span class="keywordtype">void</span> <a name="l00164"></a><a class="code" href="../../d9/d07/<API key>.html#<API key>">00164</a> <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Builds the nodes that belong to a district."><API key>::<API key></a>(<a class="code" href="../../d3/d1f/<API key>.html" title="A container for districts.">NBDistrictCont</a>&amp; dc, <a name="l00165"></a>00165 <a class="code" href="../../db/d8c/class_n_b_node_cont.html" title="Container for nodes during the netbuilding process.">NBNodeCont</a>&amp; nc) { <a name="l00166"></a>00166 <span class="keywordflow">for</span> (std::map&lt;int, IntVector&gt;::iterator k = <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Map from ditricts to connections."><API key></a>.begin(); k != <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Map from ditricts to connections."><API key></a>.end(); k++) { <a name="l00167"></a>00167 <span class="comment">// get the connections</span> <a name="l00168"></a>00168 <span class="keyword">const</span> <a class="code" href="../../d0/d40/_vector_helper_8h.html#<API key>" title="Definition of a vector of unsigned ints.">IntVector</a>&amp; connections = (*k).second; <a name="l00169"></a>00169 <span class="comment">// retrieve the current district</span> <a name="l00170"></a>00170 std::string dsid = toString&lt;int&gt;((*k).first); <a name="l00171"></a>00171 <a class="code" href="../../d7/d91/class_n_b_district.html" title="A class representing a single district.">NBDistrict</a>* district = <span class="keyword">new</span> <a class="code" href="../../d7/d91/class_n_b_district.html" title="A class representing a single district.">NBDistrict</a>(dsid); <a name="l00172"></a>00172 dc.<a class="code" href="../../d3/d1f/<API key>.html#<API key>" title="Adds a district to the dictionary.">insert</a>(district); <a name="l00173"></a>00173 <span class="comment">// compute the middle of the district</span> <a name="l00174"></a>00174 <a class="code" href="../../da/d56/<API key>.html" title="A list of 2D-positions.">PositionVector</a> pos; <a name="l00175"></a>00175 <span class="keywordflow">for</span> (IntVector::const_iterator j = connections.begin(); j != connections.end(); j++) { <a name="l00176"></a>00176 <a class="code" href="../../d9/d07/<API key>.html"><API key></a>* c = <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Inserts the connection into the dictionary after building it.">dictionary</a>(*j); <a name="l00177"></a>00177 pos.<a class="code" href="../../da/d56/<API key>.html#<API key>" title="Appends the given position to the list.">push_back</a>(c-&gt;<a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Returns the position The position yields from the edge geometry and the place the...">geomPosition</a>()); <a name="l00178"></a>00178 } <a name="l00179"></a>00179 <a class="code" href="../../d7/d3b/class_position.html" title="A point in 2D or 3D with translation and scaling methods.">Position</a> distCenter = pos.<a class="code" href="../../da/d56/<API key>.html#<API key>" title="Returns the arithmetic of all corner points.">getPolygonCenter</a>(); <a name="l00180"></a>00180 <span class="keywordflow">if</span> (connections.size() == 1) { <span class="comment">// !!! ok, ok, maybe not the best way just to add an offset</span> <a name="l00181"></a>00181 distCenter.<a class="code" href="../../d7/d3b/class_position.html#<API key>" title="Adds the given position to this one.">add</a>(10, 10); <a name="l00182"></a>00182 } <a name="l00183"></a>00183 district-&gt;setCenter(distCenter); <a name="l00184"></a>00184 <span class="comment">// build the node</span> <a name="l00185"></a>00185 std::string <span class="keywordtype">id</span> = <span class="stringliteral">&quot;District&quot;</span> + district-&gt;getID(); <a name="l00186"></a>00186 <a class="code" href="../../d3/dd1/class_n_b_node.html" title="Represents a single node (junction) during network building.">NBNode</a>* districtNode = <a name="l00187"></a>00187 <span class="keyword">new</span> <a class="code" href="../../d3/dd1/class_n_b_node.html" title="Represents a single node (junction) during network building.">NBNode</a>(<span class="keywordtype">id</span>, district-&gt;getPosition(), district); <a name="l00188"></a>00188 <span class="keywordflow">if</span> (!nc.<a class="code" href="../../db/d8c/class_n_b_node_cont.html#<API key>" title="Inserts a node into the map.">insert</a>(districtNode)) { <a name="l00189"></a>00189 <span class="keywordflow">throw</span> 1; <a name="l00190"></a>00190 } <a name="l00191"></a>00191 } <a name="l00192"></a>00192 } <a name="l00193"></a>00193 <a name="l00194"></a>00194 <span class="keywordtype">void</span> <a name="l00195"></a><a class="code" href="../../d9/d07/<API key>.html#<API key>">00195</a> <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Builds the districts."><API key>::dict_BuildDistricts</a>(<a class="code" href="../../d3/d1f/<API key>.html" title="A container for districts.">NBDistrictCont</a>&amp; dc, <a name="l00196"></a>00196 <a class="code" href="../../da/ded/class_n_b_edge_cont.html" title="Storage for edges, including some functionality operating on multiple edges.">NBEdgeCont</a>&amp; ec, <a name="l00197"></a>00197 <a class="code" href="../../db/d8c/class_n_b_node_cont.html" title="Container for nodes during the netbuilding process.">NBNodeCont</a>&amp; nc<span class="comment">/*,</span> <a name="l00198"></a>00198 <span class="comment"> NBDistribution &amp;distc*/</span>) { <a name="l00199"></a>00199 <span class="comment">// add the sources and sinks</span> <a name="l00200"></a>00200 <span class="comment">// their normalised probability is computed within NBDistrict</span> <a name="l00201"></a>00201 <span class="comment">// to avoid SUMOReal code writing and more securty within the converter</span> <a name="l00202"></a>00202 <span class="comment">// go through the district table</span> <a name="l00203"></a>00203 <span class="keywordflow">for</span> (std::map&lt;int, IntVector&gt;::iterator k = <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Map from ditricts to connections."><API key></a>.begin(); k != <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Map from ditricts to connections."><API key></a>.end(); k++) { <a name="l00204"></a>00204 <span class="comment">// get the connections</span> <a name="l00205"></a>00205 <span class="keyword">const</span> <a class="code" href="../../d0/d40/_vector_helper_8h.html#<API key>" title="Definition of a vector of unsigned ints.">IntVector</a>&amp; connections = (*k).second; <a name="l00206"></a>00206 <span class="comment">// retrieve the current district</span> <a name="l00207"></a>00207 <a class="code" href="../../d7/d91/class_n_b_district.html" title="A class representing a single district.">NBDistrict</a>* district = <a name="l00208"></a>00208 dc.<a class="code" href="../../d3/d1f/<API key>.html#<API key>" title="Returns the districts with the given id.">retrieve</a>(toString&lt;int&gt;((*k).first)); <a name="l00209"></a>00209 <a class="code" href="../../d3/dd1/class_n_b_node.html" title="Represents a single node (junction) during network building.">NBNode</a>* districtNode = nc.<a class="code" href="../../db/d8c/class_n_b_node_cont.html#<API key>" title="Returns the node with the given name.">retrieve</a>(<span class="stringliteral">&quot;District&quot;</span> + district-&gt;<a class="code" href="../../d5/dbf/class_named.html#<API key>" title="Returns the id.">getID</a>()); <a name="l00210"></a>00210 assert(district != 0 &amp;&amp; districtNode != 0); <a name="l00211"></a>00211 <a name="l00212"></a>00212 <span class="keywordflow">for</span> (IntVector::const_iterator l = connections.begin(); l != connections.end(); l++) { <a name="l00213"></a>00213 <a class="code" href="../../d9/d07/<API key>.html"><API key></a>* c = <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Inserts the connection into the dictionary after building it.">dictionary</a>(*l); <a name="l00214"></a>00214 <span class="comment">// get the edge to connect the parking place to</span> <a name="l00215"></a>00215 <a class="code" href="../../d7/d41/class_n_b_edge.html" title="The representation of a single edge during network building.">NBEdge</a>* e = ec.<a class="code" href="../../da/ded/class_n_b_edge_cont.html#<API key>" title="Returns the edge that has the given id.">retrieve</a>(toString&lt;int&gt;(c-&gt;<a class="code" href="../../d9/d07/<API key>.html#<API key>" title="The id of the connected edge.">myEdgeID</a>)); <a name="l00216"></a>00216 <span class="keywordflow">if</span> (e == 0) { <a name="l00217"></a>00217 e = ec.<a class="code" href="../../da/ded/class_n_b_edge_cont.html#<API key>" title="Tries to retrieve an edge, even if it is splitted."><API key></a>(toString&lt;int&gt;(c-&gt;<a class="code" href="../../d9/d07/<API key>.html#<API key>" title="The id of the connected edge.">myEdgeID</a>), c-&gt;<a class="code" href="../../d9/d07/<API key>.html#<API key>" title="The position on the edge.">myPosition</a>); <a name="l00218"></a>00218 } <a name="l00219"></a>00219 <span class="keywordflow">if</span> (e == 0) { <a name="l00220"></a>00220 <a class="code" href="../../d4/df7/_msg_handler_8h.html#<API key>">WRITE_WARNING</a>(<span class="stringliteral">&quot;Could not build district &#39;&quot;</span> + toString&lt;int&gt;((*k).first) + <span class="stringliteral">&quot;&#39; - edge &#39;&quot;</span> + toString&lt;int&gt;(c-&gt;<a class="code" href="../../d9/d07/<API key>.html#<API key>" title="The id of the connected edge.">myEdgeID</a>) + <span class="stringliteral">&quot;&#39; is missing.&quot;</span>); <a name="l00221"></a>00221 <span class="keywordflow">continue</span>; <a name="l00222"></a>00222 } <a name="l00223"></a>00223 std::string <span class="keywordtype">id</span> = <span class="stringliteral">&quot;ParkingPlace&quot;</span> + toString&lt;int&gt;(*l); <a name="l00224"></a>00224 <a class="code" href="../../d3/dd1/class_n_b_node.html" title="Represents a single node (junction) during network building.">NBNode</a>* parkingPlace = nc.<a class="code" href="../../db/d8c/class_n_b_node_cont.html#<API key>" title="Returns the node with the given name.">retrieve</a>(<span class="keywordtype">id</span>); <a name="l00225"></a>00225 <span class="keywordflow">if</span> (parkingPlace == 0) { <a name="l00226"></a>00226 <a class="code" href="../../db/d16/config_8h.html#<API key>">SUMOReal</a> pos = c-&gt;<a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Returns the position of the connection at the edge.">getPosition</a>(); <a name="l00227"></a>00227 <span class="keywordflow">if</span> (pos &lt; e-&gt;getLength() - pos) { <a name="l00228"></a>00228 parkingPlace = e-&gt;<a class="code" href="../../d7/d41/class_n_b_edge.html#<API key>" title="Returns the origin node of the edge.">getFromNode</a>(); <a name="l00229"></a>00229 parkingPlace-&gt;<a class="code" href="../../d3/dd1/class_n_b_node.html#<API key>"><API key></a>(); <a name="l00230"></a>00230 } <span class="keywordflow">else</span> { <a name="l00231"></a>00231 parkingPlace = e-&gt;<a class="code" href="../../d7/d41/class_n_b_edge.html#<API key>" title="Returns the destination node of the edge.">getToNode</a>(); <a name="l00232"></a>00232 parkingPlace-&gt;<a class="code" href="../../d3/dd1/class_n_b_node.html#<API key>"><API key></a>(); <a name="l00233"></a>00233 } <a name="l00234"></a>00234 } <a name="l00235"></a>00235 assert( <a name="l00236"></a>00236 e-&gt;<a class="code" href="../../d7/d41/class_n_b_edge.html#<API key>" title="Returns the destination node of the edge.">getToNode</a>() == parkingPlace <a name="l00237"></a>00237 || <a name="l00238"></a>00238 e-&gt;<a class="code" href="../../d7/d41/class_n_b_edge.html#<API key>" title="Returns the origin node of the edge.">getFromNode</a>() == parkingPlace); <a name="l00239"></a>00239 <a name="l00240"></a>00240 <span class="comment">// build the connection to the source</span> <a name="l00241"></a>00241 <span class="keywordflow">if</span> (e-&gt;<a class="code" href="../../d7/d41/class_n_b_edge.html#<API key>" title="Returns the origin node of the edge.">getFromNode</a>() == parkingPlace) { <a name="l00242"></a>00242 <span class="keywordtype">id</span> = <span class="stringliteral">&quot;<API key>&quot;</span> + toString&lt;int&gt;((*k).first) + <span class="stringliteral">&quot;-&quot;</span> + toString&lt;int&gt;(c-&gt;<a class="code" href="../../d9/d07/<API key>.html#<API key>" title="The id of the connections.">myID</a>); <a name="l00243"></a>00243 <a class="code" href="../../d7/d41/class_n_b_edge.html" title="The representation of a single edge during network building.">NBEdge</a>* source = <a name="l00244"></a>00244 <span class="keyword">new</span> <a class="code" href="../../d7/d41/class_n_b_edge.html" title="The representation of a single edge during network building.">NBEdge</a>(<span class="keywordtype">id</span>, districtNode, parkingPlace, <a name="l00245"></a>00245 <span class="stringliteral">&quot;Connection&quot;</span>, c-&gt;<a class="code" href="../../d9/d07/<API key>.html#<API key>">getMeanSpeed</a>(<span class="comment">/*distc*/</span>) / (<a class="code" href="../../db/d16/config_8h.html#<API key>">SUMOReal</a>) 3.6, 3, -1, -1, <a class="code" href="../../d6/d7a/<API key>.html#<API key>">LANESPREAD_RIGHT</a>); <a name="l00246"></a>00246 <span class="keywordflow">if</span> (!ec.<a class="code" href="../../da/ded/class_n_b_edge_cont.html#<API key>" title="Adds an edge to the dictionary.">insert</a>(source)) { <span class="comment">// !!! in den Konstruktor</span> <a name="l00247"></a>00247 <span class="keywordflow">throw</span> 1; <span class="comment">// !!!</span> <a name="l00248"></a>00248 } <a name="l00249"></a>00249 <a class="code" href="../../db/d16/config_8h.html#<API key>">SUMOReal</a> percNormed = <a name="l00250"></a>00250 c-&gt;<a class="code" href="../../d9/d07/<API key>.html#<API key>" title="A map how many vehicles (key, amount) should leave to a district (key).">myPercentages</a>[(*k).first]; <a name="l00251"></a>00251 <span class="keywordflow">if</span> (!district-&gt;<a class="code" href="../../d7/d91/class_n_b_district.html#<API key>" title="Adds a source.">addSource</a>(source, percNormed)) { <a name="l00252"></a>00252 <span class="keywordflow">throw</span> 1; <a name="l00253"></a>00253 } <a name="l00254"></a>00254 } <a name="l00255"></a>00255 <a name="l00256"></a>00256 <span class="comment">// build the connection to the destination</span> <a name="l00257"></a>00257 <span class="keywordflow">if</span> (e-&gt;<a class="code" href="../../d7/d41/class_n_b_edge.html#<API key>" title="Returns the destination node of the edge.">getToNode</a>() == parkingPlace) { <a name="l00258"></a>00258 <span class="keywordtype">id</span> = <span class="stringliteral">&quot;<API key>&quot;</span> + toString&lt;int&gt;((*k).first) + <span class="stringliteral">&quot;-&quot;</span> + toString&lt;int&gt;(c-&gt;<a class="code" href="../../d9/d07/<API key>.html#<API key>" title="The id of the connections.">myID</a>); <a name="l00259"></a>00259 <a class="code" href="../../d7/d41/class_n_b_edge.html" title="The representation of a single edge during network building.">NBEdge</a>* destination = <a name="l00260"></a>00260 <span class="keyword">new</span> <a class="code" href="../../d7/d41/class_n_b_edge.html" title="The representation of a single edge during network building.">NBEdge</a>(<span class="keywordtype">id</span>, parkingPlace, districtNode, <a name="l00261"></a>00261 <span class="stringliteral">&quot;Connection&quot;</span>, (<a class="code" href="../../db/d16/config_8h.html#<API key>">SUMOReal</a>) 100 / (<a class="code" href="../../db/d16/config_8h.html#<API key>">SUMOReal</a>) 3.6, 2, -1, -1, <a class="code" href="../../d6/d7a/<API key>.html#<API key>">LANESPREAD_RIGHT</a>); <a name="l00262"></a>00262 <span class="keywordflow">if</span> (!ec.<a class="code" href="../../da/ded/class_n_b_edge_cont.html#<API key>" title="Adds an edge to the dictionary.">insert</a>(destination)) { <span class="comment">// !!! (in den Konstruktor)</span> <a name="l00263"></a>00263 <span class="keywordflow">throw</span> 1; <span class="comment">// !!!</span> <a name="l00264"></a>00264 } <a name="l00265"></a>00265 <a class="code" href="../../db/d16/config_8h.html#<API key>">SUMOReal</a> percNormed2 = <a name="l00266"></a>00266 c-&gt;<a class="code" href="../../d9/d07/<API key>.html#<API key>" title="A map how many vehicles (key, amount) should leave to a district (key).">myPercentages</a>[(*k).first]; <a name="l00267"></a>00267 <span class="keywordflow">if</span> (!district-&gt;<a class="code" href="../../d7/d91/class_n_b_district.html#<API key>" title="Adds a sink.">addSink</a>(destination, percNormed2)) { <a name="l00268"></a>00268 <span class="keywordflow">throw</span> 1; <span class="comment">// !!!</span> <a name="l00269"></a>00269 } <a name="l00270"></a>00270 } <a name="l00271"></a>00271 <a name="l00272"></a>00272 <span class="comment">/*</span> <a name="l00273"></a>00273 <span class="comment"> if(e-&gt;getToNode()==districtNode) {</span> <a name="l00274"></a>00274 <span class="comment"> SUMOReal percNormed =</span> <a name="l00275"></a>00275 <span class="comment"> c-&gt;myPercentages[(*k).first];</span> <a name="l00276"></a>00276 <span class="comment"> district-&gt;addSink(e, percNormed);</span> <a name="l00277"></a>00277 <span class="comment"> }</span> <a name="l00278"></a>00278 <span class="comment"> if(e-&gt;getFromNode()==districtNode) {</span> <a name="l00279"></a>00279 <span class="comment"> SUMOReal percNormed =</span> <a name="l00280"></a>00280 <span class="comment"> c-&gt;myPercentages[(*k).first];</span> <a name="l00281"></a>00281 <span class="comment"> district-&gt;addSource(e, percNormed);</span> <a name="l00282"></a>00282 <span class="comment"> }</span> <a name="l00283"></a>00283 <span class="comment"> */</span> <a name="l00284"></a>00284 } <a name="l00285"></a>00285 <a name="l00286"></a>00286 <span class="comment">/*</span> <a name="l00287"></a>00287 <span class="comment"> // add them as sources and sinks to the current district</span> <a name="l00288"></a>00288 <span class="comment"> for(IntVector::const_iterator l=connections.begin(); l!=connections.end(); l++) {</span> <a name="l00289"></a>00289 <span class="comment"> // get the current connections</span> <a name="l00290"></a>00290 <span class="comment"> <API key> *c = dictionary(*l);</span> <a name="l00291"></a>00291 <span class="comment"> // get the edge to connect the parking place to</span> <a name="l00292"></a>00292 <span class="comment"> NBEdge *e = NBEdgeCont::retrieve(toString&lt;int&gt;(c-&gt;myEdgeID));</span> <a name="l00293"></a>00293 <span class="comment"> Position edgepos = c-&gt;geomPosition();</span> <a name="l00294"></a>00294 <span class="comment"> NBNode *edgeend = e-&gt;<API key>(c-&gt;myPosition,</span> <a name="l00295"></a>00295 <span class="comment"> e-&gt;getLength()/4.0);</span> <a name="l00296"></a>00296 <span class="comment"> if(edgeend==0) {</span> <a name="l00297"></a>00297 <span class="comment"> // Edge splitting omitted on build district connections by now</span> <a name="l00298"></a>00298 <span class="comment"> assert(false);</span> <a name="l00299"></a>00299 <span class="comment"> }</span> <a name="l00300"></a>00300 <span class="comment"></span> <a name="l00301"></a>00301 <span class="comment"> // build the district-node if not yet existing</span> <a name="l00302"></a>00302 <span class="comment"> std::string id = &quot;VissimParkingplace&quot; + district-&gt;getID();</span> <a name="l00303"></a>00303 <span class="comment"> NBNode *districtNode = nc.retrieve(id);</span> <a name="l00304"></a>00304 <span class="comment"> assert(districtNode!=0);</span> <a name="l00305"></a>00305 <span class="comment"></span> <a name="l00306"></a>00306 <span class="comment"> if(e-&gt;getToNode()==edgeend) {</span> <a name="l00307"></a>00307 <span class="comment"> // build the connection to the source</span> <a name="l00308"></a>00308 <span class="comment"> id = std::string(&quot;<API key>&quot;)</span> <a name="l00309"></a>00309 <span class="comment"> + toString&lt;int&gt;((*k).first) + &quot;-&quot;</span> <a name="l00310"></a>00310 <span class="comment"> + toString&lt;int&gt;(c-&gt;myID);</span> <a name="l00311"></a>00311 <span class="comment"> NBEdge *source =</span> <a name="l00312"></a>00312 <span class="comment"> new NBEdge(id, id, districtNode, edgeend,</span> <a name="l00313"></a>00313 <span class="comment"> &quot;Connection&quot;, 100/3.6, 2, 100, 0,</span> <a name="l00314"></a>00314 <span class="comment"> NBEdge::EDGEFUNCTION_SOURCE);</span> <a name="l00315"></a>00315 <span class="comment"> NBEdgeCont::insert(source); // !!! (in den Konstruktor)</span> <a name="l00316"></a>00316 <span class="comment"> SUMOReal percNormed =</span> <a name="l00317"></a>00317 <span class="comment"> c-&gt;myPercentages[(*k).first];</span> <a name="l00318"></a>00318 <span class="comment"> district-&gt;addSource(source, percNormed);</span> <a name="l00319"></a>00319 <span class="comment"> } else {</span> <a name="l00320"></a>00320 <span class="comment"> // build the connection to the destination</span> <a name="l00321"></a>00321 <span class="comment"> id = std::string(&quot;<API key>&quot;)</span> <a name="l00322"></a>00322 <span class="comment"> + toString&lt;int&gt;((*k).first) + &quot;-&quot;</span> <a name="l00323"></a>00323 <span class="comment"> + toString&lt;int&gt;(c-&gt;myID);</span> <a name="l00324"></a>00324 <span class="comment"> NBEdge *destination =</span> <a name="l00325"></a>00325 <span class="comment"> new NBEdge(id, id, edgeend, districtNode,</span> <a name="l00326"></a>00326 <span class="comment"> &quot;Connection&quot;, 100/3.6, 2, 100, 0,</span> <a name="l00327"></a>00327 <span class="comment"> NBEdge::EDGEFUNCTION_SINK);</span> <a name="l00328"></a>00328 <span class="comment"> NBEdgeCont::insert(destination); // !!! (in den Konstruktor)</span> <a name="l00329"></a>00329 <span class="comment"></span> <a name="l00330"></a>00330 <span class="comment"> // add both the source and the sink to the district</span> <a name="l00331"></a>00331 <span class="comment"> SUMOReal percNormed =</span> <a name="l00332"></a>00332 <span class="comment"> c-&gt;myPercentages[(*k).first];</span> <a name="l00333"></a>00333 <span class="comment"> district-&gt;addSink(destination, percNormed);</span> <a name="l00334"></a>00334 <span class="comment"> }</span> <a name="l00335"></a>00335 <span class="comment"> }</span> <a name="l00336"></a>00336 <span class="comment"> */</span> <a name="l00337"></a>00337 } <a name="l00338"></a>00338 } <a name="l00339"></a>00339 <a name="l00340"></a>00340 <a name="l00341"></a>00341 <a name="l00342"></a>00342 <a class="code" href="../../d7/d3b/class_position.html" title="A point in 2D or 3D with translation and scaling methods.">Position</a> <a name="l00343"></a><a class="code" href="../../d9/d07/<API key>.html#<API key>">00343</a> <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Returns the position The position yields from the edge geometry and the place the..."><API key>::geomPosition</a>()<span class="keyword"> const </span>{ <a name="l00344"></a>00344 <a class="code" href="../../da/d14/<API key>.html"><API key></a>* e = <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Inserts the connection into the dictionary after building it.">NIVissimEdge::dictionary</a>(<a class="code" href="../../d9/d07/<API key>.html#<API key>" title="The id of the connected edge.">myEdgeID</a>); <a name="l00345"></a>00345 <span class="keywordflow">return</span> e-&gt;<a class="code" href="../../da/d14/<API key>.html#<API key>">getGeomPosition</a>(<a class="code" href="../../d9/d07/<API key>.html#<API key>" title="The position on the edge.">myPosition</a>); <a name="l00346"></a>00346 } <a name="l00347"></a>00347 <a name="l00348"></a>00348 <a name="l00349"></a>00349 <a class="code" href="../../d9/d07/<API key>.html"><API key></a>* <a name="l00350"></a><a class="code" href="../../d9/d07/<API key>.html#<API key>">00350</a> <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Returns the connection to a district placed at the given node Yep, there onyl should..."><API key>::dict_findForEdge</a>(<span class="keywordtype">int</span> edgeid) { <a name="l00351"></a>00351 <span class="keywordflow">for</span> (DictType::iterator i = <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="District connection dictionary.">myDict</a>.begin(); i != <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="District connection dictionary.">myDict</a>.end(); i++) { <a name="l00352"></a>00352 <span class="keywordflow">if</span> ((*i).second-&gt;myEdgeID == edgeid) { <a name="l00353"></a>00353 <span class="keywordflow">return</span> (*i).second; <a name="l00354"></a>00354 } <a name="l00355"></a>00355 } <a name="l00356"></a>00356 <span class="keywordflow">return</span> 0; <a name="l00357"></a>00357 } <a name="l00358"></a>00358 <a name="l00359"></a>00359 <a name="l00360"></a>00360 <span class="keywordtype">void</span> <a name="l00361"></a><a class="code" href="../../d9/d07/<API key>.html#<API key>">00361</a> <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Clears the dictionary."><API key>::clearDict</a>() { <a name="l00362"></a>00362 <span class="keywordflow">for</span> (DictType::iterator i = <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="District connection dictionary.">myDict</a>.begin(); i != <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="District connection dictionary.">myDict</a>.end(); i++) { <a name="l00363"></a>00363 <span class="keyword">delete</span>(*i).second; <a name="l00364"></a>00364 } <a name="l00365"></a>00365 <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="District connection dictionary.">myDict</a>.clear(); <a name="l00366"></a>00366 } <a name="l00367"></a>00367 <a name="l00368"></a>00368 <a name="l00369"></a>00369 <a class="code" href="../../db/d16/config_8h.html#<API key>">SUMOReal</a> <a name="l00370"></a><a class="code" href="../../d9/d07/<API key>.html#<API key>">00370</a> <a class="code" href="../../d9/d07/<API key>.html#<API key>"><API key>::getMeanSpeed</a>(<span class="comment">/*NBDistribution &amp;dc*/</span>)<span class="keyword"> const </span>{ <a name="l00371"></a>00371 <span class="comment">//assert(myAssignedVehicles.size()!=0);</span> <a name="l00372"></a>00372 <span class="keywordflow">if</span> (<a class="code" href="../../d9/d07/<API key>.html#<API key>" title="The vehicles using this connection.">myAssignedVehicles</a>.size() == 0) { <a name="l00373"></a>00373 <a class="code" href="../../d4/df7/_msg_handler_8h.html#<API key>">WRITE_WARNING</a>(<span class="stringliteral">&quot;No streams assigned at district&#39;&quot;</span> + <a class="code" href="../../d8/d08/_to_string_8h.html#<API key>">toString</a>(<a class="code" href="../../d9/d07/<API key>.html#<API key>" title="The id of the connections.">myID</a>) + <span class="stringliteral">&quot;&#39;.\n Using default speed 200km/h&quot;</span>); <a name="l00374"></a>00374 <span class="keywordflow">return</span> (<a class="code" href="../../db/d16/config_8h.html#<API key>">SUMOReal</a>) 200 / (<a class="code" href="../../db/d16/config_8h.html#<API key>">SUMOReal</a>) 3.6; <a name="l00375"></a>00375 } <a name="l00376"></a>00376 <a class="code" href="../../db/d16/config_8h.html#<API key>">SUMOReal</a> speed = 0; <a name="l00377"></a>00377 std::vector&lt;std::pair&lt;int, int&gt; &gt;::const_iterator i; <a name="l00378"></a>00378 <span class="keywordflow">for</span> (i = <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="The vehicles using this connection.">myAssignedVehicles</a>.begin(); i != <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="The vehicles using this connection.">myAssignedVehicles</a>.end(); i++) { <a name="l00379"></a>00379 speed += <a class="code" href="../../d9/d07/<API key>.html#<API key>">getRealSpeed</a>(<span class="comment"></span>(*i).second); <a name="l00380"></a>00380 } <a name="l00381"></a>00381 <span class="keywordflow">return</span> speed / (<a class="code" href="../../db/d16/config_8h.html#<API key>">SUMOReal</a>) <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="The vehicles using this connection.">myAssignedVehicles</a>.size(); <a name="l00382"></a>00382 } <a name="l00383"></a>00383 <a name="l00384"></a>00384 <a name="l00385"></a>00385 <a class="code" href="../../db/d16/config_8h.html#<API key>">SUMOReal</a> <a name="l00386"></a><a class="code" href="../../d9/d07/<API key>.html#<API key>">00386</a> <a class="code" href="../../d9/d07/<API key>.html#<API key>"><API key>::getRealSpeed</a>(<span class="comment">/*NBDistribution &amp;dc, */</span><span class="keywordtype">int</span> distNo)<span class="keyword"> const </span>{ <a name="l00387"></a>00387 std::string <span class="keywordtype">id</span> = toString&lt;int&gt;(distNo); <a name="l00388"></a>00388 <a class="code" href="../../d8/d4f/class_distribution.html">Distribution</a>* dist = <a class="code" href="../../d9/d07/<API key>.html#<API key>" title="Inserts the connection into the dictionary after building it.">NBDistribution::dictionary</a>(<span class="stringliteral">&quot;speed&quot;</span>, <span class="keywordtype">id</span>); <a name="l00389"></a>00389 <span class="keywordflow">if</span> (dist == 0) { <a name="l00390"></a>00390 <a class="code" href="../../d4/df7/_msg_handler_8h.html#<API key>">WRITE_WARNING</a>(<span class="stringliteral">&quot;The referenced speed distribution &#39;&quot;</span> + <span class="keywordtype">id</span> + <span class="stringliteral">&quot;&#39; is not known.&quot;</span>); <a name="l00391"></a>00391 <a class="code" href="../../d4/df7/_msg_handler_8h.html#<API key>">WRITE_WARNING</a>(<span class="stringliteral">&quot;. Using default.&quot;</span>); <a name="l00392"></a>00392 <span class="keywordflow">return</span> <a class="code" href="../../db/d31/class_options_cont.html#<API key>" title="Retrieves the options.">OptionsCont::getOptions</a>().<a class="code" href="../../db/d31/class_options_cont.html#<API key>" title="Returns the SUMOReal-value of the named option (only for Option_Float).">getFloat</a>(<span class="stringliteral">&quot;vissim.default-speed&quot;</span>); <a name="l00393"></a>00393 } <a name="l00394"></a>00394 assert(dist != 0); <a name="l00395"></a>00395 <a class="code" href="../../db/d16/config_8h.html#<API key>">SUMOReal</a> speed = dist-&gt;getMax(); <a name="l00396"></a>00396 <span class="keywordflow">if</span> (speed &lt; 0 || speed &gt; 1000) { <a name="l00397"></a>00397 <a class="code" href="../../d4/df7/_msg_handler_8h.html#<API key>">WRITE_WARNING</a>(<span class="stringliteral">&quot; False speed at district &#39;&quot;</span> + <span class="keywordtype">id</span>); <a name="l00398"></a>00398 <a class="code" href="../../d4/df7/_msg_handler_8h.html#<API key>">WRITE_WARNING</a>(<span class="stringliteral">&quot;. Using default.&quot;</span>); <a name="l00399"></a>00399 speed = <a class="code" href="../../db/d31/class_options_cont.html#<API key>" title="Retrieves the options.">OptionsCont::getOptions</a>().<a class="code" href="../../db/d31/class_options_cont.html#<API key>" title="Returns the SUMOReal-value of the named option (only for Option_Float).">getFloat</a>(<span class="stringliteral">&quot;vissim.default-speed&quot;</span>); <a name="l00400"></a>00400 } <a name="l00401"></a>00401 <span class="keywordflow">return</span> speed; <a name="l00402"></a>00402 } <a name="l00403"></a>00403 <a name="l00404"></a>00404 <a name="l00405"></a>00405 <a name="l00406"></a>00406 <span class="comment"></span> <a name="l00407"></a>00407 </pre></div></div> <hr class="footer"/><address style="text-align: right;"><small>Generated on Tue Jul 17 12:16:07 2012 for SUMO - Simulation of Urban MObility by&nbsp; <a href="http: <img class="footer" src="../../doxygen.png" alt="doxygen"/></a> 1.6.3 </small></address> </body> </html>
#if !defined __DIALOGGLOBVAR__ #define __DIALOGGLOBVAR__ #include "PropertySheetBase.h" #include "DialogGenGlobVar.h" #include "DialogType.h" class CDialogGlobVar : public CPropertySheetBase, public CDialogGenGlobVar { public: CDialogGlobVar(DIALOGTYPE DialogType); virtual ~CDialogGlobVar(); CREATE_DELETE_DECL(CDialogGlobVar) }; #endif
<?php /** @see <API key> */ require_once 'Zend/Barcode/Exception.php'; class <API key> extends <API key> { }
package com.mec.duke; import static org.junit.Assert.*; import org.junit.Test; public class ParserTest { @Test public void testParseSQLScript() { /* * Test case for parsing SQL Script: * purpose: Re-organize the SQL script * * INPUT: * select * from * (select A.*,row_number() over() as rn from * (select C_INIT_FLAG,C_REF_NAME,C_REF_DESC,C_UNIT_CODE,C_TRX_STATUS,C_LOCKED_FLAG,C_REF_TYPE from EXI1.STT_TRX_REF where 1=1) * as A) * where rn<= 10 and rn> 0 ; * * OUTPUT: * * select * from * (select A.*,row_number() over() as rn from * (select C_INIT_FLAG,C_REF_NAME,C_REF_DESC,C_UNIT_CODE,C_TRX_STATUS,C_LOCKED_FLAG,C_REF_TYPE from EXI1.STT_TRX_REF where 1=1) * as A) AS TMP2 * where rn<= 10 and rn> 0 ; * * * Note: * 1, Grammar for the SQL */ } static class SelectStatement{ } static class InsertStatement{ } }
#ifndef <API key> #define <API key> #include <corecrypto/ccdigest.h> #include <corecrypto/ccasn1.h> void <API key>(const struct ccdigest_info *di, ccdigest_ctx_t ctx, void *digest); void ccdigest_final_64be(const struct ccdigest_info *di, ccdigest_ctx_t, unsigned char *digest); void ccdigest_final_64le(const struct ccdigest_info *di, ccdigest_ctx_t, unsigned char *digest); CC_INLINE CC_NONNULL_TU((1)) bool ccdigest_oid_equal(const struct ccdigest_info *di, ccoid_t oid) { if(di->oid == NULL && CCOID(oid) == NULL) return true; if(di->oid == NULL || CCOID(oid) == NULL) return false; return ccoid_equal(di->oid, oid); } typedef const struct ccdigest_info *(ccdigest_lookup)(ccoid_t oid); #include <stdarg.h> const struct ccdigest_info *ccdigest_oid_lookup(ccoid_t oid, ...); #endif /* <API key> */
// depth-first search // using adjancy list graph representation // Written by // INSOP SONG // Systems Design // University of Waterloo, Canada // August 2001 #ifndef _DFS_H_ #define _DFS_H_ #undef RECURSIVE #include <stdio.h> #include "../graph/graph.h" #include "../graph/stack.h" #include "../graph/bdBuffer.h" const int NumQueue = 5; // Depth First Search class DFS { private: Graph *pGrp; int id; int numQueue; int val[NumVertex]; Stack stack; BdBuffer queue[NumQueue]; public: DFS(Graph *_pGrp); void testDFS(void); void visit(int nVtx); void init(void); void search(void); void visitSP(int start, int end); void shortPath(int start, int end); void printTraverse(void); }; #endif //_DFS_H_
title: "देना बैंक ने मनाया अंतर्राष्ट्रीय महिला दिवस" layout: item category: ["business"] date: 2017-03-09T10:50:19.852Z image: 1489056619851dena.jpg <p>देना बैंक ने 8 मार्च 2017 को अंतर्राष्ट्रीय महिला दिवस मनाया. इस अवसर पर बैंक के अध्यक्ष एवं प्रबंध निदेशक श्री अश्वनी कुमार और कार्यकारी निदेशक श्रीमती तृष्णा गुहा और श्री रमेश सिंह उपस्थित थे. सुश्री हर्षिता अतालूरी, प्रभारी, बैंक सिक्योरिटी एंड फ्रॉड सेल, सीबीआई इस समारोह की मुख्य अतिथि थी और डॉ. सोनल बांगडे, प्रमोटर एंड मेडिकल डायरेक्टर, आईएनएफईएक्सएन लैबोरेटरीज प्राइवेट लिमिटेड गेस्ट ऑफ ऑनर थी. बैंक ने विभिन्न क्षेत्रों जैसे शिक्षा, खेल, हेल्थकेयर, जर्नलिज्म, मेडिकल और सौंदर्य देखभाल आदि में 11 सफल महिलाओं को सम्मानित किया. कुछ सम्मानित महिलाओं ने अपनी सफलता की कहानियों को साझा भी किया. इस अवसर पर बैंक ने अपने स्टाफ के लिए कई खेल और सांस्कृतिक कार्यक्रम भी आयोजित किए. समाज कल्याण योगदान के लिए बैंक ने मुंबई के विभिन्न स्थानों पर रक्तदान शिविरों का भी आयोजन किया. </p>
package cn.hugeterry.coderfun.fragment; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout; import com.orangegangsters.github.swipyrefreshlayout.library.<API key>; import java.util.List; import java.util.concurrent.TimeUnit; import cn.hugeterry.coderfun.CoderfunKey; import cn.hugeterry.coderfun.R; import cn.hugeterry.coderfun.adapter.ReadAdapter; import cn.hugeterry.coderfun.model.beans.DataResults; import cn.hugeterry.coderfun.model.beans.Results; import cn.hugeterry.coderfun.retrofit.CoderfunSingle; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers; public class ReadFragment extends Fragment { private SwipyRefreshLayout swipyRefreshLayout; private RecyclerView recyclerview; private ReadAdapter readAdapter; private static final String ARG_TITLE = "title"; private String mTitle; private static int read_num = CoderfunKey.READ_NUM; private static int NOW_PAGE_READ = 1; public static ReadFragment getInstance(String title) { ReadFragment fra = new ReadFragment(); Bundle bundle = new Bundle(); bundle.putString(ARG_TITLE, title); fra.setArguments(bundle); return fra; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = getArguments(); mTitle = bundle.getString(ARG_TITLE); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_list, container, false); initRecyclerView(v); <API key>(v); return v; } @Override public void onResume() { super.onResume(); loadData(true); } private void loadData(Boolean isTop) { if (isTop) { NOW_PAGE_READ = 1; } getDataResults(mTitle, read_num, NOW_PAGE_READ, isTop); } private void <API key>(View v) { swipyRefreshLayout = (SwipyRefreshLayout) v.findViewById(R.id.swipyrefreshlayout); swipyRefreshLayout.<API key>( android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light); swipyRefreshLayout.setDirection(<API key>.BOTH); swipyRefreshLayout.<API key>(new SwipyRefreshLayout.OnRefreshListener() { @Override public void onRefresh(<API key> direction) { Observable.timer(2, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<Long>() { @Override public void call(Long aLong) { swipyRefreshLayout.setRefreshing(false); } }); loadData(direction == <API key>.TOP ? true : false); } }); } private void initRecyclerView(View v) { recyclerview = (RecyclerView) v.findViewById(R.id.recyclerView); recyclerview.setLayoutManager(new LinearLayoutManager(recyclerview.getContext())); readAdapter = new ReadAdapter(getActivity(), null); recyclerview.setAdapter(readAdapter); } private void getDataResults(final String type, int number, int page, final boolean isTop) { CoderfunSingle.getInstance(true).getDataResults(type, number, page) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<DataResults>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { Snackbar.make(recyclerview, ",", Snackbar.LENGTH_SHORT).show(); } @Override public void onNext(DataResults dataResults) { if (dataResults.isError()) { Snackbar.make(recyclerview, "", Snackbar.LENGTH_SHORT).show(); } else { if (isTop) { clearAdapterResults(); } <API key>(dataResults.getResults()); } } }); } private void clearAdapterResults() { readAdapter.getResults().clear(); } private void <API key>(List<Results> read_list) { readAdapter.getResults().addAll(read_list); readAdapter.<API key>(); NOW_PAGE_READ++; } }
import { SortType, SortDirection, SortPropDir } from '../types'; import { getterForProp } from './column-prop-getters'; /** * Gets the next sort direction */ export function nextSortDir(sortType: SortType, current: SortDirection): SortDirection | undefined { if (sortType === SortType.single) { if(current === SortDirection.asc) { return SortDirection.desc; } else { return SortDirection.asc; } } else { if(!current) { return SortDirection.asc; } else if(current === SortDirection.asc) { return SortDirection.desc; } else if(current === SortDirection.desc) { return undefined; } // avoid TS7030: Not all code paths return a value. return undefined; } } export function orderByComparator(a: any, b: any): number { if (a === null || typeof a === 'undefined') a = 0; if (b === null || typeof b === 'undefined') b = 0; if (a instanceof Date && b instanceof Date) { if (a < b) return -1; if (a > b) return 1; } else if ((isNaN(parseFloat(a)) || !isFinite(a)) || (isNaN(parseFloat(b)) || !isFinite(b))) { // Convert to string in case of a=0 or b=0 a = String(a); b = String(b); // Isn't a number so lowercase the string to properly compare if (a.toLowerCase() < b.toLowerCase()) return -1; if (a.toLowerCase() > b.toLowerCase()) return 1; } else { // Parse strings as numbers to compare properly if (parseFloat(a) < parseFloat(b)) return -1; if (parseFloat(a) > parseFloat(b)) return 1; } // equal each other return 0; } /** * creates a shallow copy of the `rows` input and returns the sorted copy. this function * does not sort the `rows` argument in place */ export function sortRows(rows: any[], columns: any[], dirs: SortPropDir[]): any[] { if(!rows) return []; if(!dirs || !dirs.length || !columns) return [...rows]; /** * record the row ordering of results from prior sort operations (if applicable) * this is necessary to guarantee stable sorting behavior */ const rowToIndexMap = new Map<any, number>(); rows.forEach((row, index) => rowToIndexMap.set(row, index)); const temp = [...rows]; const cols = columns.reduce((obj, col) => { if(col.comparator && typeof col.comparator === 'function') { obj[col.prop] = col.comparator; } return obj; }, {}); // cache valueGetter and compareFn so that they // do not need to be looked-up in the sort function body const cachedDirs = dirs.map(dir => { const prop = dir.prop; return { prop, dir: dir.dir, valueGetter: getterForProp(prop), compareFn: cols[prop] || orderByComparator }; }); return temp.sort(function(rowA: any, rowB: any) { for(const cachedDir of cachedDirs) { // Get property and valuegetters for column to be sorted const { prop, valueGetter } = cachedDir; // Get A and B cell values from rows based on properties of the columns const propA = valueGetter(rowA, prop); const propB = valueGetter(rowB, prop); // Compare function gets five parameters: // Two cell values to be compared as propA and propB // Two rows corresponding to the cells as rowA and rowB // Direction of the sort for this column as SortDirection // Compare can be a standard JS comparison function (a,b) => -1|0|1 // as additional parameters are silently ignored. The whole row and sort // direction enable more complex sort logic. const comparison = cachedDir.dir !== SortDirection.desc ? cachedDir.compareFn(propA, propB, rowA, rowB, cachedDir.dir) : -cachedDir.compareFn(propA, propB, rowA, rowB, cachedDir.dir); // Don't return 0 yet in case of needing to sort by next property if (comparison !== 0) return comparison; } if (!(rowToIndexMap.has(rowA) && rowToIndexMap.has(rowB))) return 0; /** * all else being equal, preserve original order of the rows (stable sort) */ return rowToIndexMap.get(rowA) < rowToIndexMap.get(rowB) ? -1 : 1; }); }
angular.module("datetime", []); angular.module("datetime").factory("datetime", ["$locale", function($locale){ // Fetch date and time formats from $locale service var formats = $locale.DATETIME_FORMATS; // Valid format tokens. 1=sss, 2='' var tokenRE = /yyyy|yy|y|M{1,4}|dd?|EEEE?|HH?|hh?|mm?|ss?|([.,])sss|a|Z|ww|w|'(([^']+|'')*)'/g; // Token definition var definedTokens = { "y": { minLength: 1, maxLength: 4, min: 1, max: 9999, name: "year", type: "number" }, "yy": { minLength: 2, maxLength: 2, min: 1, max: 99, name: "year", type: "number" }, "yyyy": { minLength: 4, maxLength: 4, min: 1, max: 9999, name: "year", type: "number" }, "MMMM": { name: "month", type: "select", select: formats.MONTH }, "MMM": { name: "month", type: "select", select: formats.SHORTMONTH }, "MM": { minLength: 2, maxLength: 2, min: 1, max: 12, name: "month", type: "number" }, "M": { minLength: 1, maxLength: 2, min: 1, max: 12, name: "month", type: "number" }, "dd": { minLength: 2, maxLength: 2, min: 1, max: 31, name: "date", type: "number" }, "d": { minLength: 1, maxLength: 2, min: 1, max: 31, name: "date", type: "number" }, "EEEE": { name: "day", type: "select", select: fixDay(formats.DAY) }, "EEE": { name: "day", type: "select", select: fixDay(formats.SHORTDAY) }, "HH": { minLength: 2, maxLength: 2, min: 0, max: 23, name: "hour", type: "number" }, "H": { minLength: 1, maxLength: 2, min: 0, max: 23, name: "hour", type: "number" }, "hh": { minLength: 2, maxLength: 2, min: 1, max: 12, name: "hour12", type: "number" }, "h": { minLength: 1, maxLength: 2, min: 1, max: 12, name: "hour12", type: "number" }, "mm": { minLength: 2, maxLength: 2, min: 0, max: 59, name: "minute", type: "number" }, "m": { minLength: 1, maxLength: 2, min: 0, max: 59, name: "minute", type: "number" }, "ss": { minLength: 2, maxLength: 2, min: 0, max: 59, name: "second", type: "number" }, "s": { minLength: 1, maxLength: 2, min: 0, max: 59, name: "second", type: "number" }, "milliPrefix": { name: "milliPrefix", type: "regex", regex: /[,.]/ }, "sss": { minLength: 3, maxLength: 3, min: 0, max: 999, name: "millisecond", type: "number" }, "a": { name: "ampm", type: "select", select: formats.AMPMS }, "ww": { minLength: 2, maxLength: 2, min: 0, max: 53, name: "week", type: "number" }, "w": { minLength: 1, maxLength: 2, min: 0, max: 53, name: "week", type: "number" }, "Z": { name: "timezone", type: "regex", regex: /[+-]\d{4}/ }, "string": { name: "string", type: "static" } }; // Push Sunday to the end function fixDay(days) { var s = [], i; for (i = 1; i < days.length; i++) { s.push(days[i]); } s.push(days[0]); return s; } // Use localizable formats function getFormat(format) { return formats[format] || format; } function createNode(token, value) { return { token: definedTokens[token], value: value, viewValue: value || "", offset: 0 }; } // Parse format to nodes function createNodes(format) { var nodes = [], pos = 0, match; while ((match = tokenRE.exec(format))) { if (match.index > pos) { nodes.push(createNode("string", format.substring(pos, match.index))); pos = match.index; } if (match.index == pos) { if (match[1]) { nodes.push(createNode("string", match[1])); nodes.push(createNode("sss")); } else if (match[2]) { nodes.push(createNode("string", match[2].replace("''", "'"))); } else { nodes.push(createNode(match[0])); } pos = tokenRE.lastIndex; } } if (pos < format.length) { nodes.push(createNode("string", format.substring(pos))); } // Build relationship between nodes var i; for (i = 0; i < nodes.length; i++) { nodes[i].next = nodes[i + 1] || null; nodes[i].prev = nodes[i - 1] || null; nodes[i].id = i; } return nodes; } function getInteger(str, pos) { str = str.substring(pos); var match = str.match(/^\d+/); return match && match[0]; } function getMatch(str, pos, pattern) { var i = 0, strQ = str.toUpperCase(), patternQ = pattern.toUpperCase(); while (strQ[pos + i] && strQ[pos + i] == patternQ[i]) { i++; } return str.substr(pos, i); } function getWeek(date) { var yearStart = new Date(date.getFullYear(), 0, 1); var weekStart = new Date(yearStart.getTime()); if (weekStart.getDay() > 4) { weekStart.setDate(weekStart.getDate() + (1 - weekStart.getDay()) + 7); } else { weekStart.setDate(weekStart.getDate() + (1 - weekStart.getDay())); } var diff = date.getTime() - weekStart.getTime(); return Math.floor(diff / (7 * 24 * 60 * 60 * 1000)); } function num2str(num, minLength, maxLength) { var i; num = "" + num; if (num.length > maxLength) { num = num.substr(num.length - maxLength); } else if (num.length < minLength) { for (i = num.length; i < minLength; i++) { num = "0" + num; } } return num; } function setText(node, date, token) { switch (token.name) { case "year": node.value = date.getFullYear(); break; case "month": node.value = date.getMonth() + 1; break; case "date": node.value = date.getDate(); break; case "day": node.value = date.getDay() || 7; break; case "hour": node.value = date.getHours(); break; case "hour12": node.value = date.getHours() % 12 || 12; break; case "ampm": node.value = date.getHours() < 12 ? 1 : 2; break; case "minute": node.value = date.getMinutes(); break; case "second": node.value = date.getSeconds(); break; case "millisecond": node.value = date.getMilliseconds(); break; case "week": node.value = getWeek(date); break; case "timezone": node.value = (date.getTimezoneOffset() > 0 ? "-" : "+") + num2str(Math.abs(date.getTimezoneOffset() / 60), 2, 2) + "00"; break; } if (node.value < 0) { node.value = 0; } switch (token.type) { case "number": node.viewValue = num2str(node.value, token.minLength, token.maxLength); break; case "select": node.viewValue = token.select[node.value - 1]; break; default: node.viewValue = node.value + ""; } } // set the proper date value matching the weekday function setDay(date, day) { // we don't want to change month when changing date var month = date.getMonth(), diff = day - (date.getDay() || 7); // move to correct date date.setDate(date.getDate() + diff); // check month if (date.getMonth() != month) { if (diff > 0) { date.setDate(date.getDate() - 7); } else { date.setDate(date.getDate() + 7); } } } function setHour12(date, hour) { hour = hour % 12; if (date.getHours() >= 12) { hour += 12; } date.setHours(hour); } function setAmpm(date, ampm) { var hour = date.getHours(); if ((hour < 12) == (ampm > 1)) { date.setHours((hour + 12) % 24); } } function setDate(date, value, token) { switch (token.name) { case "year": date.setFullYear(value); break; case "month": date.setMonth(value - 1); break; case "date": date.setDate(value); break; case "day": setDay(date, value); break; case "hour": date.setHours(value); break; case "hour12": setHour12(date, value); break; case "ampm": setAmpm(date, value); break; case "minute": date.setMinutes(value); break; case "second": date.setSeconds(value); break; case "millisecond": date.setMilliseconds(value); break; case "week": date.setDate(date.getDate() + (value - getWeek(date)) * 7); break; } if (date.getFullYear() < 0) { date.setFullYear(0); } } // Re-calculate offset function calcOffset(nodes) { var i, offset = 0; for (i = 0; i < nodes.length; i++) { nodes[i].offset = offset; offset += nodes[i].viewValue.length; } } function parseNode(node, text, pos) { var p = node, m, match, value, j; switch (p.token.type) { case "static": if (text.lastIndexOf(p.value, pos) != pos) { throw { code: "TEXT_MISMATCH", message: "Pattern value mismatch", text: text, node: p, pos: pos }; } break; case "number": // Fail when meeting .sss value = getInteger(text, pos); if (value == null) { throw { code: "NUMBER_MISMATCH", message: "Invalid number", text: text, node: p, pos: pos }; } if (value.length < p.token.minLength) { throw { code: "NUMBER_TOOSHORT", message: "The length of number is too short", text: text, node: p, pos: pos, match: value }; } if (value.length > p.token.maxLength) { value = value.substr(0, p.token.maxLength); } if (+value < p.token.min) { throw { code: "NUMBER_TOOSMALL", message: "The number is too small", text: text, node: p, pos: pos, match: value }; } if (value.length > p.token.minLength && value[0] == "0") { throw { code: "LEADING_ZERO", message: "The number has too many leading zero", text: text, node: p, pos: pos, match: value, properValue: num2str(+value, p.token.minLength, p.token.maxLength) }; } // if (+value > p.token.max) { // throw { // code: "NUMBER_TOOLARGE", // message: "The number is too large", // text: text, // node: p, // pos: pos, // match: value, // properValue: num2str(p.token.max, p.token.minLength, p.token.maxLength) p.value = +value; p.viewValue = value; break; case "select": match = ""; for (j = 0; j < p.token.select.length; j++) { m = getMatch(text, pos, p.token.select[j]); if (m && m.length > match.length) { value = j; match = m; } } if (!match) { throw { code: "SELECT_MISMATCH", message: "Invalid select", text: text, node: p, pos: pos }; } if (match != p.token.select[value]) { throw { code: "SELECT_INCOMPLETE", message: "Incomplete select", text: text, node: p, pos: pos, match: match, selected: p.token.select[value] }; } p.value = value + 1; p.viewValue = match; break; case "regex": m = p.regex.exec(text.substr(pos)); if (!m || m.index != 0) { throw { code: "REGEX_MISMATCH", message: "Regex doesn't match", text: text, node: p, pos: pos }; } p.value = m[0]; p.viewValue = m[0]; break; } } // Main parsing loop. Loop through nodes, parse text, update date model. function parseLoop(nodes, text, date) { var i, pos, errorBuff, baseDate, compareDate; pos = 0; baseDate = new Date(date.getTime()); for (i = 0; i < nodes.length; i++) { try { parseNode(nodes[i], text, pos); pos += nodes[i].viewValue.length; compareDate = new Date(baseDate.getTime()); setDate(compareDate, nodes[i].value, nodes[i].token); if (compareDate.getTime() != baseDate.getTime()) { setDate(date, nodes[i].value, nodes[i].token); } } catch (err) { if (err.code == "NUMBER_TOOSHORT" || err.code == "NUMBER_TOOSMALL" || err.code == "LEADING_ZERO") { errorBuff = err; pos += err.match.length; } else { throw err; } } } if (text.length > pos) { throw { code: "TEXT_TOOLONG", message: "Text is too long", text: text, pos: pos }; } if (errorBuff) { throw errorBuff; } } function createParser(format) { format = getFormat(format); var nodes = createNodes(format); var parser = { parse: function(text) { var oldDate = parser.date, date = new Date(oldDate.getTime()), oldText = parser.getText(), newText; if (!text) { throw { code: "EMPTY", message: "The input is empty", oldText: oldText }; } try { parseLoop(parser.nodes, text, date); parser.setDate(date); newText = parser.getText(); if (text != newText) { throw { code: "INCONSISTENT_INPUT", message: "Successfully parsed but the output text doesn't match the input", text: text, oldText: oldText, properText: newText }; } } catch (err) { // Should we reset date object if failed to parse? parser.setDate(oldDate); throw err; } return parser; }, parseNode: function(node, text) { var date = new Date(parser.date.getTime()); try { parseNode(node, text, 0); } catch (err) { parser.setDate(parser.date); throw err; } setDate(date, node.value, node.token); parser.setDate(date); return parser; }, setDate: function(date){ parser.date = date; var i, node; for (i = 0; i < parser.nodes.length; i++) { node = parser.nodes[i]; setText(node, date, node.token); } calcOffset(parser.nodes); return parser; }, getDate: function(){ return parser.date; }, getText: function(){ var i, text = ""; for (i = 0; i < parser.nodes.length; i++) { text += parser.nodes[i].viewValue; } return text; }, date: null, format: format, nodes: nodes, error: null }; parser.setDate(new Date()); return parser; } return createParser; }]); angular.module("datetime").directive("datetime", ["datetime", "$log", "$document", function(datetime, $log, $document){ var doc = $document[0]; function getInputSelectionIE(input) { var bookmark = doc.selection.createRange().getBookmark(); var range = input.createTextRange(); var range2 = range.duplicate(); range.moveToBookmark(bookmark); range2.setEndPoint("EndToStart", range); var start = range2.text.length; var end = start + range.text.length; return { start: start, end: end }; } function getInputSelection(input) { input = input[0]; if (input.selectionStart != undefined && input.selectionEnd != undefined) { return { start: input.selectionStart, end: input.selectionEnd }; } if (doc.selection) { return getInputSelectionIE(input); } } function getInitialNode(nodes) { return getNode(nodes[0]); } function setInputSelectionIE(input, range) { var select = input.createTextRange(); select.moveStart("character", range.start); select.collapse(); select.moveEnd("character", range.end - range.start); select.select(); } function setInputSelection(input, range) { input = input[0]; if (input.setSelectionRange) { input.setSelectionRange(range.start, range.end); } else if (input.createTextRange) { setInputSelectionIE(input, range); } } function getNode(node, direction) { if (!direction) { direction = "next"; } while (node && (node.token.type == "static" || node.token.type == "regex")) { node = node[direction]; } return node; } function addDate(date, token, diff) { switch (token.name) { case "year": date.setFullYear(date.getFullYear() + diff); break; case "month": date.setMonth(date.getMonth() + diff); break; case "date": case "day": date.setDate(date.getDate() + diff); break; case "hour": case "hour12": date.setHours(date.getHours() + diff); break; case "ampm": date.setHours(date.getHours() + diff * 12); break; case "minute": date.setMinutes(date.getMinutes() + diff); break; case "second": date.setSeconds(date.getSeconds() + diff); break; case "millisecond": date.setMilliseconds(date.getMilliseconds() + diff); break; case "week": date.setDate(date.getDate() + diff * 7); break; } } function getLastNode(node, direction) { var lastNode; do { lastNode = node; node = getNode(node[direction], direction); } while (node); return lastNode; } function selectRange(range, direction, toEnd) { if (!range.node) { return; } if (direction) { range.start = 0; range.end = "end"; if (toEnd) { range.node = getLastNode(range.node, direction); } else { range.node = getNode(range.node[direction], direction) || range.node; } } setInputSelection(range.element, { start: range.start + range.node.offset, end: range.end == "end" ? range.node.offset + range.node.viewValue.length : range.end + range.node.offset }); } function isStatic(node) { return node.token.type == "static" || node.token.type == "regex"; } function closerNode(range, next, prev) { var offset = range.node.offset + range.start, disNext = next.offset - offset, disPrev = offset - (prev.offset + prev.viewValue.length); return disNext <= disPrev ? next : prev; } function createRange(element, nodes) { var prev, next, range; range = getRange(element, nodes); if (isStatic(range.node)) { next = getNode(range.node, "next"); prev = getNode(range.node, "prev"); if (!next && !prev) { range.node = nodes[0]; range.end = 0; } else if (!next || !prev) { range.node = next || prev; } else { range.node = closerNode(range, next, prev); } } range.start = 0; range.end = "end"; return range; } function getRange(element, nodes, node) { var selection = getInputSelection(element), i, range; for (i = 0; i < nodes.length; i++) { if (!range && nodes[i].offset + nodes[i].viewValue.length >= selection.start || i == nodes.length - 1) { range = { element: element, node: nodes[i], start: selection.start - nodes[i].offset, end: selection.start - nodes[i].offset }; break; } } if (node && range.node.next == node && range.start + range.node.offset == range.node.next.offset) { range.node = range.node.next; range.start = range.end = 0; } return range; } function isRangeCollapse(range) { return range.start == range.end || range.start == range.node.viewValue.length && range.end == "end"; } function isRangeAtEnd(range) { var maxLength, length; if (!isRangeCollapse(range)) { return false; } maxLength = range.node.token.maxLength; length = range.node.viewValue.length; if (maxLength && length < maxLength) { return false; } return range.start == length; } function isPrintableKey(e) { var keyCode = e.charCode || e.keyCode; return keyCode >= 48 && keyCode <= 57 || keyCode >= 65 && keyCode <= 90 || keyCode >= 97 && keyCode <= 122; } function linkFunc(scope, element, attrs, ngModel) { var parser = datetime(attrs.datetime), modelParser = attrs.datetimeModel && datetime(attrs.datetimeModel), range = { element: element, node: getInitialNode(parser.nodes), start: 0, end: "end" }, errorRange = { element: element, node: null, start: 0, end: 0 }; var validMin = function(value) { return ngModel.$isEmpty(value) || angular.isUndefined(attrs.min) || value >= new Date(attrs.min); }; var validMax = function(value) { return ngModel.$isEmpty(value) || angular.isUndefined(attrs.max) || value <= new Date(attrs.max); }; if (ngModel.$validators) { ngModel.$validators.min = validMin; ngModel.$validators.max = validMax; } attrs.$observe("min", function(){ validMinMax(parser.getDate()); }); attrs.$observe("max", function(){ validMinMax(parser.getDate()); }); ngModel.$render = function(){ element.val(ngModel.$viewValue || ""); if (doc.activeElement == element[0]) { selectRange(range); } }; function validMinMax(date) { if (ngModel.$validate) { ngModel.$validate(); } else { ngModel.$setValidity("min", validMin(date)); ngModel.$setValidity("max", validMax(date)); } return !ngModel.$error.min && !ngModel.$error.max; } ngModel.$parsers.push(function(viewValue){ // Handle empty string if (!viewValue && angular.isUndefined(attrs.required)) { // Reset range range.node = getInitialNode(parser.nodes); range.start = 0; range.end = "end"; ngModel.$setValidity("datetime", true); return null; } try { parser.parse(viewValue); } catch (err) { $log.error(err); ngModel.$setValidity("datetime", false); if (err.code == "NUMBER_TOOSHORT" || err.code == "NUMBER_TOOSMALL" && err.match.length < err.node.token.maxLength) { errorRange.node = err.node; errorRange.start = 0; errorRange.end = err.match.length; } else { if (err.code == "LEADING_ZERO") { viewValue = viewValue.substr(0, err.pos) + err.properValue + viewValue.substr(err.pos + err.match.length); if (err.match.length >= err.node.token.maxLength) { selectRange(range, "next"); } else { range.start += err.properValue.length - err.match.length + 1; range.end = range.start; } } else if (err.code == "SELECT_INCOMPLETE") { parser.parseNode(range.node, err.selected); viewValue = parser.getText(); range.start = err.match.length; range.end = "end"; } else if (err.code == "INCONSISTENT_INPUT") { viewValue = err.properText; range.start++; range.end = range.start; // } else if (err.code == "NUMBER_TOOLARGE") { // viewValue = viewValue.substr(0, err.pos) + err.properValue + viewValue.substr(err.pos + err.match.length); // range.start = 0; // range.end = "end"; } else { viewValue = parser.getText(); range.start = 0; range.end = "end"; } scope.$evalAsync(function(){ if (viewValue == ngModel.$viewValue) { throw "angular-datetime crashed!"; } ngModel.$setViewValue(viewValue); ngModel.$render(); }); } return undefined; } ngModel.$setValidity("datetime", true); if (ngModel.$validate || validMinMax(parser.getDate())) { var date = parser.getDate(); if (angular.isDefined(attrs.datetimeUtc)) { date = new Date(date.getTime() + date.getTimezoneOffset() * 60 * 1000); } if (modelParser) { return modelParser.setDate(date).getText(); } else { // Create new date to make Angular notice the difference. return new Date(date.getTime()); } } return undefined; }); ngModel.$formatters.push(function(modelValue){ if (!modelValue) { ngModel.$setValidity("datetime", angular.isUndefined(attrs.required)); return ""; } ngModel.$setValidity("datetime", true); if (modelParser) { modelValue = modelParser.parse(modelValue).getDate(); } if (angular.isDefined(attrs.datetimeUtc)) { modelValue = new Date(modelValue.getTime() + modelValue.getTimezoneOffset() * 60 * 1000); } return parser.setDate(modelValue).getText(); }); function addNodeValue(node, diff) { var date, viewValue; date = new Date(parser.date.getTime()); addDate(date, node.token, diff); parser.setDate(date); viewValue = parser.getText(); ngModel.$setViewValue(viewValue); range.start = 0; range.end = "end"; ngModel.$render(); scope.$apply(); } var waitForClick; element.on("focus keydown keypress mousedown click", function(e){ switch (e.type) { case "mousedown": waitForClick = true; break; case "focus": e.preventDefault(); // Init value on focus if (!ngModel.$viewValue) { if (angular.isDefined(attrs["default"])) { parser.setDate(new Date(attrs["default"])); } ngModel.$setViewValue(parser.getText()); ngModel.$render(); scope.$apply(); } if (!waitForClick) { setTimeout(function(){ if (!ngModel.$error.datetime) { selectRange(range); } else { selectRange(errorRange); } }); } break; case "keydown": switch (e.keyCode) { case 37: // Left e.preventDefault(); if (!ngModel.$error.datetime) { selectRange(range, "prev"); } else { selectRange(errorRange); } break; case 39: // Right e.preventDefault(); if (!ngModel.$error.datetime) { selectRange(range, "next"); } else { selectRange(errorRange); } break; case 38: e.preventDefault(); addNodeValue(range.node, 1); break; case 40: // Down e.preventDefault(); addNodeValue(range.node, -1); break; case 36: // Home e.preventDefault(); if (ngModel.$error.datetime) { selectRange(errorRange); } else { selectRange(range, "prev", true); } break; case 35: // End e.preventDefault(); if (ngModel.$error.datetime) { selectRange(errorRange); } else { selectRange(range, "next", true); } break; } break; case "click": e.preventDefault(); waitForClick = false; if (!ngModel.$error.datetime) { range = createRange(element, parser.nodes); selectRange(range); } else { selectRange(errorRange); } break; case "keypress": if (isPrintableKey(e)) { setTimeout(function(){ range = getRange(element, parser.nodes, range.node); if (isRangeAtEnd(range)) { range.node = getNode(range.node.next) || range.node; range.start = 0; range.end = "end"; selectRange(range); } }); } break; } }); } return { restrict: "A", require: "?ngModel", link: linkFunc }; }]);
<? session_start(); //Funktionen $includeName="../../../_00_basic_func.inc.php"; if (file_exists($includeName)) { require($includeName); } else { echo '<br><br><div class="meldung_fehler"><img src="../../../BL_BILDER/Meldungen_Warning.png"> <br>FU_ALL_LOAD_01</div><br><br>'; exit(); } //Datenbank Verbindung $includeName="../../../_01_basic_db.inc.php"; if (file_exists($includeName)) { require($includeName); } else { echo '<br><br><div class="meldung_fehler"><img src="../../../BL_BILDER/Meldungen_Warning.png"> <br>DB_FU_LOAD_01</div><br><br>'; exit(); } //Sessions $includeName="../../../_01_basic_sess.inc.php"; if (file_exists($includeName)) { require($includeName); } else { echo '<br><br><div class="meldung_fehler"><img src="../../../BL_BILDER/Meldungen_Warning.png"> <br>SESS_FU_LOAD_01</div><br><br>'; exit(); } if (isset($_SESSION["User_ID"]) && $_SESSION["User_Recht_Admin"]=="1" && isset($_GET['e']) && $_GET['e']!="") { $teile = explode("|", $_GET['e']); for ($i=0;$i<count($teile);$i++) { $sql2 = "SELECT von FROM `06_wkObje` WHERE `geraet` = \"".<API key>(unserialize(base64_decode($teile[$i])))."\" "; $objImVerleih = mysql_query($sql2); $Zeilen = mysql_num_rows($objImVerleih); unset($objImVerleih); $nameObj=utf8_encode(klarNameObj(unserialize(base64_decode($teile[$i])))); if ($Zeilen=="0") { $sql = "DELETE FROM `04_obj_objekte` WHERE `specid_obj` = \"".<API key>(unserialize(base64_decode($teile[$i])))."\" LIMIT 1"; $loeschOkay = mysql_query($sql); $erfolgOrNot=mysql_affected_rows(); if (is_file('../../../BL_MEDIA/PDF_OBJ/'.strip_tags(htmlspecialchars($teile[$i])).'.pdf')) { unlink('../../../BL_MEDIA/PDF_OBJ/'.strip_tags(htmlspecialchars($teile[$i])).'.pdf'); } if (is_file('../../../BL_MEDIA/PIC_OBJ/'.strip_tags(htmlspecialchars($teile[$i])).'.jpg')) { unlink('../../../BL_MEDIA/PIC_OBJ/'.strip_tags(htmlspecialchars($teile[$i])).'.jpg'); } if ($erfolgOrNot=="1") { ?> <script> $.pnotify({ pnotify_title: 'Löschen des Objektes <? echo $nameObj; ?>', pnotify_text: 'Das Objekt wurde erfolgreich gelöscht.', }); $("input[value='<? echo strip_tags($teile[$i]); ?>']").closest("tr").remove(); </script> <? } else { ?> <script> $.pnotify({ pnotify_title: 'Löschen des Objektes <? echo $nameObj ?>', pnotify_text: 'Das Objekt wurde wegen einem Übertragungsfehler nicht gelöscht.', pnotify_type: 'error', }); </script> <? } } else { //hauptgruppe ist noch objekt zugeordnet oder in leihe ?> <script> $.pnotify({ pnotify_title: 'Löschen des Objektes <? echo $nameObj ?>', pnotify_text: 'Das Objekt wurde nicht gelöscht, da mind. 1 Reservierung vorliegt.', pnotify_type: 'error', }); $("input[value='<? echo strip_tags($teile[$i]); ?>']").closest("td").animate({ backgroundColor: "#FF0000" }, 1900); //css("border","3px solid red") </script> <? } } } ?>
.options { border: 1px solid #aaa; border-radius: 5px; background-color: #eee; padding: 0 3px; } #grid { height: 300px; font-size: 8pt; } #grid-info { font-size: 9pt; } #grid .slick-row { font-size: 8pt; } #grid .slick-row:hover { font-weight: normal } .template { display: none; } .conditions { border: 1px solid #aaa; border-radius: 5px; padding: 0 3px; } .view { float: right; } .del-condition { float: right; } .init-select {margin-left: 15px; } .init-select span {font-size: smaller; }
package net.havox.times.model.factory; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.BeforeClass; import org.junit.Test; import net.havox.times.model.api.booking.Account; import net.havox.times.model.api.booking.Booking; import net.havox.times.model.api.booking.BookingReference; import net.havox.times.model.api.booking.<API key>; import net.havox.times.model.api.booking.BookingType; import net.havox.times.model.api.booking.Project; import net.havox.times.model.impl.booking.AccountImpl; import net.havox.times.model.impl.booking.BookingImpl; import net.havox.times.model.impl.booking.<API key>; import net.havox.times.model.impl.booking.<API key>; import net.havox.times.model.impl.booking.BookingTypeImpl; import net.havox.times.model.impl.booking.ProjectImpl; /** * Factory test of {@link BookingModelFactory}. * * @author Christian Otto */ public class <API key> { private static BookingModelFactory factory; @BeforeClass public static void setupClass() { factory = BookingModelFactory.getInstance(); } @Test public void testGetInstance() { Object instanceUnderTest = BookingModelFactory.getInstance(); // Is the instance initialized? assertThat( instanceUnderTest, is( notNullValue() ) ); // Is the instance of the correct type? assertThat( instanceUnderTest, is( instanceOf( BookingModelFactory.class ) ) ); } @Test public void testGetNewAccount() { Account instanceUnderTest = factory.getNewAccount(); // Is the instance initialized? assertThat( instanceUnderTest, is( notNullValue() ) ); // Is the instance of the correct type? assertThat( instanceUnderTest, is( instanceOf( AccountImpl.class ) ) ); } @Test public void testGetNewBooking() { Booking instanceUnderTest = factory.getNewBooking(); // Is the instance initialized? assertThat( instanceUnderTest, is( notNullValue() ) ); // Is the instance of the correct type? assertThat( instanceUnderTest, is( instanceOf( BookingImpl.class ) ) ); } @Test public void <API key>() { BookingReference instanceUnderTest = factory.<API key>(); // Is the instance initialized? assertThat( instanceUnderTest, is( notNullValue() ) ); // Is the instance of the correct type? assertThat( instanceUnderTest, is( instanceOf( <API key>.class ) ) ); } @Test public void <API key>() { <API key> instanceUnderTest = factory.<API key>(); // Is the instance initialized? assertThat( instanceUnderTest, is( notNullValue() ) ); // Is the instance of the correct type? assertThat( instanceUnderTest, is( instanceOf( <API key>.class ) ) ); } @Test public void <API key>() { BookingType instanceUnderTest = factory.getNewBookingType(); // Is the instance initialized? assertThat( instanceUnderTest, is( notNullValue() ) ); // Is the instance of the correct type? assertThat( instanceUnderTest, is( instanceOf( BookingTypeImpl.class ) ) ); } @Test public void testGetNewProject() { Project instanceUnderTest = factory.getNewProject(); // Is the instance initialized? assertThat( instanceUnderTest, is( notNullValue() ) ); // Is the instance of the correct type? assertThat( instanceUnderTest, is( instanceOf( ProjectImpl.class ) ) ); } }
<?php // src/res/core/Admin/Administration.php namespace Admin; class Administration { public static function printStatus($status) { $bgColor = ''; $msg = ''; if(isset($status['success'])) { $bgColor = 'green'; $msg = $status['success']; } else if(isset($status['error'])) { $bgColor = 'red'; $msg = $status['error']; } else if(isset($status['warning'])) { $bgColor = 'orange'; $msg = $status['warning']; } ?><p class="info inline <?= $bgColor ?>"><?= $msg ?></p><?php // Fail UTF-8 by urldecode() } public static function arrayToArgs($args) { $url = ''; foreach($args as $key => $value) $url .= $key.'='.$value.'&'; return $url; } }
//Exports the repo from the database const REPO=require("./create.js"); function generate(out,conf,cb) { const tmp="/tmp/osl_image_server.repo."+uuid(); const outtmp=pth.join(out,"tmp"); const self=this; newLogger("repo",self); const repo=new REPO(tmp,outtmp,conf); self.repo=repo; var sys=[]; self.info({tmp:tmp,out:out},"Generating Repo"); self.debug("Exporting..."); System.find({},function(e,r) { if (e) return cb(e); w(r,function(os2,sysCB) { var os={ id:os2._id, name:os2.name, desc:os2.desc, icon:os2.icon, theme:os2.theme, type:os2.type, channels:[] } self.trace("sys",os.name); sys.push(os.id); self.trace("Channels for "+os.name+" ..."); Channel.find({for:os.id},function(e,r) { if (e) return sysCB(e); new w(r,function(ch2,chCB) { var ch={ id:ch2._id, for:os.id, name:ch2.name, desc:ch2.desc, beta:ch2.beta, stable:ch2.stable, hooks:ch2.hooks, releases:[] } self.trace("ch",ch.name); os.channels.push(ch.id); self.trace("Releases for "+os.name+" ..."); Release.find({for:ch.id},function(e,r) { if (e) return chCB(e); new w(r,function(rel2,relCB) { var rel={ for:ch.id, date:rel2.date, name:rel2.name, version:rel2.version, codename:rel2.codename, files:rel2.files, upgrade:rel2.upgradeNext?rel2.upgradeNext:rel2.upgradeTo, hooks:rel2.hooks } self.trace("rel",rel.name); ch.releases.push(rel); relCB(); })(function(e) { self.trace("add ch",ch.id); repo.addFile(os.id+"/"+ch.id+".json",ch); chCB(e); }); }); })(function(e) { self.trace("add os",os.id); repo.addFile(os.id+".json",os); sysCB(e); }); }); })(function(e) { if (e) return cb(e); repo.addFile("main.json",{ name:conf.about.name, desc:conf.about.desc, os:sys, maintainer:conf.about.maintainer, icon:conf.about.icon||null, // TODO: add icon config sources:null // TODO: alternative sources }); plugins.hook("repo.files",repo,function() { try { self.info("Generating final repo.tar.gz"); repo.generate(function(e,p) { if (e) return cb(e); hashFile("sha256",p,function(e,h) { if (e) return cb(e); fs.writeFile(p.replace(".tar.gz",".sha256"),h,function(e) { if (e) return cb(e); new w(["repo.tar.gz","repo.sha256"],function(p,cb) { fs.rename(pth.join(outtmp,p),pth.join(out,p),cb); })(function(e) { cb(e,p); }); }); }); }); } catch(e) { return cb(e); } }) }); }); } module.exports=generate;
module.exports = { isEmpty, nonEmpty } /** * @param {string | null | undefined} string * @return {boolean} */ function isEmpty(string) { return string === undefined || string === null || string === '' } /** * @param {string | null | undefined} string * @return {boolean} */ function nonEmpty(string) { return !isEmpty(string) }
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("Shell.Common.Shares")] [assembly: AssemblyDescription ("")] [assembly: <API key> ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("tobias")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
#ifndef MAINPROCESS_H #define MAINPROCESS_H #include "rf_process.h" #include <rf_background.h> #include <rf_declares.h> #include <rf_primitive.h> #include <rf_soundmanager.h> #include <SDL2/SDL_ttf.h> #include "execontrol.h" class mainProcess : public RF_Process { public: mainProcess():RF_Process("mainProcess"){} virtual ~mainProcess(){} virtual void Start() { //la tecla esc; RF_Engine::instance->newTask(new exeControl(),id); //Levantamos el proceso que controla el fondo RF_Engine::instance->newTask(new RF_Background(),id); //Inicializamos el fondo RF_Background::instance->prepareSurface(); return; } virtual void Update(){} int& state(){return stateMachine;} private: int stateMachine = 0; int scene; void breik(RF_Process* escena){} }; #endif // MAINPROCESS_H
<?php /* *This should read json objects stored in */ $start = microtime(true); $working_dir = 'working/json-xml-cdr'; $hosts = ['alison.athnex.com:9200']; $esIndex = 'call_records.stage'; $esType = 'cdr'; $verbose = 1; $esTotalCnt = 0; $esTotalFail = 0; require 'vendor/autoload.php'; require 'esHandler.php'; $statHdlr = new esInsertStats(); $client = Elasticsearch\ClientBuilder::create()->setHosts($hosts)->build(); if (!is_dir($working_dir)){ echo "Unable to locate $working_dir as a valid working dir.\n"; exit; } // Lets start the directory read loop. $dh = opendir($working_dir); while ($entry = readdir($dh)) { if(is_dir($entry)){ continue; } if($entry == '.' OR $entry == '..'){ continue; } $json_contents = file_get_contents($working_dir.'/'.$entry); $uuid = str_replace('.cdr.json','',$entry); $params = [ 'index' => $esIndex, 'type' => $esType, 'id' => $uuid, 'body' => $json_contents ]; echo "Inserting $entry into elasticsearch\n"; $response = $client->index($params); if ($response['result'] == 'updated' OR $response['result'] == 'created') { if ($verbose != 0) { echo "Done with $uuid!\n Entry version [". $response['_version']."]\n"; echo "Deleting file ". $working_dir.'/'.$entry ."\n"; // Kidding, not actually doing this. } // unlink ($working_dir.'/'.$entry); // maybe I wasnt. if($response['result'] == 'created') $statHdlr->increment('1'); else $statHdlr->increment($response['_version']); echo "gpt ". $response['_version'] ." gpt\n"; $esTotalCnt++; } else { $esTotalFail++; $statHdlr->increment('error'); echo "Error processing ". $working_dir.'/'.$entry ."\n"; } continue; } $arrayDump = $statHdlr->getKeyList(); //var_dump($arrayDump); foreach ( $arrayDump as $key => $keyval ){ $keyavg = $statHdlr->getAverage($key); echo "For $key I got an Average of $keyavg from $keyval.\n"; } echo "Total inserted is ". $esTotalCnt ." and total Failures is ". $esTotalFail ."\n"; $timeElapsed = (microtime(true) - $start) / 60; $accurateTime = microtime(true) - $start; echo "Total time taken $timeElapsed ( $accurateTime ) seconds.\n"; //$out = $statHdlr->debugDump(); //echo $out; ?>
#!/usr/bin/env python3 """Geometric Object Class""" class GeometricObject: def __init__(self, color="green", filled=True): self.__color = color self.__filled = filled def get_color(self): return self.__color def set_color(self, color): self.__color = color def is_filled(self): return self.__filled def set_filled(self, filled): self.__filled = filled def __str__(self): return "color: " + self.__color + \ " and filled: " + str(self.__filled)
// Marie invented a Time Machine and wants to test it by time-traveling to visit Russia on the Day of the Programmer (the 256th day of the year) during a year in the inclusive range from 1700 to 2700. // From 1700 to 1917, Russia's official calendar was the Julian calendar; since 1919 they used the Gregorian calendar system. The transition from the Julian to Gregorian calendar system occurred in 1918, when the next day after January 31st was February 14th. This means that in 1918, February 14th was the 32nd day of the year in Russia. // In both calendar systems, February is the only month with a variable amount of days; it has 29 days during a leap year, and 28 days during all other years. In the Julian calendar, leap years are divisible by 4; in the Gregorian calendar, leap years are either of the following: // Divisible by 400. // Divisible by 4 and not divisible by 100. // Given a year, y, find the date of the 256th day of that year according to the official Russian calendar during that year. Then print it in the format dd.mm.yyyy, where dd is the two-digit day, mm is the two-digit month, and yyyy is y. // Input Format // A single integer denoting year y. // Constraints // 1700 <= y <= 2700 // Output Format // Print the full date of Day of the Programmer during year in the format dd.mm.yyyy, where dd is the two-digit day, mm is the two-digit month, and yyyy is y. // Sample Input 0 // 2017 // Sample Output 0 // 13.09.2017 // Explanation 0 // In the year y = 2017, January has 31 days, February has 28 days, March has 31 days, April has 30 days, May has 31 days, June has 30 days, July has 31 days, and August has 31 days. When we sum the total number of days in the first eight months, we get 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 = 243. Day of the Programmer is the 256th day, so then calculate 256 - 243 = 13 to determine that it falls on day 13 of the 9th month (September). We then print the full date in the specified format, which is 13.09.2017. // Sample Input 1 // 2016 // Sample Output 1 // 12.09.2016 // Explanation 1 // Year y = 2016 is a leap year, so February has 29 days but all the other months have the same number of days as in 2017. When we sum the total number of days in the first eight months, we get 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 = 244. Day of the Programmer is the 256th day, so then calculate 256 - 244 = 12 to determine that it falls on day 12 of the 9th month (September). We then print the full date in the specified format, which is 12.09.2016. #include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <limits.h> #include <stdbool.h> char* solve(int year){ // Complete this function char* s = (char *)malloc(sizeof(char) * 11); if(year < 1918 && year >= 1700){ // Julian Calendar // leap years are divisible by 4 if(year % 4 == 0){ // Leap Year // Answer is : 12th September sprintf(s, "12.09.%d", year); } else { // Non-Leap Year // Answer is : 13th September sprintf(s, "13.09.%d", year); } } else if(year > 1918 && year <= 2700){ // Gregorian Calendar // leap years are : divisible by 400 and divisible by 4 and not by 100 if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)){ // Leap Year // Answer is : 12th September sprintf(s, "12.09.%d", year); } else { // Non-Leap Year // Answer is : 13th September sprintf(s, "13.09.%d", year); } } else{ // Transition Year sprintf(s, "26.09.%d", year); } return s; } int main() { int year; scanf("%d", &year); int result_size; char* result = solve(year); printf("%s\n", result); return 0; }
{ (c) 2008-2009 Markus Dittrich This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License Version 3 as published by the Free Software Foundation. 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 Version 3 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. -- | routines called from the toplevel readline instance without -- before any parsing is done, aka info routines of any sort and -- shape module InfoRoutines ( confirm_and_exit , list_functions , list_variables , show_time ) where -- imports import Data.List import Data.Map import Data.Time import Prelude import System.IO import System.Locale -- local imports import CalculatorState -- | list all currently defined variables list_variables :: CalcState -> IO () list_variables (CalcState {varMap = theMap}) = mapM_ print_variable (assocs theMap) where print_variable (x,y) = putStrLn (x ++ " == " ++ (show y)) -- | list all currently defined functions list_functions :: CalcState -> IO () list_functions (CalcState {funcMap = theMap} ) = mapM_ print_function (assocs theMap) where print_function ( x , (Function { f_vars = vars , f_expression = expr } ) ) = putStrLn (x ++ "(" ++ intercalate [','] vars ++ ") = " ++ expr) -- | display the current localtime show_time :: IO () show_time = getCurrentTime >>= \utcTime -> getTimeZone utcTime >>= \zone -> let localTime = utcToLocalTime zone utcTime timeString = formatTime defaultTimeLocale "%a %b %d %Y <> %T %Z " localTime in putStrLn timeString -- | ask user for confirmation before exiting confirm_and_exit :: IO Bool confirm_and_exit = putStr "Really quit (y/n)? " >> hFlush stdout >> getLine >>= \answer -> case answer of "y" -> return True "n" -> return False _ -> confirm_and_exit
using System.IO; using System.Runtime.Serialization; using WolvenKit.CR2W.Reflection; using FastMember; using static WolvenKit.CR2W.Types.Enums; namespace WolvenKit.CR2W.Types { [DataContract(Namespace = "")] [REDMeta] public partial class CFXTrackItem : CFXBase { [Ordinal(1)] [RED("timeBegin")] public CFloat TimeBegin { get; set;} [Ordinal(2)] [RED("timeDuration")] public CFloat TimeDuration { get; set;} public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CFXTrackItem(cr2w, parent, name); } }
#include "uart.h" #include "ring_buffer.h" #include <stdint.h> #include <stddef.h> #include <msp430.h> #include <msp430g2553.h> #define DE BIT3 // Pin P1.3 #define RE BIT4 // Pin P1.4 #define RECEIVER() (P1OUT &= ~(RE | DE)) #define TRANSMITTER() (P1OUT |= (RE | DE)) struct baud_value { uint32_t baud; uint16_t UCAxBR0; uint16_t UCAxBR1; uint16_t UCAxMCTL; }; /* Table of baud rate register values from reference manual (SLAU144) */ static const struct baud_value _baud_tbl[] = { {9600, 104, 0, UCBRS_1}, {19200, 52, 0, UCBRS_0}, {38400, 26, 0, UCBRS_0}, {56000, 17, 0, UCBRS_7}, {115200, 8, 0, UCBRS_6} }; /* RX ring bufer */ static rbd_t _rbd; static char _rbmem[32]; /** * \brief Initialize the UART peripheral * \param[in] config - the UART configuration * \return 0 on success, -1 otherwise */ int uart_init(uart_config_t *config) { int status = -1; RECEIVER(); /* USCI should be in reset before configuring - only configure once */ if (UCA0CTL1 & UCSWRST) { size_t i; /* Set clock source to SMCLK */ UCA0CTL1 |= UCSSEL_2; /* Find the settings from the baud rate table */ for (i = 0; i < ARRAY_SIZE(_baud_tbl); i++) { if (_baud_tbl[i].baud == config->baud) { break; } } if (i < ARRAY_SIZE(_baud_tbl)) { rb_attr_t attr = {sizeof(_rbmem[0]), ARRAY_SIZE(_rbmem), _rbmem}; /* Set the baud rate */ UCA0BR0 = _baud_tbl[i].UCAxBR0; UCA0BR1 = _baud_tbl[i].UCAxBR1; UCA0MCTL = _baud_tbl[i].UCAxMCTL; /* Initialize the ring buffer */ if (ring_buffer_init(&_rbd, &attr) == 0) { /* Enable the USCI peripheral (take it out of reset) */ UCA0CTL1 &= ~UCSWRST; /* Enable rx interrupts */ IE2 |= UCA0RXIE; status = 0; } } } return status; } /** * \brief Read a character from UART * \return the character read on success, -1 if nothing was read */ char uart_getchar(void) { char c = -1; if (ring_buffer_get(_rbd, &c) == 0) { return c; } return c; } /** * \brief Write a character to UART * \param[in] c - the character to write * \return 0 on sucess, -1 otherwise */ int uart_putchar(char c) { TRANSMITTER(); /* Wait for the transmit buffer to be ready */ while (!(IFG2 & UCA0TXIFG)); /* Transmit data */ UCA0TXBUF = c; while (UCA0STAT & UCBUSY); //Transmit operation in progress RECEIVER(); return 0; } /** * \brief Write a string to UART * \return 0 on sucesss, -1 otherwise */ int uart_puts(const char *str) { int status = -1; TRANSMITTER(); if (str != NULL) { status = 0; while (*str != '\0') { /* Wait for the transmit buffer to be ready */ while (!(IFG2 & UCA0TXIFG)); /* Transmit data */ UCA0TXBUF = *str; /* If there is a line-feed, add a carriage return */ if (*str == '\n') { /* Wait for the transmit buffer to be ready */ while (!(IFG2 & UCA0TXIFG)); UCA0TXBUF = '\r'; } str++; } } RECEIVER(); return status; } int uart_putArray(const char *vetor, int arraySize) { int status = -1; int i; TRANSMITTER(); //Enable ransmission if (vetor != NULL) { status = 0; for(i = 0; i < arraySize; i++) { UCA0TXBUF = vetor[i]; //Send byte while (UCA0STAT & UCBUSY); //Wait transmission is matched } } RECEIVER(); //Enable reception return status; } #pragma vector=USCIAB0RX_VECTOR __interrupt void USCI0RX_ISR(void){ if (IFG2 & UCA0RXIFG) { const char c = UCA0RXBUF; //Clear the interrupt flag IFG2 &= ~UCA0RXIFG; P1OUT ^= 0x40; ring_buffer_put(_rbd, &c); } }
<?php class Race_CategoryModel extends Model_Abstract { public function getCategories() { $query = "SELECT * FROM race_category"; $stmt = Database::prepare($query); $stmt->execute(); $data = $stmt->fetchAll(); if(count($data) > 0){ foreach($data as $i => $item) { $query = "SELECT group_concat(group_name) as groups FROM race_group WHERE id IN (" . $item['group_ids'] . ")"; $stmt = Database::prepare($query); $stmt->execute(); $group = $stmt->fetch(); $data[$i]['groups'] = $group['groups']; } return $data; } } public function load($id) { $query = "SELECT * FROM race_category WHERE id = :id"; $stmt = Database::prepare($query); $stmt->bindParam(':id', $id); $stmt->execute(); $result = $stmt->fetch(); if ($result['id']>0) { return $result; } else { return FALSE; } } }
/** * Config file mimicking DiddiZ's Config class file in LB. Tailored for this * plugin. * * @author Mitsugaru */ package com.mitsugaru.KarmicShare.config; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import org.bukkit.configuration.<API key>; import org.bukkit.configuration.file.YamlConfiguration; import com.mitsugaru.KarmicShare.KarmicShare; public class RootConfig { // Class variables private static KarmicShare plugin; private static final EnumMap<ConfigNode, Object> OPTIONS = new EnumMap<ConfigNode, Object>( ConfigNode.class); // TODO ability to change config in-game // IDEA Ability to change the colors for all parameters // such as item name, amount, data value, id value, enchantment name, // enchantment lvl, page numbers, maybe even header titles /** * Constructor and initializer * * @param KarmicShare * plugin */ public static void init(KarmicShare ks) { plugin = ks; // Grab config final <API key> config = ks.getConfig(); // Insert defaults into config file if they're not present for (ConfigNode node : ConfigNode.values()) { if (!config.contains(node.getPath())) { config.set(node.getPath(), node.getDefaultValue()); } } // Save config ks.saveConfig(); /** * Database info */ updateOption(ConfigNode.MYSQL_USE); updateOption(ConfigNode.MYSQL_HOST); updateOption(ConfigNode.MYSQL_PORT); updateOption(ConfigNode.MYSQL_DATABASE); updateOption(ConfigNode.MYSQL_USER); updateOption(ConfigNode.MYSQL_PASSWORD); updateOption(ConfigNode.MYSQL_TABLE_PREFIX); updateOption(ConfigNode.MYSQL_IMPORT); updateOption(ConfigNode.VERSION); // reload to load other settings reload(); } @SuppressWarnings("unchecked") public static void updateOption(ConfigNode node) { final <API key> config = plugin.getConfig(); switch (node.getVarType()) { case LIST: { List<String> list = config.getStringList(node.getPath()); if (list == null) { list = (List<String>) node.getDefaultValue(); } OPTIONS.put(node, list); break; } case DOUBLE: { OPTIONS.put( node, config.getDouble(node.getPath(), (Double) node.getDefaultValue())); break; } case STRING: { OPTIONS.put( node, config.getString(node.getPath(), (String) node.getDefaultValue())); break; } case INTEGER: { OPTIONS.put( node, config.getInt(node.getPath(), (Integer) node.getDefaultValue())); break; } case BOOLEAN: { OPTIONS.put( node, config.getBoolean(node.getPath(), (Boolean) node.getDefaultValue())); break; } default: { OPTIONS.put(node, config.get(node.getPath(), node.getDefaultValue())); } } } public static void set(ConfigNode node, Object o) { set(node.getPath(), o); } public static void set(String path, Object o) { final <API key> config = plugin.getConfig(); config.set(path, o); plugin.saveConfig(); } public static int getInt(ConfigNode node) { int i = -1; switch (node.getVarType()) { case INTEGER: { try { i = ((Integer) OPTIONS.get(node)).intValue(); } catch (<API key> npe) { i = ((Integer) node.getDefaultValue()).intValue(); } break; } default: { // TODO throw exception break; } } return i; } public static String getString(ConfigNode node) { String out = ""; switch (node.getVarType()) { case STRING: { out = (String) OPTIONS.get(node); if (out == null) { out = (String) node.getDefaultValue(); } break; } default: { // TODO throw exception break; } } return out; } @SuppressWarnings("unchecked") public static List<String> getStringList(ConfigNode node) { List<String> list = new ArrayList<String>(); switch (node.getVarType()) { case LIST: { final <API key> config = plugin.getConfig(); list = config.getStringList(node.getPath()); if (list == null) { list = (List<String>) node.getDefaultValue(); } break; } default: { // TODO throw exception break; } } return list; } public static double getDouble(ConfigNode node) { double d = 0.0; switch (node.getVarType()) { case DOUBLE: { try { d = ((Double) OPTIONS.get(node)).doubleValue(); } catch (<API key> npe) { d = ((Double) node.getDefaultValue()).doubleValue(); } break; } default: { // TODO throw exception break; } } return d; } public static boolean getBoolean(ConfigNode node) { boolean b = false; switch (node.getVarType()) { case BOOLEAN: { b = ((Boolean) OPTIONS.get(node)).booleanValue(); break; } default: { // TODO throw exception break; } } return b; } @SuppressWarnings("unused") private static void loadBlacklist() { // final YamlConfiguration blacklistFile = blacklistFile(); // Load info into set // TODO test // final List<String> list = (List<String>) // blacklistFile.getList("blacklist", new ArrayList<String>()); } /** * Reloads info from yaml file(s) */ public static void reload() { // Initial relaod plugin.reloadConfig(); // Grab config loadSettings(plugin.getConfig()); // Load config for item specific karma if not using static karma if (!getBoolean(ConfigNode.KARMA_STATIC) && !getBoolean(ConfigNode.KARMA_DISABLED)) { // Reload karma config KarmaConfig.reload(); } // TODO // if (blacklist) { // this.loadBlacklist(); // Check bounds boundsCheck(); } private static void loadSettings(<API key> config) { updateOption(ConfigNode.CHESTS); updateOption(ConfigNode.DISABLED_WORLDS); updateOption(ConfigNode.EFFECTS); updateOption(ConfigNode.LIST_LIMIT); updateOption(ConfigNode.KARMA_DISABLED); updateOption(ConfigNode.KARMA_STATIC); updateOption(ConfigNode.KARMA_UPPER_LIMIT); updateOption(ConfigNode.KARMA_UPPER_PERCENT); updateOption(ConfigNode.KARMA_LOWER_LIMIT); updateOption(ConfigNode.KARMA_LOWER_PERCENT); updateOption(ConfigNode.<API key>); updateOption(ConfigNode.KARMA_CHANGE_GIVE); updateOption(ConfigNode.KARMA_CHANGE_TAKE); updateOption(ConfigNode.KARMA_ECONOMY); updateOption(ConfigNode.<API key>); updateOption(ConfigNode.DEBUG_TIME); updateOption(ConfigNode.DEBUG_DATABASE); updateOption(ConfigNode.DEBUG_INVENTORY); updateOption(ConfigNode.DEBUG_KARMA); updateOption(ConfigNode.DEBUG_ITEM); updateOption(ConfigNode.DEBUG_CONFIG); updateOption(ConfigNode.DEBUG_ECONOMY); } private static void boundsCheck() { // Check upper and lower limits if (getInt(ConfigNode.KARMA_UPPER_LIMIT) < getInt(ConfigNode.KARMA_LOWER_LIMIT)) { OPTIONS.put(ConfigNode.KARMA_UPPER_LIMIT, ConfigNode.KARMA_UPPER_LIMIT.getDefaultValue()); OPTIONS.put(ConfigNode.KARMA_LOWER_LIMIT, ConfigNode.KARMA_LOWER_LIMIT.getDefaultValue()); plugin.getLogger() .warning( "Upper limit is smaller than lower limit. Reverting to defaults."); } // Check that we don't go beyond what the database can handle, via // smallint else if (Math.abs(getInt(ConfigNode.KARMA_UPPER_LIMIT)) >= 30000 || Math.abs(getInt(ConfigNode.KARMA_LOWER_LIMIT)) >= 30000) { OPTIONS.put(ConfigNode.KARMA_UPPER_LIMIT, ConfigNode.KARMA_UPPER_LIMIT.getDefaultValue()); OPTIONS.put(ConfigNode.KARMA_LOWER_LIMIT, ConfigNode.KARMA_LOWER_LIMIT.getDefaultValue()); plugin.getLogger() .warning( "Upper/lower limit is beyond bounds. Reverting to defaults."); } // Check percentages if (getDouble(ConfigNode.KARMA_UPPER_PERCENT) < getDouble(ConfigNode.KARMA_LOWER_PERCENT)) { OPTIONS.put(ConfigNode.KARMA_UPPER_PERCENT, ConfigNode.KARMA_UPPER_PERCENT.getDefaultValue()); OPTIONS.put(ConfigNode.KARMA_LOWER_PERCENT, ConfigNode.KARMA_LOWER_PERCENT.getDefaultValue()); plugin.getLogger() .warning( "Upper %-age is smaller than lower %-age. Reverting to defaults."); } else if (getDouble(ConfigNode.KARMA_UPPER_PERCENT) > 1.0 || getDouble(ConfigNode.KARMA_LOWER_PERCENT) < 0) { OPTIONS.put(ConfigNode.KARMA_UPPER_PERCENT, ConfigNode.KARMA_UPPER_PERCENT.getDefaultValue()); OPTIONS.put(ConfigNode.KARMA_LOWER_PERCENT, ConfigNode.KARMA_LOWER_PERCENT.getDefaultValue()); plugin.getLogger() .warning( "Upper %-age and/or lower %-age are beyond bounds. Reverting to defaults."); } // Check that the default karma is actually in range. if (getInt(ConfigNode.<API key>) < getInt(ConfigNode.KARMA_LOWER_LIMIT) || getInt(ConfigNode.<API key>) > getInt(ConfigNode.KARMA_UPPER_LIMIT)) { // Average out valid bounds to create valid default OPTIONS.put( ConfigNode.<API key>, getInt(ConfigNode.KARMA_UPPER_LIMIT) - ((getInt(ConfigNode.KARMA_LOWER_LIMIT) + getInt(ConfigNode.KARMA_UPPER_LIMIT)) / 2)); plugin.getLogger() .warning( "Player karma default is out of range. Using average of the two."); } // Check that default karma change is not negative. if (getDouble(ConfigNode.KARMA_CHANGE_GIVE) < 0) { OPTIONS.put(ConfigNode.KARMA_CHANGE_GIVE, ConfigNode.KARMA_CHANGE_GIVE.getDefaultValue()); plugin.getLogger().warning( "Default give karma rate is negative. Using default."); } // Check that default karma change is not negative. if (getDouble(ConfigNode.KARMA_CHANGE_TAKE) < 0) { OPTIONS.put(ConfigNode.KARMA_CHANGE_TAKE, ConfigNode.KARMA_CHANGE_TAKE.getDefaultValue()); plugin.getLogger().warning( "Default take karma rate is negative. Using default."); } // Check that list is actually going to output something, based on limit // given if (getInt(ConfigNode.LIST_LIMIT) < 1) { OPTIONS.put(ConfigNode.LIST_LIMIT, ConfigNode.LIST_LIMIT.getDefaultValue()); plugin.getLogger().warning( "List limit is lower than 1. Using default."); } } @SuppressWarnings("unused") private static YamlConfiguration blacklistFile() { final File file = new File(plugin.getDataFolder().getAbsolutePath() + "/blacklist.yml"); final YamlConfiguration blacklistFile = YamlConfiguration .loadConfiguration(file); if (!file.exists()) { try { // Save the file blacklistFile.save(file); } catch (IOException e1) { plugin.getLogger().warning( "File I/O Exception on saving blacklist"); e1.printStackTrace(); } } return blacklistFile; } }
// -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*- // This program is free software; you can redistribute it and/or modify // the Free Software Foundation version 2. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #include "led-matrix.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #include <grp.h> #include <pwd.h> #include <vector> namespace rgb_matrix { RuntimeOptions::RuntimeOptions() : #ifdef RGB_SLOWDOWN_GPIO gpio_slowdown(RGB_SLOWDOWN_GPIO), #else gpio_slowdown(1), #endif daemon(0), // Don't become a daemon by default. drop_privileges(1), // Encourage good practice: drop privileges by default. do_gpio_init(true) { // Nothing to see here. } namespace { typedef char** argv_iterator; #define OPTION_PREFIX "--led-" #define OPTION_PREFIX_LEN strlen(OPTION_PREFIX) static bool ConsumeBoolFlag(const char *flag_name, const argv_iterator &pos, bool *result_value) { const char *option = *pos; if (strncmp(option, OPTION_PREFIX, OPTION_PREFIX_LEN) != 0) return false; option += OPTION_PREFIX_LEN; bool value_to_set = true; if (strncmp(option, "no-", 3) == 0) { value_to_set = false; option += 3; } if (strcmp(option, flag_name) != 0) return false; // not consumed. *result_value = value_to_set; return true; } static bool ConsumeIntFlag(const char *flag_name, argv_iterator &pos, const argv_iterator end, int *result_value, int *error) { const char *option = *pos; if (strncmp(option, OPTION_PREFIX, OPTION_PREFIX_LEN) != 0) return false; option += OPTION_PREFIX_LEN; const size_t flag_len = strlen(flag_name); if (strncmp(option, flag_name, flag_len) != 0) return false; // not consumed. const char *value; if (option[flag_len] == '=') // --option=42 # value in same arg value = option + flag_len + 1; else if (pos + 1 < end) { // --option 42 # value in next arg value = *(++pos); } else { fprintf(stderr, "Parameter expected after %s%s\n", OPTION_PREFIX, flag_name); ++*error; return true; // consumed, but error. } char *end_value = NULL; int val = strtol(value, &end_value, 10); if (!*value || *end_value) { fprintf(stderr, "Couldn't parse parameter %s%s=%s " "(Expected decimal number but '%s' looks funny)\n", OPTION_PREFIX, flag_name, value, end_value); ++*error; return true; // consumed, but error } *result_value = val; return true; // consumed. } // The resulting value is allocated. static bool ConsumeStringFlag(const char *flag_name, argv_iterator &pos, const argv_iterator end, const char **result_value, int *error) { const char *option = *pos; if (strncmp(option, OPTION_PREFIX, OPTION_PREFIX_LEN) != 0) return false; option += OPTION_PREFIX_LEN; const size_t flag_len = strlen(flag_name); if (strncmp(option, flag_name, flag_len) != 0) return false; // not consumed. const char *value; if (option[flag_len] == '=') // --option=hello # value in same arg value = option + flag_len + 1; else if (pos + 1 < end) { // --option hello # value in next arg value = *(++pos); } else { fprintf(stderr, "Parameter expected after %s%s\n", OPTION_PREFIX, flag_name); ++*error; *result_value = NULL; return true; // consumed, but error. } *result_value = strdup(value); // This will leak, but no big deal. return true; } static bool FlagInit(int &argc, char **&argv, RGBMatrix::Options *mopts, RuntimeOptions *ropts, bool <API key>) { argv_iterator it = &argv[0]; argv_iterator end = it + argc; std::vector<char*> unused_options; unused_options.push_back(*it++); // Not interested in program name bool bool_scratch; int err = 0; bool <API key> = false; // end of options '--' for (; it < end; ++it) { <API key> |= (strcmp(*it, " if (!<API key>) { if (ConsumeStringFlag("gpio-mapping", it, end, &mopts->hardware_mapping, &err)) continue; if (ConsumeStringFlag("rgb-sequence", it, end, &mopts->led_rgb_sequence, &err)) continue; if (ConsumeIntFlag("rows", it, end, &mopts->rows, &err)) continue; if (ConsumeIntFlag("chain", it, end, &mopts->chain_length, &err)) continue; if (ConsumeIntFlag("parallel", it, end, &mopts->parallel, &err)) continue; if (ConsumeIntFlag("brightness", it, end, &mopts->brightness, &err)) continue; if (ConsumeIntFlag("scan-mode", it, end, &mopts->scan_mode, &err)) continue; if (ConsumeIntFlag("pwm-bits", it, end, &mopts->pwm_bits, &err)) continue; if (ConsumeIntFlag("pwm-lsb-nanoseconds", it, end, &mopts->pwm_lsb_nanoseconds, &err)) continue; if (ConsumeBoolFlag("show-refresh", it, &mopts->show_refresh_rate)) continue; if (ConsumeBoolFlag("inverse", it, &mopts->inverse_colors)) continue; // We don't have a swap_green_blue option anymore, but we simulate the // flag for a while. bool swap_green_blue; if (ConsumeBoolFlag("swap-green-blue", it, &swap_green_blue)) { if (strlen(mopts->led_rgb_sequence) == 3) { char *new_sequence = strdup(mopts->led_rgb_sequence); new_sequence[0] = mopts->led_rgb_sequence[0]; new_sequence[1] = mopts->led_rgb_sequence[2]; new_sequence[2] = mopts->led_rgb_sequence[1]; mopts->led_rgb_sequence = new_sequence; // leaking. Ignore. } continue; } bool <API key> = !mopts-><API key>; if (ConsumeBoolFlag("hardware-pulse", it, &<API key>)) { mopts-><API key> = !<API key>; continue; } bool request_help = false; if (ConsumeBoolFlag("help", it, &request_help) && request_help) { // In that case, we pretend to have failure in parsing, which will // trigger printing the usage(). Typically :) return false; } //-- Runtime options. if (ConsumeIntFlag("slowdown-gpio", it, end, &ropts->gpio_slowdown, &err)) continue; if (ropts->daemon >= 0 && ConsumeBoolFlag("daemon", it, &bool_scratch)) { ropts->daemon = bool_scratch ? 1 : 0; continue; } if (ropts->drop_privileges >= 0 && ConsumeBoolFlag("drop-privs", it, &bool_scratch)) { ropts->drop_privileges = bool_scratch ? 1 : 0; continue; } if (strncmp(*it, OPTION_PREFIX, OPTION_PREFIX_LEN) == 0) { fprintf(stderr, "Option %s starts with %s but it is unkown. Typo?\n", *it, OPTION_PREFIX); } } unused_options.push_back(*it); } if (err > 0) { return false; } if (<API key>) { // Success. Re-arrange flags to only include the ones not consumed. argc = (int) unused_options.size(); for (int i = 0; i < argc; ++i) { argv[i] = unused_options[i]; } } return true; } static bool drop_privs(const char *priv_user, const char *priv_group) { uid_t ruid, euid, suid; if (getresuid(&ruid, &euid, &suid) >= 0) { if (euid != 0) // not root anyway. No priv dropping. return true; } struct group *g = getgrnam(priv_group); if (g == NULL) { perror("group lookup."); return false; } if (setresgid(g->gr_gid, g->gr_gid, g->gr_gid) != 0) { perror("setresgid()"); return false; } struct passwd *p = getpwnam(priv_user); if (p == NULL) { perror("user lookup."); return false; } if (setresuid(p->pw_uid, p->pw_uid, p->pw_uid) != 0) { perror("setresuid()"); return false; } return true; } } // namespace bool <API key>(int *argc, char ***argv, RGBMatrix::Options *m_opt_in, RuntimeOptions *rt_opt_in, bool <API key>) { // Replace NULL arguments with some scratch-space. RGBMatrix::Options scratch_matrix; RGBMatrix::Options *mopt = (m_opt_in != NULL) ? m_opt_in : &scratch_matrix; RuntimeOptions scratch_rt; RuntimeOptions *ropt = (rt_opt_in != NULL) ? rt_opt_in : &scratch_rt; return FlagInit(*argc, *argv, mopt, ropt, <API key>); } RGBMatrix *<API key>(const RGBMatrix::Options &options, const RuntimeOptions &runtime_options) { std::string error; if (!options.Validate(&error)) { fprintf(stderr, "%s\n", error.c_str()); return NULL; } if (runtime_options.do_gpio_init && getuid() != 0) { fprintf(stderr, "Must run as root to be able to access /dev/mem\n" "Prepend 'sudo' to the command\n"); return NULL; } if (runtime_options.gpio_slowdown < 0 || runtime_options.gpio_slowdown > 4) { fprintf(stderr, "--led-slowdown-gpio=%d is outside usable range\n", runtime_options.gpio_slowdown); return NULL; } static GPIO io; // This static var is a little bit icky. if (runtime_options.do_gpio_init && !io.Init(runtime_options.gpio_slowdown)) { return NULL; } if (runtime_options.daemon > 0 && daemon(1, 0) != 0) { perror("Failed to become daemon"); } RGBMatrix *result = new RGBMatrix(NULL, options); // Allowing daemon also means we are allowed to start the thread now. const bool allow_daemon = !(runtime_options.daemon < 0); if (runtime_options.do_gpio_init) result->SetGPIO(&io, allow_daemon); // TODO(hzeller): if we disallow daemon, then we might also disallow // drop privileges: we can't drop privileges until we have created the // realtime thread that usually requires root to be established. // Double check and document. if (runtime_options.drop_privileges > 0) { drop_privs("daemon", "daemon"); } return result; } // Public interface. RGBMatrix *<API key>(int *argc, char ***argv, RGBMatrix::Options *m_opt_in, RuntimeOptions *rt_opt_in, bool <API key>) { RGBMatrix::Options scratch_matrix; RGBMatrix::Options *mopt = (m_opt_in != NULL) ? m_opt_in : &scratch_matrix; RuntimeOptions scratch_rt; RuntimeOptions *ropt = (rt_opt_in != NULL) ? rt_opt_in : &scratch_rt; if (!<API key>(argc, argv, mopt, ropt, <API key>)) return NULL; return <API key>(*mopt, *ropt); } void PrintMatrixFlags(FILE *out, const RGBMatrix::Options &d, const RuntimeOptions &r) { fprintf(out, "\t--led-gpio-mapping=<name> : Name of GPIO mapping used. Default \"%s\"\n" "\t--led-rows=<rows> : Panel rows. 8, 16, 32 or 64. " "(Default: %d).\n" "\t--led-chain=<chained> : Number of daisy-chained panels. " "(Default: %d).\n" "\t--led-parallel=<parallel> : For A/B+ models or RPi2,3b: parallel " "chains. range=1..3 (Default: %d).\n" "\t--led-pwm-bits=<1..11> : PWM bits (Default: %d).\n" "\t--led-brightness=<percent>: Brightness in percent (Default: %d).\n" "\t--led-scan-mode=<0..1> : 0 = progressive; 1 = interlaced " "(Default: %d).\n" "\t--led-%sshow-refresh : %show refresh rate.\n" "\t--led-%sinverse " ": Switch if your matrix has inverse colors %s.\n" "\t--led-rgb-sequence : Switch if your matrix has led colors " "swapped (Default: \"RGB\")\n" "\<API key> : PWM Nanoseconds for LSB " "(Default: %d)\n" "\t--led-%shardware-pulse : %sse hardware pin-pulse generation.\n", d.hardware_mapping, d.rows, d.chain_length, d.parallel, d.pwm_bits, d.brightness, d.scan_mode, d.show_refresh_rate ? "no-" : "", d.show_refresh_rate ? "Don't s" : "S", d.inverse_colors ? "no-" : "", d.inverse_colors ? "off" : "on", d.pwm_lsb_nanoseconds, !d.<API key> ? "no-" : "", !d.<API key> ? "Don't u" : "U"); fprintf(out, "\<API key>=<0..2>: " "Slowdown GPIO. Needed for faster Pis and/or slower panels " "(Default: %d).\n", r.gpio_slowdown); if (r.daemon >= 0) { const bool on = (r.daemon > 0); fprintf(out, "\t--led-%sdaemon : " "%sake the process run in the background as daemon.\n", on ? "no-" : "", on ? "Don't m" : "M"); } if (r.drop_privileges >= 0) { const bool on = (r.drop_privileges > 0); fprintf(out, "\t--led-%sdrop-privs : %srop privileges from 'root' " "after initializing the hardware.\n", on ? "no-" : "", on ? "Don't d" : "D"); } } bool RGBMatrix::Options::Validate(std::string *err_in) const { std::string scratch; std::string *err = err_in ? err_in : &scratch; bool success = true; if (rows != 8 && rows != 16 && rows != 32 && rows != 64) { err->append("Invalid number or panel rows. " "Should be one of 8, 16, 32 or 64\n"); success = false; } if (chain_length < 1) { err->append("Chain-length outside usable range.\n"); success = false; } if (parallel < 1 || parallel > 3) { err->append("Parallel outside usable range (1..3 allowed).\n"); success = false; } if (brightness < 1 || brightness > 100) { err->append("Brightness outside usable range (Percent 1..100 allowed).\n"); success = false; } if (pwm_bits <= 0 || pwm_bits > 11) { err->append("Invalid range of pwm-bits (0..11 allowed).\n"); success = false; } if (scan_mode < 0 || scan_mode > 1) { err->append("Invalid scan mode (0 or 1 allowed).\n"); success = false; } if (pwm_lsb_nanoseconds < 50 || pwm_lsb_nanoseconds > 3000) { err->append("Invalid range of pwm-lsb-nanoseconds (50..3000 allowed).\n"); success = false; } if (led_rgb_sequence == NULL || strlen(led_rgb_sequence) != 3) { err->append("led-sequence needs to be three characters long.\n"); success = false; } else { if ((!strchr(led_rgb_sequence, 'R') && !strchr(led_rgb_sequence, 'r')) || (!strchr(led_rgb_sequence, 'G') && !strchr(led_rgb_sequence, 'g')) || (!strchr(led_rgb_sequence, 'B') && !strchr(led_rgb_sequence, 'b'))) { err->append("led-sequence needs to contain all of letters 'R', 'G' " "and 'B'\n"); success = false; } } if (!success && !err_in) { // If we didn't get a string to write to, we write things to stderr. fprintf(stderr, "%s", err->c_str()); } return success; } // Linker trick: is someone was linking the old library that didn't have the // optional parameter defined, the linking will fail it wouldn't find the symbol // with less parameters. But we don't want to clutter the header with simple // delegation calls. // So we define this symbol here and doing the delegation call until // really everyone had recompiled their code with the new header. // Should be removed in a couple of months (March 2017ish) bool <API key>(int *argc, char ***argv, RGBMatrix::Options *default_options, RuntimeOptions *rt_options) { return <API key>(argc, argv, default_options, rt_options, true); } RGBMatrix *<API key>(int *argc, char ***argv, RGBMatrix::Options *default_options, RuntimeOptions *default_rt_opts) { return <API key>(argc, argv, default_options, default_rt_opts, true); } } // namespace rgb_matrix
<header> <nav id="header" class="navbar fixed-top navbar-dark header-bg row"> <div class="col"> <a class="navbar-brand header-navbar-brand" href="/"><img src="/assets/img/logo.png" height="42px" title="Ingelectus S.L."/></a> </div> <div class="col-8 d-none d-md-block"> <ul class="nav <API key>"> {% for link in site.data.navigation.highlight %} <li class="nav-item"> <a class="nav-link header-nav-link{% if page.url == link.url %} header-nav-active{% endif %}" href="{{ link.url }}" {% if link.target %}target="{{ link.target }}"{% endif %}>{{ link.title }}</a> </li> {% endfor %} </ul> </div> <div class="col"> <button class="navbar-toggler pull-right" style="cursor: pointer" type="button" data-toggle="collapse" data-target="#sidebar" aria-expanded="false" aria-controls="sidebar"> <small><span class="navbar-toggler-icon"></span></small> </button> </div> </nav> {% include sidebar.html %} </header>
# biNixieClock Arduino code for a clock that uses only two Nixie tubes. To build a biNixie clock you need: - an Arduino board (I used Nano) - two Nixie tubes with their sockets - two 74141 or K155DI or similar BCD-to-decimal converter and driver - current limiting resistor on each tube's anode - an RTC module (like DS1307) - an HV PSU like the one sold on www.lumos.sk - a 12 Vdc source - two NO pushbuttons - wires, perfboard If you don't edit the code, wiring from the Arduino to the rest of the world: - pins D9, D7, D6, D8 are BCD of big decade, LSB first (2 of number "23") - pins D5, D16, D14, D4 are BCD of low nibble decade, MSB first (3 of number "23") - pin D15 on hour setting button - pin D18 on minute setting button Nixie anodes are not multiplexed. There is no HV PSU poweroff, it runs all the time, but you could use pin D10 to control it (code not provided). There is a quick depoison routine running at power-up and every 10 minutes past the full hour. Serial debug output has been commented out (disabled). Adjust timings to suit your needs. Right now: - 70 milliseconds between each biDigit display (13 : 45 : 43) - 1 second "on" time for each biDigit - 3.3 seconds "off" time between cycles - 500 milliseconds between each hh/mm increase when setting them The biNixie Clock schematic diagram can be seen at http://ik1zyw.blogspot.it/2016/03/<API key>.html . RULES Enjoy. Share back your code mods. Be careful with the high-voltage (can be lethal, you have been warned). Let your guests be hypnotized by the biNixie clock (and guess what it is showing).
/* DeadRSX SAMPLE || Font Author DarkhackerPS3 */ #include <stdio.h> #include <malloc.h> #include <string.h> #include <assert.h> #include <unistd.h> #include <math.h> #include <rsx/commands.h> #include <rsx/nv40.h> #include <rsx/reality.h> #include <io/pad.h> #include <sysmodule/sysmodule.h> #include <sysutil/events.h> #include <deadrsx/deadrsx.h> #include <deadrsx/texture.h> #include <deadrsx/nv_shaders.h> #include "font.h" #include "sprite.bin.h" int i,sprite_x=0,sprite_y=0; int currentBuffer = 0; int app_state = 1; // used to switch screens int background_color = COLOR_WHITE; PadInfo padinfo; PadData paddata; u32 *tx_mem,sprite_offset; Image sprite_image; void drawFrame(int buffer, long frame) { <API key>(context, 0.0, 0.0, 0.0, 0.0); <API key>(context, 1.0, 1.0, 1.0, 0.0); deadrsx_scale(); // scales screen to 847x511 - deadrsx library realityZControl(context, 0, 1, 1); // disable viewport culling realityBlendFunc(context, <API key> | <API key>, <API key> | <API key>); <API key>(context, <API key> | <API key>); realityBlendEnable(context, 1); realityViewport(context, res.width, res.height); setupRenderTarget(buffer); deadrsx_background(background_color); <API key>(context, 0xffff); realityClearBuffers(context, <API key> | <API key> | <API key> | <API key> | <API key> | <API key>); <API key>(context, &nv40_vp); <API key>(context, &nv30_fp); switch(app_state) { case 1: background_color = COLOR_WHITE; drawText(sprite_offset, 32, "DeadRSX 0.1 Font Sample", 0, 0); drawText(sprite_offset, 20, "Check www.ps3sdk.com for updates", 5,35); break; case 2: // screen while in-game xmb open background_color = COLOR_BLACK; break; } } static void eventHandle(u64 status, u64 param, void * userdata) { (void)param; (void)userdata; if(status == <API key>){ exit(0); }else if(status == EVENT_MENU_OPEN){ app_state = 2; }else if(status == EVENT_MENU_CLOSE) { app_state = 1; }else{ printf("Unhandled event: %08llX\n", (unsigned long long int)status); } } void appCleanup(){ <API key>(EVENT_SLOT0); } void loading() { // where all are loading going be done :D sprite_image = loadPng(sprite_bin); assert(<API key>(sprite_image.data, &sprite_offset) == 0); } void ps3_pad() { ioPadGetInfo(&padinfo); switch(app_state) { case 1: // are only screen open at the moment for(i=0; i<MAX_PADS; i++){ if(padinfo.status[i]){ ioPadGetData(i, &paddata); if(paddata.BTN_START){ exit(0); }else if(paddata.BTN_UP) { sprite_y -= 5; }else if(paddata.BTN_DOWN) { sprite_y += 5; }else if(paddata.BTN_LEFT) { sprite_x -= 5; }else if(paddata.BTN_RIGHT) { sprite_x += 5; }else{ } } } break; } } s32 main(s32 argc, const char* argv[]) { atexit(appCleanup); deadrsx_init(); ioPadInit(7); sysRegisterCallback(EVENT_SLOT0, eventHandle, NULL); u32 *frag_mem = rsxMemAlign(256, 256); printf("frag_mem = 0x%08lx\n", (u64) frag_mem); <API key>(context, &nv30_fp, frag_mem); loading(); // where all the loading done xD long frame = 0; while(1){ ps3_pad(); // where all are controls are waitFlip(); // Wait for the last flip to finish, so we can draw to the old buffer drawFrame(currentBuffer, frame++); // Draw into the unused buffer flip(currentBuffer); // Flip buffer onto screen currentBuffer = !currentBuffer; sysCheckCallback(); } return 0; }
#include "stdbool.h" #include "stdint.h" #include "platform.h" #include "build/debug.h" #include "common/filter.h" #include "common/maths.h" #include "common/utils.h" #include "config/feature.h" #include "pg/pg.h" #include "pg/pg_ids.h" #include "drivers/adc.h" #include "fc/runtime_config.h" #include "fc/config.h" #include "fc/rc_controls.h" #include "io/beeper.h" #include "sensors/battery.h" /** * terminology: meter vs sensors * * voltage and current sensors are used to collect data. * - e.g. voltage at an MCU ADC input pin, value from an ESC sensor. * sensors require very specific configuration, such as resistor values. * voltage and current meters are used to process and expose data collected from sensors to the rest of the system. * - e.g. a meter exposes normalized, and often filtered, values from a sensor. * meters require different or little configuration. * meters also have different precision concerns, and may use different units to the sensors. * */ static void <API key>(void); // temporary forward reference #define <API key> 20 #define LVC_AFFECT_TIME 10000000 //10 secs for the LVC to slowly kick in // Battery monitoring stuff uint8_t batteryCellCount; // Note: this can be 0 when no battery is detected or when the battery voltage sensor is missing or disabled. uint16_t <API key>; uint16_t <API key>; static lowVoltageCutoff_t lowVoltageCutoff; static currentMeter_t currentMeter; static voltageMeter_t voltageMeter; static batteryState_e batteryState; static batteryState_e voltageState; static batteryState_e consumptionState; #ifndef <API key> #ifdef <API key> #define <API key> <API key> #else #ifdef <API key> #define <API key> CURRENT_METER_MSP #else #define <API key> CURRENT_METER_NONE #endif #endif #endif #ifndef <API key> #define <API key> VOLTAGE_METER_NONE #endif <API key>(batteryConfig_t, batteryConfig, PG_BATTERY_CONFIG, 3); PG_RESET_TEMPLATE(batteryConfig_t, batteryConfig, // voltage .vbatmaxcellvoltage = 430, .vbatmincellvoltage = 330, .<API key> = 350, .<API key> = 300, //A cell below 3 will be ignored .voltageMeterSource = <API key>, .lvcPercentage = 100, //Off by default at 100% // current .batteryCapacity = 0, .currentMeterSource = <API key>, // cells .<API key> = 0, //0 will be ignored // warnings / alerts .useVBatAlerts = true, .<API key> = false, .<API key> = 10, .vbathysteresis = 1, .vbatfullcellvoltage = 410, .vbatLpfPeriod = 30, .ibatLpfPeriod = 10, ); void <API key>(timeUs_t currentTimeUs) { UNUSED(currentTimeUs); switch (batteryConfig()->voltageMeterSource) { #ifdef USE_ESC_SENSOR case VOLTAGE_METER_ESC: if (featureIsEnabled(FEATURE_ESC_SENSOR)) { <API key>(); <API key>(&voltageMeter); } break; #endif case VOLTAGE_METER_ADC: <API key>(); voltageMeterADCRead(<API key>, &voltageMeter); break; default: case VOLTAGE_METER_NONE: voltageMeterReset(&voltageMeter); break; } if (debugMode == DEBUG_BATTERY) { debug[0] = voltageMeter.unfiltered; debug[1] = voltageMeter.filtered; } } static void <API key>(void) { switch (getBatteryState()) { case BATTERY_WARNING: beeper(BEEPER_BAT_LOW); break; case BATTERY_CRITICAL: beeper(BEEPER_BAT_CRIT_LOW); break; case BATTERY_OK: case BATTERY_NOT_PRESENT: case BATTERY_INIT: break; } } void <API key>(void) { bool isVoltageStable = ABS(voltageMeter.filtered - voltageMeter.unfiltered) <= <API key>; bool isVoltageFromBat = (voltageMeter.filtered >= batteryConfig()-><API key> //above ~0V && voltageMeter.filtered <= batteryConfig()->vbatmaxcellvoltage) //1s max cell voltage check || voltageMeter.filtered > batteryConfig()-><API key>*2; //USB voltage - 2s or more check if ( (voltageState == BATTERY_NOT_PRESENT || voltageState == BATTERY_INIT) && isVoltageFromBat && isVoltageStable ) { /* Want to disable battery getting detected around USB voltage or 0V*/ /* battery has just been connected - calculate cells, warning voltages and reset state */ consumptionState = voltageState = BATTERY_OK; if (batteryConfig()-><API key> != 0) { batteryCellCount = batteryConfig()-><API key>; } else { unsigned cells = (voltageMeter.filtered / batteryConfig()->vbatmaxcellvoltage) + 1; if (cells > 8) { // something is wrong, we expect 8 cells maximum (and autodetection will be problematic at 6+ cells) cells = 8; } batteryCellCount = cells; } <API key> = batteryCellCount * batteryConfig()-><API key>; <API key> = batteryCellCount * batteryConfig()->vbatmincellvoltage; lowVoltageCutoff.percentage = 100; lowVoltageCutoff.startTime = 0; } else if ( voltageState != BATTERY_NOT_PRESENT && isVoltageStable && !isVoltageFromBat ) { /* battery has been disconnected - can take a while for filter cap to disharge so we use a threshold of batteryConfig()-><API key> */ consumptionState = voltageState = BATTERY_NOT_PRESENT; batteryCellCount = 0; <API key> = 0; <API key> = 0; } if (debugMode == DEBUG_BATTERY) { debug[2] = batteryCellCount; debug[3] = isVoltageStable; } } static void <API key>(void) { // alerts are currently used by beeper, osd and other subsystems switch (voltageState) { case BATTERY_OK: if (voltageMeter.filtered <= (<API key> - batteryConfig()->vbathysteresis)) { voltageState = BATTERY_WARNING; } break; case BATTERY_WARNING: if (voltageMeter.filtered <= (<API key> - batteryConfig()->vbathysteresis)) { voltageState = BATTERY_CRITICAL; } else if (voltageMeter.filtered > <API key>) { voltageState = BATTERY_OK; } break; case BATTERY_CRITICAL: if (voltageMeter.filtered > <API key>) { voltageState = BATTERY_WARNING; } break; default: break; } } static void batteryUpdateLVC(timeUs_t currentTimeUs) { if (batteryConfig()->lvcPercentage < 100) { if (voltageState == BATTERY_CRITICAL && !lowVoltageCutoff.enabled) { lowVoltageCutoff.enabled = true; lowVoltageCutoff.startTime = currentTimeUs; lowVoltageCutoff.percentage = 100; } if (lowVoltageCutoff.enabled) { if (cmp32(currentTimeUs,lowVoltageCutoff.startTime) < LVC_AFFECT_TIME) { lowVoltageCutoff.percentage = 100 - (cmp32(currentTimeUs,lowVoltageCutoff.startTime) * (100 - batteryConfig()->lvcPercentage) / LVC_AFFECT_TIME); } else { lowVoltageCutoff.percentage = batteryConfig()->lvcPercentage; } } } } void batteryUpdateStates(timeUs_t currentTimeUs) { <API key>(); <API key>(); batteryUpdateLVC(currentTimeUs); batteryState = MAX(voltageState, consumptionState); } const lowVoltageCutoff_t *getLowVoltageCutoff(void) { return &lowVoltageCutoff; } batteryState_e getBatteryState(void) { return batteryState; } batteryState_e getVoltageState(void) { return voltageState; } batteryState_e getConsumptionState(void) { return consumptionState; } const char * const batteryStateStrings[] = {"OK", "WARNING", "CRITICAL", "NOT PRESENT", "INIT"}; const char * <API key>(void) { return batteryStateStrings[getBatteryState()]; } void batteryInit(void) { // presence batteryState = BATTERY_INIT; batteryCellCount = 0; // voltage voltageState = BATTERY_INIT; <API key> = 0; <API key> = 0; lowVoltageCutoff.enabled = false; lowVoltageCutoff.percentage = 100; lowVoltageCutoff.startTime = 0; voltageMeterReset(&voltageMeter); switch (batteryConfig()->voltageMeterSource) { case VOLTAGE_METER_ESC: #ifdef USE_ESC_SENSOR voltageMeterESCInit(); #endif break; case VOLTAGE_METER_ADC: voltageMeterADCInit(); break; default: break; } // current consumptionState = BATTERY_OK; currentMeterReset(&currentMeter); switch (batteryConfig()->currentMeterSource) { case CURRENT_METER_ADC: currentMeterADCInit(); break; case <API key>: #ifdef <API key> <API key>(); #endif break; case CURRENT_METER_ESC: #ifdef ESC_SENSOR currentMeterESCInit(); #endif break; case CURRENT_METER_MSP: #ifdef <API key> currentMeterMSPInit(); #endif break; default: break; } } static void <API key>(void) { if (batteryConfig()-><API key> && batteryConfig()->batteryCapacity > 0 && batteryCellCount > 0) { uint8_t <API key> = <API key>(); if (<API key> == 0) { consumptionState = BATTERY_CRITICAL; } else if (<API key> <= batteryConfig()-><API key>) { consumptionState = BATTERY_WARNING; } else { consumptionState = BATTERY_OK; } } } void <API key>(timeUs_t currentTimeUs) { UNUSED(currentTimeUs); if (batteryCellCount == 0) { currentMeterReset(&currentMeter); return; } static uint32_t ibatLastServiced = 0; const int32_t lastUpdateAt = cmp32(currentTimeUs, ibatLastServiced); ibatLastServiced = currentTimeUs; switch (batteryConfig()->currentMeterSource) { case CURRENT_METER_ADC: <API key>(lastUpdateAt); currentMeterADCRead(&currentMeter); break; case <API key>: { #ifdef <API key> throttleStatus_e throttleStatus = <API key>(); bool <API key> = (throttleStatus == THROTTLE_LOW && featureIsEnabled(FEATURE_MOTOR_STOP)); int32_t throttleOffset = (int32_t)rcCommand[THROTTLE] - 1000; <API key>(lastUpdateAt, ARMING_FLAG(ARMED), <API key>, throttleOffset); <API key>(&currentMeter); #endif break; } case CURRENT_METER_ESC: #ifdef USE_ESC_SENSOR if (featureIsEnabled(FEATURE_ESC_SENSOR)) { <API key>(lastUpdateAt); <API key>(&currentMeter); } #endif break; case CURRENT_METER_MSP: #ifdef <API key> <API key>(currentTimeUs); currentMeterMSPRead(&currentMeter); #endif break; default: case CURRENT_METER_NONE: currentMeterReset(&currentMeter); break; } } float <API key>(void) { float batteryScaler = 1.0f; if (batteryConfig()->voltageMeterSource != VOLTAGE_METER_NONE && batteryCellCount > 0) { // Up to 33% PID gain. Should be fine for 4,2to 3,3 difference batteryScaler = constrainf((( (float)batteryConfig()->vbatmaxcellvoltage * batteryCellCount ) / (float) voltageMeter.filtered), 1.0f, 1.33f); } return batteryScaler; } uint8_t <API key>(void) { uint8_t batteryPercentage = 0; if (batteryCellCount > 0) { uint16_t batteryCapacity = batteryConfig()->batteryCapacity; if (batteryCapacity > 0) { batteryPercentage = constrain(((float)batteryCapacity - currentMeter.mAhDrawn) * 100 / batteryCapacity, 0, 100); } else { batteryPercentage = constrain((((uint32_t)voltageMeter.filtered - (batteryConfig()->vbatmincellvoltage * batteryCellCount)) * 100) / ((batteryConfig()->vbatmaxcellvoltage - batteryConfig()->vbatmincellvoltage) * batteryCellCount), 0, 100); } } return batteryPercentage; } void batteryUpdateAlarms(void) { // use the state to trigger beeper alerts if (batteryConfig()->useVBatAlerts) { <API key>(); } } bool <API key>(void) { return batteryConfig()->voltageMeterSource != VOLTAGE_METER_NONE; } uint16_t getBatteryVoltage(void) { return voltageMeter.filtered; } uint16_t <API key>(void) { return (voltageMeter.filtered + 5) / 10; } uint16_t <API key>(void) { return voltageMeter.unfiltered; } uint8_t getBatteryCellCount(void) { return batteryCellCount; } uint16_t <API key>(void) { return voltageMeter.filtered / batteryCellCount; } bool <API key>(void) { return batteryConfig()->currentMeterSource != CURRENT_METER_NONE; } int32_t getAmperage(void) { return currentMeter.amperage; } int32_t getAmperageLatest(void) { return currentMeter.amperageLatest; } int32_t getMAhDrawn(void) { return currentMeter.mAhDrawn; }
/** * Gazetteer combo used to search in the glorious dataset of OSM. * * @class BasiGX.view.form.field.GazetteerCombo * */ Ext.define('BasiGX.view.form.field.GazetteerCombo', { extend: 'Ext.form.field.ComboBox', xtype: '<API key>', requires: [ 'BasiGX.util.Map' ], store: [], /** * Initializes the gazetteer combo component. */ initComponent: function() { var me = this; me.callParent(arguments); me.on('boxready', me.onBoxReady, me); me.on('change', me.onComboValueChange, me); }, onBoxReady: function() { var me = this; me.nav = Ext.create('Ext.util.KeyNav', me.el, { esc: me.clearValue, scope: me }); }, /** * When the combo value changes, do a new gazetteer search. * * @param {BasiGX.view.form.field.GazetteerCombo} combo The combo. * @param {String} newValue The new selected value. */ onComboValueChange: function(combo, newValue) { var me = this; var gazetteerGrid = Ext.ComponentQuery.query('<API key>')[0]; if (newValue) { if (gazetteerGrid) { gazetteerGrid.show(combo); } me.doGazetteerSearch(newValue); } else { if (gazetteerGrid) { gazetteerGrid.getEl().slideOut('t', { duration: 250, callback: gazetteerGrid.<API key>, scope: gazetteerGrid }); } } }, /** * Modifies and then loads the store of the `<API key>`. * * @param {String} value The new selected value. */ doGazetteerSearch: function(value) { var gazetteerGrid = Ext.ComponentQuery.query( '<API key>' )[0]; var gazetteerStore = gazetteerGrid.getStore(); var checkbox = gazetteerGrid.down('checkbox[name=limitcheckbox]'); var limitToBBox = checkbox.getValue(); gazetteerGrid.show(); Ext.Ajax.abort(gazetteerStore._lastRequest); gazetteerStore.getProxy().setExtraParam('q', value); if (limitToBBox) { var map = BasiGX.util.Map.getMapComponent().getMap(); var olView = map.getView(); var projection = olView.getProjection().getCode(); var bbox = map.getView().calculateExtent(map.getSize()); var transformedBbox = ol.proj.transformExtent(bbox, projection, 'EPSG:4326'); gazetteerStore.getProxy().setExtraParam('viewboxlbrt', transformedBbox.toString()); } else { gazetteerStore.getProxy().setExtraParam('viewboxlbrt', null); } gazetteerStore.load(); gazetteerStore._lastRequest = Ext.Ajax.getLatest(); } });
<?php $L['accounts_title'] = 'Comptes'; $L['group_label'] = 'Groupes'; $L['user_label'] = 'Utilisateurs'; $L['pseudonym_label'] = 'Adresses email'; $L['ibay_label'] = 'Dossiers partagés'; $L['machine_label'] = 'Ordinateurs'; $L['ftp_label'] = 'Comptes FTP'; $L['vpn_label'] = 'Comptes VPN';
(function (doc, win) { var docEl = doc.documentElement, resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize', recalc = function () { var clientWidth = docEl.clientWidth; if (!clientWidth) return; if(clientWidth>=640){ docEl.style.fontSize = '100px'; }else{ docEl.style.fontSize = 100 * (clientWidth / 640) + 'px'; } }; if (!doc.addEventListener) return; win.addEventListener(resizeEvt, recalc, false); doc.addEventListener('DOMContentLoaded', recalc, false); })(document, window);
package com.forstudy.pc.communicator.NTRU.polynomial; import java.util.Arrays; import com.forstudy.pc.communicator.NTRU.exception.NtruException; /** * A polynomial class that combines two coefficients into one <code>long</code> value for * faster multiplication in 64 bit environments.<br/> * Coefficients can be between 0 and 2047 and are stored in pairs in the bits 0..10 and 24..34 of a <code>long</code> number. */ class LongPolynomial2 { private long[] coeffs; // each representing two coefficients in the original IntegerPolynomial private int numCoeffs; /** * Constructs a <code>LongPolynomial2</code> from a <code>IntegerPolynomial</code>. The two polynomials are independent of each other. * @param p the original polynomial. Coefficients must be between 0 and 2047. */ LongPolynomial2(IntegerPolynomial p) { numCoeffs = p.coeffs.length; coeffs = new long[(numCoeffs+1) / 2]; int idx = 0; for (int pIdx=0; pIdx<numCoeffs;) { int c0 = p.coeffs[pIdx++]; while (c0 < 0) c0 += 2048; long c1 = pIdx<numCoeffs ? p.coeffs[pIdx++] : 0; while (c1 < 0) c1 += 2048; coeffs[idx] = c0 + (c1<<24); idx++; } } private LongPolynomial2(long[] coeffs) { this.coeffs = coeffs; } private LongPolynomial2(int N) { coeffs = new long[N]; } /** Multiplies the polynomial with another, taking the indices mod N and the values mod 2048. */ public LongPolynomial2 mult(LongPolynomial2 poly2) { int N = coeffs.length; if (poly2.coeffs.length!=N || numCoeffs!=poly2.numCoeffs) throw new NtruException("Number of coefficients must be the same"); LongPolynomial2 c = multRecursive(poly2); if (c.coeffs.length > N) { if (numCoeffs%2 == 0) { for (int k=N; k<c.coeffs.length; k++) c.coeffs[k-N] = (c.coeffs[k-N]+c.coeffs[k]) & 0x7FF0007FFL; c.coeffs = Arrays.copyOf(c.coeffs, N); } else { for (int k=N; k<c.coeffs.length; k++) { c.coeffs[k-N] = c.coeffs[k-N] + (c.coeffs[k-1]>>24); c.coeffs[k-N] = c.coeffs[k-N] + ((c.coeffs[k]&2047)<<24); c.coeffs[k-N] &= 0x7FF0007FFL; } c.coeffs = Arrays.copyOf(c.coeffs, N); c.coeffs[c.coeffs.length-1] &= 2047; } } c = new LongPolynomial2(c.coeffs); c.numCoeffs = numCoeffs; return c; } public IntegerPolynomial toIntegerPolynomial() { int[] intCoeffs = new int[numCoeffs]; int uIdx = 0; for (int i=0; i<coeffs.length; i++) { intCoeffs[uIdx++] = (int)(coeffs[i] & 2047); if (uIdx < numCoeffs) intCoeffs[uIdx++] = (int)((coeffs[i]>>24) & 2047); } return new IntegerPolynomial(intCoeffs); } /** Karatsuba multiplication */ private LongPolynomial2 multRecursive(LongPolynomial2 poly2) { long[] a = coeffs; long[] b = poly2.coeffs; int n = poly2.coeffs.length; if (n <= 32) { int cn = 2 * n; LongPolynomial2 c = new LongPolynomial2(new long[cn]); for (int k=0; k<cn; k++) { for (int i=Math.max(0, k-n+1); i<=Math.min(k,n-1); i++) { long c0 = a[k-i] * b[i]; long cu = c0&0x7FF000000L + (c0&2047); long co = (c0>>>48) & 2047; c.coeffs[k] = (c.coeffs[k]+cu) & 0x7FF0007FFL; c.coeffs[k+1] = (c.coeffs[k+1]+co) & 0x7FF0007FFL; } } return c; } else { int n1 = n / 2; LongPolynomial2 a1 = new LongPolynomial2(Arrays.copyOf(a, n1)); LongPolynomial2 a2 = new LongPolynomial2(Arrays.copyOfRange(a, n1, n)); LongPolynomial2 b1 = new LongPolynomial2(Arrays.copyOf(b, n1)); LongPolynomial2 b2 = new LongPolynomial2(Arrays.copyOfRange(b, n1, n)); LongPolynomial2 A = a1.clone(); A.add(a2); LongPolynomial2 B = b1.clone(); B.add(b2); LongPolynomial2 c1 = a1.multRecursive(b1); LongPolynomial2 c2 = a2.multRecursive(b2); LongPolynomial2 c3 = A.multRecursive(B); c3.sub(c1); c3.sub(c2); LongPolynomial2 c = new LongPolynomial2(2*n); for (int i=0; i<c1.coeffs.length; i++) c.coeffs[i] = c1.coeffs[i] & 0x7FF0007FFL; for (int i=0; i<c3.coeffs.length; i++) c.coeffs[n1+i] = (c.coeffs[n1+i] + c3.coeffs[i]) & 0x7FF0007FFL; for (int i=0; i<c2.coeffs.length; i++) c.coeffs[2*n1+i] = (c.coeffs[2*n1+i] + c2.coeffs[i]) & 0x7FF0007FFL; return c; } } /** * Adds another polynomial which can have a different number of coefficients. * @param b another polynomial */ private void add(LongPolynomial2 b) { if (b.coeffs.length > coeffs.length) coeffs = Arrays.copyOf(coeffs, b.coeffs.length); for (int i=0; i<b.coeffs.length; i++) coeffs[i] = (coeffs[i] + b.coeffs[i]) & 0x7FF0007FFL; } /** * Subtracts another polynomial which can have a different number of coefficients. * @param b another polynomial */ private void sub(LongPolynomial2 b) { if (b.coeffs.length > coeffs.length) coeffs = Arrays.copyOf(coeffs, b.coeffs.length); for (int i=0; i<b.coeffs.length; i++) coeffs[i] = (0x0800000800000L + coeffs[i] - b.coeffs[i]) & 0x7FF0007FFL; } /** * Subtracts another polynomial which must have the same number of coefficients, * and applies an AND mask to the upper and lower halves of each coefficients. * @param b another polynomial * @param mask a bit mask less than 2048 to apply to each 11-bit coefficient */ void subAnd(LongPolynomial2 b, int mask) { long longMask = (((long)mask)<<24) + mask; for (int i=0; i<b.coeffs.length; i++) coeffs[i] = (0x0800000800000L + coeffs[i] - b.coeffs[i]) & longMask; } /** * Multiplies this polynomial by 2 and applies an AND mask to the upper and * lower halves of each coefficients. * @param mask a bit mask less than 2048 to apply to each 11-bit coefficient */ void mult2And(int mask) { long longMask = (((long)mask)<<24) + mask; for (int i=0; i<coeffs.length; i++) coeffs[i] = (coeffs[i]<<1) & longMask; } @Override public LongPolynomial2 clone() { LongPolynomial2 p = new LongPolynomial2(coeffs.clone()); p.numCoeffs = numCoeffs; return p; } @Override public boolean equals(Object obj) { if (obj instanceof LongPolynomial2) return Arrays.equals(coeffs, ((LongPolynomial2)obj).coeffs); else return false; } }
<div class="row"> <div class="container"> <ul class="breadcrumb"> <li><span style="color: orangered;">Master</span></li> <li class="active">Jadwal Dokter</li> </ul> </div> </div> <div class="row"> <div class="container"> <center> <uib-alert type="{{typeAlert}}" ng-show="alert">{{messageAlert}}</uib-alert> </center> </div> </div> <div class="row"> <div class="container"> <table class="table table-bordered table-hover"> <thead class="header-custom"> <tr> <th> Code </th> <th> Name </th> <th> Poli </th> <th class="col-sm-2 text-center"> <button class="btn btn-success" ng-click="<API key>()" tooltip-placement="bottom" uib-tooltip="Add New Dokter"><i class="glyphicon glyphicon-plus"></i></button> </th> </tr> </thead> <tbody> <tr ng-repeat="x in listDokter"> <td>{{x.code}}</td> <td>{{x.name}}</td> <td>{{x.poli.code}} - {{x.poli.name}}</td> <td class="col-sm-2 text-center"> <a class="glyphicon glyphicon-edit" ng-click="edit(x)" tooltip-placement="bottom" uib-tooltip="Edit {{x.nama}}"></a> <a class="glyphicon glyphicon-remove" ng-click="showDialogDelete(x)" tooltip-placement="bottom" uib-tooltip="Delete {{x.nama}}"></a> </td> </tr> </tbody> </table> <div align="center"> <uib-pagination total-items="paging.totalItems" ng-model="paging.currentPage" max-size="paging.maxPage" class="pagination-sm" ng-change="reloadPage()" boundary-links="true" items-per-page="paging.itemsPerPage"> </uib-pagination> </div> <div align="center"> <pre>Page: {{paging.currentPage}} / {{paging.maxPage}}</pre> </div> </div> </div> <div class="modal fade bs-example-modal-sm" id="modalAddDokter" tabindex="-1" role="dialog" data-backdrop="static"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header header-custom"> <button type="button" class="close" ng-click="<API key>()" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Form Input Dokter</h4> </div> <div class="modal-body"> <form name="formDokter"> <div class="form-horizontal"> <div class="form-group" ng-class="{'has-error':formDokter.code.$invalid, 'has-success':formDokter.code.$valid}"> <div class="col-sm-4"> <label for="code" class="control-label">Code</label> </div> <div class="col-sm-8"> <input name="code" type="text" class="form-control" ng-model="currentDokter.code" required /> <span style="float:right; color:white" class="help-block label label-danger" ng-show="validateCode">Code Already Exist</span> </div> </div> <div class="form-group" ng-class="{'has-error':formDokter.name.$invalid, 'has-success':formDokter.name.$valid}"> <div class="col-sm-4"> <label for="name" class="control-label">Name</label> </div> <div class="col-sm-8"> <input name="name" type="text" class="form-control" ng-model="currentDokter.name" required /> </div> </div> <div class="form-group" ng-class="{'has-error':formDokter.description.$invalid, 'has-success':formDokter.description.$valid}"> <div class="col-sm-4"> <label for="description" class="control-label">Description</label> </div> <div class="col-sm-8"> <textarea name="description" class="form-control" ng-model="currentDokter.description" required></textarea> </div> </div> <div class="form-group" ng-class="{'has-error':formDokter.poli.$invalid, 'has-success':formDokter.poli.$valid}"> <div class="col-sm-4"> <label for="poli" class="control-label">Poli</label> </div> <div class="col-sm-8"> <ui-select tagging="tagTransform" name="poli" ng-model="currentDokter.poli" theme="bootstrap" title="Choose a Poli" ng-required="true"> <ui-select-match class="ui-select-match" placeholder="Select Poli...">{{$select.selected.code}} - {{$select.selected.name}}</ui-select-match> <ui-select-choices class="ui-select-choices" repeat="x in listPoli | propsFilter: {code: $select.search, name: $select.search}"> <div ng-bind-html="x.code + ' - ' +x.name | highlight: $select.search"></div> </ui-select-choices> </ui-select> </div> </div> <div class="form-group" ng-class="{'has-error':formDokter.kuotaSenin.$invalid, 'has-success':formDokter.kuotaSenin.$valid}"> <div class="col-sm-4"> <label for="kuotaSenin" class="control-label">Kuota Senin</label> </div> <div class="col-sm-8"> <input name="kuotaSenin" type="number" class="form-control" ng-model="currentDokter.kuotaSenin" required /> </div> </div> <div class="form-group" ng-class="{'has-error':formDokter.kuotaSelasa.$invalid, 'has-success':formDokter.kuotaSelasa.$valid}"> <div class="col-sm-4"> <label for="kuotaSelasa" class="control-label">Kuota Selasa</label> </div> <div class="col-sm-8"> <input name="kuotaSelasa" type="number" class="form-control" ng-model="currentDokter.kuotaSelasa" required /> </div> </div> <div class="form-group" ng-class="{'has-error':formDokter.kuotaRabu.$invalid, 'has-success':formDokter.kuotaRabu.$valid}"> <div class="col-sm-4"> <label for="kuotaRabu" class="control-label">Kuota Rabu</label> </div> <div class="col-sm-8"> <input name="kuotaRabu" type="number" class="form-control" ng-model="currentDokter.kuotaRabu" required /> </div> </div> <div class="form-group" ng-class="{'has-error':formDokter.kuotaKamis.$invalid, 'has-success':formDokter.kuotaKamis.$valid}"> <div class="col-sm-4"> <label for="kuotaKamis" class="control-label">Kuota Kamis</label> </div> <div class="col-sm-8"> <input name="kuotaKamis" type="number" class="form-control" ng-model="currentDokter.kuotaKamis" required /> </div> </div> <div class="form-group" ng-class="{'has-error':formDokter.kuotaJumat.$invalid, 'has-success':formDokter.kuotaJumat.$valid}"> <div class="col-sm-4"> <label for="kuotaJumat" class="control-label">Kuota Jum'at</label> </div> <div class="col-sm-8"> <input name="kuotaJumat" type="number" class="form-control" ng-model="currentDokter.kuotaJumat" required /> </div> </div> <div class="form-group" ng-class="{'has-error':formDokter.kuotaSabtu.$invalid, 'has-success':formDokter.kuotaSabtu.$valid}"> <div class="col-sm-4"> <label for="kuotaSabtu" class="control-label">Kuota Sabtu</label> </div> <div class="col-sm-8"> <input name="kuotaSabtu" type="number" class="form-control" ng-model="currentDokter.kuotaSabtu" required /> </div> </div> <div class="form-group" ng-class="{'has-error':formDokter.kuotaMinggu.$invalid, 'has-success':formDokter.kuotaMinggu.$valid}"> <div class="col-sm-4"> <label for="kuotaMinggu" class="control-label">Kuota Minggu</label> </div> <div class="col-sm-8"> <input name="kuotaMinggu" type="number" class="form-control" ng-model="currentDokter.kuotaMinggu" required /> </div> </div> </div> </form> </div> <div class="modal-footer"> <button class="btn btn-default" ng-click="<API key>()">Cancel</button> <button class="btn btn-primary" ng-click="save()" ng-disabled="formDokter.$invalid">Save</button> </div> </div> </div> </div> <!-- Modal Confirm Delete --> <div class="modal fade bs-example-modal-sm" id="modalConfirmDelete" tabindex="-1" role="dialog" data-backdrop="static"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header header-custom"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Confirm Delete [{{codeDelete}}]</h4> </div> <div class="modal-body"> Are you sure ? </div> <div class="modal-footer"> <button class="btn btn-default" data-dismiss="modal">No</button> <button class="btn btn-primary" ng-click="remove(idDokter)">Yes</button> </div> </div> </div> </div>
#!/bin/sh BOARD_DIR="$(dirname $0)" BOARD_NAME="$(basename ${BOARD_DIR})" GENIMAGE_CFG="${BOARD_DIR}/genimage-${BOARD_NAME}.cfg" GENIMAGE_TMP="${BUILD_DIR}/genimage.tmp" case "${2}" in --<API key>) if ! grep -qE '^dtoverlay=' "${BINARIES_DIR}/rpi-firmware/config.txt"; then echo "Adding 'dtoverlay=pi3-miniuart-bt' to config.txt (fixes ttyAMA0 serial console)." cat << __EOF__ >> "${BINARIES_DIR}/rpi-firmware/config.txt" # fixes rpi3 ttyAMA0 serial console dtoverlay=pi3-miniuart-bt __EOF__ fi ;; --aarch64) # Run a 64bits kernel (armv8) sed -e '/^kernel=/s,=.*,=Image,' -i "${BINARIES_DIR}/rpi-firmware/config.txt" if ! grep -qE '^arm_control=0x200' "${BINARIES_DIR}/rpi-firmware/config.txt"; then cat << __EOF__ >> "${BINARIES_DIR}/rpi-firmware/config.txt" # enable 64bits support arm_control=0x200 __EOF__ fi # Enable uart console if ! grep -qE '^enable_uart=1' "${BINARIES_DIR}/rpi-firmware/config.txt"; then cat << __EOF__ >> "${BINARIES_DIR}/rpi-firmware/config.txt" # enable rpi3 ttyS0 serial console enable_uart=1 __EOF__ fi ;; esac rm -rf "${GENIMAGE_TMP}" $(dirname $0)/activate-log.sh $(dirname $0)/rpi-mksdcard.sh
#ifndef ARG_H_ #define ARG_H_ #include <argp.h> #include <stdlib.h> #include <error.h> #include <stdio.h> #include <string.h> #define ARG_SIZE 1024 /* Used by main to communicate with parse_opt. */ struct arguments { char *arg1; /* arg1 */ char **strings; /* [string...] */ char printer_sock[ARG_SIZE]; char polybox_sock[ARG_SIZE]; char serial[ARG_SIZE]; int verbose; }; error_t parse_opt (int key, char *arg, struct argp_state *state); struct argp* get_argp(); void arguments_init( struct arguments* arg); #endif
<?php require_once 'ListObject.php'; /** * SubtopicsList class * */ class SubtopicsList extends ListObject { private static $s_orderFields = array( 'default', 'bynumber', 'byname', ); /** * Creates the list of objects. Sets the parameter $p_hasNextElements to * true if this list is limited and elements still exist in the original * list (from which this was truncated) after the last element of this * list. * * @param int $p_start * @param int $p_limit * @param array $p_parameters * @param int &$p_count * @return array */ protected function CreateList($p_start = 0, $p_limit = 0, array $p_parameters, &$p_count) { $rootTopicId = $p_parameters['topic_identifier']; $start = null; $limit = null; $order = array(); if ($p_start > 0) { $start = $p_start; } if ($p_limit > 0) { $limit = $p_limit; } if (!isset($p_parameters['direct'])) { $p_parameters['direct'] = true; } if (!empty($this->m_order)) { $order = $this->m_order[0]; } $em = \Zend_Registry::get('container')->getService('em'); $cacheService = \Zend_Registry::get('container')->getService('newscoop.cache'); $topicService = \Zend_Registry::get('container')->getService('newscoop_newscoop.topic_service'); $repository = $em->getRepository('Newscoop\NewscoopBundle\Entity\Topic'); $language = $em->getReference('Newscoop\Entity\Language', $p_parameters['language_id']); $topic = $repository->getSingleTopicQuery($rootTopicId, $language ? $language->getCode() : null)->getOneOrNullResult(); if (!$topic) { $subtopics = $repository->getRootNodes($language ? $language->getCode() : null)->getArrayResult(); } else { $topicsCount = $topicService->countBy(); $cacheKey = $cacheService->getCacheKey(array('topics', $topicsCount, $rootTopicId), 'topic'); $repository = $em->getRepository('Newscoop\NewscoopBundle\Entity\Topic'); if ($cacheService->contains($cacheKey)) { $subtopics = $cacheService->fetch($cacheKey); } else { $subtopics = $repository-><API key>( $topic, $language ? $language->getCode() : null, $p_parameters['direct'], isset($order['field']) ? $order['field'] : null, isset($order['dir']) ? $order['dir'] : null, $start, $limit )->getArrayResult(); $cacheService->save($cacheKey, $subtopics); } } $p_count = count($subtopics); $metaTopicsList = array(); $index = 0; foreach ($subtopics as $topic) { $index++; if ($p_limit == 0 || ($p_limit > 0 && $index <= $p_limit)) { $metaTopicsList[] = new MetaTopic($topic['id']); } } return $metaTopicsList; } /** * Processes list constraints passed in an array. * * @param array $p_constraints * @return array */ protected function ProcessConstraints(array $p_constraints) { return array(); } /** * Processes order constraints passed in an array. * * @param array $p_order * @return array */ protected function ProcessOrder(array $p_order) { $order = array(); $state = 1; $aliases = array( 'byname' => 'title', 'bynumber' => 'id', ); foreach ($p_order as $word) { switch ($state) { case 1: // reading the order field if (array_search(strtolower($word), SubtopicsList::$s_orderFields) === false) { CampTemplate::singleton()->trigger_error("invalid order field $word in list_subtopics, order parameter"); } else { $orderField = $aliases[$word]; $state = 2; } break; case 2: // reading the order direction if (MetaOrder::IsValid($word)) { $order[] = array('field' => $orderField, 'dir' => $word); } else { CampTemplate::singleton()->trigger_error("invalid order $word of attribute $orderField in list_subtopics, order parameter"); } $state = 1; break; } } if ($state != 1) { CampTemplate::singleton()->trigger_error("unexpected end of order parameter in list_issues"); } return $order; } /** * Processes the input parameters passed in an array; drops the invalid * parameters and parameters with invalid values. Returns an array of * valid parameters. * * @param array $p_parameters * @return array */ protected function ProcessParameters(array $p_parameters) { $parameters = array(); foreach ($p_parameters as $parameter => $value) { $parameter = strtolower($parameter); switch ($parameter) { case 'length': case 'columns': case 'name': case 'order': if ($parameter == 'length' || $parameter == 'columns') { $intValue = (int) $value; if ("$intValue" != $value || $intValue < 0) { CampTemplate::singleton()->trigger_error("invalid value $value of parameter $parameter in statement list_subtopics"); } $parameters[$parameter] = (int) $value; } else { $parameters[$parameter] = $value; } break; case 'direct': $parameters[$parameter] = filter_var($value, <API key>); break; default: CampTemplate::singleton()->trigger_error("invalid parameter $parameter in list_subtopics", $p_smarty); } } // 'topic_identifier' and 'language_id' parameters are needed for the cache key $context = CampTemplate::singleton()->context(); $parameters['topic_identifier'] = $context->topic->identifier; if (is_null($parameters['topic_identifier'])) { $parameters['topic_identifier'] = 0; } $parameters['language_id'] = $context->language->number; return $parameters; } protected function getCacheKey() { if (is_null($this->m_cacheKey)) { $this->m_cacheKey = __CLASS__.'__'.serialize($this->m_parameters) .'__'.$this->m_start.'__'.$this->m_limit.'__'.$this->m_columns; } return $this->m_cacheKey; } }
import { utilityPrimary, <API key>, defaultHoverStyle, respond } from "theme/styles/mixins"; export default ` .<API key> { --focus-color: var(--<API key>); --hover-color: var(--<API key>); position: relative; display: flex; width: 100%; height: 52vw; min-height: 350px; max-height: 52vh; overflow: hidden; color: var(--<API key>); background-color: var(--<API key>); figure { position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; opacity: 1; } /* Most resource heroes are height constrained. */ /* Interactive ones are not. */ &.<API key> { display: flex; overflow: visible; background-color: inherit; figure { position: relative; height: auto; overflow: visible; } } /* Transition classes */ .slide-left-enter figure { transform: translate3d(100%, 0, 0); } .<API key> figure { transition: transform 0.4s var(--<API key>); transform: translate3d(0, 0, 0); } .slide-left-exit figure { transform: translate3d(0, 0, 0); } .<API key> figure { transition: transform 0.4s var(--<API key>); transform: translate3d(-100%, 0, 0); } .slide-right-enter figure { transform: translate3d(-100%, 0, 0); } .<API key> figure { transition: transform 0.4s var(--<API key>); transform: translate3d(0, 0, 0); } .slide-right-exit figure { transform: translate3d(0, 0, 0); } .<API key> figure { transition: transform 0.4s var(--<API key>); transform: translate3d(100%, 0, 0); } .figure-image { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: var(--<API key>); object-fit: contain; } .figure-video { position: absolute; top: 0; left: 0; width: 100%; height: 100%; iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: var(--<API key>); } } .figure-interactive { flex: 1; height: 100%; background: var(--<API key>); iframe { width: 100%; min-height: 100%; border: 0; } } .figure-default { position: absolute; top: 0; left: 0; display: flex; width: 100%; height: 100%; background-position: 50% 50%; background-size: cover; .resource-info { padding: 20px 60px; margin: auto; text-align: center; &.with-background { background-color: var(--<API key>); opacity: 0.75; } } .resource-type { ${utilityPrimary} display: block; padding-bottom: 6px; font-size: 21px; font-weight: var(--font-weight-regular); } .resource-date { ${utilityPrimary} font-size: 12px; } } .zoom-indicator { ${utilityPrimary} position: absolute; top: 30px; right: 30px; z-index: 1; display: flex; align-items: center; padding: 5.5px 11px 7.5px 13px; font-size: 12px; cursor: pointer; background-color: var(--<API key>); opacity: 0.9; transition: color ${<API key>}, background-color ${<API key>}; &:hover { ${defaultHoverStyle} } &__icon { margin-left: 4px; } } .<API key> { &:focus-visible { border: 0; outline: 0; .zoom-indicator { color: var(--<API key>); background-color: var(--focus-color, var(--<API key>)); } } } &__resource-icon { margin-bottom: 4px; ${respond( `width: 21.34vw; height: 21.34vw;`, 50 )} ${respond( `width: 220px; height: 220px;`, 120 )} } } `;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> <meta name="description" content=""> <meta name="generator" content="Hugo 0.26" /> <title>knoone.info</title> <link href="http://knoone.info/index.xml" rel="alternate" type="application/rss+xml" title="knoone.info" /> <link rel="stylesheet" type="text/css" href="http://knoone.info/css/semantic.min.css"> <style type="text/css"> body { background-color: #2D2D29; } .main.container { margin-top: 5em; } h4 { color: #ccc; } </style> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="<API key>=" crossorigin="anonymous"></script> <script src="http://knoone.info//js/semantic.min.js"></script> <link rel="canonical" href="http://knoone.info/" /> </head> <body> <div class="ui fixed inverted small menu"> <div class="ui container"> <a href="http://knoone.info/" class="header item">knoone.info</a> <div class="ui simple dropdown item"> Archives <i class="dropdown icon"></i> <div class="menu"> <a class="item" href="#"><i class="calendar icon"></i>2017</a> <a class="item" href="#"><i class="calendar icon"></i>2016</a> <a class="item" href="#"><i class="calendar icon"></i>2015</a> </div> </div> <div class="ui simple dropdown item"> Tags <i class="dropdown icon"></i> <div class="menu"> <a class="item" href="http://knoone.info/tags/angularjs"><i class="tag icon"></i>angularjs</a> <a class="item" href="http://knoone.info/tags/beer"><i class="tag icon"></i>beer</a> <a class="item" href="http://knoone.info/tags/bootstrap"><i class="tag icon"></i>bootstrap</a> <a class="item" href="http://knoone.info/tags/career"><i class="tag icon"></i>career</a> <a class="item" href="http://knoone.info/tags/cat"><i class="tag icon"></i>cat</a> <a class="item" href="http://knoone.info/tags/food"><i class="tag icon"></i>food</a> <a class="item" href="http://knoone.info/tags/furniture"><i class="tag icon"></i>furniture</a> <a class="item" href="http://knoone.info/tags/gadgets"><i class="tag icon"></i>gadgets</a> <a class="item" href="http://knoone.info/tags/gardening"><i class="tag icon"></i>gardening</a> <a class="item" href="http://knoone.info/tags/hacking"><i class="tag icon"></i>hacking</a> <a class="item" href="http://knoone.info/tags/house"><i class="tag icon"></i>house</a> <a class="item" href="http://knoone.info/tags/humor"><i class="tag icon"></i>humor</a> <a class="item" href="http://knoone.info/tags/lastfm"><i class="tag icon"></i>lastfm</a> <a class="item" href="http://knoone.info/tags/misctech"><i class="tag icon"></i>misctech</a> <a class="item" href="http://knoone.info/tags/movies"><i class="tag icon"></i>movies</a> <a class="item" href="http://knoone.info/tags/mp3"><i class="tag icon"></i>mp3</a> <a class="item" href="http://knoone.info/tags/music"><i class="tag icon"></i>music</a> <a class="item" href="http://knoone.info/tags/nature"><i class="tag icon"></i>nature</a> <a class="item" href="http://knoone.info/tags/personal"><i class="tag icon"></i>personal</a> <a class="item" href="http://knoone.info/tags/photography"><i class="tag icon"></i>photography</a> <a class="item" href="http://knoone.info/tags/politics"><i class="tag icon"></i>politics</a> <a class="item" href="http://knoone.info/tags/portland"><i class="tag icon"></i>portland</a> <a class="item" href="http://knoone.info/tags/science"><i class="tag icon"></i>science</a> <a class="item" href="http://knoone.info/tags/shopping"><i class="tag icon"></i>shopping</a> <a class="item" href="http://knoone.info/tags/sports"><i class="tag icon"></i>sports</a> <a class="item" href="http://knoone.info/tags/television"><i class="tag icon"></i>television</a> <a class="item" href="http://knoone.info/tags/texas"><i class="tag icon"></i>texas</a> <a class="item" href="http://knoone.info/tags/travel"><i class="tag icon"></i>travel</a> <a class="item" href="http://knoone.info/tags/uncategorized"><i class="tag icon"></i>uncategorized</a> <a class="item" href="http://knoone.info/tags/weather"><i class="tag icon"></i>weather</a> <a class="item" href="http://knoone.info/tags/website"><i class="tag icon"></i>website</a> <a class="item" href="http://knoone.info/tags/webstuff"><i class="tag icon"></i>webstuff</a> <a class="item" href="http://knoone.info/tags/wedding"><i class="tag icon"></i>wedding</a> </div> </div> <a href="#" class="item">About</a> <div class="right menu"> <a href="https: <a href="https://twitter.com/cleverswine" class="item"><i class="twitter icon"></i></a> <a href="https://github.com/cleverswine" class="item"><i class="github icon"></i></a> <a href="http://knoone.info/index.xml" class="item"><i class="rss icon"></i></a> </div> </div> </div> <div class="ui main container"> <div class="ui three stackable cards"> <a class="ui fluid card" href="http://knoone.info/2007/12/11/<API key>/"> <div class="content"> <div class="header">Morrissey &amp;#8211; Irish Blood, English Heart</div> <div class="meta"> <span class="category"> mp3, music </span> </div> <div class="description"> This is one of my favorite new Morrissey songs. It is fitting that part of my dad&#8217;s family are Irish immigrants living in England. Morrissey &#8211; Irish Blood, English Heart </div> </div> <div class="extra content"> <div class="right floated author"> <time datetime="2007-12-11T12:20:12Z">11 Dec 2007</time> </div> </div> </a> <a class="ui fluid card" href="http://knoone.info/2007/12/07/counting-sheep/"> <div class="content"> <div class="header">Counting Sheep</div> <div class="meta"> <span class="category"> personal, webstuff </span> </div> <div class="description"> I&#8217;ve always wondered where the term &#8220;counting sheep&#8221; came from. I&#8217;ve tried counting sheep to fall asleep, and it doesn&#8217;t work. In my case, the sheep don&#8217;t cooperate. Come to find out&#8230; &#8230;counting sheep is actually an inferior means of inducing sleep. Subjects who instead imagined &#8220;a beach or a waterfall&#8221; were forced to expend more mental energy, and fell asleep faster than those asked to simply count sheep. </div> </div> <div class="extra content"> <div class="right floated author"> <time datetime="2007-12-07T12:37:53Z">07 Dec 2007</time> </div> </div> </a> <a class="ui fluid card" href="http://knoone.info/2007/12/07/<API key>/"> <div class="content"> <div class="header">The Programmer Dress Code</div> <div class="meta"> <span class="category"> humor, misctech, webstuff </span> </div> <div class="description"> This is an funny article about how most visionaries in the programming world have beards and dress like slobs. I have to say, dressing nice and shaving are at the bottom of my list of priorities. I think the same could be said for most of the programmers that I know. </div> </div> <div class="extra content"> <div class="right floated author"> <time datetime="2007-12-07T09:16:28Z">07 Dec 2007</time> </div> </div> </a> <a class="ui fluid card" href="http://knoone.info/2007/12/06/funny-unix-commands/"> <div class="content"> <div class="header">Funny Unix Commands</div> <div class="meta"> <span class="category"> humor, webstuff </span> </div> <div class="description"> This is a list of creative and funny Unix commands. There&#8217;s one I like which doesn&#8217;t seem to be on the list: % cd /pub % more beer </div> </div> <div class="extra content"> <div class="right floated author"> <time datetime="2007-12-06T14:00:39Z">06 Dec 2007</time> </div> </div> </a> <a class="ui fluid card" href="http://knoone.info/2007/12/05/a-bird-at-my-office/"> <div class="content"> <div class="header">A Bird at my Office</div> <div class="meta"> <span class="category"> personal, photography </span> </div> <div class="description"> This seagull has been sitting outside of my office for an hour. He is screeching like he wants to be fed&#8230; Unfortunately, there is glass between us. </div> </div> <div class="extra content"> <div class="right floated author"> <time datetime="2007-12-05T11:44:04Z">05 Dec 2007</time> </div> </div> </a> <a class="ui fluid card" href="http://knoone.info/2007/12/05/<API key>/"> <div class="content"> <div class="header">Why Does a Salad Cost More Than a Big Mac?</div> <div class="meta"> <span class="category"> webstuff </span> </div> <div class="description"> This is sad&#8230; </div> </div> <div class="extra content"> <div class="right floated author"> <time datetime="2007-12-05T08:56:26Z">05 Dec 2007</time> </div> </div> </a> </div> <nav> <ul class="pager"> <li><a href="/page/36/">&larr; Older</a></li> <li><a href="/page/34/">Newer &rarr;</a></li> </ul> </nav> </div> <p> &copy; 2017 knoone.info. All rights reserved. </p> </body> </html>
<!DOCTYPE html PUBLIC "- <html><head><title></title> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta name="generator" content="Doxygen 1.8.10"/> <link rel="stylesheet" type="text/css" href="search.css"/> <script type="text/javascript" src="variables_c.js"></script> <script type="text/javascript" src="search.js"></script> </head> <body class="SRPage"> <div id="SRIndex"> <div class="SRStatus" id="Loading">Cargando...</div> <div id="SRResults"></div> <script type="text/javascript"><! createResults(); --></script> <div class="SRStatus" id="Searching">Buscando...</div> <div class="SRStatus" id="NoMatches">Nada coincide</div> <script type="text/javascript"><! document.getElementById("Loading").style.display="none"; document.getElementById("NoMatches").style.display="none"; var searchResults = new SearchResults("searchResults"); searchResults.Search(); --></script> </div> </body> </html>
<!DOCTYPE html> <!--* Generated from PreTeXt source *--> <!--* on 2021-03-10T19:24:12-08:00 *--> <!--* A recent stable commit (2020-08-09): *--> <!--* <SHA1-like> *--> <html lang="en-US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> <meta name="Keywords" content="Authored in PreTeXt"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script xmlns:svg="http: </script><link xmlns:svg="http: <link xmlns:svg="http: <link xmlns:svg="http: <link xmlns:svg="http: <link xmlns:svg="http: <link xmlns:svg="http: <link xmlns:svg="http: <link xmlns:svg="http: <link xmlns:svg="http: <link xmlns:svg="http: <!-- 2019-10-12: Temporary - CSS file for experiments with styling --><link xmlns:svg="http: </head> <body class="mathbook-book"> <a class="assistive" href=" \newcommand{\lt}{&lt;} \newcommand{\gt}{&gt;} \newcommand{\amp}{&amp;} \)</div> <header id="masthead" class="smallbuttons"><div class="banner"><div class="container"> <a id="logo-link" href=""></a><div class="title-container"> <h1 class="heading"><a href="MusicTheory.html"><span class="title">Music Theory for the 21st-Century Classroom</span></a></h1> <p class="byline">Robert Hutchinson</p> </div> </div></div></header><div class="page"><main class="main"><div id="content" class="pretext-content" style="max-width: 1600px"> <div style="text-align: center;">Reloading this page will reset a start location</div> <div class="video-box" style="width: 100%;padding-top: 56.25%;"><iframe id="video-200" class="video" allowfullscreen="" src="https: </div></main></div> <!--Start: Google Global Site Tag code <script async="" src="https: function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-166054952-1'); </script><!--End: Google Global Site Tag code </body> </html>
<?php class API_Controller_Apps extends <API key> implements <API key>, <API key> { const APP_INTERFACE = '<API key>'; public function __construct() { if(!PAuthorisation::has('org.bambuscms.login')) { throw new Exception_HTTP(403); } } protected function getKeys() { return array('guid', 'title', 'icon', 'description', 'type'); } public function resolveSubPath(array $path) { $responder = null; //we are the requested path if(count($path) == 0){ $responder = $this; } else{ //get load sub path $appGUID = array_shift($path); //resolve guid -> app class $app = BObject::resolveGUID($appGUID); //check if request is an app if(!Core::isImplementation($app, self::APP_INTERFACE)){ throw new <API key>('not an app'); } //load app controller $appCtrl = BObject::<API key>($app); //create sub component $subComponent = new <API key>($appCtrl); $responder = $subComponent->resolveSubPath($path); } return $responder; } protected function getElements() { //get <API key> classes $elements = array(); $apps = Core::<API key>(self::APP_INTERFACE); foreach ($apps as $app){ $appController = new $app(); if ($appController instanceof <API key> && PAuthorisation::has($appController->getClassGUID())) { $elements[] = array( $appController->getClassGUID(), $appController->getTitle(), $appController->getIcon(), $appController->getDescription(), $appController->getEditor() ); } } return $elements; } public function getControllerName(){ return 'apps'; } } ?>
#ifndef _GETCH_H_ #define _GETCH_H_ #define <API key> (0x01) #define <API key> (0x02) #define EXIT_KEY_KEYSYM (27) // ESC key bool <API key>(); #endif