problem
stringlengths
26
131k
labels
class label
2 classes
static int qemu_chr_open_pty(QemuOpts *opts, CharDriverState **_chr) { CharDriverState *chr; PtyCharDriver *s; struct termios tty; int slave_fd, len; #if defined(__OpenBSD__) || defined(__DragonFly__) char pty_name[PATH_MAX]; #define q_ptsname(x) pty_name #else char *pty_name = NULL; #define q_ptsname(x) ptsname(x) #endif chr = g_malloc0(sizeof(CharDriverState)); s = g_malloc0(sizeof(PtyCharDriver)); if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) { return -errno; } tcgetattr(slave_fd, &tty); cfmakeraw(&tty); tcsetattr(slave_fd, TCSAFLUSH, &tty); close(slave_fd); len = strlen(q_ptsname(s->fd)) + 5; chr->filename = g_malloc(len); snprintf(chr->filename, len, "pty:%s", q_ptsname(s->fd)); qemu_opt_set(opts, "path", q_ptsname(s->fd)); fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd)); chr->opaque = s; chr->chr_write = pty_chr_write; chr->chr_update_read_handler = pty_chr_update_read_handler; chr->chr_close = pty_chr_close; s->timer = qemu_new_timer_ms(rt_clock, pty_chr_timer, chr); *_chr = chr; return 0; }
1threat
static void co_schedule_bh_cb(void *opaque) { AioContext *ctx = opaque; QSLIST_HEAD(, Coroutine) straight, reversed; QSLIST_MOVE_ATOMIC(&reversed, &ctx->scheduled_coroutines); QSLIST_INIT(&straight); while (!QSLIST_EMPTY(&reversed)) { Coroutine *co = QSLIST_FIRST(&reversed); QSLIST_REMOVE_HEAD(&reversed, co_scheduled_next); QSLIST_INSERT_HEAD(&straight, co, co_scheduled_next); } while (!QSLIST_EMPTY(&straight)) { Coroutine *co = QSLIST_FIRST(&straight); QSLIST_REMOVE_HEAD(&straight, co_scheduled_next); trace_aio_co_schedule_bh_cb(ctx, co); aio_context_acquire(ctx); qemu_coroutine_enter(co); aio_context_release(ctx); } }
1threat
Duration in continuous dates : Server Customer. Start. End A. X. 12/10/2018 12:56 13/10/2018. 13:05 B. K. 12/10/2018 14:05. 12/10/2018. 14:25 A. N 12/10/2018. 13:08. 13/10/2018. 17:09 A. Y 15/10/2018. 16:07. 17/10/2018. 14:09 A. F. 18/10/2018 13:05. 18/10/2018 20:09 I want how much duration server A was used 12/10/2018 12:56 to 18/10/2018 20:09. And how much time it was idle i.e 13/10/2018 17:09 to 15/10/2018 16:07 duration + 17/10/2018 14:09 to 18/10/2018. If any customer is login then that time is not counted as idle. How can I do it in Excel or Google sheets
0debug
waitfor value command doesn't work properly : I tried to run this code but it doesn't work properly. It got stuck on line 3 and gives error "timeout, element not found". ie.open g1ant.com window ‴✱internet explorer✱‴ ie.waitforvalue script document.getElementsByClassName("footer_stuff").length expectedvalue 1 dialog ‴Page loaded!‴ ie.close
0debug
static int rv20_decode_picture_header(MpegEncContext *s) { int seq, mb_pos, i; i= get_bits(&s->gb, 2); switch(i){ case 0: s->pict_type= I_TYPE; break; case 1: s->pict_type= I_TYPE; break; case 2: s->pict_type= P_TYPE; break; case 3: s->pict_type= B_TYPE; break; default: av_log(s->avctx, AV_LOG_ERROR, "unknown frame type\n"); return -1; } if (get_bits(&s->gb, 1)){ av_log(s->avctx, AV_LOG_ERROR, "unknown bit set\n"); return -1; } s->qscale = get_bits(&s->gb, 5); if(s->qscale==0){ av_log(s->avctx, AV_LOG_ERROR, "error, qscale:0\n"); return -1; } if(s->avctx->sub_id == 0x20200002) seq= get_bits(&s->gb, 16); else seq= get_bits(&s->gb, 8); for(i=0; i<6; i++){ if(s->mb_width*s->mb_height < ff_mba_max[i]) break; } mb_pos= get_bits(&s->gb, ff_mba_length[i]); s->mb_x= mb_pos % s->mb_width; s->mb_y= mb_pos / s->mb_width; s->no_rounding= get_bits1(&s->gb); s->f_code = 1; s->unrestricted_mv = 1; s->h263_aic= s->pict_type == I_TYPE; if(s->avctx->debug & FF_DEBUG_PICT_INFO){ av_log(s->avctx, AV_LOG_INFO, "num:%5d x:%2d y:%2d type:%d qscale:%2d rnd:%d\n", seq, s->mb_x, s->mb_y, s->pict_type, s->qscale, s->no_rounding); } if (s->pict_type == B_TYPE){ av_log(s->avctx, AV_LOG_ERROR, "b frame not supported\n"); return -1; } return s->mb_width*s->mb_height - mb_pos; }
1threat
Print list without brackets or commas in python : <p>I'm working on a simple compression algorithm that compresses binary files. I am scanning the file and filling a list with the character &amp; the number of times that character appears after it. The list however is formatted in a way that is making the compressed result larger due to all the brackets &amp; commas and I need rid of these. I have tried several methods of removing them but nothing is working. Here is the encode algorithm:</p> <pre><code>def encode(inputString): characterCount = 1 previousCharacter = '' List = [] for character in inputString: if character != previousCharacter: if previousCharacter: listEntry = (previousCharacter, characterCount) List.append(listEntry) #print lst characterCount = 1 previousCharacter = character else: characterCount += 1 else: try: listEntry = (character, characterCount) List.append(listEntry) return (List, 0) except Exception as e: print("Exception encountered {e}".format(e=e)) return (e, 1)` </code></pre> <p>And here is where I print the list. The hashed comments are the methods I have already tried with no luck.</p> <pre><code>value = encode(binaryfile) if value[1] == 0: print(value[0]) #flattened = [val for sublist in value for val in sublist] #print(flattened) #values = value[0] #print(*value[0], sep='') #print (''.join(map(str, value))) #print(int("".join(str(x) for x in value[0]))) </code></pre> <p>And here is the output.</p> <pre><code>[('1', 2), ('0', 1), ('1', 1), ('0', 4), ('1', 2), ('0', 2), ('1', 4), ('0', 3), ('1', 1), ('0', 3), ('1', 4), ('0', 5), ('1', 1), ('0', 1), ('1', 1), ('0', 4), ('1', 2), ('0', 1), ('1', 2), ('0', 3), ('1', 1), ('0', 3), ('1', 2), ('0', 1), ('1', 1), ('0', 1), ('1', 3), ('0', 4), ('1', 1), ('0', 130), ('1', 5), ('0', 15), ('1', 2), ('0', 8), ('1', 7), ('0', 1), ('1', 8), ('0', 4), ('1', 1), ('0', 2), ('1', 1), ('0', 13), ('1', 2), ('0', 96), ('1', 1), ('0', 26), ('1', 3), ('0', 70), ('1', 1), ('0', 22), ('1', 3), ('0', 1), ('1', 1), ('0', 32), ('1', 1), ('0', 24), ('1', 7), ('0', 1), ('1', 24), ('0', 34), ('1', 2), ('0', 1), ('1', 3), ('0', 24), ('1', 3459), ('0', 1), ('1', 2), ('0', 2), ('1', 1), ('0', 1), ('1', 1), ('0', 2), ('1', 1), ('0', 1), ('1', 3), ('0', 5), ('1', 1), ('0', 10), ('1', 1), ('0', 2), ('1', 3), ('0', 1), ('1', 2), ('0', 9), ('1', 1), ('0', 2), ('1', 1), ('0', 5), ('1', 1), ('0', 18), ('1', 4), ('0', 7), ('1', 1), ('0', 2), ('1', 1), ('0', 1), ('1', 1), </code></pre> <p>Any help is greatly appreciated</p>
0debug
Unknown cron range value 11 for "50 11/2 * * *" : <p>ERROR - Unknown cron range value "11" while running job.setall('30 11/2 * * *') in python script</p>
0debug
static int hls_write_header(AVFormatContext *s) { HLSContext *hls = s->priv_data; int ret, i; char *p; const char *pattern = "%d.ts"; const char *pattern_localtime_fmt = "-%s.ts"; const char *vtt_pattern = "%d.vtt"; AVDictionary *options = NULL; int basename_size; int vtt_basename_size; hls->sequence = hls->start_sequence; hls->recording_time = (hls->init_time ? hls->init_time : hls->time) * AV_TIME_BASE; hls->start_pts = AV_NOPTS_VALUE; if (hls->flags & HLS_PROGRAM_DATE_TIME) { time_t now0; time(&now0); hls->initial_prog_date_time = now0; } if (hls->format_options_str) { ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0); if (ret < 0) { av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n", hls->format_options_str); goto fail; } } for (i = 0; i < s->nb_streams; i++) { hls->has_video += s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO; hls->has_subtitle += s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE; } if (hls->has_video > 1) av_log(s, AV_LOG_WARNING, "More than a single video stream present, " "expect issues decoding it.\n"); hls->oformat = av_guess_format("mpegts", NULL, NULL); if (!hls->oformat) { ret = AVERROR_MUXER_NOT_FOUND; goto fail; } if(hls->has_subtitle) { hls->vtt_oformat = av_guess_format("webvtt", NULL, NULL); if (!hls->oformat) { ret = AVERROR_MUXER_NOT_FOUND; goto fail; } } if (hls->segment_filename) { hls->basename = av_strdup(hls->segment_filename); if (!hls->basename) { ret = AVERROR(ENOMEM); goto fail; } } else { if (hls->flags & HLS_SINGLE_FILE) pattern = ".ts"; if (hls->use_localtime) { basename_size = strlen(s->filename) + strlen(pattern_localtime_fmt) + 1; } else { basename_size = strlen(s->filename) + strlen(pattern) + 1; } hls->basename = av_malloc(basename_size); if (!hls->basename) { ret = AVERROR(ENOMEM); goto fail; } av_strlcpy(hls->basename, s->filename, basename_size); p = strrchr(hls->basename, '.'); if (p) *p = '\0'; if (hls->use_localtime) { av_strlcat(hls->basename, pattern_localtime_fmt, basename_size); } else { av_strlcat(hls->basename, pattern, basename_size); } } if (!hls->use_localtime && (hls->flags & HLS_SECOND_LEVEL_SEGMENT_INDEX)) { av_log(hls, AV_LOG_ERROR, "second_level_segment_index hls_flag requires use_localtime to be true\n"); ret = AVERROR(EINVAL); goto fail; } if(hls->has_subtitle) { if (hls->flags & HLS_SINGLE_FILE) vtt_pattern = ".vtt"; vtt_basename_size = strlen(s->filename) + strlen(vtt_pattern) + 1; hls->vtt_basename = av_malloc(vtt_basename_size); if (!hls->vtt_basename) { ret = AVERROR(ENOMEM); goto fail; } hls->vtt_m3u8_name = av_malloc(vtt_basename_size); if (!hls->vtt_m3u8_name ) { ret = AVERROR(ENOMEM); goto fail; } av_strlcpy(hls->vtt_basename, s->filename, vtt_basename_size); p = strrchr(hls->vtt_basename, '.'); if (p) *p = '\0'; if( hls->subtitle_filename ) { strcpy(hls->vtt_m3u8_name, hls->subtitle_filename); } else { strcpy(hls->vtt_m3u8_name, hls->vtt_basename); av_strlcat(hls->vtt_m3u8_name, "_vtt.m3u8", vtt_basename_size); } av_strlcat(hls->vtt_basename, vtt_pattern, vtt_basename_size); } if ((ret = hls_mux_init(s)) < 0) goto fail; if (hls->flags & HLS_APPEND_LIST) { parse_playlist(s, s->filename); hls->discontinuity = 1; if (hls->init_time > 0) { av_log(s, AV_LOG_WARNING, "append_list mode does not support hls_init_time," " hls_init_time value will have no effect\n"); hls->init_time = 0; hls->recording_time = hls->time * AV_TIME_BASE; } } if ((ret = hls_start(s)) < 0) goto fail; av_dict_copy(&options, hls->format_options, 0); ret = avformat_write_header(hls->avf, &options); if (av_dict_count(options)) { av_log(s, AV_LOG_ERROR, "Some of provided format options in '%s' are not recognized\n", hls->format_options_str); ret = AVERROR(EINVAL); goto fail; } for (i = 0; i < s->nb_streams; i++) { AVStream *inner_st; AVStream *outer_st = s->streams[i]; if (hls->max_seg_size > 0) { if ((outer_st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) && (outer_st->codecpar->bit_rate > hls->max_seg_size)) { av_log(s, AV_LOG_WARNING, "Your video bitrate is bigger than hls_segment_size, " "(%"PRId64 " > %"PRId64 "), the result maybe not be what you want.", outer_st->codecpar->bit_rate, hls->max_seg_size); } } if (outer_st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE) inner_st = hls->avf->streams[i]; else if (hls->vtt_avf) inner_st = hls->vtt_avf->streams[0]; else { inner_st = NULL; continue; } avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den); } fail: av_dict_free(&options); if (ret < 0) { av_freep(&hls->basename); av_freep(&hls->vtt_basename); if (hls->avf) avformat_free_context(hls->avf); if (hls->vtt_avf) avformat_free_context(hls->vtt_avf); } return ret; }
1threat
How to pass arguments in __VA_ARGS to a 2d character array? : <p>I need to get result from __VA_ARGS to a function, and from there I need to pass string of each argument to a 2d character array.</p>
0debug
How to transpose mysql table data using mysql query : <p>I would like to transpose attendance sql table as below </p> <p><a href="https://i.stack.imgur.com/2FqbI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2FqbI.png" alt="Below Mysql table data"></a></p> <p>To the following </p> <p><a href="https://i.stack.imgur.com/AhrHG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AhrHG.png" alt="enter image description here"></a></p> <p>Please help me here</p> <p>Thanks Sara</p>
0debug
#include <stdio.h> int main() { int i; printf("%d",scanf("%d",&i)); return 0; } : #include <stdio.h> int main() { int i; printf("%d",scanf("%d",&i));// > What does this explain return 0; } **It returns 1 everytime how??.**
0debug
serial in postgres is being increased even though I added on conflict do nothing : <p>I'm using Postgres 9.5 and seeing some wired things here.</p> <p>I've a cron job running ever 5 mins firing a sql statement that is adding a list of records if not existing.</p> <pre><code>INSERT INTO sometable (customer, balance) VALUES (:customer, :balance) ON CONFLICT (customer) DO NOTHING </code></pre> <p>sometable.customer is a primary key (text)</p> <p><strong><em>sometable structure is:</em></strong><br> id: serial<br> customer: text<br> balance: bigint </p> <p>Now it seems like everytime this job runs, the id field is silently incremented +1. So next time, I really add a field, it is thousands of numbers above my last value. I thought this query checks for conflicts and if so, do nothing but currently it seems like it tries to insert the record, increased the id and then stops.</p> <p>Any suggestions?</p>
0debug
Why does JSON.parse() add numbers in front of elements? : <p>I have a string where I build my build my "json-like" format, like</p> <pre><code>_toBeFormated = [ {"foor":"bar","foo":"bar","foo":["bar,bar"]}, {"foor":"bar","foo":"bar","foo":["bar,bar"]}, {"foor":"bar","foo":"bar","foo":["bar,bar"]} ] </code></pre> <p>But after calling <code>JSON.parse</code> like <code>_afterFormat = JSON.parse(_toBeFormated)</code>, my structure looks like the following:</p> <pre><code>_afterFormat = 0:{"foor":"bar","foo":"bar","foo":["bar,bar"]}, 1:{"foor":"bar","foo":"bar","foo":["bar,bar"]}, 2:{"foor":"bar","foo":"bar","foo":["bar,bar"]} </code></pre> <p>If I try to change to JSON Format at the beginning, like leaving out [ ], if failes to parse, also it looks like valid <code>JSON</code> to me. What am I missing, or why does it add the numbers at the beginning?</p>
0debug
Drawing a pyramid in console application( VB.NET) : How can i write a program that asks the user to enter the number of lines for the pyramid to be  drawn. If I typed number 6 the pyramid will have 6 star from the bottom to the top.
0debug
SimpleDateFormat and not allowing it to go above 12 hours : <p>So I have this method that I wanted to expand on to have the user input a valid 12 hour time. And I have it to this which works okay. But I want it so that if the hour is over 12 hours or the minutes is over 59 then it will prompt to do it again. But right now it will just convert the time by adding it. Also is there a more efficient way to write this? (Like without having the <strong>Date newTime = sdf.parse(startTime);</strong> And have it so that the user can just input a string and have it check if it's in the correct format? </p> <pre><code>public static void userInput(){ Scanner in = new Scanner(System.in); SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa"); String startTime; System.out.print("What is the start time?: "); boolean success = false; while (success != true){ try{ startTime = in.nextLine(); Date newTime = sdf.parse(startTime); startTime = sdf.format(newTime); System.out.println(startTime); success = true; } catch(Exception e){ System.out.println("Not a valid time. Please use this format (HH:MM AM)"); } } } </code></pre>
0debug
Algorithm for checking diagonal in N queens algortihm : I am trying to implement N- Queens problem in python. I need a small help in designing the algorithm to check if given a position of Queen check whether any other queen on the board is present on its diagonal or not. I am trying to design a function diagonal_check(board, row, col) where board is N*N matrix of arrays where '1' represents presence of queen and '0' represents absence. I will pass array and position of queen (row,col) to the function. My function must return false if any other queen is present on its diagonal or else return true. If anyone could help me with algorithm for diagonal_check function. Not looking for any specific language code.
0debug
Another, but specific play/pause issue : <p>I'm trying to implement play/pause and stop buttons in a toolbar for a simple stopwatch app. See code at <a href="http://swiftstub.com/722226472" rel="nofollow">http://swiftstub.com/722226472</a> I'm experiencing strange behavior: at first the play button does nothing. If I click on the stop button, the icon disappears and then the play/pause toggles and works correctly. Suggestions? I'm using the latest swift and Xcode</p>
0debug
Is it a valid code for Sieve of Eratosthenes? : <p>I recently learned Sieve of Eratosthenes to find prime numbers. After knowing the method i wrote this code for it.<br> <strong><em>Would it be a valid C++ code for Sieve of Eratosthenes?</em></strong></p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { int n; cin&gt;&gt;n; bool array[n]; for(int i=2;i&lt;=n;i++) { array[i]=true; } for(int i=2;i&lt;=n/2;i++) { for(int j=i+1;j&lt;=n;j++) { if(array[j]==true) { if(j%i==0) array[j]=false; } } } for(int k=2;k&lt;=n;k++) { if(array[k]==true) cout&lt;&lt;k&lt;&lt;" "; } } </code></pre> <p><strong>Thanks for help!</strong></p>
0debug
checking only email, not username : I have this code which checks email availability from database, but it's only checking email and not username, I want to check email and username both, I tried to check both through below code but it doesnt works. What is wrong in the code? <?php require_once './config.php'; if (isset($_POST["sub"])) { $fname =($_POST["fname"]); $lname =($_POST["lname"]); $name = ($_POST["username"]); $pass = ($_POST["password"]); $email =($_POST["email"]); $sql = "SELECT COUNT(*) AS count from users where email = :email_id and username = :username_id "; try { $stmt = $DB->prepare($sql); $stmt->bindValue(":email_id", $email); $stmt->bindValue(":username_id", $email); $stmt->execute(); $result = $stmt->fetchAll(); if ($result[0]["count"] > 0) { echo "<div style='color:red;' class='errorbox'>Incorrect Username or Password</div><br>"; } else { $sql = "INSERT INTO `users` (`username`, `password`, `email`, `firstname`, `lastname`) VALUES " . "( :name, :pass, :email, :fname, :lname)"; } } } ?>
0debug
static void gen_rp_realize(DeviceState *dev, Error **errp) { PCIDevice *d = PCI_DEVICE(dev); GenPCIERootPort *grp = GEN_PCIE_ROOT_PORT(d); PCIERootPortClass *rpc = PCIE_ROOT_PORT_GET_CLASS(d); rpc->parent_realize(dev, errp); int rc = pci_bridge_qemu_reserve_cap_init(d, 0, grp->bus_reserve, grp->io_reserve, grp->mem_reserve, grp->pref32_reserve, grp->pref64_reserve, errp); if (rc < 0) { rpc->parent_class.exit(d); return; } if (!grp->io_reserve) { pci_word_test_and_clear_mask(d->wmask + PCI_COMMAND, PCI_COMMAND_IO); d->wmask[PCI_IO_BASE] = 0; d->wmask[PCI_IO_LIMIT] = 0; } }
1threat
UIImage Caching is hight : Everyone.My English is not good.. + (nullable UIImage *)imageNamed:(NSString *)name; I use this method. --------------------------------------------------------------- e.g `UIImage *image=[UIImage imageNamed:@"test"];` --------------------------------------------------------------- But my image's type is png. [enter image description here][1] In my project,loads a lot of different images. So,My cashe is very hight [enter image description here][2] Please help me,thanks! [1]: http://i.stack.imgur.com/M2SAI.png [2]: http://i.stack.imgur.com/mCNpx.png
0debug
Swift2 - Drawing from dictionary : I'm trying to copy image pixel by pixel and I save the data from the image in dictionary:[UIColor:CGPoint] how to draw on CGContext all points pixel by pixel with the exact color for certain pixel?
0debug
Javascript:How to Read JSON specifically : i have used this :- var user = result.user; alert(JSON.stringify(user)); the above code has returned this data {"uid":"Kbkd6QMsqIhJ4pe3QXyEUjoAohN2","displayName":"Prince Hamza","photoURL":"https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg","email":"princehamzi.mine@gmail.com","emailVerified":true,"phoneNumber":null,"isAnonymous":false,"providerData":[{"uid":"110862942226973616842","displayName":"Prince Hamza","photoURL":"https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg","email":"princehamzi.mine@gmail.com","phoneNumber":null,"providerId":"google.com"}] but i am unable to Read this data specifically i want it to return uid , photoURL , Name , Email ;: Particularly
0debug
static void tracked_request_begin(BdrvTrackedRequest *req, BlockDriverState *bs, int64_t offset, unsigned int bytes, bool is_write) { *req = (BdrvTrackedRequest){ .bs = bs, .offset = offset, .bytes = bytes, .is_write = is_write, .co = qemu_coroutine_self(), .serialising = false, .overlap_offset = offset, .overlap_bytes = bytes, }; qemu_co_queue_init(&req->wait_queue); QLIST_INSERT_HEAD(&bs->tracked_requests, req, list); }
1threat
Why do we need extension method if inheritance is already there..? : <p>I am facing this question regularly in interview. But I am not getting it's answer anywhere.Please help me.</p>
0debug
static int cloop_open(BlockDriverState *bs, QDict *options, int flags, Error **errp) { BDRVCloopState *s = bs->opaque; uint32_t offsets_size, max_compressed_block_size = 1, i; int ret; bs->read_only = 1; ret = bdrv_pread(bs->file, 128, &s->block_size, 4); if (ret < 0) { return ret; } s->block_size = be32_to_cpu(s->block_size); if (s->block_size % 512) { error_setg(errp, "block_size %u must be a multiple of 512", s->block_size); return -EINVAL; } if (s->block_size == 0) { error_setg(errp, "block_size cannot be zero"); return -EINVAL; } if (s->block_size > MAX_BLOCK_SIZE) { error_setg(errp, "block_size %u must be %u MB or less", s->block_size, MAX_BLOCK_SIZE / (1024 * 1024)); return -EINVAL; } ret = bdrv_pread(bs->file, 128 + 4, &s->n_blocks, 4); if (ret < 0) { return ret; } s->n_blocks = be32_to_cpu(s->n_blocks); if (s->n_blocks > UINT32_MAX / sizeof(uint64_t)) { error_setg(errp, "n_blocks %u must be %zu or less", s->n_blocks, UINT32_MAX / sizeof(uint64_t)); return -EINVAL; } offsets_size = s->n_blocks * sizeof(uint64_t); if (offsets_size > 512 * 1024 * 1024) { error_setg(errp, "image requires too many offsets, " "try increasing block size"); return -EINVAL; } s->offsets = g_malloc(offsets_size); ret = bdrv_pread(bs->file, 128 + 4 + 4, s->offsets, offsets_size); if (ret < 0) { goto fail; } for(i=0;i<s->n_blocks;i++) { s->offsets[i] = be64_to_cpu(s->offsets[i]); if (i > 0) { uint32_t size = s->offsets[i] - s->offsets[i - 1]; if (size > max_compressed_block_size) { max_compressed_block_size = size; } } } s->compressed_block = g_malloc(max_compressed_block_size + 1); s->uncompressed_block = g_malloc(s->block_size); if (inflateInit(&s->zstream) != Z_OK) { ret = -EINVAL; goto fail; } s->current_block = s->n_blocks; s->sectors_per_block = s->block_size/512; bs->total_sectors = s->n_blocks * s->sectors_per_block; qemu_co_mutex_init(&s->lock); return 0; fail: g_free(s->offsets); g_free(s->compressed_block); g_free(s->uncompressed_block); return ret; }
1threat
C++ Trying to delete used line from txt file : <p>I'm trying to delete used lines from a txt file (questions.txt) and put them into another file (usedQuestions.txt), but right now the code just deletes questions.txt, doesn't put anything in temp.txt or renames it; and doesn't put anything in usedQuestions.txt</p> <p>This is my code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;fstream&gt; using namespace std; int main () { // Loop infinitely for (int i = 1; i &gt; 0; i++) { // Files ifstream txtFile("questions.txt"); ofstream usedQuestions("usedQuestions.txt"); ofstream tempFile("temp.txt"); // Strings, ints etc. string question; string temp; unsigned int lineNum = 1; int requestedLineNum; // User requests line cin &gt;&gt; requestedLineNum; cout &lt;&lt; "You have requested question number: " &lt;&lt; requestedLineNum &lt;&lt; endl; // Go through lines until the correct line is found while (getline(txtFile, question)) { //If the line number is correct, output question if (lineNum == requestedLineNum) { cout &lt;&lt; "Your question is: " &lt;&lt; question &lt;&lt; endl; // Write to temporary file, doesn't work? while (getline(txtFile, temp)) { tempFile &lt;&lt; temp; } // Write to file with used questions usedQuestions &lt;&lt; question; } // Set up for while loop to go through lines lineNum++; } // Close and remove questions.txt, rename temp.txt to questions.txt txtFile.close(); remove("questions.txt"); rename("temp.txt", "questions.txt"); } return 0; } </code></pre>
0debug
Django-Rest-Framework. Updating nested object : <p>I'm having a problem of updating a nested object.</p> <p>So I have a model which structure is similar to this one:</p> <pre><code>class Invoice(models.Model): nr = models.CharField(max_length=100) title = models.CharField(max_length=100) class InvoiceItem(models.Model): name = models.CharField(max_length=100) price = models.FloatField() invoice = models.ForeignKey(Invoice, related_name='items') </code></pre> <p>I need to create child objects from parent, and what I mean by that, is to create <code>InvoiceItems</code> directly when creating an <code>Invoice</code> object. For this purpose, I've wrote the following serializers:</p> <pre><code>class InvoiceItemSerializer(serializers.ModelSerializer): invoice = serializers.PrimaryKeyRelatedField(queryset=Invoice.objects.all(), required=False) class Meta: model = InvoiceItem class InvoiceSerializer(serializers.ModelSerializer): items = InvoiceItemSerializer(many=True) class Meta: model = Invoice def create(self, validated_data): items = validated_data.pop('items', None) invoice = Invoice(**validated_data) invoice.save() for item in items: InvoiceItem.objects.create(invoice=invoice, **item) return invoice </code></pre> <p>Up till now, the create/read/delete methods work perfectly, except the <code>update</code>. I think the below logic should be correct, but it misses something.</p> <pre><code>def update(self, instance, validated_data): instance.nr = validated_data.get('nr', instance.nr) instance.title = validated_data.get('title', instance.title) instance.save() # up till here everything is updating, however the problem appears here. # I don't know how to get the right InvoiceItem object, because in the validated # data I get the items queryset, but without an id. items = validated_data.get('items') for item in items: inv_item = InvoiceItem.objects.get(id=?????, invoice=instance) inv_item.name = item.get('name', inv_item.name) inv_item.price = item.get('price', inv_item.price) inv_item.save() return instance </code></pre> <p>Any help would be really appreciated.</p>
0debug
int ff_huff_gen_len_table(uint8_t *dst, const uint64_t *stats, int stats_size, int skip0) { HeapElem *h = av_malloc_array(sizeof(*h), stats_size); int *up = av_malloc_array(sizeof(*up) * 2, stats_size); uint8_t *len = av_malloc_array(sizeof(*len) * 2, stats_size); uint16_t *map= av_malloc_array(sizeof(*map), stats_size); int offset, i, next; int size = 0; int ret = 0; if (!h || !up || !len) { ret = AVERROR(ENOMEM); goto end; } for (i = 0; i<stats_size; i++) { dst[i] = 255; if (stats[i] || !skip0) map[size++] = i; } for (offset = 1; ; offset <<= 1) { for (i=0; i < size; i++) { h[i].name = i; h[i].val = (stats[map[i]] << 14) + offset; } for (i = size / 2 - 1; i >= 0; i--) heap_sift(h, i, size); for (next = size; next < size * 2 - 1; next++) { uint64_t min1v = h[0].val; up[h[0].name] = next; h[0].val = INT64_MAX; heap_sift(h, 0, size); up[h[0].name] = next; h[0].name = next; h[0].val += min1v; heap_sift(h, 0, size); } len[2 * size - 2] = 0; for (i = 2 * size - 3; i >= size; i--) len[i] = len[up[i]] + 1; for (i = 0; i < size; i++) { dst[map[i]] = len[up[i]] + 1; if (dst[map[i]] >= 32) break; } if (i==size) break; } end: av_free(h); av_free(up); av_free(len); av_free(map); return ret; }
1threat
CSS doesn't block rendering on Firefox Quantum : <p>With Firefox Quantum I noticed a "glitch" on loading the CSS of some websites.</p> <p><strong>One of these is <a href="https://www.doveconviene.it/discount" rel="noreferrer">my company's website</a>:</strong></p> <p><a href="https://i.stack.imgur.com/OyNr1.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/OyNr1.gif" alt="DoveConviene Website"></a></p> <p><strong>Or Github too:</strong></p> <p><a href="https://i.stack.imgur.com/VrRYC.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/VrRYC.gif" alt="Github Website"></a></p> <p>In the first one, we have only one CSS file in the <code>&lt;head&gt;</code> section of our pages.</p> <p>It seems that - only in Firefox Quantum - the CSS doesn't block the render of the page <a href="https://developers.google.com/web/fundamentals/performance/critical-rendering-path/render-blocking-css" rel="noreferrer">as it should</a>. The rest of the page loads without the CSS for some instants, then the CSS is applied as if it loads asynchronously (but it's not).</p> <p>Obviously, this behavior doesn't happen in all the websites I visited.</p> <p>I really have no clue what's going on :)</p>
0debug
Java - lop to search keys words in list of String : I have list of user tweets (usersTweets), i need to find a tweets with specific keys words (listOfkeyWord), and add matches to (includeKeyWord). there can be many of word in (keyWord = "ten,six,seven,...). String keyWord = "one,two"; List<String> usersTweets = new ArrayList<String>(); usersTweets.add("three nine one two"); usersTweets.add("seven one"); usersTweets.add("three nine ten one"); usersTweets.add("...."); List<String> includeKeyWord = new LinkedList<String>(); if (keyWord.contains(",")) { List<String> listOfkeyWord = new ArrayList<String>(Arrays.asList(keyWord.split(","))); for (String tweet : usersTweets) { if (tweet.contains(listOfkeyWord)) { includeKeyWord.add(tweet); } } }
0debug
react bootstrap readonly input within formcontrol : <p>I am using react bootstrap and this framework provides some nice FormControls.</p> <p>But I would like to make the Input field that is generated within the FormControls to have a prop of readonly="readonly". This way, this field looks the same as my other FormControls, but does not give a keyboard input on IOS. </p> <p>In my case, the input will be provided by a calendar picker which will be triggered by an popover.</p> <p>Does anyone know how to give FormControl the parameter readonly="readonly", so that the generated Input field in the browser will have the prop readonly="readonly"?</p> <p>Many thnx for the answers!</p>
0debug
Where to store common component methods in #NUXT.JS : <p>Actually i want to know where to store common components methods in #NUXT.JS. </p> <p>things which i have tried. --> Storing common code in middleware (its use-less) because according to my knowledge middleware is only capable of handling request and response to server.</p> <pre><code>methods: { // states methods. SwitchManager: function (__dataContainer, __key, __value) { // stand alone debugger for this module. let debug = __debug('computed:_3levelSwitch') // debug showing function loaded. debug('(h1:sizeCheck) creating switch..') // switch. switch (__key) { // fake allow set value to true of given key default: this[__dataContainer][__key][__value] = true break } return this[__dataContainer][__key][__value] }, SizeCheck: function (__size) { // stand alone debugger for this module. let debug = __debug('tags:p') // debug showing function loaded. debug('(p:sizeCheck) checking..') // init switch. this.SwitchManager('pill', 'size', __size) }, StateCheck: function (__state) { // stand alone debugger for this module. let debug = __debug('tags:h1') // debug showing function loaded. debug('(h1:sizeCheck) checking..') // init switch. this.SwitchManager('pill', 'state', __state) } }, created () { // h1 tag size check this.SizeCheck(this.size) this.StateCheck(this.state) } </code></pre>
0debug
How to prevent web crawlers in your PHP file : <p>How to prevent web crawlers in your PHP file? I need to add a code that would stop web crawlers from crawling in to my website. </p>
0debug
Test trigger performance : <p>how can I test my trigger ,how much time does it take on a table to execute?</p>
0debug
connection.query('SELECT * FROM users WHERE username = ' + input_string)
1threat
Multiple PayPal Payments Same Receiver : I manage a Nopcommerce site that uses the PayPal Express checkout plugin. Our accounting department wants the ability to split the payments based on some business rules. This differs from PayPal's Adaptive Payments because in this case its multiple payments for the same receiver. Ultimately I would need to capture the transaction ids for each payment to process later on. Is this possible to do?
0debug
How to check if a string contains three chars in consecutive order within a given string in any location? : <p>I am working on an app integration with a website. Basically, I am a PHP developer but the android app is using Java and I am not very professional in it. I need to offer an option to change passwords via the app itself. When the user enters a new password as a string, I want the app to check and make sure that no three consecutive chars from the old password are repeated in the new password in the same order.</p> <p>Eg. If a user has the old password "Angel173MN", he/she cannot opt for any new password that contains any three chars like nge,l17,73M etc (same order as in the old password, however, the same chars in other orders is permitted eg. gen, 7l1, 3M7 etc)</p> <p>The upper/lower case is of no concern here. Can anyone please guide me how to do it?</p>
0debug
static void gen_mfc0(DisasContext *ctx, TCGv arg, int reg, int sel) { const char *rn = "invalid"; if (sel != 0) check_insn(ctx, ISA_MIPS32); switch (reg) { case 0: switch (sel) { case 0: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Index)); rn = "Index"; break; case 1: check_insn(ctx, ASE_MT); gen_helper_mfc0_mvpcontrol(arg, cpu_env); rn = "MVPControl"; break; case 2: check_insn(ctx, ASE_MT); gen_helper_mfc0_mvpconf0(arg, cpu_env); rn = "MVPConf0"; break; case 3: check_insn(ctx, ASE_MT); gen_helper_mfc0_mvpconf1(arg, cpu_env); rn = "MVPConf1"; break; default: goto die; } break; case 1: switch (sel) { case 0: gen_helper_mfc0_random(arg, cpu_env); rn = "Random"; break; case 1: check_insn(ctx, ASE_MT); gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_VPEControl)); rn = "VPEControl"; break; case 2: check_insn(ctx, ASE_MT); gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_VPEConf0)); rn = "VPEConf0"; break; case 3: check_insn(ctx, ASE_MT); gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_VPEConf1)); rn = "VPEConf1"; break; case 4: check_insn(ctx, ASE_MT); gen_mfc0_load64(arg, offsetof(CPUMIPSState, CP0_YQMask)); rn = "YQMask"; break; case 5: check_insn(ctx, ASE_MT); gen_mfc0_load64(arg, offsetof(CPUMIPSState, CP0_VPESchedule)); rn = "VPESchedule"; break; case 6: check_insn(ctx, ASE_MT); gen_mfc0_load64(arg, offsetof(CPUMIPSState, CP0_VPEScheFBack)); rn = "VPEScheFBack"; break; case 7: check_insn(ctx, ASE_MT); gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_VPEOpt)); rn = "VPEOpt"; break; default: goto die; } break; case 2: switch (sel) { case 0: tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_EntryLo0)); #if defined(TARGET_MIPS64) if (ctx->rxi) { TCGv tmp = tcg_temp_new(); tcg_gen_andi_tl(tmp, arg, (3ull << 62)); tcg_gen_shri_tl(tmp, tmp, 32); tcg_gen_or_tl(arg, arg, tmp); tcg_temp_free(tmp); } #endif tcg_gen_ext32s_tl(arg, arg); rn = "EntryLo0"; break; case 1: check_insn(ctx, ASE_MT); gen_helper_mfc0_tcstatus(arg, cpu_env); rn = "TCStatus"; break; case 2: check_insn(ctx, ASE_MT); gen_helper_mfc0_tcbind(arg, cpu_env); rn = "TCBind"; break; case 3: check_insn(ctx, ASE_MT); gen_helper_mfc0_tcrestart(arg, cpu_env); rn = "TCRestart"; break; case 4: check_insn(ctx, ASE_MT); gen_helper_mfc0_tchalt(arg, cpu_env); rn = "TCHalt"; break; case 5: check_insn(ctx, ASE_MT); gen_helper_mfc0_tccontext(arg, cpu_env); rn = "TCContext"; break; case 6: check_insn(ctx, ASE_MT); gen_helper_mfc0_tcschedule(arg, cpu_env); rn = "TCSchedule"; break; case 7: check_insn(ctx, ASE_MT); gen_helper_mfc0_tcschefback(arg, cpu_env); rn = "TCScheFBack"; break; default: goto die; } break; case 3: switch (sel) { case 0: tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_EntryLo1)); #if defined(TARGET_MIPS64) if (ctx->rxi) { TCGv tmp = tcg_temp_new(); tcg_gen_andi_tl(tmp, arg, (3ull << 62)); tcg_gen_shri_tl(tmp, tmp, 32); tcg_gen_or_tl(arg, arg, tmp); tcg_temp_free(tmp); } #endif tcg_gen_ext32s_tl(arg, arg); rn = "EntryLo1"; break; default: goto die; } break; case 4: switch (sel) { case 0: tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_Context)); tcg_gen_ext32s_tl(arg, arg); rn = "Context"; break; case 1: rn = "ContextConfig"; goto die; case 2: if (ctx->ulri) { tcg_gen_ld32s_tl(arg, cpu_env, offsetof(CPUMIPSState, active_tc.CP0_UserLocal)); rn = "UserLocal"; } else { tcg_gen_movi_tl(arg, 0); } break; default: goto die; } break; case 5: switch (sel) { case 0: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_PageMask)); rn = "PageMask"; break; case 1: check_insn(ctx, ISA_MIPS32R2); gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_PageGrain)); rn = "PageGrain"; break; default: goto die; } break; case 6: switch (sel) { case 0: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Wired)); rn = "Wired"; break; case 1: check_insn(ctx, ISA_MIPS32R2); gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSConf0)); rn = "SRSConf0"; break; case 2: check_insn(ctx, ISA_MIPS32R2); gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSConf1)); rn = "SRSConf1"; break; case 3: check_insn(ctx, ISA_MIPS32R2); gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSConf2)); rn = "SRSConf2"; break; case 4: check_insn(ctx, ISA_MIPS32R2); gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSConf3)); rn = "SRSConf3"; break; case 5: check_insn(ctx, ISA_MIPS32R2); gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSConf4)); rn = "SRSConf4"; break; default: goto die; } break; case 7: switch (sel) { case 0: check_insn(ctx, ISA_MIPS32R2); gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_HWREna)); rn = "HWREna"; break; default: goto die; } break; case 8: switch (sel) { case 0: tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_BadVAddr)); tcg_gen_ext32s_tl(arg, arg); rn = "BadVAddr"; break; case 1: if (ctx->bi) { gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_BadInstr)); rn = "BadInstr"; } else { gen_mfc0_unimplemented(ctx, arg); } break; case 2: if (ctx->bp) { gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_BadInstrP)); rn = "BadInstrP"; } else { gen_mfc0_unimplemented(ctx, arg); } break; default: goto die; } break; case 9: switch (sel) { case 0: if (use_icount) gen_io_start(); gen_helper_mfc0_count(arg, cpu_env); if (use_icount) { gen_io_end(); } ctx->bstate = BS_STOP; rn = "Count"; break; default: goto die; } break; case 10: switch (sel) { case 0: tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_EntryHi)); tcg_gen_ext32s_tl(arg, arg); rn = "EntryHi"; break; default: goto die; } break; case 11: switch (sel) { case 0: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Compare)); rn = "Compare"; break; default: goto die; } break; case 12: switch (sel) { case 0: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Status)); rn = "Status"; break; case 1: check_insn(ctx, ISA_MIPS32R2); gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_IntCtl)); rn = "IntCtl"; break; case 2: check_insn(ctx, ISA_MIPS32R2); gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSCtl)); rn = "SRSCtl"; break; case 3: check_insn(ctx, ISA_MIPS32R2); gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSMap)); rn = "SRSMap"; break; default: goto die; } break; case 13: switch (sel) { case 0: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Cause)); rn = "Cause"; break; default: goto die; } break; case 14: switch (sel) { case 0: tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_EPC)); tcg_gen_ext32s_tl(arg, arg); rn = "EPC"; break; default: goto die; } break; case 15: switch (sel) { case 0: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_PRid)); rn = "PRid"; break; case 1: check_insn(ctx, ISA_MIPS32R2); gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_EBase)); rn = "EBase"; break; default: goto die; } break; case 16: switch (sel) { case 0: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config0)); rn = "Config"; break; case 1: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config1)); rn = "Config1"; break; case 2: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config2)); rn = "Config2"; break; case 3: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config3)); rn = "Config3"; break; case 4: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config4)); rn = "Config4"; break; case 5: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config5)); rn = "Config5"; break; case 6: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config6)); rn = "Config6"; break; case 7: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config7)); rn = "Config7"; break; default: goto die; } break; case 17: switch (sel) { case 0: gen_helper_mfc0_lladdr(arg, cpu_env); rn = "LLAddr"; break; default: goto die; } break; case 18: switch (sel) { case 0 ... 7: gen_helper_1e0i(mfc0_watchlo, arg, sel); rn = "WatchLo"; break; default: goto die; } break; case 19: switch (sel) { case 0 ...7: gen_helper_1e0i(mfc0_watchhi, arg, sel); rn = "WatchHi"; break; default: goto die; } break; case 20: switch (sel) { case 0: #if defined(TARGET_MIPS64) check_insn(ctx, ISA_MIPS3); tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_XContext)); tcg_gen_ext32s_tl(arg, arg); rn = "XContext"; break; #endif default: goto die; } break; case 21: switch (sel) { case 0: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Framemask)); rn = "Framemask"; break; default: goto die; } break; case 22: tcg_gen_movi_tl(arg, 0); rn = "'Diagnostic"; break; case 23: switch (sel) { case 0: gen_helper_mfc0_debug(arg, cpu_env); rn = "Debug"; break; case 1: rn = "TraceControl"; case 2: rn = "TraceControl2"; case 3: rn = "UserTraceData"; case 4: rn = "TraceBPC"; default: goto die; } break; case 24: switch (sel) { case 0: tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_DEPC)); tcg_gen_ext32s_tl(arg, arg); rn = "DEPC"; break; default: goto die; } break; case 25: switch (sel) { case 0: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Performance0)); rn = "Performance0"; break; case 1: rn = "Performance1"; case 2: rn = "Performance2"; case 3: rn = "Performance3"; case 4: rn = "Performance4"; case 5: rn = "Performance5"; case 6: rn = "Performance6"; case 7: rn = "Performance7"; default: goto die; } break; case 26: tcg_gen_movi_tl(arg, 0); rn = "ECC"; break; case 27: switch (sel) { case 0 ... 3: tcg_gen_movi_tl(arg, 0); rn = "CacheErr"; break; default: goto die; } break; case 28: switch (sel) { case 0: case 2: case 4: case 6: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_TagLo)); rn = "TagLo"; break; case 1: case 3: case 5: case 7: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_DataLo)); rn = "DataLo"; break; default: goto die; } break; case 29: switch (sel) { case 0: case 2: case 4: case 6: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_TagHi)); rn = "TagHi"; break; case 1: case 3: case 5: case 7: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_DataHi)); rn = "DataHi"; break; default: goto die; } break; case 30: switch (sel) { case 0: tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_ErrorEPC)); tcg_gen_ext32s_tl(arg, arg); rn = "ErrorEPC"; break; default: goto die; } break; case 31: switch (sel) { case 0: gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_DESAVE)); rn = "DESAVE"; break; case 2 ... 7: if (ctx->kscrexist & (1 << sel)) { tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_KScratch[sel-2])); tcg_gen_ext32s_tl(arg, arg); rn = "KScratch"; } else { gen_mfc0_unimplemented(ctx, arg); } break; default: goto die; } break; default: goto die; } (void)rn; LOG_DISAS("mfc0 %s (reg %d sel %d)\n", rn, reg, sel); return; die: LOG_DISAS("mfc0 %s (reg %d sel %d)\n", rn, reg, sel); generate_exception(ctx, EXCP_RI); }
1threat
static int check_pow_970FX (CPUPPCState *env) { if (env->spr[SPR_HID0] & 0x00600000) return 1; return 0; }
1threat
How do I create a client server network in Swift, or how do I send a request to another iphone on the app? : <p>I'm trying to create an app like uber, and I'm having trouble with the iphone to iphone connection. How am I to send a request to another Iphone, saying I am your driver! Am I to have riders become accepted, and add them to some database of riders in which drivers can see them? Basically I just want a little explanation on the ways I can use swift to connect iphones, any help is appreciated. </p>
0debug
int ff_init_vlc_sparse(VLC *vlc, int nb_bits, int nb_codes, const void *bits, int bits_wrap, int bits_size, const void *codes, int codes_wrap, int codes_size, const void *symbols, int symbols_wrap, int symbols_size, int flags) { VLCcode *buf; int i, j, ret; vlc->bits = nb_bits; if (flags & INIT_VLC_USE_NEW_STATIC) { VLC dyn_vlc = *vlc; if (vlc->table_size) return 0; ret = ff_init_vlc_sparse(&dyn_vlc, nb_bits, nb_codes, bits, bits_wrap, bits_size, codes, codes_wrap, codes_size, symbols, symbols_wrap, symbols_size, flags & ~INIT_VLC_USE_NEW_STATIC); av_assert0(ret >= 0); av_assert0(dyn_vlc.table_size <= vlc->table_allocated); if (dyn_vlc.table_size < vlc->table_allocated) av_log(NULL, AV_LOG_ERROR, "needed %d had %d\n", dyn_vlc.table_size, vlc->table_allocated); memcpy(vlc->table, dyn_vlc.table, dyn_vlc.table_size * sizeof(*vlc->table)); vlc->table_size = dyn_vlc.table_size; ff_free_vlc(&dyn_vlc); return 0; } else { vlc->table = NULL; vlc->table_allocated = 0; vlc->table_size = 0; } av_dlog(NULL, "build table nb_codes=%d\n", nb_codes); buf = av_malloc((nb_codes + 1) * sizeof(VLCcode)); av_assert0(symbols_size <= 2 || !symbols); j = 0; #define COPY(condition)\ for (i = 0; i < nb_codes; i++) { \ GET_DATA(buf[j].bits, bits, i, bits_wrap, bits_size); \ if (!(condition)) \ continue; \ if (buf[j].bits > 3*nb_bits || buf[j].bits>32) { \ av_log(NULL, AV_LOG_ERROR, "Too long VLC (%d) in init_vlc\n", buf[j].bits);\ av_free(buf); \ return -1; \ } \ GET_DATA(buf[j].code, codes, i, codes_wrap, codes_size); \ if (buf[j].code >= (1LL<<buf[j].bits)) { \ av_log(NULL, AV_LOG_ERROR, "Invalid code in init_vlc\n"); \ av_free(buf); \ return -1; \ } \ if (flags & INIT_VLC_LE) \ buf[j].code = bitswap_32(buf[j].code); \ else \ buf[j].code <<= 32 - buf[j].bits; \ if (symbols) \ GET_DATA(buf[j].symbol, symbols, i, symbols_wrap, symbols_size) \ else \ buf[j].symbol = i; \ j++; \ } COPY(buf[j].bits > nb_bits); qsort(buf, j, sizeof(VLCcode), compare_vlcspec); COPY(buf[j].bits && buf[j].bits <= nb_bits); nb_codes = j; ret = build_table(vlc, nb_bits, nb_codes, buf, flags); av_free(buf); if (ret < 0) { av_freep(&vlc->table); return ret; } return 0; }
1threat
Does Go have exceptions during overflow for arythmetic operations : I ma just porting some Go code to Rust and I realized that when Rust rise overflow during multiplication exception Go just allow overflow to happen. Test code below, that does not cause overflow but print reduced value. (tested via: https://play.golang.org/) ``` func main() { fmt.Println("test\n") var key uint64 = 15000; key = key*2862933555777941757 + 1 fmt.Println(key) } ``` Is that expected behavior? Sorry for basic question but I don't have much Go Experience.
0debug
pl/sql query for remove duplicates rows in temp table : I need your help to fix this issue. This is database related one. I have 2 table 1 is temptable and another one is Persons. Finally i need below remove duplicate date Table one: CREATE TABLE temptable ( ID int, Name varchar(255), pan varchar(255), Address varchar(255), status varchar(255) ); Table two: CREATE TABLE Persons ( ID int, Name varchar(255), pan varchar(255), Address varchar(255), status varchar(255) ); temp Table : ----------------------------------------------------------- ID Name pan Address status ----------------------------------------------------------- 1 Gopal akkoso232l hyd ACCESSED 1 Gopal akkoso232l hyd ACCESSED 2 sAI aaa1213 VIZ PENDING 3 RAM LLWELW1213 hyd ACCESSED 4 ONE ONE12so232l CHN ACCESSED 5 REDDY aZZoWE232l TOW ACCESSED ---------------------------------------------------------- 6 sUNRAI akppg8732 hyd ACCESSED 6 sUNRAI akppg8732 hyd PENDING ----------------------------------------------- I need main table data as below : Persons : ------------------------------------------------ ID Name pan Address status ------------------------------------------------ 1 Gopal akkoso232l hyd ACCESSED 2 sAI aaa1213 VIZ PENDING 3 RAM LLWELW1213 hyd ACCESSED 4 ONE ONE12so232l CHN ACCESSED 5 REDDY aZZoWE232l TOW ACCESSED ------------------------------------------------ 6 SUNRAI akppg8732 hyd ACCESSED ------------------------------------------------
0debug
how to get first JSONs elements using python : <p>The public API respond me with JSON which has the next format</p> <pre><code>{"ABCD-EFG": {"param1":"0.1234", "param2":"0.123456", "param3":"0.12334254"}, "HIG-KLMN": {"param1":"0.3456", "param2":"0.05710" "param3":"0.004903" ... } </code></pre> <p>How can i get the List of the names (in this examle ABCD-EFG, HIG-KLMN) using Python3 ?</p> <p>They can make changes in it every API get request sending</p> <p>If it was like 'name' : 'ABCD-EFG', it would be easy. But it's not like that.</p>
0debug
void mulu64(uint64_t *phigh, uint64_t *plow, uint64_t a, uint64_t b) { #if defined(__x86_64__) __asm__ ("mul %0\n\t" : "=d" (*phigh), "=a" (*plow) : "a" (a), "0" (b) ); #else uint64_t ph, pm1, pm2, pl; pl = (uint64_t)((uint32_t)a) * (uint64_t)((uint32_t)b); pm1 = (a >> 32) * (uint32_t)b; pm2 = (uint32_t)a * (b >> 32); ph = (a >> 32) * (b >> 32); ph += pm1 >> 32; pm1 = (uint64_t)((uint32_t)pm1) + pm2 + (pl >> 32); *phigh = ph + (pm1 >> 32); *plow = (pm1 << 32) + (uint32_t)pl; #endif }
1threat
int av_file_map(const char *filename, uint8_t **bufptr, size_t *size, int log_offset, void *log_ctx) { FileLogContext file_log_ctx = { &file_log_ctx_class, log_offset, log_ctx }; int err, fd = open(filename, O_RDONLY); struct stat st; av_unused void *ptr; off_t off_size; char errbuf[128]; *bufptr = NULL; if (fd < 0) { err = AVERROR(errno); av_strerror(err, errbuf, sizeof(errbuf)); av_log(&file_log_ctx, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename, errbuf); return err; } if (fstat(fd, &st) < 0) { err = AVERROR(errno); av_strerror(err, errbuf, sizeof(errbuf)); av_log(&file_log_ctx, AV_LOG_ERROR, "Error occurred in fstat(): %s\n", errbuf); close(fd); return err; } off_size = st.st_size; if (off_size > SIZE_MAX) { av_log(&file_log_ctx, AV_LOG_ERROR, "File size for file '%s' is too big\n", filename); close(fd); return AVERROR(EINVAL); } *size = off_size; #if HAVE_MMAP ptr = mmap(NULL, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0); if ((int)(ptr) == -1) { err = AVERROR(errno); av_strerror(err, errbuf, sizeof(errbuf)); av_log(&file_log_ctx, AV_LOG_ERROR, "Error occurred in mmap(): %s\n", errbuf); close(fd); return err; } *bufptr = ptr; #elif HAVE_MAPVIEWOFFILE { HANDLE mh, fh = (HANDLE)_get_osfhandle(fd); mh = CreateFileMapping(fh, NULL, PAGE_READONLY, 0, 0, NULL); if (!mh) { av_log(&file_log_ctx, AV_LOG_ERROR, "Error occurred in CreateFileMapping()\n"); close(fd); return -1; } ptr = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, *size); CloseHandle(mh); if (!ptr) { av_log(&file_log_ctx, AV_LOG_ERROR, "Error occurred in MapViewOfFile()\n"); close(fd); return -1; } *bufptr = ptr; } #else *bufptr = av_malloc(*size); if (!*bufptr) { av_log(&file_log_ctx, AV_LOG_ERROR, "Memory allocation error occurred\n"); close(fd); return AVERROR(ENOMEM); } read(fd, *bufptr, *size); #endif close(fd); return 0; }
1threat
using processing for 3D image mapping : <p>actually I'm Arduino Neopixel fan and tried to run the spherical POV. For run POV, each image should be converted to the number of lines which is used in each revolution , I think convert the planner POV must not be so hard for java base processing to pixelizid into lines but I don't now how to map an image on spherical and then converted to image lines I really appreciated for any comment</p>
0debug
How to get "v.3.1.2" in string by regex php : <p>I need get "v3.4.2" in string by regex php. String: "ABCDEF v3.4.2 GHI KLMN";</p>
0debug
static int restore_sigcontext(CPUSH4State *regs, struct target_sigcontext *sc, target_ulong *r0_p) { unsigned int err = 0; int i; #define COPY(x) __get_user(regs->x, &sc->sc_##x) COPY(gregs[1]); COPY(gregs[2]); COPY(gregs[3]); COPY(gregs[4]); COPY(gregs[5]); COPY(gregs[6]); COPY(gregs[7]); COPY(gregs[8]); COPY(gregs[9]); COPY(gregs[10]); COPY(gregs[11]); COPY(gregs[12]); COPY(gregs[13]); COPY(gregs[14]); COPY(gregs[15]); COPY(gbr); COPY(mach); COPY(macl); COPY(pr); COPY(sr); COPY(pc); #undef COPY for (i=0; i<16; i++) { __get_user(regs->fregs[i], &sc->sc_fpregs[i]); } __get_user(regs->fpscr, &sc->sc_fpscr); __get_user(regs->fpul, &sc->sc_fpul); regs->tra = -1; __get_user(*r0_p, &sc->sc_gregs[0]); return err; }
1threat
HELPER_LD(lbu, ldub, uint8_t) HELPER_LD(lhu, lduw, uint16_t) HELPER_LD(lw, ldl, int32_t) HELPER_LD(ld, ldq, int64_t) #undef HELPER_LD #if defined(CONFIG_USER_ONLY) #define HELPER_ST(name, insn, type) \ static inline void do_##name(CPUMIPSState *env, target_ulong addr, \ type val, int mem_idx) \ { \ cpu_##insn##_data(env, addr, val); \ } #else #define HELPER_ST(name, insn, type) \ static inline void do_##name(CPUMIPSState *env, target_ulong addr, \ type val, int mem_idx) \ { \ switch (mem_idx) \ { \ case 0: cpu_##insn##_kernel(env, addr, val); break; \ case 1: cpu_##insn##_super(env, addr, val); break; \ default: \ case 2: cpu_##insn##_user(env, addr, val); break; \ } \ } #endif HELPER_ST(sb, stb, uint8_t) HELPER_ST(sh, stw, uint16_t) HELPER_ST(sw, stl, uint32_t) HELPER_ST(sd, stq, uint64_t) #undef HELPER_ST target_ulong helper_clo (target_ulong arg1) { return clo32(arg1); }
1threat
static int ogg_read_header(AVFormatContext *s) { struct ogg *ogg = s->priv_data; int ret, i; ogg->curidx = -1; do { ret = ogg_packet(s, NULL, NULL, NULL, NULL); if (ret < 0) { ogg_read_close(s); return ret; } } while (!ogg->headers); av_log(s, AV_LOG_TRACE, "found headers\n"); for (i = 0; i < ogg->nstreams; i++) { struct ogg_stream *os = ogg->streams + i; if (ogg->streams[i].header < 0) { av_log(s, AV_LOG_ERROR, "Header parsing failed for stream %d\n", i); ogg->streams[i].codec = NULL; } else if (os->codec && os->nb_header < os->codec->nb_header) { av_log(s, AV_LOG_WARNING, "Headers mismatch for stream %d: " "expected %d received %d.\n", i, os->codec->nb_header, os->nb_header); if (s->error_recognition & AV_EF_EXPLODE) return AVERROR_INVALIDDATA; } if (os->start_granule != OGG_NOGRANULE_VALUE) os->lastpts = s->streams[i]->start_time = ogg_gptopts(s, i, os->start_granule, NULL); } ret = ogg_get_length(s); if (ret < 0) { ogg_read_close(s); return ret; } return 0; }
1threat
pvscsi_on_cmd_setup_rings(PVSCSIState *s) { PVSCSICmdDescSetupRings *rc = (PVSCSICmdDescSetupRings *) s->curr_cmd_data; trace_pvscsi_on_cmd_arrived("PVSCSI_CMD_SETUP_RINGS"); pvscsi_dbg_dump_tx_rings_config(rc); if (pvscsi_ring_init_data(&s->rings, rc) < 0) { return PVSCSI_COMMAND_PROCESSING_FAILED; } s->rings_info_valid = TRUE; return PVSCSI_COMMAND_PROCESSING_SUCCEEDED; }
1threat
How to check if a class uses a trait in PHP? : <p>Notice that a trait may use other traits, so the class may not be using that trait directly. And also the class may be inherited from a parent class who is the one uses the trait.</p> <p>Is this a question that can be solved within several lines or I would have to do some loops?</p>
0debug
How can i selcet only Unique value from multiple dropdown in html? : Hi i need to selset only Uniqe value from multiple dropdown, dropwown box is not fix they are rendreing dyanmicly so then could be any number of dropdown based on dropdown value is in dropdown box. So i want if user selectsame value which is already selected in any other dropdown there should be genrate a alert message there <select name="profile1" id="profile1" > <option value="1">Delhi</option> <option value="2">Mumbai</option> <option value="3">Kanpur</option> </select> <select name="profile1" id="profile2" > <option value="1">Delhi</option> <option value="2">Mumbai</option> <option value="3">Kanpur</option> </select> <select name="profile1" id="profile3" > <option value="1">Delhi</option> <option value="2">Mumbai</option> <option value="3">Kanpur</option> </select> How can i achieve this. Thanks
0debug
How to keep matplotlib (python) window in background? : <p>I have a python / matplotlib application that frequently updates a plot with new data coming in from a measurement instrument. The plot window should not change from background to foreground (or vice versa) with respect to other windows on my desktop when the plot is updated with new data.</p> <p>This worked as desired with Python 3 on a machine running Ubuntu 16.10 with matplotlib 1.5.2rc. However, on a different machine with Ubuntu 17.04 and matplotlib 2.0.0, the figure window pops to the front every time the plot is updated with new data.</p> <p>How can I control the window foreground/background behavior and keep the window focus when updating the plot with new data?</p> <p>Here's a code example illustrating my plotting routine:</p> <pre><code>import matplotlib import matplotlib.pyplot as plt from time import time from random import random print ( matplotlib.__version__ ) # set up the figure fig = plt.figure() plt.xlabel('Time') plt.ylabel('Value') plt.ion() # plot things while new data is generated: t0 = time() t = [] y = [] while True: t.append( time()-t0 ) y.append( random() ) fig.clear() plt.plot( t , y ) plt.pause(1) </code></pre>
0debug
static inline int draw_glyph_rgb(AVFilterBufferRef *picref, FT_Bitmap *bitmap, unsigned int x, unsigned int y, unsigned int width, unsigned int height, int pixel_step, const uint8_t rgba_color[4], const uint8_t rgba_map[4]) { int r, c, alpha; uint8_t *p; uint8_t src_val; for (r = 0; r < bitmap->rows && r+y < height; r++) { for (c = 0; c < bitmap->width && c+x < width; c++) { src_val = GET_BITMAP_VAL(r, c); if (!src_val) continue; SET_PIXEL_RGB(picref, rgba_color, src_val, c+x, y+r, pixel_step, rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]); } } return 0; }
1threat
static uint_fast8_t vorbis_floor1_decode(vorbis_context *vc, vorbis_floor_data *vfu, float *vec) { vorbis_floor1 *vf = &vfu->t1; GetBitContext *gb = &vc->gb; uint_fast16_t range_v[4] = { 256, 128, 86, 64 }; uint_fast16_t range = range_v[vf->multiplier-1]; uint_fast16_t floor1_Y[258]; uint_fast16_t floor1_Y_final[258]; int floor1_flag[258]; uint_fast8_t class_; uint_fast8_t cdim; uint_fast8_t cbits; uint_fast8_t csub; uint_fast8_t cval; int_fast16_t book; uint_fast16_t offset; uint_fast16_t i,j; int_fast16_t adx, ady, off, predicted; int_fast16_t dy, err; if (!get_bits1(gb)) return 1; floor1_Y[0] = get_bits(gb, ilog(range - 1)); floor1_Y[1] = get_bits(gb, ilog(range - 1)); AV_DEBUG("floor 0 Y %d floor 1 Y %d \n", floor1_Y[0], floor1_Y[1]); offset = 2; for (i = 0; i < vf->partitions; ++i) { class_ = vf->partition_class[i]; cdim = vf->class_dimensions[class_]; cbits = vf->class_subclasses[class_]; csub = (1 << cbits) - 1; cval = 0; AV_DEBUG("Cbits %d \n", cbits); if (cbits) cval = get_vlc2(gb, vc->codebooks[vf->class_masterbook[class_]].vlc.table, vc->codebooks[vf->class_masterbook[class_]].nb_bits, 3); for (j = 0; j < cdim; ++j) { book = vf->subclass_books[class_][cval & csub]; AV_DEBUG("book %d Cbits %d cval %d bits:%d \n", book, cbits, cval, get_bits_count(gb)); cval = cval >> cbits; if (book > -1) { floor1_Y[offset+j] = get_vlc2(gb, vc->codebooks[book].vlc.table, vc->codebooks[book].nb_bits, 3); } else { floor1_Y[offset+j] = 0; } AV_DEBUG(" floor(%d) = %d \n", vf->list[offset+j].x, floor1_Y[offset+j]); } offset+=cdim; } floor1_flag[0] = 1; floor1_flag[1] = 1; floor1_Y_final[0] = floor1_Y[0]; floor1_Y_final[1] = floor1_Y[1]; for (i = 2; i < vf->x_list_dim; ++i) { uint_fast16_t val, highroom, lowroom, room; uint_fast16_t high_neigh_offs; uint_fast16_t low_neigh_offs; low_neigh_offs = vf->list[i].low; high_neigh_offs = vf->list[i].high; dy = floor1_Y_final[high_neigh_offs] - floor1_Y_final[low_neigh_offs]; adx = vf->list[high_neigh_offs].x - vf->list[low_neigh_offs].x; ady = FFABS(dy); err = ady * (vf->list[i].x - vf->list[low_neigh_offs].x); off = (int16_t)err / (int16_t)adx; if (dy < 0) { predicted = floor1_Y_final[low_neigh_offs] - off; } else { predicted = floor1_Y_final[low_neigh_offs] + off; } val = floor1_Y[i]; highroom = range-predicted; lowroom = predicted; if (highroom < lowroom) { room = highroom * 2; } else { room = lowroom * 2; } if (val) { floor1_flag[low_neigh_offs] = 1; floor1_flag[high_neigh_offs] = 1; floor1_flag[i] = 1; if (val >= room) { if (highroom > lowroom) { floor1_Y_final[i] = val - lowroom + predicted; } else { floor1_Y_final[i] = predicted - val + highroom - 1; } } else { if (val & 1) { floor1_Y_final[i] = predicted - (val + 1) / 2; } else { floor1_Y_final[i] = predicted + val / 2; } } } else { floor1_flag[i] = 0; floor1_Y_final[i] = predicted; } AV_DEBUG(" Decoded floor(%d) = %d / val %d \n", vf->list[i].x, floor1_Y_final[i], val); } ff_vorbis_floor1_render_list(vf->list, vf->x_list_dim, floor1_Y_final, floor1_flag, vf->multiplier, vec, vf->list[1].x); AV_DEBUG(" Floor decoded\n"); return 0; }
1threat
static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block, int n, int coded, int intra, int rvlc) { int level, i, last, run; int dc_pred_dir; RLTable * rl; RL_VLC_ELEM * rl_vlc; const uint8_t * scan_table; int qmul, qadd; if(intra) { if(s->qscale < s->intra_dc_threshold){ if(s->partitioned_frame){ level = s->dc_val[0][ s->block_index[n] ]; if(n<4) level= FASTDIV((level + (s->y_dc_scale>>1)), s->y_dc_scale); else level= FASTDIV((level + (s->c_dc_scale>>1)), s->c_dc_scale); dc_pred_dir= (s->pred_dir_table[s->mb_x + s->mb_y*s->mb_stride]<<n)&32; }else{ level = mpeg4_decode_dc(s, n, &dc_pred_dir); if (level < 0) return -1; } block[0] = level; i = 0; }else{ i = -1; ff_mpeg4_pred_dc(s, n, 0, &dc_pred_dir, 0); } if (!coded) goto not_coded; if(rvlc){ rl = &rvlc_rl_intra; rl_vlc = rvlc_rl_intra.rl_vlc[0]; }else{ rl = &rl_intra; rl_vlc = rl_intra.rl_vlc[0]; } if (s->ac_pred) { if (dc_pred_dir == 0) scan_table = s->intra_v_scantable.permutated; else scan_table = s->intra_h_scantable.permutated; } else { scan_table = s->intra_scantable.permutated; } qmul=1; qadd=0; } else { i = -1; if (!coded) { s->block_last_index[n] = i; return 0; } if(rvlc) rl = &rvlc_rl_inter; else rl = &rl_inter; scan_table = s->intra_scantable.permutated; if(s->mpeg_quant){ qmul=1; qadd=0; if(rvlc){ rl_vlc = rvlc_rl_inter.rl_vlc[0]; }else{ rl_vlc = rl_inter.rl_vlc[0]; } }else{ qmul = s->qscale << 1; qadd = (s->qscale - 1) | 1; if(rvlc){ rl_vlc = rvlc_rl_inter.rl_vlc[s->qscale]; }else{ rl_vlc = rl_inter.rl_vlc[s->qscale]; } } } { OPEN_READER(re, &s->gb); for(;;) { UPDATE_CACHE(re, &s->gb); GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0); if (level==0) { if(rvlc){ if(SHOW_UBITS(re, &s->gb, 1)==0){ av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in rvlc esc\n"); return -1; }; SKIP_CACHE(re, &s->gb, 1); last= SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1); run= SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6); SKIP_COUNTER(re, &s->gb, 1+1+6); UPDATE_CACHE(re, &s->gb); if(SHOW_UBITS(re, &s->gb, 1)==0){ av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in rvlc esc\n"); return -1; }; SKIP_CACHE(re, &s->gb, 1); level= SHOW_UBITS(re, &s->gb, 11); SKIP_CACHE(re, &s->gb, 11); if(SHOW_UBITS(re, &s->gb, 5)!=0x10){ av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n"); return -1; }; SKIP_CACHE(re, &s->gb, 5); level= level * qmul + qadd; level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_CACHE(re, &s->gb, 1); SKIP_COUNTER(re, &s->gb, 1+11+5+1); i+= run + 1; if(last) i+=192; }else{ int cache; cache= GET_CACHE(re, &s->gb); if(IS_3IV1) cache ^= 0xC0000000; if (cache&0x80000000) { if (cache&0x40000000) { SKIP_CACHE(re, &s->gb, 2); last= SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1); run= SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6); SKIP_COUNTER(re, &s->gb, 2+1+6); UPDATE_CACHE(re, &s->gb); if(IS_3IV1){ level= SHOW_SBITS(re, &s->gb, 12); LAST_SKIP_BITS(re, &s->gb, 12); }else{ if(SHOW_UBITS(re, &s->gb, 1)==0){ av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in 3. esc\n"); return -1; }; SKIP_CACHE(re, &s->gb, 1); level= SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12); if(SHOW_UBITS(re, &s->gb, 1)==0){ av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in 3. esc\n"); return -1; }; LAST_SKIP_CACHE(re, &s->gb, 1); SKIP_COUNTER(re, &s->gb, 1+12+1); } #if 0 if(s->error_resilience >= FF_ER_COMPLIANT){ const int abs_level= ABS(level); if(abs_level<=MAX_LEVEL && run<=MAX_RUN){ const int run1= run - rl->max_run[last][abs_level] - 1; if(abs_level <= rl->max_level[last][run]){ av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n"); return -1; } if(s->error_resilience > FF_ER_COMPLIANT){ if(abs_level <= rl->max_level[last][run]*2){ av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n"); return -1; } if(run1 >= 0 && abs_level <= rl->max_level[last][run1]){ av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n"); return -1; } } } } #endif if (level>0) level= level * qmul + qadd; else level= level * qmul - qadd; if((unsigned)(level + 2048) > 4095){ if(s->error_resilience > FF_ER_COMPLIANT){ if(level > 2560 || level<-2560){ av_log(s->avctx, AV_LOG_ERROR, "|level| overflow in 3. esc, qp=%d\n", s->qscale); return -1; } } level= level<0 ? -2048 : 2047; } i+= run + 1; if(last) i+=192; } else { #if MIN_CACHE_BITS < 20 LAST_SKIP_BITS(re, &s->gb, 2); UPDATE_CACHE(re, &s->gb); #else SKIP_BITS(re, &s->gb, 2); #endif GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1); i+= run + rl->max_run[run>>7][level/qmul] +1; level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } } else { #if MIN_CACHE_BITS < 19 LAST_SKIP_BITS(re, &s->gb, 1); UPDATE_CACHE(re, &s->gb); #else SKIP_BITS(re, &s->gb, 1); #endif GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1); i+= run; level = level + rl->max_level[run>>7][(run-1)&63] * qmul; level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } } } else { i+= run; level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } if (i > 62){ i-= 192; if(i&(~63)){ av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y); return -1; } block[scan_table[i]] = level; break; } block[scan_table[i]] = level; } CLOSE_READER(re, &s->gb); } not_coded: if (intra) { if(s->qscale >= s->intra_dc_threshold){ block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0); i -= i>>31; } mpeg4_pred_ac(s, block, n, dc_pred_dir); if (s->ac_pred) { i = 63; } } s->block_last_index[n] = i; return 0; }
1threat
pandas.DatetimeIndex frequency is None and can't be set : <p>I created a DatetimeIndex from a "date" column:</p> <pre><code>sales.index = pd.DatetimeIndex(sales["date"]) </code></pre> <p>Now the index looks as follows:</p> <pre><code>DatetimeIndex(['2003-01-02', '2003-01-03', '2003-01-04', '2003-01-06', '2003-01-07', '2003-01-08', '2003-01-09', '2003-01-10', '2003-01-11', '2003-01-13', ... '2016-07-22', '2016-07-23', '2016-07-24', '2016-07-25', '2016-07-26', '2016-07-27', '2016-07-28', '2016-07-29', '2016-07-30', '2016-07-31'], dtype='datetime64[ns]', name='date', length=4393, freq=None) </code></pre> <p>As you see, the <code>freq</code> attribute is None. I suspect that errors down the road are caused by the missing <code>freq</code>. However, if I try to set the frequency explicitly:</p> <pre><code>--------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-148-30857144de81&gt; in &lt;module&gt;() 1 #### DEBUG ----&gt; 2 sales_train = disentangle(df_train) 3 sales_holdout = disentangle(df_holdout) 4 result = sarima_fit_predict(sales_train.loc[5002, 9990]["amount_sold"], sales_holdout.loc[5002, 9990]["amount_sold"]) &lt;ipython-input-147-08b4c4ecdea3&gt; in disentangle(df_train) 2 # transform sales table to disentangle sales time series 3 sales = df_train[["date", "store_id", "article_id", "amount_sold"]] ----&gt; 4 sales.index = pd.DatetimeIndex(sales["date"], freq="d") 5 sales = sales.pivot_table(index=["store_id", "article_id", "date"]) 6 return sales /usr/local/lib/python3.6/site-packages/pandas/util/_decorators.py in wrapper(*args, **kwargs) 89 else: 90 kwargs[new_arg_name] = new_arg_value ---&gt; 91 return func(*args, **kwargs) 92 return wrapper 93 return _deprecate_kwarg /usr/local/lib/python3.6/site-packages/pandas/core/indexes/datetimes.py in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, closed, ambiguous, dtype, **kwargs) 399 'dates does not conform to passed ' 400 'frequency {1}' --&gt; 401 .format(inferred, freq.freqstr)) 402 403 if freq_infer: ValueError: Inferred frequency None from passed dates does not conform to passed frequency D </code></pre> <p>So apparently a frequency has been inferred, but is stored neither in the <code>freq</code> nor <code>inferred_freq</code> attribute of the DatetimeIndex - both are None. Can someone clear up the confusion?</p>
0debug
static uint64_t uart_read(void *opaque, target_phys_addr_t offset, unsigned size) { UartState *s = (UartState *)opaque; uint32_t c = 0; offset >>= 2; if (offset > R_MAX) { return 0; } else if (offset == R_TX_RX) { uart_read_rx_fifo(s, &c); return c; } return s->r[offset]; }
1threat
Why does this come test come up as true? : I was under the impression that numbers in "" marks become strings. Why do I get the following result? "2001".isdigit() True
0debug
How to find out how many bits are set (equal 1) in the product of two integers : <p>I am looking for an algorithm solution to find out how many bits are set (equal 1) if I multiply two integers. I have numbers A and B, between 0 and MAX_INT, to eliminate the negative numbers. How do I find out how many bits will be set in the product C = A * B.</p> <p>-of course calculating C and counting the bits is not the correct solution, it won't work for high values</p> <p>-I work in C and C++, but it is a rather general algorithm problem. I must solve it without any math/boost library help.</p> <p>Tried finding a general solution to know the bit count, but what I guessed only worked for quite some examples, it entirely failed with high numbers.</p>
0debug
Cannot load keras model with custom metric : <p>Hi I am trying to make a super resolution model on keras.</p> <p>I am referring to <a href="https://github.com/titu1994/Image-Super-Resolution" rel="noreferrer">https://github.com/titu1994/Image-Super-Resolution</a>.</p> <p>But after I compile and save a new model, when I load the model, the metric error is occurred</p> <pre><code> Traceback (most recent call last): File "autoencoder2.py", line 56, in &lt;module&gt; load_model("./ani.model") File "/home/simmani91/anaconda2/lib/python2.7/site-packages/keras/models.py", line 155, in load_model sample_weight_mode=sample_weight_mode) File "/home/simmani91/anaconda2/lib/python2.7/site-packages/keras/engine/training.py", line 665, in compile metric_fn = metrics_module.get(metric) File "/home/simmani91/anaconda2/lib/python2.7/site-packages/keras/metrics.py", line 84, in get return get_from_module(identifier, globals(), 'metric') File "/home/simmani91/anaconda2/lib/python2.7/site-packages/keras/utils/generic_utils.py", line 14, in get_from_module str(identifier)) Exception: Invalid metric: PSNRLoss </code></pre> <p>and here is my code for metric(PSNRLoss), create model, execution</p> <pre><code>def PSNRLoss(y_true, y_pred): return -10. * np.log10(K.mean(K.square(y_pred - y_true))) def create_model(): shape = (360,640,3) input_img = Input(shape=shape) x = Convolution2D(64, shape[0],shape[1], activation='relu', border_mode='same', name='level1')(input_img) x = Convolution2D(32,shape[0],shape[1], activation='relu', border_mode='same', name='level2')(x) out = Convolution2D(3, shape[0],shape[1], border_mode='same', name='output')(x) model = Model(input_img, out) #model.compile(optimizer='adadelta', loss='binary_crossentropy') adam = optimizers.Adam(lr=1e-3) model.compile(optimizer=adam, loss='mse', metrics=[PSNRLoss]) return model path = "./picture/" if not os.path.exists("./ani.model"): ani_model = create_model() ani_model.save("./ani.model") load_model("./ani.model") </code></pre> <p>Is there any way to load a model with PSNR metric?</p> <p>Thank you for reading.</p>
0debug
Is That Possible In C# Coding That Is VB.Net Coding : Data Grid view i tried if else condition in data grid view cells Dim RowIdx As Integer RowIdx = dgAttendance.CurrentRow.Index If dgAttendance.Item(3, RowIdx).Value = "P" Or dgAttendance.Item(3, RowIdx).Value = "P " Then dgAttendance.Item(3, RowIdx).Value = "A" EndIF Please Give The Solution in C#. Ho Do i use That If Else Statement In C#
0debug
when should we use semaphore vs Dispatch group vs operation queue ? [Swift iOS] : when should we use semaphore vs Dispatch group vs operation queue ? i am aware of part how all of them works, but i am not sure when to use which option. since all of the things i can achieve with semaphore can also be achieved through dispatch group and also through operation queue. Is there any specific area when each one should be preferred over other ?
0debug
static int xwma_read_header(AVFormatContext *s) { int64_t size; int ret = 0; uint32_t dpds_table_size = 0; uint32_t *dpds_table = NULL; unsigned int tag; AVIOContext *pb = s->pb; AVStream *st; XWMAContext *xwma = s->priv_data; int i; tag = avio_rl32(pb); if (tag != MKTAG('R', 'I', 'F', 'F')) return -1; avio_rl32(pb); tag = avio_rl32(pb); if (tag != MKTAG('X', 'W', 'M', 'A')) return -1; tag = avio_rl32(pb); if (tag != MKTAG('f', 'm', 't', ' ')) return -1; size = avio_rl32(pb); st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); ret = ff_get_wav_header(pb, st->codec, size, 0); if (ret < 0) return ret; st->need_parsing = AVSTREAM_PARSE_NONE; if (st->codec->codec_id != AV_CODEC_ID_WMAV2) { avpriv_request_sample(s, "Unexpected codec (tag 0x04%x; id %d)", st->codec->codec_tag, st->codec->codec_id); } else { if (st->codec->extradata_size != 0) { avpriv_request_sample(s, "Unexpected extradata (%d bytes)", st->codec->extradata_size); } else { st->codec->extradata_size = 6; st->codec->extradata = av_mallocz(6 + FF_INPUT_BUFFER_PADDING_SIZE); if (!st->codec->extradata) return AVERROR(ENOMEM); st->codec->extradata[4] = 31; } } if (!st->codec->channels) { av_log(s, AV_LOG_WARNING, "Invalid channel count: %d\n", st->codec->channels); return AVERROR_INVALIDDATA; } if (!st->codec->bits_per_coded_sample) { av_log(s, AV_LOG_WARNING, "Invalid bits_per_coded_sample: %d\n", st->codec->bits_per_coded_sample); return AVERROR_INVALIDDATA; } avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate); for (;;) { if (pb->eof_reached) { ret = AVERROR_EOF; goto fail; } tag = avio_rl32(pb); size = avio_rl32(pb); if (tag == MKTAG('d', 'a', 't', 'a')) { break; } else if (tag == MKTAG('d','p','d','s')) { if (dpds_table) { av_log(s, AV_LOG_ERROR, "two dpds chunks present\n"); ret = AVERROR_INVALIDDATA; goto fail; } if (size & 3) { av_log(s, AV_LOG_WARNING, "dpds chunk size %"PRId64" not divisible by 4\n", size); } dpds_table_size = size / 4; if (dpds_table_size == 0 || dpds_table_size >= INT_MAX / 4) { av_log(s, AV_LOG_ERROR, "dpds chunk size %"PRId64" invalid\n", size); return AVERROR_INVALIDDATA; } dpds_table = av_malloc(dpds_table_size * sizeof(uint32_t)); if (!dpds_table) { return AVERROR(ENOMEM); } for (i = 0; i < dpds_table_size; ++i) { dpds_table[i] = avio_rl32(pb); size -= 4; } } avio_skip(pb, size); } if (size < 0) { ret = AVERROR_INVALIDDATA; goto fail; } if (!size) { xwma->data_end = INT64_MAX; } else xwma->data_end = avio_tell(pb) + size; if (dpds_table && dpds_table_size) { int64_t cur_pos; const uint32_t bytes_per_sample = (st->codec->channels * st->codec->bits_per_coded_sample) >> 3; const uint64_t total_decoded_bytes = dpds_table[dpds_table_size - 1]; if (!bytes_per_sample) { av_log(s, AV_LOG_ERROR, "Invalid bits_per_coded_sample %d for %d channels\n", st->codec->bits_per_coded_sample, st->codec->channels); ret = AVERROR_INVALIDDATA; goto fail; } st->duration = total_decoded_bytes / bytes_per_sample; cur_pos = avio_tell(pb); for (i = 0; i < dpds_table_size; ++i) { av_add_index_entry(st, cur_pos + (i+1) * st->codec->block_align, dpds_table[i] / bytes_per_sample, st->codec->block_align, 0, AVINDEX_KEYFRAME); } } else if (st->codec->bit_rate) { st->duration = (size<<3) * st->codec->sample_rate / st->codec->bit_rate; } fail: av_free(dpds_table); return ret; }
1threat
Check if string contains only UTF-8 characters : <p>How to check in python3 if given string contains only <strong>utf-8</strong> characters?</p>
0debug
static void exynos4210_fimd_update(void *opaque) { Exynos4210fimdState *s = (Exynos4210fimdState *)opaque; DisplaySurface *surface = qemu_console_surface(s->console); Exynos4210fimdWindow *w; int i, line; hwaddr fb_line_addr, inc_size; int scrn_height; int first_line = -1, last_line = -1, scrn_width; bool blend = false; uint8_t *host_fb_addr; bool is_dirty = false; const int global_width = (s->vidtcon[2] & FIMD_VIDTCON2_SIZE_MASK) + 1; const int global_height = ((s->vidtcon[2] >> FIMD_VIDTCON2_VER_SHIFT) & FIMD_VIDTCON2_SIZE_MASK) + 1; if (!s || !s->console || !surface_bits_per_pixel(surface) || !s->enabled) { return; } exynos4210_update_resolution(s); for (i = 0; i < NUM_OF_WINDOWS; i++) { w = &s->window[i]; if ((w->wincon & FIMD_WINCON_ENWIN) && w->host_fb_addr) { scrn_height = w->rightbot_y - w->lefttop_y + 1; scrn_width = w->virtpage_width; inc_size = scrn_width + w->virtpage_offsize; memory_region_sync_dirty_bitmap(w->mem_section.mr); host_fb_addr = w->host_fb_addr; fb_line_addr = w->mem_section.offset_within_region; for (line = 0; line < scrn_height; line++) { is_dirty = memory_region_get_dirty(w->mem_section.mr, fb_line_addr, scrn_width, DIRTY_MEMORY_VGA); if (s->invalidate || is_dirty) { if (first_line == -1) { first_line = line; } last_line = line; w->draw_line(w, host_fb_addr, s->ifb + w->lefttop_x * RGBA_SIZE + (w->lefttop_y + line) * global_width * RGBA_SIZE, blend); } host_fb_addr += inc_size; fb_line_addr += inc_size; is_dirty = false; } memory_region_reset_dirty(w->mem_section.mr, w->mem_section.offset_within_region, w->fb_len, DIRTY_MEMORY_VGA); blend = true; } } if (first_line >= 0) { uint8_t *d; int bpp; bpp = surface_bits_per_pixel(surface); fimd_update_putpix_qemu(bpp); bpp = (bpp + 1) >> 3; d = surface_data(surface); for (line = first_line; line <= last_line; line++) { fimd_copy_line_toqemu(global_width, s->ifb + global_width * line * RGBA_SIZE, d + global_width * line * bpp); } dpy_gfx_update(s->console, 0, 0, global_width, global_height); } s->invalidate = false; s->vidintcon[1] |= FIMD_VIDINT_INTFRMPEND; if ((s->vidcon[0] & FIMD_VIDCON0_ENVID_F) == 0) { exynos4210_fimd_enable(s, false); } exynos4210_fimd_update_irq(s); }
1threat
static int dnxhd_init_vlc(DNXHDEncContext *ctx) { int i, j, level, run; int max_level = 1<<(ctx->cid_table->bit_depth+2); FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->vlc_codes, max_level*4*sizeof(*ctx->vlc_codes), fail); FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->vlc_bits, max_level*4*sizeof(*ctx->vlc_bits) , fail); FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->run_codes, 63*2, fail); FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->run_bits, 63, fail); ctx->vlc_codes += max_level*2; ctx->vlc_bits += max_level*2; for (level = -max_level; level < max_level; level++) { for (run = 0; run < 2; run++) { int index = (level<<1)|run; int sign, offset = 0, alevel = level; MASK_ABS(sign, alevel); if (alevel > 64) { offset = (alevel-1)>>6; alevel -= offset<<6; } for (j = 0; j < 257; j++) { if (ctx->cid_table->ac_level[j] >> 1 == alevel && (!offset || (ctx->cid_table->ac_index_flag[j] && offset)) && (!run || (ctx->cid_table->ac_run_flag [j] && run))) { assert(!ctx->vlc_codes[index]); if (alevel) { ctx->vlc_codes[index] = (ctx->cid_table->ac_codes[j]<<1)|(sign&1); ctx->vlc_bits [index] = ctx->cid_table->ac_bits[j]+1; } else { ctx->vlc_codes[index] = ctx->cid_table->ac_codes[j]; ctx->vlc_bits [index] = ctx->cid_table->ac_bits [j]; } break; } } assert(!alevel || j < 257); if (offset) { ctx->vlc_codes[index] = (ctx->vlc_codes[index]<<ctx->cid_table->index_bits)|offset; ctx->vlc_bits [index]+= ctx->cid_table->index_bits; } } } for (i = 0; i < 62; i++) { int run = ctx->cid_table->run[i]; assert(run < 63); ctx->run_codes[run] = ctx->cid_table->run_codes[i]; ctx->run_bits [run] = ctx->cid_table->run_bits[i]; } return 0; fail: return -1; }
1threat
static int brpix_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { BRPixContext *s = avctx->priv_data; AVFrame *frame_out = data; int ret; GetByteContext gb; unsigned int bytes_pp; unsigned int magic[4]; unsigned int chunk_type; unsigned int data_len; BRPixHeader hdr; bytestream2_init(&gb, avpkt->data, avpkt->size); magic[0] = bytestream2_get_be32(&gb); magic[1] = bytestream2_get_be32(&gb); magic[2] = bytestream2_get_be32(&gb); magic[3] = bytestream2_get_be32(&gb); if (magic[0] != 0x12 || magic[1] != 0x8 || magic[2] != 0x2 || magic[3] != 0x2) { av_log(avctx, AV_LOG_ERROR, "Not a BRender PIX file\n"); return AVERROR_INVALIDDATA; chunk_type = bytestream2_get_be32(&gb); if (chunk_type != 0x3 && chunk_type != 0x3d) { av_log(avctx, AV_LOG_ERROR, "Invalid chunk type %d\n", chunk_type); return AVERROR_INVALIDDATA; ret = brpix_decode_header(&hdr, &gb); if (!ret) { av_log(avctx, AV_LOG_ERROR, "Invalid header length\n"); return AVERROR_INVALIDDATA; switch (hdr.format) { case 3: avctx->pix_fmt = AV_PIX_FMT_PAL8; bytes_pp = 1; break; case 4: avctx->pix_fmt = AV_PIX_FMT_RGB555BE; bytes_pp = 2; break; case 5: avctx->pix_fmt = AV_PIX_FMT_RGB565BE; bytes_pp = 2; break; case 6: avctx->pix_fmt = AV_PIX_FMT_RGB24; bytes_pp = 3; break; case 7: avctx->pix_fmt = AV_PIX_FMT_0RGB; bytes_pp = 4; break; case 18: avctx->pix_fmt = AV_PIX_FMT_GRAY8A; bytes_pp = 2; break; default: av_log(avctx, AV_LOG_ERROR, "Format %d is not supported\n", hdr.format); return AVERROR_PATCHWELCOME; if (s->frame.data[0]) avctx->release_buffer(avctx, &s->frame); if (av_image_check_size(hdr.width, hdr.height, 0, avctx) < 0) return AVERROR_INVALIDDATA; if (hdr.width != avctx->width || hdr.height != avctx->height) avcodec_set_dimensions(avctx, hdr.width, hdr.height); if ((ret = ff_get_buffer(avctx, &s->frame)) < 0) { av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n"); return ret; chunk_type = bytestream2_get_be32(&gb); if (avctx->pix_fmt == AV_PIX_FMT_PAL8 && (chunk_type == 0x3 || chunk_type == 0x3d)) { BRPixHeader palhdr; ret = brpix_decode_header(&palhdr, &gb); if (!ret) { av_log(avctx, AV_LOG_ERROR, "Invalid palette header length\n"); return AVERROR_INVALIDDATA; if (palhdr.format != 7) { av_log(avctx, AV_LOG_ERROR, "Palette is not in 0RGB format\n"); return AVERROR_INVALIDDATA; chunk_type = bytestream2_get_be32(&gb); data_len = bytestream2_get_be32(&gb); bytestream2_skip(&gb, 8); if (chunk_type != 0x21 || data_len != 1032 || bytestream2_get_bytes_left(&gb) < 1032) { av_log(avctx, AV_LOG_ERROR, "Invalid palette data\n"); return AVERROR_INVALIDDATA; bytestream2_skipu(&gb, 1); *pal_out++ = (0xFFU << 24) | bytestream2_get_be24u(&gb); bytestream2_skip(&gb, 8); chunk_type = bytestream2_get_be32(&gb); data_len = bytestream2_get_be32(&gb); bytestream2_skip(&gb, 8); { unsigned int bytes_per_scanline = bytes_pp * hdr.width; unsigned int bytes_left = bytestream2_get_bytes_left(&gb); if (chunk_type != 0x21 || data_len != bytes_left || bytes_left / bytes_per_scanline < hdr.height) { av_log(avctx, AV_LOG_ERROR, "Invalid image data\n"); return AVERROR_INVALIDDATA; av_image_copy_plane(s->frame.data[0], s->frame.linesize[0], avpkt->data + bytestream2_tell(&gb), bytes_per_scanline, bytes_per_scanline, hdr.height); *frame_out = s->frame; *got_frame = 1; return avpkt->size;
1threat
Python Selenium Fill Modal Text Area : i'm new to selenium. i click button and this gives me a modal form. i want to fill text area on this modal. `<input id="name" name="name" class="form-control ng-pristine ng-invalid ng-invalid-required ng-touched" ng-model="model.newInstanceSpec.name" ng-required="true" required="required" type="text">` i tried find_element_by_id , find_element_by_class_name ect. i didnt find anything. thanks for your reply [1]: https://i.stack.imgur.com/u8Mj5.png
0debug
add munltiple elements into numpy array : I have 8 elements and I want to add them into a array in numpy. I used np.append but it seems that I can only add two elements at one time. I want to add all 8 elements at once. first_1 =35.72438966508524,first_2 = 35.73839550991734, etc. 35.72438966508524 35.73839550991734 35.81944190992304 35.80549149559467 35.78399019604507 36.03781192909738 35.9957696566448 35.94692998938782 np.append(first_1,first_2,first_3,first_4,first_5,first_6,first_7,first_8) the error is. TypeError: append() takes from 2 to 3 positional arguments but 8 were given
0debug
How to automatically size Icons in Flutter to be as big as possible : <p>At the moment, I am using the following bit of code : </p> <pre><code> body: new Container( child: new Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: &lt;Widget&gt;[ new MaterialButton( height: 120.0, child: new Column( children: &lt;Widget&gt;[ new Icon( Icons.av_timer, size: 100.0, ), new Text('TIMER'), ], ), onPressed: null, ), new MaterialButton( height: 120.0, child: new Column( children: &lt;Widget&gt;[ new Icon(Icons.alarm_add, size: 100.0), new Text('ALARM'), ], ), onPressed: null, ) ]))); </code></pre> <p>However, I have had to "hardcode" the Icon size to 100.0 and the height of the MaterialButton to 120.0. </p> <p>I would like the MaterialButton to take as much space as possible (50% of the screen for each), and I would like the Icons to "fit nicely" in that space, ideally along with the Text scaling as well. </p> <p>I haven't found the way to do that in Flutter yet. If it's not a good idea to try to do this (I would like it to use the entire space of the screen on any device) please let me know why ? </p>
0debug
struct AACISError ff_aac_is_encoding_err(AACEncContext *s, ChannelElement *cpe, int start, int w, int g, float ener0, float ener1, float ener01, int use_pcoeffs, int phase) { int i, w2; SingleChannelElement *sce0 = &cpe->ch[0]; SingleChannelElement *sce1 = &cpe->ch[1]; float *L = use_pcoeffs ? sce0->pcoeffs : sce0->coeffs; float *R = use_pcoeffs ? sce1->pcoeffs : sce1->coeffs; float *L34 = &s->scoefs[256*0], *R34 = &s->scoefs[256*1]; float *IS = &s->scoefs[256*2], *I34 = &s->scoefs[256*3]; float dist1 = 0.0f, dist2 = 0.0f; struct AACISError is_error = {0}; if (ener01 <= 0 || ener0 <= 0) { is_error.pass = 0; return is_error; } for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) { FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g]; FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g]; int is_band_type, is_sf_idx = FFMAX(1, sce0->sf_idx[(w+w2)*16+g]-4); float e01_34 = phase*pow(ener1/ener0, 3.0/4.0); float maxval, dist_spec_err = 0.0f; float minthr = FFMIN(band0->threshold, band1->threshold); for (i = 0; i < sce0->ics.swb_sizes[g]; i++) IS[i] = (L[start+(w+w2)*128+i] + phase*R[start+(w+w2)*128+i])*sqrt(ener0/ener01); abs_pow34_v(L34, &L[start+(w+w2)*128], sce0->ics.swb_sizes[g]); abs_pow34_v(R34, &R[start+(w+w2)*128], sce0->ics.swb_sizes[g]); abs_pow34_v(I34, IS, sce0->ics.swb_sizes[g]); maxval = find_max_val(1, sce0->ics.swb_sizes[g], I34); is_band_type = find_min_book(maxval, is_sf_idx); dist1 += quantize_band_cost(s, &L[start + (w+w2)*128], L34, sce0->ics.swb_sizes[g], sce0->sf_idx[(w+w2)*16+g], sce0->band_type[(w+w2)*16+g], s->lambda / band0->threshold, INFINITY, NULL, NULL, 0); dist1 += quantize_band_cost(s, &R[start + (w+w2)*128], R34, sce1->ics.swb_sizes[g], sce1->sf_idx[(w+w2)*16+g], sce1->band_type[(w+w2)*16+g], s->lambda / band1->threshold, INFINITY, NULL, NULL, 0); dist2 += quantize_band_cost(s, IS, I34, sce0->ics.swb_sizes[g], is_sf_idx, is_band_type, s->lambda / minthr, INFINITY, NULL, NULL, 0); for (i = 0; i < sce0->ics.swb_sizes[g]; i++) { dist_spec_err += (L34[i] - I34[i])*(L34[i] - I34[i]); dist_spec_err += (R34[i] - I34[i]*e01_34)*(R34[i] - I34[i]*e01_34); } dist_spec_err *= s->lambda / minthr; dist2 += dist_spec_err; } is_error.pass = dist2 <= dist1; is_error.phase = phase; is_error.error = fabsf(dist1 - dist2); is_error.dist1 = dist1; is_error.dist2 = dist2; is_error.ener01 = ener01; return is_error; }
1threat
void cpu_resume_from_signal(CPUState *env1, void *puc) { env = env1; env->exception_index = -1; longjmp(env->jmp_env, 1); }
1threat
What is the purpose of curdoc()? : <p>I've been playing with bokeh for a little bit of time and I'm now at the step where I'd like to create interactive plots and embed them online (in WordPress posts, for example).</p> <p>However, even though I spent some time reviewing and testing code from the bokeh website examples, I have a hard time understanding exactly what is the purpose of curdoc(). It seems to be necessary in order to create a bokeh app with widgets, but from what I found in the ressources, I don't quite understand it.</p>
0debug
css skewed arrow box with transparent background : <p><a href="https://i.stack.imgur.com/d86P6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/d86P6.png" alt="enter image description here"></a></p> <p>Basically thats the shape I want to create in CSS, the height is 192 and I want the background to be transparent.</p> <p>Can I do this in CSS and if so is it smarter to do with SVG maybe?</p> <p>Thanks</p>
0debug
int ff_audio_mix_init(AVAudioResampleContext *avr) { int ret; if (avr->internal_sample_fmt != AV_SAMPLE_FMT_S16P && avr->internal_sample_fmt != AV_SAMPLE_FMT_FLTP) { av_log(avr, AV_LOG_ERROR, "Unsupported internal format for " "mixing: %s\n", av_get_sample_fmt_name(avr->internal_sample_fmt)); return AVERROR(EINVAL); } if (!avr->am->matrix) { int i, j; char in_layout_name[128]; char out_layout_name[128]; double *matrix_dbl = av_mallocz(avr->out_channels * avr->in_channels * sizeof(*matrix_dbl)); if (!matrix_dbl) return AVERROR(ENOMEM); ret = avresample_build_matrix(avr->in_channel_layout, avr->out_channel_layout, avr->center_mix_level, avr->surround_mix_level, avr->lfe_mix_level, 1, matrix_dbl, avr->in_channels, avr->matrix_encoding); if (ret < 0) { av_free(matrix_dbl); return ret; } av_get_channel_layout_string(in_layout_name, sizeof(in_layout_name), avr->in_channels, avr->in_channel_layout); av_get_channel_layout_string(out_layout_name, sizeof(out_layout_name), avr->out_channels, avr->out_channel_layout); av_log(avr, AV_LOG_DEBUG, "audio_mix: %s to %s\n", in_layout_name, out_layout_name); for (i = 0; i < avr->out_channels; i++) { for (j = 0; j < avr->in_channels; j++) { av_log(avr, AV_LOG_DEBUG, " %0.3f ", matrix_dbl[i * avr->in_channels + j]); } av_log(avr, AV_LOG_DEBUG, "\n"); } ret = avresample_set_matrix(avr, matrix_dbl, avr->in_channels); if (ret < 0) { av_free(matrix_dbl); return ret; } av_free(matrix_dbl); } avr->am->fmt = avr->internal_sample_fmt; avr->am->coeff_type = avr->mix_coeff_type; avr->am->in_layout = avr->in_channel_layout; avr->am->out_layout = avr->out_channel_layout; avr->am->in_channels = avr->in_channels; avr->am->out_channels = avr->out_channels; ret = mix_function_init(avr->am); if (ret < 0) return ret; return 0; }
1threat
sql datetime. how to set the month : <pre><code>DECLARE @DateMin AS datetime = '2019-01-05 00:00:00'; DECLARE @PrmMois AS tinyint = 4; </code></pre> <p>How do I replace the month by 04 ?</p>
0debug
static int guess_ni_flag(AVFormatContext *s){ int i; int64_t last_start=0; int64_t first_end= INT64_MAX; int64_t oldpos= avio_tell(s->pb); int *idx; int64_t min_pos, pos; for(i=0; i<s->nb_streams; i++){ AVStream *st = s->streams[i]; int n= st->nb_index_entries; unsigned int size; if(n <= 0) continue; if(n >= 2){ int64_t pos= st->index_entries[0].pos; avio_seek(s->pb, pos + 4, SEEK_SET); size= avio_rl32(s->pb); if(pos + size > st->index_entries[1].pos) last_start= INT64_MAX; } if(st->index_entries[0].pos > last_start) last_start= st->index_entries[0].pos; if(st->index_entries[n-1].pos < first_end) first_end= st->index_entries[n-1].pos; } avio_seek(s->pb, oldpos, SEEK_SET); if (last_start > first_end) return 1; idx= av_mallocz(sizeof(*idx) * s->nb_streams); for (min_pos=pos=0; min_pos!=INT64_MAX; pos= min_pos+1) { int64_t max_dts = INT64_MIN/2, min_dts= INT64_MAX/2; min_pos = INT64_MAX; for (i=0; i<s->nb_streams; i++) { AVStream *st = s->streams[i]; int n= st->nb_index_entries; while (idx[i]<n && st->index_entries[idx[i]].pos < pos) idx[i]++; if (idx[i] < n) { min_dts = FFMIN(min_dts, av_rescale_q(st->index_entries[idx[i]].timestamp, st->time_base, AV_TIME_BASE_Q)); min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos); } if (idx[i]) max_dts = FFMAX(max_dts, av_rescale_q(st->index_entries[idx[i]-1].timestamp, st->time_base, AV_TIME_BASE_Q)); } if(max_dts - min_dts > 2*AV_TIME_BASE) { av_free(idx); return 1; } } av_free(idx); return 0; }
1threat
void kvm_arch_reset_vcpu(CPUX86State *env) { env->exception_injected = -1; env->interrupt_injected = -1; env->xcr0 = 1; if (kvm_irqchip_in_kernel()) { env->mp_state = cpu_is_bsp(env) ? KVM_MP_STATE_RUNNABLE : KVM_MP_STATE_UNINITIALIZED; } else { env->mp_state = KVM_MP_STATE_RUNNABLE; } }
1threat
sum of two numbers in java using two classes : <p>I want to make sum of two numbers. But I have problems to do that. I don't understand why my sum is always zero.</p> <p>class A</p> <pre><code> public class A { int a=3 ,b=4; public static void main(String[] args) { B obj= new B(); obj.prod(); } } </code></pre> <p>CLASS B</p> <pre><code> public class B { int a, b; public void prod() { System.out.print(a+b); } } </code></pre>
0debug
static void boston_register_types(void) { type_register_static(&boston_device); }
1threat
static void audio_init(qemu_irq *pic) { struct soundhw *c; int audio_enabled = 0; for (c = soundhw; !audio_enabled && c->name; ++c) { audio_enabled = c->enabled; } if (audio_enabled) { AudioState *s; s = AUD_init(); if (s) { for (c = soundhw; c->name; ++c) { if (c->enabled) { if (c->isa) { c->init.init_isa(s, pic); } } } } } }
1threat
Send cookie in HTTP POST Request in javascript : <p>I am trying to make a POST request to the server (Which is a REST service)via javascript,and in my request i want to send a cookie.My below code is not working ,as I am not able to receive cookie at the server side.Below are my client side and server side code.</p> <p><strong>Client side :</strong></p> <pre><code>var client = new XMLHttpRequest(); var request_data=JSON.stringify(data); var endPoint="http://localhost:8080/pcap"; var cookie="session=abc"; client.open("POST", endPoint, false);//This Post will become put client.setRequestHeader("Accept", "application/json"); client.setRequestHeader("Content-Type","application/json"); client.setRequestHeader("Set-Cookie","session=abc"); client.setRequestHeader("Cookie",cookie); client.send(request_data); </code></pre> <p><strong>Server Side:</strong></p> <pre><code>public @ResponseBody ResponseEntity getPcap(HttpServletRequest request,@RequestBody PcapParameters pcap_params ){ Cookie cookies[]=request.getCookies();//Its coming as NULL String cook=request.getHeader("Cookie");//Its coming as NULL } </code></pre>
0debug
void helper_ldda_asi(target_ulong addr, int asi, int rd) { if ((asi < 0x80 && (env->pstate & PS_PRIV) == 0) || ((env->def->features & CPU_FEATURE_HYPV) && asi >= 0x30 && asi < 0x80 && !(env->hpstate & HS_PRIV))) raise_exception(TT_PRIV_ACT); switch (asi) { case 0x24: case 0x2c: LE helper_check_align(addr, 0xf); if (rd == 0) { env->gregs[1] = ldq_kernel(addr + 8); if (asi == 0x2c) bswap64s(&env->gregs[1]); } else if (rd < 8) { env->gregs[rd] = ldq_kernel(addr); env->gregs[rd + 1] = ldq_kernel(addr + 8); if (asi == 0x2c) { bswap64s(&env->gregs[rd]); bswap64s(&env->gregs[rd + 1]); } } else { env->regwptr[rd] = ldq_kernel(addr); env->regwptr[rd + 1] = ldq_kernel(addr + 8); if (asi == 0x2c) { bswap64s(&env->regwptr[rd]); bswap64s(&env->regwptr[rd + 1]); } } break; default: helper_check_align(addr, 0x3); if (rd == 0) env->gregs[1] = helper_ld_asi(addr + 4, asi, 4, 0); else if (rd < 8) { env->gregs[rd] = helper_ld_asi(addr, asi, 4, 0); env->gregs[rd + 1] = helper_ld_asi(addr + 4, asi, 4, 0); } else { env->regwptr[rd] = helper_ld_asi(addr, asi, 4, 0); env->regwptr[rd + 1] = helper_ld_asi(addr + 4, asi, 4, 0); } break; } }
1threat
RxSwift minimal Observable.create example : <p>Currently I am trying to get RxSwift working. And I want to create a custom Observable. But I think I am doing something wrong. </p> <p>I have distilled what I do to this minimal sample:</p> <pre><code>import Foundation import RxSwift class Example { let exampleObservable : Observable&lt;String&gt; = Observable.create { (observer) in observer.on(.Next("hello")) observer.on(.Completed) return AnonymousDisposable { } } let exampleObserver : AnyObserver&lt;String&gt;? func run() { self.exampleObserver = exampleObservable.subscribeNext({ (text) -&gt; Void in print(text) }) } } let ex = Example() ex.run() </code></pre> <p>Is this correct? In the run method, the subscribeNext method is autocompleted that way by XCode.</p> <p><a href="https://i.stack.imgur.com/kMKjb.png"><img src="https://i.stack.imgur.com/kMKjb.png" alt="Example"></a></p> <p>But when I run it I get the following compilation error: </p> <pre><code>Cannot Invoke 'substribeNext' with an argument list of type ((String) -&gt; Void) </code></pre>
0debug
What is Best way to return Data in webapi : <p>I have a question that what is the best way to return data in webapi. for eg we can have 2 scenarios.</p> <blockquote> <p>1) GetProductsById in which we recive an id and return data for that Id.</p> <p>2) GetProducts in which we return list of data</p> </blockquote> <p>so for GetProductsById we can do : </p> <pre><code> public IHttpActionResult GetProduct(int id) { var product = getProducts().FirstOrDefault((p) =&gt; p.Id == id); if (product == null) { return NotFound(); } return Ok(product); } </code></pre> <p>and for getting list:</p> <pre><code> public IHttpActionResult GetProduct(int id) { var products = getproducts(); if (products == null) { throw new NotFoundException() } return Ok(product); } </code></pre> <p>I want to know the best method to handle not found scenario in both cases.</p>
0debug
query = 'SELECT * FROM customers WHERE email = ' + email_input
1threat
Clicking a button : How to click the buttton? Can you suggest the code I need to press the button enter <dl class="final unpoint"> <dt> <p>By clicking "Place Order", you agree to create this campaign.</p> </dt> <dd> <button>Place Order</button> </dd> </dl> here
0debug
Few questions about Visual Studio 2015 Git : <p>I started to use Git provided in Visual Studio 2015 Update 2. My team consists of only me. My needs are simple: to have history of changes, and possibility to revert them. Visual Studio created automatically local repository in my solution directory. My questions are:</p> <ol> <li><p>Is it valid way to use only local repository? Will it create any problems when I never set up remote repository?</p></li> <li><p>Is .git folder created in solution directory independent? I mean, does it have complete git information, so when I copy to another directory or machine, it will have its own full state?</p></li> <li>In case of backups, will be there any difference between: a) simply setting a 3rd party program to backup whole solution directory to remote server. b) setting up server for remote repository, and backuping by commiting changes.</li> <li><p>Why .git folder is hidden?</p></li> <li><p>How can I hide field showing number of unpublished commits, which is located on the right bottom in Visual Studio 2015 Update 2? If I will never set up remote server, this number will increase to huge numbers, and reminds me about elapsing time.</p></li> </ol>
0debug
Acceleration in Unity : <p>I am trying to emulate acceleration and deceleration in Unity.</p> <p>I have written to code to generate a track in Unity and place an object at a specific location on the track based on time. The result looks a little like this.</p> <p><a href="https://i.stack.imgur.com/1syKu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1syKu.png" alt="Cube mid way through Catmull-Rom Spline"></a></p> <p>The issue I currently have is that each section of the spline is a different length and the cube moves across each section at a different, but uniform, speed. This causes there to be sudden jumps in the change of the speed of the cube when transitioning between sections.</p> <p>In order to try and fix this issue, I attempted to use <a href="https://gist.github.com/xanathar/735e17ac129a72a277ee" rel="noreferrer">Robert Penner's easing equations</a> on the <code>GetTime(Vector3 p0, Vector3 p1, float alpha)</code> method. However, whilst this did help somewhat, it was not sufficient. There were still jumps in speed in between transitions.</p> <p>Does anyone have any ideas on how I could dynamically ease the position of the cube to make it look like it was accelerating and decelerating, without large jumps in speed between segments of the track?</p> <hr> <p>I have written a script that shows a simple implementation of my code. It can be attached to any game object. To make it easy to see what is happening when the code runs, attach to something like a cube or sphere.</p> <pre><code>using System.Collections.Generic; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif public class InterpolationExample : MonoBehaviour { [Header("Time")] [SerializeField] private float currentTime; private float lastTime = 0; [SerializeField] private float timeModifier = 1; [SerializeField] private bool running = true; private bool runningBuffer = true; [Header("Track Settings")] [SerializeField] [Range(0, 1)] private float catmullRomAlpha = 0.5f; [SerializeField] private List&lt;SimpleWayPoint&gt; wayPoints = new List&lt;SimpleWayPoint&gt; { new SimpleWayPoint() {pos = new Vector3(-4.07f, 0, 6.5f), time = 0}, new SimpleWayPoint() {pos = new Vector3(-2.13f, 3.18f, 6.39f), time = 1}, new SimpleWayPoint() {pos = new Vector3(-1.14f, 0, 4.55f), time = 6}, new SimpleWayPoint() {pos = new Vector3(0.07f, -1.45f, 6.5f), time = 7}, new SimpleWayPoint() {pos = new Vector3(1.55f, 0, 3.86f), time = 7.2f}, new SimpleWayPoint() {pos = new Vector3(4.94f, 2.03f, 6.5f), time = 10} }; [Header("Debug")] [Header("WayPoints")] [SerializeField] private bool debugWayPoints = true; [SerializeField] private WayPointDebugType debugWayPointType = WayPointDebugType.SOLID; [SerializeField] private float debugWayPointSize = 0.2f; [SerializeField] private Color debugWayPointColour = Color.green; [Header("Track")] [SerializeField] private bool debugTrack = true; [SerializeField] [Range(0, 1)] private float debugTrackResolution = 0.04f; [SerializeField] private Color debugTrackColour = Color.red; [System.Serializable] private class SimpleWayPoint { public Vector3 pos; public float time; } [System.Serializable] private enum WayPointDebugType { SOLID, WIRE } private void Start() { wayPoints.Sort((x, y) =&gt; x.time.CompareTo(y.time)); wayPoints.Insert(0, wayPoints[0]); wayPoints.Add(wayPoints[wayPoints.Count - 1]); } private void LateUpdate() { //This means that if currentTime is paused, then resumed, there is not a big jump in time if(runningBuffer != running) { runningBuffer = running; lastTime = Time.time; } if(running) { currentTime += (Time.time - lastTime) * timeModifier; lastTime = Time.time; if(currentTime &gt; wayPoints[wayPoints.Count - 1].time) { currentTime = 0; } } transform.position = GetPosition(currentTime); } #region Catmull-Rom Math public Vector3 GetPosition(float time) { //Check if before first waypoint if(time &lt;= wayPoints[0].time) { return wayPoints[0].pos; } //Check if after last waypoint else if(time &gt;= wayPoints[wayPoints.Count - 1].time) { return wayPoints[wayPoints.Count - 1].pos; } //Check time boundaries - Find the nearest WayPoint your object has passed float minTime = -1; float maxTime = -1; int minIndex = -1; for(int i = 1; i &lt; wayPoints.Count; i++) { if(time &gt; wayPoints[i - 1].time &amp;&amp; time &lt;= wayPoints[i].time) { maxTime = wayPoints[i].time; int index = i - 1; minTime = wayPoints[index].time; minIndex = index; } } float timeDiff = maxTime - minTime; float percentageThroughSegment = 1 - ((maxTime - time) / timeDiff); //Define the 4 points required to make a Catmull-Rom spline Vector3 p0 = wayPoints[ClampListPos(minIndex - 1)].pos; Vector3 p1 = wayPoints[minIndex].pos; Vector3 p2 = wayPoints[ClampListPos(minIndex + 1)].pos; Vector3 p3 = wayPoints[ClampListPos(minIndex + 2)].pos; return GetCatmullRomPosition(percentageThroughSegment, p0, p1, p2, p3, catmullRomAlpha); } //Prevent Index Out of Array Bounds private int ClampListPos(int pos) { if(pos &lt; 0) { pos = wayPoints.Count - 1; } if(pos &gt; wayPoints.Count) { pos = 1; } else if(pos &gt; wayPoints.Count - 1) { pos = 0; } return pos; } //Math behind the Catmull-Rom curve. See here for a good explanation of how it works. https://stackoverflow.com/a/23980479/4601149 private Vector3 GetCatmullRomPosition(float t, Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float alpha) { float dt0 = GetTime(p0, p1, alpha); float dt1 = GetTime(p1, p2, alpha); float dt2 = GetTime(p2, p3, alpha); Vector3 t1 = ((p1 - p0) / dt0) - ((p2 - p0) / (dt0 + dt1)) + ((p2 - p1) / dt1); Vector3 t2 = ((p2 - p1) / dt1) - ((p3 - p1) / (dt1 + dt2)) + ((p3 - p2) / dt2); t1 *= dt1; t2 *= dt1; Vector3 c0 = p1; Vector3 c1 = t1; Vector3 c2 = (3 * p2) - (3 * p1) - (2 * t1) - t2; Vector3 c3 = (2 * p1) - (2 * p2) + t1 + t2; Vector3 pos = CalculatePosition(t, c0, c1, c2, c3); return pos; } private float GetTime(Vector3 p0, Vector3 p1, float alpha) { if(p0 == p1) return 1; return Mathf.Pow((p1 - p0).sqrMagnitude, 0.5f * alpha); } private Vector3 CalculatePosition(float t, Vector3 c0, Vector3 c1, Vector3 c2, Vector3 c3) { float t2 = t * t; float t3 = t2 * t; return c0 + c1 * t + c2 * t2 + c3 * t3; } //Utility method for drawing the track private void DisplayCatmullRomSpline(int pos, float resolution) { Vector3 p0 = wayPoints[ClampListPos(pos - 1)].pos; Vector3 p1 = wayPoints[pos].pos; Vector3 p2 = wayPoints[ClampListPos(pos + 1)].pos; Vector3 p3 = wayPoints[ClampListPos(pos + 2)].pos; Vector3 lastPos = p1; int maxLoopCount = Mathf.FloorToInt(1f / resolution); for(int i = 1; i &lt;= maxLoopCount; i++) { float t = i * resolution; Vector3 newPos = GetCatmullRomPosition(t, p0, p1, p2, p3, catmullRomAlpha); Gizmos.DrawLine(lastPos, newPos); lastPos = newPos; } } #endregion private void OnDrawGizmos() { #if UNITY_EDITOR if(EditorApplication.isPlaying) { if(debugWayPoints) { Gizmos.color = debugWayPointColour; foreach(SimpleWayPoint s in wayPoints) { if(debugWayPointType == WayPointDebugType.SOLID) { Gizmos.DrawSphere(s.pos, debugWayPointSize); } else if(debugWayPointType == WayPointDebugType.WIRE) { Gizmos.DrawWireSphere(s.pos, debugWayPointSize); } } } if(debugTrack) { Gizmos.color = debugTrackColour; if(wayPoints.Count &gt;= 2) { for(int i = 0; i &lt; wayPoints.Count; i++) { if(i == 0 || i == wayPoints.Count - 2 || i == wayPoints.Count - 1) { continue; } DisplayCatmullRomSpline(i, debugTrackResolution); } } } } #endif } } </code></pre>
0debug
Create new instance of class on calling a method c# : I have a Console Application which is injecting all the service through the constructor. I am also creating and initializing a Dictionary in the Constructor of my data access class. I am calling the data access method from my main class but I wanted to create a new instance of data access class and therefore dictionary whenever I will call the method GetData(). public class Startup { private static void Main(string[] args) { ServiceCollection serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider(); serviceProvider.GetService<MyService>().Start(); } private static void ConfigureServices(IServiceCollection serviceCollection) { serviceCollection.AddTransient<IMyServiceDataAccess, MyServiceDataAccess>(); serviceCollection.AddTransient<MyService>(); } } MyServiceClass: private readonly IMyServiceDataAccess _dataAccess; public MyService(IMyServiceDataAccess dataAccess) { _dataAccess = dataAccess; } public void Start() { var data = _dataAccess.GetData(); } DataAccess interface public interface IMyServiceDataAccess { List<int> GetData(); } DataAccess class: Dictionary<bool,List<int> dict; public MyServiceDataAccess() { dict = new Dictionary<bool,List<int>>() } public List<int> GetData() { // have to access the above dict and everytime I need new instance // of this dict } This will be multithreaded application so multiple threads can share the dictionary. One way is that create new instance of dictionary in get data method everytime it is called. Any help?
0debug
static void *acpi_add_rom_blob(AcpiBuildState *build_state, GArray *blob, const char *name) { return rom_add_blob(name, blob->data, acpi_data_len(blob), -1, name, acpi_build_update, build_state); }
1threat
how to crawl every pages from the same head url? : <p>i want to crawl every pages from the same head url</p> <p>ex:"<a href="http://www.htc.com/tw/XXXXXXX" rel="nofollow noreferrer">http://www.htc.com/tw/XXXXXXX</a>" Hanv any way to do?</p> <p>thanks.</p>
0debug
How to create copies of the images. : Say i have different classes of medical x ray images, but they are not equal in number. Some class of images (Image Count) are in 1000's, some are in 100's, some are below 50 and 10. How i can make them equal.? Means i need to create copies of the images. Which is the best method for this. After that i need to do feature extraction. So if i have good number of images in each class i can train well i guess. Since x ray images are taken in different angle, mean while i am thinking how can i make some rotation to the existing images when creating duplicate images.
0debug
Can someone please tell me why is this code not being accepted? <b>Note:I am not asking for a solution, just tell me where this code fails.</b> : [link to problem.][1] [1]: https://www.codechef.com/JAN18/problems/MAXSC #include<stdio.h> int main() { long long int n, t, k, i, j, max[701], a[701][701], sum, flag; scanf( "%lld", &t ); for( k = 0 ; k < t ; k++ ) { scanf( "%lld", &n ); for( i = 1 ; i <= n ; i++ ) { for( j = 1 ; j <= n ; j++ ) { scanf( "%lld", &a[i][j] ); if( j == 1) max[i] = a[i][1]; if( a[i][j] > max[i] ) max[i] = a[i][j]; } } sum = 0, flag = 0; for( i = 1 ; i <= n-1 ; i++ ) { if( max[i] &lt; max[i+1]) sum = sum + max[i]; else { flag = 1; break; } } if(flag == 1) printf("-1\n"); else { sum = sum + max[n-1]; printf("%lld\n", sum ); } } } Compute the maximum possible value of E1 + E2 + ... + EN. If it's impossible to pick the elements E1, E2, ..., EN, print -1 instead. and a constraint: You should pick N elements, one from each sequence; let's denote the element picked from sequence Ai by Ei. For each i (2 ≤ i ≤ N), Ei should be strictly greater than Ei-1. does this constraint mean we have to choose max element from each line? If you look at example given: Example Input: 1 3 1 2 3 4 5 6 7 8 9 Output: 18 Explanation Example case 1: To maximise the score, pick 3 from the first row, 6 from the second row and 9 from the third row. The resulting sum is E1+E2+E3 = 3+6+9 = 18. if you notice they have mentioned "maximize". Though my code finds the max, it isn't being accepted.
0debug
static void encode_422_bitstream(HYuvContext *s, int count){ int i; count/=2; if(s->flags&CODEC_FLAG_PASS1){ for(i=0; i<count; i++){ s->stats[0][ s->temp[0][2*i ] ]++; s->stats[1][ s->temp[1][ i ] ]++; s->stats[0][ s->temp[0][2*i+1] ]++; s->stats[2][ s->temp[2][ i ] ]++; } }else if(s->context){ for(i=0; i<count; i++){ s->stats[0][ s->temp[0][2*i ] ]++; put_bits(&s->pb, s->len[0][ s->temp[0][2*i ] ], s->bits[0][ s->temp[0][2*i ] ]); s->stats[1][ s->temp[1][ i ] ]++; put_bits(&s->pb, s->len[1][ s->temp[1][ i ] ], s->bits[1][ s->temp[1][ i ] ]); s->stats[0][ s->temp[0][2*i+1] ]++; put_bits(&s->pb, s->len[0][ s->temp[0][2*i+1] ], s->bits[0][ s->temp[0][2*i+1] ]); s->stats[2][ s->temp[2][ i ] ]++; put_bits(&s->pb, s->len[2][ s->temp[2][ i ] ], s->bits[2][ s->temp[2][ i ] ]); } }else{ for(i=0; i<count; i++){ put_bits(&s->pb, s->len[0][ s->temp[0][2*i ] ], s->bits[0][ s->temp[0][2*i ] ]); put_bits(&s->pb, s->len[1][ s->temp[1][ i ] ], s->bits[1][ s->temp[1][ i ] ]); put_bits(&s->pb, s->len[0][ s->temp[0][2*i+1] ], s->bits[0][ s->temp[0][2*i+1] ]); put_bits(&s->pb, s->len[2][ s->temp[2][ i ] ], s->bits[2][ s->temp[2][ i ] ]); } } }
1threat
Getting form data on submit? : <p>When my form is submitted I wish to get an input value:</p> <pre><code>&lt;input type="text" id="name"&gt; </code></pre> <p>I know I can use form input bindings to update the values to a variable, but how can I just do this on submit. I currently have:</p> <pre><code>&lt;form v-on:submit.prevent="getFormValues"&gt; </code></pre> <p>But how can I get the value inside of the getFormValues method?</p> <p>Also, side question, is there any benefit to doing it on submit rather than updating variable when user enters the data via binding? </p>
0debug